diff --git a/.gitattributes b/.gitattributes index 9abc6f2bb8ca7b8b9edfea31531f70e006872e54..4aedd9204ece4f74f77c2fee6b6b674d2da42d2d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -40,3 +40,5 @@ node_modules/@plotly/d3-sankey/img/align-center.png filter=lfs diff=lfs merge=lf node_modules/@plotly/d3-sankey/img/align-left.png filter=lfs diff=lfs merge=lfs -text node_modules/@plotly/d3-sankey/img/align-right.png filter=lfs diff=lfs merge=lfs -text node_modules/@plotly/d3-sankey/img/energy.png filter=lfs diff=lfs merge=lfs -text +node_modules/@rollup/rollup-linux-x64-gnu/rollup.linux-x64-gnu.node filter=lfs diff=lfs merge=lfs -text +node_modules/@rollup/rollup-linux-x64-musl/rollup.linux-x64-musl.node filter=lfs diff=lfs merge=lfs -text diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/.eslintrc b/node_modules/@plotly/mapbox-gl/src/style-spec/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..f3fdb51db757b801c913dc837c2d41ebd3357c95 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "flowtype/require-valid-file-annotation": [0] + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/CHANGELOG.md b/node_modules/@plotly/mapbox-gl/src/style-spec/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f3ab3d7ef2bb98f3c9d7b207b8a593c0f91fe7f9 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/CHANGELOG.md @@ -0,0 +1,468 @@ +## 13.17.0 + +### ✨ Features and improvements +* Add a `filter` option for GeoJSON sources to filter out features prior to processing (e.g. before clustering). [#9864](https://github.com/mapbox/mapbox-gl-js/pull/9864) + +## 13.16.0 + +### ✨ Features and improvements +* Added `volatile` source property to control storing the tiles in local storage. ([9702](https://github.com/mapbox/mapbox-gl-js/pull/9702)) + +* Added `clusterMinPoints` option for clustered GeoJSON sources that defines the minimum number of points to form a cluster. ([#9748](https://github.com/mapbox/mapbox-gl-js/pull/9748)) + +## 13.15.0 + +### ✨ Features and improvements +* Add `distance` expression to `style-spec`. This expression returns the shortest distance between a feature and an input geometry ([#9655](https://github.com/mapbox/mapbox-gl-js/pull/9655)) + +## 13.14.0 + +### ✨ Features and improvements +* Add `index-of` and `slice` expressions to search arrays and strings for the first occurrence of a specified value and return a section of the original array or string ([#9450](https://github.com/mapbox/mapbox-gl-js/pull/9450)) (h/t [lbutler](https://github.com/lbutler)) + +## 13.13.1 + +### ✨ Features and improvements +* Expose `expression.isExpressionFilter(..)` from the bundle. ([#9530](https://github.com/mapbox/mapbox-gl-js/pull/9530)) + +### 🐛 Bug fixes +* Fix a broken module import where the `style-spec` package was importing files from `mapbox-gl-js`, it's parent repo, causing downstream build systems to break. ([#9522](https://github.com/mapbox/mapbox-gl-js/pull/9522)) + +## 13.13.0 + +### ✨ Features and improvements +* Add `within` expression for testing whether an evaluated feature lies within a given GeoJSON object ([#9352](https://github.com/mapbox/mapbox-gl-js/pull/9352)). For example:
+`"icon-opacity": ["case", ["==", ["within", "some-polygon"], true], 1, +["==", ["within", "some-polygon"], false], 0]` +* Improve scaling of patterns used in `line-pattern` on all device resolutions and pixel ratios ([#9266](https://github.com/mapbox/mapbox-gl-js/pull/9266)) + +### 🐛 Bug fixes +* Allow needle argument to `in` expression to be false ([#9295](https://github.com/mapbox/mapbox-gl-js/pull/9295)) +* Fix a bug where `icon-image` expression that evaluates to an empty string (`''`) produced a warning ([#9380](https://github.com/mapbox/mapbox-gl-js/pull/9380)) +* Prevent exception resulting from `line-dash-array` of empty length ([#9385](https://github.com/mapbox/mapbox-gl-js/pull/9385)) + +## 13.12.0 + +* Update `image` expression SDK support table ([#9228](https://github.com/mapbox/mapbox-gl-js/pull/9228)) +* Fix `promoteId` for line layers ([#9210](https://github.com/mapbox/mapbox-gl-js/pull/9210), [#9212](https://github.com/mapbox/mapbox-gl-js/pull/9212)) + +## 13.11.0 + +### ✨ Features and improvements +* Add `promoteId` option to use a feature property as ID for feature state ([#8987](https://github.com/mapbox/mapbox-gl-js/pull/8987)) +* Update `symbol-avoid-edges` documentation regarding global collision detection ([#9157](https://github.com/mapbox/mapbox-gl-js/pull/9157)) +* Remove reference to `in` function which has been replaced by the `in` expression ([#9102](https://github.com/mapbox/mapbox-gl-js/pull/9102)) + +### 🐛 Bug fixes +* Fix bug where `symbol-sort-key` was not used for collisions that crossed tile boundaries ([#9054](https://github.com/mapbox/mapbox-gl-js/pull/9054)) + +## 13.10.2 + +### 🐛 Bug fixes +* Fix style validation error messages not being displayed ([#9073](https://github.com/mapbox/mapbox-gl-js/pull/9073)) + +## 13.10.0 + +### ✨ Features and improvements +* Add ability to insert images into text labels using an `image` expression within a `format` expression: `"text-field": ["format", "Some text", ["image", "my-image"], "some more text"]` ([#8904](https://github.com/mapbox/mapbox-gl-js/pull/8904)) +* Add `in` expression. It can check if a value is in an array (`["in", value, array]`) or a substring is in a string (`["in", substring, string]`) ([#8876](https://github.com/mapbox/mapbox-gl-js/pull/8876)) +* Add support for stretchable images (aka nine-part or nine-patch images). Stretchable images can be used with `icon-text-fit` to draw resized images with unstretched corners and borders. ([#8997](https://github.com/mapbox/mapbox-gl-js/pull/8997)) +* Add an es modules build of for mapbox-gl-style-spec in dist/ ([#8247](https://github.com/mapbox/mapbox-gl-js/pull/8247)) (h/t [ahocevar](https://github.com/ahocevar)) + +## 13.9.1 + +### ✨ Improvement +* Rename `Image` type to `ResolvedImage`, to better represent the result of an `image` expression evaluation. ([#8901](https://github.com/mapbox/mapbox-gl-js/pull/8901)) + +## 13.9.0 + +* Add `image` expression operator to determine image availability ([#8684](https://github.com/mapbox/mapbox-gl-js/pull/8684)) +* Add a style-spec function to validate that styles are compatible with the Mapbox API ([#8663](https://github.com/mapbox/mapbox-gl-js/pull/8663)) + +## 13.8.0 + +- Introduce `text-writing-mode` symbol layer property to allow placing point labels vertically. [#8399](https://github.com/mapbox/mapbox-gl-js/pull/8399) +- Allow `text-color` to be used in formatted expressions to be able to draw different parts of a label in different colors. [#8068](https://github.com/mapbox/mapbox-gl-js/pull/8068) +- Improve conversion of legacy filters with duplicate values. [#8542](https://github.com/mapbox/mapbox-gl-js/pull/8542) + +## 13.7.2 + +### 🐛 Bug fixes +* Fix SDK support spec section for variable label placement ([#8384](https://github.com/mapbox/mapbox-gl-js/pull/8384)) (h/t [@pozdnyakov](https://github.com/pozdnyakov)) + +### ✨ Features and improvements +* Add SDK support spec section for text-radial-offset ([#8401](https://github.com/mapbox/mapbox-gl-js/pull/8401)) +* Add `*-sort-key` layout property for circle, fill, line ([#8467](https://github.com/mapbox/mapbox-gl-js/pull/8467)) +* Expose convertFilter API in the style specification ([#8493](https://github.com/mapbox/mapbox-gl-js/pull/8493)) + +## 13.7.1 + +### 🐛 Bug fixes +* Fix format expression options validation ([#8339](https://github.com/mapbox/mapbox-gl-js/pull/8339)) +* Fix SDK support information for style properties added in v13.7.0: ([#8384](https://github.com/mapbox/mapbox-gl-js/pull/8384)) + * Add missing SDK support section for `text-radial-offset` property + * Assign SDK versions for `text-variable-anchor` and `text-justify: auto` + +## 13.7.0 + +### ✨ Features and improvements +* Add `text-radial-offset` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596)) +* Add `text-variable-anchor` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596)) +* Add `auto` value to `text-justify` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596)) + +## 13.6.0 + +### ✨ Features and improvements +* Add `clusterProperties` option for aggregated cluster properties ([#2412](https://github.com/mapbox/mapbox-gl-js/issues/2412), fixed by [#7584](https://github.com/mapbox/mapbox-gl-js/pull/7584)) +* Add `number-format` expression ([#7626](https://github.com/mapbox/mapbox-gl-js/pull/7626)) +* Add `symbol-sort-key` style property ([#7678](https://github.com/mapbox/mapbox-gl-js/pull/7678)) + +## 13.5.0 + +### Features and improvements +* Flattens `all` expressions in converted filters ([#7679](https://github.com/mapbox/mapbox-gl-js/pull/7679)) +* Compatibility tables are updated ([#7574](https://github.com/mapbox/mapbox-gl-js/pull/7574)) + +## 13.4.0 + +### ✨ Features and improvements +* **Tighten style validation** + * Disallow expressions as stop values ([#7396](https://github.com/mapbox/mapbox-gl-js/pull/7396)) + * Disallow `feature-state` expressions in filters ([#7366](https://github.com/mapbox/mapbox-gl-js/pull/7366)) + +## 13.3.0 + +### 🐛 Bug fixes +* **Expressions** + * Fix `let` expression stripping expected type during parsing ([#7300](https://github.com/mapbox/mapbox-gl-js/issues/7300), fixed by [#7301](https://github.com/mapbox/mapbox-gl-js/pull/7301)) + * Fix superfluous wrapping of literals in `literal` expression ([#7336](https://github.com/mapbox/mapbox-gl-js/issues/7336), fixed by [#7337](https://github.com/mapbox/mapbox-gl-js/pull/7337)) + * Allow calling `to-color` on values that are already of type `Color` ([#7260](https://github.com/mapbox/mapbox-gl-js/pull/7260)) + * Fix `to-array` for empty arrays (([#7261](https://github.com/mapbox/mapbox-gl-js/pull/7261))) + * Fix identity functions for `text-field` when using formatted text ([#7351](https://github.com/mapbox/mapbox-gl-js/pull/7351)) + * Fix coercion of `null` to `0` in `to-number` expression ([#7083](https://github.com/mapbox/mapbox-gl-js/issues/7083), fixed by [#7274](https://github.com/mapbox/mapbox-gl-js/pull/7274)) + +### ✨ Features and improvements +* Add `fill-extrusion-vertical-gradient` property for controlling shading of fill extrusions ([#5768](https://github.com/mapbox/mapbox-gl-js/issues/5768), fixed by [#6841](https://github.com/mapbox/mapbox-gl-js/pull/6841)) + +## 13.2.0 + +### 🐛 Bug fixes +* Update the style-spec's old `gl-style-migrate` script to include conversion of legacy functions and filters to their expression equivalents ([#6927](https://github.com/mapbox/mapbox-gl-js/issues/6927), fixed by [#7095](https://github.com/mapbox/mapbox-gl-js/pull/7095)) + +### ✨ Features and improvements +* Add `symbol-z-order` symbol layout property to style spec ([#7219](https://github.com/mapbox/mapbox-gl-js/pull/7219)) +* Implement data-driven styling support for `*-pattern properties` ([#6289](https://github.com/mapbox/mapbox-gl-js/pull/6289)) + +## 13.1.1 + +### 🐛 Bug fixes +* Fix broken module import in mapboxgl-style-spec (v13.0.1) ([#6984](https://github.com/mapbox/mapbox-gl-js/issues/6984), fixed by [#6997](https://api.github.com/repos/mapbox/mapbox-gl-js/pulls/6997)) + +### ✨ Features and improvements +* Improve formatting for style output ([#7029](https://github.com/mapbox/mapbox-gl-js/pull/7029)) + +## 13.1.0 + +### ✨ Features and improvements +* Add `raster-resampling` raster paint property ([#6411](https://github.com/mapbox/mapbox-gl-js/pull/6411)) (h/t [andrewharvey](https://github.com/andrewharvey)) +* Add `symbol-placement: line-center` ([#6821](https://github.com/mapbox/mapbox-gl-js/pull/6821)) + +## 13.0.1 + +### ⚠️ Breaking changes +* Align implicit type behavior of `match` expressions with with `case/==` ([#6684](https://github.com/mapbox/mapbox-gl-js/pull/6684)) +* Update spec so that documentation can automatically capture which functions and expressions can be used with which properties ([#6521](https://github.com/mapbox/mapbox-gl-js/pull/6521)) + +### ✨ Features and improvements +* Add `feature-state` [#6263](https://github.com/mapbox/mapbox-gl-js/pull/6263) +* Add support for GeoJSON attribution ([#6364](https://github.com/mapbox/mapbox-gl-js/pull/6364)) (h/t [andrewharvey](https://github.com/andrewharvey)) +* Upgrade to Flow 0.69 ([#6594](https://github.com/mapbox/mapbox-gl-js/pull/6594)) + +### 🐛 Bug fixes +* Use named exports for style-spec entrypoint module ([#6601](https://github.com/mapbox/mapbox-gl-js/issues/6601) + +## 13.0.0 +Malformed package published to NPM. + +## 12.0.0 + +### ⚠️ Breaking changes +* The `"to-string"` expression operator now converts null to an empty string rather than to `"null"`. [#6534](https://github.com/mapbox/mapbox-gl-js/pull/6534) + +### ✨ Features and improvements +* 🌈 Add line-gradient property [#6303](https://github.com/mapbox/mapbox-gl-js/pull/6303) +* Add collator expression for controlling case and diacritic sensitivity in string comparisons [#6270](https://github.com/mapbox/mapbox-gl-js/pull/6270) +* Add `is-supported-script` expression for determining if a script is supported. [#6260](https://github.com/mapbox/mapbox-gl-js/pull/6260) +* Add `collator` expression for controlling case and diacritic sensitivity in string comparisons [#6270](https://github.com/mapbox/mapbox-gl-js/pull/6270) +* Add `abs`, `round`, `floor`, and `ceil` expression operators [#6496](https://github.com/mapbox/mapbox-gl-js/pull/6496) +* Add support for Mapzen Terrarium tiles in raster-dem sources [#6110](https://github.com/mapbox/mapbox-gl-js/pull/6110) + +### 🐛 Bug fixes +- Fix Rollup build [6575](https://github.com/mapbox/mapbox-gl-js/pull/6575) + +## 11.1.1 + +### 🐛 Bug fixes + +* Update SDK support information for `text-font`, and `heatmap-color`, and `hillshade` layer properties. + +## 11.1.0 + +### ✨ Features and improvements + +* Avoid use of `new Function` for filters by converting old-style filters to expressions [#5665](https://github.com/mapbox/mapbox-gl-js/pull/5665). + +## 11.0.0 + +### ⚠️ Breaking changes + +* Remove constants validating code [#5885](https://github.com/mapbox/mapbox-gl-js/pull/5885) +* `"colorSpace": "hcl"` now uses shortest-path interpolation for hue [#5811](https://github.com/mapbox/mapbox-gl-js/issues/5811) + +### ✨ Features and improvements + +* Introduce client-side hillshading with `raster-dem` source type and `hillshade` layer type [#5286](https://github.com/mapbox/mapbox-gl-js/pull/5286) +* Add Color#toString and expose Color publicly [#5866](https://github.com/mapbox/mapbox-gl-js/pull/5866) +* Improve typing for `==` and `!=` expressions [#5840](https://github.com/mapbox/mapbox-gl-js/pull/5840) +* Made `coalesce` expressions more useful [#5755](https://github.com/mapbox/mapbox-gl-js/issues/5755) +* Enable implicit type assertions for array types [#5738](https://github.com/mapbox/mapbox-gl-js/pull/5738) + +### 🐛 Bug fixes + +* Fix standalone browser build [#5736](https://github.com/mapbox/mapbox-gl-js/pull/5736), [#5906](https://github.com/mapbox/mapbox-gl-js/pull/5906) +* Handle NaN as input to step and interpolate expressions [#5757](https://github.com/mapbox/mapbox-gl-js/pull/5757) +* Fix style diffing for changes to GeoJSON sources [#5745](https://github.com/mapbox/mapbox-gl-js/pull/5745) +* Mark layer "type" property as required [#5849](https://github.com/mapbox/mapbox-gl-js/pull/5849) + +## 10.1.0 + +* Remove support for validating and migrating v6 styles [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604) +* Remove support for validating v7 styles [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604) +* Remove spaces after commas in `to-string` representation of colors [#5480](https://github.com/mapbox/mapbox-gl-js/pull/5480) +* Fix bugs preventing `mapbox-gl-style-spec` package on NPM from being used externally [#5502](https://github.com/mapbox/mapbox-gl-js/pull/5502) +* Fix flow-typed interface generator [#5478](https://github.com/mapbox/mapbox-gl-js/pull/5478) +* Export `function` [#5584](https://github.com/mapbox/mapbox-gl-js/pull/5584) +* Export `StylePropertySpecification` type [#5593](https://github.com/mapbox/mapbox-gl-js/pull/5593) +* Split the `source_tile` entry in the JSON schema into `source_vector` and `source_raster` [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604) + +### Validation Changes + +* Require that `heatmap-color` use expressions instead of stop functions [#5624](https://github.com/mapbox/mapbox-gl-js/issues/5624) +* Remove support for including `{tokens}` in expressions for `text-field` and `icon-image` [#5599](https://github.com/mapbox/mapbox-gl-js/issues/5599) +* Disallow interpolation in expressions for `line-dasharray` [#5519](https://github.com/mapbox/mapbox-gl-js/pull/5519) +* Validate that zoom expressions only appear at the top level of an expression [#5609](https://github.com/mapbox/mapbox-gl-js/issues/5609) +* Validate that `step` and `interpolate` expressions don't have any duplicate stops [#5605](https://github.com/mapbox/mapbox-gl-js/issues/5605) +* Split `curve` expression into `step` and `interpolate` expressions [#5542](https://github.com/mapbox/mapbox-gl-js/pull/5542) +* Validate expression values for enum-typed properties [#5589](https://github.com/mapbox/mapbox-gl-js/pull/5589) +* Improve validation to catch uses of deprecated function syntax [#5667](https://github.com/mapbox/mapbox-gl-js/pull/5667) + +## 10.0.1 + +* Fix bug preventing @mapbox/mapbox-gl-style-spec package from being usable outside of mapbox-gl-js (#5502) + +## 10.0.0 + +* Add expression and heatmap layer support. See Mapbox GL JS v0.40.1 changelog entry for details. + +## 9.0.1 + +* Remove `fast-stable-stringify` dependency (#5152) + +## 9.0.0 + +* Fix validation error on categorical zoom-and-property functions (#4220) +* Relax requirement that styles using "icon-image" must have a "sprite" +* Prevent infinite loop in binarySearchForIndex when duplicate stops are present. (#4503) +* Ensure generated composite function stops are in the correct order (#4509) +* Update SDK support matrices to be current as of GL JS v0.35.1, iOS SDK v3.5.0, Android SDK 5.0.0 +* Remove support for implicitly-categorical functions +* BREAKING CHANGE: the API for the `function` module has changed. The `interpolated` and `piecewise-constant` exports +were replaced with a single unnamed export, a function which accepts an object conforming to the style spec "function" +definition, and an object defining a style spec property. It handles color parsing and validation of feature values +internally. +* Functions now support a "default" property. +* `parseColor` was promoted from gl-js. + +## 8.11.0 + +* Merge `feature-filter` repository into this repository #639 + +## 8.10.0 + +v8.0.0 styles are fully compatible with v8.10.0. + +### Style Specification Changes + +* Added `colorSpace` option to functions +* Added `fill-extrusion` layer type +* Add top-level `light` property +* Remove increase maximum `maxzoom` to 24 +* Deprecate paint classes :warning: +* Increase strictness of function validation + +### Reference JSON & API Changes + +* Added `deref` utility +* Added `group_by_layout` utility +* Merge `mapbox-gl-function` repository into this repository + +## 8.9.0 + +v8.0.0 styles are fully compatible with v8.9.0. + +* Added identity functions +* Added `auto` value which represents the calculated default value + +## 8.8.1 + +v8.0.0 styles are fully compatible with v8.8.1. + +* Fixed style validation for layers with invalid types + +## 8.8.0 + +v8.0.0 styles are fully compatible with v8.8.0. + +* Clarified documentation around fill-opacity. +* Update function documentation and validation for property functions. +* Add text-pitch-alignment property. +* Add icon-text-fit, icon-text-fit-padding properties. + +## 8.7.0 + +v8.0.0 styles are fully compatible with v8.7.0. + +* Add support for has / !has operators. + +## 8.6.0 + +v8.0.0 styles are fully compatible with v8.6.0. + +* Added support for zoom and feature driven functions. + +## 8.4.2 + +v8.0.0 styles are fully compatible with v8.4.2. + +* Refactored style validator to expose more granular validation methods + +## 8.4.1 + +v8.0.0 styles are fully compatible with v8.4.1. + +* Revert ramp validation checks that broke some styles. + +## 8.4.0 + +v8.0.0 styles are fully compatible with v8.4.0. + +* Added `cluster`, `clusterRadius`, `clusterMaxZoom` GeoJSON source properties. + +## 8.3.0 + +v8.0.0 styles are fully compatible with v8.3.0. + +* Added `line-offset` style property + +## 8.2.1 + +v8.0.0 styles are fully compatible with v8.2.1. + +* Enforce that all layers that use a vector source specify a "source-layer" + +## 8.2.0 + +v8.0.0 styles are fully compatible with v8.2.0. + +* Add inline `example` property. +* Enforce that all style properties must have documentation in `doc` property. +* Create minified style specs with `doc` and `example` properties removed. +* `validate` now validates against minified style spec. +* `format` now accepts `space` option to use with `JSON.stringify`. +* Remove `gl-style-spritify`. Mapbox GL sprites are now created automatically by + the Mapbox style APIs, or for hand-crafted styles, by [spritezero-cli](https://github.com/mapbox/spritezero-cli). + +## 8.1.0 + +v8.0.0 styles are fully compatible with v8.1.0. + +* [BREAKING] Simplified layout/paint layer property types to more closely align + with v7 types. +* Fixed migration script compatibility with newer versions of Node.js and io.js +* Removed `constants` from schema, they were deprecated in v8 +* Added style diff utility to generate semantic deltas between two stylesheets +* Added `visibility` property to `circle` layer type +* Added `pitch` property to stylesheet + +## 8.0.0 + +Introduction of Mapbox GL style specification v8. To migrate a v7 style to v8, +use the `gl-style-migrate` script as described in the README. + +* [BREAKING] The value of the `text-font` property is now an array of + strings, rather than a single comma separated string. +* [BREAKING] Renamed `symbol-min-distance` to `symbol-spacing`. +* [BREAKING] Renamed `background-image` to `background-pattern`. +* [BREAKING] Renamed `line-image` to `line-pattern`. +* [BREAKING] Renamed `fill-image` to `fill-pattern`. +* [BREAKING] Renamed the `url` property of the video source type to `urls`. +* [BREAKING] Coordinates in video sources are now specified in [lon, lat] order. +* [BREAKING] Removed `text-max-size` and `icon-max-size` properties; these + are now calculated automatically. +* [BREAKING] `text-size` and `icon-size` are now layout properties instead of paint properties. +* [BREAKING] Constants are no longer supported. If you are editing styles by + hand and want to use constants, you can use a preprocessing step with a tool + like [ScreeSS](https://github.com/screee/screess). +* [BREAKING] The format for `mapbox://` glyphs URLs has changed; you should + now use `mapbox://fonts/mapbox/{fontstack}/{range}.pbf`. +* [BREAKING] Reversed the priority of layers for calculating label placement: + labels for layers that appear later in the style now have priority over earlier + layers. +* Added a new `image` source type. +* Added a new `circle` layer type. +* Default map center location can now be set in the style. +* Added `mapbox://` sprite URLs `mapbox://sprite/{user | "mapbox"}/{id}` + +## 7.5.0 + +* Added gl-style-composite script, for auto-compositing sources in a style. + +## 7.4.1 + +* Use JSON.stringify for formatting instead of js-beautify + +## 7.0.0 + +Introduction of Mapbox GL style specification v7. + +* [BREAKING] Improve dashed lines (#234) +* [BREAKING] Remove prerendered layers (#232) +* Explicit visibility property (#212) +* Functions for all properties (#237) + +## 6.0.0 (Style spec v6) + +Introduction of Mapbox GL style specification v6. + +* [BREAKING] New filter syntax (#178) +* [BREAKING] Line gap property (#131) +* [BREAKING] Remove dashes from min/max-zoom (#175) +* [BREAKING] New layout/paint terminology (#166) +* [BREAKING] Single text positioning property (#197) +* Added requirements (#200) +* Added minimum, maximum, and period values (#198) + +## 0.0.5 (in progress) + +* [BREAKING] Switch to suffix for transition properties (`transition-*` -> `*-transition`). +* Added support for remote, non-Mapbox TileJSON sources. +* [BREAKING] Source `minZoom` and `maxZoom` renamed to `minzoom` and `maxzoom to match TileJSON. +* Added support for `mapbox://` glyph URLs. +* [BREAKING] Renamed `raster-fade` to `raster-fade-duration`. +* Added background-opacity property. +* Added "tokens" property to string values that can autocomplete fields from layers +* Added "units" property to describe value types + +## 0.0.4 (Aug 8 2014) + +* Initial public release diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/README.md b/node_modules/@plotly/mapbox-gl/src/style-spec/README.md new file mode 100644 index 0000000000000000000000000000000000000000..412e68485139f6fc01e16d39261d6ff1bca6339c --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/README.md @@ -0,0 +1,59 @@ +# Mapbox GL style specification & utilities + +This directory contains code and reference files that define the Mapbox GL style specification and provides some utilities for working with Mapbox styles. + +## npm package + +The Mapbox GL style specification and utilities are published as a seperate npm +package so that they can be installed without the bulk of GL JS. + + npm install @mapbox/mapbox-gl-style-spec + +## CLI Tools + +If you install this package globally, you will have access to several CLI tools. + + npm install @mapbox/mapbox-gl-style-spec --global + + +### `gl-style-composite` +```bash +$ gl-style-composite style.json +``` + +Will take a non-composited style and produce a [composite style](https://www.mapbox.com/blog/better-label-placement-in-mapbox-studio/). + +### `gl-style-migrate` + +This repo contains scripts for migrating GL styles of any version to the latest version +(currently v8). Migrate a style like this: + +```bash +$ gl-style-migrate bright-v7.json > bright-v8.json +``` + +To migrate a file in place, you can use the `sponge` utility from the `moreutils` package: + +```bash +$ brew install moreutils +$ gl-style-migrate bright.json | sponge bright.json +``` + +### `gl-style-format` + +```bash +$ gl-style-format style.json +``` + +Will format the given style JSON to use standard indentation and sorted object keys. + +### `gl-style-validate` + +```bash +$ gl-style-validate style.json +``` + +Will validate the given style JSON and print errors to stdout. Provide a +`--json` flag to get JSON output. + +To validate that a style can be uploaded to the Mapbox Styles API, use the `--mapbox-api-supported` flag. diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-composite b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-composite new file mode 100644 index 0000000000000000000000000000000000000000..ed9bdbc8640417f281f5ebeae4a7ccf706041147 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-composite @@ -0,0 +1,9 @@ +#!/usr/bin/env node + + +var fs = require('fs'), + argv = require('minimist')(process.argv.slice(2)), + format = require('../').format, + composite = require('../').composite; + +console.log(format(composite(JSON.parse(fs.readFileSync(argv._[0]))))); diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-format b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-format new file mode 100644 index 0000000000000000000000000000000000000000..96da14b5ffd26f5593c64d860ccd0a1be69eed3f --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-format @@ -0,0 +1,22 @@ +#!/usr/bin/env node + + +var fs = require('fs'), + argv = require('minimist')(process.argv.slice(2)), + format = require('../').format; + +if (argv.help || argv.h || (!argv._.length && process.stdin.isTTY)) { + return help(); +} + +console.log(format(JSON.parse(fs.readFileSync(argv._[0])), argv.space)); + +function help() { + console.log('usage:'); + console.log(' gl-style-format source.json > destination.json'); + console.log(''); + console.log('options:'); + console.log(' --space '); + console.log(' Number of spaces in output (default "2")'); + console.log(' Pass "0" for minified output.'); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-migrate b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-migrate new file mode 100644 index 0000000000000000000000000000000000000000..0fdb3e5a6ed410fdd77453da7885a8445e99a52a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-migrate @@ -0,0 +1,9 @@ +#!/usr/bin/env node + + +var fs = require('fs'), + argv = require('minimist')(process.argv.slice(2)), + format = require('../').format, + migrate = require('../').migrate; + +console.log(format(migrate(JSON.parse(fs.readFileSync(argv._[0]))))); diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-validate b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-validate new file mode 100644 index 0000000000000000000000000000000000000000..a112d65d133fb348b0c36198ac635d25ff633950 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/bin/gl-style-validate @@ -0,0 +1,50 @@ +#!/usr/bin/env node + + +var argv = require('minimist')(process.argv.slice(2), { + boolean: 'json', + boolean: 'mapbox-api-supported' + }), + validate = require('../').validate, + validateMapboxApiSupported = require('../').validateMapboxApiSupported + rw = require('rw'), + status = 0; + +if (argv.help || argv.h || (!argv._.length && process.stdin.isTTY)) { + return help(); +} + +if (!argv._.length) { + argv._.push('/dev/stdin'); +} + +argv._.forEach(function(file) { + var errors; + if (argv['mapbox-api-supported']) { + errors = validateMapboxApiSupported(rw.readFileSync(file, 'utf8')); + } else { + errors = validate(rw.readFileSync(file, 'utf8')); + } + if (errors.length) { + if (argv.json) { + process.stdout.write(JSON.stringify(errors, null, 2)); + } else { + errors.forEach(function (e) { + console.log('%s:%d: %s', file, e.line, e.message); + }); + } + status = 1; + } +}); + +process.exit(status); + +function help() { + console.log('usage:'); + console.log(' gl-style-validate file.json'); + console.log(' gl-style-validate < file.json'); + console.log(''); + console.log('options:'); + console.log('--json output errors as json'); + console.log('--mapbox-api-supported validate compatibility with Mapbox Styles API'); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/composite.js b/node_modules/@plotly/mapbox-gl/src/style-spec/composite.js new file mode 100644 index 0000000000000000000000000000000000000000..b9858126a1524156120ad51e7b68a51b901ea809 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/composite.js @@ -0,0 +1,50 @@ + +export default function (style) { + const styleIDs = []; + const sourceIDs = []; + const compositedSourceLayers = []; + + for (const id in style.sources) { + const source = style.sources[id]; + + if (source.type !== "vector") + continue; + + const match = /^mapbox:\/\/(.*)/.exec(source.url); + if (!match) + continue; + + styleIDs.push(id); + sourceIDs.push(match[1]); + } + + if (styleIDs.length < 2) + return style; + + styleIDs.forEach((id) => { + delete style.sources[id]; + }); + + const compositeID = sourceIDs.join(","); + + style.sources[compositeID] = { + "type": "vector", + "url": `mapbox://${compositeID}` + }; + + style.layers.forEach((layer) => { + if (styleIDs.indexOf(layer.source) >= 0) { + layer.source = compositeID; + + if ('source-layer' in layer) { + if (compositedSourceLayers.indexOf(layer['source-layer']) >= 0) { + throw new Error('Conflicting source layer names'); + } else { + compositedSourceLayers.push(layer['source-layer']); + } + } + } + }); + + return style; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/declass.js b/node_modules/@plotly/mapbox-gl/src/style-spec/declass.js new file mode 100644 index 0000000000000000000000000000000000000000..8d2140f99face79b7e4ba0ea2fd720a9bcb24311 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/declass.js @@ -0,0 +1,42 @@ + +import extend from './util/extend'; + +export default declassStyle; + +/** + * Returns a new style with the given 'paint classes' merged into each layer's + * main `paint` definiton, and with all `paint.*` properties removed. + * + * @private + * @param {Object} style A style JSON object. + * @param {Array} classes An array of paint classes to apply, in order. + * + * @example + * var declass = require('mapbox-gl-style-spec/lib/declass') + * var baseStyle = { ... style with a 'paint.night' property in some layers ... } + * var nightStyle = declass(baseStyle, ['night']) + * // nightStyle now has each layer's `paint.night` properties merged in to the + * // main `paint` property. + */ +function declassStyle(style, classes) { + return extend({}, style, { + layers: style.layers.map((layer) => { + const result = classes.reduce(declassLayer, layer); + + // strip away all `paint.CLASS` definitions + for (const key in result) { + if (/paint\..*/.test(key)) { + delete result[key]; + } + } + + return result; + }) + }); +} + +function declassLayer(layer, klass) { + return extend({}, layer, { + paint: extend({}, layer.paint, layer[`paint.${klass}`]) + }); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/deref.js b/node_modules/@plotly/mapbox-gl/src/style-spec/deref.js new file mode 100644 index 0000000000000000000000000000000000000000..729c9c923fa4ce583944897138779ac63c8f343f --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/deref.js @@ -0,0 +1,52 @@ + +import refProperties from './util/ref_properties'; + +function deref(layer, parent) { + const result = {}; + + for (const k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + + refProperties.forEach((k) => { + if (k in parent) { + result[k] = parent[k]; + } + }); + + return result; +} + +export default derefLayers; + +/** + * Given an array of layers, some of which may contain `ref` properties + * whose value is the `id` of another property, return a new array where + * such layers have been augmented with the 'type', 'source', etc. properties + * from the parent layer, and the `ref` property has been removed. + * + * The input is not modified. The output may contain references to portions + * of the input. + * + * @private + * @param {Array} layers + * @returns {Array} + */ +function derefLayers(layers) { + layers = layers.slice(); + + const map = Object.create(null); + for (let i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + + for (let i = 0; i < layers.length; i++) { + if ('ref' in layers[i]) { + layers[i] = deref(layers[i], map[layers[i].ref]); + } + } + + return layers; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/diff.js b/node_modules/@plotly/mapbox-gl/src/style-spec/diff.js new file mode 100644 index 0000000000000000000000000000000000000000..9228552e4b065b6394087294f02d0c92606132d7 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/diff.js @@ -0,0 +1,393 @@ + +import isEqual from './util/deep_equal'; + +const operations = { + + /* + * { command: 'setStyle', args: [stylesheet] } + */ + setStyle: 'setStyle', + + /* + * { command: 'addLayer', args: [layer, 'beforeLayerId'] } + */ + addLayer: 'addLayer', + + /* + * { command: 'removeLayer', args: ['layerId'] } + */ + removeLayer: 'removeLayer', + + /* + * { command: 'setPaintProperty', args: ['layerId', 'prop', value] } + */ + setPaintProperty: 'setPaintProperty', + + /* + * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] } + */ + setLayoutProperty: 'setLayoutProperty', + + /* + * { command: 'setFilter', args: ['layerId', filter] } + */ + setFilter: 'setFilter', + + /* + * { command: 'addSource', args: ['sourceId', source] } + */ + addSource: 'addSource', + + /* + * { command: 'removeSource', args: ['sourceId'] } + */ + removeSource: 'removeSource', + + /* + * { command: 'setGeoJSONSourceData', args: ['sourceId', data] } + */ + setGeoJSONSourceData: 'setGeoJSONSourceData', + + /* + * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] } + */ + setLayerZoomRange: 'setLayerZoomRange', + + /* + * { command: 'setLayerProperty', args: ['layerId', 'prop', value] } + */ + setLayerProperty: 'setLayerProperty', + + /* + * { command: 'setCenter', args: [[lon, lat]] } + */ + setCenter: 'setCenter', + + /* + * { command: 'setZoom', args: [zoom] } + */ + setZoom: 'setZoom', + + /* + * { command: 'setBearing', args: [bearing] } + */ + setBearing: 'setBearing', + + /* + * { command: 'setPitch', args: [pitch] } + */ + setPitch: 'setPitch', + + /* + * { command: 'setSprite', args: ['spriteUrl'] } + */ + setSprite: 'setSprite', + + /* + * { command: 'setGlyphs', args: ['glyphsUrl'] } + */ + setGlyphs: 'setGlyphs', + + /* + * { command: 'setTransition', args: [transition] } + */ + setTransition: 'setTransition', + + /* + * { command: 'setLighting', args: [lightProperties] } + */ + setLight: 'setLight' + +}; + +function addSource(sourceId, after, commands) { + commands.push({command: operations.addSource, args: [sourceId, after[sourceId]]}); +} + +function removeSource(sourceId, commands, sourcesRemoved) { + commands.push({command: operations.removeSource, args: [sourceId]}); + sourcesRemoved[sourceId] = true; +} + +function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); +} + +function canUpdateGeoJSON(before, after, sourceId) { + let prop; + for (prop in before[sourceId]) { + if (!before[sourceId].hasOwnProperty(prop)) continue; + if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!after[sourceId].hasOwnProperty(prop)) continue; + if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; +} + +function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + + let sourceId; + + // look for sources to remove + for (sourceId in before) { + if (!before.hasOwnProperty(sourceId)) continue; + if (!after.hasOwnProperty(sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + + // look for sources to add/update + for (sourceId in after) { + if (!after.hasOwnProperty(sourceId)) continue; + if (!before.hasOwnProperty(sourceId)) { + addSource(sourceId, after, commands); + } else if (!isEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + commands.push({command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data]}); + } else { + // no update command, must remove then add + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } +} + +function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + + let prop; + + for (prop in before) { + if (!before.hasOwnProperty(prop)) continue; + if (!isEqual(before[prop], after[prop])) { + commands.push({command, args: [layerId, prop, after[prop], klass]}); + } + } + for (prop in after) { + if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) continue; + if (!isEqual(before[prop], after[prop])) { + commands.push({command, args: [layerId, prop, after[prop], klass]}); + } + } +} + +function pluckId(layer) { + return layer.id; +} +function indexById(group, layer) { + group[layer.id] = layer; + return group; +} + +function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + + // order of layers by id + const beforeOrder = before.map(pluckId); + const afterOrder = after.map(pluckId); + + // index of layer by id + const beforeIndex = before.reduce(indexById, {}); + const afterIndex = after.reduce(indexById, {}); + + // track order of layers as if they have been mutated + const tracker = beforeOrder.slice(); + + // layers that have been added do not need to be diffed + const clean = Object.create(null); + + let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop; + + // remove layers + for (i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!afterIndex.hasOwnProperty(layerId)) { + commands.push({command: operations.removeLayer, args: [layerId]}); + tracker.splice(tracker.indexOf(layerId, d), 1); + } else { + // limit where in tracker we need to look for a match + d++; + } + } + + // add/reorder layers + for (i = 0, d = 0; i < afterOrder.length; i++) { + // work backwards as insert is before an existing layer + layerId = afterOrder[afterOrder.length - 1 - i]; + + if (tracker[tracker.length - 1 - i] === layerId) continue; + + if (beforeIndex.hasOwnProperty(layerId)) { + // remove the layer before we insert at the correct position + commands.push({command: operations.removeLayer, args: [layerId]}); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } else { + // limit where in tracker we need to look for a match + d++; + } + + // add layer at correct position + insertBeforeLayerId = tracker[tracker.length - i]; + commands.push({command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId]}); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + + // update layers + for (i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + + // no need to update if previously added (new or moved) + if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue; + + // If source, source-layer, or type have changes, then remove the layer + // and add it back 'from scratch'. + if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) { + commands.push({command: operations.removeLayer, args: [layerId]}); + // we add the layer back at the same position it was already in, so + // there's no need to update the `tracker` + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + commands.push({command: operations.addLayer, args: [afterLayer, insertBeforeLayerId]}); + continue; + } + + // layout, paint, filter, minzoom, maxzoom + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty); + if (!isEqual(beforeLayer.filter, afterLayer.filter)) { + commands.push({command: operations.setFilter, args: [layerId, afterLayer.filter]}); + } + if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + commands.push({command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom]}); + } + + // handle all other layer props, including paint.* + for (prop in beforeLayer) { + if (!beforeLayer.hasOwnProperty(prop)) continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]}); + } + } + for (prop in afterLayer) { + if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]}); + } + } + } +} + +/** + * Diff two stylesheet + * + * Creates semanticly aware diffs that can easily be applied at runtime. + * Operations produced by the diff closely resemble the mapbox-gl-js API. Any + * error creating the diff will fall back to the 'setStyle' operation. + * + * Example diff: + * [ + * { command: 'setConstant', args: ['@water', '#0000FF'] }, + * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] } + * ] + * + * @private + * @param {*} [before] stylesheet to compare from + * @param {*} after stylesheet to compare to + * @returns Array list of changes + */ +function diffStyles(before, after) { + if (!before) return [{command: operations.setStyle, args: [after]}]; + + let commands = []; + + try { + // Handle changes to top-level properties + if (!isEqual(before.version, after.version)) { + return [{command: operations.setStyle, args: [after]}]; + } + if (!isEqual(before.center, after.center)) { + commands.push({command: operations.setCenter, args: [after.center]}); + } + if (!isEqual(before.zoom, after.zoom)) { + commands.push({command: operations.setZoom, args: [after.zoom]}); + } + if (!isEqual(before.bearing, after.bearing)) { + commands.push({command: operations.setBearing, args: [after.bearing]}); + } + if (!isEqual(before.pitch, after.pitch)) { + commands.push({command: operations.setPitch, args: [after.pitch]}); + } + if (!isEqual(before.sprite, after.sprite)) { + commands.push({command: operations.setSprite, args: [after.sprite]}); + } + if (!isEqual(before.glyphs, after.glyphs)) { + commands.push({command: operations.setGlyphs, args: [after.glyphs]}); + } + if (!isEqual(before.transition, after.transition)) { + commands.push({command: operations.setTransition, args: [after.transition]}); + } + if (!isEqual(before.light, after.light)) { + commands.push({command: operations.setLight, args: [after.light]}); + } + + // Handle changes to `sources` + // If a source is to be removed, we also--before the removeSource + // command--need to remove all the style layers that depend on it. + const sourcesRemoved = {}; + + // First collect the {add,remove}Source commands + const removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + + // Push a removeLayer command for each style layer that depends on a + // source that's being removed. + // Also, exclude any such layers them from the input to `diffLayers` + // below, so that diffLayers produces the appropriate `addLayers` + // command + const beforeLayers = []; + if (before.layers) { + before.layers.forEach((layer) => { + if (sourcesRemoved[layer.source]) { + commands.push({command: operations.removeLayer, args: [layer.id]}); + } else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + + // Handle changes to `layers` + diffLayers(beforeLayers, after.layers, commands); + + } catch (e) { + // fall back to setStyle + console.warn('Unable to compute style diff:', e); + commands = [{command: operations.setStyle, args: [after]}]; + } + + return commands; +} + +export default diffStyles; +export {operations}; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/dist/.gitkeep b/node_modules/@plotly/mapbox-gl/src/style-spec/dist/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/empty.js b/node_modules/@plotly/mapbox-gl/src/style-spec/empty.js new file mode 100644 index 0000000000000000000000000000000000000000..e3db069f92d9b7670bae7428fb6ad72c698bbc39 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/empty.js @@ -0,0 +1,29 @@ +import latest from './reference/latest'; + +export default function emptyStyle() { + const style = {}; + + const version = latest['$version']; + for (const styleKey in latest['$root']) { + const spec = latest['$root'][styleKey]; + + if (spec.required) { + let value = null; + if (styleKey === 'version') { + value = version; + } else { + if (spec.type === 'array') { + value = []; + } else { + value = {}; + } + } + + if (value != null) { + style[styleKey] = value; + } + } + } + + return style; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/error/parsing_error.js b/node_modules/@plotly/mapbox-gl/src/style-spec/error/parsing_error.js new file mode 100644 index 0000000000000000000000000000000000000000..8ddb923e2b3dbbc5f2e42e137e384eb568327ac1 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/error/parsing_error.js @@ -0,0 +1,16 @@ +// @flow + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. + +export default class ParsingError { + message: string; + error: Error; + line: number; + + constructor(error: Error) { + this.error = error; + this.message = error.message; + const match = error.message.match(/line (\d+)/); + this.line = match ? parseInt(match[1], 10) : 0; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/error/validation_error.js b/node_modules/@plotly/mapbox-gl/src/style-spec/error/validation_error.js new file mode 100644 index 0000000000000000000000000000000000000000..9b90c2f98003a149d36149ca94f4d3944cb28387 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/error/validation_error.js @@ -0,0 +1,18 @@ +// @flow + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. + +export default class ValidationError { + message: string; + identifier: ?string; + line: ?number; + + constructor(key: ?string, value: ?{ __line__: number }, message: string, identifier: ?string) { + this.message = (key ? `${key}: ` : '') + message; + if (identifier) this.identifier = identifier; + + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/compound_expression.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/compound_expression.js new file mode 100644 index 0000000000000000000000000000000000000000..e948b0b7689e6c6c3587b1d91a025626106ee6c7 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/compound_expression.js @@ -0,0 +1,162 @@ +// @flow + +import {toString} from './types'; + +import ParsingContext from './parsing_context'; +import EvaluationContext from './evaluation_context'; +import assert from 'assert'; + +import type {Expression, ExpressionRegistry} from './expression'; +import type {Type} from './types'; +import type {Value} from './values'; + +export type Varargs = {| type: Type |}; +type Signature = Array | Varargs; +type Evaluate = (EvaluationContext, Array) => Value; +type Definition = [Type, Signature, Evaluate] | + {|type: Type, overloads: Array<[Signature, Evaluate]>|}; + +class CompoundExpression implements Expression { + name: string; + type: Type; + _evaluate: Evaluate; + args: Array; + + static definitions: {[_: string]: Definition }; + + constructor(name: string, type: Type, evaluate: Evaluate, args: Array) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; + } + + evaluate(ctx: EvaluationContext) { + return this._evaluate(ctx, this.args); + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined() { + return false; + } + + serialize(): Array { + return [this.name].concat(this.args.map(arg => arg.serialize())); + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + const op: string = (args[0]: any); + const definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + + // Now check argument types against each signature + const type = Array.isArray(definition) ? + definition[0] : definition.type; + + const availableOverloads = Array.isArray(definition) ? + [[definition[1], definition[2]]] : + definition.overloads; + + const overloads = availableOverloads.filter(([signature]) => ( + !Array.isArray(signature) || // varags + signature.length === args.length - 1 // correct param count + )); + + let signatureContext: ParsingContext = (null: any); + + for (const [params, evaluate] of overloads) { + // Use a fresh context for each attempted signature so that, if + // we eventually succeed, we haven't polluted `context.errors`. + signatureContext = new ParsingContext(context.registry, context.path, null, context.scope); + + // First parse all the args, potentially coercing to the + // types expected by this overload. + const parsedArgs: Array = []; + let argParseFailed = false; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + const expectedType = Array.isArray(params) ? + params[i - 1] : + params.type; + + const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + // Couldn't coerce args of this overload to expected type, move + // on to next one. + continue; + } + + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`); + continue; + } + } + + for (let i = 0; i < parsedArgs.length; i++) { + const expected = Array.isArray(params) ? params[i] : params.type; + const arg = parsedArgs[i]; + signatureContext.concat(i + 1).checkSubtype(expected, arg.type); + } + + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + + assert(!signatureContext || signatureContext.errors.length > 0); + + if (overloads.length === 1) { + context.errors.push(...signatureContext.errors); + } else { + const expected = overloads.length ? overloads : availableOverloads; + const signatures = expected + .map(([params]) => stringifySignature(params)) + .join(' | '); + + const actualTypes = []; + // For error message, re-parse arguments without trying to + // apply any coercions + for (let i = 1; i < args.length; i++) { + const parsed = context.parse(args[i], 1 + actualTypes.length); + if (!parsed) return null; + actualTypes.push(toString(parsed.type)); + } + context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`); + } + + return null; + } + + static register( + registry: ExpressionRegistry, + definitions: {[_: string]: Definition } + ) { + assert(!CompoundExpression.definitions); + CompoundExpression.definitions = definitions; + for (const name in definitions) { + registry[name] = CompoundExpression; + } + } +} + +function stringifySignature(signature: Signature): string { + if (Array.isArray(signature)) { + return `(${signature.map(toString).join(', ')})`; + } else { + return `(${toString(signature.type)}...)`; + } +} + +export default CompoundExpression; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/assertion.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/assertion.js new file mode 100644 index 0000000000000000000000000000000000000000..cfadac6d5d5eadca43c7318a6da310acd27da5a2 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/assertion.js @@ -0,0 +1,130 @@ +// @flow + +import assert from 'assert'; + +import { + ObjectType, + ValueType, + StringType, + NumberType, + BooleanType, + checkSubtype, + toString, + array +} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +const types = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType +}; + +class Assertion implements Expression { + type: Type; + args: Array; + + constructor(type: Type, args: Array) { + this.type = type; + this.args = args; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length < 2) + return context.error(`Expected at least one argument.`); + + let i = 1; + let type; + + const name: string = (args[0]: any); + if (name === 'array') { + let itemType; + if (args.length > 2) { + const type = args[1]; + if (typeof type !== 'string' || !(type in types) || type === 'object') + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + itemType = types[type]; + i++; + } else { + itemType = ValueType; + } + + let N; + if (args.length > 3) { + if (args[2] !== null && + (typeof args[2] !== 'number' || + args[2] < 0 || + args[2] !== Math.floor(args[2])) + ) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + + type = array(itemType, N); + } else { + assert(types[name], name); + type = types[name]; + } + + const parsed = []; + for (; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) return null; + parsed.push(input); + } + + return new Assertion(type, parsed); + } + + evaluate(ctx: EvaluationContext) { + for (let i = 0; i < this.args.length; i++) { + const value = this.args[i].evaluate(ctx); + const error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } else if (i === this.args.length - 1) { + throw new RuntimeError(`Expected value to be of type ${toString(this.type)}, but found ${toString(typeOf(value))} instead.`); + } + } + + assert(false); + return null; + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined(): boolean { + return this.args.every(arg => arg.outputDefined()); + } + + serialize(): Array { + const type = this.type; + const serialized = [type.kind]; + if (type.kind === 'array') { + const itemType = type.itemType; + if (itemType.kind === 'string' || + itemType.kind === 'number' || + itemType.kind === 'boolean') { + serialized.push(itemType.kind); + const N = type.N; + if (typeof N === 'number' || this.args.length > 1) { + serialized.push(N); + } + } + } + return serialized.concat(this.args.map(arg => arg.serialize())); + } +} + +export default Assertion; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/at.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/at.js new file mode 100644 index 0000000000000000000000000000000000000000..e777f43355ed77c4832fc22d9dc3d4069490f230 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/at.js @@ -0,0 +1,70 @@ +// @flow + +import {array, ValueType, NumberType} from '../types'; + +import RuntimeError from '../runtime_error'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type, ArrayType} from '../types'; +import type {Value} from '../values'; + +class At implements Expression { + type: Type; + index: Expression; + input: Expression; + + constructor(type: Type, index: Expression, input: Expression) { + this.type = type; + this.index = index; + this.input = input; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 3) + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + + const index = context.parse(args[1], 1, NumberType); + const input = context.parse(args[2], 2, array(context.expectedType || ValueType)); + + if (!index || !input) return null; + + const t: ArrayType = (input.type: any); + return new At(t.itemType, index, input); + } + + evaluate(ctx: EvaluationContext) { + const index = ((this.index.evaluate(ctx): any): number); + const array = ((this.input.evaluate(ctx): any): Array); + + if (index < 0) { + throw new RuntimeError(`Array index out of bounds: ${index} < 0.`); + } + + if (index >= array.length) { + throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`); + } + + if (index !== Math.floor(index)) { + throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`); + } + + return array[index]; + } + + eachChild(fn: (_: Expression) => void) { + fn(this.index); + fn(this.input); + } + + outputDefined() { + return false; + } + + serialize() { + return ["at", this.index.serialize(), this.input.serialize()]; + } +} + +export default At; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/case.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/case.js new file mode 100644 index 0000000000000000000000000000000000000000..c750aed5ed7d6c59ff18d4bbb9f00298f6099df3 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/case.js @@ -0,0 +1,85 @@ +// @flow + +import assert from 'assert'; + +import {BooleanType} from '../types'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +type Branches = Array<[Expression, Expression]>; + +class Case implements Expression { + type: Type; + + branches: Branches; + otherwise: Expression; + + constructor(type: Type, branches: Branches, otherwise: Expression) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 0) + return context.error(`Expected an odd number of arguments.`); + + let outputType: ?Type; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + + const branches = []; + for (let i = 1; i < args.length - 1; i += 2) { + const test = context.parse(args[i], i, BooleanType); + if (!test) return null; + + const result = context.parse(args[i + 1], i + 1, outputType); + if (!result) return null; + + branches.push([test, result]); + + outputType = outputType || result.type; + } + + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) return null; + + assert(outputType); + return new Case((outputType: any), branches, otherwise); + } + + evaluate(ctx: EvaluationContext) { + for (const [test, expression] of this.branches) { + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + for (const [test, expression] of this.branches) { + fn(test); + fn(expression); + } + fn(this.otherwise); + } + + outputDefined(): boolean { + return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined(); + } + + serialize() { + const serialized = ["case"]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Case; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/coalesce.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/coalesce.js new file mode 100644 index 0000000000000000000000000000000000000000..9cfce9e987d2cdc3d6bbc2b8a132c0bc84a22120 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/coalesce.js @@ -0,0 +1,93 @@ +// @flow + +import assert from 'assert'; + +import {checkSubtype, ValueType} from '../types'; +import ResolvedImage from '../types/resolved_image'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Coalesce implements Expression { + type: Type; + args: Array; + + constructor(type: Type, args: Array) { + this.type = type; + this.args = args; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 2) { + return context.error("Expectected at least one argument."); + } + let outputType: Type = (null: any); + const expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + const parsedArgs = []; + + for (const arg of args.slice(1)) { + const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, {typeAnnotation: 'omit'}); + if (!parsed) return null; + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + assert(outputType); + + // Above, we parse arguments without inferred type annotation so that + // they don't produce a runtime error for `null` input, which would + // preempt the desired null-coalescing behavior. + // Thus, if any of our arguments would have needed an annotation, we + // need to wrap the enclosing coalesce expression with it instead. + const needsAnnotation = expectedType && + parsedArgs.some(arg => checkSubtype(expectedType, arg.type)); + + return needsAnnotation ? + new Coalesce(ValueType, parsedArgs) : + new Coalesce((outputType: any), parsedArgs); + } + + evaluate(ctx: EvaluationContext) { + let result = null; + let argCount = 0; + let requestedImageName; + for (const arg of this.args) { + argCount++; + result = arg.evaluate(ctx); + // we need to keep track of the first requested image in a coalesce statement + // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + + if (result !== null) break; + } + return result; + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined(): boolean { + return this.args.every(arg => arg.outputDefined()); + } + + serialize() { + const serialized = ["coalesce"]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Coalesce; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/coercion.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/coercion.js new file mode 100644 index 0000000000000000000000000000000000000000..3eb46f776623f5744e052b36281439995106c9d1 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/coercion.js @@ -0,0 +1,133 @@ +// @flow + +import assert from 'assert'; + +import {BooleanType, ColorType, NumberType, StringType, ValueType} from '../types'; +import {Color, toString as valueToString, validateRGBA} from '../values'; +import RuntimeError from '../runtime_error'; +import Formatted from '../types/formatted'; +import FormatExpression from '../definitions/format'; +import ImageExpression from '../definitions/image'; +import ResolvedImage from '../types/resolved_image'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +const types = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType +}; + +/** + * Special form for error-coalescing coercion expressions "to-number", + * "to-color". Since these coercions can fail at runtime, they accept multiple + * arguments, only evaluating one at a time until one succeeds. + * + * @private + */ +class Coercion implements Expression { + type: Type; + args: Array; + + constructor(type: Type, args: Array) { + this.type = type; + this.args = args; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length < 2) + return context.error(`Expected at least one argument.`); + + const name: string = (args[0]: any); + assert(types[name], name); + + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) + return context.error(`Expected one argument.`); + + const type = types[name]; + + const parsed = []; + for (let i = 1; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) return null; + parsed.push(input); + } + + return new Coercion(type, parsed); + } + + evaluate(ctx: EvaluationContext) { + if (this.type.kind === 'boolean') { + return Boolean(this.args[0].evaluate(ctx)); + } else if (this.type.kind === 'color') { + let input; + let error; + for (const arg of this.args) { + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } else if (typeof input === 'string') { + const c = ctx.parseColor(input); + if (c) return c; + } else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`; + } else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color((input[0]: any) / 255, (input[1]: any) / 255, (input[2]: any) / 255, (input[3]: any)); + } + } + } + throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : String(JSON.stringify(input))}'`); + } else if (this.type.kind === 'number') { + let value = null; + for (const arg of this.args) { + value = arg.evaluate(ctx); + if (value === null) return 0; + const num = Number(value); + if (isNaN(num)) continue; + return num; + } + throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`); + } else if (this.type.kind === 'formatted') { + // There is no explicit 'to-formatted' but this coercion can be implicitly + // created by properties that expect the 'formatted' type. + return Formatted.fromString(valueToString(this.args[0].evaluate(ctx))); + } else if (this.type.kind === 'resolvedImage') { + return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx))); + } else { + return valueToString(this.args[0].evaluate(ctx)); + } + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined(): boolean { + return this.args.every(arg => arg.outputDefined()); + } + + serialize() { + if (this.type.kind === 'formatted') { + return new FormatExpression([{content: this.args[0], scale: null, font: null, textColor: null}]).serialize(); + } + + if (this.type.kind === 'resolvedImage') { + return new ImageExpression(this.args[0]).serialize(); + } + + const serialized = [`to-${this.type.kind}`]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Coercion; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/collator.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/collator.js new file mode 100644 index 0000000000000000000000000000000000000000..379d5d6047e5132039036d567108e0867ae7c4b1 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/collator.js @@ -0,0 +1,78 @@ +// @flow + +import {StringType, BooleanType, CollatorType} from '../types'; +import Collator from '../types/collator'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +export default class CollatorExpression implements Expression { + type: Type; + caseSensitive: Expression; + diacriticSensitive: Expression; + locale: Expression | null; + + constructor(caseSensitive: Expression, diacriticSensitive: Expression, locale: Expression | null) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 2) + return context.error(`Expected one argument.`); + + const options = (args[1]: any); + if (typeof options !== "object" || Array.isArray(options)) + return context.error(`Collator options argument must be an object.`); + + const caseSensitive = context.parse( + options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) return null; + + const diacriticSensitive = context.parse( + options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) return null; + + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) return null; + } + + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); + } + + evaluate(ctx: EvaluationContext) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } + } + + outputDefined() { + // Technically the set of possible outputs is the combinatoric set of Collators produced + // by all possible outputs of locale/caseSensitive/diacriticSensitive + // But for the primary use of Collators in comparison operators, we ignore the Collator's + // possible outputs anyway, so we can get away with leaving this false for now. + return false; + } + + serialize() { + const options = {}; + options['case-sensitive'] = this.caseSensitive.serialize(); + options['diacritic-sensitive'] = this.diacriticSensitive.serialize(); + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + return ["collator", options]; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/comparison.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/comparison.js new file mode 100644 index 0000000000000000000000000000000000000000..210df55ac7ae9ee7663158967e44b7f8ca02b256 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/comparison.js @@ -0,0 +1,184 @@ +// @flow + +import {toString, ValueType, BooleanType, CollatorType} from '../types'; +import Assertion from './assertion'; +import {typeOf} from '../values'; +import RuntimeError from '../runtime_error'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +type ComparisonOperator = '==' | '!=' | '<' | '>' | '<=' | '>=' ; + +function isComparableType(op: ComparisonOperator, type: Type) { + if (op === '==' || op === '!=') { + // equality operator + return type.kind === 'boolean' || + type.kind === 'string' || + type.kind === 'number' || + type.kind === 'null' || + type.kind === 'value'; + } else { + // ordering operator + return type.kind === 'string' || + type.kind === 'number' || + type.kind === 'value'; + } +} + +function eq(ctx, a, b) { return a === b; } +function neq(ctx, a, b) { return a !== b; } +function lt(ctx, a, b) { return a < b; } +function gt(ctx, a, b) { return a > b; } +function lteq(ctx, a, b) { return a <= b; } +function gteq(ctx, a, b) { return a >= b; } + +function eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; } +function neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); } +function ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; } +function gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; } +function lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; } +function gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; } + +/** + * Special form for comparison operators, implementing the signatures: + * - (T, T, ?Collator) => boolean + * - (T, value, ?Collator) => boolean + * - (value, T, ?Collator) => boolean + * + * For inequalities, T must be either value, string, or number. For ==/!=, it + * can also be boolean or null. + * + * Equality semantics are equivalent to Javascript's strict equality (===/!==) + * -- i.e., when the arguments' types don't match, == evaluates to false, != to + * true. + * + * When types don't match in an ordering comparison, a runtime error is thrown. + * + * @private + */ +function makeComparison(op: ComparisonOperator, compareBasic, compareWithCollator) { + const isOrderComparison = op !== '==' && op !== '!='; + + return class Comparison implements Expression { + type: Type; + lhs: Expression; + rhs: Expression; + collator: ?Expression; + hasUntypedArgument: boolean; + + constructor(lhs: Expression, rhs: Expression, collator: ?Expression) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 3 && args.length !== 4) + return context.error(`Expected two or three arguments.`); + + const op: ComparisonOperator = (args[0]: any); + + let lhs = context.parse(args[1], 1, ValueType); + if (!lhs) return null; + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error(`"${op}" comparisons are not supported for type '${toString(lhs.type)}'.`); + } + let rhs = context.parse(args[2], 2, ValueType); + if (!rhs) return null; + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error(`"${op}" comparisons are not supported for type '${toString(rhs.type)}'.`); + } + + if ( + lhs.type.kind !== rhs.type.kind && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value' + ) { + return context.error(`Cannot compare types '${toString(lhs.type)}' and '${toString(rhs.type)}'.`); + } + + if (isOrderComparison) { + // typing rules specific to less/greater than operators + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + // (value, T) + lhs = new Assertion(rhs.type, [lhs]); + } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + // (T, value) + rhs = new Assertion(lhs.type, [rhs]); + } + } + + let collator = null; + if (args.length === 4) { + if ( + lhs.type.kind !== 'string' && + rhs.type.kind !== 'string' && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value' + ) { + return context.error(`Cannot use collator to compare non-string types.`); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) return null; + } + + return new Comparison(lhs, rhs, collator); + } + + evaluate(ctx: EvaluationContext) { + const lhs = this.lhs.evaluate(ctx); + const rhs = this.rhs.evaluate(ctx); + + if (isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + // check that type is string or number, and equal + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`); + } + } + + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + if (lt.kind !== 'string' || rt.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + + return this.collator ? + compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : + compareBasic(ctx, lhs, rhs); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + } + + outputDefined(): boolean { + return true; + } + + serialize() { + const serialized = [op]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } + }; +} + +export const Equals = makeComparison('==', eq, eqCollate); +export const NotEquals = makeComparison('!=', neq, neqCollate); +export const LessThan = makeComparison('<', lt, ltCollate); +export const GreaterThan = makeComparison('>', gt, gtCollate); +export const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); +export const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/format.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/format.js new file mode 100644 index 0000000000000000000000000000000000000000..a376cacff02fe195fcd583f341bb0ce027992ff0 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/format.js @@ -0,0 +1,144 @@ +// @flow + +import {NumberType, ValueType, FormattedType, array, StringType, ColorType, ResolvedImageType} from '../types'; +import Formatted, {FormattedSection} from '../types/formatted'; +import {toString, typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +type FormattedSectionExpression = { + // Content of a section may be Image expression or other + // type of expression that is coercable to 'string'. + content: Expression, + scale: Expression | null; + font: Expression | null; + textColor: Expression | null; +} + +export default class FormatExpression implements Expression { + type: Type; + sections: Array; + + constructor(sections: Array) { + this.type = FormattedType; + this.sections = sections; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length < 2) { + return context.error(`Expected at least one argument.`); + } + + const firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error(`First argument must be an image or text section.`); + } + + const sections: Array = []; + let nextTokenMayBeObject = false; + for (let i = 1; i <= args.length - 1; ++i) { + const arg = (args[i]: any); + + if (nextTokenMayBeObject && typeof arg === "object" && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + + let scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) return null; + } + + let font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array(StringType)); + if (!font) return null; + } + + let textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) return null; + } + + const lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } else { + const content = context.parse(args[i], 1, ValueType); + if (!content) return null; + + const kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') + return context.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`); + + nextTokenMayBeObject = true; + sections.push({content, scale: null, font: null, textColor: null}); + } + } + + return new FormatExpression(sections); + } + + evaluate(ctx: EvaluationContext) { + const evaluateSection = section => { + const evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + + return new FormattedSection( + toString(evaluatedContent), + null, + section.scale ? section.scale.evaluate(ctx) : null, + section.font ? section.font.evaluate(ctx).join(',') : null, + section.textColor ? section.textColor.evaluate(ctx) : null + ); + }; + + return new Formatted(this.sections.map(evaluateSection)); + } + + eachChild(fn: (_: Expression) => void) { + for (const section of this.sections) { + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } + } + + outputDefined() { + // Technically the combinatoric set of all children + // Usually, this.text will be undefined anyway + return false; + } + + serialize() { + const serialized = ["format"]; + for (const section of this.sections) { + serialized.push(section.content.serialize()); + const options = {}; + if (section.scale) { + options['font-scale'] = section.scale.serialize(); + } + if (section.font) { + options['text-font'] = section.font.serialize(); + } + if (section.textColor) { + options['text-color'] = section.textColor.serialize(); + } + serialized.push(options); + } + return serialized; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/image.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/image.js new file mode 100644 index 0000000000000000000000000000000000000000..8b73e1c79dc705135d118210650360b6f7b1b6f2 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/image.js @@ -0,0 +1,52 @@ +// @flow + +import {ResolvedImageType, StringType} from '../types'; +import ResolvedImage from '../types/resolved_image'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +export default class ImageExpression implements Expression { + type: Type; + input: Expression; + + constructor(input: Expression) { + this.type = ResolvedImageType; + this.input = input; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 2) { + return context.error(`Expected two arguments.`); + } + + const name = context.parse(args[1], 1, StringType); + if (!name) return context.error(`No image name provided.`); + + return new ImageExpression(name); + } + + evaluate(ctx: EvaluationContext) { + const evaluatedImageName = this.input.evaluate(ctx); + + const value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + + return value; + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + } + + outputDefined() { + // The output of image is determined by the list of available images in the evaluation context + return false; + } + + serialize() { + return ["image", this.input.serialize()]; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/in.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/in.js new file mode 100644 index 0000000000000000000000000000000000000000..0e6681a5080e19d045ddb4a5a6d6bffa60d46a7f --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/in.js @@ -0,0 +1,72 @@ +// @flow + +import {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class In implements Expression { + type: Type; + needle: Expression; + haystack: Expression; + + constructor(needle: Expression, haystack: Expression) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 3) { + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + } + + const needle = context.parse(args[1], 1, ValueType); + + const haystack = context.parse(args[2], 2, ValueType); + + if (!needle || !haystack) return null; + + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`); + } + + return new In(needle, haystack); + } + + evaluate(ctx: EvaluationContext) { + const needle = (this.needle.evaluate(ctx): any); + const haystack = (this.haystack.evaluate(ctx): any); + + if (!haystack) return false; + + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`); + } + + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`); + } + + return haystack.indexOf(needle) >= 0; + } + + eachChild(fn: (_: Expression) => void) { + fn(this.needle); + fn(this.haystack); + } + + outputDefined() { + return true; + } + + serialize() { + return ["in", this.needle.serialize(), this.haystack.serialize()]; + } +} + +export default In; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/index.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fcc1535c8bf33f5fe23b406cfa502b7dfc18e18d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/index.js @@ -0,0 +1,565 @@ +// @flow + +import { + type Type, + NumberType, + StringType, + BooleanType, + ColorType, + ObjectType, + ValueType, + ErrorType, + CollatorType, + array, + toString as typeToString +} from '../types'; + +import {typeOf, Color, validateRGBA, toString as valueToString} from '../values'; +import CompoundExpression from '../compound_expression'; +import RuntimeError from '../runtime_error'; +import Let from './let'; +import Var from './var'; +import Literal from './literal'; +import Assertion from './assertion'; +import Coercion from './coercion'; +import At from './at'; +import In from './in'; +import IndexOf from './index_of'; +import Match from './match'; +import Case from './case'; +import Slice from './slice'; +import Step from './step'; +import Interpolate from './interpolate'; +import Coalesce from './coalesce'; +import { + Equals, + NotEquals, + LessThan, + GreaterThan, + LessThanOrEqual, + GreaterThanOrEqual +} from './comparison'; +import CollatorExpression from './collator'; +import NumberFormat from './number_format'; +import FormatExpression from './format'; +import ImageExpression from './image'; +import Length from './length'; +import Within from './within'; + +import type {Varargs} from '../compound_expression'; +import type {ExpressionRegistry} from '../expression'; + +const expressions: ExpressionRegistry = { + // special forms + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within +}; + +function rgba(ctx, [r, g, b, a]) { + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + const alpha = a ? a.evaluate(ctx) : 1; + const error = validateRGBA(r, g, b, alpha); + if (error) throw new RuntimeError(error); + return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha); +} + +function has(key, obj) { + return key in obj; +} + +function get(key, obj) { + const v = obj[key]; + return typeof v === 'undefined' ? null : v; +} + +function binarySearch(v, a, i, j) { + while (i <= j) { + const m = (i + j) >> 1; + if (a[m] === v) + return true; + if (a[m] > v) + j = m - 1; + else + i = m + 1; + } + return false; +} + +function varargs(type: Type): Varargs { + return {type}; +} + +CompoundExpression.register(expressions, { + 'error': [ + ErrorType, + [StringType], + (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); } + ], + 'typeof': [ + StringType, + [ValueType], + (ctx, [v]) => typeToString(typeOf(v.evaluate(ctx))) + ], + 'to-rgba': [ + array(NumberType, 4), + [ColorType], + (ctx, [v]) => { + return v.evaluate(ctx).toArray(); + } + ], + 'rgb': [ + ColorType, + [NumberType, NumberType, NumberType], + rgba + ], + 'rgba': [ + ColorType, + [NumberType, NumberType, NumberType, NumberType], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + (ctx, [key]) => has(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {}) + ], + 'properties': [ + ObjectType, + [], + (ctx) => ctx.properties() + ], + 'geometry-type': [ + StringType, + [], + (ctx) => ctx.geometryType() + ], + 'id': [ + ValueType, + [], + (ctx) => ctx.id() + ], + 'zoom': [ + NumberType, + [], + (ctx) => ctx.globals.zoom + ], + 'heatmap-density': [ + NumberType, + [], + (ctx) => ctx.globals.heatmapDensity || 0 + ], + 'line-progress': [ + NumberType, + [], + (ctx) => ctx.globals.lineProgress || 0 + ], + 'accumulated': [ + ValueType, + [], + (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated + ], + '+': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 0; + for (const arg of args) { + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 1; + for (const arg of args) { + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx) + ], [ + [NumberType], + (ctx, [a]) => -a.evaluate(ctx) + ] + ] + }, + '/': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx) + ], + '%': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx) + ], + 'ln2': [ + NumberType, + [], + () => Math.LN2 + ], + 'pi': [ + NumberType, + [], + () => Math.PI + ], + 'e': [ + NumberType, + [], + () => Math.E + ], + '^': [ + NumberType, + [NumberType, NumberType], + (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx)) + ], + 'sqrt': [ + NumberType, + [NumberType], + (ctx, [x]) => Math.sqrt(x.evaluate(ctx)) + ], + 'log10': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10 + ], + 'ln': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) + ], + 'log2': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2 + ], + 'sin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.sin(n.evaluate(ctx)) + ], + 'cos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.cos(n.evaluate(ctx)) + ], + 'tan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.tan(n.evaluate(ctx)) + ], + 'asin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.asin(n.evaluate(ctx)) + ], + 'acos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.acos(n.evaluate(ctx)) + ], + 'atan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.atan(n.evaluate(ctx)) + ], + 'min': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx))) + ], + 'max': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx))) + ], + 'abs': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.abs(n.evaluate(ctx)) + ], + 'round': [ + NumberType, + [NumberType], + (ctx, [n]) => { + const v = n.evaluate(ctx); + // Javascript's Math.round() rounds towards +Infinity for halfway + // values, even when they're negative. It's more common to round + // away from 0 (e.g., this is what python and C++ do) + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.floor(n.evaluate(ctx)) + ], + 'ceil': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.ceil(n.evaluate(ctx)) + ], + 'filter-==': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => ctx.properties()[(k: any).value] === (v: any).value + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + (ctx, [v]) => ctx.id() === (v: any).value + ], + 'filter-type-==': [ + BooleanType, + [StringType], + (ctx, [v]) => ctx.geometryType() === (v: any).value + ], + 'filter-<': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + (ctx, [k]) => (k: any).value in ctx.properties() + ], + 'filter-has-id': [ + BooleanType, + [], + (ctx) => (ctx.id() !== null && ctx.id() !== undefined) + ], + 'filter-type-in': [ + BooleanType, + [array(StringType)], + (ctx, [v]) => (v: any).value.indexOf(ctx.geometryType()) >= 0 + ], + 'filter-id-in': [ + BooleanType, + [array(ValueType)], + (ctx, [v]) => (v: any).value.indexOf(ctx.id()) >= 0 + ], + 'filter-in-small': [ + BooleanType, + [StringType, array(ValueType)], + // assumes v is an array literal + (ctx, [k, v]) => (v: any).value.indexOf(ctx.properties()[(k: any).value]) >= 0 + ], + 'filter-in-large': [ + BooleanType, + [StringType, array(ValueType)], + // assumes v is a array literal with values sorted in ascending order and of a single type + (ctx, [k, v]) => binarySearch(ctx.properties()[(k: any).value], (v: any).value, 0, (v: any).value.length - 1) + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (!arg.evaluate(ctx)) + return false; + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (arg.evaluate(ctx)) + return true; + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + (ctx, [b]) => !b.evaluate(ctx) + ], + 'is-supported-script': [ + BooleanType, + [StringType], + // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant + (ctx, [s]) => { + const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toUpperCase() + ], + 'downcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toLowerCase() + ], + 'concat': [ + StringType, + varargs(ValueType), + (ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('') + ], + 'resolved-locale': [ + StringType, + [CollatorType], + (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale() + ] +}); + +export default expressions; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/index_of.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/index_of.js new file mode 100644 index 0000000000000000000000000000000000000000..48e629335cfea3fd9fc9b32cc23fab6d2a6f883c --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/index_of.js @@ -0,0 +1,89 @@ +// @flow + +import {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class IndexOf implements Expression { + type: Type; + needle: Expression; + haystack: Expression; + fromIndex: ?Expression; + + constructor(needle: Expression, haystack: Expression, fromIndex?: Expression) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + + const needle = context.parse(args[1], 1, ValueType); + + const haystack = context.parse(args[2], 2, ValueType); + + if (!needle || !haystack) return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`); + } + + if (args.length === 4) { + const fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) return null; + return new IndexOf(needle, haystack, fromIndex); + } else { + return new IndexOf(needle, haystack); + } + } + + evaluate(ctx: EvaluationContext) { + const needle = (this.needle.evaluate(ctx): any); + const haystack = (this.haystack.evaluate(ctx): any); + + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`); + } + + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`); + } + + if (this.fromIndex) { + const fromIndex = (this.fromIndex.evaluate(ctx): number); + return haystack.indexOf(needle, fromIndex); + } + + return haystack.indexOf(needle); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } + } + + outputDefined() { + return false; + } + + serialize() { + if (this.fromIndex != null && this.fromIndex !== undefined) { + const fromIndex = this.fromIndex.serialize(); + return ["index-of", this.needle.serialize(), this.haystack.serialize(), fromIndex]; + } + return ["index-of", this.needle.serialize(), this.haystack.serialize()]; + } +} + +export default IndexOf; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/interpolate.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/interpolate.js new file mode 100644 index 0000000000000000000000000000000000000000..98a1b65e4f25fcd43ea3ddfc8ee410959c01de04 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/interpolate.js @@ -0,0 +1,267 @@ +// @flow + +import UnitBezier from '@mapbox/unitbezier'; + +import * as interpolate from '../../util/interpolate'; +import {toString, NumberType, ColorType} from '../types'; +import {findStopLessThanOrEqualTo} from '../stops'; +import {hcl, lab} from '../../util/color_spaces'; + +import type {Stops} from '../stops'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +export type InterpolationType = + { name: 'linear' } | + { name: 'exponential', base: number } | + { name: 'cubic-bezier', controlPoints: [number, number, number, number] }; + +class Interpolate implements Expression { + type: Type; + + operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab'; + interpolation: InterpolationType; + input: Expression; + labels: Array; + outputs: Array; + + constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + + static interpolationFactor(interpolation: InterpolationType, input: number, lower: number, upper: number) { + let t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } else if (interpolation.name === 'cubic-bezier') { + const c = interpolation.controlPoints; + const ub = new UnitBezier(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + let [operator, interpolation, input, ...rest] = args; + + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error(`Expected an interpolation type expression.`, 1); + } + + if (interpolation[0] === 'linear') { + interpolation = {name: 'linear'}; + } else if (interpolation[0] === 'exponential') { + const base = interpolation[1]; + if (typeof base !== 'number') + return context.error(`Exponential interpolation requires a numeric base.`, 1, 1); + interpolation = { + name: 'exponential', + base + }; + } else if (interpolation[0] === 'cubic-bezier') { + const controlPoints = interpolation.slice(1); + if ( + controlPoints.length !== 4 || + controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1) + ) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + + interpolation = { + name: 'cubic-bezier', + controlPoints: (controlPoints: any) + }; + } else { + return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0); + } + + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + + if ((args.length - 1) % 2 !== 0) { + return context.error(`Expected an even number of arguments.`); + } + + input = context.parse(input, 2, NumberType); + if (!input) return null; + + const stops: Stops = []; + + let outputType: Type = (null: any); + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + + for (let i = 0; i < rest.length; i += 2) { + const label = rest[i]; + const value = rest[i + 1]; + + const labelKey = i + 3; + const valueKey = i + 4; + + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + + if (outputType.kind !== 'number' && + outputType.kind !== 'color' && + !( + outputType.kind === 'array' && + outputType.itemType.kind === 'number' && + typeof outputType.N === 'number' + ) + ) { + return context.error(`Type ${toString(outputType)} is not interpolatable.`); + } + + return new Interpolate(outputType, (operator: any), interpolation, input, stops); + } + + evaluate(ctx: EvaluationContext) { + const labels = this.labels; + const outputs = this.outputs; + + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + + const value = ((this.input.evaluate(ctx): any): number); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + + const index = findStopLessThanOrEqualTo(labels, value); + const lower = labels[index]; + const upper = labels[index + 1]; + const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + + const outputLower = outputs[index].evaluate(ctx); + const outputUpper = outputs[index + 1].evaluate(ctx); + + if (this.operator === 'interpolate') { + return (interpolate[this.type.kind.toLowerCase()]: any)(outputLower, outputUpper, t); // eslint-disable-line import/namespace + } else if (this.operator === 'interpolate-hcl') { + return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t)); + } else { + return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t)); + } + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + + outputDefined(): boolean { + return this.outputs.every(out => out.outputDefined()); + } + + serialize(): Array { + let interpolation; + if (this.interpolation.name === 'linear') { + interpolation = ["linear"]; + } else if (this.interpolation.name === 'exponential') { + if (this.interpolation.base === 1) { + interpolation = ["linear"]; + } else { + interpolation = ["exponential", this.interpolation.base]; + } + } else { + interpolation = ["cubic-bezier" ].concat(this.interpolation.controlPoints); + } + + const serialized = [this.operator, interpolation, this.input.serialize()]; + + for (let i = 0; i < this.labels.length; i++) { + serialized.push( + this.labels[i], + this.outputs[i].serialize() + ); + } + return serialized; + } +} + +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private +*/ +function exponentialInterpolation(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +export default Interpolate; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/length.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/length.js new file mode 100644 index 0000000000000000000000000000000000000000..abaaf0bc049a94d2ac9322b00661a89a86e29283 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/length.js @@ -0,0 +1,61 @@ +// @flow + +import {NumberType, toString} from '../types'; + +import {typeOf} from '../values'; +import RuntimeError from '../runtime_error'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Length implements Expression { + type: Type; + input: Expression; + + constructor(input: Expression) { + this.type = NumberType; + this.input = input; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2) + return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); + + const input = context.parse(args[1], 1); + if (!input) return null; + + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') + return context.error(`Expected argument of type string or array, but found ${toString(input.type)} instead.`); + + return new Length(input); + } + + evaluate(ctx: EvaluationContext) { + const input = this.input.evaluate(ctx); + if (typeof input === 'string') { + return input.length; + } else if (Array.isArray(input)) { + return input.length; + } else { + throw new RuntimeError(`Expected value to be of type string or array, but found ${toString(typeOf(input))} instead.`); + } + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + } + + outputDefined() { + return false; + } + + serialize() { + const serialized = ["length"]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Length; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/let.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/let.js new file mode 100644 index 0000000000000000000000000000000000000000..cfa449d8a7e67bcdfa6c0eb60529bc65d70b95ab --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/let.js @@ -0,0 +1,72 @@ +// @flow + +import type {Type} from '../types'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; + +class Let implements Expression { + type: Type; + bindings: Array<[string, Expression]>; + result: Expression; + + constructor(bindings: Array<[string, Expression]>, result: Expression) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; + } + + evaluate(ctx: EvaluationContext) { + return this.result.evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + for (const binding of this.bindings) { + fn(binding[1]); + } + fn(this.result); + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`); + + const bindings: Array<[string, Expression]> = []; + for (let i = 1; i < args.length - 1; i += 2) { + const name = args[i]; + + if (typeof name !== 'string') { + return context.error(`Expected string, but found ${typeof name} instead.`, i); + } + + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error(`Variable names must contain only alphanumeric characters or '_'.`, i); + } + + const value = context.parse(args[i + 1], i + 1); + if (!value) return null; + + bindings.push([name, value]); + } + + const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) return null; + + return new Let(bindings, result); + } + + outputDefined() { + return this.result.outputDefined(); + } + + serialize() { + const serialized = ["let"]; + for (const [name, expr] of this.bindings) { + serialized.push(name, expr.serialize()); + } + serialized.push(this.result.serialize()); + return serialized; + } +} + +export default Let; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/literal.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/literal.js new file mode 100644 index 0000000000000000000000000000000000000000..cdb45dd7fdbf236529ab45f5123ddca11dcbd9c1 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/literal.js @@ -0,0 +1,77 @@ +// @flow + +import assert from 'assert'; +import {isValue, typeOf, Color} from '../values'; +import Formatted from '../types/formatted'; + +import type {Type} from '../types'; +import type {Value} from '../values'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; + +class Literal implements Expression { + type: Type; + value: Value; + + constructor(type: Type, value: Value) { + this.type = type; + this.value = value; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2) + return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`); + + if (!isValue(args[1])) + return context.error(`invalid value`); + + const value = (args[1]: any); + let type = typeOf(value); + + // special case: infer the item type if possible for zero-length arrays + const expected = context.expectedType; + if ( + type.kind === 'array' && + type.N === 0 && + expected && + expected.kind === 'array' && + (typeof expected.N !== 'number' || expected.N === 0) + ) { + type = expected; + } + + return new Literal(type, value); + } + + evaluate() { + return this.value; + } + + eachChild() {} + + outputDefined() { + return true; + } + + serialize(): Array { + if (this.type.kind === 'array' || this.type.kind === 'object') { + return ["literal", this.value]; + } else if (this.value instanceof Color) { + // Constant-folding can generate Literal expressions that you + // couldn't actually generate with a "literal" expression, + // so we have to implement an equivalent serialization here + return ["rgba"].concat(this.value.toArray()); + } else if (this.value instanceof Formatted) { + // Same as Color + return this.value.serialize(); + } else { + assert(this.value === null || + typeof this.value === 'string' || + typeof this.value === 'number' || + typeof this.value === 'boolean'); + return (this.value: any); + } + } +} + +export default Literal; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/match.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/match.js new file mode 100644 index 0000000000000000000000000000000000000000..ec4d1c30fae61a4ed47ba2b6023d6de11a34bbd3 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/match.js @@ -0,0 +1,158 @@ +// @flow + +import assert from 'assert'; + +import {typeOf} from '../values'; +import {ValueType, type Type} from '../types'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; + +// Map input label values to output expression index +type Cases = {[number | string]: number}; + +class Match implements Expression { + type: Type; + inputType: Type; + + input: Expression; + cases: Cases; + outputs: Array; + otherwise: Expression; + + constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array, otherwise: Expression) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 5) + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 1) + return context.error(`Expected an even number of arguments.`); + + let inputType; + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const cases = {}; + const outputs = []; + for (let i = 2; i < args.length - 1; i += 2) { + let labels = args[i]; + const value = args[i + 1]; + + if (!Array.isArray(labels)) { + labels = [labels]; + } + + const labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + + for (const label of labels) { + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error(`Branch labels must be numbers or strings.`); + } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`); + + } else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error(`Numeric branch labels must be integer values.`); + + } else if (!inputType) { + inputType = typeOf(label); + } else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + + cases[String(label)] = outputs.length; + } + + const result = context.parse(value, i, outputType); + if (!result) return null; + outputType = outputType || result.type; + outputs.push(result); + } + + const input = context.parse(args[1], 1, ValueType); + if (!input) return null; + + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) return null; + + assert(inputType && outputType); + + if (input.type.kind !== 'value' && context.concat(1).checkSubtype((inputType: any), input.type)) { + return null; + } + + return new Match((inputType: any), (outputType: any), input, cases, outputs, otherwise); + } + + evaluate(ctx: EvaluationContext) { + const input = (this.input.evaluate(ctx): any); + const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise; + return output.evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); + } + + outputDefined(): boolean { + return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined(); + } + + serialize(): Array { + const serialized = ["match", this.input.serialize()]; + + // Sort so serialization has an arbitrary defined order, even though + // branch order doesn't affect evaluation + const sortedLabels = Object.keys(this.cases).sort(); + + // Group branches by unique match expression to support condensed + // serializations of the form [case1, case2, ...] -> matchExpression + const groupedByOutput: Array<[number, Array]> = []; + const outputLookup: {[index: number]: number} = {}; // lookup index into groupedByOutput for a given output expression + for (const label of sortedLabels) { + const outputIndex = outputLookup[this.cases[label]]; + if (outputIndex === undefined) { + // First time seeing this output, add it to the end of the grouped list + outputLookup[this.cases[label]] = groupedByOutput.length; + groupedByOutput.push([this.cases[label], [label]]); + } else { + // We've seen this expression before, add the label to that output's group + groupedByOutput[outputIndex][1].push(label); + } + } + + const coerceLabel = (label) => this.inputType.kind === 'number' ? Number(label) : label; + + for (const [outputIndex, labels] of groupedByOutput) { + if (labels.length === 1) { + // Only a single label matches this output expression + serialized.push(coerceLabel(labels[0])); + } else { + // Array of literal labels pointing to this output expression + serialized.push(labels.map(coerceLabel)); + } + serialized.push(this.outputs[outputIndex].serialize()); + } + serialized.push(this.otherwise.serialize()); + return serialized; + } +} + +export default Match; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/number_format.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/number_format.js new file mode 100644 index 0000000000000000000000000000000000000000..754503fb1979c4c32348fbcb2de61885f2020d3c --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/number_format.js @@ -0,0 +1,142 @@ +// @flow + +import {StringType, NumberType} from '../types'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +declare var Intl: { + NumberFormat: Class +}; + +declare class Intl$NumberFormat { + constructor ( + locales?: string | string[], + options?: NumberFormatOptions + ): Intl$NumberFormat; + + static ( + locales?: string | string[], + options?: NumberFormatOptions + ): Intl$NumberFormat; + + format(a: number): string; + + resolvedOptions(): any; +} + +type NumberFormatOptions = { + style?: 'decimal' | 'currency' | 'percent'; + currency?: null | string; + minimumFractionDigits?: null | string; + maximumFractionDigits?: null | string; +}; + +export default class NumberFormat implements Expression { + type: Type; + number: Expression; + locale: Expression | null; // BCP 47 language tag + currency: Expression | null; // ISO 4217 currency code, required if style=currency + minFractionDigits: Expression | null; // Default 0 + maxFractionDigits: Expression | null; // Default 3 + + constructor(number: Expression, + locale: Expression | null, + currency: Expression | null, + minFractionDigits: Expression | null, + maxFractionDigits: Expression | null) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 3) + return context.error(`Expected two arguments.`); + + const number = context.parse(args[1], 1, NumberType); + if (!number) return null; + + const options = (args[2]: any); + if (typeof options !== "object" || Array.isArray(options)) + return context.error(`NumberFormat options argument must be an object.`); + + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) return null; + } + + let currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) return null; + } + + let minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) return null; + } + + let maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) return null; + } + + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); + } + + evaluate(ctx: EvaluationContext) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], + { + style: this.currency ? "currency" : "decimal", + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined, + }).format(this.number.evaluate(ctx)); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } + } + + outputDefined() { + return false; + } + + serialize() { + const options = {}; + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + if (this.currency) { + options['currency'] = this.currency.serialize(); + } + if (this.minFractionDigits) { + options['min-fraction-digits'] = this.minFractionDigits.serialize(); + } + if (this.maxFractionDigits) { + options['max-fraction-digits'] = this.maxFractionDigits.serialize(); + } + return ["number-format", this.number.serialize(), options]; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/slice.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/slice.js new file mode 100644 index 0000000000000000000000000000000000000000..09a47c10e9a19f708c144e8fd62d95ddeeb47bc3 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/slice.js @@ -0,0 +1,86 @@ +// @flow + +import {ValueType, NumberType, StringType, array, toString, isValidType, isValidNativeType} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Slice implements Expression { + type: Type; + input: Expression; + beginIndex: Expression; + endIndex: ?Expression; + + constructor(type: Type, input: Expression, beginIndex: Expression, endIndex?: Expression) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; + + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + + const input = context.parse(args[1], 1, ValueType); + const beginIndex = context.parse(args[2], 2, NumberType); + + if (!input || !beginIndex) return null; + + if (!isValidType(input.type, [array(ValueType), StringType, ValueType])) { + return context.error(`Expected first argument to be of type array or string, but found ${toString(input.type)} instead`); + } + + if (args.length === 4) { + const endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) return null; + return new Slice(input.type, input, beginIndex, endIndex); + } else { + return new Slice(input.type, input, beginIndex); + } + } + + evaluate(ctx: EvaluationContext) { + const input = (this.input.evaluate(ctx): any); + const beginIndex = (this.beginIndex.evaluate(ctx): number); + + if (!isValidNativeType(input, ['string', 'array'])) { + throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString(typeOf(input))} instead.`); + } + + if (this.endIndex) { + const endIndex = (this.endIndex.evaluate(ctx): number); + return input.slice(beginIndex, endIndex); + } + + return input.slice(beginIndex); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } + } + + outputDefined() { + return false; + } + + serialize() { + if (this.endIndex != null && this.endIndex !== undefined) { + const endIndex = this.endIndex.serialize(); + return ["slice", this.input.serialize(), this.beginIndex.serialize(), endIndex]; + } + return ["slice", this.input.serialize(), this.beginIndex.serialize()]; + } +} + +export default Slice; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/step.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/step.js new file mode 100644 index 0000000000000000000000000000000000000000..3e2058290b54ca6bb11198fcd329d84e17c5eba4 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/step.js @@ -0,0 +1,120 @@ +// @flow + +import {NumberType} from '../types'; + +import {findStopLessThanOrEqualTo} from '../stops'; + +import type {Stops} from '../stops'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Step implements Expression { + type: Type; + + input: Expression; + labels: Array; + outputs: Array; + + constructor(type: Type, input: Expression, stops: Stops) { + this.type = type; + this.input = input; + + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + + if ((args.length - 1) % 2 !== 0) { + return context.error(`Expected an even number of arguments.`); + } + + const input = context.parse(args[1], 1, NumberType); + if (!input) return null; + + const stops: Stops = []; + + let outputType: Type = (null: any); + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + + for (let i = 1; i < args.length; i += 2) { + const label = i === 1 ? -Infinity : args[i]; + const value = args[i + 1]; + + const labelKey = i; + const valueKey = i + 1; + + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + + return new Step(outputType, input, stops); + } + + evaluate(ctx: EvaluationContext) { + const labels = this.labels; + const outputs = this.outputs; + + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + + const value = ((this.input.evaluate(ctx): any): number); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + + const index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + + outputDefined(): boolean { + return this.outputs.every(out => out.outputDefined()); + } + + serialize() { + const serialized = ["step", this.input.serialize()]; + for (let i = 0; i < this.labels.length; i++) { + if (i > 0) { + serialized.push(this.labels[i]); + } + serialized.push(this.outputs[i].serialize()); + } + return serialized; + } +} + +export default Step; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/var.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/var.js new file mode 100644 index 0000000000000000000000000000000000000000..aa97e6cc2e43fedfe5769591dbabee010042c6fd --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/var.js @@ -0,0 +1,46 @@ +// @flow + +import type {Type} from '../types'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; + +class Var implements Expression { + type: Type; + name: string; + boundExpression: Expression; + + constructor(name: string, boundExpression: Expression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2 || typeof args[1] !== 'string') + return context.error(`'var' expression requires exactly one string literal argument.`); + + const name = args[1]; + if (!context.scope.has(name)) { + return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1); + } + + return new Var(name, context.scope.get(name)); + } + + evaluate(ctx: EvaluationContext) { + return this.boundExpression.evaluate(ctx); + } + + eachChild() {} + + outputDefined() { + return false; + } + + serialize() { + return ["var", this.name]; + } +} + +export default Var; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/within.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/within.js new file mode 100644 index 0000000000000000000000000000000000000000..67d60beec45f36ccbc34df80f35fcdf849b10882 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/definitions/within.js @@ -0,0 +1,342 @@ +// @flow + +import {isValue} from '../values'; +import type {Type} from '../types'; +import {BooleanType} from '../types'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {GeoJSON, GeoJSONPolygon, GeoJSONMultiPolygon} from '@mapbox/geojson-types'; +import Point from '@mapbox/point-geometry'; +import type {CanonicalTileID} from '../../../source/tile_id'; + +type GeoJSONPolygons =| GeoJSONPolygon | GeoJSONMultiPolygon; + +// minX, minY, maxX, maxY +type BBox = [number, number, number, number]; +const EXTENT = 8192; + +function updateBBox(bbox: BBox, coord: Point) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); +} + +function mercatorXfromLng(lng: number) { + return (180 + lng) / 360; +} + +function mercatorYfromLat(lat: number) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} + +function boxWithinBox(bbox1: BBox, bbox2: BBox) { + if (bbox1[0] <= bbox2[0]) return false; + if (bbox1[2] >= bbox2[2]) return false; + if (bbox1[1] <= bbox2[1]) return false; + if (bbox1[3] >= bbox2[3]) return false; + return true; +} + +function getTileCoordinates(p, canonical: CanonicalTileID) { + const x = mercatorXfromLng(p[0]); + const y = mercatorYfromLat(p[1]); + const tilesAtZoom = Math.pow(2, canonical.z); + return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)]; +} + +function onBoundary(p, p1, p2) { + const x1 = p[0] - p1[0]; + const y1 = p[1] - p1[1]; + const x2 = p[0] - p2[0]; + const y2 = p[1] - p2[1]; + return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0); +} + +function rayIntersect(p, p1, p2) { + return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]); +} + +// ray casting algorithm for detecting if point is in polygon +function pointWithinPolygon(point, rings) { + let inside = false; + for (let i = 0, len = rings.length; i < len; i++) { + const ring = rings[i]; + for (let j = 0, len2 = ring.length; j < len2 - 1; j++) { + if (onBoundary(point, ring[j], ring[j + 1])) return false; + if (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside; + } + } + return inside; +} + +function pointWithinPolygons(point, polygons) { + for (let i = 0; i < polygons.length; i++) { + if (pointWithinPolygon(point, polygons[i])) return true; + } + return false; +} + +function perp(v1, v2) { + return (v1[0] * v2[1] - v1[1] * v2[0]); +} + +// check if p1 and p2 are in different sides of line segment q1->q2 +function twoSided(p1, p2, q1, q2) { + // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3) + const x1 = p1[0] - q1[0]; + const y1 = p1[1] - q1[1]; + const x2 = p2[0] - q1[0]; + const y2 = p2[1] - q1[1]; + const x3 = q2[0] - q1[0]; + const y3 = q2[1] - q1[1]; + const det1 = (x1 * y3 - x3 * y1); + const det2 = (x2 * y3 - x3 * y2); + if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) return true; + return false; +} +// a, b are end points for line segment1, c and d are end points for line segment2 +function lineIntersectLine(a, b, c, d) { + // check if two segments are parallel or not + // precondition is end point a, b is inside polygon, if line a->b is + // parallel to polygon edge c->d, then a->b won't intersect with c->d + const vectorP = [b[0] - a[0], b[1] - a[1]]; + const vectorQ = [d[0] - c[0], d[1] - c[1]]; + if (perp(vectorQ, vectorP) === 0) return false; + + // If lines are intersecting with each other, the relative location should be: + // a and b lie in different sides of segment c->d + // c and d lie in different sides of segment a->b + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true; + return false; +} + +function lineIntersectPolygon(p1, p2, polygon) { + for (const ring of polygon) { + // loop through every edge of the ring + for (let j = 0; j < ring.length - 1; ++j) { + if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; +} + +function lineStringWithinPolygon(line, polygon) { + // First, check if geometry points of line segments are all inside polygon + for (let i = 0; i < line.length; ++i) { + if (!pointWithinPolygon(line[i], polygon)) { + return false; + } + } + + // Second, check if there is line segment intersecting polygon edge + for (let i = 0; i < line.length - 1; ++i) { + if (lineIntersectPolygon(line[i], line[i + 1], polygon)) { + return false; + } + } + return true; +} + +function lineStringWithinPolygons(line, polygons) { + for (let i = 0; i < polygons.length; i++) { + if (lineStringWithinPolygon(line, polygons[i])) return true; + } + return false; +} + +function getTilePolygon(coordinates, bbox, canonical) { + const polygon = []; + for (let i = 0; i < coordinates.length; i++) { + const ring = []; + for (let j = 0; j < coordinates[i].length; j++) { + const coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; +} + +function getTilePolygons(coordinates, bbox, canonical) { + const polygons = []; + for (let i = 0; i < coordinates.length; i++) { + const polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; +} + +function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + const halfWorldSize = worldSize * 0.5; + let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0; + if (shift === 0) { + shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); +} + +function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; +} + +function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT; + const shifts = [canonical.x * EXTENT, canonical.y * EXTENT]; + const tilePoints = []; + for (const points of geometry) { + for (const point of points) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; +} + +function getTileLines(geometry, lineBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT; + const shifts = [canonical.x * EXTENT, canonical.y * EXTENT]; + const tileLines = []; + for (const line of geometry) { + const tileLine = []; + for (const point of line) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (const line of tileLines) { + for (const p of line) { + updatePoint(p, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; +} + +function pointsWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) { + const pointBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + + const canonical = ctx.canonicalID(); + + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) return false; + + for (const point of tilePoints) { + if (!pointWithinPolygon(point, tilePolygon)) return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) return false; + + for (const point of tilePoints) { + if (!pointWithinPolygons(point, tilePolygons)) return false; + } + } + + return true; +} + +function linesWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) { + const lineBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + + const canonical = ctx.canonicalID(); + + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) return false; + + for (const line of tileLines) { + if (!lineStringWithinPolygon(line, tilePolygon)) return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) return false; + + for (const line of tileLines) { + if (!lineStringWithinPolygons(line, tilePolygons)) return false; + } + } + return true; +} + +class Within implements Expression { + type: Type; + geojson: GeoJSON + geometries: GeoJSONPolygons; + + constructor(geojson: GeoJSON, geometries: GeoJSONPolygons) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2) + return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = (args[1]: Object); + if (geojson.type === 'FeatureCollection') { + for (let i = 0; i < geojson.features.length; ++i) { + const type = geojson.features[i].geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.features[i].geometry); + } + } + } else if (geojson.type === 'Feature') { + const type = geojson.geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error(`'within' expression requires valid geojson object that contains polygon geometry type.`); + } + + evaluate(ctx: EvaluationContext) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; + } + + eachChild() {} + + outputDefined(): boolean { + return true; + } + + serialize(): Array { + return ["within", this.geojson]; + } + +} + +export default Within; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/evaluation_context.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/evaluation_context.js new file mode 100644 index 0000000000000000000000000000000000000000..1e7a6d587e1d47faedc101498fc9b4380705c578 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/evaluation_context.js @@ -0,0 +1,59 @@ +// @flow + +import {Color} from './values'; +import type {FormattedSection} from './types/formatted'; +import type {GlobalProperties, Feature, FeatureState} from './index'; +import type {CanonicalTileID} from '../../source/tile_id'; + +const geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon']; + +class EvaluationContext { + globals: GlobalProperties; + feature: ?Feature; + featureState: ?FeatureState; + formattedSection: ?FormattedSection; + availableImages: ?Array; + canonical: ?CanonicalTileID; + + _parseColorCache: {[_: string]: ?Color}; + + constructor() { + this.globals = (null: any); + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; + } + + id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; + } + + geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; + } + + geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; + } + + canonicalID() { + return this.canonical; + } + + properties() { + return this.feature && this.feature.properties || {}; + } + + parseColor(input: string): ?Color { + let cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; + } +} + +export default EvaluationContext; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/expression.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/expression.js new file mode 100644 index 0000000000000000000000000000000000000000..3404686ede68b4c921aec29da08c5549367912a3 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/expression.js @@ -0,0 +1,27 @@ +// @flow + +import type {Type} from './types'; +import type ParsingContext from './parsing_context'; +import type EvaluationContext from './evaluation_context'; + +type SerializedExpression = Array | string | number | boolean | null; + +export interface Expression { + +type: Type; + + evaluate(ctx: EvaluationContext): any; + + eachChild(fn: Expression => void): void; + + /** + * Statically analyze the expression, attempting to enumerate possible outputs. Returns + * false if the complete set of outputs is statically undecidable, otherwise true. + */ + outputDefined(): boolean; + + serialize(): SerializedExpression; +} + +export type ExpressionParser = (args: $ReadOnlyArray, context: ParsingContext) => ?Expression; +export type ExpressionRegistration = Class & { +parse: ExpressionParser }; +export type ExpressionRegistry = {[_: string]: ExpressionRegistration}; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/index.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/index.js new file mode 100644 index 0000000000000000000000000000000000000000..736ad8fdc215aa9be44049231389e0b6acd48d67 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/index.js @@ -0,0 +1,392 @@ +// @flow + +import assert from 'assert'; + +import extend from '../util/extend'; +import ParsingError from './parsing_error'; +import ParsingContext from './parsing_context'; +import EvaluationContext from './evaluation_context'; +import CompoundExpression from './compound_expression'; +import Step from './definitions/step'; +import Interpolate from './definitions/interpolate'; +import Coalesce from './definitions/coalesce'; +import Let from './definitions/let'; +import definitions from './definitions'; +import * as isConstant from './is_constant'; +import RuntimeError from './runtime_error'; +import {success, error} from '../util/result'; +import {supportsPropertyExpression, supportsZoomExpression, supportsInterpolation} from '../util/properties'; + +import type {Type, EvaluationKind} from './types'; +import type {Value} from './values'; +import type {Expression} from './expression'; +import type {StylePropertySpecification} from '../style-spec'; +import type {Result} from '../util/result'; +import type {InterpolationType} from './definitions/interpolate'; +import type {PropertyValueSpecification} from '../types'; +import type {FormattedSection} from './types/formatted'; +import type Point from '@mapbox/point-geometry'; +import type {CanonicalTileID} from '../../source/tile_id'; + +export type Feature = { + +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon', + +id?: any, + +properties: {[_: string]: any}, + +patterns?: {[_: string]: {"min": string, "mid": string, "max": string}}, + +geometry?: Array> +}; + +export type FeatureState = {[_: string]: any}; + +export type GlobalProperties = $ReadOnly<{ + zoom: number, + heatmapDensity?: number, + lineProgress?: number, + isSupportedScript?: (_: string) => boolean, + accumulated?: Value +}>; + +export class StyleExpression { + expression: Expression; + + _evaluator: EvaluationContext; + _defaultValue: Value; + _warningHistory: {[key: string]: boolean}; + _enumValues: ?{[_: string]: any}; + + constructor(expression: Expression, propertySpec: ?StylePropertySpecification) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; + } + + evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + + return this.expression.evaluate(this._evaluator); + } + + evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + + try { + const val = this.expression.evaluate(this._evaluator); + // eslint-disable-next-line no-self-compare + if (val === null || val === undefined || (typeof val === 'number' && val !== val)) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`); + } + return val; + } catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } + } +} + +export function isExpression(expression: mixed) { + return Array.isArray(expression) && expression.length > 0 && + typeof expression[0] === 'string' && expression[0] in definitions; +} + +/** + * Parse and typecheck the given style spec JSON expression. If + * options.defaultValue is provided, then the resulting StyleExpression's + * `evaluate()` method will handle errors by logging a warning (once per + * message) and returning the default value. Otherwise, it will throw + * evaluation errors. + * + * @private + */ +export function createExpression(expression: mixed, propertySpec: ?StylePropertySpecification): Result> { + const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined); + + // For string-valued properties, coerce to string at the top level rather than asserting. + const parsed = parser.parse(expression, undefined, undefined, undefined, + propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined); + + if (!parsed) { + assert(parser.errors.length > 0); + return error(parser.errors); + } + + return success(new StyleExpression(parsed, propertySpec)); +} + +export class ZoomConstantExpression { + kind: Kind; + isStateDependent: boolean; + _styleExpression: StyleExpression; + + constructor(kind: Kind, expression: StyleExpression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== ('constant': EvaluationKind) && !isConstant.isStateConstant(expression.expression); + } + + evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + + evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } +} + +export class ZoomDependentExpression { + kind: Kind; + zoomStops: Array; + isStateDependent: boolean; + + _styleExpression: StyleExpression; + interpolationType: ?InterpolationType; + + constructor(kind: Kind, expression: StyleExpression, zoomStops: Array, interpolationType?: InterpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== ('camera': EvaluationKind) && !isConstant.isStateConstant(expression.expression); + this.interpolationType = interpolationType; + } + + evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + + evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } + + interpolationFactor(input: number, lower: number, upper: number): number { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } else { + return 0; + } + } +} + +export type ConstantExpression = { + kind: 'constant', + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any, +} + +export type SourceExpression = { + kind: 'source', + isStateDependent: boolean, + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any, +}; + +export type CameraExpression = { + kind: 'camera', + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any, + +interpolationFactor: (input: number, lower: number, upper: number) => number, + zoomStops: Array, + interpolationType: ?InterpolationType +}; + +export type CompositeExpression = { + kind: 'composite', + isStateDependent: boolean, + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any, + +interpolationFactor: (input: number, lower: number, upper: number) => number, + zoomStops: Array, + interpolationType: ?InterpolationType +}; + +export type StylePropertyExpression = + | ConstantExpression + | SourceExpression + | CameraExpression + | CompositeExpression; + +export function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result> { + expression = createExpression(expression, propertySpec); + if (expression.result === 'error') { + return expression; + } + + const parsed = expression.value.expression; + + const isFeatureConstant = isConstant.isFeatureConstant(parsed); + if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) { + return error([new ParsingError('', 'data expressions not supported')]); + } + + const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ParsingError('', 'zoom expressions not supported')]); + } + + const zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } else if (zoomCurve instanceof ParsingError) { + return error([zoomCurve]); + } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + + if (!zoomCurve) { + return success(isFeatureConstant ? + (new ZoomConstantExpression('constant', expression.value): ConstantExpression) : + (new ZoomConstantExpression('source', expression.value): SourceExpression)); + } + + const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + + return success(isFeatureConstant ? + (new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType): CameraExpression) : + (new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType): CompositeExpression)); +} + +import {isFunction, createFunction} from '../function'; +import {Color} from './values'; + +// serialization wrapper for old-style stop functions normalized to the +// expression interface +export class StylePropertyFunction { + _parameters: PropertyValueSpecification; + _specification: StylePropertySpecification; + + kind: EvaluationKind; + evaluate: (globals: GlobalProperties, feature?: Feature) => any; + interpolationFactor: ?(input: number, lower: number, upper: number) => number; + zoomStops: ?Array; + + constructor(parameters: PropertyValueSpecification, specification: StylePropertySpecification) { + this._parameters = parameters; + this._specification = specification; + extend(this, createFunction(this._parameters, this._specification)); + } + + static deserialize(serialized: {_parameters: PropertyValueSpecification, _specification: StylePropertySpecification}) { + return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction); + } + + static serialize(input: StylePropertyFunction) { + return { + _parameters: input._parameters, + _specification: input._specification + }; + } +} + +export function normalizePropertyExpression(value: PropertyValueSpecification, specification: StylePropertySpecification): StylePropertyExpression { + if (isFunction(value)) { + return (new StylePropertyFunction(value, specification): any); + + } else if (isExpression(value)) { + const expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + // this should have been caught in validation + throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + return expression.value; + + } else { + let constant: any = value; + if (typeof value === 'string' && specification.type === 'color') { + constant = Color.parse(value); + } + return { + kind: 'constant', + evaluate: () => constant + }; + } +} + +// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate" +// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or +// "coalesce" expressions. +function findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null { + let result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + + } else if (expression instanceof Coalesce) { + for (const arg of expression.args) { + result = findZoomCurve(arg); + if (result) { + break; + } + } + + } else if ((expression instanceof Step || expression instanceof Interpolate) && + expression.input instanceof CompoundExpression && + expression.input.name === 'zoom') { + + result = expression; + } + + if (result instanceof ParsingError) { + return result; + } + + expression.eachChild((child) => { + const childResult = findZoomCurve(child); + if (childResult instanceof ParsingError) { + result = childResult; + } else if (!result && childResult) { + result = new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } else if (result && childResult && result !== childResult) { + result = new ParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + + return result; +} + +import {ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, ResolvedImageType, array} from './types'; + +function getExpectedType(spec: StylePropertySpecification): Type { + const types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + resolvedImage: ResolvedImageType + }; + + if (spec.type === 'array') { + return array(types[spec.value] || ValueType, spec.length); + } + + return types[spec.type]; +} + +function getDefaultValue(spec: StylePropertySpecification): Value { + if (spec.type === 'color' && isFunction(spec.default)) { + // Special case for heatmap-color: it uses the 'default:' to define a + // default color ramp, but createExpression expects a simple value to fall + // back to in case of runtime errors + return new Color(0, 0, 0, 0); + } else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } else if (spec.default === undefined) { + return null; + } else { + return spec.default; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/is_constant.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/is_constant.js new file mode 100644 index 0000000000000000000000000000000000000000..bb997e899a582b6bfe8e959046c5d9e80b550e6f --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/is_constant.js @@ -0,0 +1,59 @@ +// @flow + +import CompoundExpression from './compound_expression'; +import Within from './definitions/within'; +import type {Expression} from './expression.js'; + +function isFeatureConstant(e: Expression) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } else if (e.name === 'feature-state') { + return false; + } else if (e.name === 'has' && e.args.length === 1) { + return false; + } else if ( + e.name === 'properties' || + e.name === 'geometry-type' || + e.name === 'id' + ) { + return false; + } else if (/^filter-/.test(e.name)) { + return false; + } + } + + if (e instanceof Within) { + return false; + } + + let result = true; + e.eachChild(arg => { + if (result && !isFeatureConstant(arg)) { result = false; } + }); + return result; +} + +function isStateConstant(e: Expression) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + let result = true; + e.eachChild(arg => { + if (result && !isStateConstant(arg)) { result = false; } + }); + return result; +} + +function isGlobalPropertyConstant(e: Expression, properties: Array) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { return false; } + let result = true; + e.eachChild((arg) => { + if (result && !isGlobalPropertyConstant(arg, properties)) { result = false; } + }); + return result; +} + +export {isFeatureConstant, isGlobalPropertyConstant, isStateConstant}; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/parsing_context.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/parsing_context.js new file mode 100644 index 0000000000000000000000000000000000000000..7cf8ce94e8c63454db74ea0940a732096ad4fbb2 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/parsing_context.js @@ -0,0 +1,233 @@ +// @flow + +import Scope from './scope'; +import {checkSubtype} from './types'; +import ParsingError from './parsing_error'; +import Literal from './definitions/literal'; +import Assertion from './definitions/assertion'; +import Coercion from './definitions/coercion'; +import EvaluationContext from './evaluation_context'; +import CompoundExpression from './compound_expression'; +import CollatorExpression from './definitions/collator'; +import Within from './definitions/within'; +import {isGlobalPropertyConstant, isFeatureConstant} from './is_constant'; +import Var from './definitions/var'; + +import type {Expression, ExpressionRegistry} from './expression'; +import type {Type} from './types'; + +/** + * State associated parsing at a given point in an expression tree. + * @private + */ +class ParsingContext { + registry: ExpressionRegistry; + path: Array; + key: string; + scope: Scope; + errors: Array; + + // The expected type of this expression. Provided only to allow Expression + // implementations to infer argument types: Expression#parse() need not + // check that the output type of the parsed expression matches + // `expectedType`. + expectedType: ?Type; + + constructor( + registry: ExpressionRegistry, + path: Array = [], + expectedType: ?Type, + scope: Scope = new Scope(), + errors: Array = [] + ) { + this.registry = registry; + this.path = path; + this.key = path.map(part => `[${part}]`).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; + } + + /** + * @param expr the JSON expression to parse + * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed + * @param options + * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation. + * @private + */ + parse( + expr: mixed, + index?: number, + expectedType?: ?Type, + bindings?: Array<[string, Expression]>, + options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'} = {} + ): ?Expression { + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); + } + + _parse(expr: mixed, options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'}): ?Expression { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = ['literal', expr]; + } + + function annotate(parsed, type, typeAnnotation: 'assert' | 'coerce' | 'omit') { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } else { + return parsed; + } + } + + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error(`Expected an array with at least one element. If you wanted a literal array, use ["literal", []].`); + } + + const op = expr[0]; + if (typeof op !== 'string') { + this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0); + return null; + } + + const Expr = this.registry[op]; + if (Expr) { + let parsed = Expr.parse(expr, this); + if (!parsed) return null; + + if (this.expectedType) { + const expected = this.expectedType; + const actual = parsed.type; + + // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion. + // When we expect a color or formatted string, but have a string or value, wrap it in a coercion. + // Otherwise, we do static type-checking. + // + // These behaviors are overridable for: + // * The "coalesce" operator, which needs to omit type annotations. + // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion. + // + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } else if (this.checkSubtype(expected, actual)) { + return null; + } + } + + // If an expression's arguments are all literals, we can evaluate + // it immediately and replace it with a literal value in the + // parsed/compiled result. Expressions that expect an image should + // not be resolved here so we can later get the available images. + if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && isConstant(parsed)) { + const ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } catch (e) { + this.error(e.message); + return null; + } + } + + return parsed; + } + + return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } else if (typeof expr === 'undefined') { + return this.error(`'undefined' value invalid. Use null instead.`); + } else if (typeof expr === 'object') { + return this.error(`Bare objects invalid. Use ["literal", {...}] instead.`); + } else { + return this.error(`Expected an array, but found ${typeof expr} instead.`); + } + } + + /** + * Returns a copy of this context suitable for parsing the subexpression at + * index `index`, optionally appending to 'let' binding map. + * + * Note that `errors` property, intended for collecting errors while + * parsing, is copied by reference rather than cloned. + * @private + */ + concat(index: number, expectedType?: ?Type, bindings?: Array<[string, Expression]>) { + const path = typeof index === 'number' ? this.path.concat(index) : this.path; + const scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext( + this.registry, + path, + expectedType || null, + scope, + this.errors + ); + } + + /** + * Push a parsing (or type checking) error into the `this.errors` + * @param error The message + * @param keys Optionally specify the source of the error at a child + * of the current expression at `this.key`. + * @private + */ + error(error: string, ...keys: Array) { + const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`; + this.errors.push(new ParsingError(key, error)); + } + + /** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message and also pushes it to `this.errors`. + */ + checkSubtype(expected: Type, t: Type): ?string { + const error = checkSubtype(expected, t); + if (error) this.error(error); + return error; + } +} + +export default ParsingContext; + +function isConstant(expression: Expression) { + if (expression instanceof Var) { + return isConstant(expression.boundExpression); + } else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } else if (expression instanceof CollatorExpression) { + // Although the results of a Collator expression with fixed arguments + // generally shouldn't change between executions, we can't serialize them + // as constant expressions because results change based on environment. + return false; + } else if (expression instanceof Within) { + return false; + } + + const isTypeAnnotation = expression instanceof Coercion || + expression instanceof Assertion; + + let childrenConstant = true; + expression.eachChild(child => { + // We can _almost_ assume that if `expressions` children are constant, + // they would already have been evaluated to Literal values when they + // were parsed. Type annotations are the exception, because they might + // have been inferred and added after a child was parsed. + + // So we recurse into isConstant() for the children of type annotations, + // but otherwise simply check whether they are Literals. + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isConstant(child); + } else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + + return isFeatureConstant(expression) && + isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/parsing_error.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/parsing_error.js new file mode 100644 index 0000000000000000000000000000000000000000..8f676e81313dc39341fd55de3b70ae8042420cea --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/parsing_error.js @@ -0,0 +1,13 @@ +// @flow + +class ParsingError extends Error { + key: string; + message: string; + constructor(key: string, message: string) { + super(message); + this.message = message; + this.key = key; + } +} + +export default ParsingError; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/runtime_error.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/runtime_error.js new file mode 100644 index 0000000000000000000000000000000000000000..6c7c1144851e1ea965021b2d287da4a861873789 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/runtime_error.js @@ -0,0 +1,17 @@ +// @flow + +class RuntimeError { + name: string; + message: string; + + constructor(message: string) { + this.name = 'ExpressionEvaluationError'; + this.message = message; + } + + toJSON() { + return this.message; + } +} + +export default RuntimeError; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/scope.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/scope.js new file mode 100644 index 0000000000000000000000000000000000000000..b47e7cda5bd927904ec68d6554ebcd4d2b494ddd --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/scope.js @@ -0,0 +1,36 @@ +// @flow + +import type {Expression} from './expression'; + +/** + * Tracks `let` bindings during expression parsing. + * @private + */ +class Scope { + parent: ?Scope; + bindings: {[_: string]: Expression}; + constructor(parent?: Scope, bindings: Array<[string, Expression]> = []) { + this.parent = parent; + this.bindings = {}; + for (const [name, expression] of bindings) { + this.bindings[name] = expression; + } + } + + concat(bindings: Array<[string, Expression]>) { + return new Scope(this, bindings); + } + + get(name: string): Expression { + if (this.bindings[name]) { return this.bindings[name]; } + if (this.parent) { return this.parent.get(name); } + throw new Error(`${name} not found in scope.`); + } + + has(name: string): boolean { + if (this.bindings[name]) return true; + return this.parent ? this.parent.has(name) : false; + } +} + +export default Scope; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/stops.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/stops.js new file mode 100644 index 0000000000000000000000000000000000000000..770ab4acfbaf8f98de3b8feb868892c6027953a5 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/stops.js @@ -0,0 +1,39 @@ +// @flow + +import RuntimeError from './runtime_error'; + +import type {Expression} from './expression'; + +export type Stops = Array<[number, Expression]>; + +/** + * Returns the index of the last stop <= input, or 0 if it doesn't exist. + * @private + */ +export function findStopLessThanOrEqualTo(stops: Array, input: number) { + const lastIndex = stops.length - 1; + let lowerIndex = 0; + let upperIndex = lastIndex; + let currentIndex = 0; + let currentValue, nextValue; + + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { // Search complete + return currentIndex; + } + + lowerIndex = currentIndex + 1; + } else if (currentValue > input) { + upperIndex = currentIndex - 1; + } else { + throw new RuntimeError('Input is not a number.'); + } + } + + return 0; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types.js new file mode 100644 index 0000000000000000000000000000000000000000..320c713de9496d087211dd488597e0c09c7f3b79 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types.js @@ -0,0 +1,126 @@ +// @flow + +export type NullTypeT = { kind: 'null' }; +export type NumberTypeT = { kind: 'number' }; +export type StringTypeT = { kind: 'string' }; +export type BooleanTypeT = { kind: 'boolean' }; +export type ColorTypeT = { kind: 'color' }; +export type ObjectTypeT = { kind: 'object' }; +export type ValueTypeT = { kind: 'value' }; +export type ErrorTypeT = { kind: 'error' }; +export type CollatorTypeT = { kind: 'collator' }; +export type FormattedTypeT = { kind: 'formatted' }; +export type ResolvedImageTypeT = { kind: 'resolvedImage' }; + +export type EvaluationKind = 'constant' | 'source' | 'camera' | 'composite'; + +export type Type = + NullTypeT | + NumberTypeT | + StringTypeT | + BooleanTypeT | + ColorTypeT | + ObjectTypeT | + ValueTypeT | + ArrayType | // eslint-disable-line no-use-before-define + ErrorTypeT | + CollatorTypeT | + FormattedTypeT | + ResolvedImageTypeT + +export type ArrayType = { + kind: 'array', + itemType: Type, + N: ?number +} + +export type NativeType = 'number' | 'string' | 'boolean' | 'null' | 'array' | 'object' + +export const NullType = {kind: 'null'}; +export const NumberType = {kind: 'number'}; +export const StringType = {kind: 'string'}; +export const BooleanType = {kind: 'boolean'}; +export const ColorType = {kind: 'color'}; +export const ObjectType = {kind: 'object'}; +export const ValueType = {kind: 'value'}; +export const ErrorType = {kind: 'error'}; +export const CollatorType = {kind: 'collator'}; +export const FormattedType = {kind: 'formatted'}; +export const ResolvedImageType = {kind: 'resolvedImage'}; + +export function array(itemType: Type, N: ?number): ArrayType { + return { + kind: 'array', + itemType, + N + }; +} + +export function toString(type: Type): string { + if (type.kind === 'array') { + const itemType = toString(type.itemType); + return typeof type.N === 'number' ? + `array<${itemType}, ${type.N}>` : + type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`; + } else { + return type.kind; + } +} + +const valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array(ValueType), + ResolvedImageType +]; + +/** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message. + * @private + */ +export function checkSubtype(expected: Type, t: Type): ?string { + if (t.kind === 'error') { + // Error is a subtype of every type + return null; + } else if (expected.kind === 'array') { + if (t.kind === 'array' && + ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) && + (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } else if (expected.kind === t.kind) { + return null; + } else if (expected.kind === 'value') { + for (const memberType of valueMemberTypes) { + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + + return `Expected ${toString(expected)} but found ${toString(t)} instead.`; +} + +export function isValidType(provided: Type, allowedTypes: Array): boolean { + return allowedTypes.some(t => t.kind === provided.kind); +} + +export function isValidNativeType(provided: any, allowedTypes: Array): boolean { + return allowedTypes.some(t => { + if (t === 'null') { + return provided === null; + } else if (t === 'array') { + return Array.isArray(provided); + } else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } else { + return t === typeof provided; + } + }); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/collator.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/collator.js new file mode 100644 index 0000000000000000000000000000000000000000..c9bcd61589f5b87b009c0c5b7c1a0ecc6c8f93e3 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/collator.js @@ -0,0 +1,61 @@ +// @flow + +// Flow type declarations for Intl cribbed from +// https://github.com/facebook/flow/issues/1270 + +declare var Intl: { + Collator: Class +}; + +declare class Intl$Collator { + constructor ( + locales?: string | string[], + options?: CollatorOptions + ): Intl$Collator; + + static ( + locales?: string | string[], + options?: CollatorOptions + ): Intl$Collator; + + compare (a: string, b: string): number; + + resolvedOptions(): any; +} + +type CollatorOptions = { + localeMatcher?: 'lookup' | 'best fit', + usage?: 'sort' | 'search', + sensitivity?: 'base' | 'accent' | 'case' | 'variant', + ignorePunctuation?: boolean, + numeric?: boolean, + caseFirst?: 'upper' | 'lower' | 'false' +} + +export default class Collator { + locale: string | null; + sensitivity: 'base' | 'accent' | 'case' | 'variant'; + collator: Intl$Collator; + + constructor(caseSensitive: boolean, diacriticSensitive: boolean, locale: string | null) { + if (caseSensitive) + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + else + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], + {sensitivity: this.sensitivity, usage: 'search'}); + } + + compare(lhs: string, rhs: string): number { + return this.collator.compare(lhs, rhs); + } + + resolvedLocale(): string { + // We create a Collator without "usage: search" because we don't want + // the search options encoded in our result (e.g. "en-u-co-search") + return new Intl.Collator(this.locale ? this.locale : []) + .resolvedOptions().locale; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/formatted.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/formatted.js new file mode 100644 index 0000000000000000000000000000000000000000..378a0a2bd5d313cdad5f28c6665691d5fe0ac2ee --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/formatted.js @@ -0,0 +1,73 @@ +// @flow +import type Color from '../../util/color'; +import type ResolvedImage from '../types/resolved_image'; + +export class FormattedSection { + text: string; + image: ResolvedImage | null; + scale: number | null; + fontStack: string | null; + textColor: Color | null; + + constructor(text: string, image: ResolvedImage | null, scale: number | null, fontStack: string | null, textColor: Color | null) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; + } +} + +export default class Formatted { + sections: Array; + + constructor(sections: Array) { + this.sections = sections; + } + + static fromString(unformatted: string): Formatted { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); + } + + isEmpty(): boolean { + if (this.sections.length === 0) return true; + return !this.sections.some(section => section.text.length !== 0 || + (section.image && section.image.name.length !== 0)); + } + + static factory(text: Formatted | string): Formatted { + if (text instanceof Formatted) { + return text; + } else { + return Formatted.fromString(text); + } + } + + toString(): string { + if (this.sections.length === 0) return ''; + return this.sections.map(section => section.text).join(''); + } + + serialize(): Array { + const serialized: Array = ["format"]; + for (const section of this.sections) { + if (section.image) { + serialized.push(["image", section.image.name]); + continue; + } + serialized.push(section.text); + const options: { [key: string]: mixed } = {}; + if (section.fontStack) { + options["text-font"] = ["literal", section.fontStack.split(',')]; + } + if (section.scale) { + options["font-scale"] = section.scale; + } + if (section.textColor) { + options["text-color"] = (["rgba"]: Array).concat(section.textColor.toArray()); + } + serialized.push(options); + } + return serialized; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/resolved_image.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/resolved_image.js new file mode 100644 index 0000000000000000000000000000000000000000..a9e92f8fedb8417b45c3a11cfaf0835f2053c215 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/types/resolved_image.js @@ -0,0 +1,29 @@ +// @flow + +export type ResolvedImageOptions = { + name: string, + available: boolean +}; + +export default class ResolvedImage { + name: string; + available: boolean; + + constructor(options: ResolvedImageOptions) { + this.name = options.name; + this.available = options.available; + } + + toString(): string { + return this.name; + } + + static fromString(name: string): ResolvedImage | null { + if (!name) return null; // treat empty values as no image + return new ResolvedImage({name, available: false}); + } + + serialize(): Array { + return ["image", this.name]; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/expression/values.js b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/values.js new file mode 100644 index 0000000000000000000000000000000000000000..6c5e5407dc97b071636d16caa9f7b9a1858d7373 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/expression/values.js @@ -0,0 +1,123 @@ +// @flow + +import assert from 'assert'; + +import Color from '../util/color'; +import Collator from './types/collator'; +import Formatted from './types/formatted'; +import ResolvedImage from './types/resolved_image'; +import {NullType, NumberType, StringType, BooleanType, ColorType, ObjectType, ValueType, CollatorType, FormattedType, ResolvedImageType, array} from './types'; + +import type {Type} from './types'; + +export function validateRGBA(r: mixed, g: mixed, b: mixed, a?: mixed): string | null { + if (!( + typeof r === 'number' && r >= 0 && r <= 255 && + typeof g === 'number' && g >= 0 && g <= 255 && + typeof b === 'number' && b >= 0 && b <= 255 + )) { + const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b]; + return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`; + } + + if (!( + typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1) + )) { + return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`; + } + + return null; +} + +export type Value = null | string | boolean | number | Color | Collator | Formatted | ResolvedImage | $ReadOnlyArray | { +[string]: Value } + +export function isValue(mixed: mixed): boolean { + if (mixed === null) { + return true; + } else if (typeof mixed === 'string') { + return true; + } else if (typeof mixed === 'boolean') { + return true; + } else if (typeof mixed === 'number') { + return true; + } else if (mixed instanceof Color) { + return true; + } else if (mixed instanceof Collator) { + return true; + } else if (mixed instanceof Formatted) { + return true; + } else if (mixed instanceof ResolvedImage) { + return true; + } else if (Array.isArray(mixed)) { + for (const item of mixed) { + if (!isValue(item)) { + return false; + } + } + return true; + } else if (typeof mixed === 'object') { + for (const key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } else { + return false; + } +} + +export function typeOf(value: Value): Type { + if (value === null) { + return NullType; + } else if (typeof value === 'string') { + return StringType; + } else if (typeof value === 'boolean') { + return BooleanType; + } else if (typeof value === 'number') { + return NumberType; + } else if (value instanceof Color) { + return ColorType; + } else if (value instanceof Collator) { + return CollatorType; + } else if (value instanceof Formatted) { + return FormattedType; + } else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } else if (Array.isArray(value)) { + const length = value.length; + let itemType: Type | typeof undefined; + + for (const item of value) { + const t = typeOf(item); + if (!itemType) { + itemType = t; + } else if (itemType === t) { + continue; + } else { + itemType = ValueType; + break; + } + } + + return array(itemType || ValueType, length); + } else { + assert(typeof value === 'object'); + return ObjectType; + } +} + +export function toString(value: Value) { + const type = typeof value; + if (value === null) { + return ''; + } else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } else if (value instanceof Color || value instanceof Formatted || value instanceof ResolvedImage) { + return value.toString(); + } else { + return JSON.stringify(value); + } +} + +export {Color, Collator}; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/README.md b/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6501c01a0f9960382ef25aefc63f9ddee15fbbb5 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/README.md @@ -0,0 +1,55 @@ +## Filter + +Filter expressions are used to target specific data in a layer. This library implements the semantics specified by the [Mapbox GL JS spec](https://www.mapbox.com/mapbox-gl-style-spec/#filter). + +### API + +`featureFilter(filter)` + +Given a filter expressed as nested arrays, return a new function +that evaluates whether a given feature (with a .properties or .tags property) +passes its test. + +#### Parameters + +| parameter | type | description | +| --------- | ----- | ---------------- | +| `filter` | Array | mapbox gl filter | + +**Returns** `Function`, filter-evaluating function + +### Usage + +``` javascript +var ff = require('@mapbox/mapbox-gl-style-spec').featureFilter; + +// will match a feature with class of street_limited, +// AND an admin_level less than or equal to 3, +// that's NOT a polygon. +var filter = [ + "all", + ["==", "class", "street_limited"], + ["<=", "admin_level", 3], + ["!=", "$type", "Polygon"] +] + +// will match a feature that has a class of +// wetland OR wetland_noveg. +// ["in", "class", "wetland", "wetland_noveg"] + +// testFilter will be a function that returns a boolean +var testFilter = ff(filter); + +// Layer feature that you're testing. Must have type +// and properties keys. +var feature = { + type: 2, + properties: { + class: "street_limited", + admin_level: 1 + } +}; + +// will return a boolean based on whether the feature matched the filter +return testFilter({zoom: 0}, feature); +``` diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/convert.js b/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/convert.js new file mode 100644 index 0000000000000000000000000000000000000000..d7d473c2c4a3bf08444d1c74f4a4316911a2be52 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/convert.js @@ -0,0 +1,208 @@ +// @flow + +import {isExpressionFilter} from './index'; + +import type {FilterSpecification} from '../types'; + +type ExpectedTypes = {[_: string]: 'string' | 'number' | 'boolean'}; + +/** + * Convert the given legacy filter to (the JSON representation of) an + * equivalent expression + * @private + */ +export default function convertFilter(filter: FilterSpecification): mixed { + return _convertFilter(filter, {}); +} + +/* + * Convert the given filter to an expression, storing the expected types for + * any feature properties referenced in expectedTypes. + * + * These expected types are needed in order to construct preflight type checks + * needed for handling 'any' filters. A preflight type check is necessary in + * order to mimic legacy filters' semantics around expected type mismatches. + * For example, consider the legacy filter: + * + * ["any", ["all", [">", "y", 0], [">", "y", 0]], [">", "x", 0]] + * + * Naively, we might convert this to the expression: + * + * ["any", ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], [">", ["get", "x"], 0]] + * + * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the + * [">", ["get", "y"], 0] would cause an evaluation error, leading to the + * entire filter returning false. Legacy filter semantics, though, ask for + * [">", "y", 0] to simply return `false` when `y` is of the wrong type, + * allowing the subsequent terms of the outer "any" expression to be evaluated + * (resulting, in this case, in a `true` value, because x > 0). + * + * We account for this by inserting a preflight type-checking expression before + * each "any" term, allowing us to avoid evaluating the actual converted filter + * if any type mismatches would cause it to produce an evalaution error: + * + * ["any", + * ["case", + * ["all", ["==", ["typeof", ["get", "y"]], "number"], ["==", ["typeof", ["get", "z"], "number]], + * ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], + * false + * ], + * ["case", + * ["==", ["typeof", ["get", "x"], "number"]], + * [">", ["get", "x"], 0], + * false + * ] + * ] + * + * An alternative, possibly more direct approach would be to use type checks + * in the conversion of each comparison operator, so that the converted version + * of each individual ==, >=, etc. would mimic the legacy filter semantics. The + * downside of this approach is that it can lead to many more type checks than + * would otherwise be necessary: outside the context of an "any" expression, + * bailing out due to a runtime type error (expression semantics) and returning + * false (legacy filter semantics) are equivalent: they cause the filter to + * produce a `false` result. + */ +function _convertFilter(filter: FilterSpecification, expectedTypes: ExpectedTypes): mixed { + if (isExpressionFilter(filter)) { return filter; } + + if (!filter) return true; + const op = filter[0]; + if (filter.length <= 1) return (op !== 'any'); + + let converted; + + if ( + op === '==' || + op === '!=' || + op === '<' || + op === '>' || + op === '<=' || + op === '>=' + ) { + const [, property, value] = (filter: any); + converted = convertComparisonOp(property, value, op, expectedTypes); + } else if (op === 'any') { + const children = (filter: any).slice(1).map(f => { + const types = {}; + const child = _convertFilter(f, types); + const typechecks = runtimeTypeChecks(types); + return typechecks === true ? child : ['case', typechecks, child, false]; + }); + return ['any'].concat(children); + } else if (op === 'all') { + const children = (filter: any).slice(1).map(f => _convertFilter(f, expectedTypes)); + return children.length > 1 ? ['all'].concat(children) : [].concat(...children); + } else if (op === 'none') { + return ['!', _convertFilter(['any'].concat(filter.slice(1)), {})]; + } else if (op === 'in') { + converted = convertInOp((filter[1]: any), filter.slice(2)); + } else if (op === '!in') { + converted = convertInOp((filter[1]: any), filter.slice(2), true); + } else if (op === 'has') { + converted = convertHasOp((filter[1]: any)); + } else if (op === '!has') { + converted = ['!', convertHasOp((filter[1]: any))]; + } else { + converted = true; + } + + return converted; +} + +// Given a set of feature properties and an expected type for each one, +// construct an boolean expression that tests whether each property has the +// right type. +// E.g.: for {name: 'string', population: 'number'}, return +// [ 'all', +// ['==', ['typeof', ['get', 'name'], 'string']], +// ['==', ['typeof', ['get', 'population'], 'number]] +// ] +function runtimeTypeChecks(expectedTypes: ExpectedTypes) { + const conditions = []; + for (const property in expectedTypes) { + const get = property === '$id' ? ['id'] : ['get', property]; + conditions.push(['==', ['typeof', get], expectedTypes[property]]); + } + if (conditions.length === 0) return true; + if (conditions.length === 1) return conditions[0]; + return ['all'].concat(conditions); +} + +function convertComparisonOp(property: string, value: any, op: string, expectedTypes: ?ExpectedTypes) { + let get; + if (property === '$type') { + return [op, ['geometry-type'], value]; + } else if (property === '$id') { + get = ['id']; + } else { + get = ['get', property]; + } + + if (expectedTypes && value !== null) { + const type = ((typeof value): any); + expectedTypes[property] = type; + } + + if (op === '==' && property !== '$id' && value === null) { + return [ + 'all', + ['has', property], // missing property != null for legacy filters + ['==', get, null] + ]; + } else if (op === '!=' && property !== '$id' && value === null) { + return [ + 'any', + ['!', ['has', property]], // missing property != null for legacy filters + ['!=', get, null] + ]; + } + + return [op, get, value]; +} + +function convertInOp(property: string, values: Array, negate = false) { + if (values.length === 0) return negate; + + let get; + if (property === '$type') { + get = ['geometry-type']; + } else if (property === '$id') { + get = ['id']; + } else { + get = ['get', property]; + } + + // Determine if the list of values to be searched is homogenously typed. + // If so (and if the type is string or number), then we can use a + // [match, input, [...values], true, false] construction rather than a + // bunch of `==` tests. + let uniformTypes = true; + const type = typeof values[0]; + for (const value of values) { + if (typeof value !== type) { + uniformTypes = false; + break; + } + } + + if (uniformTypes && (type === 'string' || type === 'number')) { + // Match expressions must have unique values. + const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v); + return ['match', get, uniqueValues, !negate, negate]; + } + + return [ negate ? 'all' : 'any' ].concat( + values.map(v => [negate ? '!=' : '==', get, v]) + ); +} + +function convertHasOp(property: string) { + if (property === '$type') { + return true; + } else if (property === '$id') { + return ['!=', ['id'], null]; + } else { + return ['has', property]; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/index.js b/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a096d14ed73c96fa049afa1f4032583f0032bfbc --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/feature_filter/index.js @@ -0,0 +1,175 @@ +// @flow + +import {createExpression} from '../expression'; +import type {GlobalProperties, Feature} from '../expression'; +import type {CanonicalTileID} from '../../source/tile_id'; + +type FilterExpression = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => boolean; +export type FeatureFilter ={filter: FilterExpression, needGeometry: boolean}; + +export default createFilter; +export {isExpressionFilter}; + +function isExpressionFilter(filter: any) { + if (filter === true || filter === false) { + return true; + } + + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + + case '!in': + case '!has': + case 'none': + return false; + + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + + case 'any': + case 'all': + for (const f of filter.slice(1)) { + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + + default: + return true; + } +} + +const filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': ['zoom', 'feature'] + } +}; + +/** + * Given a filter expressed as nested arrays, return a new function + * that evaluates whether a given feature (with a .properties or .tags property) + * passes its test. + * + * @private + * @param {Array} filter mapbox gl filter + * @returns {Function} filter-evaluating function + */ +function createFilter(filter: any): FeatureFilter { + if (filter === null || filter === undefined) { + return {filter: () => true, needGeometry: false}; + } + + if (!isExpressionFilter(filter)) { + filter = convertFilter(filter); + } + + const compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } else { + const needGeometry = geometryNeeded(filter); + return {filter: (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => compiled.value.evaluate(globalProperties, feature, {}, canonical), + needGeometry}; + } +} + +// Comparison function to sort numbers and strings +function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +function geometryNeeded(filter) { + if (!Array.isArray(filter)) return false; + if (filter[0] === 'within') return true; + for (let index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) return true; + } + return false; +} + +function convertFilter(filter: ?Array): mixed { + if (!filter) return true; + const op = filter[0]; + if (filter.length <= 1) return (op !== 'any'); + const converted = + op === '==' ? convertComparisonOp(filter[1], filter[2], '==') : + op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) : + op === '<' || + op === '>' || + op === '<=' || + op === '>=' ? convertComparisonOp(filter[1], filter[2], op) : + op === 'any' ? convertDisjunctionOp(filter.slice(1)) : + op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) : + op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) : + op === 'in' ? convertInOp(filter[1], filter.slice(2)) : + op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) : + op === 'has' ? convertHasOp(filter[1]) : + op === '!has' ? convertNegation(convertHasOp(filter[1])) : + op === 'within' ? filter : + true; + return converted; +} + +function convertComparisonOp(property: string, value: any, op: string) { + switch (property) { + case '$type': + return [`filter-type-${op}`, value]; + case '$id': + return [`filter-id-${op}`, value]; + default: + return [`filter-${op}`, property, value]; + } +} + +function convertDisjunctionOp(filters: Array>) { + return ['any'].concat(filters.map(convertFilter)); +} + +function convertInOp(property: string, values: Array) { + if (values.length === 0) { return false; } + switch (property) { + case '$type': + return [`filter-type-in`, ['literal', values]]; + case '$id': + return [`filter-id-in`, ['literal', values]]; + default: + if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) { + return ['filter-in-large', property, ['literal', values.sort(compare)]]; + } else { + return ['filter-in-small', property, ['literal', values]]; + } + } +} + +function convertHasOp(property: string) { + switch (property) { + case '$type': + return true; + case '$id': + return [`filter-has-id`]; + default: + return [`filter-has`, property]; + } +} + +function convertNegation(filter: mixed) { + return ['!', filter]; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/format.js b/node_modules/@plotly/mapbox-gl/src/style-spec/format.js new file mode 100644 index 0000000000000000000000000000000000000000..d32d0e4abf3cbdd498b873adeb49963ebb95c5ec --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/format.js @@ -0,0 +1,51 @@ + +import reference from './reference/latest.js'; +import stringifyPretty from 'json-stringify-pretty-compact'; + +function sortKeysBy(obj, reference) { + const result = {}; + for (const key in reference) { + if (obj[key] !== undefined) { + result[key] = obj[key]; + } + } + for (const key in obj) { + if (result[key] === undefined) { + result[key] = obj[key]; + } + } + return result; +} + +/** + * Format a Mapbox GL Style. Returns a stringified style with its keys + * sorted in the same order as the reference style. + * + * The optional `space` argument is passed to + * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) + * to generate formatted output. + * + * If `space` is unspecified, a default of `2` spaces will be used. + * + * @private + * @param {Object} style a Mapbox GL Style + * @param {number} [space] space argument to pass to `JSON.stringify` + * @returns {string} stringified formatted JSON + * @example + * var fs = require('fs'); + * var format = require('mapbox-gl-style-spec').format; + * var style = fs.readFileSync('./source.json', 'utf8'); + * fs.writeFileSync('./dest.json', format(style)); + * fs.writeFileSync('./dest.min.json', format(style, 0)); + */ +function format(style, space = 2) { + style = sortKeysBy(style, reference.$root); + + if (style.layers) { + style.layers = style.layers.map((layer) => sortKeysBy(layer, reference.layer)); + } + + return stringifyPretty(style, {indent: space}); +} + +export default format; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/function/convert.js b/node_modules/@plotly/mapbox-gl/src/style-spec/function/convert.js new file mode 100644 index 0000000000000000000000000000000000000000..34624f4238598fd5c2cc972a668801900fbfbc00 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/function/convert.js @@ -0,0 +1,270 @@ +// @flow + +import assert from 'assert'; +import type {StylePropertySpecification} from '../style-spec'; + +export default convertFunction; + +function convertLiteral(value) { + return typeof value === 'object' ? ['literal', value] : value; +} + +function convertFunction(parameters: any, propertySpec: StylePropertySpecification) { + let stops = parameters.stops; + if (!stops) { + // identity function + return convertIdentityFunction(parameters, propertySpec); + } + + const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + + stops = stops.map((stop) => { + if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') { + return [stop[0], convertTokenString(stop[1])]; + } + return [stop[0], convertLiteral(stop[1])]; + }); + + if (zoomAndFeatureDependent) { + return convertZoomAndPropertyFunction(parameters, propertySpec, stops); + } else if (zoomDependent) { + return convertZoomFunction(parameters, propertySpec, stops); + } else { + return convertPropertyFunction(parameters, propertySpec, stops); + } +} + +function convertIdentityFunction(parameters, propertySpec): Array { + const get = ['get', parameters.property]; + + if (parameters.default === undefined) { + // By default, expressions for string-valued properties get coerced. To preserve + // legacy function semantics, insert an explicit assertion instead. + return propertySpec.type === 'string' ? ['string', get] : get; + } else if (propertySpec.type === 'enum') { + return [ + 'match', + get, + Object.keys(propertySpec.values), + get, + parameters.default + ]; + } else { + const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)]; + if (propertySpec.type === 'array') { + expression.splice(1, 0, propertySpec.value, propertySpec.length || null); + } + return expression; + } +} + +function getInterpolateOperator(parameters) { + switch (parameters.colorSpace) { + case 'hcl': return 'interpolate-hcl'; + case 'lab': return 'interpolate-lab'; + default: return 'interpolate'; + } +} + +function convertZoomAndPropertyFunction(parameters, propertySpec, stops) { + const featureFunctionParameters = {}; + const featureFunctionStops = {}; + const zoomStops = []; + for (let s = 0; s < stops.length; s++) { + const stop = stops[s]; + const zoom = stop[0].zoom; + if (featureFunctionParameters[zoom] === undefined) { + featureFunctionParameters[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + }; + featureFunctionStops[zoom] = []; + zoomStops.push(zoom); + } + featureFunctionStops[zoom].push([stop[0].value, stop[1]]); + } + + // the interpolation type for the zoom dimension of a zoom-and-property + // function is determined directly from the style property specification + // for which it's being used: linear for interpolatable properties, step + // otherwise. + const functionType = getFunctionType({}, propertySpec); + if (functionType === 'exponential') { + const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']]; + + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, false); + } + + return expression; + } else { + const expression = ['step', ['zoom']]; + + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, true); + } + + fixupDegenerateStepCurve(expression); + + return expression; + } +} + +function coalesce(a, b) { + if (a !== undefined) return a; + if (b !== undefined) return b; +} + +function getFallback(parameters, propertySpec) { + const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default)); + + /* + * Some fields with type: resolvedImage have an undefined default. + * Because undefined is an invalid value for resolvedImage, set fallback to + * an empty string instead of undefined to ensure output + * passes validation. + */ + if (defaultValue === undefined && propertySpec.type === 'resolvedImage') { + return ''; + } + return defaultValue; +} + +function convertPropertyFunction(parameters, propertySpec, stops) { + const type = getFunctionType(parameters, propertySpec); + const get = ['get', parameters.property]; + if (type === 'categorical' && typeof stops[0][0] === 'boolean') { + assert(parameters.stops.length > 0 && parameters.stops.length <= 2); + const expression = ['case']; + for (const stop of stops) { + expression.push(['==', get, stop[0]], stop[1]); + } + + expression.push(getFallback(parameters, propertySpec)); + return expression; + } else if (type === 'categorical') { + const expression = ['match', get]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } else if (type === 'interval') { + const expression = ['step', ['number', get]]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], true); + } + fixupDegenerateStepCurve(expression); + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + const expression = [ + getInterpolateOperator(parameters), + base === 1 ? ["linear"] : ["exponential", base], + ["number", get] + ]; + + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } else { + throw new Error(`Unknown property function type ${type}`); + } +} + +function convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) { + const type = getFunctionType(parameters, propertySpec); + let expression; + let isStep = false; + if (type === 'interval') { + expression = ['step', input]; + isStep = true; + } else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + expression = [getInterpolateOperator(parameters), base === 1 ? ["linear"] : ["exponential", base], input]; + + } else { + throw new Error(`Unknown zoom function type "${type}"`); + } + + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], isStep); + } + + fixupDegenerateStepCurve(expression); + + return expression; +} + +function fixupDegenerateStepCurve(expression) { + // degenerate step curve (i.e. a constant function): add a noop stop + if (expression[0] === 'step' && expression.length === 3) { + expression.push(0); + expression.push(expression[3]); + } +} + +function appendStopPair(curve, input, output, isStep) { + // Skip duplicate stop values. They were not validated for functions, but they are for expressions. + // https://github.com/mapbox/mapbox-gl-js/issues/4107 + if (curve.length > 3 && input === curve[curve.length - 2]) { + return; + } + // step curves don't get the first input value, as it is redundant. + if (!(isStep && curve.length === 2)) { + curve.push(input); + } + curve.push(output); +} + +function getFunctionType(parameters, propertySpec) { + if (parameters.type) { + return parameters.type; + } else { + assert(propertySpec.expression); + return (propertySpec.expression: any).interpolated ? 'exponential' : 'interval'; + } +} + +// "String with {name} token" => ["concat", "String with ", ["get", "name"], " token"] +export function convertTokenString(s: string) { + const result = ['concat']; + const re = /{([^{}]+)}/g; + let pos = 0; + for (let match = re.exec(s); match !== null; match = re.exec(s)) { + const literal = s.slice(pos, re.lastIndex - match[0].length); + pos = re.lastIndex; + if (literal.length > 0) result.push(literal); + result.push(['get', match[1]]); + } + + if (result.length === 1) { + return s; + } + + if (pos < s.length) { + result.push(s.slice(pos)); + } else if (result.length === 2) { + return ['to-string', result[1]]; + } + + return result; +} + diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/function/index.js b/node_modules/@plotly/mapbox-gl/src/style-spec/function/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a78b575f7349aa41c900ead213a4dd2f7fe3f22e --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/function/index.js @@ -0,0 +1,262 @@ + +import * as colorSpaces from '../util/color_spaces'; +import Color from '../util/color'; +import extend from '../util/extend'; +import getType from '../util/get_type'; +import * as interpolate from '../util/interpolate'; +import Interpolate from '../expression/definitions/interpolate'; +import Formatted from '../expression/types/formatted'; +import ResolvedImage from '../expression/types/resolved_image'; +import {supportsInterpolation} from '../util/properties'; +import {findStopLessThanOrEqualTo} from '../expression/stops'; + +export function isFunction(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function identityFunction(x) { + return x; +} + +export function createFunction(parameters, propertySpec) { + const isColor = propertySpec.type === 'color'; + const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + + if (isColor) { + parameters = extend({}, parameters); + + if (parameters.stops) { + parameters.stops = parameters.stops.map((stop) => { + return [stop[0], Color.parse(stop[1])]; + }); + } + + if (parameters.default) { + parameters.default = Color.parse(parameters.default); + } else { + parameters.default = Color.parse(propertySpec.default); + } + } + + if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace + throw new Error(`Unknown color space: ${parameters.colorSpace}`); + } + + let innerFun; + let hashedStops; + let categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + + // For categorical functions, generate an Object as a hashmap of the stops for fast searching + hashedStops = Object.create(null); + for (const stop of parameters.stops) { + hashedStops[stop[0]] = stop[1]; + } + + // Infer key type based on first stop key-- used to encforce strict type checking later + categoricalKeyType = typeof parameters.stops[0][0]; + + } else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } else { + throw new Error(`Unknown function type "${type}"`); + } + + if (zoomAndFeatureDependent) { + const featureFunctions = {}; + const zoomStops = []; + for (let s = 0; s < parameters.stops.length; s++) { + const stop = parameters.stops[s]; + const zoom = stop[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); + } + + const featureFunctionStops = []; + for (const z of zoomStops) { + featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); + } + + const interpolationType = {name: 'linear'}; + return { + kind: 'composite', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(s => s[0]), + evaluate({zoom}, properties) { + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } else if (zoomDependent) { + const interpolationType = type === 'exponential' ? + {name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1} : null; + return { + kind: 'camera', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: parameters.stops.map(s => s[0]), + evaluate: ({zoom}) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) + }; + } else { + return { + kind: 'source', + evaluate(_, feature) { + const value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } +} + +function coalesce(a, b, c) { + if (a !== undefined) return a; + if (b !== undefined) return b; + if (c !== undefined) return c; +} + +function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input + return coalesce(evaluated, parameters.default, propertySpec.default); +} + +function evaluateIntervalFunction(parameters, propertySpec, input) { + // Edge cases + if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; + + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + + return parameters.stops[index][1]; +} + +function evaluateExponentialFunction(parameters, propertySpec, input) { + const base = parameters.base !== undefined ? parameters.base : 1; + + // Edge cases + if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; + + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + const t = interpolationFactor( + input, base, + parameters.stops[index][0], + parameters.stops[index + 1][0]); + + const outputLower = parameters.stops[index][1]; + const outputUpper = parameters.stops[index + 1][1]; + let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace + + if (parameters.colorSpace && parameters.colorSpace !== 'rgb') { + const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace + interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t)); + } + + if (typeof outputLower.evaluate === 'function') { + return { + evaluate(...args) { + const evaluatedLower = outputLower.evaluate.apply(undefined, args); + const evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + // Special case for fill-outline-color, which has no spec default. + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t); + } + }; + } + + return interp(outputLower, outputUpper, t); +} + +function evaluateIdentityFunction(parameters, propertySpec, input) { + if (propertySpec.type === 'color') { + input = Color.parse(input); + } else if (propertySpec.type === 'formatted') { + input = Formatted.fromString(input.toString()); + } else if (propertySpec.type === 'resolvedImage') { + input = ResolvedImage.fromString(input.toString()); + } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + return coalesce(input, parameters.default, propertySpec.default); +} + +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * + * How it works: + * Two consecutive stop values define a (scaled and shifted) exponential + * function `f(x) = a * base^x + b`, where `base` is the user-specified base, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private + */ +function interpolationFactor(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/group_by_layout.js b/node_modules/@plotly/mapbox-gl/src/style-spec/group_by_layout.js new file mode 100644 index 0000000000000000000000000000000000000000..73238a87c164f909d9bcfc81b9ca794d0941c3e8 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/group_by_layout.js @@ -0,0 +1,75 @@ + +import refProperties from './util/ref_properties'; + +function stringify(obj) { + const type = typeof obj; + if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null) + return JSON.stringify(obj); + + if (Array.isArray(obj)) { + let str = '['; + for (const val of obj) { + str += `${stringify(val)},`; + } + return `${str}]`; + } + + const keys = Object.keys(obj).sort(); + + let str = '{'; + for (let i = 0; i < keys.length; i++) { + str += `${JSON.stringify(keys[i])}:${stringify(obj[keys[i]])},`; + } + return `${str}}`; +} + +function getKey(layer) { + let key = ''; + for (const k of refProperties) { + key += `/${stringify(layer[k])}`; + } + return key; +} + +export default groupByLayout; + +/** + * Given an array of layers, return an array of arrays of layers where all + * layers in each group have identical layout-affecting properties. These + * are the properties that were formerly used by explicit `ref` mechanism + * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom', + * 'filter', and 'layout'. + * + * The input is not modified. The output layers are references to the + * input layers. + * + * @private + * @param {Array} layers + * @param {Object} [cachedKeys] - an object to keep already calculated keys. + * @returns {Array>} + */ +function groupByLayout(layers, cachedKeys) { + const groups = {}; + + for (let i = 0; i < layers.length; i++) { + + const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]); + // update the cache if there is one + if (cachedKeys) + cachedKeys[layers[i].id] = k; + + let group = groups[k]; + if (!group) { + group = groups[k] = []; + } + group.push(layers[i]); + } + + const result = []; + + for (const k in groups) { + result.push(groups[k]); + } + + return result; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/migrate.js b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate.js new file mode 100644 index 0000000000000000000000000000000000000000..d17de6afa9e37598a5bb688062356197a999f79a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate.js @@ -0,0 +1,36 @@ + +import migrateToV8 from './migrate/v8'; +import migrateToExpressions from './migrate/expressions'; + +/** + * Migrate a Mapbox GL Style to the latest version. + * + * @private + * @alias migrate + * @param {object} style a Mapbox GL Style + * @returns {Object} a migrated style + * @example + * var fs = require('fs'); + * var migrate = require('mapbox-gl-style-spec').migrate; + * var style = fs.readFileSync('./style.json', 'utf8'); + * fs.writeFileSync('./style.json', JSON.stringify(migrate(style))); + */ +export default function(style) { + let migrated = false; + + if (style.version === 7) { + style = migrateToV8(style); + migrated = true; + } + + if (style.version === 8) { + migrated = migrateToExpressions(style); + migrated = true; + } + + if (!migrated) { + throw new Error('cannot migrate from', style.version); + } + + return style; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/expressions.js b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/expressions.js new file mode 100644 index 0000000000000000000000000000000000000000..544e6d15d0670ece970efe15dd1cff747969095a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/expressions.js @@ -0,0 +1,39 @@ +// @flow + +import { + eachLayer, + eachProperty +} from '../visit'; +import {isExpression} from '../expression'; +import convertFunction, {convertTokenString} from '../function/convert'; +import convertFilter from '../feature_filter/convert'; + +import type {StyleSpecification} from '../types'; + +/** + * Migrate the given style object in place to use expressions. Specifically, + * this will convert (a) "stop" functions, and (b) legacy filters to their + * expression equivalents. + */ +export default function(style: StyleSpecification) { + const converted = []; + + eachLayer(style, (layer) => { + if (layer.filter) { + layer.filter = (convertFilter(layer.filter): any); + } + }); + + eachProperty(style, {paint: true, layout: true}, ({path, value, reference, set}) => { + if (isExpression(value)) return; + if (typeof value === 'object' && !Array.isArray(value)) { + set(convertFunction(value, reference)); + converted.push(path.join('.')); + } else if (reference.tokens && typeof value === 'string') { + set(convertTokenString(value)); + } + }); + + return style; +} + diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/v8.js b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/v8.js new file mode 100644 index 0000000000000000000000000000000000000000..632b938ee42d88a80d174002ec72895792d5320b --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/v8.js @@ -0,0 +1,203 @@ + +import URL from 'url'; +import {eachSource, eachLayer, eachProperty} from '../visit'; + +function eachLayout(layer, callback) { + for (const k in layer) { + if (k.indexOf('layout') === 0) { + callback(layer[k], k); + } + } +} + +function eachPaint(layer, callback) { + for (const k in layer) { + if (k.indexOf('paint') === 0) { + callback(layer[k], k); + } + } +} + +function resolveConstant(style, value) { + if (typeof value === 'string' && value[0] === '@') { + return resolveConstant(style, style.constants[value]); + } else { + return value; + } +} + +function isFunction(value) { + return Array.isArray(value.stops); +} + +function renameProperty(obj, from, to) { + obj[to] = obj[from]; delete obj[from]; +} + +export default function(style) { + style.version = 8; + + // Rename properties, reverse coordinates in source and layers + eachSource(style, (source) => { + if (source.type === 'video' && source.url !== undefined) { + renameProperty(source, 'url', 'urls'); + } + if (source.type === 'video') { + source.coordinates.forEach((coord) => { + return coord.reverse(); + }); + } + }); + + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['symbol-min-distance'] !== undefined) { + renameProperty(layout, 'symbol-min-distance', 'symbol-spacing'); + } + }); + + eachPaint(layer, (paint) => { + if (paint['background-image'] !== undefined) { + renameProperty(paint, 'background-image', 'background-pattern'); + } + if (paint['line-image'] !== undefined) { + renameProperty(paint, 'line-image', 'line-pattern'); + } + if (paint['fill-image'] !== undefined) { + renameProperty(paint, 'fill-image', 'fill-pattern'); + } + }); + }); + + // Inline Constants + eachProperty(style, {paint: true, layout: true}, (property) => { + const value = resolveConstant(style, property.value); + + if (isFunction(value)) { + value.stops.forEach((stop) => { + stop[1] = resolveConstant(style, stop[1]); + }); + } + + property.set(value); + }); + delete style.constants; + + eachLayer(style, (layer) => { + // get rid of text-max-size, icon-max-size + // turn text-size, icon-size into layout properties + // https://github.com/mapbox/mapbox-gl-style-spec/issues/255 + + eachLayout(layer, (layout) => { + delete layout['text-max-size']; + delete layout['icon-max-size']; + }); + + eachPaint(layer, (paint) => { + if (paint['text-size']) { + if (!layer.layout) layer.layout = {}; + layer.layout['text-size'] = paint['text-size']; + delete paint['text-size']; + } + + if (paint['icon-size']) { + if (!layer.layout) layer.layout = {}; + layer.layout['icon-size'] = paint['icon-size']; + delete paint['icon-size']; + } + }); + }); + + function migrateFontstackURL(input) { + const inputParsed = URL.parse(input); + const inputPathnameParts = inputParsed.pathname.split('/'); + + if (inputParsed.protocol !== 'mapbox:') { + return input; + + } else if (inputParsed.hostname === 'fontstack') { + assert(decodeURI(inputParsed.pathname) === '/{fontstack}/{range}.pbf'); + return 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf'; + + } else if (inputParsed.hostname === 'fonts') { + assert(inputPathnameParts[1] === 'v1'); + assert(decodeURI(inputPathnameParts[3]) === '{fontstack}'); + assert(decodeURI(inputPathnameParts[4]) === '{range}.pbf'); + return `mapbox://fonts/${inputPathnameParts[2]}/{fontstack}/{range}.pbf`; + + } else { + assert(false); + } + + function assert(predicate) { + if (!predicate) { + throw new Error(`Invalid font url: "${input}"`); + } + } + } + + if (style.glyphs) { + style.glyphs = migrateFontstackURL(style.glyphs); + } + + function migrateFontStack(font) { + function splitAndTrim(string) { + return string.split(',').map((s) => { + return s.trim(); + }); + } + + if (Array.isArray(font)) { + // Assume it's a previously migrated font-array. + return font; + + } else if (typeof font === 'string') { + return splitAndTrim(font); + + } else if (typeof font === 'object') { + font.stops.forEach((stop) => { + stop[1] = splitAndTrim(stop[1]); + }); + return font; + + } else { + throw new Error("unexpected font value"); + } + } + + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['text-font']) { + layout['text-font'] = migrateFontStack(layout['text-font']); + } + }); + }); + + // Reverse order of symbol layers. This is an imperfect migration. + // + // The order of a symbol layer in the layers list affects two things: + // - how it is drawn relative to other layers (like oneway arrows below bridges) + // - the placement priority compared to other layers + // + // It's impossible to reverse the placement priority without breaking the draw order + // in some cases. This migration only reverses the order of symbol layers that + // are above all other types of layers. + // + // Symbol layers that are at the top of the map preserve their priority. + // Symbol layers that are below another type (line, fill) of layer preserve their draw order. + + let firstSymbolLayer = 0; + for (let i = style.layers.length - 1; i >= 0; i--) { + const layer = style.layers[i]; + if (layer.type !== 'symbol') { + firstSymbolLayer = i + 1; + break; + } + } + + const symbolLayers = style.layers.splice(firstSymbolLayer); + symbolLayers.reverse(); + style.layers = style.layers.concat(symbolLayers); + + return style; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/v9.js b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/v9.js new file mode 100644 index 0000000000000000000000000000000000000000..bb182dbfea17ecc9dc196f26b8d8df40d3af3c73 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/migrate/v9.js @@ -0,0 +1,26 @@ + +import deref from '../deref'; + +function eachLayer(style, callback) { + for (const k in style.layers) { + callback(style.layers[k]); + } +} + +export default function(style) { + style.version = 9; + + // remove user-specified refs + style.layers = deref(style.layers); + + // remove class-specific paint properties + eachLayer(style, (layer) => { + for (const k in layer) { + if (/paint\..*/.test(k)) { + delete layer[k]; + } + } + }); + + return style; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/package.json b/node_modules/@plotly/mapbox-gl/src/style-spec/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c1f20eeafe4fa66c05072f264d43cf96406496a8 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/package.json @@ -0,0 +1,41 @@ +{ + "name": "@mapbox/mapbox-gl-style-spec", + "description": "a specification for mapbox gl styles", + "version": "13.18.0-dev", + "author": "Mapbox", + "keywords": [ + "mapbox", + "mapbox-gl", + "mapbox-gl-js" + ], + "license": "ISC", + "main": "./dist/index.js", + "module": "./dist/index.es.js", + "scripts": { + "copy-flow-typed": "cp -R ../../flow-typed .", + "build": "../../node_modules/.bin/rollup -c && ../../node_modules/.bin/rollup -c --environment esm", + "prepublish": "git clean -fdx && yarn copy-flow-typed && yarn build", + "postpublish": "rm -r flow-typed dist/index.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:mapbox/mapbox-gl-js.git" + }, + "bin": { + "gl-style-migrate": "bin/gl-style-migrate", + "gl-style-validate": "bin/gl-style-validate", + "gl-style-format": "bin/gl-style-format", + "gl-style-composite": "bin/gl-style-composite" + }, + "dependencies": { + "@mapbox/jsonlint-lines-primitives": "~2.0.2", + "@mapbox/unitbezier": "^0.0.0", + "@mapbox/point-geometry": "^0.1.0", + "csscolorparser": "~1.0.2", + "json-stringify-pretty-compact": "^2.0.0", + "minimist": "^1.2.5", + "rw": "^1.3.3", + "sort-object": "^0.3.2" + }, + "sideEffects": false +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/read_style.js b/node_modules/@plotly/mapbox-gl/src/style-spec/read_style.js new file mode 100644 index 0000000000000000000000000000000000000000..1fd2aa72ee6b575014ed6f1a81b169c9e9a909c5 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/read_style.js @@ -0,0 +1,14 @@ +import ParsingError from './error/parsing_error'; +import jsonlint from '@mapbox/jsonlint-lines-primitives'; + +export default function readStyle(style) { + if (style instanceof String || typeof style === 'string' || style instanceof Buffer) { + try { + return jsonlint.parse(style.toString()); + } catch (e) { + throw new ParsingError(e); + } + } + + return style; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/reference/latest.js b/node_modules/@plotly/mapbox-gl/src/style-spec/reference/latest.js new file mode 100644 index 0000000000000000000000000000000000000000..ab337fd3976efd23c834cc555be4fca281964922 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/reference/latest.js @@ -0,0 +1,3 @@ + +import spec from './v8.json'; +export default spec; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/reference/v8.json b/node_modules/@plotly/mapbox-gl/src/style-spec/reference/v8.json new file mode 100644 index 0000000000000000000000000000000000000000..0a29e67b372b9f4b73e528d85bd42977c3744d03 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/reference/v8.json @@ -0,0 +1,5914 @@ +{ + "$version": 8, + "$root": { + "version": { + "required": true, + "type": "enum", + "values": [ + 8 + ], + "doc": "Style specification version number. Must be 8.", + "example": 8 + }, + "name": { + "type": "string", + "doc": "A human-readable name for the style.", + "example": "Bright" + }, + "metadata": { + "type": "*", + "doc": "Arbitrary properties useful to track with the stylesheet, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + "center": { + "type": "array", + "value": "number", + "doc": "Default map center in longitude and latitude. The style center will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": [ + -73.9749, + 40.7736 + ] + }, + "zoom": { + "type": "number", + "doc": "Default zoom level. The style zoom will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": 12.5 + }, + "bearing": { + "type": "number", + "default": 0, + "period": 360, + "units": "degrees", + "doc": "Default bearing, in degrees. The bearing is the compass direction that is \"up\"; for example, a bearing of 90° orients the map so that east is up. This value will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": 29 + }, + "pitch": { + "type": "number", + "default": 0, + "units": "degrees", + "doc": "Default pitch, in degrees. Zero is perpendicular to the surface, for a look straight down at the map, while a greater value like 60 looks ahead towards the horizon. The style pitch will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": 50 + }, + "light": { + "type": "light", + "doc": "The global light source.", + "example": { + "anchor": "viewport", + "color": "white", + "intensity": 0.4 + } + }, + "sources": { + "required": true, + "type": "sources", + "doc": "Data source specifications.", + "example": { + "mapbox-streets": { + "type": "vector", + "url": "mapbox://mapbox.mapbox-streets-v6" + } + } + }, + "sprite": { + "type": "string", + "doc": "A base URL for retrieving the sprite image and metadata. The extensions `.png`, `.json` and scale factor `@2x.png` will be automatically appended. This property is required if any layer uses the `background-pattern`, `fill-pattern`, `line-pattern`, `fill-extrusion-pattern`, or `icon-image` properties. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + "example": "mapbox://sprites/mapbox/bright-v8" + }, + "glyphs": { + "type": "string", + "doc": "A URL template for loading signed-distance-field glyph sets in PBF format. The URL must include `{fontstack}` and `{range}` tokens. This property is required if any layer uses the `text-field` layout property. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + "example": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf" + }, + "transition": { + "type": "transition", + "doc": "A global transition definition to use as a default across properties, to be used for timing transitions between one value and the next when no property-specific transition is set. Collision-based symbol fading is controlled independently of the style's `transition` property.", + "example": { + "duration": 300, + "delay": 0 + } + }, + "layers": { + "required": true, + "type": "array", + "value": "layer", + "doc": "Layers will be drawn in the order of this array.", + "example": [ + { + "id": "water", + "source": "mapbox-streets", + "source-layer": "water", + "type": "fill", + "paint": { + "fill-color": "#00ffff" + } + } + ] + } + }, + "sources": { + "*": { + "type": "source", + "doc": "Specification of a data source. For vector and raster sources, either TileJSON or a URL to a TileJSON must be provided. For image and video sources, a URL must be provided. For GeoJSON sources, a URL or inline GeoJSON must be provided." + } + }, + "source": [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" + ], + "source_vector": { + "type": { + "required": true, + "type": "enum", + "values": { + "vector": { + "doc": "A vector tile source." + } + }, + "doc": "The type of the source." + }, + "url": { + "type": "string", + "doc": "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + "tiles": { + "type": "array", + "value": "string", + "doc": "An array of one or more tile source URLs, as in the TileJSON spec." + }, + "bounds": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + "doc": "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + "scheme": { + "type": "enum", + "values": { + "xyz": { + "doc": "Slippy map tilenames scheme." + }, + "tms": { + "doc": "OSGeo spec scheme." + } + }, + "default": "xyz", + "doc": "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + "minzoom": { + "type": "number", + "default": 0, + "doc": "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + "maxzoom": { + "type": "number", + "default": 22, + "doc": "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "promoteId": { + "type": "promoteId", + "doc": "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`. If specified as a string for a vector tile source, the same property is used across all its source layers." + }, + "volatile": { + "type": "boolean", + "default": false, + "doc": "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + "android": "9.3.0", + "ios": "5.10.0" + } + } + }, + "*": { + "type": "*", + "doc": "Other keys to configure the data source." + } + }, + "source_raster": { + "type": { + "required": true, + "type": "enum", + "values": { + "raster": { + "doc": "A raster tile source." + } + }, + "doc": "The type of the source." + }, + "url": { + "type": "string", + "doc": "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + "tiles": { + "type": "array", + "value": "string", + "doc": "An array of one or more tile source URLs, as in the TileJSON spec." + }, + "bounds": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + "doc": "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + "minzoom": { + "type": "number", + "default": 0, + "doc": "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + "maxzoom": { + "type": "number", + "default": 22, + "doc": "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + "tileSize": { + "type": "number", + "default": 512, + "units": "pixels", + "doc": "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + "scheme": { + "type": "enum", + "values": { + "xyz": { + "doc": "Slippy map tilenames scheme." + }, + "tms": { + "doc": "OSGeo spec scheme." + } + }, + "default": "xyz", + "doc": "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "volatile": { + "type": "boolean", + "default": false, + "doc": "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + "android": "9.3.0", + "ios": "5.10.0" + } + } + }, + "*": { + "type": "*", + "doc": "Other keys to configure the data source." + } + }, + "source_raster_dem": { + "type": { + "required": true, + "type": "enum", + "values": { + "raster-dem": { + "doc": "A RGB-encoded raster DEM source" + } + }, + "doc": "The type of the source." + }, + "url": { + "type": "string", + "doc": "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + "tiles": { + "type": "array", + "value": "string", + "doc": "An array of one or more tile source URLs, as in the TileJSON spec." + }, + "bounds": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + "doc": "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + "minzoom": { + "type": "number", + "default": 0, + "doc": "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + "maxzoom": { + "type": "number", + "default": 22, + "doc": "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + "tileSize": { + "type": "number", + "default": 512, + "units": "pixels", + "doc": "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "encoding": { + "type": "enum", + "values": { + "terrarium": { + "doc": "Terrarium format PNG tiles. See https://aws.amazon.com/es/public-datasets/terrain/ for more info." + }, + "mapbox": { + "doc": "Mapbox Terrain RGB tiles. See https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb for more info." + } + }, + "default": "mapbox", + "doc": "The encoding used by this source. Mapbox Terrain RGB is used by default" + }, + "volatile": { + "type": "boolean", + "default": false, + "doc": "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + "android": "9.3.0", + "ios": "5.10.0" + } + } + }, + "*": { + "type": "*", + "doc": "Other keys to configure the data source." + } + }, + "source_geojson": { + "type": { + "required": true, + "type": "enum", + "values": { + "geojson": { + "doc": "A GeoJSON data source." + } + }, + "doc": "The data type of the GeoJSON source." + }, + "data": { + "type": "*", + "doc": "A URL to a GeoJSON file, or inline GeoJSON." + }, + "maxzoom": { + "type": "number", + "default": 18, + "doc": "Maximum zoom level at which to create vector tiles (higher means greater detail at high zoom levels)." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "buffer": { + "type": "number", + "default": 128, + "maximum": 512, + "minimum": 0, + "doc": "Size of the tile buffer on each side. A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself. Larger values produce fewer rendering artifacts near tile edges and slower performance." + }, + "filter": { + "type": "*", + "doc": "An expression for filtering features prior to processing them for rendering." + }, + "tolerance": { + "type": "number", + "default": 0.375, + "doc": "Douglas-Peucker simplification tolerance (higher means simpler geometries and faster performance)." + }, + "cluster": { + "type": "boolean", + "default": false, + "doc": "If the data is a collection of point features, setting this to true clusters the points by radius into groups. Cluster groups become new `Point` features in the source with additional properties:\n * `cluster` Is `true` if the point is a cluster \n * `cluster_id` A unqiue id for the cluster to be used in conjunction with the [cluster inspection methods](https://www.mapbox.com/mapbox-gl-js/api/#geojsonsource#getclusterexpansionzoom)\n * `point_count` Number of original points grouped into this cluster\n * `point_count_abbreviated` An abbreviated point count" + }, + "clusterRadius": { + "type": "number", + "default": 50, + "minimum": 0, + "doc": "Radius of each cluster if clustering is enabled. A value of 512 indicates a radius equal to the width of a tile." + }, + "clusterMaxZoom": { + "type": "number", + "doc": "Max zoom on which to cluster points if clustering is enabled. Defaults to one zoom less than maxzoom (so that last zoom features are not clustered). Clusters are re-evaluated at integer zoom levels so setting clusterMaxZoom to 14 means the clusters will be displayed until z15." + }, + "clusterMinPoints": { + "type": "number", + "doc": "Minimum number of points necessary to form a cluster if clustering is enabled. Defaults to `2`." + }, + "clusterProperties": { + "type": "*", + "doc": "An object defining custom properties on the generated clusters if clustering is enabled, aggregating values from clustered points. Has the form `{\"property_name\": [operator, map_expression]}`. `operator` is any expression function that accepts at least 2 operands (e.g. `\"+\"` or `\"max\"`) — it accumulates the property value from clusters/points the cluster contains; `map_expression` produces the value of a single point.\n\nExample: `{\"sum\": [\"+\", [\"get\", \"scalerank\"]]}`.\n\nFor more advanced use cases, in place of `operator`, you can use a custom reduce expression that references a special `[\"accumulated\"]` value, e.g.:\n`{\"sum\": [[\"+\", [\"accumulated\"], [\"get\", \"sum\"]], [\"get\", \"scalerank\"]]}`" + }, + "lineMetrics": { + "type": "boolean", + "default": false, + "doc": "Whether to calculate line distance metrics. This is required for line layers that specify `line-gradient` values." + }, + "generateId": { + "type": "boolean", + "default": false, + "doc": "Whether to generate ids for the geojson features. When enabled, the `feature.id` property will be auto assigned based on its index in the `features` array, over-writing any previous values." + }, + "promoteId": { + "type": "promoteId", + "doc": "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`." + } + }, + "source_video": { + "type": { + "required": true, + "type": "enum", + "values": { + "video": { + "doc": "A video data source." + } + }, + "doc": "The data type of the video source." + }, + "urls": { + "required": true, + "type": "array", + "value": "string", + "doc": "URLs to video content in order of preferred format." + }, + "coordinates": { + "required": true, + "doc": "Corners of video specified in longitude, latitude pairs.", + "type": "array", + "length": 4, + "value": { + "type": "array", + "length": 2, + "value": "number", + "doc": "A single longitude, latitude pair." + } + } + }, + "source_image": { + "type": { + "required": true, + "type": "enum", + "values": { + "image": { + "doc": "An image data source." + } + }, + "doc": "The data type of the image source." + }, + "url": { + "required": true, + "type": "string", + "doc": "URL that points to an image." + }, + "coordinates": { + "required": true, + "doc": "Corners of image specified in longitude, latitude pairs.", + "type": "array", + "length": 4, + "value": { + "type": "array", + "length": 2, + "value": "number", + "doc": "A single longitude, latitude pair." + } + } + }, + "layer": { + "id": { + "type": "string", + "doc": "Unique layer name.", + "required": true + }, + "type": { + "type": "enum", + "values": { + "fill": { + "doc": "A filled polygon with an optional stroked border.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "line": { + "doc": "A stroked line.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "symbol": { + "doc": "An icon or a text label.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "circle": { + "doc": "A filled circle.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "heatmap": { + "doc": "A heatmap.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "fill-extrusion": { + "doc": "An extruded (3D) polygon.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "raster": { + "doc": "Raster map textures such as satellite imagery.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "hillshade": { + "doc": "Client-side hillshading visualization based on DEM data. Currently, the implementation only supports Mapbox Terrain RGB and Mapzen Terrarium tiles.", + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "background": { + "doc": "The background color or pattern of the map.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + } + }, + "doc": "Rendering type of this layer.", + "required": true + }, + "metadata": { + "type": "*", + "doc": "Arbitrary properties useful to track with the layer, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + "source": { + "type": "string", + "doc": "Name of a source description to be used for this layer. Required for all layer types except `background`." + }, + "source-layer": { + "type": "string", + "doc": "Layer to use from a vector tile source. Required for vector tile sources; prohibited for all other source types, including GeoJSON sources." + }, + "minzoom": { + "type": "number", + "minimum": 0, + "maximum": 24, + "doc": "The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden." + }, + "maxzoom": { + "type": "number", + "minimum": 0, + "maximum": 24, + "doc": "The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden." + }, + "filter": { + "type": "filter", + "doc": "A expression specifying conditions on source features. Only features that match the filter are displayed. Zoom expressions in filters are only evaluated at integer zoom levels. The `feature-state` expression is not supported in filter expressions." + }, + "layout": { + "type": "layout", + "doc": "Layout properties for the layer." + }, + "paint": { + "type": "paint", + "doc": "Default paint properties for this layer." + } + }, + "layout": [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" + ], + "layout_background": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_fill": { + "fill-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + }, + "data-driven styling": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_circle": { + "circle-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "1.2.0", + "android": "9.2.0", + "ios": "5.9.0", + "macos": "0.16.0" + }, + "data-driven styling": { + "js": "1.2.0", + "android": "9.2.0", + "ios": "5.9.0", + "macos": "0.16.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_heatmap": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "property-type": "constant" + } + }, + "layout_fill-extrusion": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "property-type": "constant" + } + }, + "layout_line": { + "line-cap": { + "type": "enum", + "values": { + "butt": { + "doc": "A cap with a squared-off end which is drawn to the exact endpoint of the line." + }, + "round": { + "doc": "A cap with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + "square": { + "doc": "A cap with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + } + }, + "default": "butt", + "doc": "The display of line endings.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + "type": "enum", + "values": { + "bevel": { + "doc": "A join with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + }, + "round": { + "doc": "A join with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + "miter": { + "doc": "A join with a sharp, angled corner which is drawn with the outer sides beyond the endpoint of the path until they meet." + } + }, + "default": "miter", + "doc": "The display of lines when joining.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + "type": "number", + "default": 2, + "doc": "Used to automatically convert miter joins to bevel joins for sharp angles.", + "requires": [ + { + "line-join": "miter" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + "type": "number", + "default": 1.05, + "doc": "Used to automatically convert round joins to miter joins for shallow angles.", + "requires": [ + { + "line-join": "round" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + }, + "data-driven styling": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_symbol": { + "symbol-placement": { + "type": "enum", + "values": { + "point": { + "doc": "The label is placed at the point where the geometry is located." + }, + "line": { + "doc": "The label is placed along the line of the geometry. Can only be used on `LineString` and `Polygon` geometries." + }, + "line-center": { + "doc": "The label is placed at the center of the line of the geometry. Can only be used on `LineString` and `Polygon` geometries. Note that a single feature in a vector tile may contain multiple line geometries." + } + }, + "default": "point", + "doc": "Label placement relative to its geometry.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "`line-center` value": { + "js": "0.47.0", + "android": "6.4.0", + "ios": "4.3.0", + "macos": "0.10.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + "type": "number", + "default": 250, + "minimum": 1, + "units": "pixels", + "doc": "Distance between two symbol anchors.", + "requires": [ + { + "symbol-placement": "line" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + "type": "boolean", + "default": false, + "doc": "If true, the symbols will not cross tile edges to avoid mutual collisions. Recommended in layers that don't have enough padding in the vector tile to prevent collisions, or if it is a point symbol layer placed after a line symbol layer. When using a client that supports global collision detection, like Mapbox GL JS version 0.42.0 or greater, enabling this property is not needed to prevent clipped labels at tile boundaries.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with lower sort keys are drawn and placed first. When `icon-allow-overlap` or `text-allow-overlap` is `false`, features with a lower sort key will have priority during placement. When `icon-allow-overlap` or `text-allow-overlap` is set to `true`, features with a higher sort key will overlap over features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "0.53.0", + "android": "7.4.0", + "ios": "4.11.0", + "macos": "0.14.0" + }, + "data-driven styling": { + "js": "0.53.0", + "android": "7.4.0", + "ios": "4.11.0", + "macos": "0.14.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + "type": "enum", + "values": { + "auto": { + "doc": "Sorts symbols by `symbol-sort-key` if set. Otherwise, sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + "viewport-y": { + "doc": "Sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + "source": { + "doc": "Sorts symbols by `symbol-sort-key` if set. Otherwise, no sorting is applied; symbols are rendered in the same order as the source data." + } + }, + "default": "auto", + "doc": "Determines whether overlapping symbols in the same layer are rendered in the order that they appear in the data source or by their y-position relative to the viewport. To control the order and prioritization of symbols otherwise, use `symbol-sort-key`.", + "sdk-support": { + "basic functionality": { + "js": "0.49.0", + "android": "6.6.0", + "ios": "4.5.0", + "macos": "0.12.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + "type": "boolean", + "default": false, + "doc": "If true, the icon will be visible even if it collides with other previously drawn symbols.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + "type": "boolean", + "default": false, + "doc": "If true, other symbols can be visible even if they collide with the icon.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + "type": "boolean", + "default": false, + "doc": "If true, text will display without their corresponding icons when the icon collides with other symbols and the text does not.", + "requires": [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "When `symbol-placement` is set to `point`, aligns icons east-west. When `symbol-placement` is set to `line` or `line-center`, aligns icon x-axes with the line." + }, + "viewport": { + "doc": "Produces icons whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + "auto": { + "doc": "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + "doc": "In combination with `symbol-placement`, determines the rotation behavior of icons.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "`auto` value": { + "js": "0.25.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.3.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + "type": "number", + "default": 1, + "minimum": 0, + "units": "factor of the original icon size", + "doc": "Scales the original size of the icon by the provided factor. The new pixel size of the image will be the original pixel size multiplied by `icon-size`. 1 is the original size; 3 triples the size of the image.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + "type": "enum", + "values": { + "none": { + "doc": "The icon is displayed at its intrinsic aspect ratio." + }, + "width": { + "doc": "The icon is scaled in the x-dimension to fit the width of the text." + }, + "height": { + "doc": "The icon is scaled in the y-dimension to fit the height of the text." + }, + "both": { + "doc": "The icon is scaled in both x- and y-dimensions." + } + }, + "default": "none", + "doc": "Scales the icon to fit around the associated text.", + "requires": [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + }, + "stretchable icons": { + "js": "1.6.0", + "android": "9.2.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + 0, + 0, + 0, + 0 + ], + "units": "pixels", + "doc": "Size of the additional area added to dimensions determined by `icon-text-fit`, in clockwise order: top, right, bottom, left.", + "requires": [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + "type": "resolvedImage", + "doc": "Name of image in sprite to use for drawing an image background.", + "tokens": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + "type": "number", + "default": 0, + "period": 360, + "units": "degrees", + "doc": "Rotates the icon clockwise.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.21.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + "type": "number", + "default": 2, + "minimum": 0, + "units": "pixels", + "doc": "Size of the additional area around the icon bounding box used for detecting symbol collisions.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-keep-upright": { + "type": "boolean", + "default": false, + "doc": "If true, the icon may be flipped to prevent it from being rendered upside-down.", + "requires": [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "doc": "Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. Each component is multiplied by the value of `icon-size` to obtain the final offset in pixels. When combined with `icon-rotate` the offset will be as if the rotated direction was up.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + "type": "enum", + "values": { + "center": { + "doc": "The center of the icon is placed closest to the anchor." + }, + "left": { + "doc": "The left side of the icon is placed closest to the anchor." + }, + "right": { + "doc": "The right side of the icon is placed closest to the anchor." + }, + "top": { + "doc": "The top of the icon is placed closest to the anchor." + }, + "bottom": { + "doc": "The bottom of the icon is placed closest to the anchor." + }, + "top-left": { + "doc": "The top left corner of the icon is placed closest to the anchor." + }, + "top-right": { + "doc": "The top right corner of the icon is placed closest to the anchor." + }, + "bottom-left": { + "doc": "The bottom left corner of the icon is placed closest to the anchor." + }, + "bottom-right": { + "doc": "The bottom right corner of the icon is placed closest to the anchor." + } + }, + "default": "center", + "doc": "Part of the icon placed closest to the anchor.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "The icon is aligned to the plane of the map." + }, + "viewport": { + "doc": "The icon is aligned to the plane of the viewport." + }, + "auto": { + "doc": "Automatically matches the value of `icon-rotation-alignment`." + } + }, + "default": "auto", + "doc": "Orientation of icon when map is pitched.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "The text is aligned to the plane of the map." + }, + "viewport": { + "doc": "The text is aligned to the plane of the viewport." + }, + "auto": { + "doc": "Automatically matches the value of `text-rotation-alignment`." + } + }, + "default": "auto", + "doc": "Orientation of text when map is pitched.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + }, + "`auto` value": { + "js": "0.25.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.3.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "When `symbol-placement` is set to `point`, aligns text east-west. When `symbol-placement` is set to `line` or `line-center`, aligns text x-axes with the line." + }, + "viewport": { + "doc": "Produces glyphs whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + "auto": { + "doc": "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + "doc": "In combination with `symbol-placement`, determines the rotation behavior of the individual glyphs forming the text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "`auto` value": { + "js": "0.25.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.3.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + "type": "formatted", + "default": "", + "tokens": true, + "doc": "Value to use for a text label. If a plain `string` is provided, it will be treated as a `formatted` with default/inherited formatting options.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + "type": "array", + "value": "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + "doc": "Font stack to use for displaying text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + "type": "number", + "default": 16, + "minimum": 0, + "units": "pixels", + "doc": "Font size.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + "type": "number", + "default": 10, + "minimum": 0, + "units": "ems", + "doc": "The maximum line width for text wrapping.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + "type": "number", + "default": 1.2, + "units": "ems", + "doc": "Text leading value for multi-line text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + "type": "number", + "default": 0, + "units": "ems", + "doc": "Text tracking amount.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + "type": "enum", + "values": { + "auto": { + "doc": "The text is aligned towards the anchor position." + }, + "left": { + "doc": "The text is aligned to the left." + }, + "center": { + "doc": "The text is centered." + }, + "right": { + "doc": "The text is aligned to the right." + } + }, + "default": "center", + "doc": "Text justification options.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + }, + "auto": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + "type": "number", + "units": "ems", + "default": 0, + "doc": "Radial offset of text, in the direction of the symbol's anchor. Useful in combination with `text-variable-anchor`, which defaults to using the two-dimensional `text-offset` if present.", + "sdk-support": { + "basic functionality": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + }, + "data-driven styling": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + } + }, + "requires": [ + "text-field" + ], + "property-type": "data-driven", + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + "type": "array", + "value": "enum", + "values": { + "center": { + "doc": "The center of the text is placed closest to the anchor." + }, + "left": { + "doc": "The left side of the text is placed closest to the anchor." + }, + "right": { + "doc": "The right side of the text is placed closest to the anchor." + }, + "top": { + "doc": "The top of the text is placed closest to the anchor." + }, + "bottom": { + "doc": "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + "doc": "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + "doc": "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + "doc": "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + "doc": "The bottom right corner of the text is placed closest to the anchor." + } + }, + "requires": [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + "doc": "To increase the chance of placing high-priority labels on the map, you can provide an array of `text-anchor` locations: the renderer will attempt to place the label at each location, in order, before moving onto the next label. Use `text-justify: auto` to choose justification based on anchor position. To apply an offset, use the `text-radial-offset` or the two-dimensional `text-offset`.", + "sdk-support": { + "basic functionality": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-anchor": { + "type": "enum", + "values": { + "center": { + "doc": "The center of the text is placed closest to the anchor." + }, + "left": { + "doc": "The left side of the text is placed closest to the anchor." + }, + "right": { + "doc": "The right side of the text is placed closest to the anchor." + }, + "top": { + "doc": "The top of the text is placed closest to the anchor." + }, + "bottom": { + "doc": "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + "doc": "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + "doc": "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + "doc": "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + "doc": "The bottom right corner of the text is placed closest to the anchor." + } + }, + "default": "center", + "doc": "Part of the text placed closest to the anchor.", + "requires": [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + "type": "number", + "default": 45, + "units": "degrees", + "doc": "Maximum angle change between adjacent characters.", + "requires": [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + "type": "array", + "value": "enum", + "values": { + "horizontal": { + "doc": "If a text's language supports horizontal writing mode, symbols with point placement would be laid out horizontally." + }, + "vertical": { + "doc": "If a text's language supports vertical writing mode, symbols with point placement would be laid out vertically." + } + }, + "doc": "The property allows control over a symbol's orientation. Note that the property values act as a hint, so that a symbol whose language doesn’t support the provided orientation will be laid out in its natural orientation. Example: English point symbol will be rendered horizontally even if array value contains single 'vertical' enum value. The order of elements in an array define priority order for the placement of an orientation variant.", + "requires": [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "1.3.0", + "android": "8.3.0", + "ios": "5.3.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + "type": "number", + "default": 0, + "period": 360, + "units": "degrees", + "doc": "Rotates the text clockwise.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + "type": "number", + "default": 2, + "minimum": 0, + "units": "pixels", + "doc": "Size of the additional area around the text bounding box used for detecting symbol collisions.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + "type": "boolean", + "default": true, + "doc": "If true, the text may be flipped vertically to prevent it from being rendered upside-down.", + "requires": [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + "type": "enum", + "values": { + "none": { + "doc": "The text is not altered." + }, + "uppercase": { + "doc": "Forces all letters to be displayed in uppercase." + }, + "lowercase": { + "doc": "Forces all letters to be displayed in lowercase." + } + }, + "default": "none", + "doc": "Specifies how to capitalize text, similar to the CSS `text-transform` property.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + "type": "array", + "doc": "Offset distance of text from its anchor. Positive values indicate right and down, while negative values indicate left and up. If used with text-variable-anchor, input values will be taken as absolute values. Offsets along the x- and y-axis will be applied automatically based on the anchor position.", + "value": "number", + "units": "ems", + "length": 2, + "default": [ + 0, + 0 + ], + "requires": [ + "text-field", + { + "!": "text-radial-offset" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + "type": "boolean", + "default": false, + "doc": "If true, the text will be visible even if it collides with other previously drawn symbols.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + "type": "boolean", + "default": false, + "doc": "If true, other symbols can be visible even if they collide with the text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + "type": "boolean", + "default": false, + "doc": "If true, icons will display without their corresponding text when the text collides with other symbols and the icon does not.", + "requires": [ + "text-field", + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_raster": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_hillshade": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "property-type": "constant" + } + }, + "filter": { + "type": "array", + "value": "*", + "doc": "A filter selects specific features from a layer." + }, + "filter_operator": { + "type": "enum", + "values": { + "==": { + "doc": "`[\"==\", key, value]` equality: `feature[key] = value`" + }, + "!=": { + "doc": "`[\"!=\", key, value]` inequality: `feature[key] ≠ value`" + }, + ">": { + "doc": "`[\">\", key, value]` greater than: `feature[key] > value`" + }, + ">=": { + "doc": "`[\">=\", key, value]` greater than or equal: `feature[key] ≥ value`" + }, + "<": { + "doc": "`[\"<\", key, value]` less than: `feature[key] < value`" + }, + "<=": { + "doc": "`[\"<=\", key, value]` less than or equal: `feature[key] ≤ value`" + }, + "in": { + "doc": "`[\"in\", key, v0, ..., vn]` set inclusion: `feature[key] ∈ {v0, ..., vn}`" + }, + "!in": { + "doc": "`[\"!in\", key, v0, ..., vn]` set exclusion: `feature[key] ∉ {v0, ..., vn}`" + }, + "all": { + "doc": "`[\"all\", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`" + }, + "any": { + "doc": "`[\"any\", f0, ..., fn]` logical `OR`: `f0 ∨ ... ∨ fn`" + }, + "none": { + "doc": "`[\"none\", f0, ..., fn]` logical `NOR`: `¬f0 ∧ ... ∧ ¬fn`" + }, + "has": { + "doc": "`[\"has\", key]` `feature[key]` exists" + }, + "!has": { + "doc": "`[\"!has\", key]` `feature[key]` does not exist" + }, + "within": { + "doc": "`[\"within\", object]` feature geometry is within object geometry" + } + }, + "doc": "The filter operator." + }, + "geometry_type": { + "type": "enum", + "values": { + "Point": { + "doc": "Filter to point geometries." + }, + "LineString": { + "doc": "Filter to line geometries." + }, + "Polygon": { + "doc": "Filter to polygon geometries." + } + }, + "doc": "The geometry type for the filter to select." + }, + "function": { + "expression": { + "type": "expression", + "doc": "An expression." + }, + "stops": { + "type": "array", + "doc": "An array of stops.", + "value": "function_stop" + }, + "base": { + "type": "number", + "default": 1, + "minimum": 0, + "doc": "The exponential base of the interpolation curve. It controls the rate at which the result increases. Higher values make the result increase more towards the high end of the range. With `1` the stops are interpolated linearly." + }, + "property": { + "type": "string", + "doc": "The name of a feature property to use as the function input.", + "default": "$zoom" + }, + "type": { + "type": "enum", + "values": { + "identity": { + "doc": "Return the input value as the output value." + }, + "exponential": { + "doc": "Generate an output by interpolating between stops just less than and just greater than the function input." + }, + "interval": { + "doc": "Return the output value of the stop just less than the function input." + }, + "categorical": { + "doc": "Return the output value of the stop equal to the function input." + } + }, + "doc": "The interpolation strategy to use in function evaluation.", + "default": "exponential" + }, + "colorSpace": { + "type": "enum", + "values": { + "rgb": { + "doc": "Use the RGB color space to interpolate color values" + }, + "lab": { + "doc": "Use the LAB color space to interpolate color values." + }, + "hcl": { + "doc": "Use the HCL color space to interpolate color values, interpolating the Hue, Chroma, and Luminance channels individually." + } + }, + "doc": "The color space in which colors interpolated. Interpolating colors in perceptual color spaces like LAB and HCL tend to produce color ramps that look more consistent and produce colors that can be differentiated more easily than those interpolated in RGB space.", + "default": "rgb" + }, + "default": { + "type": "*", + "required": false, + "doc": "A value to serve as a fallback function result when a value isn't otherwise available. It is used in the following circumstances:\n* In categorical functions, when the feature value does not match any of the stop domain values.\n* In property and zoom-and-property functions, when a feature does not contain a value for the specified property.\n* In identity functions, when the feature value is not valid for the style property (for example, if the function is being used for a `circle-color` property but the feature property value is not a string or not a valid color).\n* In interval or exponential property and zoom-and-property functions, when the feature value is not numeric.\nIf no default is provided, the style property's default is used in these circumstances." + } + }, + "function_stop": { + "type": "array", + "minimum": 0, + "maximum": 24, + "value": [ + "number", + "color" + ], + "length": 2, + "doc": "Zoom level and value pair." + }, + "expression": { + "type": "array", + "value": "*", + "minimum": 1, + "doc": "An expression defines a function that can be used for data-driven style properties or feature filters." + }, + "expression_name": { + "doc": "", + "type": "enum", + "values": { + "let": { + "doc": "Binds expressions to named variables, which can then be referenced in the result expression using [\"var\", \"variable_name\"].", + "group": "Variable binding", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "var": { + "doc": "References variable bound using \"let\".", + "group": "Variable binding", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "literal": { + "doc": "Provides a literal array or object value.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "array": { + "doc": "Asserts that the input is an array (optionally with a specific item type and length). If, when the input expression is evaluated, it is not of the asserted type, then this assertion will cause the whole expression to be aborted.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "at": { + "doc": "Retrieves an item from an array.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "in": { + "doc": "Determines whether an item exists in an array or a substring exists in a string.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "1.6.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + } + }, + "index-of": { + "doc": "Returns the first position at which an item can be found in an array or a substring can be found in a string, or `-1` if the input cannot be found. Accepts an optional index from where to begin the search.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "1.10.0" + } + } + }, + "slice": { + "doc": "Returns an item from an array or a substring from a string from a specified start index, or between a start index and an end index if set. The return value is inclusive of the start index but not of the end index.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "1.10.0" + } + } + }, + "case": { + "doc": "Selects the first output whose corresponding test condition evaluates to true, or the fallback value otherwise.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "match": { + "doc": "Selects the output whose label value matches the input value, or the fallback value if no match is found. The input can be any expression (e.g. `[\"get\", \"building_type\"]`). Each label must be either:\n - a single literal value; or\n - an array of literal values, whose values must be all strings or all numbers (e.g. `[100, 101]` or `[\"c\", \"b\"]`). The input matches if any of the values in the array matches, similar to the `\"in\"` operator.\nEach label must be unique. If the input type does not match the type of the labels, the result will be the fallback value.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "coalesce": { + "doc": "Evaluates each expression in turn until the first non-null value is obtained, and returns that value.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "step": { + "doc": "Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. Returns the output value of the stop just less than the input, or the first output if the input is less than the first stop.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.42.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "interpolate": { + "doc": "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. The output type must be `number`, `array`, or `color`.\n\nInterpolation types:\n- `[\"linear\"]`: Interpolates linearly between the pair of stops just less than and just greater than the input.\n- `[\"exponential\", base]`: Interpolates exponentially between the stops just less than and just greater than the input. `base` controls the rate at which the output increases: higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly.\n- `[\"cubic-bezier\", x1, y1, x2, y2]`: Interpolates using the cubic bezier curve defined by the given control points.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.42.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "interpolate-hcl": { + "doc": "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the Hue-Chroma-Luminance color space.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.49.0" + } + } + }, + "interpolate-lab": { + "doc": "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the CIELAB color space.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.49.0" + } + } + }, + "ln2": { + "doc": "Returns mathematical constant ln(2).", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "pi": { + "doc": "Returns the mathematical constant pi.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "e": { + "doc": "Returns the mathematical constant e.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "typeof": { + "doc": "Returns a string describing the type of the given value.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "string": { + "doc": "Asserts that the input value is a string. If multiple values are provided, each one is evaluated in order until a string is obtained. If none of the inputs are strings, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "number": { + "doc": "Asserts that the input value is a number. If multiple values are provided, each one is evaluated in order until a number is obtained. If none of the inputs are numbers, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "boolean": { + "doc": "Asserts that the input value is a boolean. If multiple values are provided, each one is evaluated in order until a boolean is obtained. If none of the inputs are booleans, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "object": { + "doc": "Asserts that the input value is an object. If multiple values are provided, each one is evaluated in order until an object is obtained. If none of the inputs are objects, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "collator": { + "doc": "Returns a `collator` for use in locale-dependent comparison operations. The `case-sensitive` and `diacritic-sensitive` options default to `false`. The `locale` argument specifies the IETF language tag of the locale to use. If none is provided, the default locale is used. If the requested locale is not available, the `collator` will use a system-defined fallback locale. Use `resolved-locale` to test the results of locale fallback behavior.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "format": { + "doc": "Returns a `formatted` string for displaying mixed-format text in the `text-field` property. The input may contain a string literal or expression, including an [`'image'`](#types-image) expression. Strings may be followed by a style override object that supports the following properties:\n- `\"text-font\"`: Overrides the font stack specified by the root layout property.\n- `\"text-color\"`: Overrides the color specified by the root paint property.\n- `\"font-scale\"`: Applies a scaling factor on `text-size` as specified by the root layout property.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.48.0", + "android": "6.7.0", + "ios": "4.6.0", + "macos": "0.12.0" + }, + "text-font": { + "js": "0.48.0", + "android": "6.7.0", + "ios": "4.6.0", + "macos": "0.12.0" + }, + "font-scale": { + "js": "0.48.0", + "android": "6.7.0", + "ios": "4.6.0", + "macos": "0.12.0" + }, + "text-color": { + "js": "1.3.0", + "android": "7.3.0", + "ios": "4.10.0", + "macos": "0.14.0" + }, + "image": { + "js": "1.6.0", + "android": "8.6.0", + "ios": "5.7.0", + "macos": "0.15.0" + } + } + }, + "image": { + "doc": "Returns an `image` type for use in `icon-image`, `*-pattern` entries and as a section in the `format` expression. If set, the `image` argument will check that the requested image exists in the style and will return either the resolved image name or `null`, depending on whether or not the image is currently in the style. This validation process is synchronous and requires the image to have been added to the style before requesting it in the `image` argument.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "1.4.0", + "android": "8.6.0", + "ios": "5.7.0", + "macos": "0.15.0" + } + } + }, + "number-format": { + "doc": "Converts the input number into a string representation using the providing formatting rules. If set, the `locale` argument specifies the locale to use, as a BCP 47 language tag. If set, the `currency` argument specifies an ISO 4217 code to use for currency-style formatting. If set, the `min-fraction-digits` and `max-fraction-digits` arguments specify the minimum and maximum number of fractional digits to include.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.54.0" + } + } + }, + "to-string": { + "doc": "Converts the input value to a string. If the input is `null`, the result is `\"\"`. If the input is a boolean, the result is `\"true\"` or `\"false\"`. If the input is a number, it is converted to a string as specified by the [\"NumberToString\" algorithm](https://tc39.github.io/ecma262/#sec-tostring-applied-to-the-number-type) of the ECMAScript Language Specification. If the input is a color, it is converted to a string of the form `\"rgba(r,g,b,a)\"`, where `r`, `g`, and `b` are numerals ranging from 0 to 255, and `a` ranges from 0 to 1. Otherwise, the input is converted to a string in the format specified by the [`JSON.stringify`](https://tc39.github.io/ecma262/#sec-json.stringify) function of the ECMAScript Language Specification.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-number": { + "doc": "Converts the input value to a number, if possible. If the input is `null` or `false`, the result is 0. If the input is `true`, the result is 1. If the input is a string, it is converted to a number as specified by the [\"ToNumber Applied to the String Type\" algorithm](https://tc39.github.io/ecma262/#sec-tonumber-applied-to-the-string-type) of the ECMAScript Language Specification. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-boolean": { + "doc": "Converts the input value to a boolean. The result is `false` when then input is an empty string, 0, `false`, `null`, or `NaN`; otherwise it is `true`.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-rgba": { + "doc": "Returns a four-element array containing the input color's red, green, blue, and alpha components, in that order.", + "group": "Color", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-color": { + "doc": "Converts the input value to a color. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "rgb": { + "doc": "Creates a color value from red, green, and blue components, which must range between 0 and 255, and an alpha component of 1. If any component is out of range, the expression is an error.", + "group": "Color", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "rgba": { + "doc": "Creates a color value from red, green, blue components, which must range between 0 and 255, and an alpha component which must range between 0 and 1. If any component is out of range, the expression is an error.", + "group": "Color", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "get": { + "doc": "Retrieves a property value from the current feature's properties, or from another object if a second argument is provided. Returns null if the requested property is missing.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "has": { + "doc": "Tests for the presence of an property value in the current feature's properties, or from another object if a second argument is provided.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "length": { + "doc": "Gets the length of an array or string.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "properties": { + "doc": "Gets the feature properties object. Note that in some cases, it may be more efficient to use [\"get\", \"property_name\"] directly.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "feature-state": { + "doc": "Retrieves a property value from the current feature's state. Returns null if the requested property is not present on the feature's state. A feature's state is not part of the GeoJSON or vector tile data, and must be set programmatically on each feature. Features are identified by their `id` attribute, which must be an integer or a string that can be cast to an integer. Note that [\"feature-state\"] can only be used with paint properties that support data-driven styling.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.46.0" + } + } + }, + "geometry-type": { + "doc": "Gets the feature's geometry type: `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "id": { + "doc": "Gets the feature's id, if it has one.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "zoom": { + "doc": "Gets the current zoom level. Note that in style layout and paint properties, [\"zoom\"] may only appear as the input to a top-level \"step\" or \"interpolate\" expression.", + "group": "Zoom", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "heatmap-density": { + "doc": "Gets the kernel density estimation of a pixel in a heatmap layer, which is a relative measure of how many data points are crowded around a particular pixel. Can only be used in the `heatmap-color` property.", + "group": "Heatmap", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "line-progress": { + "doc": "Gets the progress along a gradient line. Can only be used in the `line-gradient` property.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.6.0", + "macos": "0.12.0" + } + } + }, + "accumulated": { + "doc": "Gets the value of a cluster property accumulated so far. Can only be used in the `clusterProperties` option of a clustered GeoJSON source.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.53.0" + } + } + }, + "+": { + "doc": "Returns the sum of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "*": { + "doc": "Returns the product of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "-": { + "doc": "For two inputs, returns the result of subtracting the second input from the first. For a single input, returns the result of subtracting it from 0.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "/": { + "doc": "Returns the result of floating point division of the first input by the second.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "%": { + "doc": "Returns the remainder after integer division of the first input by the second.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "^": { + "doc": "Returns the result of raising the first input to the power specified by the second.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "sqrt": { + "doc": "Returns the square root of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.42.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "log10": { + "doc": "Returns the base-ten logarithm of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "ln": { + "doc": "Returns the natural logarithm of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "log2": { + "doc": "Returns the base-two logarithm of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "sin": { + "doc": "Returns the sine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "cos": { + "doc": "Returns the cosine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "tan": { + "doc": "Returns the tangent of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "asin": { + "doc": "Returns the arcsine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "acos": { + "doc": "Returns the arccosine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "atan": { + "doc": "Returns the arctangent of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "min": { + "doc": "Returns the minimum value of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "max": { + "doc": "Returns the maximum value of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "round": { + "doc": "Rounds the input to the nearest integer. Halfway values are rounded away from zero. For example, `[\"round\", -1.5]` evaluates to -2.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "abs": { + "doc": "Returns the absolute value of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "ceil": { + "doc": "Returns the smallest integer that is greater than or equal to the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "floor": { + "doc": "Returns the largest integer that is less than or equal to the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "distance": { + "doc": "Returns the shortest distance in meters between the evaluated feature and the input geometry. The input value can be a valid GeoJSON of type `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Distance values returned may vary in precision due to loss in precision from encoding geometries, particularly below zoom level 13.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "android": "9.2.0", + "ios": "5.9.0", + "macos": "0.16.0" + } + } + }, + "==": { + "doc": "Returns `true` if the input values are equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "!=": { + "doc": "Returns `true` if the input values are not equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + ">": { + "doc": "Returns `true` if the first input is strictly greater than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "<": { + "doc": "Returns `true` if the first input is strictly less than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + ">=": { + "doc": "Returns `true` if the first input is greater than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "<=": { + "doc": "Returns `true` if the first input is less than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "all": { + "doc": "Returns `true` if all the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `false`, the result is `false` and no further input expressions are evaluated.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "any": { + "doc": "Returns `true` if any of the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `true`, the result is `true` and no further input expressions are evaluated.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "!": { + "doc": "Logical negation. Returns `true` if the input is `false`, and `false` if the input is `true`.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "within": { + "doc": "Returns `true` if the evaluated feature is fully contained inside a boundary of the input geometry, `false` otherwise. The input value can be a valid GeoJSON of type `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Supported features for evaluation:\n- `Point`: Returns `false` if a point is on the boundary or falls outside the boundary.\n- `LineString`: Returns `false` if any part of a line falls outside the boundary, the line intersects the boundary, or a line's endpoint is on the boundary.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "1.9.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + } + }, + "is-supported-script": { + "doc": "Returns `true` if the input string is expected to render legibly. Returns `false` if the input string contains sections that cannot be rendered without potential loss of meaning (e.g. Indic scripts that require complex text shaping, or right-to-left scripts if the the `mapbox-gl-rtl-text` plugin is not in use in Mapbox GL JS).", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.6.0" + } + } + }, + "upcase": { + "doc": "Returns the input string converted to uppercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "downcase": { + "doc": "Returns the input string converted to lowercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "concat": { + "doc": "Returns a `string` consisting of the concatenation of the inputs. Each input is converted to a string as if by `to-string`.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "resolved-locale": { + "doc": "Returns the IETF language tag of the locale being used by the provided `collator`. This can be used to determine the default system locale, or to determine if a requested locale was successfully loaded.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + } + } + }, + "light": { + "anchor": { + "type": "enum", + "default": "viewport", + "values": { + "map": { + "doc": "The position of the light source is aligned to the rotation of the map." + }, + "viewport": { + "doc": "The position of the light source is aligned to the rotation of the viewport." + } + }, + "property-type": "data-constant", + "transition": false, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "doc": "Whether extruded geometries are lit relative to the map or viewport.", + "example": "map", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "position": { + "type": "array", + "default": [ + 1.15, + 210, + 30 + ], + "length": 3, + "value": "number", + "property-type": "data-constant", + "transition": true, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "doc": "Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below).", + "example": [ + 1.5, + 90, + 80 + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "color": { + "type": "color", + "property-type": "data-constant", + "default": "#ffffff", + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "transition": true, + "doc": "Color tint for lighting extruded geometries.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "intensity": { + "type": "number", + "property-type": "data-constant", + "default": 0.5, + "minimum": 0, + "maximum": 1, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "transition": true, + "doc": "Intensity of lighting (on a scale from 0 to 1). Higher numbers will present as more extreme contrast.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.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", + "default": true, + "doc": "Whether or not the fill should be antialiased.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "doc": "The opacity of the entire fill layer. In contrast to the `fill-color`, this value will also affect the 1px stroke around the fill, if the stroke is used.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.21.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + "type": "color", + "default": "#000000", + "doc": "The color of the filled part of this layer. This color can be specified as `rgba` with an alpha component and the color's opacity will not affect the opacity of the 1px stroke, if it is used.", + "transition": true, + "requires": [ + { + "!": "fill-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.19.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + "type": "color", + "doc": "The outline color of the fill. Matches the value of `fill-color` if unspecified.", + "transition": true, + "requires": [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.19.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The fill is translated relative to the map." + }, + "viewport": { + "doc": "The fill is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `fill-translate`.", + "default": "map", + "requires": [ + "fill-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.49.0", + "android": "6.5.0", + "macos": "0.11.0", + "ios": "4.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } + }, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "doc": "The opacity of the entire fill extrusion layer. This is rendered on a per-layer, not per-feature, basis, and data-driven styling is not available.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + "type": "color", + "default": "#000000", + "doc": "The base color of the extruded fill. The extrusion's surfaces will be shaded differently based on this color in combination with the root `light` settings. If this color is specified as `rgba` with an alpha component, the alpha component will be ignored; use `fill-extrusion-opacity` to set layer opacity.", + "transition": true, + "requires": [ + { + "!": "fill-extrusion-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up (on the flat plane), respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The fill extrusion is translated relative to the map." + }, + "viewport": { + "doc": "The fill extrusion is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `fill-extrusion-translate`.", + "default": "map", + "requires": [ + "fill-extrusion-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.49.0", + "android": "6.5.0", + "macos": "0.11.0", + "ios": "4.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + "type": "number", + "default": 0, + "minimum": 0, + "units": "meters", + "doc": "The height with which to extrude this layer.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + "type": "number", + "default": 0, + "minimum": 0, + "units": "meters", + "doc": "The height with which to extrude the base of this layer. Must be less than or equal to `fill-extrusion-height`.", + "transition": true, + "requires": [ + "fill-extrusion-height" + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + "type": "boolean", + "default": true, + "doc": "Whether to apply a vertical gradient to the sides of a fill-extrusion layer. If true, sides will be shaded slightly darker farther down.", + "transition": false, + "sdk-support": { + "basic functionality": { + "js": "0.50.0", + "ios": "4.7.0", + "macos": "0.13.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_line": { + "line-opacity": { + "type": "number", + "doc": "The opacity at which the line will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + "type": "color", + "doc": "The color with which the line will be drawn.", + "default": "#000000", + "transition": true, + "requires": [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.23.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The line is translated relative to the map." + }, + "viewport": { + "doc": "The line is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `line-translate`.", + "default": "map", + "requires": [ + "line-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + "type": "number", + "default": 1, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Stroke thickness.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + "type": "number", + "default": 0, + "minimum": 0, + "doc": "Draws a line casing outside of a line's actual path. Value indicates the width of the inner gap.", + "transition": true, + "units": "pixels", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + "type": "number", + "default": 0, + "doc": "The line's offset. For linear features, a positive value offsets the line to the right, relative to the direction of the line, and a negative value to the left. For polygon features, a positive value results in an inset, and a negative value results in an outset.", + "transition": true, + "units": "pixels", + "sdk-support": { + "basic functionality": { + "js": "0.12.1", + "android": "3.0.0", + "ios": "3.1.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Blur applied to the line, in pixels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + "type": "array", + "value": "number", + "doc": "Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to pixels, multiply the length by the current line width. Note that GeoJSON sources with `lineMetrics: true` specified won't render dashed lines to the expected scale. Also note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "minimum": 0, + "transition": true, + "units": "line widths", + "requires": [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.49.0", + "android": "6.5.0", + "macos": "0.11.0", + "ios": "4.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + "type": "color", + "doc": "Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `\"lineMetrics\": true`.", + "transition": false, + "requires": [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + "source": "geojson", + "has": { + "lineMetrics": true + } + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.4.0", + "macos": "0.11.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": true, + "parameters": [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } + }, + "paint_circle": { + "circle-radius": { + "type": "number", + "default": 5, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Circle radius.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.18.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + "type": "color", + "default": "#000000", + "doc": "The fill color of the circle.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.18.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + "type": "number", + "default": 0, + "doc": "Amount to blur the circle. 1 blurs the circle such that only the centerpoint is full opacity.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.20.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + "type": "number", + "doc": "The opacity at which the circle will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.20.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The circle is translated relative to the map." + }, + "viewport": { + "doc": "The circle is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `circle-translate`.", + "default": "map", + "requires": [ + "circle-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + "type": "enum", + "values": { + "map": { + "doc": "Circles are scaled according to their apparent distance to the camera." + }, + "viewport": { + "doc": "Circles are not scaled." + } + }, + "default": "map", + "doc": "Controls the scaling behavior of the circle when the map is pitched.", + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "The circle is aligned to the plane of the map." + }, + "viewport": { + "doc": "The circle is aligned to the plane of the viewport." + } + }, + "default": "viewport", + "doc": "Orientation of circle when map is pitched.", + "sdk-support": { + "basic functionality": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "The width of the circle's stroke. Strokes are placed outside of the `circle-radius`.", + "sdk-support": { + "basic functionality": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + "type": "color", + "default": "#000000", + "doc": "The stroke color of the circle.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + "type": "number", + "doc": "The opacity of the circle's stroke.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } + }, + "paint_heatmap": { + "heatmap-radius": { + "type": "number", + "default": 30, + "minimum": 1, + "transition": true, + "units": "pixels", + "doc": "Radius of influence of one heatmap point in pixels. Increasing the value makes the heatmap smoother, but less detailed.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "data-driven styling": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + "type": "number", + "default": 1, + "minimum": 0, + "transition": false, + "doc": "A measure of how much an individual point contributes to the heatmap. A value of 10 would be equivalent to having 10 points of weight 1 in the same spot. Especially useful when combined with clustering.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "data-driven styling": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + "type": "number", + "default": 1, + "minimum": 0, + "transition": true, + "doc": "Similar to `heatmap-weight` but controls the intensity of the heatmap globally. Primarily used for adjusting the heatmap based on zoom level.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + "type": "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + "doc": "Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `[\"heatmap-density\"]` as input.", + "transition": false, + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": true, + "parameters": [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + "type": "number", + "doc": "The global opacity at which the heatmap layer will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_symbol": { + "icon-opacity": { + "doc": "The opacity at which the icon will be drawn.", + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + "type": "color", + "default": "#000000", + "transition": true, + "doc": "The color of the icon. This can only be used with sdf icons.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + "type": "color", + "default": "rgba(0, 0, 0, 0)", + "transition": true, + "doc": "The color of the icon's halo. Icon halos can only be used with SDF icons.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Distance of halo to the icon outline.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Fade out the halo towards the outside.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "Distance that the icon's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "Icons are translated relative to the map." + }, + "viewport": { + "doc": "Icons are translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `icon-translate`.", + "default": "map", + "requires": [ + "icon-image", + "icon-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + "type": "number", + "doc": "The opacity at which the text will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + "type": "color", + "doc": "The color with which the text will be drawn.", + "default": "#000000", + "transition": true, + "overridable": true, + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + "type": "color", + "default": "rgba(0, 0, 0, 0)", + "transition": true, + "doc": "The color of the text's halo, which helps it stand out from backgrounds.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Distance of halo to the font outline. Max text halo width is 1/4 of the font-size.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "The halo's fadeout distance towards the outside.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "Distance that the text's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The text is translated relative to the map." + }, + "viewport": { + "doc": "The text is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `text-translate`.", + "default": "map", + "requires": [ + "text-field", + "text-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_raster": { + "raster-opacity": { + "type": "number", + "doc": "The opacity at which the image will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + "type": "number", + "default": 0, + "period": 360, + "transition": true, + "units": "degrees", + "doc": "Rotates hues around the color wheel.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + "type": "number", + "doc": "Increase or reduce the brightness of the image. The value is the minimum brightness.", + "default": 0, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + "type": "number", + "doc": "Increase or reduce the brightness of the image. The value is the maximum brightness.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + "type": "number", + "doc": "Increase or reduce the saturation of the image.", + "default": 0, + "minimum": -1, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + "type": "number", + "doc": "Increase or reduce the contrast of the image.", + "default": 0, + "minimum": -1, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + "type": "enum", + "doc": "The resampling/interpolation method to use for overscaling, also known as texture magnification filter", + "values": { + "linear": { + "doc": "(Bi)linear filtering interpolates pixel values using the weighted average of the four closest original source pixels creating a smooth but blurry look when overscaled" + }, + "nearest": { + "doc": "Nearest neighbor filtering interpolates pixel values using the nearest original source pixel creating a sharp but pixelated look when overscaled" + } + }, + "default": "linear", + "sdk-support": { + "basic functionality": { + "js": "0.47.0", + "android": "6.3.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + "type": "number", + "default": 300, + "minimum": 0, + "transition": false, + "units": "milliseconds", + "doc": "Fade duration when a new tile is added.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_hillshade": { + "hillshade-illumination-direction": { + "type": "number", + "default": 335, + "minimum": 0, + "maximum": 359, + "doc": "The direction of the light source used to generate the hillshading with 0 as the top of the viewport if `hillshade-illumination-anchor` is set to `viewport` and due north if `hillshade-illumination-anchor` is set to `map`.", + "transition": false, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The hillshade illumination is relative to the north direction." + }, + "viewport": { + "doc": "The hillshade illumination is relative to the top of the viewport." + } + }, + "default": "viewport", + "doc": "Direction of light source when map is rotated.", + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + "type": "number", + "doc": "Intensity of the hillshade", + "default": 0.5, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + "type": "color", + "default": "#000000", + "doc": "The shading color of areas that face away from the light source.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + "type": "color", + "default": "#FFFFFF", + "doc": "The shading color of areas that faces towards the light source.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + "type": "color", + "default": "#000000", + "doc": "The shading color used to accentuate rugged terrain like sharp cliffs and gorges.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_background": { + "background-color": { + "type": "color", + "default": "#000000", + "doc": "The color with which the background will be drawn.", + "transition": true, + "requires": [ + { + "!": "background-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "doc": "The opacity at which the background will be drawn.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "transition": { + "duration": { + "type": "number", + "default": 300, + "minimum": 0, + "units": "milliseconds", + "doc": "Time allotted for transitions to complete." + }, + "delay": { + "type": "number", + "default": 0, + "minimum": 0, + "units": "milliseconds", + "doc": "Length of time before a transition begins." + } + }, + "property-type": { + "data-driven": { + "type": "property-type", + "doc": "Property is interpolable and can be represented using a property expression." + }, + "cross-faded": { + "type": "property-type", + "doc": "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms." + }, + "cross-faded-data-driven": { + "type": "property-type", + "doc": "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms. It can be represented using a property expression." + }, + "color-ramp": { + "type": "property-type", + "doc": "Property should be specified using a color ramp from which the output color can be sampled based on a property calculation." + }, + "data-constant": { + "type": "property-type", + "doc": "Property is interpolable but cannot be represented using a property expression." + }, + "constant": { + "type": "property-type", + "doc": "Property is constant across all zoom levels and property values." + } + }, + "promoteId": { + "*": { + "type": "string", + "doc": "A name of a feature property to use as ID for feature state." + } + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/rollup.config.js b/node_modules/@plotly/mapbox-gl/src/style-spec/rollup.config.js new file mode 100644 index 0000000000000000000000000000000000000000..f0829ad896f27acbae70171d1b3c3d2e749f32a8 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/rollup.config.js @@ -0,0 +1,65 @@ +import path from 'path'; +import replace from 'rollup-plugin-replace'; +import buble from 'rollup-plugin-buble'; +import resolve from 'rollup-plugin-node-resolve'; +import commonjs from 'rollup-plugin-commonjs'; +import unassert from 'rollup-plugin-unassert'; +import json from 'rollup-plugin-json'; +import {flow} from '../../build/rollup_plugins'; + +// Build es modules? +const esm = 'esm' in process.env; + +const transforms = { + dangerousForOf: true, + modules: esm ? false : undefined +}; + +const ROOT_DIR = __dirname; + +const config = [{ + input: `${__dirname}/style-spec.js`, + output: { + name: 'mapboxGlStyleSpecification', + file: `${__dirname}/dist/${esm ? 'index.es.js' : 'index.js'}`, + format: esm ? 'esm' : 'umd', + sourcemap: true + }, + plugins: [ + { + name: 'dep-checker', + resolveId(source, importer) { + // Some users reference modules within style-spec package directly, instead of the bundle + // This means that files within the style-spec package should NOT import files from the parent mapbox-gl-js tree. + // This check will cause the build to fail on CI allowing these issues to be caught. + if (importer && !importer.includes('node_modules')) { + const resolvedPath = path.join(importer, source); + const fromRoot = path.relative(ROOT_DIR, resolvedPath); + if (fromRoot.length > 2 && fromRoot.slice(0, 2) === '..') { + throw new Error(`Module ${importer} imports ${source} from outside the style-spec package root directory.`); + } + } + + return null; + } + }, + // https://github.com/zaach/jison/issues/351 + replace({ + include: /\/jsonlint-lines-primitives\/lib\/jsonlint.js/, + delimiters: ['', ''], + values: { + '_token_stack:': '' + } + }), + flow(), + json(), + buble({transforms, objectAssign: "Object.assign"}), + unassert(), + resolve({ + browser: true, + preferBuiltins: false + }), + commonjs() + ] +}]; +export default config; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/style-spec.js b/node_modules/@plotly/mapbox-gl/src/style-spec/style-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..7bf178923533d9ff228c21f333b15e56dd0b9620 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/style-spec.js @@ -0,0 +1,124 @@ +// @flow + +type ExpressionType = 'data-driven' | 'cross-faded' | 'cross-faded-data-driven' | 'color-ramp' | 'data-constant' | 'constant'; +type ExpressionParameters = Array<'zoom' | 'feature' | 'feature-state' | 'heatmap-density' | 'line-progress'>; + +type ExpressionSpecification = { + interpolated: boolean, + parameters: ExpressionParameters +} + +export type StylePropertySpecification = { + type: 'number', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: number +} | { + type: 'string', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: string, + tokens?: boolean +} | { + type: 'boolean', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: boolean +} | { + type: 'enum', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + values: {[_: string]: {}}, + transition: boolean, + default?: string +} | { + type: 'color', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: string, + overridable: boolean +} | { + type: 'array', + value: 'number', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + length?: number, + transition: boolean, + default?: Array +} | { + type: 'array', + value: 'string', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + length?: number, + transition: boolean, + default?: Array +}; + +import v8 from './reference/v8.json'; +import latest from './reference/latest'; +import format from './format'; +import migrate from './migrate'; +import composite from './composite'; +import derefLayers from './deref'; +import diff from './diff'; +import ValidationError from './error/validation_error'; +import ParsingError from './error/parsing_error'; +import {StyleExpression, isExpression, createExpression, createPropertyExpression, normalizePropertyExpression, ZoomConstantExpression, ZoomDependentExpression, StylePropertyFunction} from './expression'; +import featureFilter, {isExpressionFilter} from './feature_filter'; + +import convertFilter from './feature_filter/convert'; +import Color from './util/color'; +import {createFunction, isFunction} from './function'; +import convertFunction from './function/convert'; +import {eachSource, eachLayer, eachProperty} from './visit'; + +import validate from './validate_style'; +import validateMapboxApiSupported from './validate_mapbox_api_supported'; + +const expression = { + StyleExpression, + isExpression, + isExpressionFilter, + createExpression, + createPropertyExpression, + normalizePropertyExpression, + ZoomConstantExpression, + ZoomDependentExpression, + StylePropertyFunction +}; + +const styleFunction = { + convertFunction, + createFunction, + isFunction +}; + +const visit = {eachSource, eachLayer, eachProperty}; + +export { + v8, + latest, + format, + migrate, + composite, + derefLayers, + diff, + ValidationError, + ParsingError, + expression, + featureFilter, + convertFilter, + Color, + styleFunction as function, + validate, + validateMapboxApiSupported, + visit +}; + +validate.parsed = validate; +validate.latest = validate; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/types.js b/node_modules/@plotly/mapbox-gl/src/style-spec/types.js new file mode 100644 index 0000000000000000000000000000000000000000..34a380e1ba078952476f3a52308d8902d2131bae --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/types.js @@ -0,0 +1,432 @@ +// @flow +// Generated code; do not edit. Edit build/generate-flow-typed-style-spec.js instead. +/* eslint-disable */ + +export type ColorSpecification = string; + +export type FormattedSpecification = string; + +export type ResolvedImageSpecification = string; + +export type PromoteIdSpecification = {[_: string]: string} | string; + +export type FilterSpecification = + | ['has', string] + | ['!has', string] + | ['==', string, string | number | boolean] + | ['!=', string, string | number | boolean] + | ['>', string, string | number | boolean] + | ['>=', string, string | number | boolean] + | ['<', string, string | number | boolean] + | ['<=', string, string | number | boolean] + | Array; // Can't type in, !in, all, any, none -- https://github.com/facebook/flow/issues/2443 + +export type TransitionSpecification = { + duration?: number, + delay?: number +}; + +// Note: doesn't capture interpolatable vs. non-interpolatable types. + +export type CameraFunctionSpecification = + | {| type: 'exponential', stops: Array<[number, T]> |} + | {| type: 'interval', stops: Array<[number, T]> |}; + +export type SourceFunctionSpecification = + | {| type: 'exponential', stops: Array<[number, T]>, property: string, default?: T |} + | {| type: 'interval', stops: Array<[number, T]>, property: string, default?: T |} + | {| type: 'categorical', stops: Array<[string | number | boolean, T]>, property: string, default?: T |} + | {| type: 'identity', property: string, default?: T |}; + +export type CompositeFunctionSpecification = + | {| type: 'exponential', stops: Array<[{zoom: number, value: number}, T]>, property: string, default?: T |} + | {| type: 'interval', stops: Array<[{zoom: number, value: number}, T]>, property: string, default?: T |} + | {| type: 'categorical', stops: Array<[{zoom: number, value: string | number | boolean}, T]>, property: string, default?: T |}; + +export type ExpressionSpecification = Array; + +export type PropertyValueSpecification = + | T + | CameraFunctionSpecification + | ExpressionSpecification; + +export type DataDrivenPropertyValueSpecification = + | T + | CameraFunctionSpecification + | SourceFunctionSpecification + | CompositeFunctionSpecification + | ExpressionSpecification; + +export type StyleSpecification = {| + "version": 8, + "name"?: string, + "metadata"?: mixed, + "center"?: Array, + "zoom"?: number, + "bearing"?: number, + "pitch"?: number, + "light"?: LightSpecification, + "sources": {[_: string]: SourceSpecification}, + "sprite"?: string, + "glyphs"?: string, + "transition"?: TransitionSpecification, + "layers": Array +|} + +export type LightSpecification = {| + "anchor"?: PropertyValueSpecification<"map" | "viewport">, + "position"?: PropertyValueSpecification<[number, number, number]>, + "color"?: PropertyValueSpecification, + "intensity"?: PropertyValueSpecification +|} + +export type VectorSourceSpecification = { + "type": "vector", + "url"?: string, + "tiles"?: Array, + "bounds"?: [number, number, number, number], + "scheme"?: "xyz" | "tms", + "minzoom"?: number, + "maxzoom"?: number, + "attribution"?: string, + "promoteId"?: PromoteIdSpecification, + "volatile"?: boolean +} + +export type RasterSourceSpecification = { + "type": "raster", + "url"?: string, + "tiles"?: Array, + "bounds"?: [number, number, number, number], + "minzoom"?: number, + "maxzoom"?: number, + "tileSize"?: number, + "scheme"?: "xyz" | "tms", + "attribution"?: string, + "volatile"?: boolean +} + +export type RasterDEMSourceSpecification = { + "type": "raster-dem", + "url"?: string, + "tiles"?: Array, + "bounds"?: [number, number, number, number], + "minzoom"?: number, + "maxzoom"?: number, + "tileSize"?: number, + "attribution"?: string, + "encoding"?: "terrarium" | "mapbox", + "volatile"?: boolean +} + +export type GeoJSONSourceSpecification = {| + "type": "geojson", + "data"?: mixed, + "maxzoom"?: number, + "attribution"?: string, + "buffer"?: number, + "filter"?: mixed, + "tolerance"?: number, + "cluster"?: boolean, + "clusterRadius"?: number, + "clusterMaxZoom"?: number, + "clusterMinPoints"?: number, + "clusterProperties"?: mixed, + "lineMetrics"?: boolean, + "generateId"?: boolean, + "promoteId"?: PromoteIdSpecification +|} + +export type VideoSourceSpecification = {| + "type": "video", + "urls": Array, + "coordinates": [[number, number], [number, number], [number, number], [number, number]] +|} + +export type ImageSourceSpecification = {| + "type": "image", + "url": string, + "coordinates": [[number, number], [number, number], [number, number], [number, number]] +|} + +export type SourceSpecification = + | VectorSourceSpecification + | RasterSourceSpecification + | RasterDEMSourceSpecification + | GeoJSONSourceSpecification + | VideoSourceSpecification + | ImageSourceSpecification + +export type FillLayerSpecification = {| + "id": string, + "type": "fill", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "fill-sort-key"?: DataDrivenPropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "fill-antialias"?: PropertyValueSpecification, + "fill-opacity"?: DataDrivenPropertyValueSpecification, + "fill-color"?: DataDrivenPropertyValueSpecification, + "fill-outline-color"?: DataDrivenPropertyValueSpecification, + "fill-translate"?: PropertyValueSpecification<[number, number]>, + "fill-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "fill-pattern"?: DataDrivenPropertyValueSpecification + |} +|} + +export type LineLayerSpecification = {| + "id": string, + "type": "line", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "line-cap"?: PropertyValueSpecification<"butt" | "round" | "square">, + "line-join"?: DataDrivenPropertyValueSpecification<"bevel" | "round" | "miter">, + "line-miter-limit"?: PropertyValueSpecification, + "line-round-limit"?: PropertyValueSpecification, + "line-sort-key"?: DataDrivenPropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "line-opacity"?: DataDrivenPropertyValueSpecification, + "line-color"?: DataDrivenPropertyValueSpecification, + "line-translate"?: PropertyValueSpecification<[number, number]>, + "line-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "line-width"?: DataDrivenPropertyValueSpecification, + "line-gap-width"?: DataDrivenPropertyValueSpecification, + "line-offset"?: DataDrivenPropertyValueSpecification, + "line-blur"?: DataDrivenPropertyValueSpecification, + "line-dasharray"?: PropertyValueSpecification>, + "line-pattern"?: DataDrivenPropertyValueSpecification, + "line-gradient"?: ExpressionSpecification + |} +|} + +export type SymbolLayerSpecification = {| + "id": string, + "type": "symbol", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "symbol-placement"?: PropertyValueSpecification<"point" | "line" | "line-center">, + "symbol-spacing"?: PropertyValueSpecification, + "symbol-avoid-edges"?: PropertyValueSpecification, + "symbol-sort-key"?: DataDrivenPropertyValueSpecification, + "symbol-z-order"?: PropertyValueSpecification<"auto" | "viewport-y" | "source">, + "icon-allow-overlap"?: PropertyValueSpecification, + "icon-ignore-placement"?: PropertyValueSpecification, + "icon-optional"?: PropertyValueSpecification, + "icon-rotation-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "icon-size"?: DataDrivenPropertyValueSpecification, + "icon-text-fit"?: PropertyValueSpecification<"none" | "width" | "height" | "both">, + "icon-text-fit-padding"?: PropertyValueSpecification<[number, number, number, number]>, + "icon-image"?: DataDrivenPropertyValueSpecification, + "icon-rotate"?: DataDrivenPropertyValueSpecification, + "icon-padding"?: PropertyValueSpecification, + "icon-keep-upright"?: PropertyValueSpecification, + "icon-offset"?: DataDrivenPropertyValueSpecification<[number, number]>, + "icon-anchor"?: DataDrivenPropertyValueSpecification<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, + "icon-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "text-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "text-rotation-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "text-field"?: DataDrivenPropertyValueSpecification, + "text-font"?: DataDrivenPropertyValueSpecification>, + "text-size"?: DataDrivenPropertyValueSpecification, + "text-max-width"?: DataDrivenPropertyValueSpecification, + "text-line-height"?: PropertyValueSpecification, + "text-letter-spacing"?: DataDrivenPropertyValueSpecification, + "text-justify"?: DataDrivenPropertyValueSpecification<"auto" | "left" | "center" | "right">, + "text-radial-offset"?: DataDrivenPropertyValueSpecification, + "text-variable-anchor"?: PropertyValueSpecification>, + "text-anchor"?: DataDrivenPropertyValueSpecification<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, + "text-max-angle"?: PropertyValueSpecification, + "text-writing-mode"?: PropertyValueSpecification>, + "text-rotate"?: DataDrivenPropertyValueSpecification, + "text-padding"?: PropertyValueSpecification, + "text-keep-upright"?: PropertyValueSpecification, + "text-transform"?: DataDrivenPropertyValueSpecification<"none" | "uppercase" | "lowercase">, + "text-offset"?: DataDrivenPropertyValueSpecification<[number, number]>, + "text-allow-overlap"?: PropertyValueSpecification, + "text-ignore-placement"?: PropertyValueSpecification, + "text-optional"?: PropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "icon-opacity"?: DataDrivenPropertyValueSpecification, + "icon-color"?: DataDrivenPropertyValueSpecification, + "icon-halo-color"?: DataDrivenPropertyValueSpecification, + "icon-halo-width"?: DataDrivenPropertyValueSpecification, + "icon-halo-blur"?: DataDrivenPropertyValueSpecification, + "icon-translate"?: PropertyValueSpecification<[number, number]>, + "icon-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "text-opacity"?: DataDrivenPropertyValueSpecification, + "text-color"?: DataDrivenPropertyValueSpecification, + "text-halo-color"?: DataDrivenPropertyValueSpecification, + "text-halo-width"?: DataDrivenPropertyValueSpecification, + "text-halo-blur"?: DataDrivenPropertyValueSpecification, + "text-translate"?: PropertyValueSpecification<[number, number]>, + "text-translate-anchor"?: PropertyValueSpecification<"map" | "viewport"> + |} +|} + +export type CircleLayerSpecification = {| + "id": string, + "type": "circle", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "circle-sort-key"?: DataDrivenPropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "circle-radius"?: DataDrivenPropertyValueSpecification, + "circle-color"?: DataDrivenPropertyValueSpecification, + "circle-blur"?: DataDrivenPropertyValueSpecification, + "circle-opacity"?: DataDrivenPropertyValueSpecification, + "circle-translate"?: PropertyValueSpecification<[number, number]>, + "circle-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "circle-pitch-scale"?: PropertyValueSpecification<"map" | "viewport">, + "circle-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport">, + "circle-stroke-width"?: DataDrivenPropertyValueSpecification, + "circle-stroke-color"?: DataDrivenPropertyValueSpecification, + "circle-stroke-opacity"?: DataDrivenPropertyValueSpecification + |} +|} + +export type HeatmapLayerSpecification = {| + "id": string, + "type": "heatmap", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "heatmap-radius"?: DataDrivenPropertyValueSpecification, + "heatmap-weight"?: DataDrivenPropertyValueSpecification, + "heatmap-intensity"?: PropertyValueSpecification, + "heatmap-color"?: ExpressionSpecification, + "heatmap-opacity"?: PropertyValueSpecification + |} +|} + +export type FillExtrusionLayerSpecification = {| + "id": string, + "type": "fill-extrusion", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "fill-extrusion-opacity"?: PropertyValueSpecification, + "fill-extrusion-color"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-translate"?: PropertyValueSpecification<[number, number]>, + "fill-extrusion-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "fill-extrusion-pattern"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-height"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-base"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-vertical-gradient"?: PropertyValueSpecification + |} +|} + +export type RasterLayerSpecification = {| + "id": string, + "type": "raster", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "raster-opacity"?: PropertyValueSpecification, + "raster-hue-rotate"?: PropertyValueSpecification, + "raster-brightness-min"?: PropertyValueSpecification, + "raster-brightness-max"?: PropertyValueSpecification, + "raster-saturation"?: PropertyValueSpecification, + "raster-contrast"?: PropertyValueSpecification, + "raster-resampling"?: PropertyValueSpecification<"linear" | "nearest">, + "raster-fade-duration"?: PropertyValueSpecification + |} +|} + +export type HillshadeLayerSpecification = {| + "id": string, + "type": "hillshade", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "hillshade-illumination-direction"?: PropertyValueSpecification, + "hillshade-illumination-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "hillshade-exaggeration"?: PropertyValueSpecification, + "hillshade-shadow-color"?: PropertyValueSpecification, + "hillshade-highlight-color"?: PropertyValueSpecification, + "hillshade-accent-color"?: PropertyValueSpecification + |} +|} + +export type BackgroundLayerSpecification = {| + "id": string, + "type": "background", + "metadata"?: mixed, + "minzoom"?: number, + "maxzoom"?: number, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "background-color"?: PropertyValueSpecification, + "background-pattern"?: PropertyValueSpecification, + "background-opacity"?: PropertyValueSpecification + |} +|} + +export type LayerSpecification = + | FillLayerSpecification + | LineLayerSpecification + | SymbolLayerSpecification + | CircleLayerSpecification + | HeatmapLayerSpecification + | FillExtrusionLayerSpecification + | RasterLayerSpecification + | HillshadeLayerSpecification + | BackgroundLayerSpecification; + diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/color.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/color.js new file mode 100644 index 0000000000000000000000000000000000000000..a8e59b74f053e123c2c2e209d213424e476deca0 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/color.js @@ -0,0 +1,95 @@ +// @flow + +import {parseCSSColor} from 'csscolorparser'; + +/** + * An RGBA color value. Create instances from color strings using the static + * method `Color.parse`. The constructor accepts RGB channel values in the range + * `[0, 1]`, premultiplied by A. + * + * @param {number} r The red channel. + * @param {number} g The green channel. + * @param {number} b The blue channel. + * @param {number} a The alpha channel. + * @private + */ +class Color { + r: number; + g: number; + b: number; + a: number; + + constructor(r: number, g: number, b: number, a: number = 1) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + + static black: Color; + static white: Color; + static transparent: Color; + static red: Color; + + /** + * Parses valid CSS color strings and returns a `Color` instance. + * @returns A `Color` instance, or `undefined` if the input is not a valid color string. + */ + static parse(input?: string | Color | null): Color | void { + if (!input) { + return undefined; + } + + if (input instanceof Color) { + return input; + } + + if (typeof input !== 'string') { + return undefined; + } + + const rgba = parseCSSColor(input); + if (!rgba) { + return undefined; + } + + return new Color( + rgba[0] / 255 * rgba[3], + rgba[1] / 255 * rgba[3], + rgba[2] / 255 * rgba[3], + rgba[3] + ); + } + + /** + * Returns an RGBA string representing the color value. + * + * @returns An RGBA string. + * @example + * var purple = new Color.parse('purple'); + * purple.toString; // = "rgba(128,0,128,1)" + * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)'); + * translucentGreen.toString(); // = "rgba(26,207,26,0.73)" + */ + toString(): string { + const [r, g, b, a] = this.toArray(); + return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`; + } + + toArray(): [number, number, number, number] { + const {r, g, b, a} = this; + return a === 0 ? [0, 0, 0, 0] : [ + r * 255 / a, + g * 255 / a, + b * 255 / a, + a + ]; + } +} + +Color.black = new Color(0, 0, 0, 1); +Color.white = new Color(1, 1, 1, 1); +Color.transparent = new Color(0, 0, 0, 0); +Color.red = new Color(1, 0, 0, 1); + +export default Color; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/color_spaces.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/color_spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..21ee75b0c69579c140c309b760e548de1a10ab52 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/color_spaces.js @@ -0,0 +1,139 @@ +// @flow + +import Color from './color'; + +import {number as interpolateNumber} from './interpolate'; + +type LABColor = { + l: number, + a: number, + b: number, + alpha: number +}; + +type HCLColor = { + h: number, + c: number, + l: number, + alpha: number +}; + +// Constants +const Xn = 0.950470, // D65 standard referent + Yn = 1, + Zn = 1.088830, + t0 = 4 / 29, + t1 = 6 / 29, + t2 = 3 * t1 * t1, + t3 = t1 * t1 * t1, + deg2rad = Math.PI / 180, + rad2deg = 180 / Math.PI; + +// Utilities +function xyz2lab(t: number) { + return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; +} + +function lab2xyz(t: number) { + return t > t1 ? t * t * t : t2 * (t - t0); +} + +function xyz2rgb(x: number) { + return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); +} + +function rgb2xyz(x: number) { + x /= 255; + return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} + +// LAB +function rgbToLab(rgbColor: Color): LABColor { + const b = rgb2xyz(rgbColor.r), + a = rgb2xyz(rgbColor.g), + l = rgb2xyz(rgbColor.b), + x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), + y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn), + z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn); + + return { + l: 116 * y - 16, + a: 500 * (x - y), + b: 200 * (y - z), + alpha: rgbColor.a + }; +} + +function labToRgb(labColor: LABColor): Color { + let y = (labColor.l + 16) / 116, + x = isNaN(labColor.a) ? y : y + labColor.a / 500, + z = isNaN(labColor.b) ? y : y - labColor.b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return new Color( + xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB + xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z), + xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z), + labColor.alpha + ); +} + +function interpolateLab(from: LABColor, to: LABColor, t: number) { + return { + l: interpolateNumber(from.l, to.l, t), + a: interpolateNumber(from.a, to.a, t), + b: interpolateNumber(from.b, to.b, t), + alpha: interpolateNumber(from.alpha, to.alpha, t) + }; +} + +// HCL +function rgbToHcl(rgbColor: Color): HCLColor { + const {l, a, b} = rgbToLab(rgbColor); + const h = Math.atan2(b, a) * rad2deg; + return { + h: h < 0 ? h + 360 : h, + c: Math.sqrt(a * a + b * b), + l, + alpha: rgbColor.a + }; +} + +function hclToRgb(hclColor: HCLColor): Color { + const h = hclColor.h * deg2rad, + c = hclColor.c, + l = hclColor.l; + return labToRgb({ + l, + a: Math.cos(h) * c, + b: Math.sin(h) * c, + alpha: hclColor.alpha + }); +} + +function interpolateHue(a: number, b: number, t: number) { + const d = b - a; + return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d); +} + +function interpolateHcl(from: HCLColor, to: HCLColor, t: number) { + return { + h: interpolateHue(from.h, to.h, t), + c: interpolateNumber(from.c, to.c, t), + l: interpolateNumber(from.l, to.l, t), + alpha: interpolateNumber(from.alpha, to.alpha, t) + }; +} + +export const lab = { + forward: rgbToLab, + reverse: labToRgb, + interpolate: interpolateLab +}; + +export const hcl = { + forward: rgbToHcl, + reverse: hclToRgb, + interpolate: interpolateHcl +}; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/deep_equal.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/deep_equal.js new file mode 100644 index 0000000000000000000000000000000000000000..773af912f59bb444a04c86f675494d1975655f03 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/deep_equal.js @@ -0,0 +1,28 @@ +// @flow + +/** + * Deeply compares two object literals. + * + * @private + */ +function deepEqual(a: ?mixed, b: ?mixed): boolean { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) return false; + for (const key in a) { + if (!deepEqual(a[key], b[key])) return false; + } + return true; + } + return a === b; +} + +export default deepEqual; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/extend.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/extend.js new file mode 100644 index 0000000000000000000000000000000000000000..076b6f278a47b49af73cfab5fc51b5ca0982735c --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/extend.js @@ -0,0 +1,10 @@ +// @flow + +export default function (output: any, ...inputs: Array) { + for (const input of inputs) { + for (const k in input) { + output[k] = input[k]; + } + } + return output; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/get_type.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/get_type.js new file mode 100644 index 0000000000000000000000000000000000000000..18b03eb625ebc7aad027b948fd33e06883ddc918 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/get_type.js @@ -0,0 +1,17 @@ +// @flow + +export default function getType(val: mixed): string { + if (val instanceof Number) { + return 'number'; + } else if (val instanceof String) { + return 'string'; + } else if (val instanceof Boolean) { + return 'boolean'; + } else if (Array.isArray(val)) { + return 'array'; + } else if (val === null) { + return 'null'; + } else { + return typeof val; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/interpolate.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/interpolate.js new file mode 100644 index 0000000000000000000000000000000000000000..9cbed3caa1676915ee89caeebac6528f9ce8fc78 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/interpolate.js @@ -0,0 +1,22 @@ +// @flow + +import Color from './color'; + +export function number(a: number, b: number, t: number) { + return (a * (1 - t)) + (b * t); +} + +export function color(from: Color, to: Color, t: number) { + return new Color( + number(from.r, to.r, t), + number(from.g, to.g, t), + number(from.b, to.b, t), + number(from.a, to.a, t) + ); +} + +export function array(from: Array, to: Array, t: number): Array { + return from.map((d, i) => { + return number(d, to[i], t); + }); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/properties.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/properties.js new file mode 100644 index 0000000000000000000000000000000000000000..dbb3ef914421e92f57151086b251c1bf3df94ed8 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/properties.js @@ -0,0 +1,15 @@ +// @flow + +import type {StylePropertySpecification} from '../style-spec'; + +export function supportsPropertyExpression(spec: StylePropertySpecification): boolean { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; +} + +export function supportsZoomExpression(spec: StylePropertySpecification): boolean { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; +} + +export function supportsInterpolation(spec: StylePropertySpecification): boolean { + return !!spec.expression && spec.expression.interpolated; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/ref_properties.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/ref_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..c3cab034c469742b81dcde0cad5b8663c31430b3 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/ref_properties.js @@ -0,0 +1,2 @@ + +export default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/result.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/result.js new file mode 100644 index 0000000000000000000000000000000000000000..9d0d3a6c4f7cbbbc88882087e3e2daa25b7997f6 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/result.js @@ -0,0 +1,19 @@ +// @flow + +/** + * A type used for returning and propagating errors. The first element of the union + * represents success and contains a value, and the second represents an error and + * contains an error value. + * @private + */ +export type Result = + | {| result: 'success', value: T |} + | {| result: 'error', value: E |}; + +export function success(value: T): Result { + return {result: 'success', value}; +} + +export function error(value: E): Result { + return {result: 'error', value}; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/util/unbundle_jsonlint.js b/node_modules/@plotly/mapbox-gl/src/style-spec/util/unbundle_jsonlint.js new file mode 100644 index 0000000000000000000000000000000000000000..72eb2d92645ea23e134889a1a981a16cb9595bcd --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/util/unbundle_jsonlint.js @@ -0,0 +1,24 @@ +// @flow + +// Turn jsonlint-lines-primitives objects into primitive objects +export function unbundle(value: mixed) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } else { + return value; + } +} + +export function deepUnbundle(value: mixed): mixed { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + const unbundledValue: { [key: string]: mixed } = {}; + for (const key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + + return unbundle(value); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/latest.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/latest.js new file mode 100644 index 0000000000000000000000000000000000000000..91db6e9eef8e78729711fef8a5920d44feaaa811 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/latest.js @@ -0,0 +1,11 @@ + +import validateStyle from '../validate_style.min'; + +/* + * Validate a style against the latest specification. This method is optimized + * to keep its bundle size small by refraining from requiring jslint or old + * style spec versions. + * @see validateStyleMin + * @deprecated This file exists for backwards compatibility and will be dropped in the next minor release. + */ +export default validateStyle; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..2c2c8aaaa1ed0c11f870d1c54511d56f20703f8f --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate.js @@ -0,0 +1,75 @@ + +import extend from '../util/extend'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import {isExpression} from '../expression'; +import {isFunction} from '../function'; + +import validateFunction from './validate_function'; +import validateExpression from './validate_expression'; +import validateObject from './validate_object'; +import validateArray from './validate_array'; +import validateBoolean from './validate_boolean'; +import validateNumber from './validate_number'; +import validateColor from './validate_color'; +import validateConstants from './validate_constants'; +import validateEnum from './validate_enum'; +import validateFilter from './validate_filter'; +import validateLayer from './validate_layer'; +import validateSource from './validate_source'; +import validateLight from './validate_light'; +import validateString from './validate_string'; +import validateFormatted from './validate_formatted'; +import validateImage from './validate_image'; + +const VALIDATORS = { + '*'() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource, + 'light': validateLight, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage +}; + +// Main recursive validation function. Tracks: +// +// - key: string representing location of validation in style tree. Used only +// for more informative error reporting. +// - value: current value from style being evaluated. May be anything from a +// high level object that needs to be descended into deeper or a simple +// scalar value. +// - valueSpec: current spec being evaluated. Tracks value. +// - styleSpec: current full spec being evaluated. + +export default function validate(options) { + const value = options.value; + const valueSpec = options.valueSpec; + const styleSpec = options.styleSpec; + + if (valueSpec.expression && isFunction(unbundle(value))) { + return validateFunction(options); + + } else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + + } else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + + } else { + const valid = validateObject(extend({}, options, { + valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec + })); + return valid; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_array.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_array.js new file mode 100644 index 0000000000000000000000000000000000000000..2f5638a61acfeb5e972f8362a8bcb450fbbaedee --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_array.js @@ -0,0 +1,52 @@ + +import getType from '../util/get_type'; +import validate from './validate'; +import ValidationError from '../error/validation_error'; + +export default function validateArray(options) { + const array = options.value; + const arraySpec = options.valueSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const key = options.key; + const validateArrayElement = options.arrayElementValidator || validate; + + if (getType(array) !== 'array') { + return [new ValidationError(key, array, `array expected, ${getType(array)} found`)]; + } + + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)]; + } + + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)]; + } + + let arrayElementSpec = { + "type": arraySpec.value, + "values": arraySpec.values + }; + + if (styleSpec.$version < 7) { + arrayElementSpec.function = arraySpec.function; + } + + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + + let errors = []; + for (let i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + style, + styleSpec, + key: `${key}[${i}]` + })); + } + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_boolean.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_boolean.js new file mode 100644 index 0000000000000000000000000000000000000000..5412b23d24f41705d6dedcae40d13c433db614ee --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_boolean.js @@ -0,0 +1,15 @@ + +import getType from '../util/get_type'; +import ValidationError from '../error/validation_error'; + +export default function validateBoolean(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + + if (type !== 'boolean') { + return [new ValidationError(key, value, `boolean expected, ${type} found`)]; + } + + return []; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_color.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_color.js new file mode 100644 index 0000000000000000000000000000000000000000..f0e935aada5a4b01e7d7be860342b54893f28dd2 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_color.js @@ -0,0 +1,20 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import {parseCSSColor} from 'csscolorparser'; + +export default function validateColor(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + + if (type !== 'string') { + return [new ValidationError(key, value, `color expected, ${type} found`)]; + } + + if (parseCSSColor(value) === null) { + return [new ValidationError(key, value, `color expected, "${value}" found`)]; + } + + return []; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_constants.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_constants.js new file mode 100644 index 0000000000000000000000000000000000000000..7888bb32621027d9ed83c3e85411c3383a3c35ab --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_constants.js @@ -0,0 +1,13 @@ + +import ValidationError from '../error/validation_error'; + +export default function validateConstants(options) { + const key = options.key; + const constants = options.value; + + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } else { + return []; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_enum.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_enum.js new file mode 100644 index 0000000000000000000000000000000000000000..655830c96ab5bd1cb1e5c3f841c417df50fc9adf --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_enum.js @@ -0,0 +1,21 @@ + +import ValidationError from '../error/validation_error'; +import {unbundle} from '../util/unbundle_jsonlint'; + +export default function validateEnum(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + const errors = []; + + if (Array.isArray(valueSpec.values)) { // <=v7 + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`)); + } + } else { // >=v8 + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`)); + } + } + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_expression.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_expression.js new file mode 100644 index 0000000000000000000000000000000000000000..63a73f441c1f7e5b1762a4d121d9b2bf7687a8f7 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_expression.js @@ -0,0 +1,43 @@ +// @flow + +import ValidationError from '../error/validation_error'; + +import {createExpression, createPropertyExpression} from '../expression'; +import {deepUnbundle} from '../util/unbundle_jsonlint'; +import {isStateConstant, isGlobalPropertyConstant, isFeatureConstant} from '../expression/is_constant'; + +export default function validateExpression(options: any): Array { + const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map((error) => { + return new ValidationError(`${options.key}${error.key}`, options.value, error.message); + }); + } + + const expressionObj = (expression.value: any).expression || (expression.value: any)._styleExpression.expression; + + if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') && + !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, `Invalid data expression for "${options.propertyKey}". Output values must be contained as literals within the expression.`)]; + } + + if (options.expressionContext === 'property' && options.propertyType === 'layout' && + (!isStateConstant(expressionObj))) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + + return []; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_filter.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_filter.js new file mode 100644 index 0000000000000000000000000000000000000000..804b7baac38e9739309f1f9e9b4c3345abd112dd --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_filter.js @@ -0,0 +1,117 @@ + +import ValidationError from '../error/validation_error'; +import validateExpression from './validate_expression'; +import validateEnum from './validate_enum'; +import getType from '../util/get_type'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import extend from '../util/extend'; +import {isExpressionFilter} from '../feature_filter'; + +export default function validateFilter(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extend({}, options, { + expressionContext: 'filter', + valueSpec: {value: 'boolean'} + })); + } else { + return validateNonExpressionFilter(options); + } +} + +function validateNonExpressionFilter(options) { + const value = options.value; + const key = options.key; + + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + + const styleSpec = options.styleSpec; + let type; + + let errors = []; + + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + + errors = errors.concat(validateEnum({ + key: `${key}[0]`, + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${value[0]}"`)); + } + /* falls through */ + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, `filter array for operator "${value[0]}" must have 3 elements`)); + } + /* falls through */ + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + } + for (let i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`)); + } + } + break; + + case 'any': + case 'all': + case 'none': + for (let i = 1; i < value.length; i++) { + errors = errors.concat(validateNonExpressionFilter({ + key: `${key}[${i}]`, + value: value[i], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } else if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + break; + case 'within': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } else if (type !== 'object') { + errors.push(new ValidationError(`${key}[1]`, value[1], `object expected, ${type} found`)); + } + break; + } + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_formatted.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_formatted.js new file mode 100644 index 0000000000000000000000000000000000000000..61ed402df3d39604299a50bd9c2d3b5990454a2d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_formatted.js @@ -0,0 +1,11 @@ +// @flow +import validateExpression from './validate_expression'; +import validateString from './validate_string'; + +export default function validateFormatted(options: any) { + if (validateString(options).length === 0) { + return []; + } + + return validateExpression(options); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_function.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_function.js new file mode 100644 index 0000000000000000000000000000000000000000..5c2fa42e6fff4b4eb53f510f726fc13867e31e5d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_function.js @@ -0,0 +1,207 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import validate from './validate'; +import validateObject from './validate_object'; +import validateArray from './validate_array'; +import validateNumber from './validate_number'; +import {isExpression} from '../expression'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import { + supportsPropertyExpression, + supportsZoomExpression, + supportsInterpolation +} from '../util/properties'; + +export default function validateFunction(options) { + const functionValueSpec = options.valueSpec; + const functionType = unbundle(options.value.type); + let stopKeyType; + let stopDomainValues = {}; + let previousStopDomainValue; + let previousStopDomainZoom; + + const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + const isPropertyFunction = !isZoomFunction; + const isZoomAndPropertyFunction = + getType(options.value.stops) === 'array' && + getType(options.value.stops[0]) === 'array' && + getType(options.value.stops[0][0]) === 'object'; + + const errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + + return errors; + + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + + let errors = []; + const value = options.value; + + errors = errors.concat(validateArray({ + key: options.key, + value, + valueSpec: options.valueSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + + return errors; + } + + function validateFunctionStop(options) { + let errors = []; + const value = options.value; + const key = options.key; + + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + + if (value.length !== 2) { + return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)]; + } + + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: `${key}[0]`, + value: value[0], + valueSpec: {zoom: {}}, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: {zoom: validateNumber, value: validateStopDomainValue} + })); + } else { + errors = errors.concat(validateStopDomainValue({ + key: `${key}[0]`, + value: value[0], + valueSpec: {}, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]); + } + + return errors.concat(validate({ + key: `${key}[1]`, + value: value[1], + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + + function validateStopDomainValue(options, stop) { + const type = getType(options.value); + const value = unbundle(options.value); + + const reportValue = options.value !== null ? options.value : stop; + + if (!stopKeyType) { + stopKeyType = type; + } else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)]; + } + + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + + if (type !== 'number' && functionType !== 'categorical') { + let message = `number expected, ${type} found`; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)]; + } + + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } else { + previousStopDomainValue = value; + } + + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } else { + stopDomainValues[value] = true; + } + + return []; + } + + function validateFunctionDefault(options) { + return validate({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_glyphs_url.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_glyphs_url.js new file mode 100644 index 0000000000000000000000000000000000000000..84f74aadef159d147d18b374fbad7396a47976ca --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_glyphs_url.js @@ -0,0 +1,21 @@ + +import ValidationError from '../error/validation_error'; +import validateString from './validate_string'; + +export default function(options) { + const value = options.value; + const key = options.key; + + const errors = validateString(options); + if (errors.length) return errors; + + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_image.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_image.js new file mode 100644 index 0000000000000000000000000000000000000000..b02763ffd92e8db0d2947398fae727ef316bbbe5 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_image.js @@ -0,0 +1,11 @@ +// @flow +import validateExpression from './validate_expression'; +import validateString from './validate_string'; + +export default function validateImage(options: any) { + if (validateString(options).length === 0) { + return []; + } + + return validateExpression(options); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_layer.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..6cfc75e1f013a5f0ec71d87ef51edc6422995a0f --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_layer.js @@ -0,0 +1,134 @@ + +import ValidationError from '../error/validation_error'; +import {unbundle} from '../util/unbundle_jsonlint'; +import validateObject from './validate_object'; +import validateFilter from './validate_filter'; +import validatePaintProperty from './validate_paint_property'; +import validateLayoutProperty from './validate_layout_property'; +import validateSpec from './validate'; +import extend from '../util/extend'; + +export default function validateLayer(options) { + let errors = []; + + const layer = options.value; + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + let type = unbundle(layer.type); + const ref = unbundle(layer.ref); + + if (layer.id) { + const layerId = unbundle(layer.id); + for (let i = 0; i < options.arrayIndex; i++) { + const otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, `duplicate layer id "${layer.id}", previously used at line ${otherLayer.id.__line__}`)); + } + } + } + + if ('ref' in layer) { + ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], `"${p}" is prohibited for ref layers`)); + } + }); + + let parent; + + style.layers.forEach((layer) => { + if (unbundle(layer.id) === ref) parent = layer; + }); + + if (!parent) { + errors.push(new ValidationError(key, layer.ref, `ref layer "${ref}" not found`)); + } else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } else { + type = unbundle(parent.type); + } + } else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } else { + const source = style.sources && style.sources[layer.source]; + const sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, `source "${layer.source}" not found`)); + } else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster source`)); + } else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a vector source`)); + } else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" must specify a "source-layer"`)); + } else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && + (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)); + } + } + } + + errors = errors.concat(validateObject({ + key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*'() { + return []; + }, + // We don't want to enforce the spec's `"requires": true` for backward compatibility with refs; + // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772. + type() { + return validateSpec({ + key: `${key}.type`, + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter, + layout(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*'(options) { + return validateLayoutProperty(extend({layerType: type}, options)); + } + } + }); + }, + paint(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*'(options) { + return validatePaintProperty(extend({layerType: type}, options)); + } + } + }); + } + } + })); + + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_layout_property.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_layout_property.js new file mode 100644 index 0000000000000000000000000000000000000000..da4151a0b4d46d193fa567279487a63bfa09fb4d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_layout_property.js @@ -0,0 +1,6 @@ + +import validateProperty from './validate_property'; + +export default function validateLayoutProperty(options) { + return validateProperty(options, 'layout'); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_light.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_light.js new file mode 100644 index 0000000000000000000000000000000000000000..4b3c364c32cbd57b4989d5c50aed0cb8f0eca580 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_light.js @@ -0,0 +1,47 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import validate from './validate'; + +export default function validateLight(options) { + const light = options.value; + const styleSpec = options.styleSpec; + const lightSpec = styleSpec.light; + const style = options.style; + + let errors = []; + + const rootType = getType(light); + if (light === undefined) { + return errors; + } else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]); + return errors; + } + + for (const key in light) { + const transitionMatch = key.match(/^(.*)-transition$/); + + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(validate({ + key, + value: light[key], + valueSpec: styleSpec.transition, + style, + styleSpec + })); + } else if (lightSpec[key]) { + errors = errors.concat(validate({ + key, + value: light[key], + valueSpec: lightSpec[key], + style, + styleSpec + })); + } else { + errors = errors.concat([new ValidationError(key, light[key], `unknown property "${key}"`)]); + } + } + + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_number.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_number.js new file mode 100644 index 0000000000000000000000000000000000000000..1db12f0364db9f173e4599dc27f67e3c0f957ebe --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_number.js @@ -0,0 +1,29 @@ + +import getType from '../util/get_type'; +import ValidationError from '../error/validation_error'; + +export default function validateNumber(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + let type = getType(value); + + // eslint-disable-next-line no-self-compare + if (type === 'number' && value !== value) { + type = 'NaN'; + } + + if (type !== 'number') { + return [new ValidationError(key, value, `number expected, ${type} found`)]; + } + + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)]; + } + + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)]; + } + + return []; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_object.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_object.js new file mode 100644 index 0000000000000000000000000000000000000000..3f36e459e1301662c7bc80a3bde3628e0c451990 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_object.js @@ -0,0 +1,61 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import validateSpec from './validate'; + +export default function validateObject(options) { + const key = options.key; + const object = options.value; + const elementSpecs = options.valueSpec || {}; + const elementValidators = options.objectElementValidators || {}; + const style = options.style; + const styleSpec = options.styleSpec; + let errors = []; + + const type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, `object expected, ${type} found`)]; + } + + for (const objectKey in object) { + const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint' + const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + + let validateElement; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } else if (elementSpecs[elementSpecKey]) { + validateElement = validateSpec; + } else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } else if (elementSpecs['*']) { + validateElement = validateSpec; + } else { + errors.push(new ValidationError(key, object[objectKey], `unknown property "${objectKey}"`)); + continue; + } + + errors = errors.concat(validateElement({ + key: (key ? `${key}.` : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style, + styleSpec, + object, + objectKey + }, object)); + } + + for (const elementSpecKey in elementSpecs) { + // Don't check `required` when there's a custom validator for that property. + if (elementValidators[elementSpecKey]) { + continue; + } + + if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) { + errors.push(new ValidationError(key, object, `missing required property "${elementSpecKey}"`)); + } + } + + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_paint_property.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_paint_property.js new file mode 100644 index 0000000000000000000000000000000000000000..bafe9bbca060aa73e08d6498166ba0ebf637c811 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_paint_property.js @@ -0,0 +1,6 @@ + +import validateProperty from './validate_property'; + +export default function validatePaintProperty(options) { + return validateProperty(options, 'paint'); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_property.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_property.js new file mode 100644 index 0000000000000000000000000000000000000000..c2e922bfbe9b065ccbf5dda728d0c8a35d299bc6 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_property.js @@ -0,0 +1,64 @@ + +import validate from './validate'; +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import {isFunction} from '../function'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import {supportsPropertyExpression} from '../util/properties'; + +export default function validateProperty(options, propertyType) { + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + const value = options.value; + const propertyKey = options.objectKey; + const layerSpec = styleSpec[`${propertyType}_${options.layerType}`]; + + if (!layerSpec) return []; + + const transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validate({ + key, + value, + valueSpec: styleSpec.transition, + style, + styleSpec + }); + } + + const valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, `unknown property "${propertyKey}"`)]; + } + + let tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError( + key, value, + `"${propertyKey}" does not support interpolation syntax\n` + + `Use an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(tokenMatch[1])} }\`.`)]; + } + + const errors = []; + + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + + return errors.concat(validate({ + key: options.key, + value, + valueSpec, + style, + styleSpec, + expressionContext: 'property', + propertyType, + propertyKey + })); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_source.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_source.js new file mode 100644 index 0000000000000000000000000000000000000000..820557d1487dc34bd540f676b1b4bac7da089071 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_source.js @@ -0,0 +1,111 @@ + +import ValidationError from '../error/validation_error'; +import {unbundle} from '../util/unbundle_jsonlint'; +import validateObject from './validate_object'; +import validateEnum from './validate_enum'; +import validateExpression from './validate_expression'; +import validateString from './validate_string'; +import getType from '../util/get_type'; + +const objectElementValidators = { + promoteId: validatePromoteId +}; + +export default function validateSource(options) { + const value = options.value; + const key = options.key; + const styleSpec = options.styleSpec; + const style = options.style; + + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + + const type = unbundle(value.type); + let errors; + + switch (type) { + case 'vector': + case 'raster': + case 'raster-dem': + errors = validateObject({ + key, + value, + valueSpec: styleSpec[`source_${type.replace('-', '_')}`], + style: options.style, + styleSpec, + objectElementValidators + }); + return errors; + + case 'geojson': + errors = validateObject({ + key, + value, + valueSpec: styleSpec.source_geojson, + style, + styleSpec, + objectElementValidators + }); + if (value.cluster) { + for (const prop in value.clusterProperties) { + const [operator, mapExpr] = value.clusterProperties[prop]; + const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator; + + errors.push(...validateExpression({ + key: `${key}.${prop}.map`, + value: mapExpr, + expressionContext: 'cluster-map' + })); + errors.push(...validateExpression({ + key: `${key}.${prop}.reduce`, + value: reduceExpr, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + + case 'video': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_video, + style, + styleSpec + }); + + case 'image': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_image, + style, + styleSpec + }); + + case 'canvas': + return [new ValidationError(key, null, `Please use runtime APIs to add canvas sources, rather than including them in stylesheets.`, 'source.canvas')]; + + default: + return validateEnum({ + key: `${key}.type`, + value: value.type, + valueSpec: {values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image']}, + style, + styleSpec + }); + } +} + +function validatePromoteId({key, value}) { + if (getType(value) === 'string') { + return validateString({key, value}); + } else { + const errors = []; + for (const prop in value) { + errors.push(...validateString({key: `${key}.${prop}`, value: value[prop]})); + } + return errors; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_string.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_string.js new file mode 100644 index 0000000000000000000000000000000000000000..c3353fdc5dcb8a1010cd09ef9ed38682169c5938 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate/validate_string.js @@ -0,0 +1,15 @@ + +import getType from '../util/get_type'; +import ValidationError from '../error/validation_error'; + +export default function validateString(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + + if (type !== 'string') { + return [new ValidationError(key, value, `string expected, ${type} found`)]; + } + + return []; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate_mapbox_api_supported.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate_mapbox_api_supported.js new file mode 100644 index 0000000000000000000000000000000000000000..e51a99e812dee1a3f524c25539051f5e4af71279 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate_mapbox_api_supported.js @@ -0,0 +1,171 @@ +// @flow + +import validateStyle from './validate_style.min'; +import {v8} from './style-spec'; +import readStyle from './read_style'; +import ValidationError from './error/validation_error'; +import getType from './util/get_type'; + +const SUPPORTED_SPEC_VERSION = 8; +const MAX_SOURCES_IN_STYLE = 15; + +function isValid(value: ?string, regex: RegExp): boolean { + if (!value || getType(value) !== 'string') return true; + return !!value.match(regex); +} + +function getSourceCount(source: Object): number { + if (source.url) { + return source.url.split(',').length; + } else { + return 0; + } +} + +function getAllowedKeyErrors(obj: Object, keys: Array<*>, path: ?string): Array { + const allowed = new Set(keys); + const errors = []; + Object.keys(obj).forEach(k => { + if (!allowed.has(k)) { + const prop = path ? `${path}.${k}` : null; + errors.push(new ValidationError(prop, obj[k], `Unsupported property "${k}"`)); + } + }); + return errors; +} + +function getSourceErrors(source: Object, i: number): Array { + const errors = []; + + /* + * Inlined sources are not supported by the Mapbox Styles API, so only + * "type", "url", and "tileSize" properties are valid + */ + const sourceKeys = ['type', 'url', 'tileSize']; + errors.push(...getAllowedKeyErrors(source, sourceKeys, 'source')); + + /* + * "source" is required. Valid examples: + * mapbox://mapbox.abcd1234 + * mapbox://penny.abcd1234 + * mapbox://mapbox.abcd1234,penny.abcd1234 + */ + const sourceUrlPattern = /^mapbox:\/\/([^/]*)$/; + if (!isValid(source.url, sourceUrlPattern)) { + errors.push(new ValidationError(`sources[${i}]`, source.url, 'Source url must be a valid Mapbox tileset url')); + } + + return errors; +} + +function getSourcesErrors(sources: Object): Array { + const errors = []; + let count = 0; + + Object.keys(sources).forEach((s: string, i: number) => { + const sourceErrors = getSourceErrors(sources[s], i); + + // If source has errors, skip counting + if (!sourceErrors.length) { + count = count + getSourceCount(sources[s]); + } + + errors.push(...sourceErrors); + }); + + if (count > MAX_SOURCES_IN_STYLE) { + errors.push(new ValidationError('sources', null, `Styles must contain ${MAX_SOURCES_IN_STYLE} or fewer sources`)); + } + + return errors; +} + +function getRootErrors(style: Object, specKeys: Array): Array { + const errors = []; + + /* + * The following keys are optional but fully managed by the Mapbox Styles + * API. Values on stylesheet on POST or PATCH will be ignored: "owner", + * "id", "cacheControl", "draft", "created", "modified" + * + * The following keys are optional. The Mapbox Styles API respects value on + * stylesheet on PATCH, but ignores the value on POST: "visibility" + */ + const optionalRootProperties = [ + 'owner', + 'id', + 'cacheControl', + 'draft', + 'created', + 'modified', + 'visibility' + ]; + + const allowedKeyErrors = getAllowedKeyErrors(style, [...specKeys, ...optionalRootProperties]); + errors.push(...allowedKeyErrors); + + if (style.version > SUPPORTED_SPEC_VERSION || style.version < SUPPORTED_SPEC_VERSION) { + errors.push(new ValidationError('version', style.version, `Style version must be ${SUPPORTED_SPEC_VERSION}`)); + } + + /* + * "glyphs" is optional. If present, valid examples: + * mapbox://fonts/penny/{fontstack}/{range}.pbf + * mapbox://fonts/mapbox/{fontstack}/{range}.pbf + */ + const glyphUrlPattern = /^mapbox:\/\/fonts\/([^/]*)\/{fontstack}\/{range}.pbf$/; + if (!isValid(style.glyphs, glyphUrlPattern)) { + errors.push(new ValidationError('glyphs', style.glyphs, 'Styles must reference glyphs hosted by Mapbox')); + } + + /* + * "sprite" is optional. If present, valid examples: + * mapbox://sprites/penny/abcd1234 + * mapbox://sprites/mapbox/abcd1234/draft + * mapbox://sprites/cyrus/abcd1234/abcd1234 + */ + const spriteUrlPattern = /^mapbox:\/\/sprites\/([^/]*)\/([^/]*)\/?([^/]*)?$/; + if (!isValid(style.sprite, spriteUrlPattern)) { + errors.push(new ValidationError('sprite', style.sprite, 'Styles must reference sprites hosted by Mapbox')); + } + + /* + * "visibility" is optional. If present, valid examples: + * "private" + * "public" + */ + const visibilityPattern = /^(public|private)$/; + if (!isValid(style.visibility, visibilityPattern)) { + errors.push(new ValidationError('visibility', style.visibility, 'Style visibility must be public or private')); + } + + return errors; +} + +/** + * Validate a Mapbox GL style against the style specification and check for + * compatibility with the Mapbox Styles API. + * + * @param {Object} style The style to be validated. + * @returns {Array} + * @example + * var validateMapboxApiSupported = require('mapbox-gl-style-spec/lib/validate_style_mapbox_api_supported.js'); + * var errors = validateMapboxApiSupported(style); + */ +export default function validateMapboxApiSupported(style: Object): Array { + let s = style; + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + + let errors = validateStyle(s, v8) + .concat(getRootErrors(s, Object.keys(v8.$root))); + + if (s.sources) { + errors = errors.concat(getSourcesErrors(s.sources)); + } + + return errors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate_style.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate_style.js new file mode 100644 index 0000000000000000000000000000000000000000..d5d9f0578de203ff7e4df3b3455e7977ae089538 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate_style.js @@ -0,0 +1,39 @@ + +import validateStyleMin from './validate_style.min'; +import {v8} from './style-spec'; +import readStyle from './read_style'; + +/** + * Validate a Mapbox GL style against the style specification. + * + * @private + * @alias validate + * @param {Object|String|Buffer} style The style to be validated. If a `String` + * or `Buffer` is provided, the returned errors will contain line numbers. + * @param {Object} [styleSpec] The style specification to validate against. + * If omitted, the spec version is inferred from the stylesheet. + * @returns {Array} + * @example + * var validate = require('mapbox-gl-style-spec').validate; + * var style = fs.readFileSync('./style.json', 'utf8'); + * var errors = validate(style); + */ + +export default function validateStyle(style, styleSpec = v8) { + let s = style; + + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + + return validateStyleMin(s, styleSpec); +} + +export const source = validateStyleMin.source; +export const light = validateStyleMin.light; +export const layer = validateStyleMin.layer; +export const filter = validateStyleMin.filter; +export const paintProperty = validateStyleMin.paintProperty; +export const layoutProperty = validateStyleMin.layoutProperty; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/validate_style.min.js b/node_modules/@plotly/mapbox-gl/src/style-spec/validate_style.min.js new file mode 100644 index 0000000000000000000000000000000000000000..b3166e800ea9b8f296adecc3c37779d40dc4cc6a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/validate_style.min.js @@ -0,0 +1,78 @@ + +import validateConstants from './validate/validate_constants'; +import validate from './validate/validate'; +import latestStyleSpec from './reference/latest'; +import validateGlyphsURL from './validate/validate_glyphs_url'; + +import validateSource from './validate/validate_source'; +import validateLight from './validate/validate_light'; +import validateLayer from './validate/validate_layer'; +import validateFilter from './validate/validate_filter'; +import validatePaintProperty from './validate/validate_paint_property'; +import validateLayoutProperty from './validate/validate_layout_property'; + +/** + * Validate a Mapbox GL style against the style specification. This entrypoint, + * `mapbox-gl-style-spec/lib/validate_style.min`, is designed to produce as + * small a browserify bundle as possible by omitting unnecessary functionality + * and legacy style specifications. + * + * @private + * @param {Object} style The style to be validated. + * @param {Object} [styleSpec] The style specification to validate against. + * If omitted, the latest style spec is used. + * @returns {Array} + * @example + * var validate = require('mapbox-gl-style-spec/lib/validate_style.min'); + * var errors = validate(style); + */ +function validateStyleMin(style, styleSpec = latestStyleSpec) { + + let errors = []; + + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec, + style, + objectElementValidators: { + glyphs: validateGlyphsURL, + '*'() { + return []; + } + } + })); + + if (style.constants) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style.constants, + style, + styleSpec + })); + } + + return sortErrors(errors); +} + +validateStyleMin.source = wrapCleanErrors(validateSource); +validateStyleMin.light = wrapCleanErrors(validateLight); +validateStyleMin.layer = wrapCleanErrors(validateLayer); +validateStyleMin.filter = wrapCleanErrors(validateFilter); +validateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty); +validateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty); + +function sortErrors(errors) { + return [].concat(errors).sort((a, b) => { + return a.line - b.line; + }); +} + +function wrapCleanErrors(inner) { + return function(...args) { + return sortErrors(inner.apply(this, args)); + }; +} + +export default validateStyleMin; diff --git a/node_modules/@plotly/mapbox-gl/src/style-spec/visit.js b/node_modules/@plotly/mapbox-gl/src/style-spec/visit.js new file mode 100644 index 0000000000000000000000000000000000000000..2911c1f03624e5abee4846714ef877d5d293024e --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style-spec/visit.js @@ -0,0 +1,77 @@ +// @flow + +import Reference from './reference/v8.json'; +import type {StylePropertySpecification} from './style-spec'; +import type { + StyleSpecification, + SourceSpecification, + LayerSpecification, + PropertyValueSpecification, + DataDrivenPropertyValueSpecification +} from './types'; + +function getPropertyReference(propertyName): StylePropertySpecification { + for (let i = 0; i < Reference.layout.length; i++) { + for (const key in Reference[Reference.layout[i]]) { + if (key === propertyName) return (Reference[Reference.layout[i]][key]: any); + } + } + for (let i = 0; i < Reference.paint.length; i++) { + for (const key in Reference[Reference.paint[i]]) { + if (key === propertyName) return (Reference[Reference.paint[i]][key]: any); + } + } + + return (null: any); +} + +export function eachSource(style: StyleSpecification, callback: (_: SourceSpecification) => void) { + for (const k in style.sources) { + callback(style.sources[k]); + } +} + +export function eachLayer(style: StyleSpecification, callback: (_: LayerSpecification) => void) { + for (const layer of style.layers) { + callback(layer); + } +} + +type PropertyCallback = ({ + path: [string, 'paint' | 'layout', string], // [layerid, paint/layout, property key] + key: string, + value: PropertyValueSpecification | DataDrivenPropertyValueSpecification, + reference: StylePropertySpecification, + set: (PropertyValueSpecification | DataDrivenPropertyValueSpecification) => void +}) => void; + +export function eachProperty( + style: StyleSpecification, + options: {paint?: boolean, layout?: boolean}, + callback: PropertyCallback +) { + function inner(layer, propertyType: 'paint' | 'layout') { + const properties = (layer[propertyType]: any); + if (!properties) return; + Object.keys(properties).forEach((key) => { + callback({ + path: [layer.id, propertyType, key], + key, + value: properties[key], + reference: getPropertyReference(key), + set(x) { + properties[key] = x; + } + }); + }); + } + + eachLayer(style, (layer) => { + if (options.paint) { + inner(layer, 'paint'); + } + if (options.layout) { + inner(layer, 'layout'); + } + }); +} diff --git a/node_modules/@plotly/mapbox-gl/src/style/style_layer_index.js b/node_modules/@plotly/mapbox-gl/src/style/style_layer_index.js new file mode 100644 index 0000000000000000000000000000000000000000..555c0993dcdda68840ebc392a65ff09ee2dff2eb --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style/style_layer_index.js @@ -0,0 +1,80 @@ +// @flow + +import StyleLayer from './style_layer'; +import createStyleLayer from './create_style_layer'; + +import {values} from '../util/util'; +import featureFilter from '../style-spec/feature_filter'; +import groupByLayout from '../style-spec/group_by_layout'; + +import type {TypedStyleLayer} from './style_layer/typed_style_layer'; +import type {LayerSpecification} from '../style-spec/types'; + +export type LayerConfigs = {[_: string]: LayerSpecification }; +export type Family = Array; + +class StyleLayerIndex { + familiesBySource: { [source: string]: { [sourceLayer: string]: Array> } }; + keyCache: { [source: string]: string }; + + _layerConfigs: LayerConfigs; + _layers: {[_: string]: StyleLayer }; + + constructor(layerConfigs: ?Array) { + this.keyCache = {}; + if (layerConfigs) { + this.replace(layerConfigs); + } + } + + replace(layerConfigs: Array) { + this._layerConfigs = {}; + this._layers = {}; + this.update(layerConfigs, []); + } + + update(layerConfigs: Array, removedIds: Array) { + for (const layerConfig of layerConfigs) { + this._layerConfigs[layerConfig.id] = layerConfig; + + const layer = this._layers[layerConfig.id] = createStyleLayer(layerConfig); + layer._featureFilter = featureFilter(layer.filter); + if (this.keyCache[layerConfig.id]) + delete this.keyCache[layerConfig.id]; + } + for (const id of removedIds) { + delete this.keyCache[id]; + delete this._layerConfigs[id]; + delete this._layers[id]; + } + + this.familiesBySource = {}; + + const groups = groupByLayout(values(this._layerConfigs), this.keyCache); + + for (const layerConfigs of groups) { + const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]); + + const layer = layers[0]; + if (layer.visibility === 'none') { + continue; + } + + const sourceId = layer.source || ''; + let sourceGroup = this.familiesBySource[sourceId]; + if (!sourceGroup) { + sourceGroup = this.familiesBySource[sourceId] = {}; + } + + const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer'; + let sourceLayerFamilies = sourceGroup[sourceLayerId]; + if (!sourceLayerFamilies) { + sourceLayerFamilies = sourceGroup[sourceLayerId] = []; + } + + sourceLayerFamilies.push(layers); + } + } +} + +export default StyleLayerIndex; diff --git a/node_modules/@plotly/mapbox-gl/src/style/validate_style.js b/node_modules/@plotly/mapbox-gl/src/style/validate_style.js new file mode 100644 index 0000000000000000000000000000000000000000..a84a38de69856ae787a8c8971e562882b322fa82 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style/validate_style.js @@ -0,0 +1,42 @@ +// @flow +import validateStyleMin from '../style-spec/validate_style.min'; +import {ErrorEvent} from '../util/evented'; + +import type {Evented} from '../util/evented'; + +type ValidationError = { + message: string, + line: number, + identifier?: string +}; + +export type Validator = (Object) => $ReadOnlyArray; + +type ValidateStyle = { + (Object, ?Object): $ReadOnlyArray, + source: Validator, + layer: Validator, + light: Validator, + filter: Validator, + paintProperty: Validator, + layoutProperty: Validator +}; + +export const validateStyle = (validateStyleMin: ValidateStyle); + +export const validateSource = validateStyle.source; +export const validateLight = validateStyle.light; +export const validateFilter = validateStyle.filter; +export const validatePaintProperty = validateStyle.paintProperty; +export const validateLayoutProperty = validateStyle.layoutProperty; + +export function emitValidationErrors(emitter: Evented, errors: ?$ReadOnlyArray<{message: string, identifier?: string}>): boolean { + let hasErrors = false; + if (errors && errors.length) { + for (const error of errors) { + emitter.fire(new ErrorEvent(new Error(error.message))); + hasErrors = true; + } + } + return hasErrors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/style/zoom_history.js b/node_modules/@plotly/mapbox-gl/src/style/zoom_history.js new file mode 100644 index 0000000000000000000000000000000000000000..b2f684e2a69fd94bae6f8ffb93bca39b94db9cf1 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/style/zoom_history.js @@ -0,0 +1,44 @@ +// @flow + +class ZoomHistory { + lastZoom: number; + lastFloorZoom: number; + lastIntegerZoom: number; + lastIntegerZoomTime: number; + first: boolean; + + constructor() { + this.first = true; + } + + update(z: number, now: number) { + const floorZ = Math.floor(z); + + if (this.first) { + this.first = false; + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = 0; + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + + if (this.lastFloorZoom > floorZ) { + this.lastIntegerZoom = floorZ + 1; + this.lastIntegerZoomTime = now; + } else if (this.lastFloorZoom < floorZ) { + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = now; + } + + if (z !== this.lastZoom) { + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + + return false; + } +} + +export default ZoomHistory; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/anchor.js b/node_modules/@plotly/mapbox-gl/src/symbol/anchor.js new file mode 100644 index 0000000000000000000000000000000000000000..cd756cc72f824f02ccac242c802bcddd0a4d8c90 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/anchor.js @@ -0,0 +1,26 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import {register} from '../util/web_worker_transfer'; + +class Anchor extends Point { + angle: any; + segment: number | void; + + constructor(x: number, y: number, angle: number, segment?: number) { + super(x, y); + this.angle = angle; + if (segment !== undefined) { + this.segment = segment; + } + } + + clone() { + return new Anchor(this.x, this.y, this.angle, this.segment); + } +} + +register('Anchor', Anchor); + +export default Anchor; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/check_max_angle.js b/node_modules/@plotly/mapbox-gl/src/symbol/check_max_angle.js new file mode 100644 index 0000000000000000000000000000000000000000..f6eddf09496186cc3d88d9e7ea004086ee436379 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/check_max_angle.js @@ -0,0 +1,81 @@ +// @flow + +export default checkMaxAngle; + +import type Point from '@mapbox/point-geometry'; +import type Anchor from './anchor'; + +/** + * Labels placed around really sharp angles aren't readable. Check if any + * part of the potential label has a combined angle that is too big. + * + * @param line + * @param anchor The point on the line around which the label is anchored. + * @param labelLength The length of the label in geometry units. + * @param windowSize The check fails if the combined angles within a part of the line that is `windowSize` long is too big. + * @param maxAngle The maximum combined angle that any window along the label is allowed to have. + * + * @returns {boolean} whether the label should be placed + * @private + */ +function checkMaxAngle(line: Array, anchor: Anchor, labelLength: number, windowSize: number, maxAngle: number) { + + // horizontal labels always pass + if (anchor.segment === undefined) return true; + + let p = anchor; + let index = anchor.segment + 1; + let anchorDistance = 0; + + // move backwards along the line to the first segment the label appears on + while (anchorDistance > -labelLength / 2) { + index--; + + // there isn't enough room for the label after the beginning of the line + if (index < 0) return false; + + anchorDistance -= line[index].dist(p); + p = line[index]; + } + + anchorDistance += line[index].dist(line[index + 1]); + index++; + + // store recent corners and their total angle difference + const recentCorners = []; + let recentAngleDelta = 0; + + // move forwards by the length of the label and check angles along the way + while (anchorDistance < labelLength / 2) { + const prev = line[index - 1]; + const current = line[index]; + const next = line[index + 1]; + + // there isn't enough room for the label before the end of the line + if (!next) return false; + + let angleDelta = prev.angleTo(current) - current.angleTo(next); + // restrict angle to -pi..pi range + angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI); + + recentCorners.push({ + distance: anchorDistance, + angleDelta + }); + recentAngleDelta += angleDelta; + + // remove corners that are far enough away from the list of recent anchors + while (anchorDistance - recentCorners[0].distance > windowSize) { + recentAngleDelta -= recentCorners.shift().angleDelta; + } + + // the sum of angles within the window area exceeds the maximum allowed value. check fails. + if (recentAngleDelta > maxAngle) return false; + + index++; + anchorDistance += current.dist(next); + } + + // no part of the line had an angle greater than the maximum allowed. check passes. + return true; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/clip_line.js b/node_modules/@plotly/mapbox-gl/src/symbol/clip_line.js new file mode 100644 index 0000000000000000000000000000000000000000..1abfea48419552c43925050ba87f3143a840de24 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/clip_line.js @@ -0,0 +1,71 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +export default clipLine; + +/** + * Returns the part of a multiline that intersects with the provided rectangular box. + * + * @param lines + * @param x1 the left edge of the box + * @param y1 the top edge of the box + * @param x2 the right edge of the box + * @param y2 the bottom edge of the box + * @returns lines + * @private + */ +function clipLine(lines: Array>, x1: number, y1: number, x2: number, y2: number): Array> { + const clippedLines = []; + + for (let l = 0; l < lines.length; l++) { + const line = lines[l]; + let clippedLine; + + for (let i = 0; i < line.length - 1; i++) { + let p0 = line[i]; + let p1 = line[i + 1]; + + if (p0.x < x1 && p1.x < x1) { + continue; + } else if (p0.x < x1) { + p0 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } else if (p1.x < x1) { + p1 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + + if (p0.y < y1 && p1.y < y1) { + continue; + } else if (p0.y < y1) { + p0 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } else if (p1.y < y1) { + p1 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + + if (p0.x >= x2 && p1.x >= x2) { + continue; + } else if (p0.x >= x2) { + p0 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } else if (p1.x >= x2) { + p1 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + + if (p0.y >= y2 && p1.y >= y2) { + continue; + } else if (p0.y >= y2) { + p0 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } else if (p1.y >= y2) { + p1 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + + if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) { + clippedLine = [p0]; + clippedLines.push(clippedLine); + } + + clippedLine.push(p1); + } + } + + return clippedLines; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/collision_feature.js b/node_modules/@plotly/mapbox-gl/src/symbol/collision_feature.js new file mode 100644 index 0000000000000000000000000000000000000000..faf3eb48a59cc931c52eb199d79970cccdc19ecf --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/collision_feature.js @@ -0,0 +1,109 @@ +// @flow + +import type {CollisionBoxArray} from '../data/array_types'; +import Point from '@mapbox/point-geometry'; +import type Anchor from './anchor'; + +/** + * A CollisionFeature represents the area of the tile covered by a single label. + * It is used with CollisionIndex to check if the label overlaps with any + * previous labels. A CollisionFeature is mostly just a set of CollisionBox + * objects. + * + * @private + */ +class CollisionFeature { + boxStartIndex: number; + boxEndIndex: number; + circleDiameter: ?number; + + /** + * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process. + * For line aligned labels a collision circle diameter is computed instead. + * + * @param anchor The point along the line around which the label is anchored. + * @param shaped The text or icon shaping results. + * @param boxScale A magic number used to convert from glyph metrics units to geometry units. + * @param padding The amount of padding to add around the label edges. + * @param alignLine Whether the label is aligned with the line or the viewport. + * @private + */ + constructor(collisionBoxArray: CollisionBoxArray, + anchor: Anchor, + featureIndex: number, + sourceLayerIndex: number, + bucketIndex: number, + shaped: Object, + boxScale: number, + padding: number, + alignLine: boolean, + rotate: number) { + + this.boxStartIndex = collisionBoxArray.length; + + if (alignLine) { + // Compute height of the shape in glyph metrics and apply collision padding. + // Note that the pixel based 'text-padding' is applied at runtime + let top = shaped.top; + let bottom = shaped.bottom; + const collisionPadding = shaped.collisionPadding; + + if (collisionPadding) { + top -= collisionPadding[1]; + bottom += collisionPadding[3]; + } + + let height = bottom - top; + + if (height > 0) { + // set minimum box height to avoid very many small labels + height = Math.max(10, height); + this.circleDiameter = height; + } + } else { + let y1 = shaped.top * boxScale - padding; + let y2 = shaped.bottom * boxScale + padding; + let x1 = shaped.left * boxScale - padding; + let x2 = shaped.right * boxScale + padding; + + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + x1 -= collisionPadding[0] * boxScale; + y1 -= collisionPadding[1] * boxScale; + x2 += collisionPadding[2] * boxScale; + y2 += collisionPadding[3] * boxScale; + } + + if (rotate) { + // Account for *-rotate in point collision boxes + // See https://github.com/mapbox/mapbox-gl-js/issues/6075 + // Doesn't account for icon-text-fit + + const tl = new Point(x1, y1); + const tr = new Point(x2, y1); + const bl = new Point(x1, y2); + const br = new Point(x2, y2); + + const rotateRadians = rotate * Math.PI / 180; + + tl._rotate(rotateRadians); + tr._rotate(rotateRadians); + bl._rotate(rotateRadians); + br._rotate(rotateRadians); + + // Collision features require an "on-axis" geometry, + // so take the envelope of the rotated geometry + // (may be quite large for wide labels rotated 45 degrees) + x1 = Math.min(tl.x, tr.x, bl.x, br.x); + x2 = Math.max(tl.x, tr.x, bl.x, br.x); + y1 = Math.min(tl.y, tr.y, bl.y, br.y); + y2 = Math.max(tl.y, tr.y, bl.y, br.y); + } + collisionBoxArray.emplaceBack(anchor.x, anchor.y, x1, y1, x2, y2, featureIndex, sourceLayerIndex, bucketIndex); + } + + this.boxEndIndex = collisionBoxArray.length; + } +} + +export default CollisionFeature; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/collision_index.js b/node_modules/@plotly/mapbox-gl/src/symbol/collision_index.js new file mode 100644 index 0000000000000000000000000000000000000000..f553e610761013babb4562d9c0d74501b738e958 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/collision_index.js @@ -0,0 +1,373 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import clipLine from './clip_line'; +import PathInterpolator from './path_interpolator'; + +import * as intersectionTests from '../util/intersection_tests'; +import Grid from './grid_index'; +import {mat4} from 'gl-matrix'; +import ONE_EM from '../symbol/one_em'; +import assert from 'assert'; + +import * as projection from '../symbol/projection'; + +import type Transform from '../geo/transform'; +import type {SingleCollisionBox} from '../data/bucket/symbol_bucket'; +import type { + GlyphOffsetArray, + SymbolLineVertexArray +} from '../data/array_types'; + +// When a symbol crosses the edge that causes it to be included in +// collision detection, it will cause changes in the symbols around +// it. This constant specifies how many pixels to pad the edge of +// the viewport for collision detection so that the bulk of the changes +// occur offscreen. Making this constant greater increases label +// stability, but it's expensive. +const viewportPadding = 100; + +/** + * A collision index used to prevent symbols from overlapping. It keep tracks of + * where previous symbols have been placed and is used to check if a new + * symbol overlaps with any previously added symbols. + * + * There are two steps to insertion: first placeCollisionBox/Circles checks if + * there's room for a symbol, then insertCollisionBox/Circles actually puts the + * symbol in the index. The two step process allows paired symbols to be inserted + * together even if they overlap. + * + * @private + */ +class CollisionIndex { + grid: Grid; + ignoredGrid: Grid; + transform: Transform; + pitchfactor: number; + screenRightBoundary: number; + screenBottomBoundary: number; + gridRightBoundary: number; + gridBottomBoundary: number; + + constructor( + transform: Transform, + grid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25), + ignoredGrid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25) + ) { + this.transform = transform; + + this.grid = grid; + this.ignoredGrid = ignoredGrid; + this.pitchfactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance; + + this.screenRightBoundary = transform.width + viewportPadding; + this.screenBottomBoundary = transform.height + viewportPadding; + this.gridRightBoundary = transform.width + 2 * viewportPadding; + this.gridBottomBoundary = transform.height + 2 * viewportPadding; + } + + placeCollisionBox(collisionBox: SingleCollisionBox, allowOverlap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroupPredicate?: any): { box: Array, offscreen: boolean } { + const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox.anchorPointX, collisionBox.anchorPointY); + const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio; + const tlX = collisionBox.x1 * tileToViewport + projectedPoint.point.x; + const tlY = collisionBox.y1 * tileToViewport + projectedPoint.point.y; + const brX = collisionBox.x2 * tileToViewport + projectedPoint.point.x; + const brY = collisionBox.y2 * tileToViewport + projectedPoint.point.y; + + if (!this.isInsideGrid(tlX, tlY, brX, brY) || + (!allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate))) { + return { + box: [], + offscreen: false + }; + } + + return { + box: [tlX, tlY, brX, brY], + offscreen: this.isOffscreen(tlX, tlY, brX, brY) + }; + } + + placeCollisionCircles(allowOverlap: boolean, + symbol: any, + lineVertexArray: SymbolLineVertexArray, + glyphOffsetArray: GlyphOffsetArray, + fontSize: number, + posMatrix: mat4, + labelPlaneMatrix: mat4, + labelToScreenMatrix?: mat4, + showCollisionCircles: boolean, + pitchWithMap: boolean, + collisionGroupPredicate?: any, + circlePixelDiameter: number, + textPixelPadding: number): { circles: Array, offscreen: boolean, collisionDetected: boolean } { + const placedCollisionCircles = []; + + const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY); + const screenAnchorPoint = projection.project(tileUnitAnchorPoint, posMatrix); + const perspectiveRatio = projection.getPerspectiveRatio(this.transform.cameraToCenterDistance, screenAnchorPoint.signedDistanceFromCamera); + const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const labelPlaneFontScale = labelPlaneFontSize / ONE_EM; + + const labelPlaneAnchorPoint = projection.project(tileUnitAnchorPoint, labelPlaneMatrix).point; + + const projectionCache = {}; + const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale; + const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale; + + const firstAndLastGlyph = projection.placeFirstAndLastGlyph( + labelPlaneFontScale, + glyphOffsetArray, + lineOffsetX, + lineOffsetY, + /*flip*/ false, + labelPlaneAnchorPoint, + tileUnitAnchorPoint, + symbol, + lineVertexArray, + labelPlaneMatrix, + projectionCache); + + let collisionDetected = false; + let inGrid = false; + let entirelyOffscreen = true; + + if (firstAndLastGlyph) { + const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding; + const screenPlaneMin = new Point(-viewportPadding, -viewportPadding); + const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary); + const interpolator = new PathInterpolator(); + + // Construct a projected path from projected line vertices. Anchor points are ignored and removed + const first = firstAndLastGlyph.first; + const last = firstAndLastGlyph.last; + + let projectedPath = []; + for (let i = first.path.length - 1; i >= 1; i--) { + projectedPath.push(first.path[i]); + } + for (let i = 1; i < last.path.length; i++) { + projectedPath.push(last.path[i]); + } + assert(projectedPath.length >= 2); + + // Tolerate a slightly longer distance than one diameter between two adjacent circles + const circleDist = radius * 2.5; + + // The path might need to be converted into screen space if a pitched map is used as the label space + if (labelToScreenMatrix) { + const screenSpacePath = projectedPath.map(p => projection.project(p, labelToScreenMatrix)); + + // Do not try to place collision circles if even of the points is behind the camera. + // This is a plausible scenario with big camera pitch angles + if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) { + projectedPath = []; + } else { + projectedPath = screenSpacePath.map(p => p.point); + } + } + + let segments = []; + + if (projectedPath.length > 0) { + // Quickly check if the path is fully inside or outside of the padded collision region. + // For overlapping paths we'll only create collision circles for the visible segments + const minPoint = projectedPath[0].clone(); + const maxPoint = projectedPath[0].clone(); + + for (let i = 1; i < projectedPath.length; i++) { + minPoint.x = Math.min(minPoint.x, projectedPath[i].x); + minPoint.y = Math.min(minPoint.y, projectedPath[i].y); + maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x); + maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y); + } + + if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x && + minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) { + // Quad fully visible + segments = [projectedPath]; + } else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x || + maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) { + // Not visible + segments = []; + } else { + segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y); + } + } + + for (const seg of segments) { + // interpolate positions for collision circles. Add a small padding to both ends of the segment + assert(seg.length > 0); + interpolator.reset(seg, radius * 0.25); + + let numCircles = 0; + + if (interpolator.length <= 0.5 * radius) { + numCircles = 1; + } else { + numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1; + } + + for (let i = 0; i < numCircles; i++) { + const t = i / Math.max(numCircles - 1, 1); + const circlePosition = interpolator.lerp(t); + + // add viewport padding to the position and perform initial collision check + const centerX = circlePosition.x + viewportPadding; + const centerY = circlePosition.y + viewportPadding; + + placedCollisionCircles.push(centerX, centerY, radius, 0); + + const x1 = centerX - radius; + const y1 = centerY - radius; + const x2 = centerX + radius; + const y2 = centerY + radius; + + entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2); + inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2); + + if (!allowOverlap) { + if (this.grid.hitTestCircle(centerX, centerY, radius, collisionGroupPredicate)) { + // Don't early exit if we're showing the debug circles because we still want to calculate + // which circles are in use + collisionDetected = true; + if (!showCollisionCircles) { + return { + circles: [], + offscreen: false, + collisionDetected + }; + } + } + } + } + } + } + + return { + circles: ((!showCollisionCircles && collisionDetected) || !inGrid) ? [] : placedCollisionCircles, + offscreen: entirelyOffscreen, + collisionDetected + }; + } + + /** + * Because the geometries in the CollisionIndex are an approximation of the shape of + * symbols on the map, we use the CollisionIndex to look up the symbol part of + * `queryRenderedFeatures`. + * + * @private + */ + queryRenderedSymbols(viewportQueryGeometry: Array) { + if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) { + return {}; + } + + const query = []; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const point of viewportQueryGeometry) { + const gridPoint = new Point(point.x + viewportPadding, point.y + viewportPadding); + minX = Math.min(minX, gridPoint.x); + minY = Math.min(minY, gridPoint.y); + maxX = Math.max(maxX, gridPoint.x); + maxY = Math.max(maxY, gridPoint.y); + query.push(gridPoint); + } + + const features = this.grid.query(minX, minY, maxX, maxY) + .concat(this.ignoredGrid.query(minX, minY, maxX, maxY)); + + const seenFeatures = {}; + const result = {}; + + for (const feature of features) { + const featureKey = feature.key; + // Skip already seen features. + if (seenFeatures[featureKey.bucketInstanceId] === undefined) { + seenFeatures[featureKey.bucketInstanceId] = {}; + } + if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) { + continue; + } + + // Check if query intersects with the feature box + // "Collision Circles" for line labels are treated as boxes here + // Since there's no actual collision taking place, the circle vs. square + // distinction doesn't matter as much, and box geometry is easier + // to work with. + const bbox = [ + new Point(feature.x1, feature.y1), + new Point(feature.x2, feature.y1), + new Point(feature.x2, feature.y2), + new Point(feature.x1, feature.y2) + ]; + if (!intersectionTests.polygonIntersectsPolygon(query, bbox)) { + continue; + } + + seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true; + if (result[featureKey.bucketInstanceId] === undefined) { + result[featureKey.bucketInstanceId] = []; + } + result[featureKey.bucketInstanceId].push(featureKey.featureIndex); + } + + return result; + } + + insertCollisionBox(collisionBox: Array, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + + const key = {bucketInstanceId, featureIndex, collisionGroupID}; + grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]); + } + + insertCollisionCircles(collisionCircles: Array, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + + const key = {bucketInstanceId, featureIndex, collisionGroupID}; + for (let k = 0; k < collisionCircles.length; k += 4) { + grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]); + } + } + + projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number) { + const p = [x, y, 0, 1]; + projection.xyTransformMat4(p, p, posMatrix); + const a = new Point( + (((p[0] / p[3] + 1) / 2) * this.transform.width) + viewportPadding, + (((-p[1] / p[3] + 1) / 2) * this.transform.height) + viewportPadding + ); + return { + point: a, + // See perspective ratio comment in symbol_sdf.vertex + // We're doing collision detection in viewport space so we need + // to scale down boxes in the distance + perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3]) + }; + } + + isOffscreen(x1: number, y1: number, x2: number, y2: number) { + return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary; + } + + isInsideGrid(x1: number, y1: number, x2: number, y2: number) { + return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary; + } + + /* + * Returns a matrix for transforming collision shapes to viewport coordinate space. + * Use this function to render e.g. collision circles on the screen. + * example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos + */ + getViewportMatrix(): mat4 { + const m = mat4.identity([]); + mat4.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]); + return m; + } +} + +export default CollisionIndex; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/cross_tile_symbol_index.js b/node_modules/@plotly/mapbox-gl/src/symbol/cross_tile_symbol_index.js new file mode 100644 index 0000000000000000000000000000000000000000..103d8399612db53f1a8efa3d4334d2bfa8287b28 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/cross_tile_symbol_index.js @@ -0,0 +1,301 @@ +// @flow + +import EXTENT from '../data/extent'; + +import {SymbolInstanceArray} from '../data/array_types'; + +import type {SymbolInstance} from '../data/array_types'; +import type {OverscaledTileID} from '../source/tile_id'; +import type SymbolBucket from '../data/bucket/symbol_bucket'; +import type StyleLayer from '../style/style_layer'; +import type Tile from '../source/tile'; + +/* + The CrossTileSymbolIndex generally works on the assumption that + a conceptual "unique symbol" can be identified by the text of + the label combined with the anchor point. The goal is to assign + these conceptual "unique symbols" a shared crossTileID that can be + used by Placement to keep fading opacity states consistent and to + deduplicate labels. + + The CrossTileSymbolIndex indexes all the current symbol instances and + their crossTileIDs. When a symbol bucket gets added or updated, the + index assigns a crossTileID to each of it's symbol instances by either + matching it with an existing id or assigning a new one. +*/ + +// Round anchor positions to roughly 4 pixel grid +const roundingFactor = 512 / EXTENT / 2; + +class TileLayerIndex { + tileID: OverscaledTileID; + indexedSymbolInstances: {[_: number]: Array<{ + crossTileID: number, + coord: { + x: number, + y: number + } + }>}; + bucketInstanceId: number; + + constructor(tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, bucketInstanceId: number) { + this.tileID = tileID; + this.indexedSymbolInstances = {}; + this.bucketInstanceId = bucketInstanceId; + + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + const key = symbolInstance.key; + if (!this.indexedSymbolInstances[key]) { + this.indexedSymbolInstances[key] = []; + } + // This tile may have multiple symbol instances with the same key + // Store each one along with its coordinates + this.indexedSymbolInstances[key].push({ + crossTileID: symbolInstance.crossTileID, + coord: this.getScaledCoordinates(symbolInstance, tileID) + }); + } + } + + // Converts the coordinates of the input symbol instance into coordinates that be can compared + // against other symbols in this index. Coordinates are: + // (1) world-based (so after conversion the source tile is irrelevant) + // (2) converted to the z-scale of this TileLayerIndex + // (3) down-sampled by "roundingFactor" from tile coordinate precision in order to be + // more tolerant of small differences between tiles. + getScaledCoordinates(symbolInstance: SymbolInstance, childTileID: OverscaledTileID) { + const zDifference = childTileID.canonical.z - this.tileID.canonical.z; + const scale = roundingFactor / Math.pow(2, zDifference); + return { + x: Math.floor((childTileID.canonical.x * EXTENT + symbolInstance.anchorX) * scale), + y: Math.floor((childTileID.canonical.y * EXTENT + symbolInstance.anchorY) * scale) + }; + } + + findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: {[crossTileID: number]: boolean}) { + const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z); + + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + if (symbolInstance.crossTileID) { + // already has a match, skip + continue; + } + + const indexedInstances = this.indexedSymbolInstances[symbolInstance.key]; + if (!indexedInstances) { + // No symbol with this key in this bucket + continue; + } + + const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID); + + for (const thisTileSymbol of indexedInstances) { + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + if (Math.abs(thisTileSymbol.coord.x - scaledSymbolCoord.x) <= tolerance && + Math.abs(thisTileSymbol.coord.y - scaledSymbolCoord.y) <= tolerance && + !zoomCrossTileIDs[thisTileSymbol.crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[thisTileSymbol.crossTileID] = true; + symbolInstance.crossTileID = thisTileSymbol.crossTileID; + break; + } + } + } + } +} + +class CrossTileIDs { + maxCrossTileID: number; + constructor() { + this.maxCrossTileID = 0; + } + generate() { + return ++this.maxCrossTileID; + } +} + +class CrossTileSymbolLayerIndex { + indexes: {[zoom: string | number]: {[tileId: string | number]: TileLayerIndex}}; + usedCrossTileIDs: {[zoom: string | number]: {[crossTileID: number]: boolean}}; + lng: number; + + constructor() { + this.indexes = {}; + this.usedCrossTileIDs = {}; + this.lng = 0; + } + + /* + * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. + * To prevent labels from flashing out and in we adjust the tileID values in the indexes + * so that they match the new wrapped version of the map. + */ + handleWrapJump(lng: number) { + const wrapDelta = Math.round((lng - this.lng) / 360); + if (wrapDelta !== 0) { + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + const newZoomIndex = {}; + for (const key in zoomIndexes) { + // change the tileID's wrap and add it to a new index + const index = zoomIndexes[key]; + index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta); + newZoomIndex[index.tileID.key] = index; + } + this.indexes[zoom] = newZoomIndex; + } + } + this.lng = lng; + } + + addBucket(tileID: OverscaledTileID, bucket: SymbolBucket, crossTileIDs: CrossTileIDs) { + if (this.indexes[tileID.overscaledZ] && + this.indexes[tileID.overscaledZ][tileID.key]) { + if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === + bucket.bucketInstanceId) { + return false; + } else { + // We're replacing this bucket with an updated version + // Remove the old bucket's "used crossTileIDs" now so that + // the new bucket can claim them. + // The old index entries themselves stick around until + // 'removeStaleBuckets' is called. + this.removeBucketCrossTileIDs(tileID.overscaledZ, + this.indexes[tileID.overscaledZ][tileID.key]); + } + } + + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + symbolInstance.crossTileID = 0; + } + + if (!this.usedCrossTileIDs[tileID.overscaledZ]) { + this.usedCrossTileIDs[tileID.overscaledZ] = {}; + } + const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ]; + + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + if (Number(zoom) > tileID.overscaledZ) { + for (const id in zoomIndexes) { + const childIndex = zoomIndexes[id]; + if (childIndex.tileID.isChildOf(tileID)) { + childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } else { + const parentCoord = tileID.scaledTo(Number(zoom)); + const parentIndex = zoomIndexes[parentCoord.key]; + if (parentIndex) { + parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + if (!symbolInstance.crossTileID) { + // symbol did not match any known symbol, assign a new id + symbolInstance.crossTileID = crossTileIDs.generate(); + zoomCrossTileIDs[symbolInstance.crossTileID] = true; + } + } + + if (this.indexes[tileID.overscaledZ] === undefined) { + this.indexes[tileID.overscaledZ] = {}; + } + this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId); + + return true; + } + + removeBucketCrossTileIDs(zoom: string | number, removedBucket: TileLayerIndex) { + for (const key in removedBucket.indexedSymbolInstances) { + for (const symbolInstance of removedBucket.indexedSymbolInstances[(key: any)]) { + delete this.usedCrossTileIDs[zoom][symbolInstance.crossTileID]; + } + } + } + + removeStaleBuckets(currentIDs: { [string | number]: boolean }) { + let tilesChanged = false; + for (const z in this.indexes) { + const zoomIndexes = this.indexes[z]; + for (const tileKey in zoomIndexes) { + if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) { + this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]); + delete zoomIndexes[tileKey]; + tilesChanged = true; + } + } + } + return tilesChanged; + } +} + +class CrossTileSymbolIndex { + layerIndexes: {[layerId: string]: CrossTileSymbolLayerIndex}; + crossTileIDs: CrossTileIDs; + maxBucketInstanceId: number; + bucketsInCurrentPlacement: {[_: number]: boolean}; + + constructor() { + this.layerIndexes = {}; + this.crossTileIDs = new CrossTileIDs(); + this.maxBucketInstanceId = 0; + this.bucketsInCurrentPlacement = {}; + } + + addLayer(styleLayer: StyleLayer, tiles: Array, lng: number) { + let layerIndex = this.layerIndexes[styleLayer.id]; + if (layerIndex === undefined) { + layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex(); + } + + let symbolBucketsChanged = false; + const currentBucketIDs = {}; + + layerIndex.handleWrapJump(lng); + + for (const tile of tiles) { + const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket); + if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0]) + continue; + + if (!symbolBucket.bucketInstanceId) { + symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId; + } + + if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) { + symbolBucketsChanged = true; + } + currentBucketIDs[symbolBucket.bucketInstanceId] = true; + } + + if (layerIndex.removeStaleBuckets(currentBucketIDs)) { + symbolBucketsChanged = true; + } + + return symbolBucketsChanged; + } + + pruneUnusedLayers(usedLayers: Array) { + const usedLayerMap = {}; + usedLayers.forEach((usedLayer) => { + usedLayerMap[usedLayer] = true; + }); + for (const layerId in this.layerIndexes) { + if (!usedLayerMap[layerId]) { + delete this.layerIndexes[layerId]; + } + } + } +} + +export default CrossTileSymbolIndex; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/get_anchors.js b/node_modules/@plotly/mapbox-gl/src/symbol/get_anchors.js new file mode 100644 index 0000000000000000000000000000000000000000..9b034b4bc865cfc51ef52f5bdfe80ef9ccaf232e --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/get_anchors.js @@ -0,0 +1,167 @@ +// @flow + +import {number as interpolate} from '../style-spec/util/interpolate'; + +import Anchor from '../symbol/anchor'; +import checkMaxAngle from './check_max_angle'; + +import type Point from '@mapbox/point-geometry'; +import type {Shaping, PositionedIcon} from './shaping'; + +export {getAnchors, getCenterAnchor}; + +function getLineLength(line: Array): number { + let lineLength = 0; + for (let k = 0; k < line.length - 1; k++) { + lineLength += line[k].dist(line[k + 1]); + } + return lineLength; +} + +function getAngleWindowSize(shapedText: ?Shaping, + glyphSize: number, + boxScale: number): number { + return shapedText ? + 3 / 5 * glyphSize * boxScale : + 0; +} + +function getShapedLabelLength(shapedText: ?Shaping, shapedIcon: ?PositionedIcon): number { + return Math.max( + shapedText ? shapedText.right - shapedText.left : 0, + shapedIcon ? shapedIcon.right - shapedIcon.left : 0); +} + +function getCenterAnchor(line: Array, + maxAngle: number, + shapedText: ?Shaping, + shapedIcon: ?PositionedIcon, + glyphSize: number, + boxScale: number) { + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale; + + let prevDistance = 0; + const centerDistance = getLineLength(line) / 2; + + for (let i = 0; i < line.length - 1; i++) { + + const a = line[i], + b = line[i + 1]; + + const segmentDistance = a.dist(b); + + if (prevDistance + segmentDistance > centerDistance) { + // The center is on this segment + const t = (centerDistance - prevDistance) / segmentDistance, + x = interpolate(a.x, b.x, t), + y = interpolate(a.y, b.y, t); + + const anchor = new Anchor(x, y, b.angleTo(a), i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + return anchor; + } else { + return; + } + } + + prevDistance += segmentDistance; + } +} + +function getAnchors(line: Array, + spacing: number, + maxAngle: number, + shapedText: ?Shaping, + shapedIcon: ?PositionedIcon, + glyphSize: number, + boxScale: number, + overscaling: number, + tileExtent: number) { + + // Resample a line to get anchor points for labels and check that each + // potential label passes text-max-angle check and has enough froom to fit + // on the line. + + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon); + const labelLength = shapedLabelLength * boxScale; + + // Is the line continued from outside the tile boundary? + const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent; + + // Is the label long, relative to the spacing? + // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. + if (spacing - labelLength < spacing / 4) { + spacing = labelLength + spacing / 4; + } + + // Offset the first anchor by: + // Either half the label length plus a fixed extra offset if the line is not continued + // Or half the spacing if the line is continued. + + // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. + const fixedExtraOffset = glyphSize * 2; + + const offset = !isLineContinued ? + ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing : + (spacing / 2 * overscaling) % spacing; + + return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent); +} + +function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) { + + const halfLabelLength = labelLength / 2; + const lineLength = getLineLength(line); + + let distance = 0, + markedDistance = offset - spacing; + + let anchors = []; + + for (let i = 0; i < line.length - 1; i++) { + + const a = line[i], + b = line[i + 1]; + + const segmentDist = a.dist(b), + angle = b.angleTo(a); + + while (markedDistance + spacing < distance + segmentDist) { + markedDistance += spacing; + + const t = (markedDistance - distance) / segmentDist, + x = interpolate(a.x, b.x, t), + y = interpolate(a.y, b.y, t); + + // Check that the point is within the tile boundaries and that + // the label would fit before the beginning and end of the line + // if placed at this point. + if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && + markedDistance - halfLabelLength >= 0 && + markedDistance + halfLabelLength <= lineLength) { + const anchor = new Anchor(x, y, angle, i); + anchor._round(); + + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + anchors.push(anchor); + } + } + } + + distance += segmentDist; + } + + if (!placeAtMiddle && !anchors.length && !isLineContinued) { + // The first attempt at finding anchors at which labels can be placed failed. + // Try again, but this time just try placing one anchor at the middle of the line. + // This has the most effect for short lines in overscaled tiles, since the + // initial offset used in overscaled tiles is calculated to align labels with positions in + // parent tiles instead of placing the label as close to the beginning as possible. + anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent); + } + + return anchors; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/grid_index.js b/node_modules/@plotly/mapbox-gl/src/symbol/grid_index.js new file mode 100644 index 0000000000000000000000000000000000000000..fa1dc103436297943b0b262cc48e7e25c66ba1ce --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/grid_index.js @@ -0,0 +1,335 @@ +// @flow + +/** + * GridIndex is a data structure for testing the intersection of + * circles and rectangles in a 2d plane. + * It is optimized for rapid insertion and querying. + * GridIndex splits the plane into a set of "cells" and keeps track + * of which geometries intersect with each cell. At query time, + * full geometry comparisons are only done for items that share + * at least one cell. As long as the geometries are relatively + * uniformly distributed across the plane, this greatly reduces + * the number of comparisons necessary. + * + * @private + */ +class GridIndex { + circleKeys: Array; + boxKeys: Array; + boxCells: Array>; + circleCells: Array>; + bboxes: Array; + circles: Array; + xCellCount: number; + yCellCount: number; + width: number; + height: number; + xScale: number; + yScale: number; + boxUid: number; + circleUid: number; + + constructor (width: number, height: number, cellSize: number) { + const boxCells = this.boxCells = []; + const circleCells = this.circleCells = []; + + // More cells -> fewer geometries to check per cell, but items tend + // to be split across more cells. + // Sweet spot allows most small items to fit in one cell + this.xCellCount = Math.ceil(width / cellSize); + this.yCellCount = Math.ceil(height / cellSize); + + for (let i = 0; i < this.xCellCount * this.yCellCount; i++) { + boxCells.push([]); + circleCells.push([]); + } + this.circleKeys = []; + this.boxKeys = []; + this.bboxes = []; + this.circles = []; + + this.width = width; + this.height = height; + this.xScale = this.xCellCount / width; + this.yScale = this.yCellCount / height; + this.boxUid = 0; + this.circleUid = 0; + } + + keysLength() { + return this.boxKeys.length + this.circleKeys.length; + } + + insert(key: any, x1: number, y1: number, x2: number, y2: number) { + this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++); + this.boxKeys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + + insertCircle(key: any, x: number, y: number, radius: number) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++); + this.circleKeys.push(key); + this.circles.push(x); + this.circles.push(y); + this.circles.push(radius); + } + + _insertBoxCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) { + this.boxCells[cellIndex].push(uid); + } + + _insertCircleCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) { + this.circleCells[cellIndex].push(uid); + } + + _query(x1: number, y1: number, x2: number, y2: number, hitTest: boolean, predicate?: any) { + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return hitTest ? false : []; + } + const result = []; + if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) { + if (hitTest) { + return true; + } + for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) { + result.push({ + key: this.boxKeys[boxUid], + x1: this.bboxes[boxUid * 4], + y1: this.bboxes[boxUid * 4 + 1], + x2: this.bboxes[boxUid * 4 + 2], + y2: this.bboxes[boxUid * 4 + 3] + }); + } + for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) { + const x = this.circles[circleUid * 3]; + const y = this.circles[circleUid * 3 + 1]; + const radius = this.circles[circleUid * 3 + 2]; + result.push({ + key: this.circleKeys[circleUid], + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + } + return predicate ? result.filter(predicate) : result; + } else { + const queryArgs = { + hitTest, + seenUids: {box: {}, circle: {}} + }; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate); + return hitTest ? result.length > 0 : result; + } + } + + _queryCircle(x: number, y: number, radius: number, hitTest: boolean, predicate?: any) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + const x1 = x - radius; + const x2 = x + radius; + const y1 = y - radius; + const y2 = y + radius; + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return hitTest ? false : []; + } + + // Box query early exits if the bounding box is larger than the grid, but we don't do + // the equivalent calculation for circle queries because early exit is less likely + // and the calculation is more expensive + const result = []; + const queryArgs = { + hitTest, + circle: {x, y, radius}, + seenUids: {box: {}, circle: {}} + }; + this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate); + return hitTest ? result.length > 0 : result; + } + + query(x1: number, y1: number, x2: number, y2: number, predicate?: any): Array { + return (this._query(x1, y1, x2, y2, false, predicate): any); + } + + hitTest(x1: number, y1: number, x2: number, y2: number, predicate?: any): boolean { + return (this._query(x1, y1, x2, y2, true, predicate): any); + } + + hitTestCircle(x: number, y: number, radius: number, predicate?: any): boolean { + return (this._queryCircle(x, y, radius, true, predicate): any); + } + + _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) { + const seenUids = queryArgs.seenUids; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + if ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]) && + (!predicate || predicate(this.boxKeys[boxUid]))) { + if (queryArgs.hitTest) { + result.push(true); + return true; + } else { + result.push({ + key: this.boxKeys[boxUid], + x1: bboxes[offset], + y1: bboxes[offset + 1], + x2: bboxes[offset + 2], + y2: bboxes[offset + 3] + }); + } + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + if (this._circleAndRectCollide( + circles[offset], + circles[offset + 1], + circles[offset + 2], + x1, + y1, + x2, + y2) && + (!predicate || predicate(this.circleKeys[circleUid]))) { + if (queryArgs.hitTest) { + result.push(true); + return true; + } else { + const x = circles[offset]; + const y = circles[offset + 1]; + const radius = circles[offset + 2]; + result.push({ + key: this.circleKeys[circleUid], + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + } + } + } + } + } + } + + _queryCellCircle(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) { + const circle = queryArgs.circle; + const seenUids = queryArgs.seenUids; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + if (this._circleAndRectCollide( + circle.x, + circle.y, + circle.radius, + bboxes[offset + 0], + bboxes[offset + 1], + bboxes[offset + 2], + bboxes[offset + 3]) && + (!predicate || predicate(this.boxKeys[boxUid]))) { + result.push(true); + return true; + } + } + } + } + + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + if (this._circlesCollide( + circles[offset], + circles[offset + 1], + circles[offset + 2], + circle.x, + circle.y, + circle.radius) && + (!predicate || predicate(this.circleKeys[circleUid]))) { + result.push(true); + return true; + } + } + } + } + } + + _forEachCell(x1: number, y1: number, x2: number, y2: number, fn: any, arg1: any, arg2?: any, predicate?: any) { + const cx1 = this._convertToXCellCoord(x1); + const cy1 = this._convertToYCellCoord(y1); + const cx2 = this._convertToXCellCoord(x2); + const cy2 = this._convertToYCellCoord(y2); + + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.xCellCount * y + x; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) return; + } + } + } + + _convertToXCellCoord(x: number) { + return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale))); + } + + _convertToYCellCoord(y: number) { + return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale))); + } + + _circlesCollide(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number): boolean { + const dx = x2 - x1; + const dy = y2 - y1; + const bothRadii = r1 + r2; + return (bothRadii * bothRadii) > (dx * dx + dy * dy); + } + + _circleAndRectCollide(circleX: number, circleY: number, radius: number, x1: number, y1: number, x2: number, y2: number): boolean { + const halfRectWidth = (x2 - x1) / 2; + const distX = Math.abs(circleX - (x1 + halfRectWidth)); + if (distX > (halfRectWidth + radius)) { + return false; + } + + const halfRectHeight = (y2 - y1) / 2; + const distY = Math.abs(circleY - (y1 + halfRectHeight)); + if (distY > (halfRectHeight + radius)) { + return false; + } + + if (distX <= halfRectWidth || distY <= halfRectHeight) { + return true; + } + + const dx = distX - halfRectWidth; + const dy = distY - halfRectHeight; + return (dx * dx + dy * dy <= (radius * radius)); + } +} + +export default GridIndex; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/mergelines.js b/node_modules/@plotly/mapbox-gl/src/symbol/mergelines.js new file mode 100644 index 0000000000000000000000000000000000000000..34b5d383495c4ac5fb5ab4781d734215f326ae40 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/mergelines.js @@ -0,0 +1,82 @@ +// @flow + +import type {SymbolFeature} from '../data/bucket/symbol_bucket'; + +export default function (features: Array): Array { + const leftIndex: {[_: string]: number} = {}; + const rightIndex: {[_: string]: number} = {}; + const mergedFeatures = []; + let mergedIndex = 0; + + function add(k) { + mergedFeatures.push(features[k]); + mergedIndex++; + } + + function mergeFromRight(leftKey: string, rightKey: string, geom) { + const i = rightIndex[leftKey]; + delete rightIndex[leftKey]; + rightIndex[rightKey] = i; + + mergedFeatures[i].geometry[0].pop(); + mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]); + return i; + } + + function mergeFromLeft(leftKey: string, rightKey: string, geom) { + const i = leftIndex[rightKey]; + delete leftIndex[rightKey]; + leftIndex[leftKey] = i; + + mergedFeatures[i].geometry[0].shift(); + mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]); + return i; + } + + function getKey(text, geom, onRight) { + const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0]; + return `${text}:${point.x}:${point.y}`; + } + + for (let k = 0; k < features.length; k++) { + const feature = features[k]; + const geom = feature.geometry; + const text = feature.text ? feature.text.toString() : null; + + if (!text) { + add(k); + continue; + } + + const leftKey = getKey(text, geom), + rightKey = getKey(text, geom, true); + + if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) { + // found lines with the same text adjacent to both ends of the current line, merge all three + const j = mergeFromLeft(leftKey, rightKey, geom); + const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry); + + delete leftIndex[leftKey]; + delete rightIndex[rightKey]; + + rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i; + mergedFeatures[j].geometry = (null: any); + + } else if (leftKey in rightIndex) { + // found mergeable line adjacent to the start of the current line, merge + mergeFromRight(leftKey, rightKey, geom); + + } else if (rightKey in leftIndex) { + // found mergeable line adjacent to the end of the current line, merge + mergeFromLeft(leftKey, rightKey, geom); + + } else { + // no adjacent lines, add as a new item + add(k); + leftIndex[leftKey] = mergedIndex - 1; + rightIndex[rightKey] = mergedIndex - 1; + } + } + + return mergedFeatures.filter((f) => f.geometry); +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/one_em.js b/node_modules/@plotly/mapbox-gl/src/symbol/one_em.js new file mode 100644 index 0000000000000000000000000000000000000000..7e20115bd9625c3f50b9d196358b458d50982c8a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/one_em.js @@ -0,0 +1,4 @@ +// @flow +// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout + +export default 24; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/opacity_state.js b/node_modules/@plotly/mapbox-gl/src/symbol/opacity_state.js new file mode 100644 index 0000000000000000000000000000000000000000..1649b2c2a0f603bbd7b0924b28848c06938fec50 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/opacity_state.js @@ -0,0 +1,27 @@ +// @flow + +import {register} from '../util/web_worker_transfer'; + +class OpacityState { + opacity: number; + targetOpacity: number; + time: number + + constructor() { + this.opacity = 0; + this.targetOpacity = 0; + this.time = 0; + } + + clone() { + const clone = new OpacityState(); + clone.opacity = this.opacity; + clone.targetOpacity = this.targetOpacity; + clone.time = this.time; + return clone; + } +} + +register('OpacityState', OpacityState); + +export default OpacityState; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/path_interpolator.js b/node_modules/@plotly/mapbox-gl/src/symbol/path_interpolator.js new file mode 100644 index 0000000000000000000000000000000000000000..f64467a5a99cb441bd51d9af041afb9df8fc714a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/path_interpolator.js @@ -0,0 +1,61 @@ +// @flow + +import {clamp} from '../util/util'; +import Point from '@mapbox/point-geometry'; +import assert from 'assert'; + +class PathInterpolator { + points: Array; + length: number; + paddedLength: number; + padding: number; + _distances: Array; + + constructor(points_: ?Array, padding_: ?number) { + this.reset(points_, padding_); + } + + reset(points_: ?Array, padding_: ?number) { + this.points = points_ || []; + + // Compute cumulative distance from first point to every other point in the segment. + // Last entry in the array is total length of the path + this._distances = [0.0]; + + for (let i = 1; i < this.points.length; i++) { + this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]); + } + + this.length = this._distances[this._distances.length - 1]; + this.padding = Math.min(padding_ || 0, this.length * 0.5); + this.paddedLength = this.length - this.padding * 2.0; + } + + lerp(t: number): Point { + assert(this.points.length > 0); + if (this.points.length === 1) { + return this.points[0]; + } + + t = clamp(t, 0, 1); + + // Find the correct segment [p0, p1] where p0 <= x < p1 + let currentIndex = 1; + let distOfCurrentIdx = this._distances[currentIndex]; + const distToTarget = t * this.paddedLength + this.padding; + + while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) { + distOfCurrentIdx = this._distances[++currentIndex]; + } + + // Interpolate between the two points of the segment + const idxOfPrevPoint = currentIndex - 1; + const distOfPrevIdx = this._distances[idxOfPrevPoint]; + const segmentLength = distOfCurrentIdx - distOfPrevIdx; + const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0; + + return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT)); + } +} + +export default PathInterpolator; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/placement.js b/node_modules/@plotly/mapbox-gl/src/symbol/placement.js new file mode 100644 index 0000000000000000000000000000000000000000..b7e06fb865af552e967d8bc676f23c9d556abf57 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/placement.js @@ -0,0 +1,1124 @@ +// @flow + +import CollisionIndex from './collision_index'; +import EXTENT from '../data/extent'; +import * as symbolSize from './symbol_size'; +import * as projection from './projection'; +import {getAnchorJustification, evaluateVariableOffset} from './symbol_layout'; +import {getAnchorAlignment, WritingMode} from './shaping'; +import {mat4} from 'gl-matrix'; +import assert from 'assert'; +import pixelsToTileUnits from '../source/pixels_to_tile_units'; +import Point from '@mapbox/point-geometry'; +import type Transform from '../geo/transform'; +import type StyleLayer from '../style/style_layer'; + +import type Tile from '../source/tile'; +import type SymbolBucket, {CollisionArrays, SingleCollisionBox} from '../data/bucket/symbol_bucket'; +import type {CollisionBoxArray, CollisionVertexArray, SymbolInstance} from '../data/array_types'; +import type FeatureIndex from '../data/feature_index'; +import type {OverscaledTileID} from '../source/tile_id'; +import type {TextAnchor} from './symbol_layout'; + +class OpacityState { + opacity: number; + placed: boolean; + constructor(prevState: ?OpacityState, increment: number, placed: boolean, skipFade: ?boolean) { + if (prevState) { + this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment))); + } else { + this.opacity = (skipFade && placed) ? 1 : 0; + } + this.placed = placed; + } + isHidden() { + return this.opacity === 0 && !this.placed; + } +} + +class JointOpacityState { + text: OpacityState; + icon: OpacityState; + constructor(prevState: ?JointOpacityState, increment: number, placedText: boolean, placedIcon: boolean, skipFade: ?boolean) { + this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade); + this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade); + } + isHidden() { + return this.text.isHidden() && this.icon.isHidden(); + } +} + +class JointPlacement { + text: boolean; + icon: boolean; + // skipFade = outside viewport, but within CollisionIndex::viewportPadding px of the edge + // Because these symbols aren't onscreen yet, we can skip the "fade in" animation, + // and if a subsequent viewport change brings them into view, they'll be fully + // visible right away. + skipFade: boolean; + constructor(text: boolean, icon: boolean, skipFade: boolean) { + this.text = text; + this.icon = icon; + this.skipFade = skipFade; + } +} + +class CollisionCircleArray { + // Stores collision circles and placement matrices of a bucket for debug rendering. + invProjMatrix: mat4; + viewportMatrix: mat4; + circles: Array; + + constructor() { + this.invProjMatrix = mat4.create(); + this.viewportMatrix = mat4.create(); + this.circles = []; + } +} + +export class RetainedQueryData { + bucketInstanceId: number; + featureIndex: FeatureIndex; + sourceLayerIndex: number; + bucketIndex: number; + tileID: OverscaledTileID; + featureSortOrder: ?Array + constructor(bucketInstanceId: number, + featureIndex: FeatureIndex, + sourceLayerIndex: number, + bucketIndex: number, + tileID: OverscaledTileID) { + this.bucketInstanceId = bucketInstanceId; + this.featureIndex = featureIndex; + this.sourceLayerIndex = sourceLayerIndex; + this.bucketIndex = bucketIndex; + this.tileID = tileID; + } +} + +type CollisionGroup = { ID: number, predicate?: any }; + +class CollisionGroups { + collisionGroups: {[groupName: string]: CollisionGroup}; + maxGroupID: number; + crossSourceCollisions: boolean; + + constructor(crossSourceCollisions: boolean) { + this.crossSourceCollisions = crossSourceCollisions; + this.maxGroupID = 0; + this.collisionGroups = {}; + } + + get(sourceID: string) { + // The predicate/groupID mechanism allows for arbitrary grouping, + // but the current interface defines one source == one group when + // crossSourceCollisions == true. + if (!this.crossSourceCollisions) { + if (!this.collisionGroups[sourceID]) { + const nextGroupID = ++this.maxGroupID; + this.collisionGroups[sourceID] = { + ID: nextGroupID, + predicate: (key) => { + return key.collisionGroupID === nextGroupID; + } + }; + } + return this.collisionGroups[sourceID]; + } else { + return {ID: 0, predicate: null}; + } + } +} + +function calculateVariableLayoutShift(anchor: TextAnchor, width: number, height: number, textOffset: [number, number], textBoxScale: number): Point { + const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + const offset = evaluateVariableOffset(anchor, textOffset); + return new Point( + shiftX + offset[0] * textBoxScale, + shiftY + offset[1] * textBoxScale + ); +} + +function shiftVariableCollisionBox(collisionBox: SingleCollisionBox, + shiftX: number, shiftY: number, + rotateWithMap: boolean, pitchWithMap: boolean, + angle: number) { + const {x1, x2, y1, y2, anchorPointX, anchorPointY} = collisionBox; + const rotatedOffset = new Point(shiftX, shiftY); + if (rotateWithMap) { + rotatedOffset._rotate(pitchWithMap ? angle : -angle); + } + return { + x1: x1 + rotatedOffset.x, + y1: y1 + rotatedOffset.y, + x2: x2 + rotatedOffset.x, + y2: y2 + rotatedOffset.y, + // symbol anchor point stays the same regardless of text-anchor + anchorPointX, + anchorPointY + }; +} + +export type VariableOffset = { + textOffset: [number, number], + width: number, + height: number, + anchor: TextAnchor, + textBoxScale: number, + prevAnchor?: TextAnchor +}; + +type TileLayerParameters = { + bucket: SymbolBucket, + layout: any, + posMatrix: mat4, + textLabelPlaneMatrix: mat4, + labelToScreenMatrix: mat4, + scale: number, + textPixelRatio: number, + holdingForFade: boolean, + collisionBoxArray: ?CollisionBoxArray, + partiallyEvaluatedTextSize: any, + collisionGroup: any +}; + +export type BucketPart = { + sortKey?: number | void, + symbolInstanceStart: number, + symbolInstanceEnd: number, + parameters: TileLayerParameters +}; + +export type CrossTileID = string | number; + +export class Placement { + transform: Transform; + collisionIndex: CollisionIndex; + placements: { [_: CrossTileID]: JointPlacement }; + opacities: { [_: CrossTileID]: JointOpacityState }; + variableOffsets: {[_: CrossTileID]: VariableOffset }; + placedOrientations: {[_: CrossTileID]: number }; + commitTime: number; + prevZoomAdjustment: number; + lastPlacementChangeTime: number; + stale: boolean; + fadeDuration: number; + retainedQueryData: {[_: number]: RetainedQueryData}; + collisionGroups: CollisionGroups; + prevPlacement: ?Placement; + zoomAtLastRecencyCheck: number; + collisionCircleArrays: {[any]: CollisionCircleArray}; + + constructor(transform: Transform, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement) { + this.transform = transform.clone(); + this.collisionIndex = new CollisionIndex(this.transform); + this.placements = {}; + this.opacities = {}; + this.variableOffsets = {}; + this.stale = false; + this.commitTime = 0; + this.fadeDuration = fadeDuration; + this.retainedQueryData = {}; + this.collisionGroups = new CollisionGroups(crossSourceCollisions); + this.collisionCircleArrays = {}; + + this.prevPlacement = prevPlacement; + if (prevPlacement) { + prevPlacement.prevPlacement = undefined; // Only hold on to one placement back + } + + this.placedOrientations = {}; + } + + getBucketParts(results: Array, styleLayer: StyleLayer, tile: Tile, sortAcrossTiles: boolean) { + const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket); + const bucketFeatureIndex = tile.latestFeatureIndex; + if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) + return; + + const collisionBoxArray = tile.collisionBoxArray; + + const layout = symbolBucket.layers[0].layout; + + const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ); + const textPixelRatio = tile.tileSize / EXTENT; + + const posMatrix = this.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom); + + const textLabelPlaneMatrix = projection.getLabelPlaneMatrix(posMatrix, + pitchWithMap, + rotateWithMap, + this.transform, + pixelsToTiles); + + let labelToScreenMatrix = null; + + if (pitchWithMap) { + const glMatrix = projection.getGlCoordMatrix( + posMatrix, + pitchWithMap, + rotateWithMap, + this.transform, + pixelsToTiles); + + labelToScreenMatrix = mat4.multiply([], this.transform.labelPlaneMatrix, glMatrix); + } + + // As long as this placement lives, we have to hold onto this bucket's + // matching FeatureIndex/data for querying purposes + this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData( + symbolBucket.bucketInstanceId, + bucketFeatureIndex, + symbolBucket.sourceLayerIndex, + symbolBucket.index, + tile.tileID + ); + + const parameters = { + bucket: symbolBucket, + layout, + posMatrix, + textLabelPlaneMatrix, + labelToScreenMatrix, + scale, + textPixelRatio, + holdingForFade: tile.holdingForFade(), + collisionBoxArray, + partiallyEvaluatedTextSize: symbolSize.evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom), + collisionGroup: this.collisionGroups.get(symbolBucket.sourceID) + }; + + if (sortAcrossTiles) { + for (const range of symbolBucket.sortKeyRanges) { + const {sortKey, symbolInstanceStart, symbolInstanceEnd} = range; + results.push({sortKey, symbolInstanceStart, symbolInstanceEnd, parameters}); + } + } else { + results.push({ + symbolInstanceStart: 0, + symbolInstanceEnd: symbolBucket.symbolInstances.length, + parameters + }); + } + } + + attemptAnchorPlacement(anchor: TextAnchor, textBox: SingleCollisionBox, width: number, height: number, + textBoxScale: number, rotateWithMap: boolean, + pitchWithMap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroup: CollisionGroup, + textAllowOverlap: boolean, symbolInstance: SymbolInstance, bucket: SymbolBucket, orientation: number, iconBox: ?SingleCollisionBox): ?{ shift: Point, placedGlyphBoxes: { box: Array, offscreen: boolean } } { + + const textOffset = [symbolInstance.textOffset0, symbolInstance.textOffset1]; + const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale); + + const placedGlyphBoxes = this.collisionIndex.placeCollisionBox( + shiftVariableCollisionBox( + textBox, shift.x, shift.y, + rotateWithMap, pitchWithMap, this.transform.angle), + textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate); + + if (iconBox) { + const placedIconBoxes = this.collisionIndex.placeCollisionBox( + shiftVariableCollisionBox( + iconBox, shift.x, shift.y, + rotateWithMap, pitchWithMap, this.transform.angle), + textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate); + if (placedIconBoxes.box.length === 0) return; + } + + if (placedGlyphBoxes.box.length > 0) { + let prevAnchor; + // If this label was placed in the previous placement, record the anchor position + // to allow us to animate the transition + if (this.prevPlacement && + this.prevPlacement.variableOffsets[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID].text) { + prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor; + } + assert(symbolInstance.crossTileID !== 0); + this.variableOffsets[symbolInstance.crossTileID] = { + textOffset, + width, + height, + anchor, + textBoxScale, + prevAnchor + }; + this.markUsedJustification(bucket, anchor, symbolInstance, orientation); + + if (bucket.allowVerticalPlacement) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + + return {shift, placedGlyphBoxes}; + } + } + + placeLayerBucketPart(bucketPart: Object, seenCrossTileIDs: { [string | number]: boolean }, showCollisionBoxes: boolean) { + + const { + bucket, + layout, + posMatrix, + textLabelPlaneMatrix, + labelToScreenMatrix, + textPixelRatio, + holdingForFade, + collisionBoxArray, + partiallyEvaluatedTextSize, + collisionGroup + } = bucketPart.parameters; + + const textOptional = layout.get('text-optional'); + const iconOptional = layout.get('icon-optional'); + const textAllowOverlap = layout.get('text-allow-overlap'); + const iconAllowOverlap = layout.get('icon-allow-overlap'); + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y'; + + // This logic is similar to the "defaultOpacityState" logic below in updateBucketOpacities + // If we know a symbol is always supposed to show, force it to be marked visible even if + // it wasn't placed into the collision index (because some or all of it was outside the range + // of the collision grid). + // There is a subtle edge case here we're accepting: + // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false + // A's icon is outside the grid, so doesn't get placed + // A's text would be inside grid, but doesn't get placed because of icon-optional: false + // We still show A because of the allow-overlap settings. + // Symbol B has allow-overlap: false, and gets placed where A's text would be + // On panning in, there is a short period when Symbol B and Symbol A will overlap + // This is the reverse of our normal policy of "fade in on pan", but should look like any other + // collision and hopefully not be too noticeable. + // See https://github.com/mapbox/mapbox-gl-js/issues/7172 + const alwaysShowText = textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || iconOptional); + const alwaysShowIcon = iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || textOptional); + + if (!bucket.collisionArrays && collisionBoxArray) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + + const placeSymbol = (symbolInstance: SymbolInstance, collisionArrays: CollisionArrays) => { + if (seenCrossTileIDs[symbolInstance.crossTileID]) return; + if (holdingForFade) { + // Mark all symbols from this tile as "not placed", but don't add to seenCrossTileIDs, because we don't + // know yet if we have a duplicate in a parent tile that _should_ be placed. + this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false); + return; + } + + let placeText = false; + let placeIcon = false; + let offscreen = true; + let shift = null; + + let placed = {box: null, offscreen: null}; + let placedVerticalText = {box: null, offscreen: null}; + + let placedGlyphBoxes = null; + let placedGlyphCircles = null; + let placedIconBoxes = null; + let textFeatureIndex = 0; + let verticalTextFeatureIndex = 0; + let iconFeatureIndex = 0; + + if (collisionArrays.textFeatureIndex) { + textFeatureIndex = collisionArrays.textFeatureIndex; + } else if (symbolInstance.useRuntimeCollisionCircles) { + textFeatureIndex = symbolInstance.featureIndex; + } + if (collisionArrays.verticalTextFeatureIndex) { + verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex; + } + + const textBox = collisionArrays.textBox; + if (textBox) { + + const updatePreviousOrientationIfNotPlaced = (isPlaced) => { + let previousOrientation = WritingMode.horizontal; + if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) { + const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID]; + if (prevPlacedOrientation) { + this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation; + previousOrientation = prevPlacedOrientation; + this.markUsedOrientation(bucket, previousOrientation, symbolInstance); + } + } + return previousOrientation; + }; + + const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => { + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) { + for (const placementMode of bucket.writingModes) { + if (placementMode === WritingMode.vertical) { + placed = placeVerticalFn(); + placedVerticalText = placed; + } else { + placed = placeHorizontalFn(); + } + if (placed && placed.box && placed.box.length) break; + } + } else { + placed = placeHorizontalFn(); + } + }; + + if (!layout.get('text-variable-anchor')) { + const placeBox = (collisionTextBox, orientation) => { + const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, textAllowOverlap, + textPixelRatio, posMatrix, collisionGroup.predicate); + if (placedFeature && placedFeature.box && placedFeature.box.length) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return placedFeature; + }; + + const placeHorizontal = () => { + return placeBox(textBox, WritingMode.horizontal); + }; + + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBox(verticalTextBox, WritingMode.vertical); + } + return {box: null, offscreen: null}; + }; + + placeTextForPlacementModes(placeHorizontal, placeVertical); + updatePreviousOrientationIfNotPlaced(placed && placed.box && placed.box.length); + + } else { + let anchors = layout.get('text-variable-anchor'); + + // If this symbol was in the last placement, shift the previously used + // anchor to the front of the anchor list, only if the previous anchor + // is still in the anchor list + if (this.prevPlacement && this.prevPlacement.variableOffsets[symbolInstance.crossTileID]) { + const prevOffsets = this.prevPlacement.variableOffsets[symbolInstance.crossTileID]; + if (anchors.indexOf(prevOffsets.anchor) > 0) { + anchors = anchors.filter(anchor => anchor !== prevOffsets.anchor); + anchors.unshift(prevOffsets.anchor); + } + } + + const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => { + const width = collisionTextBox.x2 - collisionTextBox.x1; + const height = collisionTextBox.y2 - collisionTextBox.y1; + const textBoxScale = symbolInstance.textBoxScale; + + const variableIconBox = hasIconTextFit && !iconAllowOverlap ? collisionIconBox : null; + + let placedBox: ?{ box: Array, offscreen: boolean } = {box: [], offscreen: false}; + const placementAttempts = textAllowOverlap ? anchors.length * 2 : anchors.length; + for (let i = 0; i < placementAttempts; ++i) { + const anchor = anchors[i % anchors.length]; + const allowOverlap = (i >= anchors.length); + const result = this.attemptAnchorPlacement( + anchor, collisionTextBox, width, height, + textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, + collisionGroup, allowOverlap, symbolInstance, bucket, orientation, variableIconBox); + + if (result) { + placedBox = result.placedGlyphBoxes; + if (placedBox && placedBox.box && placedBox.box.length) { + placeText = true; + shift = result.shift; + break; + } + } + } + + return placedBox; + }; + + const placeHorizontal = () => { + return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, WritingMode.horizontal); + }; + + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + const wasPlaced = placed && placed.box && placed.box.length; + if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, WritingMode.vertical); + } + return {box: null, offscreen: null}; + }; + + placeTextForPlacementModes(placeHorizontal, placeVertical); + + if (placed) { + placeText = placed.box; + offscreen = placed.offscreen; + } + + const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.box); + + // If we didn't get placed, we still need to copy our position from the last placement for + // fade animations + if (!placeText && this.prevPlacement) { + const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.variableOffsets[symbolInstance.crossTileID] = prevOffset; + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation); + } + } + + } + } + + placedGlyphBoxes = placed; + placeText = placedGlyphBoxes && placedGlyphBoxes.box && placedGlyphBoxes.box.length > 0; + + offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen; + + if (symbolInstance.useRuntimeCollisionCircles) { + const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex); + const fontSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol); + + const textPixelPadding = layout.get('text-padding'); + const circlePixelDiameter = symbolInstance.collisionCircleDiameter; + + placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textAllowOverlap, + placedSymbol, + bucket.lineVertexArray, + bucket.glyphOffsetArray, + fontSize, + posMatrix, + textLabelPlaneMatrix, + labelToScreenMatrix, + showCollisionBoxes, + pitchWithMap, + collisionGroup.predicate, + circlePixelDiameter, + textPixelPadding); + + assert(!placedGlyphCircles.circles.length || (!placedGlyphCircles.collisionDetected || showCollisionBoxes)); + // If text-allow-overlap is set, force "placedCircles" to true + // In theory there should always be at least one circle placed + // in this case, but for now quirks in text-anchor + // and text-offset may prevent that from being true. + placeText = textAllowOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected); + offscreen = offscreen && placedGlyphCircles.offscreen; + } + + if (collisionArrays.iconFeatureIndex) { + iconFeatureIndex = collisionArrays.iconFeatureIndex; + } + + if (collisionArrays.iconBox) { + + const placeIconFeature = iconBox => { + const shiftedIconBox = hasIconTextFit && shift ? + shiftVariableCollisionBox( + iconBox, shift.x, shift.y, + rotateWithMap, pitchWithMap, this.transform.angle) : + iconBox; + return this.collisionIndex.placeCollisionBox(shiftedIconBox, + iconAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate); + }; + + if (placedVerticalText && placedVerticalText.box && placedVerticalText.box.length && collisionArrays.verticalIconBox) { + placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox); + placeIcon = placedIconBoxes.box.length > 0; + } else { + placedIconBoxes = placeIconFeature(collisionArrays.iconBox); + placeIcon = placedIconBoxes.box.length > 0; + } + offscreen = offscreen && placedIconBoxes.offscreen; + } + + const iconWithoutText = textOptional || + (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0); + const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0; + + // Combine the scales for icons and text. + if (!iconWithoutText && !textWithoutIcon) { + placeIcon = placeText = placeIcon && placeText; + } else if (!textWithoutIcon) { + placeText = placeIcon && placeText; + } else if (!iconWithoutText) { + placeIcon = placeIcon && placeText; + } + + if (placeText && placedGlyphBoxes && placedGlyphBoxes.box) { + if (placedVerticalText && placedVerticalText.box && verticalTextFeatureIndex) { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'), + bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID); + } else { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'), + bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + + } + if (placeIcon && placedIconBoxes) { + this.collisionIndex.insertCollisionBox(placedIconBoxes.box, layout.get('icon-ignore-placement'), + bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID); + } + if (placedGlyphCircles) { + if (placeText) { + this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, layout.get('text-ignore-placement'), + bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + + if (showCollisionBoxes) { + const id = bucket.bucketInstanceId; + let circleArray = this.collisionCircleArrays[id]; + + // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement + // for a bucket is not guaranteed to be complete before the commit-function has been called + if (circleArray === undefined) + circleArray = this.collisionCircleArrays[id] = new CollisionCircleArray(); + + for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) { + circleArray.circles.push(placedGlyphCircles.circles[i + 0]); // x + circleArray.circles.push(placedGlyphCircles.circles[i + 1]); // y + circleArray.circles.push(placedGlyphCircles.circles[i + 2]); // radius + circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0); // collisionDetected-flag + } + } + } + + assert(symbolInstance.crossTileID !== 0); + assert(bucket.bucketInstanceId !== 0); + + this.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded); + seenCrossTileIDs[symbolInstance.crossTileID] = true; + }; + + if (zOrderByViewportY) { + assert(bucketPart.symbolInstanceStart === 0); + const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle); + for (let i = symbolIndexes.length - 1; i >= 0; --i) { + const symbolIndex = symbolIndexes[i]; + placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex]); + } + } else { + for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) { + placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i]); + } + } + + if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) { + const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId]; + + // Store viewport and inverse projection matrices per bucket + mat4.invert(circleArray.invProjMatrix, posMatrix); + circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix(); + } + + bucket.justReloaded = false; + } + + markUsedJustification(bucket: SymbolBucket, placedAnchor: TextAnchor, symbolInstance: SymbolInstance, orientation: number) { + const justifications = { + "left": symbolInstance.leftJustifiedTextSymbolIndex, + "center": symbolInstance.centerJustifiedTextSymbolIndex, + "right": symbolInstance.rightJustifiedTextSymbolIndex + }; + + let autoIndex; + if (orientation === WritingMode.vertical) { + autoIndex = symbolInstance.verticalPlacedTextSymbolIndex; + } else { + autoIndex = justifications[getAnchorJustification(placedAnchor)]; + } + + const indexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.verticalPlacedTextSymbolIndex + ]; + + for (const index of indexes) { + if (index >= 0) { + if (autoIndex >= 0 && index !== autoIndex) { + // There are multiple justifications and this one isn't it: shift offscreen + bucket.text.placedSymbolArray.get(index).crossTileID = 0; + } else { + // Either this is the chosen justification or the justification is hardwired: use this one + bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID; + } + } + } + } + + markUsedOrientation(bucket: SymbolBucket, orientation: number, symbolInstance: SymbolInstance) { + const horizontal = (orientation === WritingMode.horizontal || orientation === WritingMode.horizontalOnly) ? orientation : 0; + const vertical = orientation === WritingMode.vertical ? orientation : 0; + + const horizontalIndexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex + ]; + + for (const index of horizontalIndexes) { + bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal; + } + + if (symbolInstance.verticalPlacedTextSymbolIndex) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical; + } + } + + commit(now: number): void { + this.commitTime = now; + this.zoomAtLastRecencyCheck = this.transform.zoom; + + const prevPlacement = this.prevPlacement; + let placementChanged = false; + + this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0; + const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1; + + const prevOpacities = prevPlacement ? prevPlacement.opacities : {}; + const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {}; + const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {}; + + // add the opacities from the current placement, and copy their current values from the previous placement + for (const crossTileID in this.placements) { + const jointPlacement = this.placements[crossTileID]; + const prevOpacity = prevOpacities[crossTileID]; + if (prevOpacity) { + this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon); + placementChanged = placementChanged || + jointPlacement.text !== prevOpacity.text.placed || + jointPlacement.icon !== prevOpacity.icon.placed; + } else { + this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade); + placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon; + } + } + + // copy and update values from the previous placement that aren't in the current placement but haven't finished fading + for (const crossTileID in prevOpacities) { + const prevOpacity = prevOpacities[crossTileID]; + if (!this.opacities[crossTileID]) { + const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false); + if (!jointOpacity.isHidden()) { + this.opacities[crossTileID] = jointOpacity; + placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed; + } + } + } + for (const crossTileID in prevOffsets) { + if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.variableOffsets[crossTileID] = prevOffsets[crossTileID]; + } + } + + for (const crossTileID in prevOrientations) { + if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.placedOrientations[crossTileID] = prevOrientations[crossTileID]; + } + } + + // this.lastPlacementChangeTime is the time of the last commit() that + // resulted in a placement change -- in other words, the start time of + // the last symbol fade animation + assert(!prevPlacement || prevPlacement.lastPlacementChangeTime !== undefined); + if (placementChanged) { + this.lastPlacementChangeTime = now; + } else if (typeof this.lastPlacementChangeTime !== 'number') { + this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now; + } + } + + updateLayerOpacities(styleLayer: StyleLayer, tiles: Array) { + const seenCrossTileIDs = {}; + for (const tile of tiles) { + const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket); + if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) { + this.updateBucketOpacities(symbolBucket, seenCrossTileIDs, tile.collisionBoxArray); + } + } + } + + updateBucketOpacities(bucket: SymbolBucket, seenCrossTileIDs: { [string | number]: boolean }, collisionBoxArray: ?CollisionBoxArray) { + if (bucket.hasTextData()) bucket.text.opacityVertexArray.clear(); + if (bucket.hasIconData()) bucket.icon.opacityVertexArray.clear(); + if (bucket.hasIconCollisionBoxData()) bucket.iconCollisionBox.collisionVertexArray.clear(); + if (bucket.hasTextCollisionBoxData()) bucket.textCollisionBox.collisionVertexArray.clear(); + + const layout = bucket.layers[0].layout; + const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true); + const textAllowOverlap = layout.get('text-allow-overlap'); + const iconAllowOverlap = layout.get('icon-allow-overlap'); + const variablePlacement = layout.get('text-variable-anchor'); + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + // If allow-overlap is true, we can show symbols before placement runs on them + // But we have to wait for placement if we potentially depend on a paired icon/text + // with allow-overlap: false. + // See https://github.com/mapbox/mapbox-gl-js/issues/7032 + const defaultOpacityState = new JointOpacityState(null, 0, + textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')), + iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')), + true); + + if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + + const addOpacities = (iconOrText, numVertices: number, opacity: number) => { + for (let i = 0; i < numVertices / 4; i++) { + iconOrText.opacityVertexArray.emplaceBack(opacity); + } + }; + + for (let s = 0; s < bucket.symbolInstances.length; s++) { + const symbolInstance = bucket.symbolInstances.get(s); + const { + numHorizontalGlyphVertices, + numVerticalGlyphVertices, + crossTileID + } = symbolInstance; + + const isDuplicate = seenCrossTileIDs[crossTileID]; + + let opacityState = this.opacities[crossTileID]; + if (isDuplicate) { + opacityState = duplicateOpacityState; + } else if (!opacityState) { + opacityState = defaultOpacityState; + // store the state so that future placements use it as a starting point + this.opacities[crossTileID] = opacityState; + } + + seenCrossTileIDs[crossTileID] = true; + + const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0; + const hasIcon = symbolInstance.numIconVertices > 0; + + const placedOrientation = this.placedOrientations[symbolInstance.crossTileID]; + const horizontalHidden = placedOrientation === WritingMode.vertical; + const verticalHidden = placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly; + + if (hasText) { + const packedOpacity = packOpacity(opacityState.text); + // Vertical text fades in/out on collision the same way as corresponding + // horizontal text. Switch between vertical/horizontal should be instantaneous + const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity); + const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity); + + // If this label is completely faded, mark it so that we don't have to calculate + // its position at render time. If this layer has variable placement, shift the various + // symbol instances appropriately so that symbols from buckets that have yet to be placed + // offset appropriately. + const symbolHidden = opacityState.text.isHidden(); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach(index => { + if (index >= 0) { + bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0; + } + }); + + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0; + } + + const prevOffset = this.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation); + } + + const prevOrientation = this.placedOrientations[symbolInstance.crossTileID]; + if (prevOrientation) { + this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation); + this.markUsedOrientation(bucket, prevOrientation, symbolInstance); + } + } + + if (hasIcon) { + const packedOpacity = packOpacity(opacityState.icon); + + const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden); + + if (symbolInstance.placedIconSymbolIndex >= 0) { + const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden = + (opacityState.icon.isHidden(): any); + } + + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden = + (opacityState.icon.isHidden(): any); + } + } + + if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) { + const collisionArrays = bucket.collisionArrays[s]; + if (collisionArrays) { + let shift = new Point(0, 0); + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let used = true; + if (variablePlacement) { + const variableOffset = this.variableOffsets[crossTileID]; + if (variableOffset) { + // This will show either the currently placed position or the last + // successfully placed position (so you can visualize what collision + // just made the symbol disappear, and the most likely place for the + // symbol to come back) + shift = calculateVariableLayoutShift(variableOffset.anchor, + variableOffset.width, + variableOffset.height, + variableOffset.textOffset, + variableOffset.textBoxScale); + if (rotateWithMap) { + shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle); + } + } else { + // No offset -> this symbol hasn't been placed since coming on-screen + // No single box is particularly meaningful and all of them would be too noisy + // Use the center box just to show something's there, but mark it "not used" + used = false; + } + } + + if (collisionArrays.textBox) { + updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || horizontalHidden, shift.x, shift.y); + } + if (collisionArrays.verticalTextBox) { + updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || verticalHidden, shift.x, shift.y); + } + } + + const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox); + + if (collisionArrays.iconBox) { + updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, verticalIconUsed, + hasIconTextFit ? shift.x : 0, + hasIconTextFit ? shift.y : 0); + } + + if (collisionArrays.verticalIconBox) { + updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, !verticalIconUsed, + hasIconTextFit ? shift.x : 0, + hasIconTextFit ? shift.y : 0); + } + } + } + } + + bucket.sortFeatures(this.transform.angle); + if (this.retainedQueryData[bucket.bucketInstanceId]) { + this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder; + } + + if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) { + bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray); + } + if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) { + bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray); + } + if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) { + bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray); + } + if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) { + bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray); + } + + assert(bucket.text.opacityVertexArray.length === bucket.text.layoutVertexArray.length / 4); + assert(bucket.icon.opacityVertexArray.length === bucket.icon.layoutVertexArray.length / 4); + + // Push generated collision circles to the bucket for debug rendering + if (bucket.bucketInstanceId in this.collisionCircleArrays) { + const instance = this.collisionCircleArrays[bucket.bucketInstanceId]; + + bucket.placementInvProjMatrix = instance.invProjMatrix; + bucket.placementViewportMatrix = instance.viewportMatrix; + bucket.collisionCircleArray = instance.circles; + + delete this.collisionCircleArrays[bucket.bucketInstanceId]; + } + } + + symbolFadeChange(now: number) { + return this.fadeDuration === 0 ? + 1 : + ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment); + } + + zoomAdjustment(zoom: number) { + // When zooming out quickly, labels can overlap each other. This + // adjustment is used to reduce the interval between placement calculations + // and to reduce the fade duration when zooming out quickly. Discovering the + // collisions more quickly and fading them more quickly reduces the unwanted effect. + return Math.max(0, (this.transform.zoom - zoom) / 1.5); + } + + hasTransitions(now: number) { + return this.stale || + now - this.lastPlacementChangeTime < this.fadeDuration; + } + + stillRecent(now: number, zoom: number) { + // The adjustment makes placement more frequent when zooming. + // This condition applies the adjustment only after the map has + // stopped zooming. This avoids adding extra jank while zooming. + const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? + (1 - this.zoomAdjustment(zoom)) : + 1; + this.zoomAtLastRecencyCheck = zoom; + + return this.commitTime + this.fadeDuration * durationAdjustment > now; + } + + setStale() { + this.stale = true; + } +} + +function updateCollisionVertices(collisionVertexArray: CollisionVertexArray, placed: boolean, notUsed: boolean | number, shiftX?: number, shiftY?: number) { + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); +} + +// All four vertices for a glyph will have the same opacity state +// So we pack the opacity into a uint8, and then repeat it four times +// to make a single uint32 that we can upload for each glyph in the +// label. +const shift25 = Math.pow(2, 25); +const shift24 = Math.pow(2, 24); +const shift17 = Math.pow(2, 17); +const shift16 = Math.pow(2, 16); +const shift9 = Math.pow(2, 9); +const shift8 = Math.pow(2, 8); +const shift1 = Math.pow(2, 1); +function packOpacity(opacityState: OpacityState): number { + if (opacityState.opacity === 0 && !opacityState.placed) { + return 0; + } else if (opacityState.opacity === 1 && opacityState.placed) { + return 4294967295; + } + const targetBit = opacityState.placed ? 1 : 0; + const opacityBits = Math.floor(opacityState.opacity * 127); + return opacityBits * shift25 + targetBit * shift24 + + opacityBits * shift17 + targetBit * shift16 + + opacityBits * shift9 + targetBit * shift8 + + opacityBits * shift1 + targetBit; +} + +const PACKED_HIDDEN_OPACITY = 0; diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/projection.js b/node_modules/@plotly/mapbox-gl/src/symbol/projection.js new file mode 100644 index 0000000000000000000000000000000000000000..e0c16142989ea56523dfde39d1cab52964ed7327 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/projection.js @@ -0,0 +1,451 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import {mat4, vec4} from 'gl-matrix'; +import * as symbolSize from './symbol_size'; +import {addDynamicAttributes} from '../data/bucket/symbol_bucket'; + +import type Painter from '../render/painter'; +import type Transform from '../geo/transform'; +import type SymbolBucket from '../data/bucket/symbol_bucket'; +import type { + GlyphOffsetArray, + SymbolLineVertexArray, + SymbolDynamicLayoutArray +} from '../data/array_types'; +import {WritingMode} from '../symbol/shaping'; + +export {updateLineLabels, hideGlyphs, getLabelPlaneMatrix, getGlCoordMatrix, project, getPerspectiveRatio, placeFirstAndLastGlyph, placeGlyphAlongLine, xyTransformMat4}; + +/* + * # Overview of coordinate spaces + * + * ## Tile coordinate spaces + * Each label has an anchor. Some labels have corresponding line geometries. + * The points for both anchors and lines are stored in tile units. Each tile has it's own + * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. + * + * ## GL coordinate space + * At the end of everything, the vertex shader needs to produce a position in GL coordinate space, + * which is (-1, 1) at the top left and (1, -1) in the bottom right. + * + * ## Map pixel coordinate spaces + * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is + * whatever counts as 1 pixel at the current zoom. + * This space is used for pitch-alignment=map, rotation-alignment=map + * + * ## Rotated map pixel coordinate spaces + * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. + * This space is used for pitch-alignment=map, rotation-alignment=viewport + * + * ## Viewport pixel coordinate space + * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner + * of the canvas. This space is used for pitch-alignment=viewport + * + * + * # Vertex projection + * It goes roughly like this: + * 1. project the anchor and line from tile units into the correct label coordinate space + * - map pixel space pitch-alignment=map rotation-alignment=map + * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport + * - viewport pixel space pitch-alignment=viewport rotation-alignment=* + * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. + * 3. add the glyph's corner offset to the point from step 3 + * 4. convert from the label coordinate space to gl coordinates + * + * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). + * This is what `u_label_plane_matrix` is used for. + * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. + * This is what `updateLineLabels(...)` does. + * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. + * + * Steps 3 and 4 are done in the shaders for all labels. + */ + +/* + * Returns a matrix for converting from tile units to the correct label coordinate space. + */ +function getLabelPlaneMatrix(posMatrix: mat4, + pitchWithMap: boolean, + rotateWithMap: boolean, + transform: Transform, + pixelsToTileUnits: number) { + const m = mat4.create(); + if (pitchWithMap) { + mat4.scale(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]); + if (!rotateWithMap) { + mat4.rotateZ(m, m, transform.angle); + } + } else { + mat4.multiply(m, transform.labelPlaneMatrix, posMatrix); + } + return m; +} + +/* + * Returns a matrix for converting from the correct label coordinate space to gl coords. + */ +function getGlCoordMatrix(posMatrix: mat4, + pitchWithMap: boolean, + rotateWithMap: boolean, + transform: Transform, + pixelsToTileUnits: number) { + if (pitchWithMap) { + const m = mat4.clone(posMatrix); + mat4.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]); + if (!rotateWithMap) { + mat4.rotateZ(m, m, -transform.angle); + } + return m; + } else { + return transform.glCoordMatrix; + } +} + +function project(point: Point, matrix: mat4) { + const pos = [point.x, point.y, 0, 1]; + xyTransformMat4(pos, pos, matrix); + const w = pos[3]; + return { + point: new Point(pos[0] / w, pos[1] / w), + signedDistanceFromCamera: w + }; +} + +function getPerspectiveRatio(cameraToCenterDistance: number, signedDistanceFromCamera: number): number { + return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera); +} + +function isVisible(anchorPos: [number, number, number, number], + clippingBuffer: [number, number]) { + const x = anchorPos[0] / anchorPos[3]; + const y = anchorPos[1] / anchorPos[3]; + const inPaddedViewport = ( + x >= -clippingBuffer[0] && + x <= clippingBuffer[0] && + y >= -clippingBuffer[1] && + y <= clippingBuffer[1]); + return inPaddedViewport; +} + +/* + * Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view. + * This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader. + */ +function updateLineLabels(bucket: SymbolBucket, + posMatrix: mat4, + painter: Painter, + isText: boolean, + labelPlaneMatrix: mat4, + glCoordMatrix: mat4, + pitchWithMap: boolean, + keepUpright: boolean) { + + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const partiallyEvaluatedSize = symbolSize.evaluateSizeForZoom(sizeData, painter.transform.zoom); + + const clippingBuffer = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1]; + + const dynamicLayoutVertexArray = isText ? + bucket.text.dynamicLayoutVertexArray : + bucket.icon.dynamicLayoutVertexArray; + dynamicLayoutVertexArray.clear(); + + const lineVertexArray = bucket.lineVertexArray; + const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray; + + const aspectRatio = painter.transform.width / painter.transform.height; + + let useVertical = false; + + for (let s = 0; s < placedSymbols.length; s++) { + const symbol: any = placedSymbols.get(s); + + // Don't do calculations for vertical glyphs unless the previous symbol was horizontal + // and we determined that vertical glyphs were necessary. + // Also don't do calculations for symbols that are collided and fully faded out + if (symbol.hidden || symbol.writingMode === WritingMode.vertical && !useVertical) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart + useVertical = false; + + const anchorPos = [symbol.anchorX, symbol.anchorY, 0, 1]; + vec4.transformMat4(anchorPos, anchorPos, posMatrix); + + // Don't bother calculating the correct point for invisible labels. + if (!isVisible(anchorPos, clippingBuffer)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + + const cameraToAnchorDistance = anchorPos[3]; + const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance); + + const fontSize = symbolSize.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol); + const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + + const tileAnchorPoint = new Point(symbol.anchorX, symbol.anchorY); + const anchorPoint = project(tileAnchorPoint, labelPlaneMatrix).point; + const projectionCache = {}; + + const placeUnflipped: any = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, + bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio); + + useVertical = placeUnflipped.useVertical; + + if (placeUnflipped.notEnoughRoom || useVertical || + (placeUnflipped.needsFlipping && + placeGlyphsAlongLine(symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, + bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio).notEnoughRoom)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + } + } + + if (isText) { + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } else { + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } +} + +function placeFirstAndLastGlyph(fontScale: number, glyphOffsetArray: GlyphOffsetArray, lineOffsetX: number, lineOffsetY: number, flip: boolean, anchorPoint: Point, tileAnchorPoint: Point, symbol: any, lineVertexArray: SymbolLineVertexArray, labelPlaneMatrix: mat4, projectionCache: any) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + + const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex); + const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1); + + const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!firstPlacedGlyph) + return null; + + const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!lastPlacedGlyph) + return null; + + return {first: firstPlacedGlyph, last: lastPlacedGlyph}; +} + +function requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) { + if (writingMode === WritingMode.horizontal) { + // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate + // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal + // and vertical versions can have slightly different projections which could lead to angles where both or + // neither showed. + const rise = Math.abs(lastPoint.y - firstPoint.y); + const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio; + if (rise > run) { + return {useVertical: true}; + } + } + + if (writingMode === WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) { + // Includes "horizontalOnly" case for labels without vertical glyphs + return {needsFlipping: true}; + } + + return null; +} + +function placeGlyphsAlongLine(symbol, fontSize, flip, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio) { + const fontScale = fontSize / 24; + const lineOffsetX = symbol.lineOffsetX * fontScale; + const lineOffsetY = symbol.lineOffsetY * fontScale; + + let placedGlyphs; + if (symbol.numGlyphs > 1) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + + // Place the first and the last glyph in the label first, so we can figure out + // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode + const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!firstAndLastGlyph) { + return {notEnoughRoom: true}; + } + const firstPoint = project(firstAndLastGlyph.first.point, glCoordMatrix).point; + const lastPoint = project(firstAndLastGlyph.last.point, glCoordMatrix).point; + + if (keepUpright && !flip) { + const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + + placedGlyphs = [firstAndLastGlyph.first]; + for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) { + // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed + // $FlowFixMe + placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache)); + } + placedGlyphs.push(firstAndLastGlyph.last); + } else { + // Only a single glyph to place + // So, determine whether to flip based on projected angle of the line segment it's on + if (keepUpright && !flip) { + const a = project(tileAnchorPoint, posMatrix).point; + const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1); + // $FlowFixMe + const tileSegmentEnd = new Point(lineVertexArray.getx(tileVertexIndex), lineVertexArray.gety(tileVertexIndex)); + const projectedVertex = project(tileSegmentEnd, posMatrix); + // We know the anchor will be in the viewport, but the end of the line segment may be + // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) + // point on the segment. + const b = (projectedVertex.signedDistanceFromCamera > 0) ? + projectedVertex.point : + projectTruncatedLineSegment(tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix); + + const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + // $FlowFixMe + const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!singleGlyph) + return {notEnoughRoom: true}; + + placedGlyphs = [singleGlyph]; + } + + for (const glyph: any of placedGlyphs) { + addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle); + } + return {}; +} + +function projectTruncatedLineSegment(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionMatrix: mat4) { + // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane + // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) + // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the + // plane of the camera. + const projectedUnitVertex = project(previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()), projectionMatrix).point; + const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex); + + return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag())); +} + +function placeGlyphAlongLine(offsetX: number, + lineOffsetX: number, + lineOffsetY: number, + flip: boolean, + anchorPoint: Point, + tileAnchorPoint: Point, + anchorSegment: number, + lineStartIndex: number, + lineEndIndex: number, + lineVertexArray: SymbolLineVertexArray, + labelPlaneMatrix: mat4, + projectionCache: {[_: number]: Point}) { + + const combinedOffsetX = flip ? + offsetX - lineOffsetX : + offsetX + lineOffsetX; + + let dir = combinedOffsetX > 0 ? 1 : -1; + + let angle = 0; + if (flip) { + // The label needs to be flipped to keep text upright. + // Iterate in the reverse direction. + dir *= -1; + angle = Math.PI; + } + + if (dir < 0) angle += Math.PI; + + let currentIndex = dir > 0 ? + lineStartIndex + anchorSegment : + lineStartIndex + anchorSegment + 1; + + let current = anchorPoint; + let prev = anchorPoint; + let distanceToPrev = 0; + let currentSegmentDistance = 0; + const absOffsetX = Math.abs(combinedOffsetX); + const pathVertices = []; + + while (distanceToPrev + currentSegmentDistance <= absOffsetX) { + currentIndex += dir; + + // offset does not fit on the projected line + if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex) + return null; + + prev = current; + pathVertices.push(current); + + current = projectionCache[currentIndex]; + if (current === undefined) { + const currentVertex = new Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex)); + const projection = project(currentVertex, labelPlaneMatrix); + if (projection.signedDistanceFromCamera > 0) { + current = projectionCache[currentIndex] = projection.point; + } else { + // The vertex is behind the plane of the camera, so we can't project it + // Instead, we'll create a vertex along the line that's far enough to include the glyph + const previousLineVertexIndex = currentIndex - dir; + const previousTilePoint = distanceToPrev === 0 ? + tileAnchorPoint : + new Point(lineVertexArray.getx(previousLineVertexIndex), lineVertexArray.gety(previousLineVertexIndex)); + // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment + current = projectTruncatedLineSegment(previousTilePoint, currentVertex, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix); + } + } + + distanceToPrev += currentSegmentDistance; + currentSegmentDistance = prev.dist(current); + } + + // The point is on the current segment. Interpolate to find it. + const segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance; + const prevToCurrent = current.sub(prev); + const p = prevToCurrent.mult(segmentInterpolationT)._add(prev); + + // offset the point from the line to text-offset and icon-offset + p._add(prevToCurrent._unit()._perp()._mult(lineOffsetY * dir)); + + const segmentAngle = angle + Math.atan2(current.y - prev.y, current.x - prev.x); + + pathVertices.push(p); + + return { + point: p, + angle: segmentAngle, + path: pathVertices + }; +} + +const hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]); + +// Hide them by moving them offscreen. We still need to add them to the buffer +// because the dynamic buffer is paired with a static buffer that doesn't get updated. +function hideGlyphs(num: number, dynamicLayoutVertexArray: SymbolDynamicLayoutArray) { + for (let i = 0; i < num; i++) { + const offset = dynamicLayoutVertexArray.length; + dynamicLayoutVertexArray.resize(offset + 4); + // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set + // for each set of four vertices, instead of calling addDynamicAttributes for each vertex. + dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3); + } +} + +// For line label layout, we're not using z output and our w input is always 1 +// This custom matrix transformation ignores those components to make projection faster +function xyTransformMat4(out: vec4, a: vec4, m: mat4) { + const x = a[0], y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + out[3] = m[3] * x + m[7] * y + m[15]; + return out; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/quads.js b/node_modules/@plotly/mapbox-gl/src/symbol/quads.js new file mode 100644 index 0000000000000000000000000000000000000000..9b1c100620e71b92fc7c804ad975874600766262 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/quads.js @@ -0,0 +1,334 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf'; + +import type Anchor from './anchor'; +import type {PositionedIcon, Shaping} from './shaping'; +import {SHAPING_DEFAULT_OFFSET} from './shaping'; +import {IMAGE_PADDING} from '../render/image_atlas'; +import type SymbolStyleLayer from '../style/style_layer/symbol_style_layer'; +import type {Feature} from '../style-spec/expression'; +import type {StyleImage} from '../style/style_image'; +import ONE_EM from './one_em'; + +/** + * A textured quad for rendering a single icon or glyph. + * + * The zoom range the glyph can be shown is defined by minScale and maxScale. + * + * @param tl The offset of the top left corner from the anchor. + * @param tr The offset of the top right corner from the anchor. + * @param bl The offset of the bottom left corner from the anchor. + * @param br The offset of the bottom right corner from the anchor. + * @param tex The texture coordinates. + * + * @private + */ +export type SymbolQuad = { + tl: Point, + tr: Point, + bl: Point, + br: Point, + tex: { + x: number, + y: number, + w: number, + h: number + }, + pixelOffsetTL: Point, + pixelOffsetBR: Point, + writingMode: any | void, + glyphOffset: [number, number], + sectionIndex: number, + isSDF: boolean, + minFontScaleX: number, + minFontScaleY: number +}; + +// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual +// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped +// on one edge in some cases. +const border = IMAGE_PADDING; + +/** + * Create the quads used for rendering an icon. + * @private + */ +export function getIconQuads( + shapedIcon: PositionedIcon, + iconRotate: number, + isSDFIcon: boolean, + hasIconTextFit: boolean): Array { + const quads = []; + + const image = shapedIcon.image; + const pixelRatio = image.pixelRatio; + const imageWidth = image.paddedRect.w - 2 * border; + const imageHeight = image.paddedRect.h - 2 * border; + + const iconWidth = shapedIcon.right - shapedIcon.left; + const iconHeight = shapedIcon.bottom - shapedIcon.top; + + const stretchX = image.stretchX || [[0, imageWidth]]; + const stretchY = image.stretchY || [[0, imageHeight]]; + + const reduceRanges = (sum, range) => sum + range[1] - range[0]; + const stretchWidth = stretchX.reduce(reduceRanges, 0); + const stretchHeight = stretchY.reduce(reduceRanges, 0); + const fixedWidth = imageWidth - stretchWidth; + const fixedHeight = imageHeight - stretchHeight; + + let stretchOffsetX = 0; + let stretchContentWidth = stretchWidth; + let stretchOffsetY = 0; + let stretchContentHeight = stretchHeight; + let fixedOffsetX = 0; + let fixedContentWidth = fixedWidth; + let fixedOffsetY = 0; + let fixedContentHeight = fixedHeight; + + if (image.content && hasIconTextFit) { + const content = image.content; + stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); + stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); + stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); + stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); + fixedOffsetX = content[0] - stretchOffsetX; + fixedOffsetY = content[1] - stretchOffsetY; + fixedContentWidth = content[2] - content[0] - stretchContentWidth; + fixedContentHeight = content[3] - content[1] - stretchContentHeight; + } + + const makeBox = (left, top, right, bottom) => { + + const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left); + const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); + + const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top); + const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); + + const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left); + const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); + + const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top); + const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + + const tl = new Point(leftEm, topEm); + const tr = new Point(rightEm, topEm); + const br = new Point(rightEm, bottomEm); + const bl = new Point(leftEm, bottomEm); + const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio); + const pixelOffsetBR = new Point(rightPx / pixelRatio, bottomPx / pixelRatio); + + const angle = iconRotate * Math.PI / 180; + + if (angle) { + const sin = Math.sin(angle), + cos = Math.cos(angle), + matrix = [cos, -sin, sin, cos]; + + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + + const x1 = left.stretch + left.fixed; + const x2 = right.stretch + right.fixed; + const y1 = top.stretch + top.fixed; + const y2 = bottom.stretch + bottom.fixed; + + const subRect = { + x: image.paddedRect.x + border + x1, + y: image.paddedRect.y + border + y1, + w: x2 - x1, + h: y2 - y1 + }; + + const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; + const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; + + // Icon quad is padded, so texture coordinates also need to be padded. + return {tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon}; + }; + + if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) { + quads.push(makeBox( + {fixed: 0, stretch: -1}, + {fixed: 0, stretch: -1}, + {fixed: 0, stretch: imageWidth + 1}, + {fixed: 0, stretch: imageHeight + 1})); + } else { + const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); + const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); + + for (let xi = 0; xi < xCuts.length - 1; xi++) { + const x1 = xCuts[xi]; + const x2 = xCuts[xi + 1]; + for (let yi = 0; yi < yCuts.length - 1; yi++) { + const y1 = yCuts[yi]; + const y2 = yCuts[yi + 1]; + quads.push(makeBox(x1, y1, x2, y2)); + } + } + } + + return quads; +} + +function sumWithinRange(ranges, min, max) { + let sum = 0; + for (const range of ranges) { + sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); + } + return sum; +} + +function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { + const cuts = [{fixed: -border, stretch: 0}]; + + for (const [c1, c2] of stretchZones) { + const last = cuts[cuts.length - 1]; + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + }); + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + (c2 - c1) + }); + } + cuts.push({ + fixed: fixedSize + border, + stretch: stretchSize + }); + return cuts; +} + +function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { + return stretchOffset / stretchSize * iconSize + iconOffset; +} + +function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { + return fixedOffset - fixedSize * stretchOffset / stretchSize; +} + +/** + * Create the quads used for rendering a text label. + * @private + */ +export function getGlyphQuads(anchor: Anchor, + shaping: Shaping, + textOffset: [number, number], + layer: SymbolStyleLayer, + alongLine: boolean, + feature: Feature, + imageMap: {[_: string]: StyleImage}, + allowVerticalPlacement: boolean): Array { + + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180; + const quads = []; + + for (const line of shaping.positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + if (!positionedGlyph.rect) continue; + const textureRect = positionedGlyph.rect || {}; + + // The rects have an additional buffer that is not included in their size. + const glyphPadding = 1.0; + let rectBuffer = GLYPH_PBF_BORDER + glyphPadding; + let isSDF = true; + let pixelRatio = 1.0; + let lineOffset = 0.0; + + const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; + const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; + + // Align images and scaled glyphs in the middle of a vertical line. + if (allowVerticalPlacement && shaping.verticalizable) { + const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM; + const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; + lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); + } + + if (positionedGlyph.imageName) { + const image = imageMap[positionedGlyph.imageName]; + isSDF = image.sdf; + pixelRatio = image.pixelRatio; + rectBuffer = IMAGE_PADDING / pixelRatio; + } + + const glyphOffset = alongLine ? + [positionedGlyph.x + halfAdvance, positionedGlyph.y] : + [0, 0]; + + let builtInOffset = alongLine ? + [0, 0] : + [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; + + let verticalizedLabelOffset = [0, 0]; + if (rotateVerticalGlyph) { + // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation + // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset. + verticalizedLabelOffset = builtInOffset; + builtInOffset = [0, 0]; + } + + const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; + const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; + const x2 = x1 + textureRect.w * positionedGlyph.scale / pixelRatio; + const y2 = y1 + textureRect.h * positionedGlyph.scale / pixelRatio; + + const tl = new Point(x1, y1); + const tr = new Point(x2, y1); + const bl = new Point(x1, y2); + const br = new Point(x2, y2); + + if (rotateVerticalGlyph) { + // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) + // In horizontal orientation, the y values for glyphs are below the midline + // and we use a "yOffset" of -17 to pull them up to the middle. + // By rotating counter-clockwise around the point at the center of the left + // edge of a 24x24 layout box centered below the midline, we align the center + // of the glyphs with the horizontal midline, so the yOffset is no longer + // necessary, but we also pull the glyph to the left along the x axis. + // The y coordinate includes baseline yOffset, thus needs to be accounted + // for when glyph is rotated and translated. + const center = new Point(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET); + const verticalRotation = -Math.PI / 2; + + // xHalfWidthOffsetCorrection is a difference between full-width and half-width + // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. + const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance; + const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0; + const halfWidthOffsetCorrection = new Point(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); + const verticalOffsetCorrection = new Point(...verticalizedLabelOffset); + tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + } + + if (textRotate) { + const sin = Math.sin(textRotate), + cos = Math.cos(textRotate), + matrix = [cos, -sin, sin, cos]; + + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + + const pixelOffsetTL = new Point(0, 0); + const pixelOffsetBR = new Point(0, 0); + const minFontScaleX = 0; + const minFontScaleY = 0; + quads.push({tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY}); + } + } + + return quads; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/shaping.js b/node_modules/@plotly/mapbox-gl/src/symbol/shaping.js new file mode 100644 index 0000000000000000000000000000000000000000..dafdd6ecfacfe10793765a6fe0ec00b74e747aec --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/shaping.js @@ -0,0 +1,816 @@ +// @flow + +import assert from 'assert'; +import { + charHasUprightVerticalOrientation, + charAllowsIdeographicBreaking, + charInComplexShapingScript +} from '../util/script_detection'; +import verticalizePunctuation from '../util/verticalize_punctuation'; +import {plugin as rtlTextPlugin} from '../source/rtl_text_plugin'; +import ONE_EM from './one_em'; +import {warnOnce} from '../util/util'; + +import type {StyleGlyph, GlyphMetrics} from '../style/style_glyph'; +import {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf'; +import type {ImagePosition} from '../render/image_atlas'; +import {IMAGE_PADDING} from '../render/image_atlas'; +import type {Rect, GlyphPosition} from '../render/glyph_atlas'; +import Formatted, {FormattedSection} from '../style-spec/expression/types/formatted'; + +const WritingMode = { + horizontal: 1, + vertical: 2, + horizontalOnly: 3 +}; + +const SHAPING_DEFAULT_OFFSET = -17; +export {shapeText, shapeIcon, fitIconToText, getAnchorAlignment, WritingMode, SHAPING_DEFAULT_OFFSET}; + +// The position of a glyph relative to the text's anchor point. +export type PositionedGlyph = { + glyph: number, + imageName: string | null, + x: number, + y: number, + vertical: boolean, + scale: number, + fontStack: string, + sectionIndex: number, + metrics: GlyphMetrics, + rect: Rect | null +}; + +export type PositionedLine = { + positionedGlyphs: Array, + lineOffset: number +}; + +// A collection of positioned glyphs and some metadata +export type Shaping = { + positionedLines: Array, + top: number, + bottom: number, + left: number, + right: number, + writingMode: 1 | 2, + text: string, + iconsInText: boolean, + verticalizable: boolean +}; + +function isEmpty(positionedLines: Array) { + for (const line of positionedLines) { + if (line.positionedGlyphs.length !== 0) { + return false; + } + } + return true; +} + +export type SymbolAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; +export type TextJustify = 'left' | 'center' | 'right'; + +// Max number of images in label is 6401 U+E000–U+F8FF that covers +// Basic Multilingual Plane Unicode Private Use Area (PUA). +const PUAbegin = 0xE000; +const PUAend = 0xF8FF; + +class SectionOptions { + // Text options + scale: number; + fontStack: string; + // Image options + imageName: string | null; + + constructor() { + this.scale = 1.0; + this.fontStack = ""; + this.imageName = null; + } + + static forText(scale: number | null, fontStack: string) { + const textOptions = new SectionOptions(); + textOptions.scale = scale || 1; + textOptions.fontStack = fontStack; + return textOptions; + } + + static forImage(imageName: string) { + const imageOptions = new SectionOptions(); + imageOptions.imageName = imageName; + return imageOptions; + } + +} + +class TaggedString { + text: string; + sectionIndex: Array // maps each character in 'text' to its corresponding entry in 'sections' + sections: Array + imageSectionID: number | null; + + constructor() { + this.text = ""; + this.sectionIndex = []; + this.sections = []; + this.imageSectionID = null; + } + + static fromFeature(text: Formatted, defaultFontStack: string) { + const result = new TaggedString(); + for (let i = 0; i < text.sections.length; i++) { + const section = text.sections[i]; + if (!section.image) { + result.addTextSection(section, defaultFontStack); + } else { + result.addImageSection(section); + } + } + return result; + } + + length(): number { + return this.text.length; + } + + getSection(index: number): SectionOptions { + return this.sections[this.sectionIndex[index]]; + } + + getSectionIndex(index: number): number { + return this.sectionIndex[index]; + } + + getCharCode(index: number): number { + return this.text.charCodeAt(index); + } + + verticalizePunctuation() { + this.text = verticalizePunctuation(this.text); + } + + trim() { + let beginningWhitespace = 0; + for (let i = 0; + i < this.text.length && whitespace[this.text.charCodeAt(i)]; + i++) { + beginningWhitespace++; + } + let trailingWhitespace = this.text.length; + for (let i = this.text.length - 1; + i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)]; + i--) { + trailingWhitespace--; + } + this.text = this.text.substring(beginningWhitespace, trailingWhitespace); + this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace); + } + + substring(start: number, end: number): TaggedString { + const substring = new TaggedString(); + substring.text = this.text.substring(start, end); + substring.sectionIndex = this.sectionIndex.slice(start, end); + substring.sections = this.sections; + return substring; + } + + toString(): string { + return this.text; + } + + getMaxScale() { + return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0); + } + + addTextSection(section: FormattedSection, defaultFontStack: string) { + this.text += section.text; + this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack)); + const index = this.sections.length - 1; + for (let i = 0; i < section.text.length; ++i) { + this.sectionIndex.push(index); + } + } + + addImageSection(section: FormattedSection) { + const imageName = section.image ? section.image.name : ''; + if (imageName.length === 0) { + warnOnce(`Can't add FormattedSection with an empty image.`); + return; + } + + const nextImageSectionCharCode = this.getNextImageSectionCharCode(); + if (!nextImageSectionCharCode) { + warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`); + return; + } + + this.text += String.fromCharCode(nextImageSectionCharCode); + this.sections.push(SectionOptions.forImage(imageName)); + this.sectionIndex.push(this.sections.length - 1); + } + + getNextImageSectionCharCode(): number | null { + if (!this.imageSectionID) { + this.imageSectionID = PUAbegin; + return this.imageSectionID; + } + + if (this.imageSectionID >= PUAend) return null; + return ++this.imageSectionID; + } +} + +function breakLines(input: TaggedString, lineBreakPoints: Array): Array { + const lines = []; + const text = input.text; + let start = 0; + for (const lineBreak of lineBreakPoints) { + lines.push(input.substring(start, lineBreak)); + start = lineBreak; + } + + if (start < text.length) { + lines.push(input.substring(start, text.length)); + } + return lines; +} + +function shapeText(text: Formatted, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + glyphPositions: {[_: string]: {[_: number]: GlyphPosition}}, + imagePositions: {[_: string]: ImagePosition}, + defaultFontStack: string, + maxWidth: number, + lineHeight: number, + textAnchor: SymbolAnchor, + textJustify: TextJustify, + spacing: number, + translate: [number, number], + writingMode: 1 | 2, + allowVerticalPlacement: boolean, + symbolPlacement: string, + layoutTextSize: number, + layoutTextSizeThisZoom: number): Shaping | false { + const logicalInput = TaggedString.fromFeature(text, defaultFontStack); + + if (writingMode === WritingMode.vertical) { + logicalInput.verticalizePunctuation(); + } + + let lines: Array; + + const {processBidirectionalText, processStyledBidirectionalText} = rtlTextPlugin; + if (processBidirectionalText && logicalInput.sections.length === 1) { + // Bidi doesn't have to be style-aware + lines = []; + const untaggedLines = + processBidirectionalText(logicalInput.toString(), + determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize)); + for (const line of untaggedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line; + taggedLine.sections = logicalInput.sections; + for (let i = 0; i < line.length; i++) { + taggedLine.sectionIndex.push(0); + } + lines.push(taggedLine); + } + } else if (processStyledBidirectionalText) { + // Need version of mapbox-gl-rtl-text with style support for combining RTL text + // with formatting + lines = []; + const processedLines = + processStyledBidirectionalText(logicalInput.text, + logicalInput.sectionIndex, + determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize)); + for (const line of processedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line[0]; + taggedLine.sectionIndex = line[1]; + taggedLine.sections = logicalInput.sections; + lines.push(taggedLine); + } + } else { + lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize)); + } + + const positionedLines = []; + const shaping = { + positionedLines, + text: logicalInput.toString(), + top: translate[1], + bottom: translate[1], + left: translate[0], + right: translate[0], + writingMode, + iconsInText: false, + verticalizable: false + }; + + shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom); + if (isEmpty(positionedLines)) return false; + + return shaping; +} + +// using computed properties due to https://github.com/facebook/flow/issues/380 +/* eslint no-useless-computed-key: 0 */ + +const whitespace: {[_: number]: boolean} = { + [0x09]: true, // tab + [0x0a]: true, // newline + [0x0b]: true, // vertical tab + [0x0c]: true, // form feed + [0x0d]: true, // carriage return + [0x20]: true, // space +}; + +const breakable: {[_: number]: boolean} = { + [0x0a]: true, // newline + [0x20]: true, // space + [0x26]: true, // ampersand + [0x28]: true, // left parenthesis + [0x29]: true, // right parenthesis + [0x2b]: true, // plus sign + [0x2d]: true, // hyphen-minus + [0x2f]: true, // solidus + [0xad]: true, // soft hyphen + [0xb7]: true, // middle dot + [0x200b]: true, // zero-width space + [0x2010]: true, // hyphen + [0x2013]: true, // en dash + [0x2027]: true // interpunct + // Many other characters may be reasonable breakpoints + // Consider "neutral orientation" characters at scriptDetection.charHasNeutralVerticalOrientation + // See https://github.com/mapbox/mapbox-gl-js/issues/3658 +}; + +function getGlyphAdvance(codePoint: number, + section: SectionOptions, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + imagePositions: {[_: string]: ImagePosition}, + spacing: number, + layoutTextSize: number): number { + if (!section.imageName) { + const positions = glyphMap[section.fontStack]; + const glyph = positions && positions[codePoint]; + if (!glyph) return 0; + return glyph.metrics.advance * section.scale + spacing; + } else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) return 0; + return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing; + } +} + +function determineAverageLineWidth(logicalInput: TaggedString, + spacing: number, + maxWidth: number, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + imagePositions: {[_: string]: ImagePosition}, + layoutTextSize: number) { + let totalWidth = 0; + + for (let index = 0; index < logicalInput.length(); index++) { + const section = logicalInput.getSection(index); + totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize); + } + + const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth)); + return totalWidth / lineCount; +} + +function calculateBadness(lineWidth: number, + targetWidth: number, + penalty: number, + isLastBreak: boolean) { + const raggedness = Math.pow(lineWidth - targetWidth, 2); + if (isLastBreak) { + // Favor finals lines shorter than average over longer than average + if (lineWidth < targetWidth) { + return raggedness / 2; + } else { + return raggedness * 2; + } + } + + return raggedness + Math.abs(penalty) * penalty; +} + +function calculatePenalty(codePoint: number, nextCodePoint: number, penalizableIdeographicBreak: boolean) { + let penalty = 0; + // Force break on newline + if (codePoint === 0x0a) { + penalty -= 10000; + } + // Penalize breaks between characters that allow ideographic breaking because + // they are less preferable than breaks at spaces (or zero width spaces). + if (penalizableIdeographicBreak) { + penalty += 150; + } + + // Penalize open parenthesis at end of line + if (codePoint === 0x28 || codePoint === 0xff08) { + penalty += 50; + } + + // Penalize close parenthesis at beginning of line + if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) { + penalty += 50; + } + return penalty; +} + +type Break = { + index: number, + x: number, + priorBreak: ?Break, + badness: number +}; + +function evaluateBreak(breakIndex: number, + breakX: number, + targetWidth: number, + potentialBreaks: Array, + penalty: number, + isLastBreak: boolean): Break { + // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth + // ...but in fact we allow lines longer than maxWidth (if there's no break points) + // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give + // more lopsided results. + + let bestPriorBreak: ?Break = null; + let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); + + for (const potentialBreak of potentialBreaks) { + const lineWidth = breakX - potentialBreak.x; + const breakBadness = + calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + if (breakBadness <= bestBreakBadness) { + bestPriorBreak = potentialBreak; + bestBreakBadness = breakBadness; + } + } + + return { + index: breakIndex, + x: breakX, + priorBreak: bestPriorBreak, + badness: bestBreakBadness + }; +} + +function leastBadBreaks(lastLineBreak: ?Break): Array { + if (!lastLineBreak) { + return []; + } + return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index); +} + +function determineLineBreaks(logicalInput: TaggedString, + spacing: number, + maxWidth: number, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + imagePositions: {[_: string]: ImagePosition}, + symbolPlacement: string, + layoutTextSize: number): Array { + if (symbolPlacement !== 'point') + return []; + + if (!logicalInput) + return []; + + const potentialLineBreaks = []; + const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + + const hasServerSuggestedBreakpoints = logicalInput.text.indexOf("\u200b") >= 0; + + let currentX = 0; + + for (let i = 0; i < logicalInput.length(); i++) { + const section = logicalInput.getSection(i); + const codePoint = logicalInput.getCharCode(i); + if (!whitespace[codePoint]) currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize); + + // Ideographic characters, spaces, and word-breaking punctuation that often appear without + // surrounding spaces. + if ((i < logicalInput.length() - 1)) { + const ideographicBreak = charAllowsIdeographicBreaking(codePoint); + if (breakable[codePoint] || ideographicBreak || section.imageName) { + + potentialLineBreaks.push( + evaluateBreak( + i + 1, + currentX, + targetWidth, + potentialLineBreaks, + calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), + false)); + } + } + } + + return leastBadBreaks( + evaluateBreak( + logicalInput.length(), + currentX, + targetWidth, + potentialLineBreaks, + 0, + true)); +} + +function getAnchorAlignment(anchor: SymbolAnchor) { + let horizontalAlign = 0.5, verticalAlign = 0.5; + + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + horizontalAlign = 1; + break; + case 'left': + case 'top-left': + case 'bottom-left': + horizontalAlign = 0; + break; + } + + switch (anchor) { + case 'bottom': + case 'bottom-right': + case 'bottom-left': + verticalAlign = 1; + break; + case 'top': + case 'top-right': + case 'top-left': + verticalAlign = 0; + break; + } + + return {horizontalAlign, verticalAlign}; +} + +function shapeLines(shaping: Shaping, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + glyphPositions: {[_: string]: {[_: number]: GlyphPosition}}, + imagePositions: {[_: string]: ImagePosition}, + lines: Array, + lineHeight: number, + textAnchor: SymbolAnchor, + textJustify: TextJustify, + writingMode: 1 | 2, + spacing: number, + allowVerticalPlacement: boolean, + layoutTextSizeThisZoom: number) { + + let x = 0; + let y = SHAPING_DEFAULT_OFFSET; + + let maxLineLength = 0; + let maxLineHeight = 0; + + const justify = + textJustify === 'right' ? 1 : + textJustify === 'left' ? 0 : 0.5; + + let lineIndex = 0; + for (const line of lines) { + line.trim(); + + const lineMaxScale = line.getMaxScale(); + const maxLineOffset = (lineMaxScale - 1) * ONE_EM; + const positionedLine = {positionedGlyphs: [], lineOffset: 0}; + shaping.positionedLines[lineIndex] = positionedLine; + const positionedGlyphs = positionedLine.positionedGlyphs; + let lineOffset = 0.0; + + if (!line.length()) { + y += lineHeight; // Still need a line feed after empty line + ++lineIndex; + continue; + } + + for (let i = 0; i < line.length(); i++) { + const section = line.getSection(i); + const sectionIndex = line.getSectionIndex(i); + const codePoint = line.getCharCode(i); + let baselineOffset = 0.0; + let metrics = null; + let rect = null; + let imageName = null; + let verticalAdvance = ONE_EM; + const vertical = !(writingMode === WritingMode.horizontal || + // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled. + (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) || + // If vertical placement is enabled, don't verticalize glyphs that + // are from complex text layout script, or whitespaces. + (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)))); + + if (!section.imageName) { + const positions = glyphPositions[section.fontStack]; + const glyphPosition = positions && positions[codePoint]; + if (glyphPosition && glyphPosition.rect) { + rect = glyphPosition.rect; + metrics = glyphPosition.metrics; + } else { + const glyphs = glyphMap[section.fontStack]; + const glyph = glyphs && glyphs[codePoint]; + if (!glyph) continue; + metrics = glyph.metrics; + } + + // We don't know the baseline, but since we're laying out + // at 24 points, we can calculate how much it will move when + // we scale up or down. + baselineOffset = (lineMaxScale - section.scale) * ONE_EM; + } else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) continue; + imageName = section.imageName; + shaping.iconsInText = shaping.iconsInText || true; + rect = imagePosition.paddedRect; + const size = imagePosition.displaySize; + // If needed, allow to set scale factor for an image using + // alias "image-scale" that could be alias for "font-scale" + // when FormattedSection is an image section. + section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom; + + metrics = {width: size[0], + height: size[1], + left: IMAGE_PADDING, + top: -GLYPH_PBF_BORDER, + advance: vertical ? size[1] : size[0]}; + + // Difference between one EM and an image size. + // Aligns bottom of an image to a baseline level. + const imageOffset = ONE_EM - size[1] * section.scale; + baselineOffset = maxLineOffset + imageOffset; + verticalAdvance = metrics.advance; + + // Difference between height of an image and one EM at max line scale. + // Pushes current line down if an image size is over 1 EM at max line scale. + const offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale : + size[1] * section.scale - ONE_EM * lineMaxScale; + if (offset > 0 && offset > lineOffset) { + lineOffset = offset; + } + } + + if (!vertical) { + positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect}); + x += metrics.advance * section.scale + spacing; + } else { + shaping.verticalizable = true; + positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect}); + x += verticalAdvance * section.scale + spacing; + } + } + + // Only justify if we placed at least one glyph + if (positionedGlyphs.length !== 0) { + const lineLength = x - spacing; + maxLineLength = Math.max(lineLength, maxLineLength); + justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset); + } + + x = 0; + const currentLineHeight = lineHeight * lineMaxScale + lineOffset; + positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset); + y += currentLineHeight; + maxLineHeight = Math.max(currentLineHeight, maxLineHeight); + ++lineIndex; + } + + // Calculate the bounding box and justify / align text block. + const height = y - SHAPING_DEFAULT_OFFSET; + const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor); + align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length); + + shaping.top += -verticalAlign * height; + shaping.bottom = shaping.top + height; + shaping.left += -horizontalAlign * maxLineLength; + shaping.right = shaping.left + maxLineLength; +} + +// justify right = 1, left = 0, center = 0.5 +function justifyLine(positionedGlyphs: Array, + start: number, + end: number, + justify: 1 | 0 | 0.5, + lineOffset: number) { + if (!justify && !lineOffset) + return; + + const lastPositionedGlyph = positionedGlyphs[end]; + const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale; + const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify; + + for (let j = start; j <= end; j++) { + positionedGlyphs[j].x -= lineIndent; + positionedGlyphs[j].y += lineOffset; + } +} + +function align(positionedLines: Array, + justify: number, + horizontalAlign: number, + verticalAlign: number, + maxLineLength: number, + maxLineHeight: number, + lineHeight: number, + blockHeight: number, + lineCount: number) { + const shiftX = (justify - horizontalAlign) * maxLineLength; + let shiftY = 0; + + if (maxLineHeight !== lineHeight) { + shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET; + } else { + shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight; + } + + for (const line of positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + positionedGlyph.x += shiftX; + positionedGlyph.y += shiftY; + } + } +} + +export type PositionedIcon = { + image: ImagePosition, + top: number, + bottom: number, + left: number, + right: number, + collisionPadding?: [number, number, number, number] +}; + +function shapeIcon(image: ImagePosition, iconOffset: [number, number], iconAnchor: SymbolAnchor): PositionedIcon { + const {horizontalAlign, verticalAlign} = getAnchorAlignment(iconAnchor); + const dx = iconOffset[0]; + const dy = iconOffset[1]; + const x1 = dx - image.displaySize[0] * horizontalAlign; + const x2 = x1 + image.displaySize[0]; + const y1 = dy - image.displaySize[1] * verticalAlign; + const y2 = y1 + image.displaySize[1]; + return {image, top: y1, bottom: y2, left: x1, right: x2}; +} + +function fitIconToText(shapedIcon: PositionedIcon, shapedText: Shaping, + textFit: string, + padding: [ number, number, number, number ], + iconOffset: [ number, number ], fontScale: number): PositionedIcon { + assert(textFit !== 'none'); + assert(Array.isArray(padding) && padding.length === 4); + assert(Array.isArray(iconOffset) && iconOffset.length === 2); + + const image = shapedIcon.image; + + let collisionPadding; + if (image.content) { + const content = image.content; + const pixelRatio = image.pixelRatio || 1; + collisionPadding = [ + content[0] / pixelRatio, + content[1] / pixelRatio, + image.displaySize[0] - content[2] / pixelRatio, + image.displaySize[1] - content[3] / pixelRatio + ]; + } + + // We don't respect the icon-anchor, because icon-text-fit is set. Instead, + // the icon will be centered on the text, then stretched in the given + // dimensions. + + const textLeft = shapedText.left * fontScale; + const textRight = shapedText.right * fontScale; + + let top, right, bottom, left; + if (textFit === 'width' || textFit === 'both') { + // Stretched horizontally to the text width + left = iconOffset[0] + textLeft - padding[3]; + right = iconOffset[0] + textRight + padding[1]; + } else { + // Centered on the text + left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2; + right = left + image.displaySize[0]; + } + + const textTop = shapedText.top * fontScale; + const textBottom = shapedText.bottom * fontScale; + if (textFit === 'height' || textFit === 'both') { + // Stretched vertically to the text height + top = iconOffset[1] + textTop - padding[0]; + bottom = iconOffset[1] + textBottom + padding[2]; + } else { + // Centered on the text + top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2; + bottom = top + image.displaySize[1]; + } + + return {image, top, right, bottom, left, collisionPadding}; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/symbol_layout.js b/node_modules/@plotly/mapbox-gl/src/symbol/symbol_layout.js new file mode 100644 index 0000000000000000000000000000000000000000..990c8417282fdb341346d1d31cb1e1465c5f57d3 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/symbol_layout.js @@ -0,0 +1,796 @@ +// @flow + +import Anchor from './anchor'; + +import {getAnchors, getCenterAnchor} from './get_anchors'; +import clipLine from './clip_line'; +import {shapeText, shapeIcon, WritingMode, fitIconToText} from './shaping'; +import {getGlyphQuads, getIconQuads} from './quads'; +import CollisionFeature from './collision_feature'; +import {warnOnce} from '../util/util'; +import { + allowsVerticalWritingMode, + allowsLetterSpacing +} from '../util/script_detection'; +import findPoleOfInaccessibility from '../util/find_pole_of_inaccessibility'; +import classifyRings from '../util/classify_rings'; +import EXTENT from '../data/extent'; +import SymbolBucket from '../data/bucket/symbol_bucket'; +import EvaluationParameters from '../style/evaluation_parameters'; +import {SIZE_PACK_FACTOR} from './symbol_size'; +import ONE_EM from './one_em'; +import type {CanonicalTileID} from '../source/tile_id'; +import type {Shaping, PositionedIcon, TextJustify} from './shaping'; +import type {CollisionBoxArray} from '../data/array_types'; +import type {SymbolFeature} from '../data/bucket/symbol_bucket'; +import type {StyleImage} from '../style/style_image'; +import type {StyleGlyph} from '../style/style_glyph'; +import type SymbolStyleLayer from '../style/style_layer/symbol_style_layer'; +import type {ImagePosition} from '../render/image_atlas'; +import type {GlyphPosition} from '../render/glyph_atlas'; +import type {PossiblyEvaluatedPropertyValue} from '../style/properties'; + +import Point from '@mapbox/point-geometry'; +import murmur3 from 'murmurhash-js'; + +// The symbol layout process needs `text-size` evaluated at up to five different zoom levels, and +// `icon-size` at up to three: +// +// 1. `text-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `text-size` +// expressions, and to calculate the box dimensions for icon-text-fit. +// 2. `icon-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `icon-size` +// expressions. +// 3. `text-size` and `icon-size` at the zoom level of the bucket, plus one. Used to calculate collision boxes. +// 4. `text-size` at zoom level 18. Used for something line-symbol-placement-related. +// 5. For composite `*-size` expressions: two zoom levels of curve stops that "cover" the zoom level of the +// bucket. These go into a vertex buffer and are used by the shader to interpolate the size at render time. +// +// (1) and (2) are stored in `bucket.layers[0].layout`. The remainder are below. +// +type Sizes = { + layoutTextSize: PossiblyEvaluatedPropertyValue, // (3) + layoutIconSize: PossiblyEvaluatedPropertyValue, // (3) + textMaxSize: PossiblyEvaluatedPropertyValue, // (4) + compositeTextSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue], // (5) + compositeIconSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue], // (5) +}; + +export type TextAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + +// The radial offset is to the edge of the text box +// In the horizontal direction, the edge of the text box is where glyphs start +// But in the vertical direction, the glyphs appear to "start" at the baseline +// We don't actually load baseline data, but we assume an offset of ONE_EM - 17 +// (see "yOffset" in shaping.js) +const baselineOffset = 7; +const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY; + +export function evaluateVariableOffset(anchor: TextAnchor, offset: [number, number]) { + + function fromRadialOffset(anchor: TextAnchor, radialOffset: number) { + let x = 0, y = 0; + if (radialOffset < 0) radialOffset = 0; // Ignore negative offset. + // solve for r where r^2 + r^2 = radialOffset^2 + const hypotenuse = radialOffset / Math.sqrt(2); + switch (anchor) { + case 'top-right': + case 'top-left': + y = hypotenuse - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + y = -hypotenuse + baselineOffset; + break; + case 'bottom': + y = -radialOffset + baselineOffset; + break; + case 'top': + y = radialOffset - baselineOffset; + break; + } + + switch (anchor) { + case 'top-right': + case 'bottom-right': + x = -hypotenuse; + break; + case 'top-left': + case 'bottom-left': + x = hypotenuse; + break; + case 'left': + x = radialOffset; + break; + case 'right': + x = -radialOffset; + break; + } + + return [x, y]; + } + + function fromTextOffset(anchor: TextAnchor, offsetX: number, offsetY: number) { + let x = 0, y = 0; + // Use absolute offset values. + offsetX = Math.abs(offsetX); + offsetY = Math.abs(offsetY); + + switch (anchor) { + case 'top-right': + case 'top-left': + case 'top': + y = offsetY - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + case 'bottom': + y = -offsetY + baselineOffset; + break; + } + + switch (anchor) { + case 'top-right': + case 'bottom-right': + case 'right': + x = -offsetX; + break; + case 'top-left': + case 'bottom-left': + case 'left': + x = offsetX; + break; + } + + return [x, y]; + } + + return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]); +} + +export function performSymbolLayout(bucket: SymbolBucket, + glyphMap: {[_: string]: {[number]: ?StyleGlyph}}, + glyphPositions: {[_: string]: {[number]: GlyphPosition}}, + imageMap: {[_: string]: StyleImage}, + imagePositions: {[_: string]: ImagePosition}, + showCollisionBoxes: boolean, + canonical: CanonicalTileID) { + bucket.createArrays(); + + const tileSize = 512 * bucket.overscaling; + bucket.tilePixelRatio = EXTENT / tileSize; + bucket.compareText = {}; + bucket.iconsNeedLinear = false; + + const layout = bucket.layers[0].layout; + const unevaluatedLayoutValues = bucket.layers[0]._unevaluatedLayout._values; + + const sizes = {}; + + if (bucket.textSizeData.kind === 'composite') { + const {minZoom, maxZoom} = bucket.textSizeData; + sizes.compositeTextSizes = [ + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical), + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical) + ]; + } + + if (bucket.iconSizeData.kind === 'composite') { + const {minZoom, maxZoom} = bucket.iconSizeData; + sizes.compositeIconSizes = [ + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical), + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical) + ]; + } + + sizes.layoutTextSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1), canonical); + sizes.layoutIconSize = unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1), canonical); + sizes.textMaxSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18)); + + const lineHeight = layout.get('text-line-height') * ONE_EM; + const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point'; + const keepUpright = layout.get('text-keep-upright'); + const textSize = layout.get('text-size'); + + for (const feature of bucket.features) { + const fontstack = layout.get('text-font').evaluate(feature, {}, canonical).join(','); + const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, canonical); + const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, canonical); + const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, canonical); + + const shapedTextOrientations = { + horizontal: {}, + vertical: undefined + }; + const text = feature.text; + let textOffset: [number, number] = [0, 0]; + if (text) { + const unformattedText = text.toString(); + const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, canonical) * ONE_EM; + const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0; + + const textAnchor = layout.get('text-anchor').evaluate(feature, {}, canonical); + const variableTextAnchor = layout.get('text-variable-anchor'); + + if (!variableTextAnchor) { + const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, canonical); + // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector + // is calculated at placement time instead of layout time + if (radialOffset) { + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]); + } else { + textOffset = (layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM): any); + } + } + + let textJustify = textAlongLine ? + "center" : + layout.get('text-justify').evaluate(feature, {}, canonical); + + const symbolPlacement = layout.get('symbol-placement'); + const maxWidth = symbolPlacement === 'point' ? + layout.get('text-max-width').evaluate(feature, {}, canonical) * ONE_EM : + 0; + + const addVerticalShapingForPointLabelIfNeeded = () => { + if (bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) { + // Vertical POI label placement is meant to be used for scripts that support vertical + // writing mode, thus, default left justification is used. If Latin + // scripts would need to be supported, this should take into account other justifications. + shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, + 'left', spacingIfAllowed, textOffset, WritingMode.vertical, true, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + } + }; + + // If this layer uses text-variable-anchor, generate shapings for all justification possibilities. + if (!textAlongLine && variableTextAnchor) { + const justifications = textJustify === "auto" ? + variableTextAnchor.map(a => getAnchorJustification(a)) : + [textJustify]; + + let singleLine = false; + for (let i = 0; i < justifications.length; i++) { + const justification: TextJustify = justifications[i]; + if (shapedTextOrientations.horizontal[justification]) continue; + if (singleLine) { + // If the shaping for the first justification was only a single line, we + // can re-use it for the other justifications + shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0]; + } else { + // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply + // the offsets for the anchor in the placement step. + const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, 'center', + justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) { + shapedTextOrientations.horizontal[justification] = shaping; + singleLine = shaping.positionedLines.length === 1; + } + } + } + + addVerticalShapingForPointLabelIfNeeded(); + } else { + if (textJustify === "auto") { + textJustify = getAnchorJustification(textAnchor); + } + + // Horizontal point or line label. + const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, + textOffset, WritingMode.horizontal, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) shapedTextOrientations.horizontal[textJustify] = shaping; + + // Vertical point label (if allowVerticalPlacement is enabled). + addVerticalShapingForPointLabelIfNeeded(); + + // Verticalized line label. + if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) { + shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, + spacingIfAllowed, textOffset, WritingMode.vertical, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + } + } + } + + let shapedIcon; + let isSDFIcon = false; + if (feature.icon && feature.icon.name) { + const image = imageMap[feature.icon.name]; + if (image) { + shapedIcon = shapeIcon( + imagePositions[feature.icon.name], + layout.get('icon-offset').evaluate(feature, {}, canonical), + layout.get('icon-anchor').evaluate(feature, {}, canonical)); + isSDFIcon = image.sdf; + if (bucket.sdfIcons === undefined) { + bucket.sdfIcons = image.sdf; + } else if (bucket.sdfIcons !== image.sdf) { + warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer'); + } + if (image.pixelRatio !== bucket.pixelRatio) { + bucket.iconsNeedLinear = true; + } else if (layout.get('icon-rotate').constantOr(1) !== 0) { + bucket.iconsNeedLinear = true; + } + } + } + + const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical; + bucket.iconsInText = shapedText ? shapedText.iconsInText : false; + if (shapedText || shapedIcon) { + addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical); + } + } + + if (showCollisionBoxes) { + bucket.generateCollisionDebugBuffers(); + } +} + +// Choose the justification that matches the direction of the TextAnchor +export function getAnchorJustification(anchor: TextAnchor): TextJustify { + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + return 'right'; + case 'left': + case 'top-left': + case 'bottom-left': + return 'left'; + } + return 'center'; +} + +/** + * Given a feature and its shaped text and icon data, add a 'symbol + * instance' for each _possible_ placement of the symbol feature. + * (At render timePlaceSymbols#place() selects which of these instances to + * show or hide based on collisions with symbols in other layers.) + * @private + */ +function addFeature(bucket: SymbolBucket, + feature: SymbolFeature, + shapedTextOrientations: any, + shapedIcon: PositionedIcon | void, + imageMap: {[_: string]: StyleImage}, + sizes: Sizes, + layoutTextSize: number, + layoutIconSize: number, + textOffset: [number, number], + isSDFIcon: boolean, canonical: CanonicalTileID) { + // To reduce the number of labels that jump around when zooming we need + // to use a text-size value that is the same for all zoom levels. + // bucket calculates text-size at a high zoom level so that all tiles can + // use the same value when calculating anchor positions. + let textMaxSize = sizes.textMaxSize.evaluate(feature, {}); + if (textMaxSize === undefined) { + textMaxSize = layoutTextSize; + } + const layout = bucket.layers[0].layout; + const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical); + const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal); + const glyphSize = 24, + fontScale = layoutTextSize / glyphSize, + textBoxScale = bucket.tilePixelRatio * fontScale, + textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, + iconBoxScale = bucket.tilePixelRatio * layoutIconSize, + symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'), + textPadding = layout.get('text-padding') * bucket.tilePixelRatio, + iconPadding = layout.get('icon-padding') * bucket.tilePixelRatio, + textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI, + textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', + iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', + symbolPlacement = layout.get('symbol-placement'), + textRepeatDistance = symbolMinDistance / 2; + + const iconTextFit = layout.get('icon-text-fit'); + let verticallyShapedIcon; + // Adjust shaped icon size when icon-text-fit is used. + if (shapedIcon && iconTextFit !== 'none') { + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, + layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + if (defaultHorizontalShaping) { + shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, + layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + } + + const addSymbolAtAnchor = (line, anchor) => { + if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) { + // Symbol layers are drawn across tile boundaries, We filter out symbols + // outside our tile boundaries (which may be included in vector tile buffers) + // to prevent double-drawing symbols. + return; + } + + addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], + bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, + textBoxScale, textPadding, textAlongLine, textOffset, + iconBoxScale, iconPadding, iconAlongLine, iconOffset, + feature, sizes, isSDFIcon, canonical, layoutTextSize); + }; + + if (symbolPlacement === 'line') { + for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) { + const anchors = getAnchors( + line, + symbolMinDistance, + textMaxAngle, + shapedTextOrientations.vertical || defaultHorizontalShaping, + shapedIcon, + glyphSize, + textMaxBoxScale, + bucket.overscaling, + EXTENT + ); + for (const anchor of anchors) { + const shapedText = defaultHorizontalShaping; + if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) { + addSymbolAtAnchor(line, anchor); + } + } + } + } else if (symbolPlacement === 'line-center') { + // No clipping, multiple lines per feature are allowed + // "lines" with only one point are ignored as in clipLines + for (const line of feature.geometry) { + if (line.length > 1) { + const anchor = getCenterAnchor( + line, + textMaxAngle, + shapedTextOrientations.vertical || defaultHorizontalShaping, + shapedIcon, + glyphSize, + textMaxBoxScale); + if (anchor) { + addSymbolAtAnchor(line, anchor); + } + } + } + } else if (feature.type === 'Polygon') { + for (const polygon of classifyRings(feature.geometry, 0)) { + // 16 here represents 2 pixels + const poi = findPoleOfInaccessibility(polygon, 16); + addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0)); + } + } else if (feature.type === 'LineString') { + // https://github.com/mapbox/mapbox-gl-js/issues/3808 + for (const line of feature.geometry) { + addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0)); + } + } else if (feature.type === 'Point') { + for (const points of feature.geometry) { + for (const point of points) { + addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0)); + } + } + } +} + +const MAX_GLYPH_ICON_SIZE = 255; +const MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR; +export {MAX_PACKED_SIZE}; + +function addTextVertices(bucket: SymbolBucket, + anchor: Point, + shapedText: Shaping, + imageMap: {[_: string]: StyleImage}, + layer: SymbolStyleLayer, + textAlongLine: boolean, + feature: SymbolFeature, + textOffset: [number, number], + lineArray: {lineStartIndex: number, lineLength: number}, + writingMode: number, + placementTypes: Array<'vertical' | 'center' | 'left' | 'right'>, + placedTextSymbolIndices: {[_: string]: number}, + placedIconIndex: number, + sizes: Sizes, + canonical: CanonicalTileID) { + const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, + layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement); + + const sizeData = bucket.textSizeData; + let textSizeData = null; + + if (sizeData.kind === 'source') { + textSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } else if (sizeData.kind === 'composite') { + textSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + + bucket.addSymbols( + bucket.text, + glyphQuads, + textSizeData, + textOffset, + textAlongLine, + feature, + writingMode, + anchor, + lineArray.lineStartIndex, + lineArray.lineLength, + placedIconIndex, + canonical); + + // The placedSymbolArray is used at render time in drawTileSymbols + // These indices allow access to the array at collision detection time + for (const placementType of placementTypes) { + placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1; + } + + return glyphQuads.length * 4; +} + +function getDefaultHorizontalShaping(horizontalShaping: {[_: TextJustify]: Shaping}): Shaping | null { + // We don't care which shaping we get because this is used for collision purposes + // and all the justifications have the same collision box + for (const justification: any in horizontalShaping) { + return horizontalShaping[justification]; + } + return null; +} + +/** + * Add a single label & icon placement. + * + * @private + */ +function addSymbol(bucket: SymbolBucket, + anchor: Anchor, + line: Array, + shapedTextOrientations: any, + shapedIcon: PositionedIcon | void, + imageMap: {[_: string]: StyleImage}, + verticallyShapedIcon: PositionedIcon | void, + layer: SymbolStyleLayer, + collisionBoxArray: CollisionBoxArray, + featureIndex: number, + sourceLayerIndex: number, + bucketIndex: number, + textBoxScale: number, + textPadding: number, + textAlongLine: boolean, + textOffset: [number, number], + iconBoxScale: number, + iconPadding: number, + iconAlongLine: boolean, + iconOffset: [number, number], + feature: SymbolFeature, + sizes: Sizes, + isSDFIcon: boolean, + canonical: CanonicalTileID, + layoutTextSize: number) { + const lineArray = bucket.addToLineVertexArray(anchor, line); + + let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature; + + let numIconVertices = 0; + let numVerticalIconVertices = 0; + let numHorizontalGlyphVertices = 0; + let numVerticalGlyphVertices = 0; + let placedIconSymbolIndex = -1; + let verticalPlacedIconSymbolIndex = -1; + const placedTextSymbolIndices = {}; + let key = murmur3(''); + + let textOffset0 = 0; + let textOffset1 = 0; + if (layer._unevaluatedLayout.getValue('text-radial-offset') === undefined) { + [textOffset0, textOffset1] = (layer.layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM): any); + } else { + textOffset0 = layer.layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM; + textOffset1 = INVALID_TEXT_OFFSET; + } + + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + const verticalTextRotation = textRotation + 90.0; + const verticalShaping = shapedTextOrientations.vertical; + verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation); + + if (verticallyShapedIcon) { + verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation); + } + } + + //Place icon first, so text can have a reference to its index in the placed symbol array. + //Text symbols can lazily shift at render-time because of variable anchor placement. + //If the style specifies an `icon-text-fit` then the icon would have to shift along with it. + // For more info check `updateVariableAnchors` in `draw_symbol.js` . + if (shapedIcon) { + const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}); + const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none'; + const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit); + const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined; + iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/false, iconRotate); + + numIconVertices = iconQuads.length * 4; + + const sizeData = bucket.iconSizeData; + let iconSizeData = null; + + if (sizeData.kind === 'source') { + iconSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } else if (sizeData.kind === 'composite') { + iconSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + + bucket.addSymbols( + bucket.icon, + iconQuads, + iconSizeData, + iconOffset, + iconAlongLine, + feature, + false, + anchor, + lineArray.lineStartIndex, + lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isnt placed yet + -1, canonical); + + placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + + if (verticalIconQuads) { + numVerticalIconVertices = verticalIconQuads.length * 4; + + bucket.addSymbols( + bucket.icon, + verticalIconQuads, + iconSizeData, + iconOffset, + iconAlongLine, + feature, + WritingMode.vertical, + anchor, + lineArray.lineStartIndex, + lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isnt placed yet + -1, canonical); + + verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + } + } + + for (const justification: any in shapedTextOrientations.horizontal) { + const shaping = shapedTextOrientations.horizontal[justification]; + + if (!textCollisionFeature) { + key = murmur3(shaping.text); + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature + // We're counting on all versions having similar dimensions + textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate); + } + + const singleLine = shaping.positionedLines.length === 1; + numHorizontalGlyphVertices += addTextVertices( + bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray, + shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly, + singleLine ? (Object.keys(shapedTextOrientations.horizontal): any) : [justification], + placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical); + + if (singleLine) { + break; + } + } + + if (shapedTextOrientations.vertical) { + numVerticalGlyphVertices += addTextVertices( + bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, + textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical); + } + + const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + // Check if runtime collision circles should be used for any of the collision features. + // It is enough to choose the tallest feature shape as circles are always placed on a line. + // All measurements are in glyph metrics and later converted into pixels using proper font size "layoutTextSize" + let collisionCircleDiameter = -1; + + const getCollisionCircleHeight = (feature: ?CollisionFeature, prevHeight: number): number => { + if (feature && feature.circleDiameter) + return Math.max(feature.circleDiameter, prevHeight); + return prevHeight; + }; + + collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter); + const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0; + + // Convert circle collision height into pixels + if (useRuntimeCollisionCircles) + collisionCircleDiameter *= layoutTextSize / ONE_EM; + + if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) warnOnce( + "Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907" + ); + + if (feature.sortKey !== undefined) { + bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey); + } + + bucket.symbolInstances.emplaceBack( + anchor.x, + anchor.y, + placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, + placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, + placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, + placedTextSymbolIndices.vertical || -1, + placedIconSymbolIndex, + verticalPlacedIconSymbolIndex, + key, + textBoxStartIndex, + textBoxEndIndex, + verticalTextBoxStartIndex, + verticalTextBoxEndIndex, + iconBoxStartIndex, + iconBoxEndIndex, + verticalIconBoxStartIndex, + verticalIconBoxEndIndex, + featureIndex, + numHorizontalGlyphVertices, + numVerticalGlyphVertices, + numIconVertices, + numVerticalIconVertices, + useRuntimeCollisionCircles, + 0, + textBoxScale, + textOffset0, + textOffset1, + collisionCircleDiameter); +} + +function anchorIsTooClose(bucket: any, text: string, repeatDistance: number, anchor: Point) { + const compareText = bucket.compareText; + if (!(text in compareText)) { + compareText[text] = []; + } else { + const otherAnchors = compareText[text]; + for (let k = otherAnchors.length - 1; k >= 0; k--) { + if (anchor.dist(otherAnchors[k]) < repeatDistance) { + // If it's within repeatDistance of one anchor, stop looking + return true; + } + } + } + // If anchor is not within repeatDistance of any other anchor, add to array + compareText[text].push(anchor); + return false; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/symbol_size.js b/node_modules/@plotly/mapbox-gl/src/symbol/symbol_size.js new file mode 100644 index 0000000000000000000000000000000000000000..dab8f4b898974f47d2d103e1a80d03545db20120 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/symbol_size.js @@ -0,0 +1,113 @@ +// @flow + +import {number as interpolate} from '../style-spec/util/interpolate'; +import Interpolate from '../style-spec/expression/definitions/interpolate'; +import {clamp} from '../util/util'; +import EvaluationParameters from '../style/evaluation_parameters'; + +import type {PropertyValue, PossiblyEvaluatedPropertyValue} from '../style/properties'; +import type {InterpolationType} from '../style-spec/expression/definitions/interpolate'; + +const SIZE_PACK_FACTOR = 128; + +export {getSizeData, evaluateSizeForFeature, evaluateSizeForZoom, SIZE_PACK_FACTOR}; + +export type SizeData = { + kind: 'constant', + layoutSize: number +} | { + kind: 'source' +} | { + kind: 'camera', + minZoom: number, + maxZoom: number, + minSize: number, + maxSize: number, + interpolationType: ?InterpolationType +} | { + kind: 'composite', + minZoom: number, + maxZoom: number, + interpolationType: ?InterpolationType +}; + +// For {text,icon}-size, get the bucket-level data that will be needed by +// the painter to set symbol-size-related uniforms +function getSizeData(tileZoom: number, value: PropertyValue>): SizeData { + const {expression} = value; + + if (expression.kind === 'constant') { + const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1)); + return {kind: 'constant', layoutSize}; + + } else if (expression.kind === 'source') { + return {kind: 'source'}; + + } else { + const {zoomStops, interpolationType} = expression; + + // calculate covering zoom stops for zoom-dependent values + let lower = 0; + while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) lower++; + lower = Math.max(0, lower - 1); + let upper = lower; + while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) upper++; + upper = Math.min(zoomStops.length - 1, upper); + + const minZoom = zoomStops[lower]; + const maxZoom = zoomStops[upper]; + + // We'd like to be able to use CameraExpression or CompositeExpression in these + // return types rather than ExpressionSpecification, but the former are not + // transferrable across Web Worker boundaries. + if (expression.kind === 'composite') { + return {kind: 'composite', minZoom, maxZoom, interpolationType}; + } + + // for camera functions, also save off the function values + // evaluated at the covering zoom levels + const minSize = expression.evaluate(new EvaluationParameters(minZoom)); + const maxSize = expression.evaluate(new EvaluationParameters(maxZoom)); + + return {kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType}; + } +} + +function evaluateSizeForFeature(sizeData: SizeData, + {uSize, uSizeT}: { uSize: number, uSizeT: number }, + {lowerSize, upperSize}: { lowerSize: number, upperSize: number}) { + if (sizeData.kind === 'source') { + return lowerSize / SIZE_PACK_FACTOR; + } else if (sizeData.kind === 'composite') { + return interpolate(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT); + } + return uSize; +} + +function evaluateSizeForZoom(sizeData: SizeData, zoom: number) { + let uSizeT = 0; + let uSize = 0; + + if (sizeData.kind === 'constant') { + uSize = sizeData.layoutSize; + + } else if (sizeData.kind !== 'source') { + const {interpolationType, minZoom, maxZoom} = sizeData; + + // Even though we could get the exact value of the camera function + // at z = tr.zoom, we intentionally do not: instead, we interpolate + // between the camera function values at a pair of zoom stops covering + // [tileZoom, tileZoom + 1] in order to be consistent with this + // restriction on composite functions + const t = !interpolationType ? 0 : clamp( + Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1); + + if (sizeData.kind === 'camera') { + uSize = interpolate(sizeData.minSize, sizeData.maxSize, t); + } else { + uSizeT = t; + } + } + + return {uSizeT, uSize}; +} diff --git a/node_modules/@plotly/mapbox-gl/src/symbol/transform_text.js b/node_modules/@plotly/mapbox-gl/src/symbol/transform_text.js new file mode 100644 index 0000000000000000000000000000000000000000..c6d4c74671383c343c7b4a957275911c5185fc2d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/symbol/transform_text.js @@ -0,0 +1,29 @@ +// @flow + +import {plugin as rtlTextPlugin} from '../source/rtl_text_plugin'; + +import type SymbolStyleLayer from '../style/style_layer/symbol_style_layer'; +import type {Feature} from '../style-spec/expression'; +import Formatted from '../style-spec/expression/types/formatted'; + +function transformText(text: string, layer: SymbolStyleLayer, feature: Feature) { + const transform = layer.layout.get('text-transform').evaluate(feature, {}); + if (transform === 'uppercase') { + text = text.toLocaleUpperCase(); + } else if (transform === 'lowercase') { + text = text.toLocaleLowerCase(); + } + + if (rtlTextPlugin.applyArabicShaping) { + text = rtlTextPlugin.applyArabicShaping(text); + } + + return text; +} + +export default function(text: Formatted, layer: SymbolStyleLayer, feature: Feature): Formatted { + text.sections.forEach(section => { + section.text = transformText(section.text, layer, feature); + }); + return text; +} diff --git a/node_modules/@plotly/mapbox-gl/src/types/callback.js b/node_modules/@plotly/mapbox-gl/src/types/callback.js new file mode 100644 index 0000000000000000000000000000000000000000..217eff73014f170575a6b370adf4076346d8c5fc --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/types/callback.js @@ -0,0 +1,17 @@ +// @flow strict + +// Flow can't perfectly type Node-style callbacks yet; it does not have a way to +// express that if the first parameter is null, the second is not, so for the time +// being, both parameters must be optional. Use the following convention when defining +// a callback: +// +// asyncFunction((error, result) => { +// if (error) { +// // handle error +// } else if (result) { +// // handle success +// } +// }); +// +// See https://github.com/facebook/flow/issues/2123 for more. +export type Callback = (error: ?Error, result: ?T) => void; diff --git a/node_modules/@plotly/mapbox-gl/src/types/cancelable.js b/node_modules/@plotly/mapbox-gl/src/types/cancelable.js new file mode 100644 index 0000000000000000000000000000000000000000..e155168ac003a502129ba0f079e65a476e7838fe --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/types/cancelable.js @@ -0,0 +1,3 @@ +// @flow strict + +export type Cancelable = { cancel: () => void }; diff --git a/node_modules/@plotly/mapbox-gl/src/types/tilejson.js b/node_modules/@plotly/mapbox-gl/src/types/tilejson.js new file mode 100644 index 0000000000000000000000000000000000000000..328f378e2a95d280152c3ae4b1c3519ff5d31867 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/types/tilejson.js @@ -0,0 +1,17 @@ +// @flow + +export type TileJSON = {| + tilejson: '2.2.0' | '2.1.0' | '2.0.1' | '2.0.0' | '1.0.0', + name?: string, + description?: string, + version?: string, + attribution?: string, + template?: string, + tiles: Array, + grids?: Array, + data?: Array, + minzoom?: number, + maxzoom?: number, + bounds?: [number, number, number, number], + center?: [number, number, number] +|}; diff --git a/node_modules/@plotly/mapbox-gl/src/types/transferable.js b/node_modules/@plotly/mapbox-gl/src/types/transferable.js new file mode 100644 index 0000000000000000000000000000000000000000..0d57cc4c5017e7805ceefa85ed2ba1ed9f8d40e1 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/types/transferable.js @@ -0,0 +1,3 @@ +// @flow + +export type Transferable = ArrayBuffer | MessagePort | ImageBitmap; diff --git a/node_modules/@plotly/mapbox-gl/src/types/window.js b/node_modules/@plotly/mapbox-gl/src/types/window.js new file mode 100644 index 0000000000000000000000000000000000000000..8957156fcc71016485f546a050f72003f4924066 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/types/window.js @@ -0,0 +1,172 @@ +// @flow strict + +/* global EventTarget, IDBEnvironment */ + +export interface Window extends EventTarget, IDBEnvironment { + +caches: CacheStorage; + +clientInformation: Navigator; + +closed: boolean; + defaultStatus: string; + +devicePixelRatio: number; + +document: Document; + +doNotTrack: string; + +frameElement: Element; + +frames: Window; + +history: History; + +innerHeight: number; + +innerWidth: number; + +isSecureContext: boolean; + +length: number; + +location: Location; + +origin: string; + name: string; + +navigator: Navigator; + offscreenBuffering: string | boolean; + onabort: (ev: UIEvent) => ?boolean; + onafterprint: (ev: Event) => ?boolean; + onbeforeprint: (ev: Event) => ?boolean; + onbeforeunload: (ev: Event) => ?boolean; + onblur: (ev: FocusEvent) => ?boolean; + oncanplay: (ev: Event) => ?boolean; + oncanplaythrough: (ev: Event) => ?boolean; + onchange: (ev: Event) => ?boolean; + onclick: (ev: MouseEvent) => ?boolean; + oncompassneedscalibration: (ev: Event) => ?boolean; + oncontextmenu: (ev: Event) => ?boolean; + ondblclick: (ev: MouseEvent) => ?boolean; + ondevicelight: (ev: Event) => ?boolean; + ondevicemotion: (ev: Event) => ?boolean; + ondeviceorientation: (ev: Event) => ?boolean; + ondrag: (ev: DragEvent) => ?boolean; + ondragend: (ev: DragEvent) => ?boolean; + ondragenter: (ev: DragEvent) => ?boolean; + ondragleave: (ev: DragEvent) => ?boolean; + ondragover: (ev: DragEvent) => ?boolean; + ondragstart: (ev: DragEvent) => ?boolean; + ondrop: (ev: DragEvent) => ?boolean; + ondurationchange: (ev: Event) => ?boolean; + onemptied: (ev: Event) => ?boolean; + onended: (ev: Event) => ?boolean; + onerror: (ev: Event) => ?boolean; + onfocus: (ev: FocusEvent) => ?boolean; + onhashchange: (ev: Event) => ?boolean; + oninput: (ev: Event) => ?boolean; + oninvalid: (ev: Event) => ?boolean; + onkeydown: (ev: KeyboardEvent) => ?boolean; + onkeypress: (ev: KeyboardEvent) => ?boolean; + onkeyup: (ev: KeyboardEvent) => ?boolean; + onload: (ev: Event) => ?boolean; + onloadeddata: (ev: Event) => ?boolean; + onloadedmetadata: (ev: Event) => ?boolean; + onloadstart: (ev: Event) => ?boolean; + onmessage: (ev: MessageEvent) => ?boolean; + onmousedown: (ev: MouseEvent) => ?boolean; + onmouseenter: (ev: MouseEvent) => ?boolean; + onmouseleave: (ev: MouseEvent) => ?boolean; + onmousemove: (ev: MouseEvent) => ?boolean; + onmouseout: (ev: MouseEvent) => ?boolean; + onmouseover: (ev: MouseEvent) => ?boolean; + onmouseup: (ev: MouseEvent) => ?boolean; + onmousewheel: (ev: WheelEvent) => ?boolean; + onoffline: (ev: Event) => ?boolean; + ononline: (ev: Event) => ?boolean; + onorientationchange: (ev: Event) => ?boolean; + onpagehide: (ev: Event) => ?boolean; + onpageshow: (ev: Event) => ?boolean; + onpause: (ev: Event) => ?boolean; + onplay: (ev: Event) => ?boolean; + onplaying: (ev: Event) => ?boolean; + onpopstate: (ev: Event) => ?boolean; + onprogress: (ev: ProgressEvent) => ?boolean; + onratechange: (ev: Event) => ?boolean; + onreadystatechange: (ev: ProgressEvent) => ?boolean; + onreset: (ev: Event) => ?boolean; + onresize: (ev: UIEvent) => ?boolean; + onscroll: (ev: UIEvent) => ?boolean; + onseeked: (ev: Event) => ?boolean; + onseeking: (ev: Event) => ?boolean; + onselect: (ev: UIEvent) => ?boolean; + onstalled: (ev: Event) => ?boolean; + onstorage: (ev: Event) => ?boolean; + onsubmit: (ev: Event) => ?boolean; + onsuspend: (ev: Event) => ?boolean; + ontimeupdate: (ev: Event) => ?boolean; + ontouchcancel: (ev: TouchEvent) => ?boolean; + ontouchend: (ev: TouchEvent) => ?boolean; + ontouchmove: (ev: TouchEvent) => ?boolean; + ontouchstart: (ev: TouchEvent) => ?boolean; + onunload: (ev: Event) => ?boolean; + onvolumechange: (ev: Event) => ?boolean; + onwaiting: (ev: Event) => ?boolean; + opener: Window; + orientation: string | number; + +outerHeight: number; + +outerWidth: number; + +pageXOffset: number; + +pageYOffset: number; + +parent: Window; + +performance: Performance; + +screen: Screen; + +screenLeft: number; + +screenTop: number; + +screenX: number; + +screenY: number; + +scrollX: number; + +scrollY: number; + +self: Window; + status: string; + +top: Window; + +window: Window; + + Blob: typeof Blob; + HTMLImageElement: typeof HTMLImageElement; + HTMLElement: typeof HTMLElement; + HTMLVideoElement: typeof HTMLVideoElement; + HTMLCanvasElement: typeof HTMLCanvasElement; + Image: typeof Image; + ImageData: typeof ImageData; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + WebGLFramebuffer: typeof WebGLFramebuffer; + WheelEvent: typeof WheelEvent; + Worker: typeof Worker; + XMLHttpRequest: typeof XMLHttpRequest; + Request: typeof Request; + AbortController: typeof AbortController; + + alert(message?: string): void; + blur(): void; + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getSelection(): Selection; + moveBy(x?: number, y?: number): void; + moveTo(x?: number, y?: number): void; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + postMessage(message: mixed, targetOrigin: string, transfer?: ArrayBuffer[]): void; + print(): void; + prompt(message?: string, _default?: string): string | null; + releaseEvents(): void; + resizeBy(x?: number, y?: number): void; + resizeTo(x?: number, y?: number): void; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; + stop(): void; + + clearInterval(intervalId?: number): void; + clearTimeout(timeoutId?: number): void; + setTimeout(callback: () => void, ms?: number): number; + setInterval(callback: () => void, ms?: number): number; + + requestAnimationFrame(callback: (timestamp: number) => void): number; + cancelAnimationFrame(handle: number): void; + msRequestAnimationFrame(callback: (timestamp: number) => void): number; + msCancelAnimationFrame(handle: number): void; + webkitRequestAnimationFrame(callback: (timestamp: number) => void): number; + webkitCancelAnimationFrame(handle: number): void; +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/anchor.js b/node_modules/@plotly/mapbox-gl/src/ui/anchor.js new file mode 100644 index 0000000000000000000000000000000000000000..78b2bc2b99fb072ffd64b1461bd3cb7ccb0e64d4 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/anchor.js @@ -0,0 +1,32 @@ +// @flow + +export type Anchor = + | 'center' + | 'top' + | 'bottom' + | 'left' + | 'right' + | 'top-left' + | 'top-right' + | 'bottom-left' + | 'bottom-right'; + +export const anchorTranslate: {[_: Anchor]: string} = { + 'center': 'translate(-50%,-50%)', + '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%)' +}; + +export function applyAnchorClass(element: HTMLElement, anchor: Anchor, prefix: string) { + const classList = element.classList; + for (const key in anchorTranslate) { + classList.remove(`mapboxgl-${prefix}-anchor-${key}`); + } + classList.add(`mapboxgl-${prefix}-anchor-${anchor}`); +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/camera.js b/node_modules/@plotly/mapbox-gl/src/ui/camera.js new file mode 100644 index 0000000000000000000000000000000000000000..f0a922acb8a623a961385225ab72c143df112703 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/camera.js @@ -0,0 +1,1277 @@ +// @flow + +import { + bindAll, + extend, + warnOnce, + clamp, + wrap, + ease as defaultEasing, + pick +} from '../util/util'; +import {number as interpolate} from '../style-spec/util/interpolate'; +import browser from '../util/browser'; +import LngLat from '../geo/lng_lat'; +import LngLatBounds from '../geo/lng_lat_bounds'; +import Point from '@mapbox/point-geometry'; +import {Event, Evented} from '../util/evented'; +import assert from 'assert'; +import {Debug} from '../util/debug'; + +import type Transform from '../geo/transform'; +import type {LngLatLike} from '../geo/lng_lat'; +import type {LngLatBoundsLike} from '../geo/lng_lat_bounds'; +import type {TaskID} from '../util/task_queue'; +import type {PointLike} from '@mapbox/point-geometry'; +import type {PaddingOptions} from '../geo/edge_insets'; + +/** + * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location, + * zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current + * camera value for that property will remain unchanged. + * + * @typedef {Object} CameraOptions + * @property {LngLatLike} center The desired center. + * @property {number} zoom The desired zoom level. + * @property {number} bearing The desired bearing in degrees. The bearing is the compass direction that + * is "up". For example, `bearing: 90` orients the map so that east is up. + * @property {number} pitch The desired pitch in degrees. The pitch is the angle towards the horizon + * measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance + * of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon. + * Increasing the pitch value is often used to display 3D objects. + * @property {LngLatLike} around If `zoom` is specified, `around` determines the point around which the zoom is centered. + * @property {PaddingOptions} padding Dimensions in pixels applied on each side of the viewport for shifting the vanishing point. + * @example + * // set the map's initial perspective with CameraOptions + * var map = new mapboxgl.Map({ + * container: 'map', + * style: 'mapbox://styles/mapbox/streets-v11', + * center: [-73.5804, 45.53483], + * pitch: 60, + * bearing: -60, + * zoom: 10 + * }); + * @see [Set pitch and bearing](https://docs.mapbox.com/mapbox-gl-js/example/set-perspective/) + * @see [Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/) + * @see [Fly to a location](https://docs.mapbox.com/mapbox-gl-js/example/flyto/) + * @see [Display buildings in 3D](https://docs.mapbox.com/mapbox-gl-js/example/3d-buildings/) + */ +export type CameraOptions = { + center?: LngLatLike, + zoom?: number, + bearing?: number, + pitch?: number, + around?: LngLatLike, + padding?: PaddingOptions +}; + +/** + * Options common to map movement methods that involve animation, such as {@link Map#panBy} and + * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties + * are optional. + * + * @typedef {Object} AnimationOptions + * @property {number} duration The animation's duration, measured in milliseconds. + * @property {Function} easing A function taking a time in the range 0..1 and returning a number where 0 is + * the initial state and 1 is the final state. + * @property {PointLike} offset of the target center relative to real map container center at the end of animation. + * @property {boolean} animate If `false`, no animation will occur. + * @property {boolean} essential If `true`, then the animation is considered essential and will not be affected by + * [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion). + */ +export type AnimationOptions = { + duration?: number, + easing?: (_: number) => number, + offset?: PointLike, + animate?: boolean, + essential?: boolean +}; + +/** + * Options for setting padding on calls to methods such as {@link Map#fitBounds}, {@link Map#fitScreenCoordinates}, and {@link Map#setPadding}. Adjust these options to set the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual values for each edge. All properties of this object must be + * non-negative integers. + * + * @typedef {Object} PaddingOptions + * @property {number} top Padding in pixels from the top of the map canvas. + * @property {number} bottom Padding in pixels from the bottom of the map canvas. + * @property {number} left Padding in pixels from the left of the map canvas. + * @property {number} right Padding in pixels from the right of the map canvas. + * + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: 20 + * }); + * @see [Fit to the bounds of a LineString](https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/) + * @see [Fit a map to a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/fitbounds/) + */ + +class Camera extends Evented { + transform: Transform; + _moving: boolean; + _zooming: boolean; + _rotating: boolean; + _pitching: boolean; + _padding: boolean; + + _bearingSnap: number; + _easeStart: number; + _easeOptions: {duration: number, easing: (_: number) => number}; + _easeId: string | void; + + _onEaseFrame: (_: number) => void; + _onEaseEnd: (easeId?: string) => void; + _easeFrameId: ?TaskID; + + +_requestRenderFrame: (() => void) => TaskID; + +_cancelRenderFrame: (_: TaskID) => void; + + constructor(transform: Transform, options: {bearingSnap: number}) { + super(); + this._moving = false; + this._zooming = false; + this.transform = transform; + this._bearingSnap = options.bearingSnap; + + bindAll(['_renderFrameCallback'], this); + + //addAssertions(this); + } + + /** + * Returns the map's geographical centerpoint. + * + * @memberof Map# + * @returns The map's geographical centerpoint. + * @example + * // return a LngLat object such as {lng: 0, lat: 0} + * var center = map.getCenter(); + * // access longitude and latitude values directly + * var {longitude, latitude} = map.getCenter(); + * @see Tutorial: [Use Mapbox GL JS in a React app](https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/#store-the-new-coordinates) + */ + getCenter(): LngLat { return new LngLat(this.transform.center.lng, this.transform.center.lat); } + + /** + * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`. + * + * @memberof Map# + * @param center The centerpoint to set. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * map.setCenter([-74, 38]); + */ + setCenter(center: LngLatLike, eventData?: Object) { + return this.jumpTo({center}, eventData); + } + + /** + * Pans the map by the specified offset. + * + * @memberof Map# + * @param offset `x` and `y` coordinates by which to pan the map. + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/) + */ + panBy(offset: PointLike, options?: AnimationOptions, eventData?: Object) { + offset = Point.convert(offset).mult(-1); + return this.panTo(this.transform.center, extend({offset}, options), eventData); + } + + /** + * Pans the map to the specified location with an animated transition. + * + * @memberof Map# + * @param lnglat The location to pan the map to. + * @param options Options describing the destination and animation of the transition. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * map.panTo([-74, 38]); + * @example + * // Specify that the panTo animation should last 5000 milliseconds. + * map.panTo([-74, 38], {duration: 5000}); + * @see [Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/) + */ + panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: Object) { + return this.easeTo(extend({ + center: lnglat + }, options), eventData); + } + + /** + * Returns the map's current zoom level. + * + * @memberof Map# + * @returns The map's current zoom level. + * @example + * map.getZoom(); + */ + getZoom(): number { return this.transform.zoom; } + + /** + * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`. + * + * @memberof Map# + * @param zoom The zoom level to set (0-20). + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // Zoom to the zoom level 5 without an animated transition + * map.setZoom(5); + */ + setZoom(zoom: number, eventData?: Object) { + this.jumpTo({zoom}, eventData); + return this; + } + + /** + * Zooms the map to the specified zoom level, with an animated transition. + * + * @memberof Map# + * @param zoom The zoom level to transition to. + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // Zoom to the zoom level 5 without an animated transition + * map.zoomTo(5); + * // Zoom to the zoom level 8 with an animated transition + * map.zoomTo(8, { + * duration: 2000, + * offset: [100, 50] + * }); + */ + zoomTo(zoom: number, options: ? AnimationOptions, eventData?: Object) { + return this.easeTo(extend({ + zoom + }, options), eventData); + } + + /** + * Increases the map's zoom level by 1. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // zoom the map in one level with a custom animation duration + * map.zoomIn({duration: 1000}); + */ + zoomIn(options?: AnimationOptions, eventData?: Object) { + this.zoomTo(this.getZoom() + 1, options, eventData); + return this; + } + + /** + * Decreases the map's zoom level by 1. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // zoom the map out one level with a custom animation offset + * map.zoomOut({offset: [80, 60]}); + */ + zoomOut(options?: AnimationOptions, eventData?: Object) { + this.zoomTo(this.getZoom() - 1, options, eventData); + return this; + } + + /** + * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * @memberof Map# + * @returns The map's current bearing. + * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/) + */ + getBearing(): number { return this.transform.bearing; } + + /** + * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * Equivalent to `jumpTo({bearing: bearing})`. + * + * @memberof Map# + * @param bearing The desired bearing. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * // rotate the map to 90 degrees + * map.setBearing(90); + */ + setBearing(bearing: number, eventData?: Object) { + this.jumpTo({bearing}, eventData); + return this; + } + + /** + * Returns the current padding applied around the map viewport. + * + * @memberof Map# + * @returns The current padding around the map viewport. + */ + getPadding(): PaddingOptions { return this.transform.padding; } + + /** + * Sets the padding in pixels around the viewport. + * + * Equivalent to `jumpTo({padding: padding})`. + * + * @memberof Map# + * @param padding The desired padding. Format: { left: number, right: number, top: number, bottom: number } + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * // Sets a left padding of 300px, and a top padding of 50px + * map.setPadding({ left: 300, top: 50 }); + */ + setPadding(padding: PaddingOptions, eventData?: Object) { + this.jumpTo({padding}, eventData); + return this; + } + + /** + * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction + * that is \"up\"; for example, a bearing of 90° orients the map so that east is up. + * + * @memberof Map# + * @param bearing The desired bearing. + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + rotateTo(bearing: number, options?: AnimationOptions, eventData?: Object) { + return this.easeTo(extend({ + bearing + }, options), eventData); + } + + /** + * Rotates the map so that north is up (0° bearing), with an animated transition. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + resetNorth(options?: AnimationOptions, eventData?: Object) { + this.rotateTo(0, extend({duration: 1000}, options), eventData); + return this; + } + + /** + * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + resetNorthPitch(options?: AnimationOptions, eventData?: Object) { + this.easeTo(extend({ + bearing: 0, + pitch: 0, + duration: 1000 + }, options), eventData); + return this; + } + + /** + * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the + * `bearingSnap` threshold). + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + snapToNorth(options?: AnimationOptions, eventData?: Object) { + if (Math.abs(this.getBearing()) < this._bearingSnap) { + return this.resetNorth(options, eventData); + } + return this; + } + + /** + * Returns the map's current pitch (tilt). + * + * @memberof Map# + * @returns The map's current pitch, measured in degrees away from the plane of the screen. + */ + getPitch(): number { return this.transform.pitch; } + + /** + * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`. + * + * @memberof Map# + * @param pitch The pitch to set, measured in degrees away from the plane of the screen (0-60). + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires pitchstart + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + setPitch(pitch: number, eventData?: Object) { + this.jumpTo({pitch}, eventData); + return this; + } + + /** + * @memberof Map# + * @param {LngLatBoundsLike} bounds Calculate the center for these bounds in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. + * @param options Options object + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {number} [options.bearing=0] Desired map bearing at end of animation, in degrees. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds. + * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with + * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined. + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * var newCameraTransform = map.cameraForBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + */ + cameraForBounds(bounds: LngLatBoundsLike, options?: CameraOptions): void | CameraOptions & AnimationOptions { + bounds = LngLatBounds.convert(bounds); + const bearing = options && options.bearing || 0; + return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options); + } + + /** + * Calculate the center of these two points in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * the points in the viewport at the specified bearing. + * @memberof Map# + * @param {LngLatLike} p0 First point + * @param {LngLatLike} p1 Second point + * @param bearing Desired map bearing at end of animation, in degrees + * @param options + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds. + * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with + * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined. + * @private + * @example + * var p0 = [-79, 43]; + * var p1 = [-73, 45]; + * var bearing = 90; + * var newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + */ + _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraOptions): void | CameraOptions & AnimationOptions { + const defaultPadding = { + top: 0, + bottom: 0, + right: 0, + left: 0 + }; + options = extend({ + padding: defaultPadding, + offset: [0, 0], + maxZoom: this.transform.maxZoom + }, options); + + if (typeof options.padding === 'number') { + const p = options.padding; + options.padding = { + top: p, + bottom: p, + right: p, + left: p + }; + } + + options.padding = extend(defaultPadding, options.padding); + const tr = this.transform; + const edgePadding = tr.padding; + + // We want to calculate the upper right and lower left of the box defined by p0 and p1 + // in a coordinate system rotate to match the destination bearing. + const p0world = tr.project(LngLat.convert(p0)); + const p1world = tr.project(LngLat.convert(p1)); + const p0rotated = p0world.rotate(-bearing * Math.PI / 180); + const p1rotated = p1world.rotate(-bearing * Math.PI / 180); + + const upperRight = new Point(Math.max(p0rotated.x, p1rotated.x), Math.max(p0rotated.y, p1rotated.y)); + const lowerLeft = new Point(Math.min(p0rotated.x, p1rotated.x), Math.min(p0rotated.y, p1rotated.y)); + + // Calculate zoom: consider the original bbox and padding. + const size = upperRight.sub(lowerLeft); + const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x; + const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y; + + if (scaleY < 0 || scaleX < 0) { + warnOnce( + 'Map cannot fit within canvas with the given bounds, padding, and/or offset.' + ); + return; + } + + const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom); + + // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding. + const offset = (typeof options.offset.x === 'number') ? new Point(options.offset.x, options.offset.y) : Point.convert(options.offset); + const paddingOffsetX = (options.padding.left - options.padding.right) / 2; + const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2; + const paddingOffset = new Point(paddingOffsetX, paddingOffsetY); + const rotatedPaddingOffset = paddingOffset.rotate(bearing * Math.PI / 180); + const offsetAtInitialZoom = offset.add(rotatedPaddingOffset); + const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom)); + + const center = tr.unproject(p0world.add(p1world).div(2).sub(offsetAtFinalZoom)); + + return { + center, + zoom, + bearing + }; + } + + /** + * Pans and zooms the map to contain its visible area within the specified geographical bounds. + * This function will also reset the map's bearing to 0 if bearing is nonzero. + * + * @memberof Map# + * @param bounds Center these bounds in the viewport and use the highest + * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. + * @param {Object} [options] Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below. + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {boolean} [options.linear=false] If `true`, the map transitions using + * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See + * those functions and {@link AnimationOptions} for information about options available. + * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds. + * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * @see [Fit a map to a bounding box](https://www.mapbox.com/mapbox-gl-js/example/fitbounds/) + */ + fitBounds(bounds: LngLatBoundsLike, options?: AnimationOptions & CameraOptions, eventData?: Object) { + return this._fitInternal( + this.cameraForBounds(bounds, options), + options, + eventData); + } + + /** + * Pans, rotates and zooms the map to to fit the box made by points p0 and p1 + * once the map is rotated to the specified bearing. To zoom without rotating, + * pass in the current map bearing. + * + * @memberof Map# + * @param p0 First point on screen, in pixel coordinates + * @param p1 Second point on screen, in pixel coordinates + * @param bearing Desired map bearing at end of animation, in degrees + * @param options Options object + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {boolean} [options.linear=false] If `true`, the map transitions using + * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See + * those functions and {@link AnimationOptions} for information about options available. + * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * var p0 = [220, 400]; + * var p1 = [500, 900]; + * map.fitScreenCoordinates(p0, p1, map.getBearing(), { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * @see Used by {@link BoxZoomHandler} + */ + fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: AnimationOptions & CameraOptions, eventData?: Object) { + return this._fitInternal( + this._cameraForBoxAndBearing( + this.transform.pointLocation(Point.convert(p0)), + this.transform.pointLocation(Point.convert(p1)), + bearing, + options), + options, + eventData); + } + + _fitInternal(calculatedOptions?: CameraOptions & AnimationOptions, options?: AnimationOptions & CameraOptions, eventData?: Object) { + // cameraForBounds warns + returns undefined if unable to fit: + if (!calculatedOptions) return this; + + options = extend(calculatedOptions, options); + // Explictly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly. + delete options.padding; + + return options.linear ? + this.easeTo(options, eventData) : + this.flyTo(options, eventData); + } + + /** + * Changes any combination of center, zoom, bearing, and pitch, without + * an animated transition. The map will retain its current values for any + * details not specified in `options`. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires pitchstart + * @fires rotate + * @fires move + * @fires zoom + * @fires pitch + * @fires moveend + * @fires zoomend + * @fires pitchend + * @returns {Map} `this` + * @example + * // jump to coordinates at current zoom + * map.jumpTo({center: [0, 0]}); + * // jump with zoom, pitch, and bearing options + * map.jumpTo({ + * center: [0, 0], + * zoom: 8, + * pitch: 45, + * bearing: 90 + * }); + * @see [Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/) + * @see [Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/) + */ + jumpTo(options: CameraOptions, eventData?: Object) { + this.stop(); + + const tr = this.transform; + let zoomChanged = false, + bearingChanged = false, + pitchChanged = false; + + if ('zoom' in options && tr.zoom !== +options.zoom) { + zoomChanged = true; + tr.zoom = +options.zoom; + } + + if (options.center !== undefined) { + tr.center = LngLat.convert(options.center); + } + + if ('bearing' in options && tr.bearing !== +options.bearing) { + bearingChanged = true; + tr.bearing = +options.bearing; + } + + if ('pitch' in options && tr.pitch !== +options.pitch) { + pitchChanged = true; + tr.pitch = +options.pitch; + } + + if (options.padding != null && !tr.isPaddingEqual(options.padding)) { + tr.padding = options.padding; + } + + this.fire(new Event('movestart', eventData)) + .fire(new Event('move', eventData)); + + if (zoomChanged) { + this.fire(new Event('zoomstart', eventData)) + .fire(new Event('zoom', eventData)) + .fire(new Event('zoomend', eventData)); + } + + if (bearingChanged) { + this.fire(new Event('rotatestart', eventData)) + .fire(new Event('rotate', eventData)) + .fire(new Event('rotateend', eventData)); + } + + if (pitchChanged) { + this.fire(new Event('pitchstart', eventData)) + .fire(new Event('pitch', eventData)) + .fire(new Event('pitchend', eventData)); + } + + return this.fire(new Event('moveend', eventData)); + } + + /** + * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition + * between old and new values. The map will retain its current values for any + * details not specified in `options`. + * + * Note: The transition will happen instantly if the user has enabled + * the `reduced motion` accesibility feature enabled in their operating system, + * unless `options` includes `essential: true`. + * + * @memberof Map# + * @param options Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions} and {@link AnimationOptions}. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires pitchstart + * @fires rotate + * @fires move + * @fires zoom + * @fires pitch + * @fires moveend + * @fires zoomend + * @fires pitchend + * @returns {Map} `this` + * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/) + */ + easeTo(options: CameraOptions & AnimationOptions & {easeId?: string}, eventData?: Object) { + this._stop(false, options.easeId); + + options = extend({ + offset: [0, 0], + duration: 500, + easing: defaultEasing + }, options); + + if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) options.duration = 0; + + const tr = this.transform, + startZoom = this.getZoom(), + startBearing = this.getBearing(), + startPitch = this.getPitch(), + startPadding = this.getPadding(), + + zoom = 'zoom' in options ? +options.zoom : startZoom, + bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, + pitch = 'pitch' in options ? +options.pitch : startPitch, + padding = 'padding' in options ? options.padding : tr.padding; + + const offsetAsPoint = Point.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const center = LngLat.convert(options.center || locationAtOffset); + this._normalizeCenter(center); + + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + const finalScale = tr.zoomScale(zoom - startZoom); + + let around, aroundPoint; + + if (options.around) { + around = LngLat.convert(options.around); + aroundPoint = tr.locationPoint(around); + } + + const currently = { + moving: this._moving, + zooming: this._zooming, + rotating: this._rotating, + pitching: this._pitching + }; + + this._zooming = this._zooming || (zoom !== startZoom); + this._rotating = this._rotating || (startBearing !== bearing); + this._pitching = this._pitching || (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + + this._easeId = options.easeId; + this._prepareEase(eventData, options.noMoveStart, currently); + + this._ease((k) => { + if (this._zooming) { + tr.zoom = interpolate(startZoom, zoom, k); + } + if (this._rotating) { + tr.bearing = interpolate(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = interpolate(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continously, + // thus we need to recalculate offsetPoint every fra,e + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + + if (around) { + tr.setLocationAtPoint(around, aroundPoint); + } else { + const scale = tr.zoomScale(tr.zoom - startZoom); + const base = zoom > startZoom ? + Math.min(2, finalScale) : + Math.max(0.5, finalScale); + const speedup = Math.pow(base, 1 - k); + const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + } + + this._fireMoveEvents(eventData); + + }, (interruptingEaseId?: string) => { + this._afterEase(eventData, interruptingEaseId); + }, options); + + return this; + } + + _prepareEase(eventData?: Object, noMoveStart: boolean, currently: Object = {}) { + this._moving = true; + + if (!noMoveStart && !currently.moving) { + this.fire(new Event('movestart', eventData)); + } + if (this._zooming && !currently.zooming) { + this.fire(new Event('zoomstart', eventData)); + } + if (this._rotating && !currently.rotating) { + this.fire(new Event('rotatestart', eventData)); + } + if (this._pitching && !currently.pitching) { + this.fire(new Event('pitchstart', eventData)); + } + } + + _fireMoveEvents(eventData?: Object) { + this.fire(new Event('move', eventData)); + if (this._zooming) { + this.fire(new Event('zoom', eventData)); + } + if (this._rotating) { + this.fire(new Event('rotate', eventData)); + } + if (this._pitching) { + this.fire(new Event('pitch', eventData)); + } + } + + _afterEase(eventData?: Object, easeId?: string) { + // if this easing is being stopped to start another easing with + // the same id then don't fire any events to avoid extra start/stop events + if (this._easeId && easeId && this._easeId === easeId) { + return; + } + delete this._easeId; + + const wasZooming = this._zooming; + const wasRotating = this._rotating; + const wasPitching = this._pitching; + this._moving = false; + this._zooming = false; + this._rotating = false; + this._pitching = false; + this._padding = false; + + if (wasZooming) { + this.fire(new Event('zoomend', eventData)); + } + if (wasRotating) { + this.fire(new Event('rotateend', eventData)); + } + if (wasPitching) { + this.fire(new Event('pitchend', eventData)); + } + this.fire(new Event('moveend', eventData)); + } + + /** + * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that + * evokes flight. The animation seamlessly incorporates zooming and panning to help + * the user maintain her bearings even after traversing a great distance. + * + * Note: The animation will be skipped, and this will behave equivalently to `jumpTo` + * if the user has the `reduced motion` accesibility feature enabled in their operating system, + * unless 'options' includes `essential: true`. + * + * @memberof Map# + * @param {Object} options Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions}, {@link AnimationOptions}, + * and the following additional options. + * @param {number} [options.curve=1.42] The zooming "curve" that will occur along the + * flight path. A high value maximizes zooming for an exaggerated animation, while a low + * value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average + * value selected by participants in the user study discussed in + * [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of + * `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A + * value of 1 would produce a circular motion. + * @param {number} [options.minZoom] The zero-based zoom level at the peak of the flight path. If + * `options.curve` is specified, this option is ignored. + * @param {number} [options.speed=1.2] The average speed of the animation defined in relation to + * `options.curve`. A speed of 1.2 means that the map appears to move along the flight path + * by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span. + * It does not correspond to a fixed physical distance, but varies by zoom level. + * @param {number} [options.screenSpeed] The average speed of the animation measured in screenfuls + * per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored. + * @param {number} [options.maxDuration] The animation's maximum duration, measured in milliseconds. + * If duration exceeds maximum duration, it resets to 0. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires pitchstart + * @fires move + * @fires zoom + * @fires rotate + * @fires pitch + * @fires moveend + * @fires zoomend + * @fires pitchend + * @returns {Map} `this` + * @example + * // fly with default options to null island + * map.flyTo({center: [0, 0], zoom: 9}); + * // using flyTo options + * map.flyTo({ + * center: [0, 0], + * zoom: 9, + * speed: 0.2, + * curve: 1, + * easing(t) { + * return t; + * } + * }); + * @see [Fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto/) + * @see [Slowly fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto-options/) + * @see [Fly to a location based on scroll position](https://www.mapbox.com/mapbox-gl-js/example/scroll-fly-to/) + */ + flyTo(options: Object, eventData?: Object) { + // Fall through to jumpTo if user has set prefers-reduced-motion + if (!options.essential && browser.prefersReducedMotion) { + const coercedOptions = (pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']): CameraOptions); + return this.jumpTo(coercedOptions, eventData); + } + + // This method implements an “optimal path” animation, as detailed in: + // + // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS + // ’03. pp. 15–22. . + // + // Where applicable, local variable documentation begins with the associated variable or + // function in van Wijk (2003). + + this.stop(); + + options = extend({ + offset: [0, 0], + speed: 1.2, + curve: 1.42, + easing: defaultEasing + }, options); + + const tr = this.transform, + startZoom = this.getZoom(), + startBearing = this.getBearing(), + startPitch = this.getPitch(), + startPadding = this.getPadding(); + + const zoom = 'zoom' in options ? clamp(+options.zoom, tr.minZoom, tr.maxZoom) : startZoom; + const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing; + const pitch = 'pitch' in options ? +options.pitch : startPitch; + const padding = 'padding' in options ? options.padding : tr.padding; + + const scale = tr.zoomScale(zoom - startZoom); + const offsetAsPoint = Point.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const center = LngLat.convert(options.center || locationAtOffset); + this._normalizeCenter(center); + + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + + let rho = options.curve; + + // w₀: Initial visible span, measured in pixels at the initial scale. + const w0 = Math.max(tr.width, tr.height), + // w₁: Final visible span, measured in pixels with respect to the initial scale. + w1 = w0 / scale, + // Length of the flight path as projected onto the ground plane, measured in pixels from + // the world image origin at the initial scale. + u1 = delta.mag(); + + if ('minZoom' in options) { + const minZoom = clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom); + // wm: Maximum visible span, measured in pixels with respect to the initial + // scale. + const wMax = w0 / tr.zoomScale(minZoom - startZoom); + rho = Math.sqrt(wMax / u1 * 2); + } + + // ρ² + const rho2 = rho * rho; + + /** + * rᵢ: Returns the zoom-out factor at one end of the animation. + * + * @param i 0 for the ascent or 1 for the descent. + * @private + */ + function r(i) { + const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1); + return Math.log(Math.sqrt(b * b + 1) - b); + } + + function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } + function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } + function tanh(n) { return sinh(n) / cosh(n); } + + // r₀: Zoom-out factor during ascent. + const r0 = r(0); + + // w(s): Returns the visible span on the ground, measured in pixels with respect to the + // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°. + let w: (_: number) => number = function (s) { + return (cosh(r0) / cosh(r0 + rho * s)); + }; + + // u(s): Returns the distance along the flight path as projected onto the ground plane, + // measured in pixels from the world image origin at the initial scale. + let u: (_: number) => number = function (s) { + return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1; + }; + + // S: Total length of the flight path, measured in ρ-screenfuls. + let S = (r(1) - r0) / rho; + + // When u₀ = u₁, the optimal path doesn’t require both ascent and descent. + if (Math.abs(u1) < 0.000001 || !isFinite(S)) { + // Perform a more or less instantaneous transition if the path is too short. + if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(options, eventData); + + const k = w1 < w0 ? -1 : 1; + S = Math.abs(Math.log(w1 / w0)) / rho; + + u = function() { return 0; }; + w = function(s) { return Math.exp(k * rho * s); }; + } + + if ('duration' in options) { + options.duration = +options.duration; + } else { + const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed; + options.duration = 1000 * S / V; + } + + if (options.maxDuration && options.duration > options.maxDuration) { + options.duration = 0; + } + + this._zooming = true; + this._rotating = (startBearing !== bearing); + this._pitching = (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + + this._prepareEase(eventData, false); + + this._ease((k) => { + // s: The distance traveled along the flight path, measured in ρ-screenfuls. + const s = k * S; + const scale = 1 / w(s); + tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale); + + if (this._rotating) { + tr.bearing = interpolate(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = interpolate(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + + const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + + this._fireMoveEvents(eventData); + + }, () => this._afterEase(eventData), options); + + return this; + } + + isEasing() { + return !!this._easeFrameId; + } + + /** + * Stops any animated transition underway. + * + * @memberof Map# + * @returns {Map} `this` + */ + stop(): this { + return this._stop(); + } + + _stop(allowGestures?: boolean, easeId?: string): this { + if (this._easeFrameId) { + this._cancelRenderFrame(this._easeFrameId); + delete this._easeFrameId; + delete this._onEaseFrame; + } + + if (this._onEaseEnd) { + // The _onEaseEnd function might emit events which trigger new + // animation, which sets a new _onEaseEnd. Ensure we don't delete + // it unintentionally. + const onEaseEnd = this._onEaseEnd; + delete this._onEaseEnd; + onEaseEnd.call(this, easeId); + } + if (!allowGestures) { + const handlers = (this: any).handlers; + if (handlers) handlers.stop(false); + } + return this; + } + + _ease(frame: (_: number) => void, + finish: () => void, + options: {animate: boolean, duration: number, easing: (_: number) => number}) { + if (options.animate === false || options.duration === 0) { + frame(1); + finish(); + } else { + this._easeStart = browser.now(); + this._easeOptions = options; + this._onEaseFrame = frame; + this._onEaseEnd = finish; + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + } + + // Callback for map._requestRenderFrame + _renderFrameCallback() { + const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1); + this._onEaseFrame(this._easeOptions.easing(t)); + if (t < 1) { + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } else { + this.stop(); + } + } + + // convert bearing so that it's numerically close to the current one so that it interpolates properly + _normalizeBearing(bearing: number, currentBearing: number) { + bearing = wrap(bearing, -180, 180); + const diff = Math.abs(bearing - currentBearing); + if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360; + if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360; + return bearing; + } + + // If a path crossing the antimeridian would be shorter, extend the final coordinate so that + // interpolating between the two endpoints will cross it. + _normalizeCenter(center: LngLat) { + const tr = this.transform; + if (!tr.renderWorldCopies || tr.lngRange) return; + + const delta = center.lng - tr.center.lng; + center.lng += + delta > 180 ? -360 : + delta < -180 ? 360 : 0; + } +} + +// In debug builds, check that camera change events are fired in the correct order. +// - ___start events needs to be fired before ___ and ___end events +// - another ___start event can't be fired before a ___end event has been fired for the previous one +function addAssertions(camera: Camera) { //eslint-disable-line + Debug.run(() => { + const inProgress = {}; + + ['drag', 'zoom', 'rotate', 'pitch', 'move'].forEach(name => { + inProgress[name] = false; + + camera.on(`${name}start`, () => { + assert(!inProgress[name], `"${name}start" fired twice without a "${name}end"`); + inProgress[name] = true; + assert(inProgress.move); + }); + + camera.on(name, () => { + assert(inProgress[name]); + assert(inProgress.move); + }); + + camera.on(`${name}end`, () => { + assert(inProgress.move); + assert(inProgress[name]); + inProgress[name] = false; + }); + }); + + // Canary used to test whether this function is stripped in prod build + canary = 'canary debug run'; + }); +} + +let canary; //eslint-disable-line + +export default Camera; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/control/attribution_control.js b/node_modules/@plotly/mapbox-gl/src/ui/control/attribution_control.js new file mode 100644 index 0000000000000000000000000000000000000000..21b6a289a718823863e5b5c967bb4fcdc03178a7 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/control/attribution_control.js @@ -0,0 +1,212 @@ +// @flow + +import DOM from '../../util/dom'; +import {bindAll} from '../../util/util'; +import config from '../../util/config'; + +import type Map from '../map'; + +type Options = { + compact?: boolean, + customAttribution?: string | Array +}; + +/** + * An `AttributionControl` control presents the map's [attribution information](https://docs.mapbox.com/help/how-mapbox-works/attribution/). + * + * @implements {IControl} + * @param {Object} [options] + * @param {boolean} [options.compact] If `true`, force a compact attribution that shows the full attribution on mouse hover. If `false`, force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide. **Attribution should not be collapsed if it can comfortably fit on the map. `compact` should only be used to modify default attribution when map size makes it impossible to fit [default attribution](https://docs.mapbox.com/help/how-mapbox-works/attribution/) and when the automatic compact resizing for default settings are not sufficient.** + * @param {string | Array} [options.customAttribution] String or strings to show in addition to any other attributions. + * @example + * var map = new mapboxgl.Map({attributionControl: false}) + * .addControl(new mapboxgl.AttributionControl({ + * compact: true + * })); + */ +class AttributionControl { + options: Options; + _map: Map; + _container: HTMLElement; + _innerContainer: HTMLElement; + _compactButton: HTMLButtonElement; + _editLink: ?HTMLAnchorElement; + _attribHTML: string; + styleId: string; + styleOwner: string; + + constructor(options: Options = {}) { + this.options = options; + + bindAll([ + '_toggleAttribution', + '_updateEditLink', + '_updateData', + '_updateCompact' + ], this); + } + + getDefaultPosition() { + return 'bottom-right'; + } + + onAdd(map: Map) { + const compact = this.options && this.options.compact; + + this._map = map; + this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-attrib'); + this._compactButton = DOM.create('button', 'mapboxgl-ctrl-attrib-button', this._container); + this._compactButton.addEventListener('click', this._toggleAttribution); + this._setElementTitle(this._compactButton, 'ToggleAttribution'); + this._innerContainer = DOM.create('div', 'mapboxgl-ctrl-attrib-inner', this._container); + this._innerContainer.setAttribute('role', 'list'); + + if (compact) { + this._container.classList.add('mapboxgl-compact'); + } + + this._updateAttributions(); + this._updateEditLink(); + + this._map.on('styledata', this._updateData); + this._map.on('sourcedata', this._updateData); + this._map.on('moveend', this._updateEditLink); + + if (compact === undefined) { + this._map.on('resize', this._updateCompact); + this._updateCompact(); + } + + return this._container; + } + + onRemove() { + DOM.remove(this._container); + + this._map.off('styledata', this._updateData); + this._map.off('sourcedata', this._updateData); + this._map.off('moveend', this._updateEditLink); + this._map.off('resize', this._updateCompact); + + this._map = (undefined: any); + this._attribHTML = (undefined: any); + } + + _setElementTitle(element: HTMLElement, title: string) { + const str = this._map._getUIString(`AttributionControl.${title}`); + element.title = str; + element.setAttribute('aria-label', str); + } + + _toggleAttribution() { + if (this._container.classList.contains('mapboxgl-compact-show')) { + this._container.classList.remove('mapboxgl-compact-show'); + this._compactButton.setAttribute('aria-pressed', 'false'); + } else { + this._container.classList.add('mapboxgl-compact-show'); + this._compactButton.setAttribute('aria-pressed', 'true'); + } + } + + _updateEditLink() { + let editLink = this._editLink; + if (!editLink) { + editLink = this._editLink = (this._container.querySelector('.mapbox-improve-map'): any); + } + + const params = [ + {key: 'owner', value: this.styleOwner}, + {key: 'id', value: this.styleId}, + {key: 'access_token', value: this._map._requestManager._customAccessToken || config.ACCESS_TOKEN} + ]; + + if (editLink) { + const paramString = params.reduce((acc, next, i) => { + if (next.value) { + acc += `${next.key}=${next.value}${i < params.length - 1 ? '&' : ''}`; + } + return acc; + }, `?`); + editLink.href = `${config.FEEDBACK_URL}/${paramString}${this._map._hash ? this._map._hash.getHashString(true) : ''}`; + editLink.rel = 'noopener nofollow'; + this._setElementTitle(editLink, 'MapFeedback'); + } + } + + _updateData(e: any) { + if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style')) { + this._updateAttributions(); + this._updateEditLink(); + } + } + + _updateAttributions() { + if (!this._map.style) return; + let attributions: Array = []; + if (this.options.customAttribution) { + if (Array.isArray(this.options.customAttribution)) { + attributions = attributions.concat( + this.options.customAttribution.map(attribution => { + if (typeof attribution !== 'string') return ''; + return attribution; + }) + ); + } else if (typeof this.options.customAttribution === 'string') { + attributions.push(this.options.customAttribution); + } + } + + if (this._map.style.stylesheet) { + const stylesheet: any = this._map.style.stylesheet; + this.styleOwner = stylesheet.owner; + this.styleId = stylesheet.id; + } + + const sourceCaches = this._map.style.sourceCaches; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used) { + const source = sourceCache.getSource(); + if (source.attribution && attributions.indexOf(source.attribution) < 0) { + attributions.push(source.attribution); + } + } + } + + // remove any entries that are substrings of another entry. + // first sort by length so that substrings come first + attributions.sort((a, b) => a.length - b.length); + attributions = attributions.filter((attrib, i) => { + for (let j = i + 1; j < attributions.length; j++) { + if (attributions[j].indexOf(attrib) >= 0) { return false; } + } + return true; + }); + + // check if attribution string is different to minimize DOM changes + const attribHTML = attributions.join(' | '); + if (attribHTML === this._attribHTML) return; + + this._attribHTML = attribHTML; + + if (attributions.length) { + this._innerContainer.innerHTML = attribHTML; + this._container.classList.remove('mapboxgl-attrib-empty'); + } else { + this._container.classList.add('mapboxgl-attrib-empty'); + } + // remove old DOM node from _editLink + this._editLink = null; + } + + _updateCompact() { + if (this._map.getCanvasContainer().offsetWidth <= 640) { + this._container.classList.add('mapboxgl-compact'); + } else { + this._container.classList.remove('mapboxgl-compact', 'mapboxgl-compact-show'); + } + } + +} + +export default AttributionControl; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/control/fullscreen_control.js b/node_modules/@plotly/mapbox-gl/src/ui/control/fullscreen_control.js new file mode 100644 index 0000000000000000000000000000000000000000..e7006d5d871653e2f42e9c09e7acf143675d738d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/control/fullscreen_control.js @@ -0,0 +1,147 @@ +// @flow + +import DOM from '../../util/dom'; + +import {bindAll, warnOnce} from '../../util/util'; +import window from '../../util/window'; + +import type Map from '../map'; + +type Options = { + container?: HTMLElement +}; + +/** + * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode. + * + * @implements {IControl} + * @param {Object} [options] + * @param {HTMLElement} [options.container] `container` is the [compatible DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen#Compatible_elements) which should be made full screen. By default, the map container element will be made full screen. + * + * @example + * map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')})); + * @see [View a fullscreen map](https://www.mapbox.com/mapbox-gl-js/example/fullscreen/) + */ + +class FullscreenControl { + _map: Map; + _controlContainer: HTMLElement; + _fullscreen: boolean; + _fullscreenchange: string; + _fullscreenButton: HTMLElement; + _container: HTMLElement; + + constructor(options: Options) { + this._fullscreen = false; + if (options && options.container) { + if (options.container instanceof window.HTMLElement) { + this._container = options.container; + } else { + warnOnce('Full screen control \'container\' must be a DOM element.'); + } + } + bindAll([ + '_onClickFullscreen', + '_changeIcon' + ], this); + if ('onfullscreenchange' in window.document) { + this._fullscreenchange = 'fullscreenchange'; + } else if ('onmozfullscreenchange' in window.document) { + this._fullscreenchange = 'mozfullscreenchange'; + } else if ('onwebkitfullscreenchange' in window.document) { + this._fullscreenchange = 'webkitfullscreenchange'; + } else if ('onmsfullscreenchange' in window.document) { + this._fullscreenchange = 'MSFullscreenChange'; + } + } + + onAdd(map: Map) { + this._map = map; + if (!this._container) this._container = this._map.getContainer(); + this._controlContainer = DOM.create('div', `mapboxgl-ctrl mapboxgl-ctrl-group`); + if (this._checkFullscreenSupport()) { + this._setupUI(); + } else { + this._controlContainer.style.display = 'none'; + warnOnce('This device does not support fullscreen mode.'); + } + return this._controlContainer; + } + + onRemove() { + DOM.remove(this._controlContainer); + this._map = (null: any); + window.document.removeEventListener(this._fullscreenchange, this._changeIcon); + } + + _checkFullscreenSupport() { + return !!( + window.document.fullscreenEnabled || + (window.document: any).mozFullScreenEnabled || + (window.document: any).msFullscreenEnabled || + (window.document: any).webkitFullscreenEnabled + ); + } + + _setupUI() { + const button = this._fullscreenButton = DOM.create('button', (`mapboxgl-ctrl-fullscreen`), this._controlContainer); + DOM.create('span', `mapboxgl-ctrl-icon`, button).setAttribute('aria-hidden', true); + button.type = 'button'; + this._updateTitle(); + this._fullscreenButton.addEventListener('click', this._onClickFullscreen); + window.document.addEventListener(this._fullscreenchange, this._changeIcon); + } + + _updateTitle() { + const title = this._getTitle(); + this._fullscreenButton.setAttribute("aria-label", title); + this._fullscreenButton.title = title; + } + + _getTitle() { + return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter'); + } + + _isFullscreen() { + return this._fullscreen; + } + + _changeIcon() { + const fullscreenElement = + window.document.fullscreenElement || + (window.document: any).mozFullScreenElement || + (window.document: any).webkitFullscreenElement || + (window.document: any).msFullscreenElement; + + if ((fullscreenElement === this._container) !== this._fullscreen) { + this._fullscreen = !this._fullscreen; + this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-shrink`); + this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-fullscreen`); + this._updateTitle(); + } + } + + _onClickFullscreen() { + if (this._isFullscreen()) { + if (window.document.exitFullscreen) { + (window.document: any).exitFullscreen(); + } else if (window.document.mozCancelFullScreen) { + (window.document: any).mozCancelFullScreen(); + } else if (window.document.msExitFullscreen) { + (window.document: any).msExitFullscreen(); + } else if (window.document.webkitCancelFullScreen) { + (window.document: any).webkitCancelFullScreen(); + } + } else if (this._container.requestFullscreen) { + this._container.requestFullscreen(); + } else if ((this._container: any).mozRequestFullScreen) { + (this._container: any).mozRequestFullScreen(); + } else if ((this._container: any).msRequestFullscreen) { + (this._container: any).msRequestFullscreen(); + } else if ((this._container: any).webkitRequestFullscreen) { + (this._container: any).webkitRequestFullscreen(); + } + } +} + +export default FullscreenControl; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/control/geolocate_control.js b/node_modules/@plotly/mapbox-gl/src/ui/control/geolocate_control.js new file mode 100644 index 0000000000000000000000000000000000000000..fd30719c1b822dd100f3c0e966596ac3e1a64693 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/control/geolocate_control.js @@ -0,0 +1,707 @@ +// @flow + +import {Event, Evented} from '../../util/evented'; +import DOM from '../../util/dom'; +import window from '../../util/window'; +import {extend, bindAll, warnOnce} from '../../util/util'; +import assert from 'assert'; +import LngLat from '../../geo/lng_lat'; +import Marker from '../marker'; + +import type Map from '../map'; +import type {AnimationOptions, CameraOptions} from '../camera'; + +type Options = { + positionOptions?: PositionOptions, + fitBoundsOptions?: AnimationOptions & CameraOptions, + trackUserLocation?: boolean, + showAccuracyCircle?: boolean, + showUserLocation?: boolean +}; + +const defaultOptions: Options = { + positionOptions: { + enableHighAccuracy: false, + maximumAge: 0, + timeout: 6000 /* 6 sec */ + }, + fitBoundsOptions: { + maxZoom: 15 + }, + trackUserLocation: false, + showAccuracyCircle: true, + showUserLocation: true +}; + +let supportsGeolocation; + +function checkGeolocationSupport(callback) { + if (supportsGeolocation !== undefined) { + callback(supportsGeolocation); + + } else if (window.navigator.permissions !== undefined) { + // navigator.permissions has incomplete browser support + // http://caniuse.com/#feat=permissions-api + // Test for the case where a browser disables Geolocation because of an + // insecure origin + window.navigator.permissions.query({name: 'geolocation'}).then((p) => { + supportsGeolocation = p.state !== 'denied'; + callback(supportsGeolocation); + }); + + } else { + supportsGeolocation = !!window.navigator.geolocation; + callback(supportsGeolocation); + } +} + +let numberOfWatches = 0; +let noTimeout = false; + +/** + * A `GeolocateControl` control provides a button that uses the browser's geolocation + * API to locate the user on the map. + * + * Not all browsers support geolocation, + * and some users may disable the feature. Geolocation support for modern + * browsers including Chrome requires sites to be served over HTTPS. If + * geolocation support is not available, the GeolocateControl will show + * as disabled. + * + * The zoom level applied will depend on the accuracy of the geolocation provided by the device. + * + * The GeolocateControl has two modes. If `trackUserLocation` is `false` (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If `trackUserLocation` is `true` the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the GeolocateControl has three interaction states: + * * active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center. Initial state and upon clicking the `GeolocateControl` button. + * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement. + * * disabled - occurs if Geolocation is not available, disabled or denied. + * + * These interaction states can't be controlled programmatically, rather they are set based on user interactions. + * + * @implements {IControl} + * @param {Object} [options] + * @param {Object} [options.positionOptions={enableHighAccuracy: false, timeout: 6000}] A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object. + * @param {Object} [options.fitBoundsOptions={maxZoom: 15}] A {@link Map#fitBounds} options object to use when the map is panned and zoomed to the user's location. The default is to use a `maxZoom` of 15 to limit how far the map will zoom in for very accurate locations. + * @param {Object} [options.trackUserLocation=false] If `true` the Geolocate Control becomes a toggle button and when active the map will receive updates to the user's location as it changes. + * @param {Object} [options.showAccuracyCircle=true] By default, if showUserLocation is `true`, a transparent circle will be drawn around the user location indicating the accuracy (95% confidence level) of the user's location. Set to `false` to disable. Always disabled when showUserLocation is `false`. + * @param {Object} [options.showUserLocation=true] By default a dot will be shown on the map at the user's location. Set to `false` to disable. + * + * @example + * map.addControl(new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * })); + * @see [Locate the user](https://www.mapbox.com/mapbox-gl-js/example/locate-user/) + */ +class GeolocateControl extends Evented { + _map: Map; + options: Options; + _container: HTMLElement; + _dotElement: HTMLElement; + _circleElement: HTMLElement; + _geolocateButton: HTMLButtonElement; + _geolocationWatchID: number; + _timeoutId: ?TimeoutID; + _watchState: 'OFF' | 'ACTIVE_LOCK' | 'WAITING_ACTIVE' | 'ACTIVE_ERROR' | 'BACKGROUND' | 'BACKGROUND_ERROR'; + _lastKnownPosition: any; + _userLocationDotMarker: Marker; + _accuracyCircleMarker: Marker; + _accuracy: number; + _setup: boolean; // set to true once the control has been setup + + constructor(options: Options) { + super(); + this.options = extend({}, defaultOptions, options); + + bindAll([ + '_onSuccess', + '_onError', + '_onZoom', + '_finish', + '_setupUI', + '_updateCamera', + '_updateMarker' + ], this); + } + + onAdd(map: Map) { + this._map = map; + this._container = DOM.create('div', `mapboxgl-ctrl mapboxgl-ctrl-group`); + checkGeolocationSupport(this._setupUI); + return this._container; + } + + onRemove() { + // clear the geolocation watch if exists + if (this._geolocationWatchID !== undefined) { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = (undefined: any); + } + + // clear the markers from the map + if (this.options.showUserLocation && this._userLocationDotMarker) { + this._userLocationDotMarker.remove(); + } + if (this.options.showAccuracyCircle && this._accuracyCircleMarker) { + this._accuracyCircleMarker.remove(); + } + + DOM.remove(this._container); + this._map.off('zoom', this._onZoom); + this._map = (undefined: any); + numberOfWatches = 0; + noTimeout = false; + } + + /** + * Check if the Geolocation API Position is outside the map's maxbounds. + * + * @param {Position} position the Geolocation API Position + * @returns {boolean} Returns `true` if position is outside the map's maxbounds, otherwise returns `false`. + * @private + */ + _isOutOfMapMaxBounds(position: Position) { + const bounds = this._map.getMaxBounds(); + const coordinates = position.coords; + + return bounds && ( + coordinates.longitude < bounds.getWest() || + coordinates.longitude > bounds.getEast() || + coordinates.latitude < bounds.getSouth() || + coordinates.latitude > bounds.getNorth() + ); + } + + _setErrorState() { + 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'); + // turn marker grey + 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'); + // turn marker grey + break; + case 'ACTIVE_ERROR': + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + } + + /** + * When the Geolocation API returns a new location, update the GeolocateControl. + * + * @param {Position} position the Geolocation API Position + * @private + */ + _onSuccess(position: Position) { + if (!this._map) { + // control has since been removed + return; + } + + if (this._isOutOfMapMaxBounds(position)) { + this._setErrorState(); + + this.fire(new Event('outofmaxbounds', position)); + this._updateMarker(); + this._finish(); + + return; + } + + if (this.options.trackUserLocation) { + // keep a record of the position so that if the state is BACKGROUND and the user + // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for + // watchPosition to trigger _onSuccess + this._lastKnownPosition = position; + + switch (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'); + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + } + + // if showUserLocation and the watch state isn't off then update the marker location + if (this.options.showUserLocation && this._watchState !== 'OFF') { + this._updateMarker(position); + } + + // if in normal mode (not watch mode), or if in watch mode and the state is active watch + // then update the camera + if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') { + this._updateCamera(position); + } + + if (this.options.showUserLocation) { + this._dotElement.classList.remove('mapboxgl-user-location-dot-stale'); + } + + this.fire(new Event('geolocate', position)); + this._finish(); + } + + /** + * Update the camera location to center on the current position + * + * @param {Position} position the Geolocation API Position + * @private + */ + _updateCamera(position: Position) { + const center = new LngLat(position.coords.longitude, position.coords.latitude); + const radius = position.coords.accuracy; + const bearing = this._map.getBearing(); + const options = extend({bearing}, this.options.fitBoundsOptions); + + this._map.fitBounds(center.toBounds(radius), options, { + geolocateSource: true // tag this camera change so it won't cause the control to change to background state + }); + } + + /** + * Update the user location dot Marker to the current position + * + * @param {Position} [position] the Geolocation API Position + * @private + */ + _updateMarker(position: ?Position) { + if (position) { + const center = new LngLat(position.coords.longitude, position.coords.latitude); + this._accuracyCircleMarker.setLngLat(center).addTo(this._map); + this._userLocationDotMarker.setLngLat(center).addTo(this._map); + this._accuracy = position.coords.accuracy; + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + } else { + this._userLocationDotMarker.remove(); + this._accuracyCircleMarker.remove(); + } + } + + _updateCircleRadius() { + assert(this._circleElement); + const y = this._map._container.clientHeight / 2; + const a = this._map.unproject([0, y]); + const b = this._map.unproject([1, y]); + const metersPerPixel = a.distanceTo(b); + const circleDiameter = Math.ceil(2.0 * this._accuracy / metersPerPixel); + this._circleElement.style.width = `${circleDiameter}px`; + this._circleElement.style.height = `${circleDiameter}px`; + } + + _onZoom() { + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + } + + _onError(error: PositionError) { + if (!this._map) { + // control has since been removed + return; + } + + if (this.options.trackUserLocation) { + if (error.code === 1) { + // PERMISSION_DENIED + 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._geolocateButton.disabled = true; + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + + if (this._geolocationWatchID !== undefined) { + this._clearWatch(); + } + } else if (error.code === 3 && noTimeout) { + // this represents a forced error state + // this was triggered to force immediate geolocation when a watch is already present + // see https://github.com/mapbox/mapbox-gl-js/issues/8214 + // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position + return; + } else { + this._setErrorState(); + } + } + + if (this._watchState !== 'OFF' && this.options.showUserLocation) { + this._dotElement.classList.add('mapboxgl-user-location-dot-stale'); + } + + this.fire(new Event('error', error)); + + this._finish(); + } + + _finish() { + if (this._timeoutId) { clearTimeout(this._timeoutId); } + this._timeoutId = undefined; + } + + _setupUI(supported: boolean) { + this._container.addEventListener('contextmenu', (e: MouseEvent) => e.preventDefault()); + this._geolocateButton = DOM.create('button', `mapboxgl-ctrl-geolocate`, this._container); + DOM.create('span', `mapboxgl-ctrl-icon`, this._geolocateButton).setAttribute('aria-hidden', true); + this._geolocateButton.type = 'button'; + + if (supported === false) { + warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.'); + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.disabled = true; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } else { + const title = this._map._getUIString('GeolocateControl.FindMyLocation'); + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + + if (this.options.trackUserLocation) { + this._geolocateButton.setAttribute('aria-pressed', 'false'); + this._watchState = 'OFF'; + } + + // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map + if (this.options.showUserLocation) { + this._dotElement = DOM.create('div', 'mapboxgl-user-location-dot'); + + this._userLocationDotMarker = new Marker(this._dotElement); + + this._circleElement = DOM.create('div', 'mapboxgl-user-location-accuracy-circle'); + this._accuracyCircleMarker = new Marker({element: this._circleElement, pitchAlignment: 'map'}); + + if (this.options.trackUserLocation) this._watchState = 'OFF'; + + this._map.on('zoom', this._onZoom); + } + + this._geolocateButton.addEventListener('click', + this.trigger.bind(this)); + + this._setup = true; + + // when the camera is changed (and it's not as a result of the Geolocation Control) change + // the watch mode to background watch, so that the marker is updated but not the camera. + if (this.options.trackUserLocation) { + this._map.on('movestart', (event) => { + const fromResize = event.originalEvent && event.originalEvent.type === 'resize'; + if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) { + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'); + + this.fire(new Event('trackuserlocationend')); + } + }); + } + } + + /** + * Programmatically request and move the map to the user's location. + * + * @returns {boolean} Returns `false` if called before control was added to a map, otherwise returns `true`. + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * map.on('load', function() { + * geolocate.trigger(); + * }); + */ + trigger() { + if (!this._setup) { + warnOnce('Geolocate control triggered before added to a map'); + return false; + } + if (this.options.trackUserLocation) { + // update watchState and do any outgoing state cleanup + switch (this._watchState) { + case 'OFF': + // turn on the Geolocate Control + this._watchState = 'WAITING_ACTIVE'; + + this.fire(new Event('trackuserlocationstart')); + break; + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + case 'BACKGROUND_ERROR': + // turn off the Geolocate Control + numberOfWatches--; + noTimeout = false; + 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(new Event('trackuserlocationend')); + break; + case 'BACKGROUND': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'); + // set camera to last known location + if (this._lastKnownPosition) this._updateCamera(this._lastKnownPosition); + + this.fire(new Event('trackuserlocationstart')); + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + + // incoming state setup + 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'); + break; + case 'OFF': + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + + // manage geolocation.watchPosition / geolocation.clearWatch + if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) { + // clear watchPosition as we've changed to an OFF state + this._clearWatch(); + } else if (this._geolocationWatchID === undefined) { + // enable watchPosition since watchState is not OFF and there is no watchPosition already running + + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'true'); + + numberOfWatches++; + let positionOptions; + if (numberOfWatches > 1) { + positionOptions = {maximumAge:600000, timeout:0}; + noTimeout = true; + } else { + positionOptions = this.options.positionOptions; + noTimeout = false; + } + + this._geolocationWatchID = window.navigator.geolocation.watchPosition( + this._onSuccess, this._onError, positionOptions); + } + } else { + window.navigator.geolocation.getCurrentPosition( + this._onSuccess, this._onError, this.options.positionOptions); + + // This timeout ensures that we still call finish() even if + // the user declines to share their location in Firefox + this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */); + } + + return true; + } + + _clearWatch() { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + + this._geolocationWatchID = (undefined: any); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'false'); + + if (this.options.showUserLocation) { + this._updateMarker(null); + } + } +} + +export default GeolocateControl; + +/* Geolocate Control Watch States + * This is the private state of the control. + * + * OFF + * off/inactive + * WAITING_ACTIVE + * Geolocate Control was clicked but still waiting for Geolocation API response with user location + * ACTIVE_LOCK + * Showing the user location as a dot AND tracking the camera to be fixed to their location. If their location changes the map moves to follow. + * ACTIVE_ERROR + * There was en error from the Geolocation API while trying to show and track the user location. + * BACKGROUND + * Showing the user location as a dot but the camera doesn't follow their location as it changes. + * BACKGROUND_ERROR + * There was an error from the Geolocation API while trying to show (but not track) the user location. + */ + +/** + * Fired on each Geolocation API position update which returned as success. + * + * @event geolocate + * @memberof GeolocateControl + * @instance + * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a geolocate event occurs. + * geolocate.on('geolocate', function() { + * console.log('A geolocate event has occurred.') + * }); + * + */ + +/** + * Fired on each Geolocation API position update which returned as an error. + * + * @event error + * @memberof GeolocateControl + * @instance + * @property {PositionError} data The returned [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/PositionError) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an error event occurs. + * geolocate.on('error', function() { + * console.log('An error event has occurred.') + * }); + * + */ + +/** + * Fired on each Geolocation API position update which returned as success but user position is out of map maxBounds. + * + * @event outofmaxbounds + * @memberof GeolocateControl + * @instance + * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an outofmaxbounds event occurs. + * geolocate.on('outofmaxbounds', function() { + * console.log('An outofmaxbounds event has occurred.') + * }); + * + */ + +/** + * Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users's location changes). + * + * @event trackuserlocationstart + * @memberof GeolocateControl + * @instance + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationstart event occurs. + * geolocate.on('trackuserlocationstart', function() { + * console.log('A trackuserlocationstart event has occurred.') + * }); + * + */ + +/** + * Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not. + * + * @event trackuserlocationend + * @memberof GeolocateControl + * @instance + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationend event occurs. + * geolocate.on('trackuserlocationend', function() { + * console.log('A trackuserlocationend event has occurred.') + * }); + * + */ diff --git a/node_modules/@plotly/mapbox-gl/src/ui/control/logo_control.js b/node_modules/@plotly/mapbox-gl/src/ui/control/logo_control.js new file mode 100644 index 0000000000000000000000000000000000000000..a56fdb912a12d83cfb4e8d5142af44cae0872f81 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/control/logo_control.js @@ -0,0 +1,92 @@ +// @flow + +import DOM from '../../util/dom'; + +import {bindAll} from '../../util/util'; + +import type Map from '../map'; + +/** + * A `LogoControl` is a control that adds the Mapbox watermark + * to the map as required by the [terms of service](https://www.mapbox.com/tos/) for Mapbox + * vector tiles and core styles. + * + * @implements {IControl} + * @private +**/ + +class LogoControl { + _map: Map; + _container: HTMLElement; + + constructor() { + bindAll(['_updateLogo'], this); + bindAll(['_updateCompact'], this); + } + + onAdd(map: Map) { + this._map = map; + this._container = DOM.create('div', 'mapboxgl-ctrl'); + const anchor = DOM.create('a', 'mapboxgl-ctrl-logo'); + anchor.target = "_blank"; + anchor.rel = "noopener nofollow"; + anchor.href = "https://www.mapbox.com/"; + anchor.setAttribute("aria-label", this._map._getUIString('LogoControl.Title')); + anchor.setAttribute("rel", "noopener nofollow"); + this._container.appendChild(anchor); + this._container.style.display = 'none'; + + this._map.on('sourcedata', this._updateLogo); + this._updateLogo(); + + this._map.on('resize', this._updateCompact); + this._updateCompact(); + + return this._container; + } + + onRemove() { + DOM.remove(this._container); + this._map.off('sourcedata', this._updateLogo); + this._map.off('resize', this._updateCompact); + } + + getDefaultPosition() { + return 'bottom-left'; + } + + _updateLogo(e: any) { + if (!e || e.sourceDataType === 'metadata') { + this._container.style.display = this._logoRequired() ? 'block' : 'none'; + } + } + + _logoRequired() { + if (!this._map.style) return; + + const sourceCaches = this._map.style.sourceCaches; + for (const id in sourceCaches) { + const source = sourceCaches[id].getSource(); + if (source.mapbox_logo) { + return true; + } + } + + return false; + } + + _updateCompact() { + const containerChildren = this._container.children; + if (containerChildren.length) { + const anchor = containerChildren[0]; + if (this._map.getCanvasContainer().offsetWidth < 250) { + anchor.classList.add('mapboxgl-compact'); + } else { + anchor.classList.remove('mapboxgl-compact'); + } + } + } + +} + +export default LogoControl; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/control/navigation_control.js b/node_modules/@plotly/mapbox-gl/src/ui/control/navigation_control.js new file mode 100644 index 0000000000000000000000000000000000000000..4ec8da6647bc2368f21e4a0aebebbce9fe0a8e61 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/control/navigation_control.js @@ -0,0 +1,257 @@ +// @flow + +import DOM from '../../util/dom'; +import {extend, bindAll} from '../../util/util'; +import {MouseRotateHandler, MousePitchHandler} from '../handler/mouse'; +import window from '../../util/window'; + +import type Map from '../map'; + +type Options = { + showCompass?: boolean, + showZoom?: boolean, + visualizePitch?: boolean +}; + +const defaultOptions: Options = { + showCompass: true, + showZoom: true, + visualizePitch: false +}; + +/** + * A `NavigationControl` control contains zoom buttons and a compass. + * + * @implements {IControl} + * @param {Object} [options] + * @param {Boolean} [options.showCompass=true] If `true` the compass button is included. + * @param {Boolean} [options.showZoom=true] If `true` the zoom-in and zoom-out buttons are included. + * @param {Boolean} [options.visualizePitch=false] If `true` the pitch is visualized by rotating X-axis of compass. + * @example + * var nav = new mapboxgl.NavigationControl(); + * map.addControl(nav, 'top-left'); + * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/) + * @see [Add a third party vector tile source](https://www.mapbox.com/mapbox-gl-js/example/third-party/) + */ +class NavigationControl { + _map: Map; + options: Options; + _container: HTMLElement; + _zoomInButton: HTMLButtonElement; + _zoomOutButton: HTMLButtonElement; + _compass: HTMLButtonElement; + _compassIcon: HTMLElement; + _handler: MouseRotateWrapper; + + constructor(options: Options) { + this.options = extend({}, defaultOptions, options); + + this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-group'); + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + + if (this.options.showZoom) { + bindAll([ + '_setButtonTitle', + '_updateZoomButtons' + ], this); + this._zoomInButton = this._createButton('mapboxgl-ctrl-zoom-in', (e) => this._map.zoomIn({}, {originalEvent: e})); + DOM.create('span', `mapboxgl-ctrl-icon`, this._zoomInButton).setAttribute('aria-hidden', true); + this._zoomOutButton = this._createButton('mapboxgl-ctrl-zoom-out', (e) => this._map.zoomOut({}, {originalEvent: e})); + DOM.create('span', `mapboxgl-ctrl-icon`, this._zoomOutButton).setAttribute('aria-hidden', true); + } + if (this.options.showCompass) { + bindAll([ + '_rotateCompassArrow' + ], this); + this._compass = this._createButton('mapboxgl-ctrl-compass', (e) => { + if (this.options.visualizePitch) { + this._map.resetNorthPitch({}, {originalEvent: e}); + } else { + this._map.resetNorth({}, {originalEvent: e}); + } + }); + this._compassIcon = DOM.create('span', 'mapboxgl-ctrl-icon', this._compass); + this._compassIcon.setAttribute('aria-hidden', true); + } + } + + _updateZoomButtons() { + const zoom = this._map.getZoom(); + const isMax = zoom === this._map.getMaxZoom(); + const isMin = zoom === this._map.getMinZoom(); + this._zoomInButton.disabled = isMax; + this._zoomOutButton.disabled = isMin; + this._zoomInButton.setAttribute('aria-disabled', isMax.toString()); + this._zoomOutButton.setAttribute('aria-disabled', isMin.toString()); + } + + _rotateCompassArrow() { + const rotate = this.options.visualizePitch ? + `scale(${1 / Math.pow(Math.cos(this._map.transform.pitch * (Math.PI / 180)), 0.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle * (180 / Math.PI)}deg)` : + `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`; + + this._compassIcon.style.transform = rotate; + } + + onAdd(map: Map) { + this._map = map; + if (this.options.showZoom) { + this._setButtonTitle(this._zoomInButton, 'ZoomIn'); + this._setButtonTitle(this._zoomOutButton, 'ZoomOut'); + this._map.on('zoom', this._updateZoomButtons); + this._updateZoomButtons(); + } + if (this.options.showCompass) { + this._setButtonTitle(this._compass, 'ResetBearing'); + if (this.options.visualizePitch) { + this._map.on('pitch', this._rotateCompassArrow); + } + this._map.on('rotate', this._rotateCompassArrow); + this._rotateCompassArrow(); + this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch); + } + return this._container; + } + + onRemove() { + DOM.remove(this._container); + if (this.options.showZoom) { + this._map.off('zoom', this._updateZoomButtons); + } + if (this.options.showCompass) { + if (this.options.visualizePitch) { + this._map.off('pitch', this._rotateCompassArrow); + } + this._map.off('rotate', this._rotateCompassArrow); + this._handler.off(); + delete this._handler; + } + + delete this._map; + } + + _createButton(className: string, fn: () => mixed) { + const a = DOM.create('button', className, this._container); + a.type = 'button'; + a.addEventListener('click', fn); + return a; + } + + _setButtonTitle(button: HTMLButtonElement, title: string) { + const str = this._map._getUIString(`NavigationControl.${title}`); + button.title = str; + button.setAttribute('aria-label', str); + } +} + +class MouseRotateWrapper { + + map: Map; + _clickTolerance: number; + element: HTMLElement; + mouseRotate: MouseRotateHandler; + mousePitch: MousePitchHandler; + _startPos: Point; + _lastPos: Point; + + constructor(map: Map, element: HTMLElement, pitch?: boolean = false) { + this._clickTolerance = 10; + this.element = element; + this.mouseRotate = new MouseRotateHandler({clickTolerance: map.dragRotate._mouseRotate._clickTolerance}); + this.map = map; + if (pitch) this.mousePitch = new MousePitchHandler({clickTolerance: map.dragRotate._mousePitch._clickTolerance}); + + bindAll(['mousedown', 'mousemove', 'mouseup', 'touchstart', 'touchmove', 'touchend', 'reset'], this); + DOM.addEventListener(element, 'mousedown', this.mousedown); + DOM.addEventListener(element, 'touchstart', this.touchstart, {passive: false}); + DOM.addEventListener(element, 'touchmove', this.touchmove); + DOM.addEventListener(element, 'touchend', this.touchend); + DOM.addEventListener(element, 'touchcancel', this.reset); + } + + down(e: MouseEvent, point: Point) { + this.mouseRotate.mousedown(e, point); + if (this.mousePitch) this.mousePitch.mousedown(e, point); + DOM.disableDrag(); + } + + move(e: MouseEvent, point: Point) { + const map = this.map; + const r = this.mouseRotate.mousemoveWindow(e, point); + if (r && r.bearingDelta) map.setBearing(map.getBearing() + r.bearingDelta); + if (this.mousePitch) { + const p = this.mousePitch.mousemoveWindow(e, point); + if (p && p.pitchDelta) map.setPitch(map.getPitch() + p.pitchDelta); + } + } + + off() { + const element = this.element; + DOM.removeEventListener(element, 'mousedown', this.mousedown); + DOM.removeEventListener(element, 'touchstart', this.touchstart, {passive: false}); + DOM.removeEventListener(element, 'touchmove', this.touchmove); + DOM.removeEventListener(element, 'touchend', this.touchend); + DOM.removeEventListener(element, 'touchcancel', this.reset); + this.offTemp(); + } + + offTemp() { + DOM.enableDrag(); + DOM.removeEventListener(window, 'mousemove', this.mousemove); + DOM.removeEventListener(window, 'mouseup', this.mouseup); + } + + mousedown(e: MouseEvent) { + this.down(extend({}, e, {ctrlKey: true, preventDefault: () => e.preventDefault()}), DOM.mousePos(this.element, e)); + DOM.addEventListener(window, 'mousemove', this.mousemove); + DOM.addEventListener(window, 'mouseup', this.mouseup); + } + + mousemove(e: MouseEvent) { + this.move(e, DOM.mousePos(this.element, e)); + } + + mouseup(e: MouseEvent) { + this.mouseRotate.mouseupWindow(e); + if (this.mousePitch) this.mousePitch.mouseupWindow(e); + this.offTemp(); + } + + touchstart(e: TouchEvent) { + if (e.targetTouches.length !== 1) { + this.reset(); + } else { + this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.down((({type: 'mousedown', button: 0, ctrlKey: true, preventDefault: () => e.preventDefault()}: any): MouseEvent), this._startPos); + } + } + + touchmove(e: TouchEvent) { + if (e.targetTouches.length !== 1) { + this.reset(); + } else { + this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.move((({preventDefault: () => e.preventDefault()}: any): MouseEvent), this._lastPos); + } + } + + touchend(e: TouchEvent) { + if (e.targetTouches.length === 0 && + this._startPos && + this._lastPos && + this._startPos.dist(this._lastPos) < this._clickTolerance) { + this.element.click(); + } + this.reset(); + } + + reset() { + this.mouseRotate.reset(); + if (this.mousePitch) this.mousePitch.reset(); + delete this._startPos; + delete this._lastPos; + this.offTemp(); + } +} + +export default NavigationControl; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/control/scale_control.js b/node_modules/@plotly/mapbox-gl/src/ui/control/scale_control.js new file mode 100644 index 0000000000000000000000000000000000000000..a8c5ce258587bc7561c559ee1a3c6f32944fa2eb --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/control/scale_control.js @@ -0,0 +1,142 @@ +// @flow + +import DOM from '../../util/dom'; +import {extend, bindAll} from '../../util/util'; + +import type Map from '../map'; + +type Unit = 'imperial' | 'metric' | 'nautical'; + +type Options = { + maxWidth?: number, + unit?: Unit; +}; + +const defaultOptions: Options = { + maxWidth: 100, + unit: 'metric' +}; + +/** + * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground. + * + * @implements {IControl} + * @param {Object} [options] + * @param {number} [options.maxWidth='100'] The maximum length of the scale control in pixels. + * @param {string} [options.unit='metric'] Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + * @example + * var scale = new mapboxgl.ScaleControl({ + * maxWidth: 80, + * unit: 'imperial' + * }); + * map.addControl(scale); + * + * scale.setUnit('metric'); + */ +class ScaleControl { + _map: Map; + _container: HTMLElement; + options: Options; + + constructor(options: Options) { + this.options = extend({}, defaultOptions, options); + + bindAll([ + '_onMove', + 'setUnit' + ], this); + } + + getDefaultPosition() { + return 'bottom-left'; + } + + _onMove() { + updateScale(this._map, this._container, this.options); + } + + onAdd(map: Map) { + this._map = map; + this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-scale', map.getContainer()); + + this._map.on('move', this._onMove); + this._onMove(); + + return this._container; + } + + onRemove() { + DOM.remove(this._container); + this._map.off('move', this._onMove); + this._map = (undefined: any); + } + + /** + * Set the scale's unit of the distance + * + * @param unit Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + */ + setUnit(unit: Unit) { + this.options.unit = unit; + updateScale(this._map, this._container, this.options); + } +} + +export default ScaleControl; + +function updateScale(map, container, options) { + // A horizontal scale is imagined to be present at center of the map + // container with maximum length (Default) as 100px. + // Using spherical law of cosines approximation, the real distance is + // found between the two coordinates. + const maxWidth = options && options.maxWidth || 100; + + const y = map._container.clientHeight / 2; + const left = map.unproject([0, y]); + const right = map.unproject([maxWidth, y]); + const maxMeters = left.distanceTo(right); + // The real distance corresponding to 100px scale length is rounded off to + // near pretty number and the scale length for the same is found out. + // Default unit of the scale is based on User's locale. + if (options && options.unit === 'imperial') { + const maxFeet = 3.2808 * maxMeters; + if (maxFeet > 5280) { + const maxMiles = maxFeet / 5280; + setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles')); + } else { + setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet')); + } + } else if (options && options.unit === 'nautical') { + const maxNauticals = maxMeters / 1852; + setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles')); + } else if (maxMeters >= 1000) { + setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers')); + } else { + setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters')); + } +} + +function setScale(container, maxWidth, maxDistance, unit) { + const distance = getRoundNum(maxDistance); + const ratio = distance / maxDistance; + container.style.width = `${maxWidth * ratio}px`; + container.innerHTML = `${distance} ${unit}`; +} + +function getDecimalRoundNum(d) { + const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10)); + return Math.round(d * multiplier) / multiplier; +} + +function getRoundNum(num) { + const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1); + let d = num / pow10; + + d = d >= 10 ? 10 : + d >= 5 ? 5 : + d >= 3 ? 3 : + d >= 2 ? 2 : + d >= 1 ? 1 : getDecimalRoundNum(d); + + return pow10 * d; +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/default_locale.js b/node_modules/@plotly/mapbox-gl/src/ui/default_locale.js new file mode 100644 index 0000000000000000000000000000000000000000..92c548d4504d84f4fe24ca755739e9726f584173 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/default_locale.js @@ -0,0 +1,22 @@ +// @flow + +const defaultLocale = { + 'AttributionControl.ToggleAttribution': 'Toggle attribution', + 'AttributionControl.MapFeedback': 'Map feedback', + 'FullscreenControl.Enter': 'Enter fullscreen', + 'FullscreenControl.Exit': 'Exit fullscreen', + 'GeolocateControl.FindMyLocation': 'Find my location', + 'GeolocateControl.LocationNotAvailable': 'Location not available', + 'LogoControl.Title': 'Mapbox logo', + 'NavigationControl.ResetBearing': 'Reset bearing to north', + 'NavigationControl.ZoomIn': 'Zoom in', + 'NavigationControl.ZoomOut': 'Zoom out', + 'ScaleControl.Feet': 'ft', + 'ScaleControl.Meters': 'm', + 'ScaleControl.Kilometers': 'km', + 'ScaleControl.Miles': 'mi', + 'ScaleControl.NauticalMiles': 'nm' + +}; + +export default defaultLocale; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/events.js b/node_modules/@plotly/mapbox-gl/src/ui/events.js new file mode 100644 index 0000000000000000000000000000000000000000..275225d61e53c4c4a4a0cecd958b93edce65072b --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/events.js @@ -0,0 +1,1301 @@ +// @flow + +import {Event} from '../util/evented'; + +import DOM from '../util/dom'; +import Point from '@mapbox/point-geometry'; +import {extend} from '../util/util'; + +import type Map from './map'; +import type LngLat from '../geo/lng_lat'; + +/** + * `MapMouseEvent` is the event type for mouse-related map events. + * @extends {Object} + * @example + * // The `click` event is an example of a `MapMouseEvent`. + * // Set up an event listener on the map. + * map.on('click', function(e) { + * // The event object (e) contains information like the + * // coordinates of the point on the map that was clicked. + * console.log('A click event has occurred at ' + e.lngLat); + * }); + */ +export class MapMouseEvent extends Event { + /** + * The event type (one of {@link Map.event:mousedown}, + * {@link Map.event:mouseup}, + * {@link Map.event:click}, + * {@link Map.event:dblclick}, + * {@link Map.event:mousemove}, + * {@link Map.event:mouseover}, + * {@link Map.event:mouseenter}, + * {@link Map.event:mouseleave}, + * {@link Map.event:mouseout}, + * {@link Map.event:contextmenu}). + */ + type: 'mousedown' + | 'mouseup' + | 'click' + | 'dblclick' + | 'mousemove' + | 'mouseover' + | 'mouseenter' + | 'mouseleave' + | 'mouseout' + | 'contextmenu'; + + /** + * The `Map` object that fired the event. + */ + target: Map; + + /** + * The DOM event which caused the map event. + */ + originalEvent: MouseEvent; + + /** + * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner. + */ + point: Point; + + /** + * The geographic location on the map of the mouse cursor. + */ + lngLat: LngLat; + + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `mousedown` events, the behavior of {@link DragPanHandler} + * * On `mousedown` events, the behavior of {@link DragRotateHandler} + * * On `mousedown` events, the behavior of {@link BoxZoomHandler} + * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + + /** + * `true` if `preventDefault` has been called. + * @private + */ + get defaultPrevented(): boolean { + return this._defaultPrevented; + } + + _defaultPrevented: boolean; + + /** + * @private + */ + constructor(type: string, map: Map, originalEvent: MouseEvent, data: Object = {}) { + const point = DOM.mousePos(map.getCanvasContainer(), originalEvent); + const lngLat = map.unproject(point); + super(type, extend({point, lngLat, originalEvent}, data)); + this._defaultPrevented = false; + this.target = map; + } +} + +/** + * `MapTouchEvent` is the event type for touch-related map events. + * @extends {Object} + */ +export class MapTouchEvent extends Event { + /** + * The event type. + */ + type: 'touchstart' + | 'touchend' + | 'touchcancel'; + + /** + * The `Map` object that fired the event. + */ + target: Map; + + /** + * The DOM event which caused the map event. + */ + originalEvent: TouchEvent; + + /** + * The geographic location on the map of the center of the touch event points. + */ + lngLat: LngLat; + + /** + * The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left + * corner. + */ + point: Point; + + /** + * The array of pixel coordinates corresponding to a + * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property. + */ + points: Array; + + /** + * The geographical locations on the map corresponding to a + * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property. + */ + lngLats: Array; + + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `touchstart` events, the behavior of {@link DragPanHandler} + * * On `touchstart` events, the behavior of {@link TouchZoomRotateHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + + /** + * `true` if `preventDefault` has been called. + * @private + */ + get defaultPrevented(): boolean { + return this._defaultPrevented; + } + + _defaultPrevented: boolean; + + /** + * @private + */ + constructor(type: string, map: Map, originalEvent: TouchEvent) { + const touches = type === "touchend" ? originalEvent.changedTouches : originalEvent.touches; + const points = DOM.touchPos(map.getCanvasContainer(), touches); + const lngLats = points.map((t) => map.unproject(t)); + const point = points.reduce((prev, curr, i, arr) => { + return prev.add(curr.div(arr.length)); + }, new Point(0, 0)); + const lngLat = map.unproject(point); + super(type, {points, point, lngLats, lngLat, originalEvent}); + this._defaultPrevented = false; + } +} + +/** + * `MapWheelEvent` is the event type for the `wheel` map event. + * @extends {Object} + */ +export class MapWheelEvent extends Event { + /** + * The event type. + */ + type: 'wheel'; + + /** + * The `Map` object that fired the event. + */ + target: Map; + + /** + * The DOM event which caused the map event. + */ + originalEvent: WheelEvent; + + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the the behavior of {@link ScrollZoomHandler}. + */ + preventDefault() { + this._defaultPrevented = true; + } + + /** + * `true` if `preventDefault` has been called. + * @private + */ + get defaultPrevented(): boolean { + return this._defaultPrevented; + } + + _defaultPrevented: boolean; + + /** + * @private + */ + constructor(type: string, map: Map, originalEvent: WheelEvent) { + super(type, {originalEvent}); + this._defaultPrevented = false; + } +} + +/** + * A `MapBoxZoomEvent` is the event type for the boxzoom-related map events emitted by the {@link BoxZoomHandler}. + * + * @typedef {Object} MapBoxZoomEvent + * @property {MouseEvent} originalEvent The DOM event that triggered the boxzoom event. Can be a `MouseEvent` or `KeyboardEvent` + * @property {string} type The type of boxzoom event. One of `boxzoomstart`, `boxzoomend` or `boxzoomcancel` + * @property {Map} target The `Map` instance that triggerred the event + */ +export type MapBoxZoomEvent = { + type: 'boxzoomstart' + | 'boxzoomend' + | 'boxzoomcancel', + target: Map, + originalEvent: MouseEvent +}; + +/** + * A `MapDataEvent` object is emitted with the {@link Map.event:data} + * and {@link Map.event:dataloading} events. Possible values for + * `dataType`s are: + * + * - `'source'`: The non-tile data associated with any source + * - `'style'`: The [style](https://www.mapbox.com/mapbox-gl-style-spec/) used by the map + * + * @typedef {Object} MapDataEvent + * @property {string} type The event type. + * @property {string} dataType The type of data that has changed. One of `'source'`, `'style'`. + * @property {boolean} [isSourceLoaded] True if the event has a `dataType` of `source` and the source has no outstanding network requests. + * @property {Object} [source] The [style spec representation of the source](https://www.mapbox.com/mapbox-gl-style-spec/#sources) if the event has a `dataType` of `source`. + * @property {string} [sourceDataType] Included if the event has a `dataType` of `source` and the event signals + * that internal data has been received or changed. Possible values are `metadata`, `content` and `visibility`. + * @property {Object} [tile] The tile being loaded or changed, if the event has a `dataType` of `source` and + * the event is related to loading of a tile. + * @property {Coordinate} [coord] The coordinate of the tile if the event has a `dataType` of `source` and + * the event is related to loading of a tile. + * @example + * // The sourcedata event is an example of MapDataEvent. + * // Set up an event listener on the map. + * map.on('sourcedata', function(e) { + * if (e.isSourceLoaded) { + * // Do something when the source has finished loading + * } + * }); + */ +export type MapDataEvent = { + type: string, + dataType: string +}; + +export type MapContextEvent = { + type: 'webglcontextlost' | 'webglcontextrestored', + originalEvent: WebGLContextEvent +} + +export type MapEvent = + /** + * Fired when a pointing device (usually a mouse) is pressed within the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is pressed while inside a visible portion of the specifed layer. + * + * @event mousedown + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mousedown', function() { + * console.log('A mousedown event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mousedown', 'poi-label', function() { + * console.log('A mousedown event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'mousedown' + + /** + * Fired when a pointing device (usually a mouse) is released within the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is released while inside a visible portion of the specifed layer. + * + * @event mouseup + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mouseup', function() { + * console.log('A mouseup event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mouseup', 'poi-label', function() { + * console.log('A mouseup event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'mouseup' + + /** + * Fired when a pointing device (usually a mouse) is moved within the map. + * As you move the cursor across a web page containing a map, + * the event will fire each time it enters the map or any child elements. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is moved inside a visible portion of the specifed layer. + * + * @event mouseover + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mouseover', function() { + * console.log('A mouseover event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mouseover', 'poi-label', function() { + * console.log('A mouseover event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/) + * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + */ + | 'mouseover' + + /** + * Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map. + * As you move the cursor across the map, the event will fire every time the cursor changes position within the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is inside a visible portion of the specified layer. + * + * @event mousemove + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mousemove', function() { + * console.log('A mousemove event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mousemove', 'poi-label', function() { + * console.log('A mousemove event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/) + * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Display a popup on over](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + */ + | 'mousemove' + + /** + * Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * point that is pressed and released contains a visible portion of the specifed layer. + * + * @event click + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('click', function(e) { + * console.log('A click event has occurred at ' + e.lngLat); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('click', 'poi-label', function(e) { + * console.log('A click event has occurred on a visible portion of the poi-label layer at ' + e.lngLat); + * }); + * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/) + * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + */ + | 'click' + + /** + * Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on + * the map in rapid succession. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only + * when the point that is clicked twice contains a visible portion of the specifed layer. + * + * @event dblclick + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('dblclick', function(e) { + * console.log('A dblclick event has occurred at ' + e.lngLat); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('dblclick', 'poi-label', function(e) { + * console.log('A dblclick event has occurred on a visible portion of the poi-label layer at ' + e.lngLat); + * }); + */ + | 'dblclick' + + /** + * Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from + * outside that layer or outside the map canvas. + * + * **Important:** This event can only be listened for when {@link Map#on} includes three arguments, + * where the second argument specifies the desired layer. + * + * @event mouseenter + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mouseenter', 'water', function() { + * console.log('A mouseenter event occurred on a visible portion of the water layer.'); + * }); + * @see [Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + */ + | 'mouseenter' + + /** + * Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves + * the map canvas. + * + * **Important:** This event can only be listened for when {@link Map#on} includes three arguements, + * where the second argument specifies the desired layer. + * + * @event mouseleave + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the pointing device leaves + * // a visible portion of the specified layer. + * map.on('mouseleave', 'water', function() { + * console.log('A mouseleave event occurred.'); + * }); + * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + */ + | 'mouseleave' + + /** + * Fired when a point device (usually a mouse) leaves the map's canvas. + * + * @event mouseout + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the pointing device leave's + * // the map's canvas. + * map.on('mouseout', function() { + * console.log('A mouseout event occurred.'); + * }); + */ + | 'mouseout' + + /** + * Fired when the right button of the mouse is clicked or the context menu key is pressed within the map. + * + * @event contextmenu + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the right mouse button is + * // pressed within the map. + * map.on('contextmenu', function() { + * console.log('A contextmenu event occurred.'); + * }); + */ + | 'contextmenu' + + /** + * Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map. + * + * @event wheel + * @memberof Map + * @instance + * @property {MapWheelEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a wheel event occurs within the map. + * map.on('wheel', function() { + * console.log('A wheel event occurred.'); + * }); + */ + | 'wheel' + + /** + * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map. + * + * @event touchstart + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchstart event occurs within the map. + * map.on('touchstart', function() { + * console.log('A touchstart event occurred.'); + * }); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'touchstart' + + /** + * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map. + * + * @event touchend + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchstart event occurs within the map. + * map.on('touchstart', function() { + * console.log('A touchstart event occurred.'); + * }); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'touchend' + + /** + * Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map. + * + * @event touchmove + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchmove event occurs within the map. + * map.on('touchmove', function() { + * console.log('A touchmove event occurred.'); + * }); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'touchmove' + + /** + * Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map. + * + * @event touchcancel + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchcancel event occurs within the map. + * map.on('touchcancel', function() { + * console.log('A touchcancel event occurred.'); + * }); + */ + | 'touchcancel' + + /** + * Fired just before the map begins a transition from one + * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}. + * + * @event movestart + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before the map begins a transition + * // from one view to another. + * map.on('movestart', function() { + * console.log('A movestart` event occurred.'); + * }); + */ + | 'movestart' + + /** + * Fired repeatedly during an animated transition from one view to + * another, as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event move + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during an animated transition. + * map.on('move', function() { + * console.log('A move event occurred.'); + * }); + * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/) + * @see [Filter features within map view](https://docs.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + */ + | 'move' + + /** + * Fired just after the map completes a transition from one + * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}. + * + * @event moveend + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after the map completes a transition. + * map.on('moveend', function() { + * console.log('A moveend event occurred.'); + * }); + * @see [Play map locations as a slideshow](https://www.mapbox.com/mapbox-gl-js/example/playback-locations/) + * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/) + */ + | 'moveend' + + /** + * Fired when a "drag to pan" interaction starts. See {@link DragPanHandler}. + * + * @event dragstart + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a "drag to pan" interaction starts. + * map.on('dragstart', function() { + * console.log('A dragstart event occurred.'); + * }); + */ + | 'dragstart' + + /** + * Fired repeatedly during a "drag to pan" interaction. See {@link DragPanHandler}. + * + * @event drag + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during a "drag to pan" interaction. + * map.on('drag', function() { + * console.log('A drag event occurred.'); + * }); + */ + | 'drag' + + /** + * Fired when a "drag to pan" interaction ends. See {@link DragPanHandler}. + * + * @event dragend + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a "drag to pan" interaction ends. + * map.on('dragend', function() { + * console.log('A dragend event occurred.'); + * }); + * @see [Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + */ + | 'dragend' + + /** + * Fired just before the map begins a transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event zoomstart + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a zoom transition starts. + * map.on('zoomstart', function() { + * console.log('A zoomstart event occurred.'); + * }); + */ + | 'zoomstart' + + /** + * Fired repeatedly during an animated transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event zoom + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during a zoom transition. + * map.on('zoom', function() { + * console.log('A zoom event occurred.'); + * }); + * @see [Update a choropleth layer by zoom level](https://www.mapbox.com/mapbox-gl-js/example/updating-choropleth/) + */ + | 'zoom' + + /** + * Fired just after the map completes a transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event zoomend + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a zoom transition finishes. + * map.on('zoomend', function() { + * console.log('A zoomend event occurred.'); + * }); + */ + | 'zoomend' + + /** + * Fired when a "drag to rotate" interaction starts. See {@link DragRotateHandler}. + * + * @event rotatestart + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a "drag to rotate" interaction starts. + * map.on('rotatestart', function() { + * console.log('A rotatestart event occurred.'); + * }); + */ + | 'rotatestart' + + /** + * Fired repeatedly during a "drag to rotate" interaction. See {@link DragRotateHandler}. + * + * @event rotate + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during "drag to rotate" interaction. + * map.on('rotate', function() { + * console.log('A rotate event occurred.'); + * }); + */ + | 'rotate' + + /** + * Fired when a "drag to rotate" interaction ends. See {@link DragRotateHandler}. + * + * @event rotateend + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a "drag to rotate" interaction ends. + * map.on('rotateend', function() { + * console.log('A rotateend event occurred.'); + * }); + */ + | 'rotateend' + + /** + * Fired whenever the map's pitch (tilt) begins a change as + * the result of either user interaction or methods such as {@link Map#flyTo} . + * + * @event pitchstart + * @memberof Map + * @instance + * @property {MapEventData} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a pitch (tilt) transition starts. + * map.on('pitchstart', function() { + * console.log('A pitchstart event occurred.'); + * }); + */ + | 'pitchstart' + + /** + * Fired repeatedly during the map's pitch (tilt) animation between + * one state and another as the result of either user interaction + * or methods such as {@link Map#flyTo}. + * + * @event pitch + * @memberof Map + * @instance + * @property {MapEventData} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during a pitch (tilt) transition. + * map.on('pitch', function() { + * console.log('A pitch event occurred.'); + * }); + */ + | 'pitch' + + /** + * Fired immediately after the map's pitch (tilt) finishes changing as + * the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event pitchend + * @memberof Map + * @instance + * @property {MapEventData} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a pitch (tilt) transition ends. + * map.on('pitchend', function() { + * console.log('A pitchend event occurred.'); + * }); + */ + | 'pitchend' + + /** + * Fired when a "box zoom" interaction starts. See {@link BoxZoomHandler}. + * + * @event boxzoomstart + * @memberof Map + * @instance + * @property {MapBoxZoomEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a "box zoom" interaction starts. + * map.on('boxzoomstart', function() { + * console.log('A boxzoomstart event occurred.'); + * }); + */ + | 'boxzoomstart' + + /** + * Fired when a "box zoom" interaction ends. See {@link BoxZoomHandler}. + * + * @event boxzoomend + * @memberof Map + * @instance + * @type {Object} + * @property {MapBoxZoomEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a "box zoom" interaction ends. + * map.on('boxzoomend', function() { + * console.log('A boxzoomend event occurred.'); + * }); + */ + | 'boxzoomend' + + /** + * Fired when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. + * See {@link BoxZoomHandler}. + * + * @event boxzoomcancel + * @memberof Map + * @instance + * @property {MapBoxZoomEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // the user cancels a "box zoom" interaction. + * map.on('boxzoomcancel', function() { + * console.log('A boxzoomcancel event occurred.'); + * }); + */ + | 'boxzoomcancel' + + /** + * Fired immediately after the map has been resized. + * + * @event resize + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // immediately after the map has been resized. + * map.on('resize', function() { + * console.log('A resize event occurred.'); + * }); + */ + | 'resize' + + /** + * Fired when the WebGL context is lost. + * + * @event webglcontextlost + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the WebGL context is lost. + * map.on('webglcontextlost', function() { + * console.log('A webglcontextlost event occurred.'); + * }); + */ + | 'webglcontextlost' + + /** + * Fired when the WebGL context is restored. + * + * @event webglcontextrestored + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the WebGL context is restored. + * map.on('webglcontextrestored', function() { + * console.log('A webglcontextrestored event occurred.'); + * }); + */ + | 'webglcontextrestored' + + /** + * Fired immediately after all necessary resources have been downloaded + * and the first visually complete rendering of the map has occurred. + * + * @event load + * @memberof Map + * @instance + * @type {Object} + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the map has finished loading. + * map.on('load', function() { + * console.log('A load event occurred.'); + * }); + * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/) + * @see [Add live realtime data](https://www.mapbox.com/mapbox-gl-js/example/live-geojson/) + * @see [Animate a point](https://www.mapbox.com/mapbox-gl-js/example/animate-point-along-line/) + */ + | 'load' + + /** + * Fired whenever the map is drawn to the screen, as the result of + * + * - a change to the map's position, zoom, pitch, or bearing + * - a change to the map's style + * - a change to a GeoJSON source + * - the loading of a vector tile, GeoJSON file, glyph, or sprite + * + * @event render + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // whenever the map is drawn to the screen. + * map.on('render', function() { + * console.log('A render event occurred.'); + * }); + */ + | 'render' + + /** + * Fired after the last frame rendered before the map enters an + * "idle" state: + * + * - No camera transitions are in progress + * - All currently requested tiles have loaded + * - All fade/transition animations have completed + * + * @event idle + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before the map enters an "idle" state. + * map.on('idle', function() { + * console.log('A idle event occurred.'); + * }); + */ + | 'idle' + + /** + * Fired immediately after the map has been removed with {@link Map.event:remove}. + * + * @event remove + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after the map is removed. + * map.on('remove', function() { + * console.log('A remove event occurred.'); + * }); + */ + | 'remove' + + /** + * Fired when an error occurs. This is GL JS's primary error reporting + * mechanism. We use an event instead of `throw` to better accommodate + * asyncronous operations. If no listeners are bound to the `error` event, the + * error will be printed to the console. + * + * @event error + * @memberof Map + * @instance + * @property {{error: {message: string}}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when an error occurs. + * map.on('error', function() { + * console.log('A error event occurred.'); + * }); + */ + | 'error' + + /** + * Fired when any map data loads or changes. See {@link MapDataEvent} + * for more information. + * + * @event data + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when map data loads or changes. + * map.on('data', function() { + * console.log('A data event occurred.'); + * }); + * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/) + */ + | 'data' + + /** + * Fired when the map's style loads or changes. See + * {@link MapDataEvent} for more information. + * + * @event styledata + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the map's style loads or changes. + * map.on('styledata', function() { + * console.log('A styledata event occurred.'); + * }); + */ + | 'styledata' + + /** + * Fired when one of the map's sources loads or changes, including if a tile belonging + * to a source loads or changes. See {@link MapDataEvent} for more information. + * + * @event sourcedata + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when one of the map's sources loads or changes. + * map.on('sourcedata', function() { + * console.log('A sourcedata event occurred.'); + * }); + */ + | 'sourcedata' + + /** + * Fired when any map data (style, source, tile, etc) begins loading or + * changing asyncronously. All `dataloading` events are followed by a `data` + * or `error` event. See {@link MapDataEvent} for more information. + * + * @event dataloading + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when any map data begins loading + * // or changing asynchronously. + * map.on('dataloading', function() { + * console.log('A dataloading event occurred.'); + * }); + */ + | 'dataloading' + + /** + * Fired when the map's style begins loading or changing asyncronously. + * All `styledataloading` events are followed by a `styledata` + * or `error` event. See {@link MapDataEvent} for more information. + * + * @event styledataloading + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // map's style begins loading or + * // changing asyncronously. + * map.on('styledataloading', function() { + * console.log('A styledataloading event occurred.'); + * }); + */ + | 'styledataloading' + + /** + * Fired when one of the map's sources begins loading or changing asyncronously. + * All `sourcedataloading` events are followed by a `sourcedata` or `error` event. + * See {@link MapDataEvent} for more information. + * + * @event sourcedataloading + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // map's sources begin loading or + * // changing asyncronously. + * map.on('sourcedataloading', function() { + * console.log('A sourcedataloading event occurred.'); + * }); + */ + | 'sourcedataloading' + + /** + * Fired when an icon or pattern needed by the style is missing. The missing image can + * be added with {@link Map#addImage} within this event listener callback to prevent the image from + * being skipped. This event can be used to dynamically generate icons and patterns. + * + * @event styleimagemissing + * @memberof Map + * @instance + * @property {string} id The id of the missing image. + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // an icon or pattern is missing. + * map.on('styleimagemissing', function() { + * console.log('A styleimagemissing event occurred.'); + * }); + * @see [Generate and add a missing icon to the map](https://mapbox.com/mapbox-gl-js/example/add-image-missing-generated/) + */ + | 'styleimagemissing' + + /** + * @event style.load + * @memberof Map + * @instance + * @private + */ + | 'style.load'; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/box_zoom.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/box_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..c004e3637d004065f31900114010f03ce1190f27 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/box_zoom.js @@ -0,0 +1,170 @@ +// @flow + +import DOM from '../../util/dom'; + +import {Event} from '../../util/evented'; + +import type Map from '../map'; + +/** + * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box. + * The bounding box is defined by clicking and holding `shift` while dragging the cursor. + */ +class BoxZoomHandler { + _map: Map; + _el: HTMLElement; + _container: HTMLElement; + _enabled: boolean; + _active: boolean; + _startPos: Point; + _lastPos: Point; + _box: HTMLElement; + _clickTolerance: number; + + /** + * @private + */ + constructor(map: Map, options: { + clickTolerance: number + }) { + this._map = map; + this._el = map.getCanvasContainer(); + this._container = map.getContainer(); + this._clickTolerance = options.clickTolerance || 1; + } + + /** + * Returns a Boolean indicating whether the "box zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "box zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + + /** + * Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "box zoom" interaction is active. + */ + isActive() { + return !!this._active; + } + + /** + * Enables the "box zoom" interaction. + * + * @example + * map.boxZoom.enable(); + */ + enable() { + if (this.isEnabled()) return; + this._enabled = true; + } + + /** + * Disables the "box zoom" interaction. + * + * @example + * map.boxZoom.disable(); + */ + disable() { + if (!this.isEnabled()) return; + this._enabled = false; + } + + mousedown(e: MouseEvent, point: Point) { + if (!this.isEnabled()) return; + if (!(e.shiftKey && e.button === 0)) return; + + DOM.disableDrag(); + this._startPos = this._lastPos = point; + this._active = true; + } + + mousemoveWindow(e: MouseEvent, point: Point) { + if (!this._active) return; + + const pos = point; + + if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) { + return; + } + + const p0 = this._startPos; + this._lastPos = pos; + + if (!this._box) { + this._box = DOM.create('div', 'mapboxgl-boxzoom', this._container); + this._container.classList.add('mapboxgl-crosshair'); + this._fireEvent('boxzoomstart', e); + } + + const minX = Math.min(p0.x, pos.x), + maxX = Math.max(p0.x, pos.x), + minY = Math.min(p0.y, pos.y), + maxY = Math.max(p0.y, pos.y); + + DOM.setTransform(this._box, `translate(${minX}px,${minY}px)`); + + this._box.style.width = `${maxX - minX}px`; + this._box.style.height = `${maxY - minY}px`; + } + + mouseupWindow(e: MouseEvent, point: Point) { + if (!this._active) return; + + if (e.button !== 0) return; + + const p0 = this._startPos, + p1 = point; + + this.reset(); + + DOM.suppressClick(); + + if (p0.x === p1.x && p0.y === p1.y) { + this._fireEvent('boxzoomcancel', e); + } else { + this._map.fire(new Event('boxzoomend', {originalEvent: e})); + return { + cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._map.getBearing(), {linear: true}) + }; + } + } + + keydown(e: KeyboardEvent) { + if (!this._active) return; + + if (e.keyCode === 27) { + this.reset(); + this._fireEvent('boxzoomcancel', e); + } + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + + this._container.classList.remove('mapboxgl-crosshair'); + + if (this._box) { + DOM.remove(this._box); + this._box = (null: any); + } + + DOM.enableDrag(); + + delete this._startPos; + delete this._lastPos; + } + + _fireEvent(type: string, e: *) { + return this._map.fire(new Event(type, {originalEvent: e})); + } +} + +export default BoxZoomHandler; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/click_zoom.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/click_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..2d8f5662b7f876ce01aeb50d47e016a3da6aafbc --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/click_zoom.js @@ -0,0 +1,52 @@ +// @flow + +import type Point from '@mapbox/point-geometry'; +import type Map from '../map'; + +export default class ClickZoomHandler { + + _enabled: boolean; + _active: boolean; + + constructor() { + this.reset(); + } + + reset() { + this._active = false; + } + + blur() { + this.reset(); + } + + dblclick(e: MouseEvent, point: Point) { + e.preventDefault(); + return { + cameraAnimation: (map: Map) => { + map.easeTo({ + duration: 300, + zoom: map.getZoom() + (e.shiftKey ? -1 : 1), + around: map.unproject(point) + }, {originalEvent: e}); + } + }; + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/handler_util.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/handler_util.js new file mode 100644 index 0000000000000000000000000000000000000000..493f93d626404ed543f0507cc750bbb441151adb --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/handler_util.js @@ -0,0 +1,12 @@ +// @flow + +import assert from 'assert'; + +export function indexTouches(touches: Array, points: Array) { + assert(touches.length === points.length); + const obj = {}; + for (let i = 0; i < touches.length; i++) { + obj[touches[i].identifier] = points[i]; + } + return obj; +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/keyboard.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/keyboard.js new file mode 100644 index 0000000000000000000000000000000000000000..15de2d541532b4a7502fee689b6d75b27bba3a0e --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/keyboard.js @@ -0,0 +1,208 @@ +// @flow + +import type Map from '../map'; + +const defaultOptions = { + panStep: 100, + bearingStep: 15, + pitchStep: 10 +}; + +/** + * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using + * the following keyboard shortcuts: + * + * - `=` / `+`: Increase the zoom level by 1. + * - `Shift-=` / `Shift-+`: Increase the zoom level by 2. + * - `-`: Decrease the zoom level by 1. + * - `Shift--`: Decrease the zoom level by 2. + * - Arrow keys: Pan by 100 pixels. + * - `Shift+⇢`: Increase the rotation by 15 degrees. + * - `Shift+⇠`: Decrease the rotation by 15 degrees. + * - `Shift+⇡`: Increase the pitch by 10 degrees. + * - `Shift+⇣`: Decrease the pitch by 10 degrees. + */ +class KeyboardHandler { + _enabled: boolean; + _active: boolean; + _panStep: number; + _bearingStep: number; + _pitchStep: number; + _rotationDisabled: boolean; + + /** + * @private + */ + constructor() { + const stepOptions = defaultOptions; + this._panStep = stepOptions.panStep; + this._bearingStep = stepOptions.bearingStep; + this._pitchStep = stepOptions.pitchStep; + this._rotationDisabled = false; + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + } + + keydown(e: KeyboardEvent) { + if (e.altKey || e.ctrlKey || e.metaKey) return; + + let zoomDir = 0; + let bearingDir = 0; + let pitchDir = 0; + let xDir = 0; + let yDir = 0; + + switch (e.keyCode) { + case 61: + case 107: + case 171: + case 187: + zoomDir = 1; + break; + + case 189: + case 109: + case 173: + zoomDir = -1; + break; + + case 37: + if (e.shiftKey) { + bearingDir = -1; + } else { + e.preventDefault(); + xDir = -1; + } + break; + + case 39: + if (e.shiftKey) { + bearingDir = 1; + } else { + e.preventDefault(); + xDir = 1; + } + break; + + case 38: + if (e.shiftKey) { + pitchDir = 1; + } else { + e.preventDefault(); + yDir = -1; + } + break; + + case 40: + if (e.shiftKey) { + pitchDir = -1; + } else { + e.preventDefault(); + yDir = 1; + } + break; + + default: + return; + } + + if (this._rotationDisabled) { + bearingDir = 0; + pitchDir = 0; + } + + return { + cameraAnimation: (map: Map) => { + const zoom = map.getZoom(); + map.easeTo({ + duration: 300, + easeId: 'keyboardHandler', + easing: easeOut, + + zoom: zoomDir ? Math.round(zoom) + zoomDir * (e.shiftKey ? 2 : 1) : zoom, + bearing: map.getBearing() + bearingDir * this._bearingStep, + pitch: map.getPitch() + pitchDir * this._pitchStep, + offset: [-xDir * this._panStep, -yDir * this._panStep], + center: map.getCenter() + }, {originalEvent: e}); + } + }; + } + + /** + * Enables the "keyboard rotate and zoom" interaction. + * + * @example + * map.keyboard.enable(); + */ + enable() { + this._enabled = true; + } + + /** + * Disables the "keyboard rotate and zoom" interaction. + * + * @example + * map.keyboard.disable(); + */ + disable() { + this._enabled = false; + this.reset(); + } + + /** + * Returns a Boolean indicating whether the "keyboard rotate and zoom" + * interaction is enabled. + * + * @returns {boolean} `true` if the "keyboard rotate and zoom" + * interaction is enabled. + */ + isEnabled() { + return this._enabled; + } + + /** + * Returns true if the handler is enabled and has detected the start of a + * zoom/rotate gesture. + * + * @returns {boolean} `true` if the handler is enabled and has detected the + * start of a zoom/rotate gesture. + */ + isActive() { + return this._active; + } + + /** + * Disables the "keyboard pan/rotate" interaction, leaving the + * "keyboard zoom" interaction enabled. + * + * @example + * map.keyboard.disableRotation(); + */ + disableRotation() { + this._rotationDisabled = true; + } + + /** + * Enables the "keyboard pan/rotate" interaction. + * + * @example + * map.keyboard.enable(); + * map.keyboard.enableRotation(); + */ + enableRotation() { + this._rotationDisabled = false; + } +} + +function easeOut(t: number) { + return t * (2 - t); +} + +export default KeyboardHandler; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/map_event.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/map_event.js new file mode 100644 index 0000000000000000000000000000000000000000..31b46e5ba23b0255fb237f73c1e53c27f3166069 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/map_event.js @@ -0,0 +1,156 @@ +// @flow + +import {MapMouseEvent, MapTouchEvent, MapWheelEvent} from '../events'; +import type Map from '../map'; + +export class MapEventHandler { + + _mousedownPos: Point; + _clickTolerance: number; + _map: Map; + + constructor(map: Map, options: { clickTolerance: number }) { + this._map = map; + this._clickTolerance = options.clickTolerance; + } + + reset() { + delete this._mousedownPos; + } + + wheel(e: WheelEvent) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - ScrollZoom + return this._firePreventable(new MapWheelEvent(e.type, this._map, e)); + } + + mousedown(e: MouseEvent, point: Point) { + this._mousedownPos = point; + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - MousePan + // - MouseRotate + // - MousePitch + // - DblclickHandler + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + + mouseup(e: MouseEvent) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + click(e: MouseEvent, point: Point) { + if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) return; + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + dblclick(e: MouseEvent) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - DblClickZoom + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + + mouseover(e: MouseEvent) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + mouseout(e: MouseEvent) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + touchstart(e: TouchEvent) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - TouchPan + // - TouchZoom + // - TouchRotate + // - TouchPitch + // - TapZoom + // - SwipeZoom + return this._firePreventable(new MapTouchEvent(e.type, this._map, e)); + } + + touchmove(e: TouchEvent) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + + touchend(e: TouchEvent) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + + touchcancel(e: TouchEvent) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + + _firePreventable(mapEvent: MapMouseEvent | MapTouchEvent | MapWheelEvent) { + this._map.fire(mapEvent); + if (mapEvent.defaultPrevented) { + // returning an object marks the handler as active and resets other handlers + return {}; + } + } + + isEnabled() { + return true; + } + + isActive() { + return false; + } + enable() {} + disable() {} +} + +export class BlockableMapEventHandler { + _map: Map; + _delayContextMenu: boolean; + _contextMenuEvent: MouseEvent; + + constructor(map: Map) { + this._map = map; + } + + reset() { + this._delayContextMenu = false; + delete this._contextMenuEvent; + } + + mousemove(e: MouseEvent) { + // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + mousedown() { + this._delayContextMenu = true; + } + + mouseup() { + this._delayContextMenu = false; + if (this._contextMenuEvent) { + this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent)); + delete this._contextMenuEvent; + } + } + contextmenu(e: MouseEvent) { + if (this._delayContextMenu) { + // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake + this._contextMenuEvent = e; + } else { + // Windows: contextmenu fired on mouseup, so fire event now + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + // prevent browser context menu when necessary + if (this._map.listens('contextmenu')) { + e.preventDefault(); + } + } + + isEnabled() { + return true; + } + + isActive() { + return false; + } + enable() {} + disable() {} +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/mouse.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/mouse.js new file mode 100644 index 0000000000000000000000000000000000000000..55b235fe39f74a089166d6d065345839ed6e21ee --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/mouse.js @@ -0,0 +1,171 @@ +// @flow + +import DOM from '../../util/dom'; +import type Point from '@mapbox/point-geometry'; + +const LEFT_BUTTON = 0; +const RIGHT_BUTTON = 2; + +// the values for each button in MouseEvent.buttons +const BUTTONS_FLAGS = { + [LEFT_BUTTON]: 1, + [RIGHT_BUTTON]: 2 +}; + +function buttonStillPressed(e: MouseEvent, button: number) { + const flag = BUTTONS_FLAGS[button]; + return e.buttons === undefined || (e.buttons & flag) !== flag; +} + +class MouseHandler { + + _enabled: boolean; + _active: boolean; + _lastPoint: Point; + _eventButton: number; + _moved: boolean; + _clickTolerance: number; + + constructor(options: { clickTolerance: number }) { + this.reset(); + this._clickTolerance = options.clickTolerance || 1; + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + this._moved = false; + delete this._lastPoint; + delete this._eventButton; + } + + _correctButton(e: MouseEvent, button: number) { //eslint-disable-line + return false; // implemented by child + } + + _move(lastPoint: Point, point: Point) { //eslint-disable-line + return {}; // implemented by child + } + + mousedown(e: MouseEvent, point: Point) { + if (this._lastPoint) return; + + const eventButton = DOM.mouseButton(e); + if (!this._correctButton(e, eventButton)) return; + + this._lastPoint = point; + this._eventButton = eventButton; + } + + mousemoveWindow(e: MouseEvent, point: Point) { + const lastPoint = this._lastPoint; + if (!lastPoint) return; + e.preventDefault(); + + if (buttonStillPressed(e, this._eventButton)) { + // Some browsers don't fire a `mouseup` when the mouseup occurs outside + // the window or iframe: + // https://github.com/mapbox/mapbox-gl-js/issues/4622 + // + // If the button is no longer pressed during this `mousemove` it may have + // been released outside of the window or iframe. + this.reset(); + return; + } + + if (!this._moved && point.dist(lastPoint) < this._clickTolerance) return; + this._moved = true; + this._lastPoint = point; + + // implemented by child class + return this._move(lastPoint, point); + } + + mouseupWindow(e: MouseEvent) { + if (!this._lastPoint) return; + const eventButton = DOM.mouseButton(e); + if (eventButton !== this._eventButton) return; + if (this._moved) DOM.suppressClick(); + this.reset(); + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} + +export class MousePanHandler extends MouseHandler { + + mousedown(e: MouseEvent, point: Point) { + super.mousedown(e, point); + if (this._lastPoint) this._active = true; + } + _correctButton(e: MouseEvent, button: number) { + return button === LEFT_BUTTON && !e.ctrlKey; + } + + _move(lastPoint: Point, point: Point) { + return { + around: point, + panDelta: point.sub(lastPoint) + }; + } +} + +export class MouseRotateHandler extends MouseHandler { + _correctButton(e: MouseEvent, button: number) { + return (button === LEFT_BUTTON && e.ctrlKey) || (button === RIGHT_BUTTON); + } + + _move(lastPoint: Point, point: Point) { + const degreesPerPixelMoved = 0.8; + const bearingDelta = (point.x - lastPoint.x) * degreesPerPixelMoved; + if (bearingDelta) { + this._active = true; + return {bearingDelta}; + } + } + + contextmenu(e: MouseEvent) { + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + e.preventDefault(); + } +} + +export class MousePitchHandler extends MouseHandler { + _correctButton(e: MouseEvent, button: number) { + return (button === LEFT_BUTTON && e.ctrlKey) || (button === RIGHT_BUTTON); + } + + _move(lastPoint: Point, point: Point) { + const degreesPerPixelMoved = -0.5; + const pitchDelta = (point.y - lastPoint.y) * degreesPerPixelMoved; + if (pitchDelta) { + this._active = true; + return {pitchDelta}; + } + } + + contextmenu(e: MouseEvent) { + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + e.preventDefault(); + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/scroll_zoom.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/scroll_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..40eb32a89d4d8bd26bbd12c052111351b778aeae --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/scroll_zoom.js @@ -0,0 +1,350 @@ +// @flow + +import assert from 'assert'; +import DOM from '../../util/dom'; + +import {ease as _ease, bindAll, bezier} from '../../util/util'; +import browser from '../../util/browser'; +import window from '../../util/window'; +import {number as interpolate} from '../../style-spec/util/interpolate'; +import LngLat from '../../geo/lng_lat'; + +import type Map from '../map'; +import type HandlerManager from '../handler_manager'; +import type Point from '@mapbox/point-geometry'; + +// deltaY value for mouse scroll wheel identification +const wheelZoomDelta = 4.000244140625; + +// These magic numbers control the rate of zoom. Trackpad events fire at a greater +// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick +const defaultZoomRate = 1 / 100; +const wheelZoomRate = 1 / 450; + +// upper bound on how much we scale the map in any single render frame; this +// is used to limit zoom rate in the case of very fast scrolling +const maxScalePerFrame = 2; + +/** + * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. + */ +class ScrollZoomHandler { + _map: Map; + _el: HTMLElement; + _enabled: boolean; + _active: boolean; + _zooming: boolean; + _aroundCenter: boolean; + _around: Point; + _aroundPoint: Point; + _type: 'wheel' | 'trackpad' | null; + _lastValue: number; + _timeout: ?TimeoutID; // used for delayed-handling of a single wheel movement + _finishTimeout: ?TimeoutID; // used to delay final '{move,zoom}end' events + + _lastWheelEvent: any; + _lastWheelEventTime: number; + + _startZoom: ?number; + _targetZoom: ?number; + _delta: number; + _easing: ?((number) => number); + _prevEase: ?{start: number, duration: number, easing: (_: number) => number}; + + _frameId: ?boolean; + _handler: HandlerManager; + + _defaultZoomRate: number; + _wheelZoomRate: number; + + /** + * @private + */ + constructor(map: Map, handler: HandlerManager) { + this._map = map; + this._el = map.getCanvasContainer(); + this._handler = handler; + + this._delta = 0; + + this._defaultZoomRate = defaultZoomRate; + this._wheelZoomRate = wheelZoomRate; + + bindAll(['_onTimeout'], this); + } + + /** + * Set the zoom rate of a trackpad + * @param {number} [zoomRate=1/100] The rate used to scale trackpad movement to a zoom value. + * @example + * // Speed up trackpad zoom + * map.scrollZoom.setZoomRate(1/25); + */ + setZoomRate(zoomRate: number) { + this._defaultZoomRate = zoomRate; + } + + /** + * Set the zoom rate of a mouse wheel + * @param {number} [wheelZoomRate=1/450] The rate used to scale mouse wheel movement to a zoom value. + * @example + * // Slow down zoom of mouse wheel + * map.scrollZoom.setWheelZoomRate(1/600); + */ + setWheelZoomRate(wheelZoomRate: number) { + this._wheelZoomRate = wheelZoomRate; + } + + /** + * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "scroll to zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + + /* + * Active state is turned on and off with every scroll wheel event and is set back to false before the map + * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in + * progress. + */ + isActive() { + return !!this._active || this._finishTimeout !== undefined; + } + + isZooming() { + return !!this._zooming; + } + + /** + * Enables the "scroll to zoom" interaction. + * + * @param {Object} [options] Options object. + * @param {string} [options.around] If "center" is passed, map will zoom around center of map + * + * @example + * map.scrollZoom.enable(); + * @example + * map.scrollZoom.enable({ around: 'center' }) + */ + enable(options: any) { + if (this.isEnabled()) return; + this._enabled = true; + this._aroundCenter = options && options.around === 'center'; + } + + /** + * Disables the "scroll to zoom" interaction. + * + * @example + * map.scrollZoom.disable(); + */ + disable() { + if (!this.isEnabled()) return; + this._enabled = false; + } + + wheel(e: WheelEvent) { + if (!this.isEnabled()) return; + + // Remove `any` cast when https://github.com/facebook/flow/issues/4879 is fixed. + let value = e.deltaMode === (window.WheelEvent: any).DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY; + const now = browser.now(), + timeDelta = now - (this._lastWheelEventTime || 0); + + this._lastWheelEventTime = now; + + if (value !== 0 && (value % wheelZoomDelta) === 0) { + // This one is definitely a mouse wheel event. + this._type = 'wheel'; + + } else if (value !== 0 && Math.abs(value) < 4) { + // This one is definitely a trackpad event because it is so small. + this._type = 'trackpad'; + + } else if (timeDelta > 400) { + // This is likely a new scroll action. + this._type = null; + this._lastValue = value; + + // Start a timeout in case this was a singular event, and dely it by up to 40ms. + this._timeout = setTimeout(this._onTimeout, 40, e); + + } else if (!this._type) { + // This is a repeating event, but we don't know the type of event just yet. + // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode. + this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel'; + + // Make sure our delayed event isn't fired again, because we accumulate + // the previous event (which was less than 40ms ago) into this event. + if (this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + value += this._lastValue; + } + } + + // Slow down zoom if shift key is held for more precise zooming + if (e.shiftKey && value) value = value / 4; + + // Only fire the callback if we actually know what type of scrolling device the user uses. + if (this._type) { + this._lastWheelEvent = e; + this._delta -= value; + if (!this._active) { + this._start(e); + } + } + + e.preventDefault(); + } + + _onTimeout(initialEvent: any) { + this._type = 'wheel'; + this._delta -= this._lastValue; + if (!this._active) { + this._start(initialEvent); + } + } + + _start(e: any) { + if (!this._delta) return; + + if (this._frameId) { + this._frameId = null; + } + + this._active = true; + if (!this.isZooming()) { + this._zooming = true; + } + + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + + const pos = DOM.mousePos(this._el, e); + + this._around = LngLat.convert(this._aroundCenter ? this._map.getCenter() : this._map.unproject(pos)); + this._aroundPoint = this._map.transform.locationPoint(this._around); + if (!this._frameId) { + this._frameId = true; + this._handler._triggerRenderFrame(); + } + } + + renderFrame() { + if (!this._frameId) return; + this._frameId = null; + + if (!this.isActive()) return; + const tr = this._map.transform; + + // if we've had scroll events since the last render frame, consume the + // accumulated delta, and update the target zoom level accordingly + if (this._delta !== 0) { + // For trackpad events and single mouse wheel ticks, use the default zoom rate + const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate; + // Scale by sigmoid of scroll wheel delta. + let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate))); + + if (this._delta < 0 && scale !== 0) { + scale = 1 / scale; + } + + const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : tr.scale; + this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale))); + + // if this is a mouse wheel, refresh the starting zoom and easing + // function we're using to smooth out the zooming between wheel + // events + if (this._type === 'wheel') { + this._startZoom = tr.zoom; + this._easing = this._smoothOutEasing(200); + } + + this._delta = 0; + } + + const targetZoom = typeof this._targetZoom === 'number' ? + this._targetZoom : tr.zoom; + const startZoom = this._startZoom; + const easing = this._easing; + + let finished = false; + let zoom; + if (this._type === 'wheel' && startZoom && easing) { + assert(easing && typeof startZoom === 'number'); + + const t = Math.min((browser.now() - this._lastWheelEventTime) / 200, 1); + const k = easing(t); + zoom = interpolate(startZoom, targetZoom, k); + if (t < 1) { + if (!this._frameId) { + this._frameId = true; + } + } else { + finished = true; + } + } else { + zoom = targetZoom; + finished = true; + } + + this._active = true; + + if (finished) { + this._active = false; + this._finishTimeout = setTimeout(() => { + this._zooming = false; + this._handler._triggerRenderFrame(); + delete this._targetZoom; + delete this._finishTimeout; + }, 200); + } + + return { + noInertia: true, + needsRenderFrame: !finished, + zoomDelta: zoom - tr.zoom, + around: this._aroundPoint, + originalEvent: this._lastWheelEvent + }; + } + + _smoothOutEasing(duration: number) { + let easing = _ease; + + if (this._prevEase) { + const ease = this._prevEase, + t = (browser.now() - ease.start) / ease.duration, + speed = ease.easing(t + 0.01) - ease.easing(t), + + // Quick hack to make new bezier that is continuous with last + x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01, + y = Math.sqrt(0.27 * 0.27 - x * x); + + easing = bezier(x, y, 0.25, 1); + } + + this._prevEase = { + start: browser.now(), + duration, + easing + }; + + return easing; + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + } +} + +export default ScrollZoomHandler; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/dblclick_zoom.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/dblclick_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..b63cfbada678bee026b1b8509b7b33174950dbb5 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/dblclick_zoom.js @@ -0,0 +1,62 @@ +// @flow + +import type ClickZoomHandler from '../click_zoom'; +import type TapZoomHandler from './../tap_zoom'; + +/** + * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by + * double clicking or double tapping. + */ +export default class DoubleClickZoomHandler { + + _clickZoom: ClickZoomHandler; + _tapZoom: TapZoomHandler; + + /** + * @private + */ + constructor(clickZoom: ClickZoomHandler, TapZoom: TapZoomHandler) { + this._clickZoom = clickZoom; + this._tapZoom = TapZoom; + } + + /** + * Enables the "double click to zoom" interaction. + * + * @example + * map.doubleClickZoom.enable(); + */ + enable() { + this._clickZoom.enable(); + this._tapZoom.enable(); + } + + /** + * Disables the "double click to zoom" interaction. + * + * @example + * map.doubleClickZoom.disable(); + */ + disable() { + this._clickZoom.disable(); + this._tapZoom.disable(); + } + + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "double click to zoom" interaction is enabled. + */ + isEnabled() { + return this._clickZoom.isEnabled() && this._tapZoom.isEnabled(); + } + + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "double click to zoom" interaction is active. + */ + isActive() { + return this._clickZoom.isActive() || this._tapZoom.isActive(); + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/drag_pan.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/drag_pan.js new file mode 100644 index 0000000000000000000000000000000000000000..2b55e42539f44d88415e41cd582c1c3afd1f4e4d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/drag_pan.js @@ -0,0 +1,88 @@ +// @flow + +import type {MousePanHandler} from '../mouse'; +import type TouchPanHandler from './../touch_pan'; + +export type DragPanOptions = { + linearity?: number; + easing?: (t: number) => number; + deceleration?: number; + maxSpeed?: number; +}; + +/** + * The `DragPanHandler` allows the user to pan the map by clicking and dragging + * the cursor. + */ +export default class DragPanHandler { + + _el: HTMLElement; + _mousePan: MousePanHandler; + _touchPan: TouchPanHandler; + _inertiaOptions: DragPanOptions + + /** + * @private + */ + constructor(el: HTMLElement, mousePan: MousePanHandler, touchPan: TouchPanHandler) { + this._el = el; + this._mousePan = mousePan; + this._touchPan = touchPan; + } + + /** + * Enables the "drag to pan" interaction. + * + * @param {Object} [options] Options object + * @param {number} [options.linearity=0] factor used to scale the drag velocity + * @param {Function} [options.easing=bezier(0, 0, 0.3, 1)] easing function applled to `map.panTo` when applying the drag. + * @param {number} [options.maxSpeed=1400] the maximum value of the drag velocity. + * @param {number} [options.deceleration=2500] the rate at which the speed reduces after the pan ends. + * + * @example + * map.dragPan.enable(); + * @example + * map.dragPan.enable({ + * linearity: 0.3, + * easing: bezier(0, 0, 0.3, 1), + * maxSpeed: 1400, + * deceleration: 2500, + * }); + */ + enable(options?: DragPanOptions) { + this._inertiaOptions = options || {}; + this._mousePan.enable(); + this._touchPan.enable(); + this._el.classList.add('mapboxgl-touch-drag-pan'); + } + + /** + * Disables the "drag to pan" interaction. + * + * @example + * map.dragPan.disable(); + */ + disable() { + this._mousePan.disable(); + this._touchPan.disable(); + this._el.classList.remove('mapboxgl-touch-drag-pan'); + } + + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is enabled. + * + * @returns {boolean} `true` if the "drag to pan" interaction is enabled. + */ + isEnabled() { + return this._mousePan.isEnabled() && this._touchPan.isEnabled(); + } + + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "drag to pan" interaction is active. + */ + isActive() { + return this._mousePan.isActive() || this._touchPan.isActive(); + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/drag_rotate.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/drag_rotate.js new file mode 100644 index 0000000000000000000000000000000000000000..22141fa5116fdd5848188bbccd304c72edf5b0e0 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/drag_rotate.js @@ -0,0 +1,67 @@ +// @flow + +import type {MouseRotateHandler, MousePitchHandler} from '../mouse'; + +/** + * The `DragRotateHandler` allows the user to rotate the map by clicking and + * dragging the cursor while holding the right mouse button or `ctrl` key. + */ +export default class DragRotateHandler { + + _mouseRotate: MouseRotateHandler; + _mousePitch: MousePitchHandler; + _pitchWithRotate: boolean; + + /** + * @param {Object} [options] + * @param {number} [options.bearingSnap] The threshold, measured in degrees, that determines when the map's + * bearing will snap to north. + * @param {bool} [options.pitchWithRotate=true] Control the map pitch in addition to the bearing + * @private + */ + constructor(options: {pitchWithRotate: boolean}, mouseRotate: MouseRotateHandler, mousePitch: MousePitchHandler) { + this._pitchWithRotate = options.pitchWithRotate; + this._mouseRotate = mouseRotate; + this._mousePitch = mousePitch; + } + + /** + * Enables the "drag to rotate" interaction. + * + * @example + * map.dragRotate.enable(); + */ + enable() { + this._mouseRotate.enable(); + if (this._pitchWithRotate) this._mousePitch.enable(); + } + + /** + * Disables the "drag to rotate" interaction. + * + * @example + * map.dragRotate.disable(); + */ + disable() { + this._mouseRotate.disable(); + this._mousePitch.disable(); + } + + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is enabled. + * + * @returns {boolean} `true` if the "drag to rotate" interaction is enabled. + */ + isEnabled() { + return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled()); + } + + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "drag to rotate" interaction is active. + */ + isActive() { + return this._mouseRotate.isActive() || this._mousePitch.isActive(); + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/touch_zoom_rotate.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/touch_zoom_rotate.js new file mode 100644 index 0000000000000000000000000000000000000000..b1cbe4ea7bd6eeb69f0c8e60a5ab8eb1df4f3091 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/shim/touch_zoom_rotate.js @@ -0,0 +1,108 @@ +// @flow + +import type {TouchZoomHandler, TouchRotateHandler} from '../touch_zoom_rotate'; +import type TapDragZoomHandler from '../tap_drag_zoom'; + +/** + * The `TouchZoomRotateHandler` allows the user to zoom and rotate the map by + * pinching on a touchscreen. + * + * They can zoom with one finger by double tapping and dragging. On the second tap, + * hold the finger down and drag up or down to zoom in or out. + */ +export default class TouchZoomRotateHandler { + + _el: HTMLElement; + _touchZoom: TouchZoomHandler; + _touchRotate: TouchRotateHandler; + _tapDragZoom: TapDragZoomHandler; + _rotationDisabled: boolean; + _enabled: boolean; + + /** + * @private + */ + constructor(el: HTMLElement, touchZoom: TouchZoomHandler, touchRotate: TouchRotateHandler, tapDragZoom: TapDragZoomHandler) { + this._el = el; + this._touchZoom = touchZoom; + this._touchRotate = touchRotate; + this._tapDragZoom = tapDragZoom; + this._rotationDisabled = false; + this._enabled = true; + } + + /** + * Enables the "pinch to rotate and zoom" interaction. + * + * @param {Object} [options] Options object. + * @param {string} [options.around] If "center" is passed, map will zoom around the center + * + * @example + * map.touchZoomRotate.enable(); + * @example + * map.touchZoomRotate.enable({ around: 'center' }); + */ + enable(options: ?{around?: 'center'}) { + this._touchZoom.enable(options); + if (!this._rotationDisabled) this._touchRotate.enable(options); + this._tapDragZoom.enable(); + this._el.classList.add('mapboxgl-touch-zoom-rotate'); + } + + /** + * Disables the "pinch to rotate and zoom" interaction. + * + * @example + * map.touchZoomRotate.disable(); + */ + disable() { + this._touchZoom.disable(); + this._touchRotate.disable(); + this._tapDragZoom.disable(); + this._el.classList.remove('mapboxgl-touch-zoom-rotate'); + } + + /** + * Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "pinch to rotate and zoom" interaction is enabled. + */ + isEnabled() { + return this._touchZoom.isEnabled() && + (this._rotationDisabled || this._touchRotate.isEnabled()) && + this._tapDragZoom.isEnabled(); + } + + /** + * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. + * + * @returns {boolean} //eslint-disable-line + */ + isActive() { + return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive(); + } + + /** + * Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" + * interaction enabled. + * + * @example + * map.touchZoomRotate.disableRotation(); + */ + disableRotation() { + this._rotationDisabled = true; + this._touchRotate.disable(); + } + + /** + * Enables the "pinch to rotate" interaction. + * + * @example + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enableRotation(); + */ + enableRotation() { + this._rotationDisabled = false; + if (this._touchZoom.isEnabled()) this._touchRotate.enable(); + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_drag_zoom.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_drag_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..d8bf435a2c5414fd3d23653b1f439e004765e65a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_drag_zoom.js @@ -0,0 +1,103 @@ +// @flow + +import {TapRecognizer, MAX_TAP_INTERVAL} from './tap_recognizer'; +import type Point from '@mapbox/point-geometry'; + +export default class TapDragZoomHandler { + + _enabled: boolean; + _active: boolean; + _swipePoint: Point; + _swipeTouch: number; + _tapTime: number; + _tap: TapRecognizer; + + constructor() { + + this._tap = new TapRecognizer({ + numTouches: 1, + numTaps: 1 + }); + + this.reset(); + } + + reset() { + this._active = false; + delete this._swipePoint; + delete this._swipeTouch; + delete this._tapTime; + this._tap.reset(); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + if (this._swipePoint) return; + + if (this._tapTime && e.timeStamp - this._tapTime > MAX_TAP_INTERVAL) { + this.reset(); + } + + if (!this._tapTime) { + this._tap.touchstart(e, points, mapTouches); + } else if (mapTouches.length > 0) { + this._swipePoint = points[0]; + this._swipeTouch = mapTouches[0].identifier; + } + + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._tapTime) { + this._tap.touchmove(e, points, mapTouches); + } else if (this._swipePoint) { + if (mapTouches[0].identifier !== this._swipeTouch) { + return; + } + + const newSwipePoint = points[0]; + const dist = newSwipePoint.y - this._swipePoint.y; + this._swipePoint = newSwipePoint; + + e.preventDefault(); + this._active = true; + + return { + zoomDelta: dist / 128 + }; + } + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._tapTime) { + const point = this._tap.touchend(e, points, mapTouches); + if (point) { + this._tapTime = e.timeStamp; + } + } else if (this._swipePoint) { + if (mapTouches.length === 0) { + this.reset(); + } + } + } + + touchcancel() { + this.reset(); + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_recognizer.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_recognizer.js new file mode 100644 index 0000000000000000000000000000000000000000..01e9dee629e36fe61af590d5e45733518aa3fa13 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_recognizer.js @@ -0,0 +1,133 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import {indexTouches} from './handler_util'; + +function getCentroid(points: Array) { + const sum = new Point(0, 0); + for (const point of points) { + sum._add(point); + } + return sum.div(points.length); +} + +export const MAX_TAP_INTERVAL = 500; +const MAX_TOUCH_TIME = 500; +const MAX_DIST = 30; + +export class SingleTapRecognizer { + + numTouches: number; + centroid: Point; + startTime: number; + aborted: boolean; + touches: { [number | string]: Point }; + + constructor(options: { numTouches: number }) { + this.reset(); + this.numTouches = options.numTouches; + } + + reset() { + delete this.centroid; + delete this.startTime; + delete this.touches; + this.aborted = false; + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + + if (this.centroid || mapTouches.length > this.numTouches) { + this.aborted = true; + } + if (this.aborted) { + return; + } + + if (this.startTime === undefined) { + this.startTime = e.timeStamp; + } + + if (mapTouches.length === this.numTouches) { + this.centroid = getCentroid(points); + this.touches = indexTouches(mapTouches, points); + } + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (this.aborted || !this.centroid) return; + + const newTouches = indexTouches(mapTouches, points); + for (const id in this.touches) { + const prevPos = this.touches[id]; + const pos = newTouches[id]; + if (!pos || pos.dist(prevPos) > MAX_DIST) { + this.aborted = true; + } + } + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) { + this.aborted = true; + } + + if (mapTouches.length === 0) { + const centroid = !this.aborted && this.centroid; + this.reset(); + if (centroid) return centroid; + } + } + +} + +export class TapRecognizer { + + singleTap: SingleTapRecognizer; + numTaps: number; + lastTime: number; + lastTap: Point; + count: number; + + constructor(options: { numTaps: number, numTouches: number }) { + this.singleTap = new SingleTapRecognizer(options); + this.numTaps = options.numTaps; + this.reset(); + } + + reset() { + this.lastTime = Infinity; + delete this.lastTap; + this.count = 0; + this.singleTap.reset(); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + this.singleTap.touchstart(e, points, mapTouches); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + this.singleTap.touchmove(e, points, mapTouches); + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + const tap = this.singleTap.touchend(e, points, mapTouches); + if (tap) { + const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL; + const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST; + + if (!soonEnough || !closeEnough) { + this.reset(); + } + + this.count++; + this.lastTime = e.timeStamp; + this.lastTap = tap; + + if (this.count === this.numTaps) { + this.reset(); + return tap; + } + } + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_zoom.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..1aee59d1e8835320d0e01b1f6e191b167798b6e2 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/tap_zoom.js @@ -0,0 +1,93 @@ +// @flow + +import {TapRecognizer} from './tap_recognizer'; +import type Point from '@mapbox/point-geometry'; +import type Map from '../map'; + +export default class TapZoomHandler { + + _enabled: boolean; + _active: boolean; + _zoomIn: TapRecognizer; + _zoomOut: TapRecognizer; + + constructor() { + this._zoomIn = new TapRecognizer({ + numTouches: 1, + numTaps: 2 + }); + + this._zoomOut = new TapRecognizer({ + numTouches: 2, + numTaps: 1 + }); + + this.reset(); + } + + reset() { + this._active = false; + this._zoomIn.reset(); + this._zoomOut.reset(); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + this._zoomIn.touchstart(e, points, mapTouches); + this._zoomOut.touchstart(e, points, mapTouches); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + this._zoomIn.touchmove(e, points, mapTouches); + this._zoomOut.touchmove(e, points, mapTouches); + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches); + const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches); + + if (zoomInPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map: Map) => map.easeTo({ + duration: 300, + zoom: map.getZoom() + 1, + around: map.unproject(zoomInPoint) + }, {originalEvent: e}) + }; + } else if (zoomOutPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map: Map) => map.easeTo({ + duration: 300, + zoom: map.getZoom() - 1, + around: map.unproject(zoomOutPoint) + }, {originalEvent: e}) + }; + } + } + + touchcancel() { + this.reset(); + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/touch_pan.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/touch_pan.js new file mode 100644 index 0000000000000000000000000000000000000000..6a879efb828143767a7bb3efc4166a76517045ca --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/touch_pan.js @@ -0,0 +1,101 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import {indexTouches} from './handler_util'; + +export default class TouchPanHandler { + + _enabled: boolean; + _active: boolean; + _touches: { [string | number]: Point }; + _minTouches: number; + _clickTolerance: number; + _sum: Point; + + constructor(options: { clickTolerance: number }) { + this._minTouches = 1; + this._clickTolerance = options.clickTolerance || 1; + this.reset(); + } + + reset() { + this._active = false; + this._touches = {}; + this._sum = new Point(0, 0); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + return this._calculateTransform(e, points, mapTouches); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._active || mapTouches.length < this._minTouches) return; + e.preventDefault(); + return this._calculateTransform(e, points, mapTouches); + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + this._calculateTransform(e, points, mapTouches); + + if (this._active && mapTouches.length < this._minTouches) { + this.reset(); + } + } + + touchcancel() { + this.reset(); + } + + _calculateTransform(e: TouchEvent, points: Array, mapTouches: Array) { + if (mapTouches.length > 0) this._active = true; + + const touches = indexTouches(mapTouches, points); + + const touchPointSum = new Point(0, 0); + const touchDeltaSum = new Point(0, 0); + let touchDeltaCount = 0; + + for (const identifier in touches) { + const point = touches[identifier]; + const prevPoint = this._touches[identifier]; + if (prevPoint) { + touchPointSum._add(point); + touchDeltaSum._add(point.sub(prevPoint)); + touchDeltaCount++; + touches[identifier] = point; + } + } + + this._touches = touches; + + if (touchDeltaCount < this._minTouches || !touchDeltaSum.mag()) return; + + const panDelta = touchDeltaSum.div(touchDeltaCount); + this._sum._add(panDelta); + if (this._sum.mag() < this._clickTolerance) return; + + const around = touchPointSum.div(touchDeltaCount); + + return { + around, + panDelta + }; + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler/touch_zoom_rotate.js b/node_modules/@plotly/mapbox-gl/src/ui/handler/touch_zoom_rotate.js new file mode 100644 index 0000000000000000000000000000000000000000..8e7b910c2058a65e9ad7167f90e69b0e5c92ee68 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler/touch_zoom_rotate.js @@ -0,0 +1,305 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import DOM from '../../util/dom'; + +class TwoTouchHandler { + + _enabled: boolean; + _active: boolean; + _firstTwoTouches: [number, number]; + _vector: Point; + _startVector: Point; + _aroundCenter: boolean; + + constructor() { + this.reset(); + } + + reset() { + this._active = false; + delete this._firstTwoTouches; + } + + _start(points: [Point, Point]) {} //eslint-disable-line + _move(points: [Point, Point], pinchAround: Point, e: TouchEvent) { return {}; } //eslint-disable-line + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + //console.log(e.target, e.targetTouches.length ? e.targetTouches[0].target : null); + //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined); + if (this._firstTwoTouches || mapTouches.length < 2) return; + + this._firstTwoTouches = [ + mapTouches[0].identifier, + mapTouches[1].identifier + ]; + + // implemented by child classes + this._start([points[0], points[1]]); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._firstTwoTouches) return; + + e.preventDefault(); + + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (!a || !b) return; + const pinchAround = this._aroundCenter ? null : a.add(b).div(2); + + // implemented by child classes + return this._move([a, b], pinchAround, e); + + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._firstTwoTouches) return; + + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (a && b) return; + + if (this._active) DOM.suppressClick(); + + this.reset(); + } + + touchcancel() { + this.reset(); + } + + enable(options: ?{around?: 'center'}) { + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} + +function getTouchById(mapTouches: Array, points: Array, identifier: number) { + for (let i = 0; i < mapTouches.length; i++) { + if (mapTouches[i].identifier === identifier) return points[i]; + } +} + +/* ZOOM */ + +const ZOOM_THRESHOLD = 0.1; + +function getZoomDelta(distance, lastDistance) { + return Math.log(distance / lastDistance) / Math.LN2; +} + +export class TouchZoomHandler extends TwoTouchHandler { + + _distance: number; + _startDistance: number; + + reset() { + super.reset(); + delete this._distance; + delete this._startDistance; + } + + _start(points: [Point, Point]) { + this._startDistance = this._distance = points[0].dist(points[1]); + } + + _move(points: [Point, Point], pinchAround: Point) { + const lastDistance = this._distance; + this._distance = points[0].dist(points[1]); + if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD) return; + this._active = true; + return { + zoomDelta: getZoomDelta(this._distance, lastDistance), + pinchAround + }; + } +} + +/* ROTATE */ + +const ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle + +function getBearingDelta(a, b) { + return a.angleWith(b) * 180 / Math.PI; +} + +export class TouchRotateHandler extends TwoTouchHandler { + _minDiameter: number; + + reset() { + super.reset(); + delete this._minDiameter; + delete this._startVector; + delete this._vector; + } + + _start(points: [Point, Point]) { + this._startVector = this._vector = points[0].sub(points[1]); + this._minDiameter = points[0].dist(points[1]); + } + + _move(points: [Point, Point], pinchAround: Point) { + const lastVector = this._vector; + this._vector = points[0].sub(points[1]); + + if (!this._active && this._isBelowThreshold(this._vector)) return; + this._active = true; + + return { + bearingDelta: getBearingDelta(this._vector, lastVector), + pinchAround + }; + } + + _isBelowThreshold(vector: Point) { + /* + * The threshold before a rotation actually happens is configured in + * pixels alongth circumference of the circle formed by the two fingers. + * This makes the threshold in degrees larger when the fingers are close + * together and smaller when the fingers are far apart. + * + * Use the smallest diameter from the whole gesture to reduce sensitivity + * when pinching in and out. + */ + + this._minDiameter = Math.min(this._minDiameter, vector.mag()); + const circumference = Math.PI * this._minDiameter; + const threshold = ROTATION_THRESHOLD / circumference * 360; + + const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector); + return Math.abs(bearingDeltaSinceStart) < threshold; + } +} + +/* PITCH */ + +function isVertical(vector) { + return Math.abs(vector.y) > Math.abs(vector.x); +} + +const ALLOWED_SINGLE_TOUCH_TIME = 100; + +/** + * The `TouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers. + */ +export class TouchPitchHandler extends TwoTouchHandler { + + _valid: boolean | void; + _firstMove: number; + _lastPoints: [Point, Point]; + + reset() { + super.reset(); + this._valid = undefined; + delete this._firstMove; + delete this._lastPoints; + } + + _start(points: [Point, Point]) { + this._lastPoints = points; + if (isVertical(points[0].sub(points[1]))) { + // fingers are more horizontal than vertical + this._valid = false; + + } + } + + _move(points: [Point, Point], center: Point, e: TouchEvent) { + const vectorA = points[0].sub(this._lastPoints[0]); + const vectorB = points[1].sub(this._lastPoints[1]); + + this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp); + if (!this._valid) return; + + this._lastPoints = points; + this._active = true; + const yDeltaAverage = (vectorA.y + vectorB.y) / 2; + const degreesPerPixelMoved = -0.5; + return { + pitchDelta: yDeltaAverage * degreesPerPixelMoved + }; + } + + gestureBeginsVertically(vectorA: Point, vectorB: Point, timeStamp: number) { + if (this._valid !== undefined) return this._valid; + + const threshold = 2; + const movedA = vectorA.mag() >= threshold; + const movedB = vectorB.mag() >= threshold; + + // neither finger has moved a meaningful amount, wait + if (!movedA && !movedB) return; + + // One finger has moved and the other has not. + // If enough time has passed, decide it is not a pitch. + if (!movedA || !movedB) { + if (this._firstMove === undefined) { + this._firstMove = timeStamp; + } + + if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) { + // still waiting for a movement from the second finger + return undefined; + } else { + return false; + } + } + + const isSameDirection = vectorA.y > 0 === vectorB.y > 0; + return isVertical(vectorA) && isVertical(vectorB) && isSameDirection; + } + + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is enabled. + * + * @memberof TouchPitchHandler + * @name isEnabled + * @instance + * @returns {boolean} `true` if the "drag to pitch" interaction is enabled. + */ + + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used. + * + * @memberof TouchPitchHandler + * @name isActive + * @instance + * @returns {boolean} `true` if the "drag to pitch" interaction is active. + */ + + /** + * Enables the "drag to pitch" interaction. + * + * @memberof TouchPitchHandler + * @name enable + * @instance + * @example + * map.touchPitch.enable(); + */ + + /** + * Disables the "drag to pitch" interaction. + * + * @memberof TouchPitchHandler + * @name disable + * @instance + * @example + * map.touchPitch.disable(); + */ +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler_inertia.js b/node_modules/@plotly/mapbox-gl/src/ui/handler_inertia.js new file mode 100644 index 0000000000000000000000000000000000000000..7c3fc13dfca4217ac111098a81c501ab6ba3f64a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler_inertia.js @@ -0,0 +1,158 @@ +// @flow + +import browser from '../util/browser'; +import type Map from './map'; +import {bezier, clamp, extend} from '../util/util'; +import Point from '@mapbox/point-geometry'; +import type {DragPanOptions} from './handler/shim/drag_pan'; + +const defaultInertiaOptions = { + linearity: 0.3, + easing: bezier(0, 0, 0.3, 1), +}; + +const defaultPanInertiaOptions = extend({ + deceleration: 2500, + maxSpeed: 1400 +}, defaultInertiaOptions); + +const defaultZoomInertiaOptions = extend({ + deceleration: 20, + maxSpeed: 1400 +}, defaultInertiaOptions); + +const defaultBearingInertiaOptions = extend({ + deceleration: 1000, + maxSpeed: 360 +}, defaultInertiaOptions); + +const defaultPitchInertiaOptions = extend({ + deceleration: 1000, + maxSpeed: 90 +}, defaultInertiaOptions); + +export type InertiaOptions = { + linearity: number; + easing: (t: number) => number; + deceleration: number; + maxSpeed: number; +}; + +export type InputEvent = MouseEvent | TouchEvent | KeyboardEvent | WheelEvent; + +export default class HandlerInertia { + _map: Map; + _inertiaBuffer: Array<{ time: number, settings: Object }>; + + constructor(map: Map) { + this._map = map; + this.clear(); + } + + clear() { + this._inertiaBuffer = []; + } + + record(settings: any) { + this._drainInertiaBuffer(); + this._inertiaBuffer.push({time: browser.now(), settings}); + } + + _drainInertiaBuffer() { + const inertia = this._inertiaBuffer, + now = browser.now(), + cutoff = 160; //msec + + while (inertia.length > 0 && now - inertia[0].time > cutoff) + inertia.shift(); + } + + _onMoveEnd(panInertiaOptions?: DragPanOptions) { + this._drainInertiaBuffer(); + if (this._inertiaBuffer.length < 2) { + return; + } + + const deltas = { + zoom: 0, + bearing: 0, + pitch: 0, + pan: new Point(0, 0), + pinchAround: undefined, + around: undefined + }; + + for (const {settings} of this._inertiaBuffer) { + deltas.zoom += settings.zoomDelta || 0; + deltas.bearing += settings.bearingDelta || 0; + deltas.pitch += settings.pitchDelta || 0; + if (settings.panDelta) deltas.pan._add(settings.panDelta); + if (settings.around) deltas.around = settings.around; + if (settings.pinchAround) deltas.pinchAround = settings.pinchAround; + } + + const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1]; + const duration = (lastEntry.time - this._inertiaBuffer[0].time); + + const easeOptions = {}; + + if (deltas.pan.mag()) { + const result = calculateEasing(deltas.pan.mag(), duration, extend({}, defaultPanInertiaOptions, panInertiaOptions || {})); + easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag()); + easeOptions.center = this._map.transform.center; + extendDuration(easeOptions, result); + } + + if (deltas.zoom) { + const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions); + easeOptions.zoom = this._map.transform.zoom + result.amount; + extendDuration(easeOptions, result); + } + + if (deltas.bearing) { + const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions); + easeOptions.bearing = this._map.transform.bearing + clamp(result.amount, -179, 179); + extendDuration(easeOptions, result); + } + + if (deltas.pitch) { + const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions); + easeOptions.pitch = this._map.transform.pitch + result.amount; + extendDuration(easeOptions, result); + } + + if (easeOptions.zoom || easeOptions.bearing) { + const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround; + easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter(); + } + + this.clear(); + return extend(easeOptions, { + noMoveStart: true + }); + + } +} + +// Unfortunately zoom, bearing, etc can't have different durations and easings so +// we need to choose one. We use the longest duration and it's corresponding easing. +function extendDuration(easeOptions, result) { + if (!easeOptions.duration || easeOptions.duration < result.duration) { + easeOptions.duration = result.duration; + easeOptions.easing = result.easing; + } +} + +function calculateEasing(amount, inertiaDuration: number, inertiaOptions) { + const {maxSpeed, linearity, deceleration} = inertiaOptions; + const speed = clamp( + amount * linearity / (inertiaDuration / 1000), + -maxSpeed, + maxSpeed); + const duration = Math.abs(speed) / (deceleration * linearity); + return { + easing: inertiaOptions.easing, + duration: duration * 1000, + amount: speed * (duration / 2) + }; +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/handler_manager.js b/node_modules/@plotly/mapbox-gl/src/ui/handler_manager.js new file mode 100644 index 0000000000000000000000000000000000000000..4b4d2d9f04692e1f866b426c25a10e4a6d92c5ca --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/handler_manager.js @@ -0,0 +1,531 @@ +// @flow + +import {Event} from '../util/evented'; +import DOM from '../util/dom'; +import type Map from './map'; +import HandlerInertia from './handler_inertia'; +import {MapEventHandler, BlockableMapEventHandler} from './handler/map_event'; +import BoxZoomHandler from './handler/box_zoom'; +import TapZoomHandler from './handler/tap_zoom'; +import {MousePanHandler, MouseRotateHandler, MousePitchHandler} from './handler/mouse'; +import TouchPanHandler from './handler/touch_pan'; +import {TouchZoomHandler, TouchRotateHandler, TouchPitchHandler} from './handler/touch_zoom_rotate'; +import KeyboardHandler from './handler/keyboard'; +import ScrollZoomHandler from './handler/scroll_zoom'; +import DoubleClickZoomHandler from './handler/shim/dblclick_zoom'; +import ClickZoomHandler from './handler/click_zoom'; +import TapDragZoomHandler from './handler/tap_drag_zoom'; +import DragPanHandler from './handler/shim/drag_pan'; +import DragRotateHandler from './handler/shim/drag_rotate'; +import TouchZoomRotateHandler from './handler/shim/touch_zoom_rotate'; +import {bindAll, extend} from '../util/util'; +import window from '../util/window'; +import Point from '@mapbox/point-geometry'; +import assert from 'assert'; + +export type InputEvent = MouseEvent | TouchEvent | KeyboardEvent | WheelEvent; + +const isMoving = p => p.zoom || p.drag || p.pitch || p.rotate; + +class RenderFrameEvent extends Event { + type: 'renderFrame'; + timeStamp: number; +} + +// Handlers interpret dom events and return camera changes that should be +// applied to the map (`HandlerResult`s). The camera changes are all deltas. +// The handler itself should have no knowledge of the map's current state. +// This makes it easier to merge multiple results and keeps handlers simpler. +// For example, if there is a mousedown and mousemove, the mousePan handler +// would return a `panDelta` on the mousemove. +export interface Handler { + enable(): void; + disable(): void; + isEnabled(): boolean; + isActive(): boolean; + + // `reset` can be called by the manager at any time and must reset everything to it's original state + reset(): void; + + // Handlers can optionally implement these methods. + // They are called with dom events whenever those dom evens are received. + +touchstart?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +touchmove?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +touchend?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +touchcancel?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +mousedown?: (e: MouseEvent, point: Point) => HandlerResult | void; + +mousemove?: (e: MouseEvent, point: Point) => HandlerResult | void; + +mouseup?: (e: MouseEvent, point: Point) => HandlerResult | void; + +dblclick?: (e: MouseEvent, point: Point) => HandlerResult | void; + +wheel?: (e: WheelEvent, point: Point) => HandlerResult | void; + +keydown?: (e: KeyboardEvent) => HandlerResult | void; + +keyup?: (e: KeyboardEvent) => HandlerResult | void; + + // `renderFrame` is the only non-dom event. It is called during render + // frames and can be used to smooth camera changes (see scroll handler). + +renderFrame?: () => HandlerResult | void; +} + +// All handler methods that are called with events can optionally return a `HandlerResult`. +export type HandlerResult = {| + panDelta?: Point, + zoomDelta?: number, + bearingDelta?: number, + pitchDelta?: number, + // the point to not move when changing the camera + around?: Point | null, + // same as above, except for pinch actions, which are given higher priority + pinchAround?: Point | null, + // A method that can fire a one-off easing by directly changing the map's camera. + cameraAnimation?: (map: Map) => any; + + // The last three properties are needed by only one handler: scrollzoom. + // The DOM event to be used as the `originalEvent` on any camera change events. + originalEvent?: any, + // Makes the manager trigger a frame, allowing the handler to return multiple results over time (see scrollzoom). + needsRenderFrame?: boolean, + // The camera changes won't get recorded for inertial zooming. + noInertia?: boolean +|}; + +function hasChange(result: HandlerResult) { + return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta; +} + +class HandlerManager { + _map: Map; + _el: HTMLElement; + _handlers: Array<{ handlerName: string, handler: Handler, allowed: any }>; + _eventsInProgress: Object; + _frameId: number; + _inertia: HandlerInertia; + _bearingSnap: number; + _handlersById: { [string]: Handler }; + _updatingCamera: boolean; + _changes: Array<[HandlerResult, Object, any]>; + _previousActiveHandlers: { [string]: Handler }; + _listeners: Array<[HTMLElement, string, void | {passive?: boolean, capture?: boolean}]>; + + constructor(map: Map, options: { interactive: boolean, pitchWithRotate: boolean, clickTolerance: number, bearingSnap: number}) { + this._map = map; + this._el = this._map.getCanvasContainer(); + this._handlers = []; + this._handlersById = {}; + this._changes = []; + + this._inertia = new HandlerInertia(map); + this._bearingSnap = options.bearingSnap; + this._previousActiveHandlers = {}; + + // Track whether map is currently moving, to compute start/move/end events + this._eventsInProgress = {}; + + this._addDefaultHandlers(options); + + bindAll(['handleEvent', 'handleWindowEvent'], this); + + const el = this._el; + + this._listeners = [ + // This needs to be `passive: true` so that a double tap fires two + // pairs of touchstart/end events in iOS Safari 13. If this is set to + // `passive: false` then the second pair of events is only fired if + // preventDefault() is called on the first touchstart. Calling preventDefault() + // undesirably prevents click events. + [el, 'touchstart', {passive: true}], + // This needs to be `passive: false` so that scrolls and pinches can be + // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12. + [el, 'touchmove', {passive: false}], + [el, 'touchend', undefined], + [el, 'touchcancel', undefined], + + [el, 'mousedown', undefined], + [el, 'mousemove', undefined], + [el, 'mouseup', undefined], + + // Bind window-level event listeners for move and up/end events. In the absence of + // the pointer capture API, which is not supported by all necessary platforms, + // window-level event listeners give us the best shot at capturing events that + // fall outside the map canvas element. Use `{capture: true}` for the move event + // to prevent map move events from being fired during a drag. + [window.document, 'mousemove', {capture: true}], + [window.document, 'mouseup', undefined], + + [el, 'mouseover', undefined], + [el, 'mouseout', undefined], + [el, 'dblclick', undefined], + [el, 'click', undefined], + + [el, 'keydown', {capture: false}], + [el, 'keyup', undefined], + + [el, 'wheel', {passive: false}], + [el, 'contextmenu', undefined], + + [window, 'blur', undefined] + ]; + + for (const [target, type, listenerOptions] of this._listeners) { + DOM.addEventListener(target, type, target === window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + + destroy() { + for (const [target, type, listenerOptions] of this._listeners) { + DOM.removeEventListener(target, type, target === window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + + _addDefaultHandlers(options: { interactive: boolean, pitchWithRotate: boolean, clickTolerance: number }) { + const map = this._map; + const el = map.getCanvasContainer(); + this._add('mapEvent', new MapEventHandler(map, options)); + + const boxZoom = map.boxZoom = new BoxZoomHandler(map, options); + this._add('boxZoom', boxZoom); + + const tapZoom = new TapZoomHandler(); + const clickZoom = new ClickZoomHandler(); + map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom); + this._add('tapZoom', tapZoom); + this._add('clickZoom', clickZoom); + + const tapDragZoom = new TapDragZoomHandler(); + this._add('tapDragZoom', tapDragZoom); + + const touchPitch = map.touchPitch = new TouchPitchHandler(); + this._add('touchPitch', touchPitch); + + const mouseRotate = new MouseRotateHandler(options); + const mousePitch = new MousePitchHandler(options); + map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch); + this._add('mouseRotate', mouseRotate, ['mousePitch']); + this._add('mousePitch', mousePitch, ['mouseRotate']); + + const mousePan = new MousePanHandler(options); + const touchPan = new TouchPanHandler(options); + map.dragPan = new DragPanHandler(el, mousePan, touchPan); + this._add('mousePan', mousePan); + this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']); + + const touchRotate = new TouchRotateHandler(); + const touchZoom = new TouchZoomHandler(); + map.touchZoomRotate = new TouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom); + this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']); + this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']); + + const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, this); + this._add('scrollZoom', scrollZoom, ['mousePan']); + + const keyboard = map.keyboard = new KeyboardHandler(); + this._add('keyboard', keyboard); + + this._add('blockableMapEvent', new BlockableMapEventHandler(map)); + + for (const name of ['boxZoom', 'doubleClickZoom', 'tapDragZoom', 'touchPitch', 'dragRotate', 'dragPan', 'touchZoomRotate', 'scrollZoom', 'keyboard']) { + if (options.interactive && (options: any)[name]) { + (map: any)[name].enable((options: any)[name]); + } + } + } + + _add(handlerName: string, handler: Handler, allowed?: Array) { + this._handlers.push({handlerName, handler, allowed}); + this._handlersById[handlerName] = handler; + } + + stop(allowEndAnimation: boolean) { + // do nothing if this method was triggered by a gesture update + if (this._updatingCamera) return; + + for (const {handler} of this._handlers) { + handler.reset(); + } + this._inertia.clear(); + this._fireEvents({}, {}, allowEndAnimation); + this._changes = []; + } + + isActive() { + for (const {handler} of this._handlers) { + if (handler.isActive()) return true; + } + return false; + } + + isZooming() { + return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming(); + } + isRotating() { + return !!this._eventsInProgress.rotate; + } + + isMoving() { + return Boolean(isMoving(this._eventsInProgress)) || this.isZooming(); + } + + _blockedByActive(activeHandlers: { [string]: Handler }, allowed: Array, myName: string) { + for (const name in activeHandlers) { + if (name === myName) continue; + if (!allowed || allowed.indexOf(name) < 0) { + return true; + } + } + return false; + } + + handleWindowEvent(e: InputEvent) { + this.handleEvent(e, `${e.type}Window`); + } + + _getMapTouches(touches: TouchList) { + const mapTouches = []; + for (const t of touches) { + const target = ((t.target: any): Node); + if (this._el.contains(target)) { + mapTouches.push(t); + } + } + return ((mapTouches: any): TouchList); + } + + handleEvent(e: InputEvent | RenderFrameEvent, eventName?: string) { + + this._updatingCamera = true; + assert(e.timeStamp !== undefined); + + const inputEvent = e.type === 'renderFrame' ? undefined : ((e: any): InputEvent); + + /* + * We don't call e.preventDefault() for any events by default. + * Handlers are responsible for calling it where necessary. + */ + + const mergedHandlerResult: HandlerResult = {needsRenderFrame: false}; + const eventsInProgress = {}; + const activeHandlers = {}; + + const mapTouches = e.touches ? this._getMapTouches(((e: any): TouchEvent).touches) : undefined; + const points = mapTouches ? DOM.touchPos(this._el, mapTouches) : DOM.mousePos(this._el, ((e: any): MouseEvent)); + + for (const {handlerName, handler, allowed} of this._handlers) { + if (!handler.isEnabled()) continue; + + let data: HandlerResult | void; + if (this._blockedByActive(activeHandlers, allowed, handlerName)) { + handler.reset(); + + } else { + if ((handler: any)[eventName || e.type]) { + data = (handler: any)[eventName || e.type](e, points, mapTouches); + this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent); + if (data && data.needsRenderFrame) { + this._triggerRenderFrame(); + } + } + } + + if (data || handler.isActive()) { + activeHandlers[handlerName] = handler; + } + } + + const deactivatedHandlers = {}; + for (const name in this._previousActiveHandlers) { + if (!activeHandlers[name]) { + deactivatedHandlers[name] = inputEvent; + } + } + this._previousActiveHandlers = activeHandlers; + + if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) { + this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]); + this._triggerRenderFrame(); + } + + if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) { + this._map._stop(true); + } + + this._updatingCamera = false; + + const {cameraAnimation} = mergedHandlerResult; + if (cameraAnimation) { + this._inertia.clear(); + this._fireEvents({}, {}, true); + this._changes = []; + cameraAnimation(this._map); + } + } + + mergeHandlerResult(mergedHandlerResult: HandlerResult, eventsInProgress: Object, handlerResult: HandlerResult, name: string, e?: InputEvent) { + if (!handlerResult) return; + + extend(mergedHandlerResult, handlerResult); + + const eventData = {handlerName: name, originalEvent: handlerResult.originalEvent || e}; + + // track which handler changed which camera property + if (handlerResult.zoomDelta !== undefined) { + eventsInProgress.zoom = eventData; + } + if (handlerResult.panDelta !== undefined) { + eventsInProgress.drag = eventData; + } + if (handlerResult.pitchDelta !== undefined) { + eventsInProgress.pitch = eventData; + } + if (handlerResult.bearingDelta !== undefined) { + eventsInProgress.rotate = eventData; + } + + } + + _applyChanges() { + const combined = {}; + const combinedEventsInProgress = {}; + const combinedDeactivatedHandlers = {}; + + for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) { + + if (change.panDelta) combined.panDelta = (combined.panDelta || new Point(0, 0))._add(change.panDelta); + if (change.zoomDelta) combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta; + if (change.bearingDelta) combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta; + if (change.pitchDelta) combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta; + if (change.around !== undefined) combined.around = change.around; + if (change.pinchAround !== undefined) combined.pinchAround = change.pinchAround; + if (change.noInertia) combined.noInertia = change.noInertia; + + extend(combinedEventsInProgress, eventsInProgress); + extend(combinedDeactivatedHandlers, deactivatedHandlers); + } + + this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers); + this._changes = []; + } + + _updateMapTransform(combinedResult: any, combinedEventsInProgress: Object, deactivatedHandlers: Object) { + + const map = this._map; + const tr = map.transform; + + if (!hasChange(combinedResult)) { + return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + + let {panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround} = combinedResult; + + if (pinchAround !== undefined) { + around = pinchAround; + } + + // stop any ongoing camera animations (easeTo, flyTo) + map._stop(true); + + around = around || map.transform.centerPoint; + const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around); + if (bearingDelta) tr.bearing += bearingDelta; + if (pitchDelta) tr.pitch += pitchDelta; + if (zoomDelta) tr.zoom += zoomDelta; + tr.setLocationAtPoint(loc, around); + + this._map._update(); + if (!combinedResult.noInertia) this._inertia.record(combinedResult); + this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + + } + + _fireEvents(newEventsInProgress: { [string]: Object }, deactivatedHandlers: Object, allowEndAnimation: boolean) { + + const wasMoving = isMoving(this._eventsInProgress); + const nowMoving = isMoving(newEventsInProgress); + + const startEvents = {}; + + for (const eventName in newEventsInProgress) { + const {originalEvent} = newEventsInProgress[eventName]; + if (!this._eventsInProgress[eventName]) { + startEvents[`${eventName}start`] = originalEvent; + } + this._eventsInProgress[eventName] = newEventsInProgress[eventName]; + } + + // fire start events only after this._eventsInProgress has been updated + if (!wasMoving && nowMoving) { + this._fireEvent('movestart', nowMoving.originalEvent); + } + + for (const name in startEvents) { + this._fireEvent(name, startEvents[name]); + } + + if (nowMoving) { + this._fireEvent('move', nowMoving.originalEvent); + } + + for (const eventName in newEventsInProgress) { + const {originalEvent} = newEventsInProgress[eventName]; + this._fireEvent(eventName, originalEvent); + } + + const endEvents = {}; + + let originalEndEvent; + for (const eventName in this._eventsInProgress) { + const {handlerName, originalEvent} = this._eventsInProgress[eventName]; + if (!this._handlersById[handlerName].isActive()) { + delete this._eventsInProgress[eventName]; + originalEndEvent = deactivatedHandlers[handlerName] || originalEvent; + endEvents[`${eventName}end`] = originalEndEvent; + } + } + + for (const name in endEvents) { + this._fireEvent(name, endEvents[name]); + } + + const stillMoving = isMoving(this._eventsInProgress); + if (allowEndAnimation && (wasMoving || nowMoving) && !stillMoving) { + this._updatingCamera = true; + const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions); + + const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap; + + if (inertialEase) { + if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) { + inertialEase.bearing = 0; + } + this._map.easeTo(inertialEase, {originalEvent: originalEndEvent}); + } else { + this._map.fire(new Event('moveend', {originalEvent: originalEndEvent})); + if (shouldSnapToNorth(this._map.getBearing())) { + this._map.resetNorth(); + } + } + this._updatingCamera = false; + } + + } + + _fireEvent(type: string, e: *) { + this._map.fire(new Event(type, e ? {originalEvent: e} : {})); + } + + _requestFrame() { + this._map.triggerRepaint(); + return this._map._renderTaskQueue.add(timeStamp => { + delete this._frameId; + this.handleEvent(new RenderFrameEvent('renderFrame', {timeStamp})); + this._applyChanges(); + }); + } + + _triggerRenderFrame() { + if (this._frameId === undefined) { + this._frameId = this._requestFrame(); + } + } + +} + +export default HandlerManager; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/hash.js b/node_modules/@plotly/mapbox-gl/src/ui/hash.js new file mode 100644 index 0000000000000000000000000000000000000000..82d98153b518626c241309031d8e415d955c5e41 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/hash.js @@ -0,0 +1,148 @@ +// @flow + +import {bindAll} from '../util/util'; +import window from '../util/window'; +import throttle from '../util/throttle'; + +import type Map from './map'; + +/* + * Adds the map's position to its page's location hash. + * Passed as an option to the map object. + * + * @returns {Hash} `this` + */ +class Hash { + _map: Map; + _updateHash: () => ?TimeoutID; + _hashName: ?string; + + constructor(hashName: ?string) { + this._hashName = hashName && encodeURIComponent(hashName); + bindAll([ + '_getCurrentHash', + '_onHashChange', + '_updateHash' + ], this); + + // Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds. + this._updateHash = throttle(this._updateHashUnthrottled.bind(this), 30 * 1000 / 100); + } + + /* + * Map element to listen for coordinate changes + * + * @param {Object} map + * @returns {Hash} `this` + */ + addTo(map: Map) { + this._map = map; + window.addEventListener('hashchange', this._onHashChange, false); + this._map.on('moveend', this._updateHash); + return this; + } + + /* + * Removes hash + * + * @returns {Popup} `this` + */ + remove() { + window.removeEventListener('hashchange', this._onHashChange, false); + this._map.off('moveend', this._updateHash); + clearTimeout(this._updateHash()); + + delete this._map; + return this; + } + + getHashString(mapFeedback?: boolean) { + const center = this._map.getCenter(), + zoom = Math.round(this._map.getZoom() * 100) / 100, + // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px + precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), + m = Math.pow(10, precision), + lng = Math.round(center.lng * m) / m, + lat = Math.round(center.lat * m) / m, + bearing = this._map.getBearing(), + pitch = this._map.getPitch(); + let hash = ''; + if (mapFeedback) { + // new map feedback site has some constraints that don't allow + // us to use the same hash format as we do for the Map hash option. + hash += `/${lng}/${lat}/${zoom}`; + } else { + hash += `${zoom}/${lat}/${lng}`; + } + + if (bearing || pitch) hash += (`/${Math.round(bearing * 10) / 10}`); + if (pitch) hash += (`/${Math.round(pitch)}`); + + if (this._hashName) { + const hashName = this._hashName; + let found = false; + const parts = window.location.hash.slice(1).split('&').map(part => { + const key = part.split('=')[0]; + if (key === hashName) { + found = true; + return `${key}=${hash}`; + } + return part; + }).filter(a => a); + if (!found) { + parts.push(`${hashName}=${hash}`); + } + return `#${parts.join('&')}`; + } + + return `#${hash}`; + } + + _getCurrentHash() { + // Get the current hash from location, stripped from its number sign + const hash = window.location.hash.replace('#', ''); + if (this._hashName) { + // Split the parameter-styled hash into parts and find the value we need + let keyval; + hash.split('&').map( + part => part.split('=') + ).forEach(part => { + if (part[0] === this._hashName) { + keyval = part; + } + }); + return (keyval ? keyval[1] || '' : '').split('/'); + } + return hash.split('/'); + } + + _onHashChange() { + const loc = this._getCurrentHash(); + if (loc.length >= 3 && !loc.some(v => isNaN(v))) { + const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing(); + this._map.jumpTo({ + center: [+loc[2], +loc[1]], + zoom: +loc[0], + bearing, + pitch: +(loc[4] || 0) + }); + return true; + } + return false; + } + + _updateHashUnthrottled() { + // Replace if already present, else append the updated hash string + const location = window.location.href.replace(/(#.+)?$/, this.getHashString()); + try { + window.history.replaceState(window.history.state, null, location); + } catch (SecurityError) { + // IE11 does not allow this if the page is within an iframe created + // with iframe.contentWindow.document.write(...). + // https://github.com/mapbox/mapbox-gl-js/issues/7410 + } + } + +} + +export default Hash; diff --git a/node_modules/@plotly/mapbox-gl/src/ui/map.js b/node_modules/@plotly/mapbox-gl/src/ui/map.js new file mode 100644 index 0000000000000000000000000000000000000000..21d2d77dd1aeb1890f7bde702ed46487eb15eb3b --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/map.js @@ -0,0 +1,2874 @@ +// @flow + +import {version} from '../../package.json'; +import {extend, bindAll, warnOnce, uniqueId} from '../util/util'; +import browser from '../util/browser'; +import window from '../util/window'; +const {HTMLImageElement, HTMLElement, ImageBitmap} = window; +import DOM from '../util/dom'; +import {getImage, getJSON, ResourceType} from '../util/ajax'; +import {RequestManager} from '../util/mapbox'; +import Style from '../style/style'; +import EvaluationParameters from '../style/evaluation_parameters'; +import Painter from '../render/painter'; +import Transform from '../geo/transform'; +import Hash from './hash'; +import HandlerManager from './handler_manager'; +import Camera from './camera'; +import LngLat from '../geo/lng_lat'; +import LngLatBounds from '../geo/lng_lat_bounds'; +import Point from '@mapbox/point-geometry'; +import AttributionControl from './control/attribution_control'; +import LogoControl from './control/logo_control'; +import isSupported from '@mapbox/mapbox-gl-supported'; +import {RGBAImage} from '../util/image'; +import {Event, ErrorEvent} from '../util/evented'; +import {MapMouseEvent} from './events'; +import TaskQueue from '../util/task_queue'; +import webpSupported from '../util/webp_supported'; +import {PerformanceMarkers, PerformanceUtils} from '../util/performance'; + +import {setCacheLimits} from '../util/tile_request_cache'; + +import type {PointLike} from '@mapbox/point-geometry'; +import type {RequestTransformFunction} from '../util/mapbox'; +import type {LngLatLike} from '../geo/lng_lat'; +import type {LngLatBoundsLike} from '../geo/lng_lat_bounds'; +import type {StyleOptions, StyleSetterOptions} from '../style/style'; +import type {MapEvent, MapDataEvent} from './events'; +import type {CustomLayerInterface} from '../style/style_layer/custom_style_layer'; +import type {StyleImageInterface, StyleImageMetadata} from '../style/style_image'; + +import type ScrollZoomHandler from './handler/scroll_zoom'; +import type BoxZoomHandler from './handler/box_zoom'; +import type {TouchPitchHandler} from './handler/touch_zoom_rotate'; +import type DragRotateHandler from './handler/shim/drag_rotate'; +import type DragPanHandler, {DragPanOptions} from './handler/shim/drag_pan'; +import type KeyboardHandler from './handler/keyboard'; +import type DoubleClickZoomHandler from './handler/shim/dblclick_zoom'; +import type TouchZoomRotateHandler from './handler/shim/touch_zoom_rotate'; +import defaultLocale from './default_locale'; +import type {TaskID} from '../util/task_queue'; +import type {Cancelable} from '../types/cancelable'; +import type { + LayerSpecification, + FilterSpecification, + StyleSpecification, + LightSpecification, + SourceSpecification +} from '../style-spec/types'; + +type ControlPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; +/* eslint-disable no-use-before-define */ +type IControl = { + onAdd(map: Map): HTMLElement; + onRemove(map: Map): void; + + +getDefaultPosition?: () => ControlPosition; +} +/* eslint-enable no-use-before-define */ + +type MapOptions = { + hash?: boolean | string, + interactive?: boolean, + container: HTMLElement | string, + bearingSnap?: number, + attributionControl?: boolean, + customAttribution?: string | Array, + logoPosition?: ControlPosition, + failIfMajorPerformanceCaveat?: boolean, + preserveDrawingBuffer?: boolean, + antialias?: boolean, + refreshExpiredTiles?: boolean, + maxBounds?: LngLatBoundsLike, + scrollZoom?: boolean, + minZoom?: ?number, + maxZoom?: ?number, + minPitch?: ?number, + maxPitch?: ?number, + boxZoom?: boolean, + dragRotate?: boolean, + dragPan?: DragPanOptions, + keyboard?: boolean, + doubleClickZoom?: boolean, + touchZoomRotate?: boolean, + touchPitch?: boolean, + trackResize?: boolean, + center?: LngLatLike, + zoom?: number, + bearing?: number, + pitch?: number, + renderWorldCopies?: boolean, + maxTileCacheSize?: number, + transformRequest?: RequestTransformFunction, + accessToken: string, + locale?: Object +}; + +const defaultMinZoom = -2; +const defaultMaxZoom = 22; + +// the default values, but also the valid range +const defaultMinPitch = 0; +const defaultMaxPitch = 60; + +const defaultOptions = { + center: [0, 0], + zoom: 0, + bearing: 0, + pitch: 0, + + minZoom: defaultMinZoom, + maxZoom: defaultMaxZoom, + + minPitch: defaultMinPitch, + maxPitch: defaultMaxPitch, + + interactive: true, + scrollZoom: true, + boxZoom: true, + dragRotate: true, + dragPan: true, + keyboard: true, + doubleClickZoom: true, + touchZoomRotate: true, + touchPitch: true, + + bearingSnap: 7, + clickTolerance: 3, + pitchWithRotate: true, + + hash: false, + attributionControl: true, + + failIfMajorPerformanceCaveat: false, + preserveDrawingBuffer: false, + trackResize: true, + renderWorldCopies: true, + refreshExpiredTiles: true, + maxTileCacheSize: null, + localIdeographFontFamily: 'sans-serif', + transformRequest: null, + accessToken: null, + fadeDuration: 300, + crossSourceCollisions: true +}; + +/** + * The `Map` object represents the map on your page. It exposes methods + * and properties that enable you to programmatically change the map, + * and fires events as users interact with it. + * + * You create a `Map` by specifying a `container` and other options. + * Then Mapbox GL JS initializes the map on the page and returns your `Map` + * object. + * + * @extends Evented + * @param {Object} options + * @param {HTMLElement|string} options.container The HTML element in which Mapbox GL JS will render the map, or the element's string `id`. The specified element must have no children. + * @param {number} [options.minZoom=0] The minimum zoom level of the map (0-24). + * @param {number} [options.maxZoom=22] The maximum zoom level of the map (0-24). + * @param {number} [options.minPitch=0] The minimum pitch of the map (0-60). + * @param {number} [options.maxPitch=60] The maximum pitch of the map (0-60). + * @param {Object|string} [options.style] The map's Mapbox style. This must be an a JSON object conforming to + * the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to + * such JSON. + * + * To load a style from the Mapbox API, you can use a URL of the form `mapbox://styles/:owner/:style`, + * where `:owner` is your Mapbox account name and `:style` is the style ID. Or you can use one of the following + * [the predefined Mapbox styles](https://www.mapbox.com/maps/): + * + * * `mapbox://styles/mapbox/streets-v11` + * * `mapbox://styles/mapbox/outdoors-v11` + * * `mapbox://styles/mapbox/light-v10` + * * `mapbox://styles/mapbox/dark-v10` + * * `mapbox://styles/mapbox/satellite-v9` + * * `mapbox://styles/mapbox/satellite-streets-v11` + * * `mapbox://styles/mapbox/navigation-preview-day-v4` + * * `mapbox://styles/mapbox/navigation-preview-night-v4` + * * `mapbox://styles/mapbox/navigation-guidance-day-v4` + * * `mapbox://styles/mapbox/navigation-guidance-night-v4` + * + * Tilesets hosted with Mapbox can be style-optimized if you append `?optimize=true` to the end of your style URL, like `mapbox://styles/mapbox/streets-v11?optimize=true`. + * Learn more about style-optimized vector tiles in our [API documentation](https://www.mapbox.com/api-documentation/maps/#retrieve-tiles). + * + * @param {(boolean|string)} [options.hash=false] If `true`, the map's position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL. + * For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`. + * An additional string may optionally be provided to indicate a parameter-styled hash, + * e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where foo + * is a custom parameter and bar is an arbitrary hash distinct from the map hash. + * @param {boolean} [options.interactive=true] If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction. + * @param {number} [options.bearingSnap=7] The threshold, measured in degrees, that determines when the map's + * bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates + * the map within 7 degrees of north, the map will automatically snap to exact north. + * @param {boolean} [options.pitchWithRotate=true] If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled. + * @param {number} [options.clickTolerance=3] The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag). + * @param {boolean} [options.attributionControl=true] If `true`, an {@link AttributionControl} will be added to the map. + * @param {string | Array} [options.customAttribution] String or strings to show in an {@link AttributionControl}. Only applicable if `options.attributionControl` is `true`. + * @param {string} [options.logoPosition='bottom-left'] A string representing the position of the Mapbox wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, `bottom-right`. + * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`, map creation will fail if the performance of Mapbox + * GL JS would be dramatically worse than expected (i.e. a software renderer would be used). + * @param {boolean} [options.preserveDrawingBuffer=false] If `true`, the map's canvas can be exported to a PNG using `map.getCanvas().toDataURL()`. This is `false` by default as a performance optimization. + * @param {boolean} [options.antialias] If `true`, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this is `false` by default as a performance optimization. + * @param {boolean} [options.refreshExpiredTiles=true] If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers. + * @param {LngLatBoundsLike} [options.maxBounds] If set, the map will be constrained to the given bounds. + * @param {boolean|Object} [options.scrollZoom=true] If `true`, the "scroll to zoom" interaction is enabled. An `Object` value is passed as options to {@link ScrollZoomHandler#enable}. + * @param {boolean} [options.boxZoom=true] If `true`, the "box zoom" interaction is enabled (see {@link BoxZoomHandler}). + * @param {boolean} [options.dragRotate=true] If `true`, the "drag to rotate" interaction is enabled (see {@link DragRotateHandler}). + * @param {boolean|Object} [options.dragPan=true] If `true`, the "drag to pan" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler#enable}. + * @param {boolean} [options.keyboard=true] If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}). + * @param {boolean} [options.doubleClickZoom=true] If `true`, the "double click to zoom" interaction is enabled (see {@link DoubleClickZoomHandler}). + * @param {boolean|Object} [options.touchZoomRotate=true] If `true`, the "pinch to rotate and zoom" interaction is enabled. An `Object` value is passed as options to {@link TouchZoomRotateHandler#enable}. + * @param {boolean|Object} [options.touchPitch=true] If `true`, the "drag to pitch" interaction is enabled. An `Object` value is passed as options to {@link TouchPitchHandler#enable}. + * @param {boolean} [options.trackResize=true] If `true`, the map will automatically resize when the browser window resizes. + * @param {LngLatLike} [options.center=[0, 0]] The inital geographical centerpoint of the map. If `center` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `[0, 0]` Note: Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON. + * @param {number} [options.zoom=0] The initial zoom level of the map. If `zoom` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`. + * @param {number} [options.bearing=0] The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`. + * @param {number} [options.pitch=0] The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-60). If `pitch` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`. + * @param {LngLatBoundsLike} [options.bounds] The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options. + * @param {Object} [options.fitBoundsOptions] A {@link Map#fitBounds} options object to use _only_ when fitting the initial `bounds` provided above. + * @param {boolean} [options.renderWorldCopies=true] If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @param {number} [options.maxTileCacheSize=null] The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport. + * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS + * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges. + * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). + * Set to `false`, to enable font settings from the map's style for these glyph ranges. Note that [Mapbox Studio](https://studio.mapbox.com/) sets this value to `false` by default. + * The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See [Use locally generated ideographs](https://www.mapbox.com/mapbox-gl-js/example/local-ideographs).) + * @param {RequestTransformFunction} [options.transformRequest=null] A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. + * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties. + * @param {boolean} [options.collectResourceTiming=false] If `true`, Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a `resourceTiming` property of relevant `data` events. + * @param {number} [options.fadeDuration=300] Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading. + * @param {boolean} [options.crossSourceCollisions=true] If `true`, symbols from multiple sources can collide with each other during collision detection. If `false`, collision detection is run separately for the symbols in each source. + * @param {string} [options.accessToken=null] If specified, map will use this token instead of the one defined in mapboxgl.accessToken. + * @param {Object} [options.locale=null] A patch to apply to the default localization table for UI strings, e.g. control tooltips. The `locale` object maps namespaced UI string IDs to translated strings in the target language; see `src/ui/default_locale.js` for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table). + * @example + * var map = new mapboxgl.Map({ + * container: 'map', + * center: [-122.420679, 37.772537], + * zoom: 13, + * style: style_object, + * hash: true, + * transformRequest: (url, resourceType)=> { + * if(resourceType === 'Source' && url.startsWith('http://myHost')) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true}, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * }); + * @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/) + */ +class Map extends Camera { + style: Style; + painter: Painter; + handlers: HandlerManager; + + _container: HTMLElement; + _missingCSSCanary: HTMLElement; + _canvasContainer: HTMLElement; + _controlContainer: HTMLElement; + _controlPositions: {[_: string]: HTMLElement}; + _interactive: ?boolean; + _showTileBoundaries: ?boolean; + _showCollisionBoxes: ?boolean; + _showPadding: ?boolean; + _showOverdrawInspector: boolean; + _repaint: ?boolean; + _vertices: ?boolean; + _canvas: HTMLCanvasElement; + _maxTileCacheSize: number; + _frame: ?Cancelable; + _styleDirty: ?boolean; + _sourcesDirty: ?boolean; + _placementDirty: ?boolean; + _loaded: boolean; + // accounts for placement finishing as well + _fullyLoaded: boolean; + _trackResize: boolean; + _preserveDrawingBuffer: boolean; + _failIfMajorPerformanceCaveat: boolean; + _antialias: boolean; + _refreshExpiredTiles: boolean; + _hash: Hash; + _delegatedListeners: any; + _fadeDuration: number; + _crossSourceCollisions: boolean; + _crossFadingFactor: number; + _collectResourceTiming: boolean; + _renderTaskQueue: TaskQueue; + _controls: Array; + _mapId: number; + _localIdeographFontFamily: string; + _requestManager: RequestManager; + _locale: Object; + _removed: boolean; + _clickTolerance: number; + + /** + * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad. + * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section. + */ + scrollZoom: ScrollZoomHandler; + + /** + * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed. + * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section. + */ + boxZoom: BoxZoomHandler; + + /** + * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right + * mouse button or with the Control key pressed. Find more details and examples using `dragRotate` + * in the {@link DragRotateHandler} section. + */ + dragRotate: DragRotateHandler; + + /** + * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture. + * Find more details and examples using `dragPan` in the {@link DragPanHandler} section. + */ + dragPan: DragPanHandler; + + /** + * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard + * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section. + */ + keyboard: KeyboardHandler; + + /** + * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking. + * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section. + */ + doubleClickZoom: DoubleClickZoomHandler; + + /** + * The map's {@link TouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures. + * Find more details and examples using `touchZoomRotate` in the {@link TouchZoomRotateHandler} section. + */ + touchZoomRotate: TouchZoomRotateHandler; + + /** + * The map's {@link TouchPitchHandler}, which allows the user to pitch the map with touch gestures. + * Find more details and examples using `touchPitch` in the {@link TouchPitchHandler} section. + */ + touchPitch: TouchPitchHandler; + + constructor(options: MapOptions) { + PerformanceUtils.mark(PerformanceMarkers.create); + + options = extend({}, defaultOptions, options); + + if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) { + throw new Error(`maxZoom must be greater than or equal to minZoom`); + } + + if (options.minPitch != null && options.maxPitch != null && options.minPitch > options.maxPitch) { + throw new Error(`maxPitch must be greater than or equal to minPitch`); + } + + if (options.minPitch != null && options.minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + + if (options.maxPitch != null && options.maxPitch > defaultMaxPitch) { + throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`); + } + + const transform = new Transform(options.minZoom, options.maxZoom, options.minPitch, options.maxPitch, options.renderWorldCopies); + super(transform, options); + + this._interactive = options.interactive; + this._maxTileCacheSize = options.maxTileCacheSize; + this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat; + this._preserveDrawingBuffer = options.preserveDrawingBuffer; + this._antialias = options.antialias; + this._trackResize = options.trackResize; + this._bearingSnap = options.bearingSnap; + this._refreshExpiredTiles = options.refreshExpiredTiles; + this._fadeDuration = options.fadeDuration; + this._crossSourceCollisions = options.crossSourceCollisions; + this._crossFadingFactor = 1; + this._collectResourceTiming = options.collectResourceTiming; + this._renderTaskQueue = new TaskQueue(); + this._controls = []; + this._mapId = uniqueId(); + this._locale = extend({}, defaultLocale, options.locale); + this._clickTolerance = options.clickTolerance; + + this._requestManager = new RequestManager(options.transformRequest, options.accessToken); + + if (typeof options.container === 'string') { + this._container = window.document.getElementById(options.container); + if (!this._container) { + throw new Error(`Container '${options.container}' not found.`); + } + } else if (options.container instanceof HTMLElement) { + this._container = options.container; + } else { + throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`); + } + + if (options.maxBounds) { + this.setMaxBounds(options.maxBounds); + } + + bindAll([ + '_onWindowOnline', + '_onWindowResize', + '_onMapScroll', + '_contextLost', + '_contextRestored' + ], this); + + this._setupContainer(); + this._setupPainter(); + if (this.painter === undefined) { + throw new Error(`Failed to initialize WebGL.`); + } + + this.on('move', () => this._update(false)); + this.on('moveend', () => this._update(false)); + this.on('zoom', () => this._update(true)); + + if (typeof window !== 'undefined') { + window.addEventListener('online', this._onWindowOnline, false); + window.addEventListener('resize', this._onWindowResize, false); + window.addEventListener('orientationchange', this._onWindowResize, false); + } + + this.handlers = new HandlerManager(this, options); + + const hashName = (typeof options.hash === 'string' && options.hash) || undefined; + this._hash = options.hash && (new Hash(hashName)).addTo(this); + // don't set position from options if set through hash + if (!this._hash || !this._hash._onHashChange()) { + this.jumpTo({ + center: options.center, + zoom: options.zoom, + bearing: options.bearing, + pitch: options.pitch + }); + + if (options.bounds) { + this.resize(); + this.fitBounds(options.bounds, extend({}, options.fitBoundsOptions, {duration: 0})); + } + } + + this.resize(); + + this._localIdeographFontFamily = options.localIdeographFontFamily; + if (options.style) this.setStyle(options.style, {localIdeographFontFamily: options.localIdeographFontFamily}); + + if (options.attributionControl) + this.addControl(new AttributionControl({customAttribution: options.customAttribution})); + + this.addControl(new LogoControl(), options.logoPosition); + + this.on('style.load', () => { + if (this.transform.unmodified) { + this.jumpTo((this.style.stylesheet: any)); + } + }); + this.on('data', (event: MapDataEvent) => { + this._update(event.dataType === 'style'); + this.fire(new Event(`${event.dataType}data`, event)); + }); + this.on('dataloading', (event: MapDataEvent) => { + this.fire(new Event(`${event.dataType}dataloading`, event)); + }); + } + + /* + * Returns a unique number for this map instance which is used for the MapLoadEvent + * to make sure we only fire one event per instantiated map object. + * @private + * @returns {number} + */ + _getMapId() { + return this._mapId; + } + + /** + * Adds an {@link IControl} to the map, calling `control.onAdd(this)`. + * + * @param {IControl} control The {@link IControl} to add. + * @param {string} [position] position on the map to which the control will be added. + * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`. + * @returns {Map} `this` + * @example + * // Add zoom and rotation controls to the map. + * map.addControl(new mapboxgl.NavigationControl()); + * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/) + */ + addControl(control: IControl, position?: ControlPosition) { + if (position === undefined) { + if (control.getDefaultPosition) { + position = control.getDefaultPosition(); + } else { + position = 'top-right'; + } + } + if (!control || !control.onAdd) { + return this.fire(new ErrorEvent(new Error( + 'Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const controlElement = control.onAdd(this); + this._controls.push(control); + + const positionContainer = this._controlPositions[position]; + if (position.indexOf('bottom') !== -1) { + positionContainer.insertBefore(controlElement, positionContainer.firstChild); + } else { + positionContainer.appendChild(controlElement); + } + return this; + } + + /** + * Removes the control from the map. + * + * @param {IControl} control The {@link IControl} to remove. + * @returns {Map} `this` + * @example + * // Define a new navigation control. + * var navigation = new mapboxgl.NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Remove zoom and rotation controls from the map. + * map.removeControl(navigation); + */ + removeControl(control: IControl) { + if (!control || !control.onRemove) { + return this.fire(new ErrorEvent(new Error( + 'Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const ci = this._controls.indexOf(control); + if (ci > -1) this._controls.splice(ci, 1); + control.onRemove(this); + return this; + } + + /** + * Checks if a control exists on the map. + * + * @param {IControl} control The {@link IControl} to check. + * @returns {boolean} True if map contains control. + * @example + * // Define a new navigation control. + * var navigation = new mapboxgl.NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Check that the navigation control exists on the map. + * map.hasControl(navigation); + */ + hasControl(control: IControl) { + return this._controls.indexOf(control) > -1; + } + + /** + * Resizes the map according to the dimensions of its + * `container` element. + * + * Checks if the map container size changed and updates the map if it has changed. + * This method must be called after the map's `container` is resized programmatically + * or when the map is shown after being initially hidden with CSS. + * + * @param eventData Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend` + * events that get triggered as a result of resize. This can be useful for differentiating the + * source of an event (for example, user-initiated or programmatically-triggered events). + * @returns {Map} `this` + * @example + * // Resize the map when the map container is shown + * // after being initially hidden with CSS. + * var mapDiv = document.getElementById('map'); + * if (mapDiv.style.visibility === true) map.resize(); + */ + resize(eventData?: Object) { + const [width, height] = this._containerDimensions(); + + // do nothing if container remained the same size + if (width === this.transform.width && height === this.transform.height) return this; + + this._resizeCanvas(width, height); + this.transform.resize(width, height); + this.painter.resize(width, height); + + const fireMoving = !this._moving; + if (fireMoving) { + this.fire(new Event('movestart', eventData)) + .fire(new Event('move', eventData)); + } + + this.fire(new Event('resize', eventData)); + + if (fireMoving) this.fire(new Event('moveend', eventData)); + + return this; + } + + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns {LngLatBounds} The geographical bounds of the map as {@link LngLatBounds}. + * @example + * var bounds = map.getBounds(); + */ + getBounds(): LngLatBounds { + return this.transform.getBounds(); + } + + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns The map object. + * @example + * var maxBounds = map.getMaxBounds(); + */ + getMaxBounds(): LngLatBounds | null { + return this.transform.getMaxBounds(); + } + + /** + * Sets or clears the map's geographical bounds. + * + * Pan and zoom operations are constrained within these bounds. + * If a pan or zoom is performed that would + * display regions outside these bounds, the map will + * instead display a position and zoom level + * as close as possible to the operation's request while still + * remaining within the bounds. + * + * @param {LngLatBoundsLike | null | undefined} bounds The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds. + * @returns {Map} `this` + * @example + * // Define bounds that conform to the `LngLatBoundsLike` object. + * var bounds = [ + * [-74.04728, 40.68392], // [west, south] + * [-73.91058, 40.87764] // [east, north] + * ]; + * // Set the map's max bounds. + * map.setMaxBounds(bounds); + */ + setMaxBounds(bounds: LngLatBoundsLike) { + this.transform.setMaxBounds(LngLatBounds.convert(bounds)); + return this._update(); + } + + /** + * Sets or clears the map's minimum zoom level. + * If the map's current zoom level is lower than the new minimum, + * the map will zoom to the new minimum. + * + * It is not always possible to zoom out and reach the set `minZoom`. + * Other factors such as map height may restrict zooming. For example, + * if the map is 512px tall it will not be possible to zoom below zoom 0 + * no matter what the `minZoom` is set to. + * + * @param {number | null | undefined} minZoom The minimum zoom level to set (-2 - 24). + * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2). + * @returns {Map} `this` + * @example + * map.setMinZoom(12.25); + */ + setMinZoom(minZoom?: ?number) { + + minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom; + + if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) { + this.transform.minZoom = minZoom; + this._update(); + + if (this.getZoom() < minZoom) this.setZoom(minZoom); + + return this; + + } else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`); + } + + /** + * Returns the map's minimum allowable zoom level. + * + * @returns {number} minZoom + * @example + * var minZoom = map.getMinZoom(); + */ + getMinZoom() { return this.transform.minZoom; } + + /** + * Sets or clears the map's maximum zoom level. + * If the map's current zoom level is higher than the new maximum, + * the map will zoom to the new maximum. + * + * @param {number | null | undefined} maxZoom The maximum zoom level to set. + * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22). + * @returns {Map} `this` + * @example + * map.setMaxZoom(18.75); + */ + setMaxZoom(maxZoom?: ?number) { + + maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom; + + if (maxZoom >= this.transform.minZoom) { + this.transform.maxZoom = maxZoom; + this._update(); + + if (this.getZoom() > maxZoom) this.setZoom(maxZoom); + + return this; + + } else throw new Error(`maxZoom must be greater than the current minZoom`); + } + + /** + * Returns the map's maximum allowable zoom level. + * + * @returns {number} maxZoom + * @example + * var maxZoom = map.getMaxZoom(); + */ + getMaxZoom() { return this.transform.maxZoom; } + + /** + * Sets or clears the map's minimum pitch. + * If the map's current pitch is lower than the new minimum, + * the map will pitch to the new minimum. + * + * @param {number | null | undefined} minPitch The minimum pitch to set (0-60). + * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0). + * @returns {Map} `this` + */ + setMinPitch(minPitch?: ?number) { + + minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch; + + if (minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + + if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) { + this.transform.minPitch = minPitch; + this._update(); + + if (this.getPitch() < minPitch) this.setPitch(minPitch); + + return this; + + } else throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`); + } + + /** + * Returns the map's minimum allowable pitch. + * + * @returns {number} minPitch + */ + getMinPitch() { return this.transform.minPitch; } + + /** + * Sets or clears the map's maximum pitch. + * If the map's current pitch is higher than the new maximum, + * the map will pitch to the new maximum. + * + * @param {number | null | undefined} maxPitch The maximum pitch to set. + * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60). + * @returns {Map} `this` + */ + setMaxPitch(maxPitch?: ?number) { + + maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch; + + if (maxPitch > defaultMaxPitch) { + throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`); + } + + if (maxPitch >= this.transform.minPitch) { + this.transform.maxPitch = maxPitch; + this._update(); + + if (this.getPitch() > maxPitch) this.setPitch(maxPitch); + + return this; + + } else throw new Error(`maxPitch must be greater than the current minPitch`); + } + + /** + * Returns the map's maximum allowable pitch. + * + * @returns {number} maxPitch + */ + getMaxPitch() { return this.transform.maxPitch; } + + /** + * Returns the state of `renderWorldCopies`. If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @returns {boolean} renderWorldCopies + * @example + * var worldCopiesRendered = map.getRenderWorldCopies(); + * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/) + */ + getRenderWorldCopies() { return this.transform.renderWorldCopies; } + + /** + * Sets the state of `renderWorldCopies`. + * + * @param {boolean} renderWorldCopies If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * + * `undefined` is treated as `true`, `null` is treated as `false`. + * @returns {Map} `this` + * @example + * map.setRenderWorldCopies(true); + * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/) + */ + setRenderWorldCopies(renderWorldCopies?: ?boolean) { + this.transform.renderWorldCopies = renderWorldCopies; + return this._update(); + } + + /** + * Returns a {@link Point} representing pixel coordinates, relative to the map's `container`, + * that correspond to the specified geographical location. + * + * @param {LngLatLike} lnglat The geographical location to project. + * @returns {Point} The {@link Point} corresponding to `lnglat`, relative to the map's `container`. + * @example + * var coordinate = [-122.420679, 37.772537]; + * var point = map.project(coordinate); + */ + project(lnglat: LngLatLike) { + return this.transform.locationPoint(LngLat.convert(lnglat)); + } + + /** + * Returns a {@link LngLat} representing geographical coordinates that correspond + * to the specified pixel coordinates. + * + * @param {PointLike} point The pixel coordinates to unproject. + * @returns {LngLat} The {@link LngLat} corresponding to `point`. + * @example + * map.on('click', function(e) { + * // When the map is clicked, get the geographic coordinate. + * var coordinate = map.unproject(e.point); + * }); + */ + unproject(point: PointLike) { + return this.transform.pointLocation(Point.convert(point)); + } + + /** + * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture. + * @returns {boolean} True if the map is moving. + * @example + * var isMoving = map.isMoving(); + */ + isMoving(): boolean { + return this._moving || this.handlers.isMoving(); + } + + /** + * Returns true if the map is zooming due to a camera animation or user gesture. + * @returns {boolean} True if the map is zooming. + * @example + * var isZooming = map.isZooming(); + */ + isZooming(): boolean { + return this._zooming || this.handlers.isZooming(); + } + + /** + * Returns true if the map is rotating due to a camera animation or user gesture. + * @returns {boolean} True if the map is rotating. + * @example + * map.isRotating(); + */ + isRotating(): boolean { + return this._rotating || this.handlers.isRotating(); + } + + _createDelegatedListener(type: MapEvent, layerId: any, listener: any) { + if (type === 'mouseenter' || type === 'mouseover') { + let mousein = false; + const mousemove = (e) => { + const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : []; + if (!features.length) { + mousein = false; + } else if (!mousein) { + mousein = true; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent, {features})); + } + }; + const mouseout = () => { + mousein = false; + }; + return {layer: layerId, listener, delegates: {mousemove, mouseout}}; + } else if (type === 'mouseleave' || type === 'mouseout') { + let mousein = false; + const mousemove = (e) => { + const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : []; + if (features.length) { + mousein = true; + } else if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + const mouseout = (e) => { + if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + return {layer: layerId, listener, delegates: {mousemove, mouseout}}; + } else { + const delegate = (e) => { + const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : []; + if (features.length) { + // Here we need to mutate the original event, so that preventDefault works as expected. + e.features = features; + listener.call(this, e); + delete e.features; + } + }; + return {layer: layerId, listener, delegates: {[type]: delegate}}; + } + } + + /** + * Adds a listener for events of a specified type, optionally limited to features in a specified style layer. + * + * @param {string} type The event type to listen for. Events compatible with the optional `layerId` parameter are triggered + * when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. + * + * | Event | Compatible with `layerId` | + * |-----------------------------------------------------------|---------------------------| + * | [`mousedown`](#map.event:mousedown) | yes | + * | [`mouseup`](#map.event:mouseup) | yes | + * | [`mouseover`](#map.event:mouseover) | yes | + * | [`mouseout`](#map.event:mouseout) | yes | + * | [`mousemove`](#map.event:mousemove) | yes | + * | [`mouseenter`](#map.event:mouseenter) | yes (required) | + * | [`mouseleave`](#map.event:mouseleave) | yes (required) | + * | [`click`](#map.event:click) | yes | + * | [`dblclick`](#map.event:dblclick) | yes | + * | [`contextmenu`](#map.event:contextmenu) | yes | + * | [`touchstart`](#map.event:touchstart) | yes | + * | [`touchend`](#map.event:touchend) | yes | + * | [`touchcancel`](#map.event:touchcancel) | yes | + * | [`wheel`](#map.event:wheel) | | + * | [`resize`](#map.event:resize) | | + * | [`remove`](#map.event:remove) | | + * | [`touchmove`](#map.event:touchmove) | | + * | [`movestart`](#map.event:movestart) | | + * | [`move`](#map.event:move) | | + * | [`moveend`](#map.event:moveend) | | + * | [`dragstart`](#map.event:dragstart) | | + * | [`drag`](#map.event:drag) | | + * | [`dragend`](#map.event:dragend) | | + * | [`zoomstart`](#map.event:zoomstart) | | + * | [`zoom`](#map.event:zoom) | | + * | [`zoomend`](#map.event:zoomend) | | + * | [`rotatestart`](#map.event:rotatestart) | | + * | [`rotate`](#map.event:rotate) | | + * | [`rotateend`](#map.event:rotateend) | | + * | [`pitchstart`](#map.event:pitchstart) | | + * | [`pitch`](#map.event:pitch) | | + * | [`pitchend`](#map.event:pitchend) | | + * | [`boxzoomstart`](#map.event:boxzoomstart) | | + * | [`boxzoomend`](#map.event:boxzoomend) | | + * | [`boxzoomcancel`](#map.event:boxzoomcancel) | | + * | [`webglcontextlost`](#map.event:webglcontextlost) | | + * | [`webglcontextrestored`](#map.event:webglcontextrestored) | | + * | [`load`](#map.event:load) | | + * | [`render`](#map.event:render) | | + * | [`idle`](#map.event:idle) | | + * | [`error`](#map.event:error) | | + * | [`data`](#map.event:data) | | + * | [`styledata`](#map.event:styledata) | | + * | [`sourcedata`](#map.event:sourcedata) | | + * | [`dataloading`](#map.event:dataloading) | | + * | [`styledataloading`](#map.event:styledataloading) | | + * | [`sourcedataloading`](#map.event:sourcedataloading) | | + * | [`styleimagemissing`](#map.event:styleimagemissing) | | + * + * @param {string} layerId (optional) The ID of a style layer. Event will only be triggered if its location + * is within a visible feature in this layer. The event will have a `features` property containing + * an array of the matching features. If `layerId` is not supplied, the event will not have a `features` property. + * Please note that many event types are not compatible with the optional `layerId` parameter. + * @param {Function} listener The function to be called when the event is fired. + * @returns {Map} `this` + * @example + * // Set an event listener that will fire + * // when the map has finished loading + * map.on('load', function() { + * // Once the map has finished loading, + * // add a new layer + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'mapbox://mapbox.mapbox-streets-v8' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // Mapbox Style Specification paint properties + * }, + * layout: { + * // Mapbox Style Specification layout properties + * } + * }); + * }); + * @example + * // Set an event listener that will fire + * // when a feature on the countries layer of the map is clicked + * map.on('click', 'countries', function(e) { + * new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setHTML(`Country name: ${e.features[0].properties.name}`) + * .addTo(map); + * }); + * @see [Display popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + * @see [Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + on(type: MapEvent, layerId: any, listener: any) { + if (listener === undefined) { + return super.on(type, layerId); + } + + const delegatedListener = this._createDelegatedListener(type, layerId, listener); + + this._delegatedListeners = this._delegatedListeners || {}; + this._delegatedListeners[type] = this._delegatedListeners[type] || []; + this._delegatedListeners[type].push(delegatedListener); + + for (const event in delegatedListener.delegates) { + this.on((event: any), delegatedListener.delegates[event]); + } + + return this; + } + + /** + * Adds a listener that will be called only once to a specified event type. + * + * @method + * @name once + * @memberof Map + * @instance + * @param {string} type The event type to add a listener for. + * @param {Function} listener The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + * @returns {Map} `this` + */ + + /** + * Adds a listener that will be called only once to a specified event type occurring on features in a specified style layer. + * + * @param {string} type The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`, + * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`, + * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters + * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave` + * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves + * the map canvas. + * @param {string} layerId The ID of a style layer. Only events whose location is within a visible + * feature in this layer will trigger the listener. The event will have a `features` property containing + * an array of the matching features. + * @param {Function} listener The function to be called when the event is fired. + * @returns {Map} `this` + */ + + once(type: MapEvent, layerId: any, listener: any) { + + if (listener === undefined) { + return super.once(type, layerId); + } + + const delegatedListener = this._createDelegatedListener(type, layerId, listener); + + for (const event in delegatedListener.delegates) { + this.once((event: any), delegatedListener.delegates[event]); + } + + return this; + } + + /** + * Removes an event listener previously added with `Map#on`. + * + * @method + * @name off + * @memberof Map + * @instance + * @param {string} type The event type previously used to install the listener. + * @param {Function} listener The function previously installed as a listener. + * @returns {Map} `this` + */ + + /** + * Removes an event listener for layer-specific events previously added with `Map#on`. + * + * @param {string} type The event type previously used to install the listener. + * @param {string} layerId The layer ID previously used to install the listener. + * @param {Function} listener The function previously installed as a listener. + * @returns {Map} `this` + */ + off(type: MapEvent, layerId: any, listener: any) { + if (listener === undefined) { + return super.off(type, layerId); + } + + const removeDelegatedListener = (delegatedListeners) => { + const listeners = delegatedListeners[type]; + for (let i = 0; i < listeners.length; i++) { + const delegatedListener = listeners[i]; + if (delegatedListener.layer === layerId && delegatedListener.listener === listener) { + for (const event in delegatedListener.delegates) { + this.off((event: any), delegatedListener.delegates[event]); + } + listeners.splice(i, 1); + return this; + } + } + }; + + if (this._delegatedListeners && this._delegatedListeners[type]) { + removeDelegatedListener(this._delegatedListeners); + } + + return this; + } + + /** + * Returns an array of [GeoJSON](http://geojson.org/) + * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) + * representing visible features that satisfy the query parameters. + * + * @param {PointLike|Array} [geometry] - The geometry of the query region: + * either a single point or southwest and northeast points describing a bounding box. + * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments, + * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire + * map viewport. + * @param {Object} [options] Options object. + * @param {Array} [options.layers] An array of [style layer IDs](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-id) for the query to inspect. + * Only features within these layers will be returned. If this parameter is undefined, all layers will be checked. + * @param {Array} [options.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) + * to limit query results. + * @param {boolean} [options.validate=true] Whether to check if the [options.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * + * @returns {Array} An array of [GeoJSON](http://geojson.org/) + * [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2). + * + * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only + * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported). + * + * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object + * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values + * which are fully evaluated for the given zoom level and feature. + * + * Only features that are currently rendered are included. Some features will **not** be included, like: + * + * - Features from layers whose `visibility` property is `"none"`. + * - Features from layers whose zoom range excludes the current zoom level. + * - Symbol features that have been hidden due to text or icon collision. + * + * Features from all other layers are included, including features that may have no visible + * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to + * 0. + * + * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by + * descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low + * zoom levels) are returned only once (though subject to the following caveat). + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * // Find all features at a point + * var features = map.queryRenderedFeatures( + * [20, 35], + * { layers: ['my-layer-name'] } + * ); + * + * @example + * // Find all features within a static bounding box + * var features = map.queryRenderedFeatures( + * [[10, 20], [30, 50]], + * { layers: ['my-layer-name'] } + * ); + * + * @example + * // Find all features within a bounding box around a point + * var width = 10; + * var height = 20; + * var features = map.queryRenderedFeatures([ + * [point.x - width / 2, point.y - height / 2], + * [point.x + width / 2, point.y + height / 2] + * ], { layers: ['my-layer-name'] }); + * + * @example + * // Query all rendered features from a single layer + * var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] }); + * @see [Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/) + * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + */ + queryRenderedFeatures(geometry?: PointLike | [PointLike, PointLike], options?: Object) { + // The first parameter can be omitted entirely, making this effectively an overloaded method + // with two signatures: + // + // queryRenderedFeatures(geometry: PointLike | [PointLike, PointLike], options?: Object) + // queryRenderedFeatures(options?: Object) + // + // There no way to express that in a way that's compatible with both flow and documentation.js. + // Related: https://github.com/facebook/flow/issues/1556 + + if (!this.style) { + return []; + } + + if (options === undefined && geometry !== undefined && !(geometry instanceof Point) && !Array.isArray(geometry)) { + options = (geometry: Object); + geometry = undefined; + } + + options = options || {}; + geometry = geometry || [[0, 0], [this.transform.width, this.transform.height]]; + + let queryGeometry; + if (geometry instanceof Point || typeof geometry[0] === 'number') { + queryGeometry = [Point.convert(geometry)]; + } else { + const tl = Point.convert(geometry[0]); + const br = Point.convert(geometry[1]); + queryGeometry = [tl, new Point(br.x, tl.y), br, new Point(tl.x, br.y), tl]; + } + + return this.style.queryRenderedFeatures(queryGeometry, options, this.transform); + } + + /** + * Returns an array of [GeoJSON](http://geojson.org/) + * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) + * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters. + * + * @param {string} sourceId The ID of the vector tile or GeoJSON source to query. + * @param {Object} [parameters] Options object. + * @param {string} [parameters.sourceLayer] The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/) + * to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored. + * @param {Array} [parameters.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) + * to limit query results. + * @param {boolean} [parameters.validate=true] Whether to check if the [parameters.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * + * @returns {Array} An array of [GeoJSON](http://geojson.org/) + * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2). + * + * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters, + * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded + * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently + * visible viewport. + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * // Find all features in one source layer in a vector source + * var features = map.querySourceFeatures('your-source-id', { + * sourceLayer: 'your-source-layer' + * }); + * + * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/) + */ + querySourceFeatures(sourceId: string, parameters: ?{sourceLayer: ?string, filter: ?Array, validate?: boolean}) { + return this.style.querySourceFeatures(sourceId, parameters); + } + + /** + * Updates the map's Mapbox style object with a new value. + * + * If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style + * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites + * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current + * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building + * the given one from scratch. + * + * + * @param style A JSON object conforming to the schema described in the + * [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to such JSON. + * @param {Object} [options] Options object. + * @param {boolean} [options.diff=true] If false, force a 'full' update, removing the current style + * and building the given one instead of attempting a diff-based update. + * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS + * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges. + * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). + * Set to `false`, to enable font settings from the map's style for these glyph ranges. + * Forces a full update. + * @returns {Map} `this` + * + * @example + * map.setStyle("mapbox://styles/mapbox/streets-v11"); + * + * @see [Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/) + */ + setStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) { + options = extend({}, {localIdeographFontFamily: this._localIdeographFontFamily}, options); + + if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) { + this._diffStyle(style, options); + return this; + } else { + this._localIdeographFontFamily = options.localIdeographFontFamily; + return this._updateStyle(style, options); + } + } + + _getUIString(key: string) { + const str = this._locale[key]; + if (str == null) { + throw new Error(`Missing UI string '${key}'`); + } + + return str; + } + + _updateStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) { + if (this.style) { + this.style.setEventedParent(null); + this.style._remove(); + } + + if (!style) { + delete this.style; + return this; + } else { + this.style = new Style(this, options || {}); + } + + this.style.setEventedParent(this, {style: this.style}); + + if (typeof style === 'string') { + this.style.loadURL(style); + } else { + this.style.loadJSON(style); + } + + return this; + } + + _lazyInitEmptyStyle() { + if (!this.style) { + this.style = new Style(this, {}); + this.style.setEventedParent(this, {style: this.style}); + this.style.loadEmpty(); + } + } + + _diffStyle(style: StyleSpecification | string, options?: {diff?: boolean} & StyleOptions) { + if (typeof style === 'string') { + const url = this._requestManager.normalizeStyleURL(style); + const request = this._requestManager.transformRequest(url, ResourceType.Style); + getJSON(request, (error: ?Error, json: ?Object) => { + if (error) { + this.fire(new ErrorEvent(error)); + } else if (json) { + this._updateDiff(json, options); + } + }); + } else if (typeof style === 'object') { + this._updateDiff(style, options); + } + } + + _updateDiff(style: StyleSpecification, options?: {diff?: boolean} & StyleOptions) { + try { + if (this.style.setState(style)) { + this._update(true); + } + } catch (e) { + warnOnce( + `Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.` + ); + this._updateStyle(style, options); + } + } + + /** + * Returns the map's Mapbox [style](https://docs.mapbox.com/help/glossary/style/) object, a JSON object which can be used to recreate the map's style. + * + * @returns {Object} The map's style JSON object. + * + * @example + * var styleJson = map.getStyle(); + * + */ + getStyle() { + if (this.style) { + return this.style.serialize(); + } + } + + /** + * Returns a Boolean indicating whether the map's style is fully loaded. + * + * @returns {boolean} A Boolean indicating whether the style is fully loaded. + * + * @example + * var styleLoadStatus = map.isStyleLoaded(); + */ + isStyleLoaded() { + if (!this.style) return warnOnce('There is no style added to the map.'); + return this.style.loaded(); + } + + /** + * Adds a source to the map's style. + * + * @param {string} id The ID of the source to add. Must not conflict with existing sources. + * @param {Object} source The source object, conforming to the + * Mapbox Style Specification's [source definition](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or + * {@link CanvasSourceOptions}. + * @fires source.add + * @returns {Map} `this` + * @example + * map.addSource('my-data', { + * type: 'vector', + * url: 'mapbox://myusername.tilesetid' + * }); + * @example + * map.addSource('my-data', { + * "type": "geojson", + * "data": { + * "type": "Feature", + * "geometry": { + * "type": "Point", + * "coordinates": [-77.0323, 38.9131] + * }, + * "properties": { + * "title": "Mapbox DC", + * "marker-symbol": "monument" + * } + * } + * }); + * @see Vector source: [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/) + * @see GeoJSON source: [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/) + * @see Raster DEM source: [Add hillshading](https://docs.mapbox.com/mapbox-gl-js/example/hillshade/) + */ + addSource(id: string, source: SourceSpecification) { + this._lazyInitEmptyStyle(); + this.style.addSource(id, source); + return this._update(true); + } + + /** + * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with + * the given ID in the map's style has no outstanding network requests, otherwise `false`. + * + * @param {string} id The ID of the source to be checked. + * @returns {boolean} A Boolean indicating whether the source is loaded. + * @example + * var sourceLoaded = map.isSourceLoaded('bathymetry-data'); + */ + isSourceLoaded(id: string) { + const source = this.style && this.style.sourceCaches[id]; + if (source === undefined) { + this.fire(new ErrorEvent(new Error(`There is no source with ID '${id}'`))); + return; + } + return source.loaded(); + } + + /** + * Returns a Boolean indicating whether all tiles in the viewport from all sources on + * the style are loaded. + * + * @returns {boolean} A Boolean indicating whether all tiles are loaded. + * @example + * var tilesLoaded = map.areTilesLoaded(); + */ + + areTilesLoaded() { + const sources = this.style && this.style.sourceCaches; + for (const id in sources) { + const source = sources[id]; + const tiles = source._tiles; + for (const t in tiles) { + const tile = tiles[t]; + if (!(tile.state === 'loaded' || tile.state === 'errored')) return false; + } + } + return true; + } + + /** + * Adds a [custom source type](#Custom Sources), making it available for use with + * {@link Map#addSource}. + * @private + * @param {string} name The name of the source type; source definition objects use this name in the `{type: ...}` field. + * @param {Function} SourceType A {@link Source} constructor. + * @param {Function} callback Called when the source type is ready or with an error argument if there is an error. + */ + addSourceType(name: string, SourceType: any, callback: Function) { + this._lazyInitEmptyStyle(); + return this.style.addSourceType(name, SourceType, callback); + } + + /** + * Removes a source from the map's style. + * + * @param {string} id The ID of the source to remove. + * @returns {Map} `this` + * @example + * map.removeSource('bathymetry-data'); + */ + removeSource(id: string) { + this.style.removeSource(id); + return this._update(true); + } + + /** + * Returns the source with the specified ID in the map's style. + * + * This method is often used to update a source using the instance members for the relevant + * source type as defined in [Sources](#sources). + * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates` + * of an image source. + * + * @param {string} id The ID of the source to get. + * @returns {?Object} The style source with the specified ID or `undefined` if the ID + * corresponds to no existing sources. + * The shape of the object varies by source type. + * A list of options for each source type is available on the Mapbox Style Specification's + * [Sources](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/) page. + * @example + * var sourceObject = map.getSource('points'); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + * @see [Animate a point](https://docs.mapbox.com/mapbox-gl-js/example/animate-point-along-line/) + * @see [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/) + */ + getSource(id: string) { + return this.style.getSource(id); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Add an image to the style. This image can be displayed on the map like any other icon in the style's + * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with + * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image), + * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern), + * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern), + * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern). + * A {@link Map.event:error} event will be fired if there is not enough space in the sprite to add this image. + * + * @param id The ID of the image. + * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @param options Options object. + * @param options.pixelRatio The ratio of pixels in the image to physical pixels on the screen + * @param options.sdf Whether the image should be interpreted as an SDF image + * @param options.content `[x1, y1, x2, y2]` If `icon-text-fit` is used in a layer with this image, this option defines the part of the image that can be covered by the content in `text-field`. + * @param options.stretchX `[[x1, x2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally. + * @param options.stretchY `[[y1, y2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically. + * + * @example + * // If the style's sprite does not already contain an image with ID 'cat', + * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'. + * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', function(error, image) { + * if (error) throw error; + * if (!map.hasImage('cat')) map.addImage('cat', image); + * }); + * + * + * // Add a stretchable image that can be used with `icon-text-fit` + * // In this example, the image is 600px wide by 400px high. + * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', function(error, image) { + * if (error) throw error; + * if (!map.hasImage('border-image')) { + * map.addImage('border-image', image, { + * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border + * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border + * stretchY: [[16, 384]], // stretch everything vertically except the 16px border + * }); + * } + * }); + * + * + * @see Use `HTMLImageElement`: [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/) + * @see Use `ImageData`: [Add a generated icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image-generated/) + */ + addImage(id: string, + image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface, + {pixelRatio = 1, sdf = false, stretchX, stretchY, content}: $Shape = {}) { + this._lazyInitEmptyStyle(); + const version = 0; + + if (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) { + const {width, height, data} = browser.getImageData(image); + this.style.addImage(id, {data: new RGBAImage({width, height}, data), pixelRatio, stretchX, stretchY, content, sdf, version}); + } else if (image.width === undefined || image.height === undefined) { + return this.fire(new ErrorEvent(new Error( + 'Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } else { + const {width, height, data} = image; + const userImage = ((image: any): StyleImageInterface); + + this.style.addImage(id, { + data: new RGBAImage({width, height}, new Uint8Array(data)), + pixelRatio, + stretchX, + stretchY, + content, + sdf, + version, + userImage + }); + + if (userImage.onAdd) { + userImage.onAdd(this, id); + } + } + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's + * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with + * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image), + * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern), + * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern), + * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern). + * + * @param id The ID of the image. + * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * + * @example + * // If an image with the ID 'cat' already exists in the style's sprite, + * // replace that image with a new image, 'other-cat-icon.png'. + * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png'); + */ + updateImage(id: string, + image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface) { + + const existingImage = this.style.getImage(id); + if (!existingImage) { + return this.fire(new ErrorEvent(new Error( + 'The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.'))); + } + const imageData = (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) ? browser.getImageData(image) : image; + const {width, height, data} = imageData; + + if (width === undefined || height === undefined) { + return this.fire(new ErrorEvent(new Error( + 'Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + + if (width !== existingImage.data.width || height !== existingImage.data.height) { + return this.fire(new ErrorEvent(new Error( + 'The width and height of the updated image must be that same as the previous version of the image'))); + } + + const copy = !(image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)); + existingImage.data.replace(data, copy); + + this.style.updateImage(id, existingImage); + } + + /** + * Check whether or not an image with a specific ID exists in the style. This checks both images + * in the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) and any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id The ID of the image. + * + * @returns {boolean} A Boolean indicating whether the image exists. + * @example + * // Check if an image with the ID 'cat' exists in + * // the style's sprite. + * var catIconExists = map.hasImage('cat'); + */ + hasImage(id: string): boolean { + if (!id) { + this.fire(new ErrorEvent(new Error('Missing required image id'))); + return false; + } + + return !!this.style.getImage(id); + } + + /** + * Remove an image from a style. This can be an image from the style's original + * [sprite](https://docs.mapbox.com/help/glossary/sprite/) or any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id The ID of the image. + * + * @example + * // If an image with the ID 'cat' exists in + * // the style's sprite, remove it. + * if (map.hasImage('cat')) map.removeImage('cat'); + */ + removeImage(id: string) { + this.style.removeImage(id); + } + + /** + * Load an image from an external URL to be used with {@link Map#addImage}. External + * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). + * + * @param {string} url The URL of the image file. Image file must be in png, webp, or jpg format. + * @param {Function} callback Expecting `callback(error, data)`. Called when the image has loaded or with an error argument if there is an error. + * + * @example + * // Load an image from an external URL. + * map.loadImage('http://placekitten.com/50/50', function(error, image) { + * if (error) throw error; + * // Add the loaded image to the style's sprite with the ID 'kitten'. + * map.addImage('kitten', image); + * }); + * + * @see [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/) + */ + loadImage(url: string, callback: Function) { + getImage(this._requestManager.transformRequest(url, ResourceType.Image), callback); + } + + /** + * Returns an Array of strings containing the IDs of all images currently available in the map. + * This includes both images from the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @returns {Array} An Array of strings containing the names of all sprites/images currently available in the map. + * + * @example + * var allImages = map.listImages(); + * + */ + listImages() { + return this.style.listImages(); + } + + /** + * Adds a [Mapbox style layer](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers) + * to the map's style. + * + * A layer defines how data from a specified source will be styled. Read more about layer types + * and available paint and layout properties in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers). + * + * @param {Object | CustomLayerInterface} layer The layer to add, conforming to either the Mapbox Style Specification's [layer definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers) or, less commonly, the {@link CustomLayerInterface} specification. + * The Mapbox Style Specification's layer definition is appropriate for most layers. + * + * @param {string} layer.id A unique idenfier that you define. + * @param {string} layer.type The type of layer (for example `fill` or `symbol`). + * A list of layer types is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#type). + * + * (This can also be `custom`. For more information, see {@link CustomLayerInterface}.) + * @param {string | Object} [layer.source] The data source for the layer. + * Reference a source that has _already been defined_ using the source's unique id. + * Reference a _new source_ using a source object (as defined in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/)) directly. + * This is **required** for all `layer.type` options _except_ for `custom`. + * @param {string} [layer.sourceLayer] (optional) The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/) within the specified `layer.source` to use for this style layer. + * This is only applicable for vector tile sources and is **required** when `layer.source` is of the type `vector`. + * @param {array} [layer.filter] (optional) An expression specifying conditions on source features. + * Only features that match the filter are displayed. + * The Mapbox Style Specification includes more information on the limitations of the [`filter`](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) parameter + * and a complete list of available [expressions](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/). + * If no filter is provided, all features in the source (or source layer for vector tilesets) will be displayed. + * @param {Object} [layer.paint] (optional) Paint properties for the layer. + * Available paint properties vary by `layer.type`. + * A full list of paint properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/). + * If no paint properties are specified, default values will be used. + * @param {Object} [layer.layout] (optional) Layout properties for the layer. + * Available layout properties vary by `layer.type`. + * A full list of layout properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/). + * If no layout properties are specified, default values will be used. + * @param {number} [layer.maxzoom] (optional) The maximum zoom level for the layer. + * At zoom levels equal to or greater than the maxzoom, the layer will be hidden. + * The value can be any number between `0` and `24` (inclusive). + * If no maxzoom is provided, the layer will be visible at all zoom levels for which there are tiles available. + * @param {number} [layer.minzoom] (optional) The minimum zoom level for the layer. + * At zoom levels less than the minzoom, the layer will be hidden. + * The value can be any number between `0` and `24` (inclusive). + * If no minzoom is provided, the layer will be visible at all zoom levels for which there are tiles available. + * @param {Object} [layer.metadata] (optional) Arbitrary properties useful to track with the layer, but do not influence rendering. + * @param {string} [layer.renderingMode] This is only applicable for layers with the type `custom`. + * See {@link CustomLayerInterface} for more information. + * @param {string} [beforeId] The ID of an existing layer to insert the new layer before, + * resulting in the new layer appearing visually beneath the existing layer. + * If this argument is not specified, the layer will be appended to the end of the layers array + * and appear visually above all other layers. + * + * @returns {Map} `this` + * + * @example + * // Add a circle layer with a vector source + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'mapbox://mapbox.mapbox-streets-v8' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // Mapbox Style Specification paint properties + * }, + * layout: { + * // Mapbox Style Specification layout properties + * } + * }); + * + * @example + * // Define a source before using it to create a new layer + * map.addSource('state-data', { + * type: 'geojson', + * data: 'path/to/data.geojson' + * }); + * + * map.addLayer({ + * id: 'states', + * // References the GeoJSON source defined above + * // and does not require a `source-layer` + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * }); + * + * @example + * // Add a new symbol layer before an existing layer + * map.addLayer({ + * id: 'states', + * // References a source that's already been defined + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * // Add the layer before the existing `cities` layer + * }, 'cities'); + * + * @see [Create and style clusters](https://docs.mapbox.com/mapbox-gl-js/example/cluster/) + * @see [Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/) + * @see [Add a WMS source](https://docs.mapbox.com/mapbox-gl-js/example/wms/) + */ + addLayer(layer: LayerSpecification | CustomLayerInterface, beforeId?: string) { + this._lazyInitEmptyStyle(); + this.style.addLayer(layer, beforeId); + return this._update(true); + } + + /** + * Moves a layer to a different z-position. + * + * @param {string} id The ID of the layer to move. + * @param {string} [beforeId] The ID of an existing layer to insert the new layer before. When viewing the map, the `id` layer will appear beneath the `beforeId` layer. If `beforeId` is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map. + * @returns {Map} `this` + * + * @example + * // Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map. + * map.moveLayer('polygon', 'country-label'); + */ + moveLayer(id: string, beforeId?: string) { + this.style.moveLayer(id, beforeId); + return this._update(true); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Removes the layer with the given ID from the map's style. + * + * If no such layer exists, an `error` event is fired. + * + * @param {string} id id of the layer to remove + * @fires error + * + * @example + * // If a layer with ID 'state-data' exists, remove it. + * if (map.getLayer('state-data')) map.removeLayer('state-data'); + */ + removeLayer(id: string) { + this.style.removeLayer(id); + return this._update(true); + } + + /** + * Returns the layer with the specified ID in the map's style. + * + * @param {string} id The ID of the layer to get. + * @returns {?Object} The layer with the specified ID, or `undefined` + * if the ID corresponds to no existing layers. + * + * @example + * var stateDataLayer = map.getLayer('state-data'); + * + * @see [Filter symbols by toggling a list](https://www.mapbox.com/mapbox-gl-js/example/filter-markers/) + * @see [Filter symbols by text input](https://www.mapbox.com/mapbox-gl-js/example/filter-markers-by-input/) + */ + getLayer(id: string) { + return this.style.getLayer(id); + } + + /** + * Sets the zoom extent for the specified style layer. The zoom extent includes the + * [minimum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-minzoom) + * and [maximum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-maxzoom)) + * at which the layer will be rendered. + * + * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the + * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum + * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style + * layer will not be rendered at all zoom levels in the zoom range. + * + * @param {string} layerId The ID of the layer to which the zoom extent will be applied. + * @param {number} minzoom The minimum zoom to set (0-24). + * @param {number} maxzoom The maximum zoom to set (0-24). + * @returns {Map} `this` + * + * @example + * map.setLayerZoomRange('my-layer', 2, 5); + * + */ + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number) { + this.style.setLayerZoomRange(layerId, minzoom, maxzoom); + return this._update(true); + } + + /** + * Sets the filter for the specified style layer. + * + * Filters control which features a style layer renders from its source. + * Any feature for which the filter expression evaluates to `true` will be + * rendered on the map. Those that are false will be hidden. + * + * Use `setFilter` to show a subset of your source data. + * + * To clear the filter, pass `null` or `undefined` as the second parameter. + * + * @param {string} layerId The ID of the layer to which the filter will be applied. + * @param {Array | null | undefined} filter The filter, conforming to the Mapbox Style Specification's + * [filter definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer. + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * + * @example + * // display only features with the 'name' property 'USA' + * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']); + * @example + * // display only features with five or more 'available-spots' + * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]); + * @example + * // remove the filter for the 'bike-docks' style layer + * map.setFilter('bike-docks', null); + * + * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/) + * @see [Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/) + * @see Tutorial: [Show changes over time](https://docs.mapbox.com/help/tutorials/show-changes-over-time/) + */ + setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) { + this.style.setFilter(layerId, filter, options); + return this._update(true); + } + + /** + * Returns the filter applied to the specified style layer. + * + * @param {string} layerId The ID of the style layer whose filter to get. + * @returns {Array} The layer's filter. + */ + getFilter(layerId: string) { + return this.style.getFilter(layerId); + } + + /** + * Sets the value of a paint property in the specified style layer. + * + * @param {string} layerId The ID of the layer to set the paint property in. + * @param {string} name The name of the paint property to set. + * @param {*} value The value of the paint property to set. + * Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/). + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * @example + * map.setPaintProperty('my-layer', 'fill-color', '#faafee'); + * @see [Change a layer's color with buttons](https://www.mapbox.com/mapbox-gl-js/example/color-switcher/) + * @see [Adjust a layer's opacity](https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/) + * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) { + this.style.setPaintProperty(layerId, name, value, options); + return this._update(true); + } + + /** + * Returns the value of a paint property in the specified style layer. + * + * @param {string} layerId The ID of the layer to get the paint property from. + * @param {string} name The name of a paint property to get. + * @returns {*} The value of the specified paint property. + */ + getPaintProperty(layerId: string, name: string) { + return this.style.getPaintProperty(layerId, name); + } + + /** + * Sets the value of a layout property in the specified style layer. + * + * @param {string} layerId The ID of the layer to set the layout property in. + * @param {string} name The name of the layout property to set. + * @param {*} value The value of the layout property. Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/). + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * @example + * map.setLayoutProperty('my-layer', 'visibility', 'none'); + * @see [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/) + */ + setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) { + this.style.setLayoutProperty(layerId, name, value, options); + return this._update(true); + } + + /** + * Returns the value of a layout property in the specified style layer. + * + * @param {string} layerId The ID of the layer to get the layout property from. + * @param {string} name The name of the layout property to get. + * @returns {*} The value of the specified layout property. + */ + getLayoutProperty(layerId: string, name: string) { + return this.style.getLayoutProperty(layerId, name); + } + + /** + * Sets the any combination of light values. + * + * @param light Light properties to set. Must conform to the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#light). + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * @example + * var layerVisibility = map.getLayoutProperty('my-layer', 'visibility'); + * @see [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/) + */ + setLight(light: LightSpecification, options: StyleSetterOptions = {}) { + this._lazyInitEmptyStyle(); + this.style.setLight(light, options); + return this._update(true); + } + + /** + * Returns the value of the light object. + * + * @returns {Object} light Light properties of the style. + */ + getLight() { + return this.style.getLight(); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Sets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways: + * - For vector or GeoJSON sources, including an `id` attribute in the original data file. + * - For vector or GeoJSON sources, using the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option at the time the source is defined. + * - For GeoJSON sources, using the [`generateId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#geojson-generateId) option to auto-assign an `id` based on the feature's index in the source data. If you change feature data using `map.getSource('some id').setData(..)`, you may need to re-apply state taking into account updated `id` values. + * + * _Note: You can use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._ + * + * @param {Object} feature Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param {string | number} feature.id Unique id of the feature. + * @param {string} feature.source The id of the vector or GeoJSON source for the feature. + * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.* + * @param {Object} state A set of key-value pairs. The values should be valid JSON types. + * + * @example + * // When the mouse moves over the `my-layer` layer, update + * // the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', function(e) { + * if (e.features.length > 0) { + * map.setFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id, + * }, { + * hover: true + * }); + * } + * }); + * + * @see [Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see Tutorial: [Create interactive hover effects with Mapbox GL JS](https://docs.mapbox.com/help/tutorials/create-interactive-hover-effects-with-mapbox-gl-js/) + */ + setFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }, state: Object) { + this.style.setFeatureState(feature, state); + return this._update(); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Removes the `state` of a feature, setting it back to the default behavior. + * If only a `target.source` is specified, it will remove the state for all features from that source. + * If `target.id` is also specified, it will remove all keys for that feature's state. + * If `key` is also specified, it removes only that key from that feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * @param {Object} target Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. + * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param {string | number} target.id (optional) Unique id of the feature. Optional if key is not specified. + * @param {string} target.source The id of the vector or GeoJSON source for the feature. + * @param {string} [target.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.* + * @param {string} key (optional) The key in the feature state to reset. + * + * @example + * // Reset the entire state object for all features + * // in the `my-source` source + * map.removeFeatureState({ + * source: 'my-source' + * }); + * + * @example + * // When the mouse leaves the `my-layer` layer, + * // reset the entire state object for the + * // feature under the mouse + * map.on('mouseleave', 'my-layer', function(e) { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * }); + * + * @example + * // When the mouse leaves the `my-layer` layer, + * // reset only the `hover` key-value pair in the + * // state for the feature under the mouse + * map.on('mouseleave', 'my-layer', function(e) { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }, 'hover'); + * }); + * + */ + removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) { + this.style.removeFeatureState(target, key); + return this._update(); + } + + /** + * Gets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state)._ + * + * @param {Object} feature Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param {string | number} feature.id Unique id of the feature. + * @param {string} feature.source The id of the vector or GeoJSON source for the feature. + * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.* + * + * @returns {Object} The state of the feature: a set of key-value pairs that was assigned to the feature at runtime. + * + * @example + * // When the mouse moves over the `my-layer` layer, + * // get the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', function(e) { + * if (e.features.length > 0) { + * map.getFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * } + * }); + * + */ + getFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }): any { + return this.style.getFeatureState(feature); + } + + /** + * Returns the map's containing HTML element. + * + * @returns {HTMLElement} The map's container. + */ + getContainer() { + return this._container; + } + + /** + * Returns the HTML element containing the map's `` element. + * + * If you want to add non-GL overlays to the map, you should append them to this element. + * + * This is the element to which event bindings for map interactivity (such as panning and zooming) are + * attached. It will receive bubbled events from child elements such as the ``, but not from + * map controls. + * + * @returns {HTMLElement} The container of the map's ``. + * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/) + * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + */ + getCanvasContainer() { + return this._canvasContainer; + } + + /** + * Returns the map's `` element. + * + * @returns {HTMLCanvasElement} The map's `` element. + * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/) + * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + */ + getCanvas() { + return this._canvas; + } + + _containerDimensions() { + let width = 0; + let height = 0; + + if (this._container) { + width = this._container.clientWidth || 400; + height = this._container.clientHeight || 300; + } + + return [width, height]; + } + + _detectMissingCSS(): void { + const computedColor = window.getComputedStyle(this._missingCSSCanary).getPropertyValue('background-color'); + if (computedColor !== 'rgb(250, 128, 114)') { + warnOnce('This page appears to be missing CSS declarations for ' + + 'Mapbox GL JS, which may cause the map to display incorrectly. ' + + 'Please ensure your page includes mapbox-gl.css, as described ' + + 'in https://www.mapbox.com/mapbox-gl-js/api/.'); + } + } + + _setupContainer() { + const container = this._container; + container.classList.add('mapboxgl-map'); + + const missingCSSCanary = this._missingCSSCanary = DOM.create('div', 'mapboxgl-canary', container); + missingCSSCanary.style.visibility = 'hidden'; + this._detectMissingCSS(); + + const canvasContainer = this._canvasContainer = DOM.create('div', 'mapboxgl-canvas-container', container); + if (this._interactive) { + canvasContainer.classList.add('mapboxgl-interactive'); + } + + this._canvas = DOM.create('canvas', 'mapboxgl-canvas', canvasContainer); + this._canvas.addEventListener('webglcontextlost', this._contextLost, false); + this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.setAttribute('tabindex', '0'); + this._canvas.setAttribute('aria-label', 'Map'); + this._canvas.setAttribute('role', 'region'); + + const dimensions = this._containerDimensions(); + this._resizeCanvas(dimensions[0], dimensions[1]); + + const controlContainer = this._controlContainer = DOM.create('div', 'mapboxgl-control-container', container); + const positions = this._controlPositions = {}; + ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => { + positions[positionName] = DOM.create('div', `mapboxgl-ctrl-${positionName}`, controlContainer); + }); + + this._container.addEventListener('scroll', this._onMapScroll, false); + } + + _resizeCanvas(width: number, height: number) { + const pixelRatio = browser.devicePixelRatio || 1; + + // Request the required canvas size taking the pixelratio into account. + this._canvas.width = pixelRatio * width; + this._canvas.height = pixelRatio * height; + + // Maintain the same canvas size, potentially downscaling it for HiDPI displays + this._canvas.style.width = `${width}px`; + this._canvas.style.height = `${height}px`; + } + + _setupPainter() { + const attributes = extend({}, isSupported.webGLContextAttributes, { + failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat, + preserveDrawingBuffer: this._preserveDrawingBuffer, + antialias: this._antialias || false + }); + + const gl = this._canvas.getContext('webgl', attributes) || + this._canvas.getContext('experimental-webgl', attributes); + + if (!gl) { + this.fire(new ErrorEvent(new Error('Failed to initialize WebGL'))); + return; + } + + this.painter = new Painter(gl, this.transform); + + webpSupported.testSupport(gl); + } + + _contextLost(event: *) { + event.preventDefault(); + if (this._frame) { + this._frame.cancel(); + this._frame = null; + } + this.fire(new Event('webglcontextlost', {originalEvent: event})); + } + + _contextRestored(event: *) { + this._setupPainter(); + this.resize(); + this._update(); + this.fire(new Event('webglcontextrestored', {originalEvent: event})); + } + + _onMapScroll(event: *) { + if (event.target !== this._container) return; + + // Revert any scroll which would move the canvas outside of the view + this._container.scrollTop = 0; + this._container.scrollLeft = 0; + return false; + } + + /** + * Returns a Boolean indicating whether the map is fully loaded. + * + * Returns `false` if the style is not yet fully loaded, + * or if there has been a change to the sources or style that + * has not yet fully loaded. + * + * @returns {boolean} A Boolean indicating whether the map is fully loaded. + */ + loaded() { + return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded(); + } + + /** + * Update this map's style and sources, and re-render the map. + * + * @param {boolean} updateStyle mark the map's style for reprocessing as + * well as its sources + * @returns {Map} this + * @private + */ + _update(updateStyle?: boolean) { + if (!this.style) return this; + + this._styleDirty = this._styleDirty || updateStyle; + this._sourcesDirty = true; + this.triggerRepaint(); + + return this; + } + + /** + * Request that the given callback be executed during the next render + * frame. Schedule a render frame if one is not already scheduled. + * @returns An id that can be used to cancel the callback + * @private + */ + _requestRenderFrame(callback: () => void): TaskID { + this._update(); + return this._renderTaskQueue.add(callback); + } + + _cancelRenderFrame(id: TaskID) { + this._renderTaskQueue.remove(id); + } + + /** + * Call when a (re-)render of the map is required: + * - The style has changed (`setPaintProperty()`, etc.) + * - Source data has changed (e.g. tiles have finished loading) + * - The map has is moving (or just finished moving) + * - A transition is in progress + * + * @param {number} paintStartTimeStamp The time when the animation frame began executing. + * + * @returns {Map} this + * @private + */ + _render(paintStartTimeStamp: number) { + let gpuTimer, frameStartTime = 0; + const extTimerQuery = this.painter.context.extTimerQuery; + if (this.listens('gpu-timing-frame')) { + gpuTimer = extTimerQuery.createQueryEXT(); + extTimerQuery.beginQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer); + frameStartTime = browser.now(); + } + + // A custom layer may have used the context asynchronously. Mark the state as dirty. + this.painter.context.setDirty(); + this.painter.setBaseState(); + + this._renderTaskQueue.run(paintStartTimeStamp); + // A task queue callback may have fired a user event which may have removed the map + if (this._removed) return; + + let crossFading = false; + + // If the style has changed, the map is being zoomed, or a transition or fade is in progress: + // - Apply style changes (in a batch) + // - Recalculate paint properties. + if (this.style && this._styleDirty) { + this._styleDirty = false; + + const zoom = this.transform.zoom; + const now = browser.now(); + this.style.zoomHistory.update(zoom, now); + + const parameters = new EvaluationParameters(zoom, { + now, + fadeDuration: this._fadeDuration, + zoomHistory: this.style.zoomHistory, + transition: this.style.getTransition() + }); + + const factor = parameters.crossFadingFactor(); + if (factor !== 1 || factor !== this._crossFadingFactor) { + crossFading = true; + this._crossFadingFactor = factor; + } + + this.style.update(parameters); + } + + // If we are in _render for any reason other than an in-progress paint + // transition, update source caches to check for and load any tiles we + // need for the current transform + if (this.style && this._sourcesDirty) { + this._sourcesDirty = false; + this.style._updateSources(this.transform); + } + + this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, this._fadeDuration, this._crossSourceCollisions); + + // Actually draw + this.painter.render(this.style, { + showTileBoundaries: this.showTileBoundaries, + showOverdrawInspector: this._showOverdrawInspector, + rotating: this.isRotating(), + zooming: this.isZooming(), + moving: this.isMoving(), + fadeDuration: this._fadeDuration, + showPadding: this.showPadding, + gpuTiming: !!this.listens('gpu-timing-layer'), + }); + + this.fire(new Event('render')); + + if (this.loaded() && !this._loaded) { + this._loaded = true; + PerformanceUtils.mark(PerformanceMarkers.load); + this.fire(new Event('load')); + } + + if (this.style && (this.style.hasTransitions() || crossFading)) { + this._styleDirty = true; + } + + if (this.style && !this._placementDirty) { + // Since no fade operations are in progress, we can release + // all tiles held for fading. If we didn't do this, the tiles + // would just sit in the SourceCaches until the next render + this.style._releaseSymbolFadeTiles(); + } + + if (this.listens('gpu-timing-frame')) { + const renderCPUTime = browser.now() - frameStartTime; + extTimerQuery.endQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer); + setTimeout(() => { + const renderGPUTime = extTimerQuery.getQueryObjectEXT(gpuTimer, extTimerQuery.QUERY_RESULT_EXT) / (1000 * 1000); + extTimerQuery.deleteQueryEXT(gpuTimer); + this.fire(new Event('gpu-timing-frame', { + cpuTime: renderCPUTime, + gpuTime: renderGPUTime + })); + }, 50); // Wait 50ms to give time for all GPU calls to finish before querying + } + + if (this.listens('gpu-timing-layer')) { + // Resetting the Painter's per-layer timing queries here allows us to isolate + // the queries to individual frames. + const frameLayerQueries = this.painter.collectGpuTimers(); + + setTimeout(() => { + const renderedLayerTimes = this.painter.queryGpuTimers(frameLayerQueries); + + this.fire(new Event('gpu-timing-layer', { + layerTimes: renderedLayerTimes + })); + }, 50); // Wait 50ms to give time for all GPU calls to finish before querying + } + + // Schedule another render frame if it's needed. + // + // Even though `_styleDirty` and `_sourcesDirty` are reset in this + // method, synchronous events fired during Style#update or + // Style#_updateSources could have caused them to be set again. + const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty; + if (somethingDirty || this._repaint) { + this.triggerRepaint(); + } else if (!this.isMoving() && this.loaded()) { + this.fire(new Event('idle')); + } + + if (this._loaded && !this._fullyLoaded && !somethingDirty) { + this._fullyLoaded = true; + PerformanceUtils.mark(PerformanceMarkers.fullLoad); + } + + return this; + } + + /** + * Clean up and release all internal resources associated with this map. + * + * This includes DOM elements, event bindings, web workers, and WebGL resources. + * + * Use this method when you are done using the map and wish to ensure that it no + * longer consumes browser resources. Afterwards, you must not call any other + * methods on the map. + */ + remove() { + if (this._hash) this._hash.remove(); + + for (const control of this._controls) control.onRemove(this); + this._controls = []; + + if (this._frame) { + this._frame.cancel(); + this._frame = null; + } + this._renderTaskQueue.clear(); + this.painter.destroy(); + this.handlers.destroy(); + delete this.handlers; + this.setStyle(null); + if (typeof window !== 'undefined') { + window.removeEventListener('resize', this._onWindowResize, false); + window.removeEventListener('orientationchange', this._onWindowResize, false); + window.removeEventListener('online', this._onWindowOnline, false); + } + + const extension = this.painter.context.gl.getExtension('WEBGL_lose_context'); + if (extension && extension.loseContext) extension.loseContext(); + removeNode(this._canvasContainer); + removeNode(this._controlContainer); + removeNode(this._missingCSSCanary); + this._container.classList.remove('mapboxgl-map'); + + PerformanceUtils.clearMetrics(); + + this._removed = true; + this.fire(new Event('remove')); + } + + /** + * Trigger the rendering of a single frame. Use this method with custom layers to + * repaint the map when the layer changes. Calling this multiple times before the + * next frame is rendered will still result in only a single frame being rendered. + * @example + * map.triggerRepaint(); + * @see [Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/) + * @see [Add an animated icon to the map](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/) + */ + triggerRepaint() { + if (this.style && !this._frame) { + this._frame = browser.frame((paintStartTimeStamp: number) => { + PerformanceUtils.frame(paintStartTimeStamp); + this._frame = null; + this._render(paintStartTimeStamp); + }); + } + } + + _onWindowOnline() { + this._update(); + } + + _onWindowResize(event: Event) { + if (this._trackResize) { + this.resize({originalEvent: event})._update(); + } + } + + /** + * Gets and sets a Boolean indicating whether the map will render an outline + * around each tile and the tile ID. These tile boundaries are useful for + * debugging. + * + * The uncompressed file size of the first vector source is drawn in the top left + * corner of each tile, next to the tile ID. + * + * @name showTileBoundaries + * @type {boolean} + * @instance + * @memberof Map + * @example + * map.showTileBoundaries = true; + */ + get showTileBoundaries(): boolean { return !!this._showTileBoundaries; } + set showTileBoundaries(value: boolean) { + if (this._showTileBoundaries === value) return; + this._showTileBoundaries = value; + this._update(); + } + + /** + * Gets and sets a Boolean indicating whether the map will visualize + * the padding offsets. + * + * @name showPadding + * @type {boolean} + * @instance + * @memberof Map + */ + get showPadding(): boolean { return !!this._showPadding; } + set showPadding(value: boolean) { + if (this._showPadding === value) return; + this._showPadding = value; + this._update(); + } + + /** + * Gets and sets a Boolean indicating whether the map will render boxes + * around all symbols in the data source, revealing which symbols + * were rendered or which were hidden due to collisions. + * This information is useful for debugging. + * + * @name showCollisionBoxes + * @type {boolean} + * @instance + * @memberof Map + */ + get showCollisionBoxes(): boolean { return !!this._showCollisionBoxes; } + set showCollisionBoxes(value: boolean) { + if (this._showCollisionBoxes === value) return; + this._showCollisionBoxes = value; + if (value) { + // When we turn collision boxes on we have to generate them for existing tiles + // When we turn them off, there's no cost to leaving existing boxes in place + this.style._generateCollisionBoxes(); + } else { + // Otherwise, call an update to remove collision boxes + this._update(); + } + } + + /* + * Gets and sets a Boolean indicating whether the map should color-code + * each fragment to show how many times it has been shaded. + * White fragments have been shaded 8 or more times. + * Black fragments have been shaded 0 times. + * This information is useful for debugging. + * + * @name showOverdraw + * @type {boolean} + * @instance + * @memberof Map + */ + get showOverdrawInspector(): boolean { return !!this._showOverdrawInspector; } + set showOverdrawInspector(value: boolean) { + if (this._showOverdrawInspector === value) return; + this._showOverdrawInspector = value; + this._update(); + } + + /** + * Gets and sets a Boolean indicating whether the map will + * continuously repaint. This information is useful for analyzing performance. + * + * @name repaint + * @type {boolean} + * @instance + * @memberof Map + */ + get repaint(): boolean { return !!this._repaint; } + set repaint(value: boolean) { + if (this._repaint !== value) { + this._repaint = value; + this.triggerRepaint(); + } + } + // show vertices + get vertices(): boolean { return !!this._vertices; } + set vertices(value: boolean) { this._vertices = value; this._update(); } + + // for cache browser tests + _setCacheLimits(limit: number, checkThreshold: number) { + setCacheLimits(limit, checkThreshold); + } + + /** + * The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release. + * + * @name version + * @instance + * @memberof Map + * @var {string} version + */ + + get version(): string { return version; } +} + +export default Map; + +function removeNode(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +} + +/** + * Interface for interactive controls added to the map. This is a + * specification for implementers to model: it is not + * an exported method or class. + * + * Controls must implement `onAdd` and `onRemove`, and must own an + * element, which is often a `div` element. To use Mapbox GL JS's + * default control styling, add the `mapboxgl-ctrl` class to your control's + * node. + * + * @interface IControl + * @example + * // Control implemented as ES6 class + * class HelloWorldControl { + * onAdd(map) { + * this._map = map; + * this._container = document.createElement('div'); + * this._container.className = 'mapboxgl-ctrl'; + * this._container.textContent = 'Hello, world'; + * return this._container; + * } + * + * onRemove() { + * this._container.parentNode.removeChild(this._container); + * this._map = undefined; + * } + * } + * + * // Control implemented as ES5 prototypical class + * function HelloWorldControl() { } + * + * HelloWorldControl.prototype.onAdd = function(map) { + * this._map = map; + * this._container = document.createElement('div'); + * this._container.className = 'mapboxgl-ctrl'; + * this._container.textContent = 'Hello, world'; + * return this._container; + * }; + * + * HelloWorldControl.prototype.onRemove = function () { + * this._container.parentNode.removeChild(this._container); + * this._map = undefined; + * }; + */ + +/** + * Register a control on the map and give it a chance to register event listeners + * and resources. This method is called by {@link Map#addControl} + * internally. + * + * @function + * @memberof IControl + * @instance + * @name onAdd + * @param {Map} map the Map this control will be added to + * @returns {HTMLElement} The control's container element. This should + * be created by the control and returned by onAdd without being attached + * to the DOM: the map will insert the control's element into the DOM + * as necessary. + */ + +/** + * Unregister a control on the map and give it a chance to detach event listeners + * and resources. This method is called by {@link Map#removeControl} + * internally. + * + * @function + * @memberof IControl + * @instance + * @name onRemove + * @param {Map} map the Map this control will be removed from + * @returns {undefined} there is no required return value for this method + */ + +/** + * Optionally provide a default position for this control. If this method + * is implemented and {@link Map#addControl} is called without the `position` + * parameter, the value returned by getDefaultPosition will be used as the + * control's position. + * + * @function + * @memberof IControl + * @instance + * @name getDefaultPosition + * @returns {string} a control position, one of the values valid in addControl. + */ + +/** + * A [`Point` geometry](https://github.com/mapbox/point-geometry) object, which has + * `x` and `y` properties representing screen coordinates in pixels. + * + * @typedef {Object} Point + * @example + * var point = new mapboxgl.Point(-77, 38); + */ + +/** + * A {@link Point} or an array of two numbers representing `x` and `y` screen coordinates in pixels. + * + * @typedef {(Point | Array)} PointLike + * @example + * var p1 = new mapboxgl.Point(-77, 38); // a PointLike which is a Point + * var p2 = [-77, 38]; // a PointLike which is an array of two numbers + */ diff --git a/node_modules/@plotly/mapbox-gl/src/ui/marker.js b/node_modules/@plotly/mapbox-gl/src/ui/marker.js new file mode 100644 index 0000000000000000000000000000000000000000..75d2de3d787e3de2ec16e7f6d16c4bc5d1ebe7da --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/marker.js @@ -0,0 +1,672 @@ +// @flow + +import DOM from '../util/dom'; +import window from '../util/window'; +import LngLat from '../geo/lng_lat'; +import Point from '@mapbox/point-geometry'; +import smartWrap from '../util/smart_wrap'; +import {bindAll, extend} from '../util/util'; +import {type Anchor, anchorTranslate, applyAnchorClass} from './anchor'; +import {Event, Evented} from '../util/evented'; +import type Map from './map'; +import type Popup from './popup'; +import type {LngLatLike} from "../geo/lng_lat"; +import type {MapMouseEvent, MapTouchEvent} from './events'; +import type {PointLike} from '@mapbox/point-geometry'; + +type Options = { + element?: HTMLElement, + offset?: PointLike, + anchor?: Anchor, + color?: string, + scale?: number, + draggable?: boolean, + clickTolerance?: number, + rotation?: number, + rotationAlignment?: string, + pitchAlignment?: string +}; + +/** + * Creates a marker component + * @param {Object} [options] + * @param {HTMLElement} [options.element] DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker. + * @param {string} [options.anchor='center'] A string indicating the part of the Marker that should be positioned closest to the coordinate set via {@link Marker#setLngLat}. + * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. + * @param {PointLike} [options.offset] The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + * @param {string} [options.color='#3FB1CE'] The color to use for the default marker if options.element is not provided. The default is light blue. + * @param {number} [options.scale=1] The scale to use for the default marker if options.element is not provided. The default scale corresponds to a height of `41px` and a width of `27px`. + * @param {boolean} [options.draggable=false] A boolean indicating whether or not a marker is able to be dragged to a new position on the map. + * @param {number} [options.clickTolerance=0] The max number of pixels a user can shift the mouse pointer during a click on the marker for it to be considered a valid click (as opposed to a marker drag). The default is to inherit map's clickTolerance. + * @param {number} [options.rotation=0] The rotation angle of the marker in degrees, relative to its respective `rotationAlignment` setting. A positive value will rotate the marker clockwise. + * @param {string} [options.pitchAlignment='auto'] `map` aligns the `Marker` to the plane of the map. `viewport` aligns the `Marker` to the plane of the viewport. `auto` automatically matches the value of `rotationAlignment`. + * @param {string} [options.rotationAlignment='auto'] `map` aligns the `Marker`'s rotation relative to the map, maintaining a bearing as the map rotates. `viewport` aligns the `Marker`'s rotation relative to the viewport, agnostic to map rotations. `auto` is equivalent to `viewport`. + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); + * @example + * // Set options + * var marker = new mapboxgl.Marker({ + * color: "#FFFFFF", + * draggable: true + * }).setLngLat([30.5, 50.5]) + * .addTo(map); + * @see [Add custom icons with Markers](https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/) + * @see [Create a draggable Marker](https://www.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + */ +export default class Marker extends Evented { + _map: Map; + _anchor: Anchor; + _offset: Point; + _element: HTMLElement; + _popup: ?Popup; + _lngLat: LngLat; + _pos: ?Point; + _color: ?string; + _scale: number; + _defaultMarker: boolean; + _draggable: boolean; + _clickTolerance: number; + _isDragging: boolean; + _state: 'inactive' | 'pending' | 'active'; // used for handling drag events + _positionDelta: ?Point; + _pointerdownPos: ?Point; + _rotation: number; + _pitchAlignment: string; + _rotationAlignment: string; + _originalTabIndex: ?string; // original tabindex of _element + + constructor(options?: Options, legacyOptions?: Options) { + super(); + // For backward compatibility -- the constructor used to accept the element as a + // required first argument, before it was made optional. + if (options instanceof window.HTMLElement || legacyOptions) { + options = extend({element: options}, legacyOptions); + } + + bindAll([ + '_update', + '_onMove', + '_onUp', + '_addDragHandler', + '_onMapClick', + '_onKeyPress' + ], this); + + this._anchor = options && options.anchor || 'center'; + this._color = options && options.color || '#3FB1CE'; + this._scale = options && options.scale || 1; + this._draggable = options && options.draggable || false; + this._clickTolerance = options && options.clickTolerance || 0; + this._isDragging = false; + this._state = 'inactive'; + this._rotation = options && options.rotation || 0; + this._rotationAlignment = options && options.rotationAlignment || 'auto'; + this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment; + + if (!options || !options.element) { + this._defaultMarker = true; + this._element = DOM.create('div'); + this._element.setAttribute('aria-label', 'Map marker'); + + // create default map marker SVG + const svg = DOM.createNS('http://www.w3.org/2000/svg', 'svg'); + const defaultHeight = 41; + const defaultWidth = 27; + svg.setAttributeNS(null, 'display', 'block'); + svg.setAttributeNS(null, 'height', `${defaultHeight}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth}px`); + svg.setAttributeNS(null, 'viewBox', `0 0 ${defaultWidth} ${defaultHeight}`); + + const markerLarge = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + markerLarge.setAttributeNS(null, 'stroke', 'none'); + markerLarge.setAttributeNS(null, 'stroke-width', '1'); + markerLarge.setAttributeNS(null, 'fill', 'none'); + markerLarge.setAttributeNS(null, 'fill-rule', 'evenodd'); + + const page1 = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + page1.setAttributeNS(null, 'fill-rule', 'nonzero'); + + const shadow = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + shadow.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)'); + shadow.setAttributeNS(null, 'fill', '#000000'); + + const ellipses = [ + {'rx': '10.5', 'ry': '5.25002273'}, + {'rx': '10.5', 'ry': '5.25002273'}, + {'rx': '9.5', 'ry': '4.77275007'}, + {'rx': '8.5', 'ry': '4.29549936'}, + {'rx': '7.5', 'ry': '3.81822308'}, + {'rx': '6.5', 'ry': '3.34094679'}, + {'rx': '5.5', 'ry': '2.86367051'}, + {'rx': '4.5', 'ry': '2.38636864'} + ]; + + for (const data of ellipses) { + const ellipse = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse'); + ellipse.setAttributeNS(null, 'opacity', '0.04'); + ellipse.setAttributeNS(null, 'cx', '10.5'); + ellipse.setAttributeNS(null, 'cy', '5.80029008'); + ellipse.setAttributeNS(null, 'rx', data['rx']); + ellipse.setAttributeNS(null, 'ry', data['ry']); + shadow.appendChild(ellipse); + } + + const background = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + background.setAttributeNS(null, 'fill', this._color); + + const bgPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + bgPath.setAttributeNS(null, 'd', 'M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z'); + + background.appendChild(bgPath); + + const border = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + border.setAttributeNS(null, 'opacity', '0.25'); + border.setAttributeNS(null, 'fill', '#000000'); + + const borderPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + borderPath.setAttributeNS(null, 'd', 'M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z'); + + border.appendChild(borderPath); + + const maki = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + maki.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)'); + maki.setAttributeNS(null, 'fill', '#FFFFFF'); + + const circleContainer = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + circleContainer.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)'); + + const circle1 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle1.setAttributeNS(null, 'fill', '#000000'); + circle1.setAttributeNS(null, 'opacity', '0.25'); + circle1.setAttributeNS(null, 'cx', '5.5'); + circle1.setAttributeNS(null, 'cy', '5.5'); + circle1.setAttributeNS(null, 'r', '5.4999962'); + + const circle2 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle2.setAttributeNS(null, 'fill', '#FFFFFF'); + circle2.setAttributeNS(null, 'cx', '5.5'); + circle2.setAttributeNS(null, 'cy', '5.5'); + circle2.setAttributeNS(null, 'r', '5.4999962'); + + circleContainer.appendChild(circle1); + circleContainer.appendChild(circle2); + + page1.appendChild(shadow); + page1.appendChild(background); + page1.appendChild(border); + page1.appendChild(maki); + page1.appendChild(circleContainer); + + svg.appendChild(page1); + + svg.setAttributeNS(null, 'height', `${defaultHeight * this._scale}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth * this._scale}px`); + + this._element.appendChild(svg); + + // if no element and no offset option given apply an offset for the default marker + // the -14 as the y value of the default marker offset was determined as follows + // + // the marker tip is at the center of the shadow ellipse from the default svg + // the y value of the center of the shadow ellipse relative to the svg top left is "shadow transform translate-y (29.0) + ellipse cy (5.80029008)" + // offset to the svg center "height (41 / 2)" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14 + // negative is used to move the marker up from the center so the tip is at the Marker lngLat + this._offset = Point.convert(options && options.offset || [0, -14]); + } else { + this._element = options.element; + this._offset = Point.convert(options && options.offset || [0, 0]); + } + + this._element.classList.add('mapboxgl-marker'); + this._element.addEventListener('dragstart', (e: DragEvent) => { + e.preventDefault(); + }); + this._element.addEventListener('mousedown', (e: MouseEvent) => { + // prevent focusing on click + e.preventDefault(); + }); + applyAnchorClass(this._element, this._anchor, 'marker'); + + this._popup = null; + } + + /** + * Attaches the `Marker` to a `Map` object. + * @param {Map} map The Mapbox GL JS map to add the marker to. + * @returns {Marker} `this` + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); // add the marker to the map + */ + addTo(map: Map) { + this.remove(); + this._map = map; + map.getCanvasContainer().appendChild(this._element); + map.on('move', this._update); + map.on('moveend', this._update); + this.setDraggable(this._draggable); + this._update(); + + // If we attached the `click` listener to the marker element, the popup + // would close once the event propogated to `map` due to the + // `Popup#_onClickClose` listener. + this._map.on('click', this._onMapClick); + + return this; + } + + /** + * Removes the marker from a map + * @example + * var marker = new mapboxgl.Marker().addTo(map); + * marker.remove(); + * @returns {Marker} `this` + */ + remove() { + if (this._map) { + this._map.off('click', this._onMapClick); + this._map.off('move', this._update); + this._map.off('moveend', this._update); + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + this._map.off('mouseup', this._onUp); + this._map.off('touchend', this._onUp); + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + delete this._map; + } + DOM.remove(this._element); + if (this._popup) this._popup.remove(); + return this; + } + + /** + * Get the marker's geographical location. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep + * the marker on screen. + * + * @returns {LngLat} A {@link LngLat} describing the marker's location. + * @example + * // Store the marker's longitude and latitude coordinates in a variable + * var lngLat = marker.getLngLat(); + * // Print the marker's longitude and latitude values in the console + * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat ) + * @see [Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + */ + getLngLat() { + return this._lngLat; + } + + /** + * Set the marker's geographical position and move it. + * @param {LngLat} lnglat A {@link LngLat} describing where the marker should be located. + * @returns {Marker} `this` + * @example + * // Create a new marker, set the longitude and latitude, and add it to the map + * new mapboxgl.Marker() + * .setLngLat([-65.017, -16.457]) + * .addTo(map); + * @see [Add custom icons with Markers](https://docs.mapbox.com/mapbox-gl-js/example/custom-marker-icons/) + * @see [Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + * @see [Add a marker using a place name](https://docs.mapbox.com/mapbox-gl-js/example/marker-from-geocode/) + */ + setLngLat(lnglat: LngLatLike) { + this._lngLat = LngLat.convert(lnglat); + this._pos = null; + if (this._popup) this._popup.setLngLat(this._lngLat); + this._update(); + return this; + } + + /** + * Returns the `Marker`'s HTML element. + * @returns {HTMLElement} element + */ + getElement() { + return this._element; + } + + /** + * Binds a {@link Popup} to the {@link Marker}. + * @param popup An instance of the {@link Popup} class. If undefined or null, any popup + * set on this {@link Marker} instance is unset. + * @returns {Marker} `this` + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([0, 0]) + * .setPopup(new mapboxgl.Popup().setHTML("

Hello World!

")) // add popup + * .addTo(map); + * @see [Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/) + */ + setPopup(popup: ?Popup) { + if (this._popup) { + this._popup.remove(); + this._popup = null; + this._element.removeEventListener('keypress', this._onKeyPress); + + if (!this._originalTabIndex) { + this._element.removeAttribute('tabindex'); + } + } + + if (popup) { + if (!('offset' in popup.options)) { + const markerHeight = 41 - (5.8 / 2); + const markerRadius = 13.5; + const linearOffset = Math.sqrt(Math.pow(markerRadius, 2) / 2); + popup.options.offset = this._defaultMarker ? { + 'top': [0, 0], + 'top-left': [0, 0], + 'top-right': [0, 0], + 'bottom': [0, -markerHeight], + 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'left': [markerRadius, (markerHeight - markerRadius) * -1], + 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + } : this._offset; + } + this._popup = popup; + if (this._lngLat) this._popup.setLngLat(this._lngLat); + + this._originalTabIndex = this._element.getAttribute('tabindex'); + if (!this._originalTabIndex) { + this._element.setAttribute('tabindex', '0'); + } + this._element.addEventListener('keypress', this._onKeyPress); + } + + return this; + } + + _onKeyPress(e: KeyboardEvent) { + const code = e.code; + const legacyCode = e.charCode || e.keyCode; + + if ( + (code === 'Space') || (code === 'Enter') || + (legacyCode === 32) || (legacyCode === 13) // space or enter + ) { + this.togglePopup(); + } + } + + _onMapClick(e: MapMouseEvent) { + const targetElement = e.originalEvent.target; + const element = this._element; + + if (this._popup && (targetElement === element || element.contains((targetElement: any)))) { + this.togglePopup(); + } + } + + /** + * Returns the {@link Popup} instance that is bound to the {@link Marker}. + * @returns {Popup} popup + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([0, 0]) + * .setPopup(new mapboxgl.Popup().setHTML("

Hello World!

")) + * .addTo(map); + * + * console.log(marker.getPopup()); // return the popup instance + */ + getPopup() { + return this._popup; + } + + /** + * Opens or closes the {@link Popup} instance that is bound to the {@link Marker}, depending on the current state of the {@link Popup}. + * @returns {Marker} `this` + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([0, 0]) + * .setPopup(new mapboxgl.Popup().setHTML("

Hello World!

")) + * .addTo(map); + * + * marker.togglePopup(); // toggle popup open or closed + */ + togglePopup() { + const popup = this._popup; + + if (!popup) return this; + else if (popup.isOpen()) popup.remove(); + else popup.addTo(this._map); + return this; + } + + _update(e?: {type: 'move' | 'moveend'}) { + if (!this._map) return; + + if (this._map.transform.renderWorldCopies) { + this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform); + } + + this._pos = this._map.project(this._lngLat)._add(this._offset); + + let rotation = ""; + if (this._rotationAlignment === "viewport" || this._rotationAlignment === "auto") { + rotation = `rotateZ(${this._rotation}deg)`; + } else if (this._rotationAlignment === "map") { + rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`; + } + + let pitch = ""; + if (this._pitchAlignment === "viewport" || this._pitchAlignment === "auto") { + pitch = "rotateX(0deg)"; + } else if (this._pitchAlignment === "map") { + pitch = `rotateX(${this._map.getPitch()}deg)`; + } + + // because rounding the coordinates at every `move` event causes stuttered zooming + // we only round them when _update is called with `moveend` or when its called with + // no arguments (when the Marker is initialized or Marker#setLngLat is invoked). + if (!e || e.type === "moveend") { + this._pos = this._pos.round(); + } + + DOM.setTransform(this._element, `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`); + } + + /** + * Get the marker's offset. + * @returns {Point} The marker's screen coordinates in pixels. + */ + getOffset() { + return this._offset; + } + + /** + * Sets the offset of the marker + * @param {PointLike} offset The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + * @returns {Marker} `this` + */ + setOffset(offset: PointLike) { + this._offset = Point.convert(offset); + this._update(); + return this; + } + + _onMove(e: MapMouseEvent | MapTouchEvent) { + if (!this._isDragging) { + const clickTolerance = this._clickTolerance || this._map._clickTolerance; + this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance; + } + if (!this._isDragging) return; + + this._pos = e.point.sub(this._positionDelta); + this._lngLat = this._map.unproject(this._pos); + this.setLngLat(this._lngLat); + // suppress click event so that popups don't toggle on drag + this._element.style.pointerEvents = 'none'; + + // make sure dragstart only fires on the first move event after mousedown. + // this can't be on mousedown because that event doesn't necessarily + // imply that a drag is about to happen. + if (this._state === 'pending') { + this._state = 'active'; + + /** + * Fired when dragging starts + * + * @event dragstart + * @memberof Marker + * @instance + * @type {Object} + * @property {Marker} marker object that is being dragged + */ + this.fire(new Event('dragstart')); + } + + /** + * Fired while dragging + * + * @event drag + * @memberof Marker + * @instance + * @type {Object} + * @property {Marker} marker object that is being dragged + */ + this.fire(new Event('drag')); + } + + _onUp() { + // revert to normal pointer event handling + this._element.style.pointerEvents = 'auto'; + this._positionDelta = null; + this._pointerdownPos = null; + this._isDragging = false; + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + + // only fire dragend if it was preceded by at least one drag event + if (this._state === 'active') { + /** + * Fired when the marker is finished being dragged + * + * @event dragend + * @memberof Marker + * @instance + * @type {Object} + * @property {Marker} marker object that was dragged + */ + this.fire(new Event('dragend')); + } + + this._state = 'inactive'; + } + + _addDragHandler(e: MapMouseEvent | MapTouchEvent) { + if (this._element.contains((e.originalEvent.target: any))) { + e.preventDefault(); + + // We need to calculate the pixel distance between the click point + // and the marker position, with the offset accounted for. Then we + // can subtract this distance from the mousemove event's position + // to calculate the new marker position. + // If we don't do this, the marker 'jumps' to the click position + // creating a jarring UX effect. + this._positionDelta = e.point.sub(this._pos).add(this._offset); + + this._pointerdownPos = e.point; + + this._state = 'pending'; + this._map.on('mousemove', this._onMove); + this._map.on('touchmove', this._onMove); + this._map.once('mouseup', this._onUp); + this._map.once('touchend', this._onUp); + } + } + + /** + * Sets the `draggable` property and functionality of the marker + * @param {boolean} [shouldBeDraggable=false] Turns drag functionality on/off + * @returns {Marker} `this` + */ + setDraggable(shouldBeDraggable: boolean) { + this._draggable = !!shouldBeDraggable; // convert possible undefined value to false + + // handle case where map may not exist yet + // e.g. when setDraggable is called before addTo + if (this._map) { + if (shouldBeDraggable) { + this._map.on('mousedown', this._addDragHandler); + this._map.on('touchstart', this._addDragHandler); + } else { + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + } + } + + return this; + } + + /** + * Returns true if the marker can be dragged + * @returns {boolean} True if the marker is draggable. + */ + isDraggable() { + return this._draggable; + } + + /** + * Sets the `rotation` property of the marker. + * @param {number} [rotation=0] The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting. + * @returns {Marker} `this` + */ + setRotation(rotation: number) { + this._rotation = rotation || 0; + this._update(); + return this; + } + + /** + * Returns the current rotation angle of the marker (in degrees). + * @returns {number} The current rotation angle of the marker. + */ + getRotation() { + return this._rotation; + } + + /** + * Sets the `rotationAlignment` property of the marker. + * @param {string} [alignment='auto'] Sets the `rotationAlignment` property of the marker. + * @returns {Marker} `this` + */ + setRotationAlignment(alignment: string) { + this._rotationAlignment = alignment || 'auto'; + this._update(); + return this; + } + + /** + * Returns the current `rotationAlignment` property of the marker. + * @returns {string} The current rotational alignment of the marker. + */ + getRotationAlignment() { + return this._rotationAlignment; + } + + /** + * Sets the `pitchAlignment` property of the marker. + * @param {string} [alignment] Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`. + * @returns {Marker} `this` + */ + setPitchAlignment(alignment: string) { + this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment; + this._update(); + return this; + } + + /** + * Returns the current `pitchAlignment` property of the marker. + * @returns {string} The current pitch alignment of the marker in degrees. + */ + getPitchAlignment() { + return this._pitchAlignment; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/ui/popup.js b/node_modules/@plotly/mapbox-gl/src/ui/popup.js new file mode 100644 index 0000000000000000000000000000000000000000..8636862dc2feee85c999212b5a8ea9116106b04d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/ui/popup.js @@ -0,0 +1,640 @@ +// @flow + +import {extend, bindAll} from '../util/util'; +import {Event, Evented} from '../util/evented'; +import {MapMouseEvent} from '../ui/events'; +import DOM from '../util/dom'; +import LngLat from '../geo/lng_lat'; +import Point from '@mapbox/point-geometry'; +import window from '../util/window'; +import smartWrap from '../util/smart_wrap'; +import {type Anchor, anchorTranslate, applyAnchorClass} from './anchor'; + +import type Map from './map'; +import type {LngLatLike} from '../geo/lng_lat'; +import type {PointLike} from '@mapbox/point-geometry'; + +const defaultOptions = { + closeButton: true, + closeOnClick: true, + focusAfterOpen: true, + className: '', + maxWidth: "240px" +}; + +export type Offset = number | PointLike | {[_: Anchor]: PointLike}; + +export type PopupOptions = { + closeButton?: boolean, + closeOnClick?: boolean, + closeOnMove?: boolean, + focusAfterOpen?: boolean, + anchor?: Anchor, + offset?: Offset, + className?: string, + maxWidth?: string +}; + +const focusQuerySelector = [ + "a[href]", + "[tabindex]:not([tabindex='-1'])", + "[contenteditable]:not([contenteditable='false'])", + "button:not([disabled])", + "input:not([disabled])", + "select:not([disabled])", + "textarea:not([disabled])", +].join(", "); + +/** + * A popup component. + * + * @param {Object} [options] + * @param {boolean} [options.closeButton=true] If `true`, a close button will appear in the + * top right corner of the popup. + * @param {boolean} [options.closeOnClick=true] If `true`, the popup will closed when the + * map is clicked. + * @param {boolean} [options.closeOnMove=false] If `true`, the popup will closed when the + * map moves. + * @param {boolean} [options.focusAfterOpen=true] If `true`, the popup will try to focus the + * first focusable element inside the popup. + * @param {string} [options.anchor] - A string indicating the part of the Popup that should + * be positioned closest to the coordinate set via {@link Popup#setLngLat}. + * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, + * `'top-right'`, `'bottom-left'`, and `'bottom-right'`. If unset the anchor will be + * dynamically set to ensure the popup falls within the map container with a preference + * for `'bottom'`. + * @param {number|PointLike|Object} [options.offset] - + * A pixel offset applied to the popup's location specified as: + * - a single number specifying a distance from the popup's location + * - a {@link PointLike} specifying a constant offset + * - an object of {@link Point}s specifing an offset for each anchor position + * Negative offsets indicate left and up. + * @param {string} [options.className] Space-separated CSS class names to add to popup container + * @param {string} [options.maxWidth='240px'] - + * A string that sets the CSS property of the popup's maximum width, eg `'300px'`. + * To ensure the popup resizes to fit its content, set this property to `'none'`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * @example + * var markerHeight = 50, markerRadius = 10, linearOffset = 25; + * var popupOffsets = { + * 'top': [0, 0], + * 'top-left': [0,0], + * 'top-right': [0,0], + * 'bottom': [0, -markerHeight], + * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'left': [markerRadius, (markerHeight - markerRadius) * -1], + * 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + * }; + * var popup = new mapboxgl.Popup({offset: popupOffsets, className: 'my-class'}) + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .setMaxWidth("300px") + * .addTo(map); + * @see [Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/) + * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Display a popup on click](https://www.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Attach a popup to a marker instance](https://www.mapbox.com/mapbox-gl-js/example/set-popup/) + */ +export default class Popup extends Evented { + _map: Map; + options: PopupOptions; + _content: HTMLElement; + _container: HTMLElement; + _closeButton: HTMLElement; + _tip: HTMLElement; + _lngLat: LngLat; + _trackPointer: boolean; + _pos: ?Point; + + constructor(options: PopupOptions) { + super(); + this.options = extend(Object.create(defaultOptions), options); + bindAll(['_update', '_onClose', 'remove', '_onMouseMove', '_onMouseUp', '_onDrag'], this); + } + + /** + * Adds the popup to a map. + * + * @param {Map} map The Mapbox GL JS map to add the popup to. + * @returns {Popup} `this` + * @example + * new mapboxgl.Popup() + * .setLngLat([0, 0]) + * .setHTML("

Null Island

") + * .addTo(map); + * @see [Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/) + * @see [Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Show polygon information on click](https://docs.mapbox.com/mapbox-gl-js/example/polygon-popup-on-click/) + */ + addTo(map: Map) { + if (this._map) this.remove(); + + this._map = map; + if (this.options.closeOnClick) { + this._map.on('click', this._onClose); + } + + if (this.options.closeOnMove) { + this._map.on('move', this._onClose); + } + + this._map.on('remove', this.remove); + this._update(); + this._focusFirstElement(); + + if (this._trackPointer) { + this._map.on('mousemove', this._onMouseMove); + this._map.on('mouseup', this._onMouseUp); + if (this._container) { + this._container.classList.add('mapboxgl-popup-track-pointer'); + } + this._map._canvasContainer.classList.add('mapboxgl-track-pointer'); + } else { + this._map.on('move', this._update); + } + + /** + * Fired when the popup is opened manually or programatically. + * + * @event open + * @memberof Popup + * @instance + * @type {Object} + * @property {Popup} popup object that was opened + * + * @example + * // Create a popup + * var popup = new mapboxgl.Popup(); + * // Set an event listener that will fire + * // any time the popup is opened + * popup.on('open', function(){ + * console.log('popup was opened'); + * }); + * + */ + this.fire(new Event('open')); + + return this; + } + + /** + * @returns {boolean} `true` if the popup is open, `false` if it is closed. + */ + isOpen() { + return !!this._map; + } + + /** + * Removes the popup from the map it has been added to. + * + * @example + * var popup = new mapboxgl.Popup().addTo(map); + * popup.remove(); + * @returns {Popup} `this` + */ + remove() { + if (this._content) { + DOM.remove(this._content); + } + + if (this._container) { + DOM.remove(this._container); + delete this._container; + } + + if (this._map) { + this._map.off('move', this._update); + this._map.off('move', this._onClose); + this._map.off('click', this._onClose); + this._map.off('remove', this.remove); + this._map.off('mousemove', this._onMouseMove); + this._map.off('mouseup', this._onMouseUp); + this._map.off('drag', this._onDrag); + delete this._map; + } + + /** + * Fired when the popup is closed manually or programatically. + * + * @event close + * @memberof Popup + * @instance + * @type {Object} + * @property {Popup} popup object that was closed + * + * @example + * // Create a popup + * var popup = new mapboxgl.Popup(); + * // Set an event listener that will fire + * // any time the popup is closed + * popup.on('close', function(){ + * console.log('popup was closed'); + * }); + * + */ + this.fire(new Event('close')); + + return this; + } + + /** + * Returns the geographical location of the popup's anchor. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep + * the popup on screen. + * + * @returns {LngLat} The geographical location of the popup's anchor. + */ + getLngLat() { + return this._lngLat; + } + + /** + * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior. + * + * @param lnglat The geographical location to set as the popup's anchor. + * @returns {Popup} `this` + */ + setLngLat(lnglat: LngLatLike) { + this._lngLat = LngLat.convert(lnglat); + this._pos = null; + + this._trackPointer = false; + + this._update(); + + if (this._map) { + this._map.on('move', this._update); + this._map.off('mousemove', this._onMouseMove); + if (this._container) { + this._container.classList.remove('mapboxgl-popup-track-pointer'); + } + this._map._canvasContainer.classList.remove('mapboxgl-track-pointer'); + } + + return this; + } + + /** + * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior. + * For most use cases, set `closeOnClick` and `closeButton` to `false`. + * @example + * var popup = new mapboxgl.Popup({ closeOnClick: false, closeButton: false }) + * .setHTML("

Hello World!

") + * .trackPointer() + * .addTo(map); + * @returns {Popup} `this` + */ + trackPointer() { + this._trackPointer = true; + this._pos = null; + this._update(); + if (this._map) { + this._map.off('move', this._update); + this._map.on('mousemove', this._onMouseMove); + this._map.on('drag', this._onDrag); + if (this._container) { + this._container.classList.add('mapboxgl-popup-track-pointer'); + } + this._map._canvasContainer.classList.add('mapboxgl-track-pointer'); + } + + return this; + + } + + /** + * Returns the `Popup`'s HTML element. + * @example + * // Change the `Popup` element's font size + * var popup = new mapboxgl.Popup() + * .setLngLat([-96, 37.8]) + * .setHTML("

Hello World!

") + * .addTo(map); + * var popupElem = popup.getElement(); + * popupElem.style.fontSize = "25px"; + * @returns {HTMLElement} element + */ + getElement() { + return this._container; + } + + /** + * Sets the popup's content to a string of text. + * + * This function creates a [Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) node in the DOM, + * so it cannot insert raw HTML. Use this method for security against XSS + * if the popup content is user-provided. + * + * @param text Textual content for the popup. + * @returns {Popup} `this` + * @example + * var popup = new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setText('Hello, world!') + * .addTo(map); + */ + setText(text: string) { + return this.setDOMContent(window.document.createTextNode(text)); + } + + /** + * Sets the popup's content to the HTML provided as a string. + * + * This method does not perform HTML filtering or sanitization, and must be + * used only with trusted content. Consider {@link Popup#setText} if + * the content is an untrusted text string. + * + * @param html A string representing HTML content for the popup. + * @returns {Popup} `this` + * @example + * var popup = new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .addTo(map); + * @see [Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/) + * @see [Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/) + */ + setHTML(html: string) { + const frag = window.document.createDocumentFragment(); + const temp = window.document.createElement('body'); + let child; + temp.innerHTML = html; + while (true) { + child = temp.firstChild; + if (!child) break; + frag.appendChild(child); + } + + return this.setDOMContent(frag); + } + + /** + * Returns the popup's maximum width. + * + * @returns {string} The maximum width of the popup. + */ + getMaxWidth() { + return this._container && this._container.style.maxWidth; + } + + /** + * Sets the popup's maximum width. This is setting the CSS property `max-width`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * + * @param maxWidth A string representing the value for the maximum width. + * @returns {Popup} `this` + */ + setMaxWidth(maxWidth: string) { + this.options.maxWidth = maxWidth; + this._update(); + return this; + } + + /** + * Sets the popup's content to the element provided as a DOM node. + * + * @param htmlNode A DOM node to be used as content for the popup. + * @returns {Popup} `this` + * @example + * // create an element with the popup content + * var div = window.document.createElement('div'); + * div.innerHTML = 'Hello, world!'; + * var popup = new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setDOMContent(div) + * .addTo(map); + */ + setDOMContent(htmlNode: Node) { + if (this._content) { + // Clear out children first. + while (this._content.hasChildNodes()) { + if (this._content.firstChild) { + this._content.removeChild(this._content.firstChild); + } + } + } else { + this._content = DOM.create('div', 'mapboxgl-popup-content', this._container); + } + + // The close button should be the last tabbable element inside the popup for a good keyboard UX. + this._content.appendChild(htmlNode); + this._createCloseButton(); + this._update(); + this._focusFirstElement(); + return this; + } + + /** + * Adds a CSS class to the popup container element. + * + * @param {string} className Non-empty string with CSS class name to add to popup container + * + * @example + * let popup = new mapboxgl.Popup() + * popup.addClassName('some-class') + */ + addClassName(className: string) { + if (this._container) { + this._container.classList.add(className); + } + } + + /** + * Removes a CSS class from the popup container element. + * + * @param {string} className Non-empty string with CSS class name to remove from popup container + * + * @example + * let popup = new mapboxgl.Popup() + * popup.removeClassName('some-class') + */ + removeClassName(className: string) { + if (this._container) { + this._container.classList.remove(className); + } + } + + /** + * Sets the popup's offset. + * + * @param offset Sets the popup's offset. + * @returns {Popup} `this` + */ + setOffset (offset?: Offset) { + this.options.offset = offset; + this._update(); + return this; + } + + /** + * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class. + * + * @param {string} className Non-empty string with CSS class name to add/remove + * + * @returns {boolean} if the class was removed return false, if class was added, then return true + * + * @example + * let popup = new mapboxgl.Popup() + * popup.toggleClassName('toggleClass') + */ + toggleClassName(className: string) { + if (this._container) { + return this._container.classList.toggle(className); + } + } + + _createCloseButton() { + if (this.options.closeButton) { + this._closeButton = DOM.create('button', 'mapboxgl-popup-close-button', this._content); + this._closeButton.type = 'button'; + this._closeButton.setAttribute('aria-label', 'Close popup'); + this._closeButton.innerHTML = '×'; + this._closeButton.addEventListener('click', this._onClose); + } + } + + _onMouseUp(event: MapMouseEvent) { + this._update(event.point); + } + + _onMouseMove(event: MapMouseEvent) { + this._update(event.point); + } + + _onDrag(event: MapMouseEvent) { + this._update(event.point); + } + + _update(cursor: ?PointLike) { + const hasPosition = this._lngLat || this._trackPointer; + + if (!this._map || !hasPosition || !this._content) { return; } + + if (!this._container) { + this._container = DOM.create('div', 'mapboxgl-popup', this._map.getContainer()); + this._tip = DOM.create('div', 'mapboxgl-popup-tip', this._container); + this._container.appendChild(this._content); + if (this.options.className) { + this.options.className.split(' ').forEach(name => + this._container.classList.add(name)); + } + + if (this._trackPointer) { + this._container.classList.add('mapboxgl-popup-track-pointer'); + } + } + + if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) { + this._container.style.maxWidth = this.options.maxWidth; + } + + if (this._map.transform.renderWorldCopies && !this._trackPointer) { + this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform); + } + + if (this._trackPointer && !cursor) return; + + const pos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat); + + let anchor: ?Anchor = this.options.anchor; + const offset = normalizeOffset(this.options.offset); + + if (!anchor) { + const width = this._container.offsetWidth; + const height = this._container.offsetHeight; + let anchorComponents; + + if (pos.y + offset.bottom.y < height) { + anchorComponents = ['top']; + } else if (pos.y > this._map.transform.height - height) { + anchorComponents = ['bottom']; + } else { + anchorComponents = []; + } + + if (pos.x < width / 2) { + anchorComponents.push('left'); + } else if (pos.x > this._map.transform.width - width / 2) { + anchorComponents.push('right'); + } + + if (anchorComponents.length === 0) { + anchor = 'bottom'; + } else { + anchor = (anchorComponents.join('-'): any); + } + } + + const offsetedPos = pos.add(offset[anchor]).round(); + DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`); + applyAnchorClass(this._container, anchor, 'popup'); + } + + _focusFirstElement() { + if (!this.options.focusAfterOpen || !this._container) return; + + const firstFocusable = this._container.querySelector(focusQuerySelector); + + if (firstFocusable) firstFocusable.focus(); + } + + _onClose() { + this.remove(); + } +} + +function normalizeOffset(offset: ?Offset) { + if (!offset) { + return normalizeOffset(new Point(0, 0)); + + } else if (typeof offset === 'number') { + // input specifies a radius from which to calculate offsets at all positions + const cornerOffset = Math.round(Math.sqrt(0.5 * Math.pow(offset, 2))); + return { + 'center': new Point(0, 0), + 'top': new Point(0, offset), + 'top-left': new Point(cornerOffset, cornerOffset), + 'top-right': new Point(-cornerOffset, cornerOffset), + 'bottom': new Point(0, -offset), + 'bottom-left': new Point(cornerOffset, -cornerOffset), + 'bottom-right': new Point(-cornerOffset, -cornerOffset), + 'left': new Point(offset, 0), + 'right': new Point(-offset, 0) + }; + + } else if (offset instanceof Point || Array.isArray(offset)) { + // input specifies a single offset to be applied to all positions + const convertedOffset = Point.convert(offset); + return { + 'center': convertedOffset, + 'top': convertedOffset, + 'top-left': convertedOffset, + 'top-right': convertedOffset, + 'bottom': convertedOffset, + 'bottom-left': convertedOffset, + 'bottom-right': convertedOffset, + 'left': convertedOffset, + 'right': convertedOffset + }; + + } else { + // input specifies an offset per position + return { + 'center': Point.convert(offset['center'] || [0, 0]), + 'top': Point.convert(offset['top'] || [0, 0]), + 'top-left': Point.convert(offset['top-left'] || [0, 0]), + 'top-right': Point.convert(offset['top-right'] || [0, 0]), + 'bottom': Point.convert(offset['bottom'] || [0, 0]), + 'bottom-left': Point.convert(offset['bottom-left'] || [0, 0]), + 'bottom-right': Point.convert(offset['bottom-right'] || [0, 0]), + 'left': Point.convert(offset['left'] || [0, 0]), + 'right': Point.convert(offset['right'] || [0, 0]) + }; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/actor.js b/node_modules/@plotly/mapbox-gl/src/util/actor.js new file mode 100644 index 0000000000000000000000000000000000000000..ac441726c417ecb1fdc15c7c14db4a589f84f785 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/actor.js @@ -0,0 +1,212 @@ +// @flow + +import {bindAll, isWorker, isSafari} from './util'; +import window from './window'; +import {serialize, deserialize} from './web_worker_transfer'; +import ThrottledInvoker from './throttled_invoker'; + +import type {Transferable} from '../types/transferable'; +import type {Cancelable} from '../types/cancelable'; + +/** + * An implementation of the [Actor design pattern](http://en.wikipedia.org/wiki/Actor_model) + * that maintains the relationship between asynchronous tasks and the objects + * that spin them off - in this case, tasks like parsing parts of styles, + * owned by the styles + * + * @param {WebWorker} target + * @param {WebWorker} parent + * @param {string|number} mapId A unique identifier for the Map instance using this Actor. + * @private + */ +class Actor { + target: any; + parent: any; + mapId: ?number; + callbacks: { number: any }; + name: string; + tasks: { number: any }; + taskQueue: Array; + cancelCallbacks: { number: Cancelable }; + invoker: ThrottledInvoker; + globalScope: any; + + constructor(target: any, parent: any, mapId: ?number) { + this.target = target; + this.parent = parent; + this.mapId = mapId; + this.callbacks = {}; + this.tasks = {}; + this.taskQueue = []; + this.cancelCallbacks = {}; + bindAll(['receive', 'process'], this); + this.invoker = new ThrottledInvoker(this.process); + this.target.addEventListener('message', this.receive, false); + this.globalScope = isWorker() ? target : window; + } + + /** + * Sends a message from a main-thread map to a Worker or from a Worker back to + * a main-thread map instance. + * + * @param type The name of the target method to invoke or '[source-type].[source-name].name' for a method on a WorkerSource. + * @param targetMapId A particular mapId to which to send this message. + * @private + */ + send(type: string, data: mixed, callback: ?Function, targetMapId: ?string, mustQueue: boolean = false): ?Cancelable { + // We're using a string ID instead of numbers because they are being used as object keys + // anyway, and thus stringified implicitly. We use random IDs because an actor may receive + // message from multiple other actors which could run in different execution context. A + // linearly increasing ID could produce collisions. + const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10); + if (callback) { + this.callbacks[id] = callback; + } + const buffers: ?Array = isSafari(this.globalScope) ? undefined : []; + this.target.postMessage({ + id, + type, + hasCallback: !!callback, + targetMapId, + mustQueue, + sourceMapId: this.mapId, + data: serialize(data, buffers) + }, buffers); + return { + cancel: () => { + if (callback) { + // Set the callback to null so that it never fires after the request is aborted. + delete this.callbacks[id]; + } + this.target.postMessage({ + id, + type: '', + targetMapId, + sourceMapId: this.mapId + }); + } + }; + } + + receive(message: Object) { + const data = message.data, + id = data.id; + + if (!id) { + return; + } + + if (data.targetMapId && this.mapId !== data.targetMapId) { + return; + } + + if (data.type === '') { + // Remove the original request from the queue. This is only possible if it + // hasn't been kicked off yet. The id will remain in the queue, but because + // there is no associated task, it will be dropped once it's time to execute it. + delete this.tasks[id]; + const cancel = this.cancelCallbacks[id]; + delete this.cancelCallbacks[id]; + if (cancel) { + cancel(); + } + } else { + if (isWorker() || data.mustQueue) { + // In workers, store the tasks that we need to process before actually processing them. This + // is necessary because we want to keep receiving messages, and in particular, + // messages. Some tasks may take a while in the worker thread, so before + // executing the next task in our queue, postMessage preempts this and + // messages can be processed. We're using a MessageChannel object to get throttle the + // process() flow to one at a time. + this.tasks[id] = data; + this.taskQueue.push(id); + this.invoker.trigger(); + } else { + // In the main thread, process messages immediately so that other work does not slip in + // between getting partial data back from workers. + this.processTask(id, data); + } + } + } + + process() { + if (!this.taskQueue.length) { + return; + } + const id = this.taskQueue.shift(); + const task = this.tasks[id]; + delete this.tasks[id]; + // Schedule another process call if we know there's more to process _before_ invoking the + // current task. This is necessary so that processing continues even if the current task + // doesn't execute successfully. + if (this.taskQueue.length) { + this.invoker.trigger(); + } + if (!task) { + // If the task ID doesn't have associated task data anymore, it was canceled. + return; + } + + this.processTask(id, task); + } + + processTask(id: number, task: any) { + if (task.type === '') { + // The done() function in the counterpart has been called, and we are now + // firing the callback in the originating actor, if there is one. + const callback = this.callbacks[id]; + delete this.callbacks[id]; + if (callback) { + // If we get a response, but don't have a callback, the request was canceled. + if (task.error) { + callback(deserialize(task.error)); + } else { + callback(null, deserialize(task.data)); + } + } + } else { + let completed = false; + const buffers: ?Array = isSafari(this.globalScope) ? undefined : []; + const done = task.hasCallback ? (err, data) => { + completed = true; + delete this.cancelCallbacks[id]; + this.target.postMessage({ + id, + type: '', + sourceMapId: this.mapId, + error: err ? serialize(err) : null, + data: serialize(data, buffers) + }, buffers); + } : (_) => { + completed = true; + }; + + let callback = null; + const params = (deserialize(task.data): any); + if (this.parent[task.type]) { + // task.type == 'loadTile', 'removeTile', etc. + callback = this.parent[task.type](task.sourceMapId, params, done); + } else if (this.parent.getWorkerSource) { + // task.type == sourcetype.method + const keys = task.type.split('.'); + const scope = (this.parent: any).getWorkerSource(task.sourceMapId, keys[0], params.source); + callback = scope[keys[1]](params, done); + } else { + // No function was found. + done(new Error(`Could not find function ${task.type}`)); + } + + if (!completed && callback && callback.cancel) { + // Allows canceling the task as long as it hasn't been completed yet. + this.cancelCallbacks[id] = callback.cancel; + } + } + } + + remove() { + this.invoker.remove(); + this.target.removeEventListener('message', this.receive, false); + } +} + +export default Actor; diff --git a/node_modules/@plotly/mapbox-gl/src/util/ajax.js b/node_modules/@plotly/mapbox-gl/src/util/ajax.js new file mode 100644 index 0000000000000000000000000000000000000000..e3dfeeef0e905f40488b4de0689155ab793e540d --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/ajax.js @@ -0,0 +1,388 @@ +// @flow + +import window from './window'; +import {extend, warnOnce, isWorker} from './util'; +import {isMapboxHTTPURL, hasCacheDefeatingSku} from './mapbox'; +import config from './config'; +import assert from 'assert'; +import {cacheGet, cachePut} from './tile_request_cache'; +import webpSupported from './webp_supported'; +import offscreenCanvasSupported from './offscreen_canvas_supported'; + +import type {Callback} from '../types/callback'; +import type {Cancelable} from '../types/cancelable'; + +/** + * The type of a resource. + * @private + * @readonly + * @enum {string} + */ +const ResourceType = { + Unknown: 'Unknown', + Style: 'Style', + Source: 'Source', + Tile: 'Tile', + Glyphs: 'Glyphs', + SpriteImage: 'SpriteImage', + SpriteJSON: 'SpriteJSON', + Image: 'Image' +}; +export {ResourceType}; + +if (typeof Object.freeze == 'function') { + Object.freeze(ResourceType); +} + +/** + * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks. + * @typedef {Object} RequestParameters + * @property {string} url The URL to be requested. + * @property {Object} headers The headers to be sent with the request. + * @property {string} method Request method `'GET' | 'POST' | 'PUT'`. + * @property {string} body Request body. + * @property {string} type Response body type to be returned `'string' | 'json' | 'arrayBuffer'`. + * @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests. + * @property {boolean} collectResourceTiming If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events. + * @example + * // use transformRequest to modify requests that begin with `http://myHost` + * transformRequest: function(url, resourceType) { + * if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true }, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * + */ +export type RequestParameters = { + url: string, + headers?: Object, + method?: 'GET' | 'POST' | 'PUT', + body?: string, + type?: 'string' | 'json' | 'arrayBuffer', + credentials?: 'same-origin' | 'include', + collectResourceTiming?: boolean +}; + +export type ResponseCallback = (error: ?Error, data: ?T, cacheControl: ?string, expires: ?string) => void; + +class AJAXError extends Error { + status: number; + url: string; + constructor(message: string, status: number, url: string) { + if (status === 401 && isMapboxHTTPURL(url)) { + message += ': you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes'; + } + super(message); + this.status = status; + this.url = url; + + // work around for https://github.com/Rich-Harris/buble/issues/40 + this.name = this.constructor.name; + this.message = message; + } + + toString() { + return `${this.name}: ${this.message} (${this.status}): ${this.url}`; + } +} + +// Ensure that we're sending the correct referrer from blob URL worker bundles. +// For files loaded from the local file system, `location.origin` will be set +// to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge, IE), +// and we will set an empty referrer. Otherwise, we're using the document's URL. +/* global self */ +export const getReferrer = isWorker() ? + () => self.worker && self.worker.referrer : + () => (window.location.protocol === 'blob:' ? window.parent : window).location.href; + +// Determines whether a URL is a file:// URL. This is obviously the case if it begins +// with file://. Relative URLs are also file:// URLs iff the original document was loaded +// via a file:// URL. +const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url)); + +function makeFetchRequest(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + const controller = new window.AbortController(); + const request = new window.Request(requestParameters.url, { + method: requestParameters.method || 'GET', + body: requestParameters.body, + credentials: requestParameters.credentials, + headers: requestParameters.headers, + referrer: getReferrer(), + signal: controller.signal + }); + let complete = false; + let aborted = false; + + const cacheIgnoringSearch = hasCacheDefeatingSku(request.url); + + if (requestParameters.type === 'json') { + request.headers.set('Accept', 'application/json'); + } + + const validateOrFetch = (err, cachedResponse, responseIsFresh) => { + if (aborted) return; + + if (err) { + // Do fetch in case of cache error. + // HTTP pages in Edge trigger a security error that can be ignored. + if (err.message !== 'SecurityError') { + warnOnce(err); + } + } + + if (cachedResponse && responseIsFresh) { + return finishRequest(cachedResponse); + } + + if (cachedResponse) { + // We can't do revalidation with 'If-None-Match' because then the + // request doesn't have simple cors headers. + } + + const requestTime = Date.now(); + + window.fetch(request).then(response => { + if (response.ok) { + const cacheableResponse = cacheIgnoringSearch ? response.clone() : null; + return finishRequest(response, cacheableResponse, requestTime); + + } else { + return callback(new AJAXError(response.statusText, response.status, requestParameters.url)); + } + }).catch(error => { + if (error.code === 20) { + // silence expected AbortError + return; + } + callback(new Error(error.message)); + }); + }; + + const finishRequest = (response, cacheableResponse, requestTime) => { + ( + requestParameters.type === 'arrayBuffer' ? response.arrayBuffer() : + requestParameters.type === 'json' ? response.json() : + response.text() + ).then(result => { + if (aborted) return; + if (cacheableResponse && requestTime) { + // The response needs to be inserted into the cache after it has completely loaded. + // Until it is fully loaded there is a chance it will be aborted. Aborting while + // reading the body can cause the cache insertion to error. We could catch this error + // in most browsers but in Firefox it seems to sometimes crash the tab. Adding + // it to the cache here avoids that error. + cachePut(request, cacheableResponse, requestTime); + } + complete = true; + callback(null, result, response.headers.get('Cache-Control'), response.headers.get('Expires')); + }).catch(err => { + if (!aborted) callback(new Error(err.message)); + }); + }; + + if (cacheIgnoringSearch) { + cacheGet(request, validateOrFetch); + } else { + validateOrFetch(null, null); + } + + return {cancel: () => { + aborted = true; + if (!complete) controller.abort(); + }}; +} + +function makeXMLHttpRequest(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + const xhr: XMLHttpRequest = new window.XMLHttpRequest(); + + xhr.open(requestParameters.method || 'GET', requestParameters.url, true); + if (requestParameters.type === 'arrayBuffer') { + xhr.responseType = 'arraybuffer'; + } + for (const k in requestParameters.headers) { + xhr.setRequestHeader(k, requestParameters.headers[k]); + } + if (requestParameters.type === 'json') { + xhr.responseType = 'text'; + xhr.setRequestHeader('Accept', 'application/json'); + } + xhr.withCredentials = requestParameters.credentials === 'include'; + xhr.onerror = () => { + callback(new Error(xhr.statusText)); + }; + xhr.onload = () => { + if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) { + let data: mixed = xhr.response; + if (requestParameters.type === 'json') { + // We're manually parsing JSON here to get better error messages. + try { + data = JSON.parse(xhr.response); + } catch (err) { + return callback(err); + } + } + callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires')); + } else { + callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url)); + } + }; + xhr.send(requestParameters.body); + return {cancel: () => xhr.abort()}; +} + +export const makeRequest = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + // We're trying to use the Fetch API if possible. However, in some situations we can't use it: + // - IE11 doesn't support it at all. In this case, we dispatch the request to the main thread so + // that we can get an accruate referrer header. + // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in + // some versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2) + // - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In + // this case we unconditionally use XHR on the current thread since referrers don't matter. + if (!isFileURL(requestParameters.url)) { + if (window.fetch && window.Request && window.AbortController && window.Request.prototype.hasOwnProperty('signal')) { + return makeFetchRequest(requestParameters, callback); + } + if (isWorker() && self.worker && self.worker.actor) { + const queueOnMainThread = true; + return self.worker.actor.send('getResource', requestParameters, callback, undefined, queueOnMainThread); + } + } + return makeXMLHttpRequest(requestParameters, callback); +}; + +export const getJSON = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + return makeRequest(extend(requestParameters, {type: 'json'}), callback); +}; + +export const getArrayBuffer = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), callback); +}; + +export const postData = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + return makeRequest(extend(requestParameters, {method: 'POST'}), callback); +}; + +function sameOrigin(url) { + const a: HTMLAnchorElement = window.document.createElement('a'); + a.href = url; + return a.protocol === window.document.location.protocol && a.host === window.document.location.host; +} + +const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; + +function arrayBufferToImage(data: ArrayBuffer, callback: (err: ?Error, image: ?HTMLImageElement) => void, cacheControl: ?string, expires: ?string) { + const img: HTMLImageElement = new window.Image(); + const URL = window.URL; + img.onload = () => { + callback(null, img); + URL.revokeObjectURL(img.src); + // prevent image dataURI memory leak in Safari; + // but don't free the image immediately because it might be uploaded in the next frame + // https://github.com/mapbox/mapbox-gl-js/issues/10226 + img.onload = null; + window.requestAnimationFrame(() => { img.src = transparentPngUrl; }); + }; + img.onerror = () => callback(new Error('Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.')); + const blob: Blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'}); + (img: any).cacheControl = cacheControl; + (img: any).expires = expires; + img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; +} + +function arrayBufferToImageBitmap(data: ArrayBuffer, callback: (err: ?Error, image: ?ImageBitmap) => void) { + const blob: Blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'}); + window.createImageBitmap(blob).then((imgBitmap) => { + callback(null, imgBitmap); + }).catch((e) => { + callback(new Error(`Could not load image because of ${e.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)); + }); +} + +let imageQueue, numImageRequests; +export const resetImageRequestQueue = () => { + imageQueue = []; + numImageRequests = 0; +}; +resetImageRequestQueue(); + +export const getImage = function(requestParameters: RequestParameters, callback: Callback): Cancelable { + if (webpSupported.supported) { + if (!requestParameters.headers) { + requestParameters.headers = {}; + } + requestParameters.headers.accept = 'image/webp,*/*'; + } + + // limit concurrent image loads to help with raster sources performance on big screens + if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) { + const queued = { + requestParameters, + callback, + cancelled: false, + cancel() { this.cancelled = true; } + }; + imageQueue.push(queued); + return queued; + } + numImageRequests++; + + let advanced = false; + const advanceImageRequestQueue = () => { + if (advanced) return; + advanced = true; + numImageRequests--; + assert(numImageRequests >= 0); + while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) { // eslint-disable-line + const request = imageQueue.shift(); + const {requestParameters, callback, cancelled} = request; + if (!cancelled) { + request.cancel = getImage(requestParameters, callback).cancel; + } + } + }; + + // request the image with XHR to work around caching issues + // see https://github.com/mapbox/mapbox-gl-js/issues/1470 + const request = getArrayBuffer(requestParameters, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => { + + advanceImageRequestQueue(); + + if (err) { + callback(err); + } else if (data) { + if (offscreenCanvasSupported()) { + arrayBufferToImageBitmap(data, callback); + } else { + arrayBufferToImage(data, callback, cacheControl, expires); + } + } + }); + + return { + cancel: () => { + request.cancel(); + advanceImageRequestQueue(); + } + }; +}; + +export const getVideo = function(urls: Array, callback: Callback): Cancelable { + const video: HTMLVideoElement = window.document.createElement('video'); + video.muted = true; + video.onloadstart = function() { + callback(null, video); + }; + for (let i = 0; i < urls.length; i++) { + const s: HTMLSourceElement = window.document.createElement('source'); + if (!sameOrigin(urls[i])) { + video.crossOrigin = 'Anonymous'; + } + s.src = urls[i]; + video.appendChild(s); + } + return {cancel: () => {}}; +}; diff --git a/node_modules/@plotly/mapbox-gl/src/util/browser.js b/node_modules/@plotly/mapbox-gl/src/util/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..808a6fcc5c44eb44aa431312058d28fb8bac2cf1 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/browser.js @@ -0,0 +1,70 @@ +// @flow strict + +import window from './window'; +import type {Cancelable} from '../types/cancelable'; + +const now = window.performance && window.performance.now ? + window.performance.now.bind(window.performance) : + Date.now.bind(Date); + +const raf = window.requestAnimationFrame || + window.mozRequestAnimationFrame || + window.webkitRequestAnimationFrame || + window.msRequestAnimationFrame; + +const cancel = window.cancelAnimationFrame || + window.mozCancelAnimationFrame || + window.webkitCancelAnimationFrame || + window.msCancelAnimationFrame; + +let linkEl; + +let reducedMotionQuery: MediaQueryList; + +/** + * @private + */ +const exported = { + /** + * Provides a function that outputs milliseconds: either performance.now() + * or a fallback to Date.now() + */ + now, + + frame(fn: (paintStartTimestamp: number) => void): Cancelable { + const frame = raf(fn); + return {cancel: () => cancel(frame)}; + }, + + getImageData(img: CanvasImageSource, padding?: number = 0): ImageData { + const canvas = window.document.createElement('canvas'); + const context = canvas.getContext('2d'); + if (!context) { + throw new Error('failed to create canvas 2d context'); + } + canvas.width = img.width; + canvas.height = img.height; + context.drawImage(img, 0, 0, img.width, img.height); + return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding); + }, + + resolveURL(path: string) { + if (!linkEl) linkEl = window.document.createElement('a'); + linkEl.href = path; + return linkEl.href; + }, + + hardwareConcurrency: window.navigator && window.navigator.hardwareConcurrency || 4, + + get devicePixelRatio() { return window.devicePixelRatio; }, + get prefersReducedMotion(): boolean { + if (!window.matchMedia) return false; + //Lazily initialize media query + if (reducedMotionQuery == null) { + reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)'); + } + return reducedMotionQuery.matches; + }, +}; + +export default exported; diff --git a/node_modules/@plotly/mapbox-gl/src/util/browser/web_worker.js b/node_modules/@plotly/mapbox-gl/src/util/browser/web_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..3d1314da10c67709e05333e8abfc470ee45862fa --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/browser/web_worker.js @@ -0,0 +1,10 @@ +// @flow + +import window from '../window'; +import mapboxgl from '../../'; + +import type {WorkerInterface} from '../web_worker'; + +export default function (): WorkerInterface { + return (new window.Worker(mapboxgl.workerUrl): any); +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/browser/window.js b/node_modules/@plotly/mapbox-gl/src/util/browser/window.js new file mode 100644 index 0000000000000000000000000000000000000000..d2ceea5613a7aa964d4c7ba5cdb4093428359836 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/browser/window.js @@ -0,0 +1,6 @@ +// @flow +/* eslint-env browser */ +import type {Window} from '../../types/window'; + +// shim window for the case of requiring the browser bundle in Node +export default typeof self !== 'undefined' ? (self: Window) : (({}: any): Window); diff --git a/node_modules/@plotly/mapbox-gl/src/util/classify_rings.js b/node_modules/@plotly/mapbox-gl/src/util/classify_rings.js new file mode 100644 index 0000000000000000000000000000000000000000..3d18b60fcab59e7c232e67815b505123e77eabcf --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/classify_rings.js @@ -0,0 +1,52 @@ +// @flow + +import quickselect from 'quickselect'; + +import {calculateSignedArea} from './util'; + +import type Point from '@mapbox/point-geometry'; + +// classifies an array of rings into polygons with outer rings and holes +export default function classifyRings(rings: Array>, maxRings: number) { + const len = rings.length; + + if (len <= 1) return [rings]; + + const polygons = []; + let polygon, + ccw; + + for (let i = 0; i < len; i++) { + const area = calculateSignedArea(rings[i]); + if (area === 0) continue; + + (rings[i]: any).area = Math.abs(area); + + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + + } else { + (polygon: any).push(rings[i]); + } + } + if (polygon) polygons.push(polygon); + + // Earcut performance degrades with the # of rings in a polygon. For this + // reason, we limit strip out all but the `maxRings` largest rings. + if (maxRings > 1) { + for (let j = 0; j < polygons.length; j++) { + if (polygons[j].length <= maxRings) continue; + quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas); + polygons[j] = polygons[j].slice(0, maxRings); + } + } + + return polygons; +} + +function compareAreas(a, b) { + return b.area - a.area; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/color_ramp.js b/node_modules/@plotly/mapbox-gl/src/util/color_ramp.js new file mode 100644 index 0000000000000000000000000000000000000000..24dc0758699865939ac88d23c97124c18ac9621a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/color_ramp.js @@ -0,0 +1,61 @@ +// @flow + +import {RGBAImage} from './image'; +import {isPowerOfTwo} from './util'; +import assert from 'assert'; + +import type {StylePropertyExpression} from '../style-spec/expression/index'; + +export type ColorRampParams = { + expression: StylePropertyExpression; + evaluationKey: string; + resolution?: number; + image?: RGBAImage; + clips?: Array; +} + +/** + * Given an expression that should evaluate to a color ramp, + * return a RGBA image representing that ramp expression. + * + * @private + */ +export function renderColorRamp(params: ColorRampParams): RGBAImage { + const evaluationGlobals = {}; + const width = params.resolution || 256; + const height = params.clips ? params.clips.length : 1; + const image = params.image || new RGBAImage({width, height}); + + assert(isPowerOfTwo(width)); + + const renderPixel = (stride, index, progress) => { + evaluationGlobals[params.evaluationKey] = progress; + const pxColor = params.expression.evaluate((evaluationGlobals: any)); + // the colors are being unpremultiplied because Color uses + // premultiplied values, and the Texture class expects unpremultiplied ones + image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a); + image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a); + image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a); + image.data[stride + index + 3] = Math.floor(pxColor.a * 255); + }; + + if (!params.clips) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + const progress = i / (width - 1); + + renderPixel(0, j, progress); + } + } else { + for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + // Remap progress between clips + const progress = i / (width - 1); + const {start, end} = params.clips[clip]; + const evaluationProgress = start * (1 - progress) + end * progress; + renderPixel(stride, j, evaluationProgress); + } + } + } + + return image; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/config.js b/node_modules/@plotly/mapbox-gl/src/util/config.js new file mode 100644 index 0000000000000000000000000000000000000000..8c9872d1d2092fa6ef8eeef9d9d049d842154416 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/config.js @@ -0,0 +1,30 @@ +// @flow strict + +type Config = {| + API_URL: string, + EVENTS_URL: ?string, + FEEDBACK_URL: string, + REQUIRE_ACCESS_TOKEN: boolean, + ACCESS_TOKEN: ?string, + MAX_PARALLEL_IMAGE_REQUESTS: number +|}; + +const config: Config = { + API_URL: 'https://api.mapbox.com', + get EVENTS_URL() { + if (!this.API_URL) { return null; } + if (this.API_URL.indexOf('https://api.mapbox.cn') === 0) { + return 'https://events.mapbox.cn/events/v2'; + } else if (this.API_URL.indexOf('https://api.mapbox.com') === 0) { + return 'https://events.mapbox.com/events/v2'; + } else { + return null; + } + }, + FEEDBACK_URL: 'https://apps.mapbox.com/feedback', + REQUIRE_ACCESS_TOKEN: true, + ACCESS_TOKEN: null, + MAX_PARALLEL_IMAGE_REQUESTS: 16 +}; + +export default config; diff --git a/node_modules/@plotly/mapbox-gl/src/util/debug.js b/node_modules/@plotly/mapbox-gl/src/util/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..e26672e7472602c1fe2f250d797770b58ebcdb42 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/debug.js @@ -0,0 +1,28 @@ +// @flow +import {extend} from './util'; +import window from './window'; + +/** + * This is a private namespace for utility functions that will get automatically stripped + * out in production builds. + * + * @private + */ +export const Debug = { + extend(dest: Object, ...sources: Array): Object { + return extend(dest, ...sources); + }, + + run(fn: () => any) { + fn(); + }, + + logToElement(message: string, overwrite: boolean = false, id: string = "log") { + const el = window.document.getElementById(id); + if (el) { + if (overwrite) el.innerHTML = ''; + el.innerHTML += `
${message}`; + } + + } +}; diff --git a/node_modules/@plotly/mapbox-gl/src/util/dictionary_coder.js b/node_modules/@plotly/mapbox-gl/src/util/dictionary_coder.js new file mode 100644 index 0000000000000000000000000000000000000000..320eb3548f8040169669be827d2c60df58f9d542 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/dictionary_coder.js @@ -0,0 +1,30 @@ +// @flow strict + +import assert from 'assert'; + +class DictionaryCoder { + _stringToNumber: {[_: string]: number }; + _numberToString: Array; + + constructor(strings: Array) { + this._stringToNumber = {}; + this._numberToString = []; + for (let i = 0; i < strings.length; i++) { + const string = strings[i]; + this._stringToNumber[string] = i; + this._numberToString[i] = string; + } + } + + encode(string: string) { + assert(string in this._stringToNumber); + return this._stringToNumber[string]; + } + + decode(n: number) { + assert(n < this._numberToString.length); + return this._numberToString[n]; + } +} + +export default DictionaryCoder; diff --git a/node_modules/@plotly/mapbox-gl/src/util/dispatcher.js b/node_modules/@plotly/mapbox-gl/src/util/dispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..7a184f8489eb33baf223c83cf53086eb42ae9ee7 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/dispatcher.js @@ -0,0 +1,70 @@ +// @flow + +import {uniqueId, asyncAll} from './util'; +import Actor from './actor'; +import assert from 'assert'; + +import type WorkerPool from './worker_pool'; + +/** + * Responsible for sending messages from a {@link Source} to an associated + * {@link WorkerSource}. + * + * @private + */ +class Dispatcher { + workerPool: WorkerPool; + actors: Array; + currentActor: number; + id: number; + + // exposed to allow stubbing in unit tests + static Actor: Class; + + constructor(workerPool: WorkerPool, parent: any) { + this.workerPool = workerPool; + this.actors = []; + this.currentActor = 0; + this.id = uniqueId(); + const workers = this.workerPool.acquire(this.id); + for (let i = 0; i < workers.length; i++) { + const worker = workers[i]; + const actor = new Dispatcher.Actor(worker, parent, this.id); + actor.name = `Worker ${i}`; + this.actors.push(actor); + } + assert(this.actors.length); + } + + /** + * Broadcast a message to all Workers. + * @private + */ + broadcast(type: string, data: mixed, cb?: Function) { + assert(this.actors.length); + cb = cb || function () {}; + asyncAll(this.actors, (actor, done) => { + actor.send(type, data, done); + }, cb); + } + + /** + * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion. + * @returns An actor object backed by a web worker for processing messages. + */ + getActor(): Actor { + assert(this.actors.length); + this.currentActor = (this.currentActor + 1) % this.actors.length; + return this.actors[this.currentActor]; + } + + remove() { + this.actors.forEach((actor) => { actor.remove(); }); + this.actors = []; + this.workerPool.release(this.id); + } +} + +Dispatcher.Actor = Actor; + +export default Dispatcher; diff --git a/node_modules/@plotly/mapbox-gl/src/util/dom.js b/node_modules/@plotly/mapbox-gl/src/util/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..34e2af64f8ba70058d13cb72f2f6dd1e91be6acc --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/dom.js @@ -0,0 +1,142 @@ +// @flow strict + +import Point from '@mapbox/point-geometry'; + +import window from './window'; +import assert from 'assert'; + +const DOM = {}; +export default DOM; + +DOM.create = function (tagName: string, className: ?string, container?: HTMLElement) { + const el = window.document.createElement(tagName); + if (className !== undefined) el.className = className; + if (container) container.appendChild(el); + return el; +}; + +DOM.createNS = function (namespaceURI: string, tagName: string) { + const el = window.document.createElementNS(namespaceURI, tagName); + return el; +}; + +const docStyle = window.document && window.document.documentElement.style; + +function testProp(props) { + if (!docStyle) return props[0]; + for (let i = 0; i < props.length; i++) { + if (props[i] in docStyle) { + return props[i]; + } + } + return props[0]; +} + +const selectProp = testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']); +let userSelect; + +DOM.disableDrag = function () { + if (docStyle && selectProp) { + userSelect = docStyle[selectProp]; + docStyle[selectProp] = 'none'; + } +}; + +DOM.enableDrag = function () { + if (docStyle && selectProp) { + docStyle[selectProp] = userSelect; + } +}; + +const transformProp = testProp(['transform', 'WebkitTransform']); + +DOM.setTransform = function(el: HTMLElement, value: string) { + // https://github.com/facebook/flow/issues/7754 + // $FlowFixMe + el.style[transformProp] = value; +}; + +// Feature detection for {passive: false} support in add/removeEventListener. +let passiveSupported = false; + +try { + // https://github.com/facebook/flow/issues/285 + // $FlowFixMe + const options = Object.defineProperty({}, "passive", { + get() { // eslint-disable-line + passiveSupported = true; + } + }); + window.addEventListener("test", options, options); + window.removeEventListener("test", options, options); +} catch (err) { + passiveSupported = false; +} + +DOM.addEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) { + if ('passive' in options && passiveSupported) { + target.addEventListener(type, callback, options); + } else { + target.addEventListener(type, callback, options.capture); + } +}; + +DOM.removeEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) { + if ('passive' in options && passiveSupported) { + target.removeEventListener(type, callback, options); + } else { + target.removeEventListener(type, callback, options.capture); + } +}; + +// Suppress the next click, but only if it's immediate. +const suppressClick: MouseEventListener = function (e) { + e.preventDefault(); + e.stopPropagation(); + window.removeEventListener('click', suppressClick, true); +}; + +DOM.suppressClick = function() { + window.addEventListener('click', suppressClick, true); + window.setTimeout(() => { + window.removeEventListener('click', suppressClick, true); + }, 0); +}; + +DOM.mousePos = function (el: HTMLElement, e: MouseEvent | window.TouchEvent | Touch) { + const rect = el.getBoundingClientRect(); + return new Point( + e.clientX - rect.left - el.clientLeft, + e.clientY - rect.top - el.clientTop + ); +}; + +DOM.touchPos = function (el: HTMLElement, touches: TouchList) { + const rect = el.getBoundingClientRect(), + points = []; + for (let i = 0; i < touches.length; i++) { + points.push(new Point( + touches[i].clientX - rect.left - el.clientLeft, + touches[i].clientY - rect.top - el.clientTop + )); + } + return points; +}; + +DOM.mouseButton = function (e: MouseEvent) { + assert(e.type === 'mousedown' || e.type === 'mouseup'); + if (typeof window.InstallTrigger !== 'undefined' && e.button === 2 && e.ctrlKey && + window.navigator.platform.toUpperCase().indexOf('MAC') >= 0) { + // Fix for https://github.com/mapbox/mapbox-gl-js/issues/3131: + // Firefox (detected by InstallTrigger) on Mac determines e.button = 2 when + // using Control + left click + return 0; + } + return e.button; +}; + +DOM.remove = function(node: HTMLElement) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +}; diff --git a/node_modules/@plotly/mapbox-gl/src/util/evented.js b/node_modules/@plotly/mapbox-gl/src/util/evented.js new file mode 100644 index 0000000000000000000000000000000000000000..de05d10921961a979013dc9cc3e3dc5a243cb8a2 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/evented.js @@ -0,0 +1,174 @@ +// @flow + +import {extend} from './util'; + +type Listener = (Object) => any; +type Listeners = {[_: string]: Array }; + +function _addEventListener(type: string, listener: Listener, listenerList: Listeners) { + const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1; + if (!listenerExists) { + listenerList[type] = listenerList[type] || []; + listenerList[type].push(listener); + } +} + +function _removeEventListener(type: string, listener: Listener, listenerList: Listeners) { + if (listenerList && listenerList[type]) { + const index = listenerList[type].indexOf(listener); + if (index !== -1) { + listenerList[type].splice(index, 1); + } + } +} + +export class Event { + +type: string; + + constructor(type: string, data: Object = {}) { + extend(this, data); + this.type = type; + } +} + +interface ErrorLike { + message: string; +} + +export class ErrorEvent extends Event { + error: ErrorLike; + + constructor(error: ErrorLike, data: Object = {}) { + super('error', extend({error}, data)); + } +} + +/** + * Methods mixed in to other classes for event capabilities. + * + * @mixin Evented + */ +export class Evented { + _listeners: Listeners; + _oneTimeListeners: Listeners; + _eventedParent: ?Evented; + _eventedParentData: ?(Object | () => Object); + + /** + * Adds a listener to a specified event type. + * + * @param {string} type The event type to add a listen for. + * @param {Function} listener The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + * @returns {Object} `this` + */ + on(type: *, listener: Listener): this { + this._listeners = this._listeners || {}; + _addEventListener(type, listener, this._listeners); + + return this; + } + + /** + * Removes a previously registered event listener. + * + * @param {string} type The event type to remove listeners for. + * @param {Function} listener The listener function to remove. + * @returns {Object} `this` + */ + off(type: *, listener: Listener) { + _removeEventListener(type, listener, this._listeners); + _removeEventListener(type, listener, this._oneTimeListeners); + + return this; + } + + /** + * Adds a listener that will be called only once to a specified event type. + * + * The listener will be called first time the event fires after the listener is registered. + * + * @param {string} type The event type to listen for. + * @param {Function} listener The function to be called when the event is fired the first time. + * @returns {Object} `this` + */ + once(type: *, listener: Listener) { + this._oneTimeListeners = this._oneTimeListeners || {}; + _addEventListener(type, listener, this._oneTimeListeners); + + return this; + } + + fire(event: Event, properties?: Object) { + // Compatibility with (type: string, properties: Object) signature from previous versions. + // See https://github.com/mapbox/mapbox-gl-js/issues/6522, + // https://github.com/mapbox/mapbox-gl-draw/issues/766 + if (typeof event === 'string') { + event = new Event(event, properties || {}); + } + + const type = event.type; + + if (this.listens(type)) { + (event: any).target = this; + + // make sure adding or removing listeners inside other listeners won't cause an infinite loop + const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : []; + for (const listener of listeners) { + listener.call(this, event); + } + + const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : []; + for (const listener of oneTimeListeners) { + _removeEventListener(type, listener, this._oneTimeListeners); + listener.call(this, event); + } + + const parent = this._eventedParent; + if (parent) { + extend( + event, + typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData + ); + parent.fire(event); + } + + // To ensure that no error events are dropped, print them to the + // console if they have no listeners. + } else if (event instanceof ErrorEvent) { + console.error(event.error); + } + + return this; + } + + /** + * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. + * + * @param {string} type The event type + * @returns {boolean} `true` if there is at least one registered listener for specified event type, `false` otherwise + * @private + */ + listens(type: string) { + return ( + (this._listeners && this._listeners[type] && this._listeners[type].length > 0) || + (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) || + (this._eventedParent && this._eventedParent.listens(type)) + ); + } + + /** + * Bubble all events fired by this instance of Evented to this parent instance of Evented. + * + * @private + * @returns {Object} `this` + * @private + */ + setEventedParent(parent: ?Evented, data?: Object | () => Object) { + this._eventedParent = parent; + this._eventedParentData = data; + + return this; + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/find_pole_of_inaccessibility.js b/node_modules/@plotly/mapbox-gl/src/util/find_pole_of_inaccessibility.js new file mode 100644 index 0000000000000000000000000000000000000000..5bf8c1c44c852215229c3ce8b17da668124ce834 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/find_pole_of_inaccessibility.js @@ -0,0 +1,129 @@ +// @flow + +import Queue from 'tinyqueue'; + +import Point from '@mapbox/point-geometry'; +import {distToSegmentSquared} from './intersection_tests'; + +/** + * Finds an approximation of a polygon's Pole Of Inaccessibiliy https://en.wikipedia.org/wiki/Pole_of_inaccessibility + * This is a copy of http://github.com/mapbox/polylabel adapted to use Points + * + * @param polygonRings first item in array is the outer ring followed optionally by the list of holes, should be an element of the result of util/classify_rings + * @param precision Specified in input coordinate units. If 0 returns after first run, if > 0 repeatedly narrows the search space until the radius of the area searched for the best pole is less than precision + * @param debug Print some statistics to the console during execution + * @returns Pole of Inaccessibiliy. + * @private + */ +export default function (polygonRings: Array>, precision?: number = 1, debug?: boolean = false): Point { + // find the bounding box of the outer ring + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const outerRing = polygonRings[0]; + for (let i = 0; i < outerRing.length; i++) { + const p = outerRing[i]; + if (!i || p.x < minX) minX = p.x; + if (!i || p.y < minY) minY = p.y; + if (!i || p.x > maxX) maxX = p.x; + if (!i || p.y > maxY) maxY = p.y; + } + + const width = maxX - minX; + const height = maxY - minY; + const cellSize = Math.min(width, height); + let h = cellSize / 2; + + // a priority queue of cells in order of their "potential" (max distance to polygon) + const cellQueue = new Queue([], compareMax); + + if (cellSize === 0) return new Point(minX, minY); + + // cover polygon with initial cells + for (let x = minX; x < maxX; x += cellSize) { + for (let y = minY; y < maxY; y += cellSize) { + cellQueue.push(new Cell(x + h, y + h, h, polygonRings)); + } + } + + // take centroid as the first best guess + let bestCell = getCentroidCell(polygonRings); + let numProbes = cellQueue.length; + + while (cellQueue.length) { + // pick the most promising cell from the queue + const cell = cellQueue.pop(); + + // update the best cell if we found a better one + if (cell.d > bestCell.d || !bestCell.d) { + bestCell = cell; + if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes); + } + + // do not drill down further if there's no chance of a better solution + if (cell.max - bestCell.d <= precision) continue; + + // split the cell into four cells + h = cell.h / 2; + cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings)); + numProbes += 4; + } + + if (debug) { + console.log(`num probes: ${numProbes}`); + console.log(`best distance: ${bestCell.d}`); + } + + return bestCell.p; +} + +function compareMax(a, b) { + return b.max - a.max; +} + +function Cell(x, y, h, polygon) { + this.p = new Point(x, y); + this.h = h; // half the cell size + this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon + this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell +} + +// signed distance from point to polygon outline (negative if point is outside) +function pointToPolygonDist(p, polygon) { + let inside = false; + let minDistSq = Infinity; + + for (let k = 0; k < polygon.length; k++) { + const ring = polygon[k]; + + for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + const a = ring[i]; + const b = ring[j]; + + if ((a.y > p.y !== b.y > p.y) && + (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) inside = !inside; + + minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b)); + } + } + + return (inside ? 1 : -1) * Math.sqrt(minDistSq); +} + +// get polygon centroid +function getCentroidCell(polygon) { + let area = 0; + let x = 0; + let y = 0; + const points = polygon[0]; + for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) { + const a = points[i]; + const b = points[j]; + const f = a.x * b.y - b.x * a.y; + x += (a.x + b.x) * f; + y += (a.y + b.y) * f; + area += f * 3; + } + return new Cell(x / area, y / area, 0, polygon); +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/global_worker_pool.js b/node_modules/@plotly/mapbox-gl/src/util/global_worker_pool.js new file mode 100644 index 0000000000000000000000000000000000000000..3fb1d06258d70b8ea10a99845419e03158bd7961 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/global_worker_pool.js @@ -0,0 +1,35 @@ +// @flow + +import WorkerPool, {PRELOAD_POOL_ID} from './worker_pool'; + +let globalWorkerPool; + +/** + * Creates (if necessary) and returns the single, global WorkerPool instance + * to be shared across each Map + * @private + */ +export default function getGlobalWorkerPool () { + if (!globalWorkerPool) { + globalWorkerPool = new WorkerPool(); + } + return globalWorkerPool; +} + +export function prewarm() { + const workerPool = getGlobalWorkerPool(); + workerPool.acquire(PRELOAD_POOL_ID); +} + +export function clearPrewarmedResources() { + const pool = globalWorkerPool; + if (pool) { + // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed. + if (pool.isPreloaded() && pool.numActive() === 1) { + pool.release(PRELOAD_POOL_ID); + globalWorkerPool = null; + } else { + console.warn('Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()'); + } + } +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/image.js b/node_modules/@plotly/mapbox-gl/src/util/image.js new file mode 100644 index 0000000000000000000000000000000000000000..2ef55d01391913a59e6e59953a0b8f944b20b8d5 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/image.js @@ -0,0 +1,142 @@ +// @flow + +import assert from 'assert'; + +import {register} from './web_worker_transfer'; + +export type Size = { + width: number, + height: number +}; + +type Point = { + x: number, + y: number +}; + +function createImage(image: *, {width, height}: Size, channels: number, data?: Uint8Array | Uint8ClampedArray) { + if (!data) { + data = new Uint8Array(width * height * channels); + } else if (data instanceof Uint8ClampedArray) { + data = new Uint8Array(data.buffer); + } else if (data.length !== width * height * channels) { + throw new RangeError('mismatched image size'); + } + image.width = width; + image.height = height; + image.data = data; + return image; +} + +function resizeImage(image: *, {width, height}: Size, channels: number) { + if (width === image.width && height === image.height) { + return; + } + + const newImage = createImage({}, {width, height}, channels); + + copyImage(image, newImage, {x: 0, y: 0}, {x: 0, y: 0}, { + width: Math.min(image.width, width), + height: Math.min(image.height, height) + }, channels); + + image.width = width; + image.height = height; + image.data = newImage.data; +} + +function copyImage(srcImg: *, dstImg: *, srcPt: Point, dstPt: Point, size: Size, channels: number) { + if (size.width === 0 || size.height === 0) { + return dstImg; + } + + if (size.width > srcImg.width || + size.height > srcImg.height || + srcPt.x > srcImg.width - size.width || + srcPt.y > srcImg.height - size.height) { + throw new RangeError('out of range source coordinates for image copy'); + } + + if (size.width > dstImg.width || + size.height > dstImg.height || + dstPt.x > dstImg.width - size.width || + dstPt.y > dstImg.height - size.height) { + throw new RangeError('out of range destination coordinates for image copy'); + } + + const srcData = srcImg.data; + const dstData = dstImg.data; + + assert(srcData !== dstData); + + for (let y = 0; y < size.height; y++) { + const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels; + const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels; + for (let i = 0; i < size.width * channels; i++) { + dstData[dstOffset + i] = srcData[srcOffset + i]; + } + } + return dstImg; +} + +export class AlphaImage { + width: number; + height: number; + data: Uint8Array; + + constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) { + createImage(this, size, 1, data); + } + + resize(size: Size) { + resizeImage(this, size, 1); + } + + clone() { + return new AlphaImage({width: this.width, height: this.height}, new Uint8Array(this.data)); + } + + static copy(srcImg: AlphaImage, dstImg: AlphaImage, srcPt: Point, dstPt: Point, size: Size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 1); + } +} + +// Not premultiplied, because ImageData is not premultiplied. +// UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture. +export class RGBAImage { + width: number; + height: number; + + // data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not + // support Uint8ClampedArray in all browsers + data: Uint8Array; + + constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) { + createImage(this, size, 4, data); + } + + resize(size: Size) { + resizeImage(this, size, 4); + } + + replace(data: Uint8Array | Uint8ClampedArray, copy?: boolean) { + if (copy) { + this.data.set(data); + } else if (data instanceof Uint8ClampedArray) { + this.data = new Uint8Array(data.buffer); + } else { + this.data = data; + } + } + + clone() { + return new RGBAImage({width: this.width, height: this.height}, new Uint8Array(this.data)); + } + + static copy(srcImg: RGBAImage | ImageData, dstImg: RGBAImage, srcPt: Point, dstPt: Point, size: Size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 4); + } +} + +register('AlphaImage', AlphaImage); +register('RGBAImage', RGBAImage); diff --git a/node_modules/@plotly/mapbox-gl/src/util/intersection_tests.js b/node_modules/@plotly/mapbox-gl/src/util/intersection_tests.js new file mode 100644 index 0000000000000000000000000000000000000000..d79f6f744b341f8de6c389a63be8cc9b375e0fa9 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/intersection_tests.js @@ -0,0 +1,208 @@ +// @flow + +import {isCounterClockwise} from './util'; + +import Point from '@mapbox/point-geometry'; + +export {polygonIntersectsBufferedPoint, polygonIntersectsMultiPolygon, polygonIntersectsBufferedMultiLine, polygonIntersectsPolygon, distToSegmentSquared, polygonIntersectsBox}; + +type Line = Array; +type MultiLine = Array; +type Ring = Array; +type Polygon = Array; +type MultiPolygon = Array; + +function polygonIntersectsPolygon(polygonA: Polygon, polygonB: Polygon) { + for (let i = 0; i < polygonA.length; i++) { + if (polygonContainsPoint(polygonB, polygonA[i])) return true; + } + + for (let i = 0; i < polygonB.length; i++) { + if (polygonContainsPoint(polygonA, polygonB[i])) return true; + } + + if (lineIntersectsLine(polygonA, polygonB)) return true; + + return false; +} + +function polygonIntersectsBufferedPoint(polygon: Polygon, point: Point, radius: number) { + if (polygonContainsPoint(polygon, point)) return true; + if (pointIntersectsBufferedLine(point, polygon, radius)) return true; + return false; +} + +function polygonIntersectsMultiPolygon(polygon: Polygon, multiPolygon: MultiPolygon) { + + if (polygon.length === 1) { + return multiPolygonContainsPoint(multiPolygon, polygon[0]); + } + + for (let m = 0; m < multiPolygon.length; m++) { + const ring = multiPolygon[m]; + for (let n = 0; n < ring.length; n++) { + if (polygonContainsPoint(polygon, ring[n])) return true; + } + } + + for (let i = 0; i < polygon.length; i++) { + if (multiPolygonContainsPoint(multiPolygon, polygon[i])) return true; + } + + for (let k = 0; k < multiPolygon.length; k++) { + if (lineIntersectsLine(polygon, multiPolygon[k])) return true; + } + + return false; +} + +function polygonIntersectsBufferedMultiLine(polygon: Polygon, multiLine: MultiLine, radius: number) { + for (let i = 0; i < multiLine.length; i++) { + const line = multiLine[i]; + + if (polygon.length >= 3) { + for (let k = 0; k < line.length; k++) { + if (polygonContainsPoint(polygon, line[k])) return true; + } + } + + if (lineIntersectsBufferedLine(polygon, line, radius)) return true; + } + return false; +} + +function lineIntersectsBufferedLine(lineA: Line, lineB: Line, radius: number) { + + if (lineA.length > 1) { + if (lineIntersectsLine(lineA, lineB)) return true; + + // Check whether any point in either line is within radius of the other line + for (let j = 0; j < lineB.length; j++) { + if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) return true; + } + } + + for (let k = 0; k < lineA.length; k++) { + if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) return true; + } + + return false; +} + +function lineIntersectsLine(lineA: Line, lineB: Line) { + if (lineA.length === 0 || lineB.length === 0) return false; + for (let i = 0; i < lineA.length - 1; i++) { + const a0 = lineA[i]; + const a1 = lineA[i + 1]; + for (let j = 0; j < lineB.length - 1; j++) { + const b0 = lineB[j]; + const b1 = lineB[j + 1]; + if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) return true; + } + } + return false; +} + +function lineSegmentIntersectsLineSegment(a0: Point, a1: Point, b0: Point, b1: Point) { + return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && + isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1); +} + +function pointIntersectsBufferedLine(p: Point, line: Line, radius: number) { + const radiusSquared = radius * radius; + + if (line.length === 1) return p.distSqr(line[0]) < radiusSquared; + + for (let i = 1; i < line.length; i++) { + // Find line segments that have a distance <= radius^2 to p + // In that case, we treat the line as "containing point p". + const v = line[i - 1], w = line[i]; + if (distToSegmentSquared(p, v, w) < radiusSquared) return true; + } + return false; +} + +// Code from http://stackoverflow.com/a/1501725/331379. +function distToSegmentSquared(p: Point, v: Point, w: Point) { + const l2 = v.distSqr(w); + if (l2 === 0) return p.distSqr(v); + const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + if (t < 0) return p.distSqr(v); + if (t > 1) return p.distSqr(w); + return p.distSqr(w.sub(v)._mult(t)._add(v)); +} + +// point in polygon ray casting algorithm +function multiPolygonContainsPoint(rings: Array, p: Point) { + let c = false, + ring, p1, p2; + + for (let k = 0; k < rings.length; k++) { + ring = rings[k]; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { + c = !c; + } + } + } + return c; +} + +function polygonContainsPoint(ring: Ring, p: Point) { + let c = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const p1 = ring[i]; + const p2 = ring[j]; + if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { + c = !c; + } + } + return c; +} + +function polygonIntersectsBox(ring: Ring, boxX1: number, boxY1: number, boxX2: number, boxY2: number) { + for (const p of ring) { + if (boxX1 <= p.x && + boxY1 <= p.y && + boxX2 >= p.x && + boxY2 >= p.y) return true; + } + + const corners = [ + new Point(boxX1, boxY1), + new Point(boxX1, boxY2), + new Point(boxX2, boxY2), + new Point(boxX2, boxY1)]; + + if (ring.length > 2) { + for (const corner of corners) { + if (polygonContainsPoint(ring, corner)) return true; + } + } + + for (let i = 0; i < ring.length - 1; i++) { + const p1 = ring[i]; + const p2 = ring[i + 1]; + if (edgeIntersectsBox(p1, p2, corners)) return true; + } + + return false; +} + +function edgeIntersectsBox(e1: Point, e2: Point, corners: Array) { + const tl = corners[0]; + const br = corners[2]; + // the edge and box do not intersect in either the x or y dimensions + if (((e1.x < tl.x) && (e2.x < tl.x)) || + ((e1.x > br.x) && (e2.x > br.x)) || + ((e1.y < tl.y) && (e2.y < tl.y)) || + ((e1.y > br.y) && (e2.y > br.y))) return false; + + // check if all corners of the box are on the same side of the edge + const dir = isCounterClockwise(e1, e2, corners[0]); + return dir !== isCounterClockwise(e1, e2, corners[1]) || + dir !== isCounterClockwise(e1, e2, corners[2]) || + dir !== isCounterClockwise(e1, e2, corners[3]); +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/is_char_in_unicode_block.js b/node_modules/@plotly/mapbox-gl/src/util/is_char_in_unicode_block.js new file mode 100644 index 0000000000000000000000000000000000000000..427f741d196e5e6842fee319eabfaf2400d56075 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/is_char_in_unicode_block.js @@ -0,0 +1,311 @@ +// @flow + +// The following table comes from . +// Keep it synchronized with . + +type UnicodeBlockLookup = {[key: string]: (char: number) => boolean}; + +const unicodeBlockLookup: UnicodeBlockLookup = { + // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F, + 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF, + // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F, + // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F, + // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF, + // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF, + // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F, + // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF, + // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF, + // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F, + // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F, + //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF, + 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF, + //'Syriac': (char) => char >= 0x0700 && char <= 0x074F, + 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F, + // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF, + // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF, + // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F, + // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F, + // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F, + 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF, + // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F, + // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF, + // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F, + // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF, + // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F, + // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF, + // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F, + // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF, + // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F, + // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF, + // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F, + // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF, + // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF, + // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F, + // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF, + 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF, + // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F, + // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F, + // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF, + 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F, + // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F, + // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF, + // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F, + // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F, + // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F, + // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F, + 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF, + // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF, + 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF, + // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F, + // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F, + // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF, + // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF, + // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F, + // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF, + // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF, + // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F, + // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF, + // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF, + // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F, + // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F, + // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F, + // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF, + // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF, + // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF, + // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F, + // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF, + // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF, + // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF, + // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF, + 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F, + // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F, + // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF, + // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF, + 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F, + 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F, + // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF, + // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF, + 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF, + 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F, + 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F, + 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF, + // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F, + // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F, + 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF, + 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF, + // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF, + // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF, + // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF, + // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF, + // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F, + // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF, + // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF, + 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF, + // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F, + // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F, + // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF, + // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F, + // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F, + // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF, + // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF, + // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F, + 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF, + 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF, + 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF, + 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F, + 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F, + 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF, + 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F, + 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F, + 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F, + 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF, + 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF, + 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF, + 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF, + 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF, + 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF, + 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF, + 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF, + 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F, + 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF, + // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF, + // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F, + // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F, + // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF, + // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F, + // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF, + // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F, + // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F, + // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F, + // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF, + // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF, + // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F, + // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F, + 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F, + // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF, + // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF, + // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F, + // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F, + // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF, + // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF, + // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F, + // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F, + // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF, + // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF, + 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF, + 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF, + // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F, + // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF, + // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF, + 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF, + 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF, + // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F, + 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF, + // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F, + 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F, + // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F, + 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F, + 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F, + 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF, + 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF + // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF, + // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F, + // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF, + // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F, + // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F, + // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF, + // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF, + // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F, + // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF, + // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF, + // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F, + // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F, + // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F, + // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F, + // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF, + // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F, + // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F, + // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF, + // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF, + // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F, + // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F, + // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F, + // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F, + // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F, + // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F, + // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF, + // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF, + // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F, + // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F, + // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F, + // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF, + // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F, + // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F, + // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F, + // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF, + // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F, + // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F, + // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F, + // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF, + // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F, + // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF, + // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F, + // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F, + // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F, + // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F, + // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF, + // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F, + // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF, + // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF, + // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F, + // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F, + // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF, + // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF, + // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F, + // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF, + // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF, + // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F, + // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F, + // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF, + // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF, + // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F, + // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F, + // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF, + // 'Ahom': (char) => char >= 0x11700 && char <= 0x1173F, + // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F, + // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF, + // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF, + // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F, + // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF, + // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF, + // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F, + // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF, + // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F, + // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF, + // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF, + // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF, + // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF, + // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F, + // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F, + // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F, + // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1343F, + // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F, + // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F, + // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F, + // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF, + // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F, + // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F, + // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F, + // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF, + // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF, + // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF, + // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF, + // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F, + // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F, + // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF, + // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F, + // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF, + // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF, + // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF, + // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F, + // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF, + // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F, + // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F, + // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF, + // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF, + // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F, + // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F, + // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF, + // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF, + // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F, + // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF, + // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F, + // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF, + // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F, + // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F, + // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF, + // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF, + // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF, + // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF, + // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F, + // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F, + // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF, + // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F, + // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF, + // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF, + // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF, + // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F, + // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF, + // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF, + // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F, + // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F, + // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF, + // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF, + // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F, + // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F, + // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF, + // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF, + // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF, +}; + +export default unicodeBlockLookup; diff --git a/node_modules/@plotly/mapbox-gl/src/util/mapbox.js b/node_modules/@plotly/mapbox-gl/src/util/mapbox.js new file mode 100644 index 0000000000000000000000000000000000000000..665ac7b9690b5971e82eddf566b041dccc33c483 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/mapbox.js @@ -0,0 +1,490 @@ +// @flow + +/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR +* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ****** +* The following code is used to access Mapbox's Mapping APIs. Removal or modification +* of this code when used with Mapbox's Mapping APIs can result in higher fees and/or +* termination of your account with Mapbox. +* +* Under the Mapbox Terms of Service, you may not use this code to access Mapbox +* Mapping APIs other than through Mapbox SDKs. +* +* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps +* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/ +******************************************************************************/ + +import config from './config'; + +import browser from './browser'; +import window from './window'; +import webpSupported from './webp_supported'; +import {createSkuToken, SKU_ID} from './sku_token'; +import {version as sdkVersion} from '../../package.json'; +import {uuid, validateUuid, storageAvailable, b64DecodeUnicode, b64EncodeUnicode, warnOnce, extend} from './util'; +import {postData, ResourceType} from './ajax'; + +import type {RequestParameters} from './ajax'; +import type {Cancelable} from '../types/cancelable'; +import type {TileJSON} from '../types/tilejson'; + +type ResourceTypeEnum = $Keys; +export type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters; + +type UrlObject = {| + protocol: string, + authority: string, + path: string, + params: Array +|}; + +export class RequestManager { + _skuToken: string; + _skuTokenExpiresAt: number; + _transformRequestFn: ?RequestTransformFunction; + _customAccessToken: ?string; + + constructor(transformRequestFn?: RequestTransformFunction, customAccessToken?: string) { + this._transformRequestFn = transformRequestFn; + this._customAccessToken = customAccessToken; + this._createSkuToken(); + } + + _createSkuToken() { + const skuToken = createSkuToken(); + this._skuToken = skuToken.token; + this._skuTokenExpiresAt = skuToken.tokenExpiresAt; + } + + _isSkuTokenExpired(): boolean { + return Date.now() > this._skuTokenExpiresAt; + } + + transformRequest(url: string, type: ResourceTypeEnum) { + if (this._transformRequestFn) { + return this._transformRequestFn(url, type) || {url}; + } + + return {url}; + } + + normalizeStyleURL(url: string, accessToken?: string): string { + if (!isMapboxURL(url)) return url; + const urlObject = parseUrl(url); + urlObject.path = `/styles/v1${urlObject.path}`; + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeGlyphsURL(url: string, accessToken?: string): string { + if (!isMapboxURL(url)) return url; + const urlObject = parseUrl(url); + urlObject.path = `/fonts/v1${urlObject.path}`; + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeSourceURL(url: string, accessToken?: string): string { + if (!isMapboxURL(url)) return url; + const urlObject = parseUrl(url); + urlObject.path = `/v4/${urlObject.authority}.json`; + // TileJSON requests need a secure flag appended to their URLs so + // that the server knows to send SSL-ified resource references. + urlObject.params.push('secure'); + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeSpriteURL(url: string, format: string, extension: string, accessToken?: string): string { + const urlObject = parseUrl(url); + if (!isMapboxURL(url)) { + urlObject.path += `${format}${extension}`; + return formatUrl(urlObject); + } + urlObject.path = `/styles/v1${urlObject.path}/sprite${format}${extension}`; + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeTileURL(tileURL: string, tileSize?: ?number): string { + if (this._isSkuTokenExpired()) { + this._createSkuToken(); + } + + if (tileURL && !isMapboxURL(tileURL)) return tileURL; + + const urlObject = parseUrl(tileURL); + const imageExtensionRe = /(\.(png|jpg)\d*)(?=$)/; + const tileURLAPIPrefixRe = /^.+\/v4\//; + + // The v4 mapbox tile API supports 512x512 image tiles only when @2x + // is appended to the tile URL. If `tileSize: 512` is specified for + // a Mapbox raster source force the @2x suffix even if a non hidpi device. + const suffix = browser.devicePixelRatio >= 2 || tileSize === 512 ? '@2x' : ''; + const extension = webpSupported.supported ? '.webp' : '$1'; + urlObject.path = urlObject.path.replace(imageExtensionRe, `${suffix}${extension}`); + urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/'); + urlObject.path = `/v4${urlObject.path}`; + + const accessToken = this._customAccessToken || getAccessToken(urlObject.params) || config.ACCESS_TOKEN; + if (config.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) { + urlObject.params.push(`sku=${this._skuToken}`); + } + + return this._makeAPIURL(urlObject, accessToken); + } + + canonicalizeTileURL(url: string, removeAccessToken: boolean) { + const version = "/v4/"; + // matches any file extension specified by a dot and one or more alphanumeric characters + const extensionRe = /\.[\w]+$/; + + const urlObject = parseUrl(url); + // Make sure that we are dealing with a valid Mapbox tile URL. + // Has to begin with /v4/, with a valid filename + extension + if (!urlObject.path.match(/(^\/v4\/)/) || !urlObject.path.match(extensionRe)) { + // Not a proper Mapbox tile URL. + return url; + } + // Reassemble the canonical URL from the parts we've parsed before. + let result = "mapbox://tiles/"; + result += urlObject.path.replace(version, ''); + + // Append the query string, minus the access token parameter. + let params = urlObject.params; + if (removeAccessToken) { + params = params.filter(p => !p.match(/^access_token=/)); + } + if (params.length) result += `?${params.join('&')}`; + return result; + } + + canonicalizeTileset(tileJSON: TileJSON, sourceURL?: string) { + const removeAccessToken = sourceURL ? isMapboxURL(sourceURL) : false; + const canonical = []; + for (const url of tileJSON.tiles || []) { + if (isMapboxHTTPURL(url)) { + canonical.push(this.canonicalizeTileURL(url, removeAccessToken)); + } else { + canonical.push(url); + } + } + return canonical; + } + + _makeAPIURL(urlObject: UrlObject, accessToken: string | null | void): string { + const help = 'See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes'; + const apiUrlObject = parseUrl(config.API_URL); + urlObject.protocol = apiUrlObject.protocol; + urlObject.authority = apiUrlObject.authority; + + if (urlObject.protocol === 'http') { + const i = urlObject.params.indexOf('secure'); + if (i >= 0) urlObject.params.splice(i, 1); + } + + if (apiUrlObject.path !== '/') { + urlObject.path = `${apiUrlObject.path}${urlObject.path}`; + } + + if (!config.REQUIRE_ACCESS_TOKEN) return formatUrl(urlObject); + + accessToken = accessToken || config.ACCESS_TOKEN; + if (!accessToken) + throw new Error(`An API access token is required to use Mapbox GL. ${help}`); + if (accessToken[0] === 's') + throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${help}`); + + urlObject.params = urlObject.params.filter((d) => d.indexOf('access_token') === -1); + urlObject.params.push(`access_token=${accessToken}`); + return formatUrl(urlObject); + } +} + +function isMapboxURL(url: string) { + return url.indexOf('mapbox:') === 0; +} + +const mapboxHTTPURLRe = /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i; +function isMapboxHTTPURL(url: string): boolean { + return mapboxHTTPURLRe.test(url); +} + +function hasCacheDefeatingSku(url: string) { + return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url); +} + +function getAccessToken(params: Array): string | null { + for (const param of params) { + const match = param.match(/^access_token=(.*)$/); + if (match) { + return match[1]; + } + } + return null; +} + +const urlRe = /^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/; + +function parseUrl(url: string): UrlObject { + const parts = url.match(urlRe); + if (!parts) { + throw new Error('Unable to parse URL object'); + } + return { + protocol: parts[1], + authority: parts[2], + path: parts[3] || '/', + params: parts[4] ? parts[4].split('&') : [] + }; +} + +function formatUrl(obj: UrlObject): string { + const params = obj.params.length ? `?${obj.params.join('&')}` : ''; + return `${obj.protocol}://${obj.authority}${obj.path}${params}`; +} + +export {isMapboxURL, isMapboxHTTPURL, hasCacheDefeatingSku}; + +const telemEventKey = 'mapbox.eventData'; + +function parseAccessToken(accessToken: ?string) { + if (!accessToken) { + return null; + } + + const parts = accessToken.split('.'); + if (!parts || parts.length !== 3) { + return null; + } + + try { + const jsonData = JSON.parse(b64DecodeUnicode(parts[1])); + return jsonData; + } catch (e) { + return null; + } +} + +type TelemetryEventType = 'appUserTurnstile' | 'map.load'; + +class TelemetryEvent { + eventData: any; + anonId: ?string; + queue: Array; + type: TelemetryEventType; + pendingRequest: ?Cancelable; + _customAccessToken: ?string; + + constructor(type: TelemetryEventType) { + this.type = type; + this.anonId = null; + this.eventData = {}; + this.queue = []; + this.pendingRequest = null; + } + + getStorageKey(domain: ?string) { + const tokenData = parseAccessToken(config.ACCESS_TOKEN); + let u = ''; + if (tokenData && tokenData['u']) { + u = b64EncodeUnicode(tokenData['u']); + } else { + u = config.ACCESS_TOKEN || ''; + } + return domain ? + `${telemEventKey}.${domain}:${u}` : + `${telemEventKey}:${u}`; + } + + fetchEventData() { + const isLocalStorageAvailable = storageAvailable('localStorage'); + const storageKey = this.getStorageKey(); + const uuidKey = this.getStorageKey('uuid'); + + if (isLocalStorageAvailable) { + //Retrieve cached data + try { + const data = window.localStorage.getItem(storageKey); + if (data) { + this.eventData = JSON.parse(data); + } + + const uuid = window.localStorage.getItem(uuidKey); + if (uuid) this.anonId = uuid; + } catch (e) { + warnOnce('Unable to read from LocalStorage'); + } + } + } + + saveEventData() { + const isLocalStorageAvailable = storageAvailable('localStorage'); + const storageKey = this.getStorageKey(); + const uuidKey = this.getStorageKey('uuid'); + if (isLocalStorageAvailable) { + try { + window.localStorage.setItem(uuidKey, this.anonId); + if (Object.keys(this.eventData).length >= 1) { + window.localStorage.setItem(storageKey, JSON.stringify(this.eventData)); + } + } catch (e) { + warnOnce('Unable to write to LocalStorage'); + } + } + + } + + processRequests(_: ?string) {} + + /* + * If any event data should be persisted after the POST request, the callback should modify eventData` + * to the values that should be saved. For this reason, the callback should be invoked prior to the call + * to TelemetryEvent#saveData + */ + postEvent(timestamp: number, additionalPayload: {[_: string]: any}, callback: (err: ?Error) => void, customAccessToken?: ?string) { + if (!config.EVENTS_URL) return; + const eventsUrlObject: UrlObject = parseUrl(config.EVENTS_URL); + eventsUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`); + + const payload: Object = { + event: this.type, + created: new Date(timestamp).toISOString(), + sdkIdentifier: 'mapbox-gl-js', + sdkVersion, + skuId: SKU_ID, + userId: this.anonId + }; + + const finalPayload = additionalPayload ? extend(payload, additionalPayload) : payload; + const request: RequestParameters = { + url: formatUrl(eventsUrlObject), + headers: { + 'Content-Type': 'text/plain' //Skip the pre-flight OPTIONS request + }, + body: JSON.stringify([finalPayload]) + }; + + this.pendingRequest = postData(request, (error) => { + this.pendingRequest = null; + callback(error); + this.saveEventData(); + this.processRequests(customAccessToken); + }); + } + + queueRequest(event: number | {id: number, timestamp: number}, customAccessToken?: ?string) { + this.queue.push(event); + this.processRequests(customAccessToken); + } +} + +export class MapLoadEvent extends TelemetryEvent { + +success: {[_: number]: boolean}; + skuToken: string; + + constructor() { + super('map.load'); + this.success = {}; + this.skuToken = ''; + } + + postMapLoadEvent(tileUrls: Array, mapId: number, skuToken: string, customAccessToken: string) { + this.skuToken = skuToken; + + const accessTokenIsSet = !!(customAccessToken || config.ACCESS_TOKEN); + const usesMapboxTiles = Array.isArray(tileUrls) && tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url)); + + // Enabled only when Mapbox Access Token is set and a source uses mapbox tiles. + if (config.EVENTS_URL && accessTokenIsSet && usesMapboxTiles) { + this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken); + } + } + + processRequests(customAccessToken?: ?string) { + if (this.pendingRequest || this.queue.length === 0) return; + const {id, timestamp} = this.queue.shift(); + + // Only one load event should fire per map + if (id && this.success[id]) return; + + if (!this.anonId) { + this.fetchEventData(); + } + + if (!validateUuid(this.anonId)) { + this.anonId = uuid(); + } + + this.postEvent(timestamp, {skuToken: this.skuToken}, (err) => { + if (!err) { + if (id) this.success[id] = true; + } + }, customAccessToken); + } +} + +export class TurnstileEvent extends TelemetryEvent { + constructor(customAccessToken?: ?string) { + super('appUserTurnstile'); + this._customAccessToken = customAccessToken; + } + + postTurnstileEvent(tileUrls: Array, customAccessToken?: ?string) { + //Enabled only when Mapbox Access Token is set and a source uses + // mapbox tiles. + if (config.EVENTS_URL && + config.ACCESS_TOKEN && + Array.isArray(tileUrls) && + tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) { + this.queueRequest(Date.now(), customAccessToken); + } + } + + processRequests(customAccessToken?: ?string) { + if (this.pendingRequest || this.queue.length === 0) { + return; + } + + if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) { + //Retrieve cached data + this.fetchEventData(); + } + + const tokenData = parseAccessToken(config.ACCESS_TOKEN); + const tokenU = tokenData ? tokenData['u'] : config.ACCESS_TOKEN; + //Reset event data cache if the access token owner changed. + let dueForEvent = tokenU !== this.eventData.tokenU; + + if (!validateUuid(this.anonId)) { + this.anonId = uuid(); + dueForEvent = true; + } + + const nextUpdate = this.queue.shift(); + // Record turnstile event once per calendar day. + if (this.eventData.lastSuccess) { + const lastUpdate = new Date(this.eventData.lastSuccess); + const nextDate = new Date(nextUpdate); + const daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1000); + dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate(); + } else { + dueForEvent = true; + } + + if (!dueForEvent) { + return this.processRequests(); + } + + this.postEvent(nextUpdate, {"enabled.telemetry": false}, (err) => { + if (!err) { + this.eventData.lastSuccess = nextUpdate; + this.eventData.tokenU = tokenU; + } + }, customAccessToken); + } +} + +const turnstileEvent_ = new TurnstileEvent(); +export const postTurnstileEvent = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_); + +const mapLoadEvent_ = new MapLoadEvent(); +export const postMapLoadEvent = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_); + +/***** END WARNING - REMOVAL OR MODIFICATION OF THE +PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/ diff --git a/node_modules/@plotly/mapbox-gl/src/util/offscreen_canvas_supported.js b/node_modules/@plotly/mapbox-gl/src/util/offscreen_canvas_supported.js new file mode 100644 index 0000000000000000000000000000000000000000..4ec6b188d05a679e471197753df59ebe0217c7ef --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/offscreen_canvas_supported.js @@ -0,0 +1,14 @@ +// @flow +import window from './window'; + +let supportsOffscreenCanvas: ?boolean; + +export default function offscreenCanvasSupported(): boolean { + if (supportsOffscreenCanvas == null) { + supportsOffscreenCanvas = window.OffscreenCanvas && + new window.OffscreenCanvas(1, 1).getContext('2d') && + typeof window.createImageBitmap === 'function'; + } + + return supportsOffscreenCanvas; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/performance.js b/node_modules/@plotly/mapbox-gl/src/util/performance.js new file mode 100644 index 0000000000000000000000000000000000000000..0b6a26c377b1bbceef7909a1f9af0792f5657403 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/performance.js @@ -0,0 +1,112 @@ +// @flow + +import window from '../util/window'; +import type {RequestParameters} from '../util/ajax'; + +const performance = window.performance; + +export type PerformanceMetrics = { + loadTime: number, + fullLoadTime: number, + fps: number, + percentDroppedFrames: number +} + +export const PerformanceMarkers = { + create: 'create', + load: 'load', + fullLoad: 'fullLoad' +}; + +let lastFrameTime = null; +let frameTimes = []; + +const minFramerateTarget = 30; +const frameTimeTarget = 1000 / minFramerateTarget; + +export const PerformanceUtils = { + mark(marker: $Keys) { + performance.mark(marker); + }, + frame(timestamp: number) { + const currTimestamp = timestamp; + if (lastFrameTime != null) { + const frameTime = currTimestamp - lastFrameTime; + frameTimes.push(frameTime); + } + lastFrameTime = currTimestamp; + }, + clearMetrics() { + lastFrameTime = null; + frameTimes = []; + performance.clearMeasures('loadTime'); + performance.clearMeasures('fullLoadTime'); + + for (const marker in PerformanceMarkers) { + performance.clearMarks(PerformanceMarkers[marker]); + } + }, + getPerformanceMetrics(): PerformanceMetrics { + const loadTime = performance.measure('loadTime', PerformanceMarkers.create, PerformanceMarkers.load).duration; + const fullLoadTime = performance.measure('fullLoadTime', PerformanceMarkers.create, PerformanceMarkers.fullLoad).duration; + const totalFrames = frameTimes.length; + + const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000; + const fps = 1 / avgFrameTime; + + // count frames that missed our framerate target + const droppedFrames = frameTimes + .filter((frameTime) => frameTime > frameTimeTarget) + .reduce((acc, curr) => { + return acc + (curr - frameTimeTarget) / frameTimeTarget; + }, 0); + const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100; + + return { + loadTime, + fullLoadTime, + fps, + percentDroppedFrames + }; + } +}; + +/** + * Safe wrapper for the performance resource timing API in web workers with graceful degradation + * + * @param {RequestParameters} request + * @private + */ +export class RequestPerformance { + _marks: {start: string, end: string, measure: string}; + + constructor (request: RequestParameters) { + this._marks = { + start: [request.url, 'start'].join('#'), + end: [request.url, 'end'].join('#'), + measure: request.url.toString() + }; + + performance.mark(this._marks.start); + } + + finish() { + performance.mark(this._marks.end); + let resourceTimingData = performance.getEntriesByName(this._marks.measure); + + // fallback if web worker implementation of perf.getEntriesByName returns empty + if (resourceTimingData.length === 0) { + performance.measure(this._marks.measure, this._marks.start, this._marks.end); + resourceTimingData = performance.getEntriesByName(this._marks.measure); + + // cleanup + performance.clearMarks(this._marks.start); + performance.clearMarks(this._marks.end); + performance.clearMeasures(this._marks.measure); + } + + return resourceTimingData; + } +} + +export default performance; diff --git a/node_modules/@plotly/mapbox-gl/src/util/primitives.js b/node_modules/@plotly/mapbox-gl/src/util/primitives.js new file mode 100644 index 0000000000000000000000000000000000000000..b1cd69e6fe345e3df5154be3e6cb21784ffa28ce --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/primitives.js @@ -0,0 +1,145 @@ +// @flow + +import {vec3, vec4} from 'gl-matrix'; +import assert from 'assert'; + +class Frustum { + points: Array>; + planes: Array>; + + constructor(points_: Array>, planes_: Array>) { + this.points = points_; + this.planes = planes_; + } + + static fromInvProjectionMatrix(invProj: Float64Array, worldSize: number, zoom: number): Frustum { + const clipSpaceCorners = [ + [-1, 1, -1, 1], + [ 1, 1, -1, 1], + [ 1, -1, -1, 1], + [-1, -1, -1, 1], + [-1, 1, 1, 1], + [ 1, 1, 1, 1], + [ 1, -1, 1, 1], + [-1, -1, 1, 1] + ]; + + const scale = Math.pow(2, zoom); + + // Transform frustum corner points from clip space to tile space + const frustumCoords = clipSpaceCorners + .map(v => vec4.transformMat4([], v, invProj)) + .map(v => vec4.scale([], v, 1.0 / v[3] / worldSize * scale)); + + const frustumPlanePointIndices = [ + [0, 1, 2], // near + [6, 5, 4], // far + [0, 3, 7], // left + [2, 1, 5], // right + [3, 2, 6], // bottom + [0, 4, 5] // top + ]; + + const frustumPlanes = frustumPlanePointIndices.map((p: Array) => { + const a = vec3.sub([], frustumCoords[p[0]], frustumCoords[p[1]]); + const b = vec3.sub([], frustumCoords[p[2]], frustumCoords[p[1]]); + const n = vec3.normalize([], vec3.cross([], a, b)); + const d = -vec3.dot(n, frustumCoords[p[1]]); + return n.concat(d); + }); + + return new Frustum(frustumCoords, frustumPlanes); + } +} + +class Aabb { + min: vec3; + max: vec3; + center: vec3; + + constructor(min_: vec3, max_: vec3) { + this.min = min_; + this.max = max_; + this.center = vec3.scale([], vec3.add([], this.min, this.max), 0.5); + } + + quadrant(index: number): Aabb { + const split = [(index % 2) === 0, index < 2]; + const qMin = vec3.clone(this.min); + const qMax = vec3.clone(this.max); + for (let axis = 0; axis < split.length; axis++) { + qMin[axis] = split[axis] ? this.min[axis] : this.center[axis]; + qMax[axis] = split[axis] ? this.center[axis] : this.max[axis]; + } + // Elevation is always constant, hence quadrant.max.z = this.max.z + qMax[2] = this.max[2]; + return new Aabb(qMin, qMax); + } + + distanceX(point: Array): number { + const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]); + return pointOnAabb - point[0]; + } + + distanceY(point: Array): number { + const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]); + return pointOnAabb - point[1]; + } + + // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection, + // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum. + intersects(frustum: Frustum): number { + // Execute separating axis test between two convex objects to find intersections + // Each frustum plane together with 3 major axes define the separating axes + // Note: test only 4 points as both min and max points have equal elevation + assert(this.min[2] === 0 && this.max[2] === 0); + + const aabbPoints = [ + [this.min[0], this.min[1], 0.0, 1], + [this.max[0], this.min[1], 0.0, 1], + [this.max[0], this.max[1], 0.0, 1], + [this.min[0], this.max[1], 0.0, 1] + ]; + + let fullyInside = true; + + for (let p = 0; p < frustum.planes.length; p++) { + const plane = frustum.planes[p]; + let pointsInside = 0; + + for (let i = 0; i < aabbPoints.length; i++) { + pointsInside += vec4.dot(plane, aabbPoints[i]) >= 0; + } + + if (pointsInside === 0) + return 0; + + if (pointsInside !== aabbPoints.length) + fullyInside = false; + } + + if (fullyInside) + return 2; + + for (let axis = 0; axis < 3; axis++) { + let projMin = Number.MAX_VALUE; + let projMax = -Number.MAX_VALUE; + + for (let p = 0; p < frustum.points.length; p++) { + const projectedPoint = frustum.points[p][axis] - this.min[axis]; + + projMin = Math.min(projMin, projectedPoint); + projMax = Math.max(projMax, projectedPoint); + } + + if (projMax < 0 || projMin > this.max[axis] - this.min[axis]) + return 0; + } + + return 1; + } +} +export { + Aabb, + Frustum +}; diff --git a/node_modules/@plotly/mapbox-gl/src/util/resolve_tokens.js b/node_modules/@plotly/mapbox-gl/src/util/resolve_tokens.js new file mode 100644 index 0000000000000000000000000000000000000000..3ca7c86055b779361a242b53f87dbaa43b60065a --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/resolve_tokens.js @@ -0,0 +1,16 @@ +// @flow +export default resolveTokens; + +/** + * Replace tokens in a string template with values in an object + * + * @param properties a key/value relationship between tokens and replacements + * @param text the template string + * @returns the template with tokens replaced + * @private + */ +function resolveTokens(properties: {+[string]: mixed}, text: string): string { + return text.replace(/{([^{}]+)}/g, (match, key: string) => { + return key in properties ? String(properties[key]) : ''; + }); +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/script_detection.js b/node_modules/@plotly/mapbox-gl/src/util/script_detection.js new file mode 100644 index 0000000000000000000000000000000000000000..985ae4830012bf15b01f54e2a1974a207042bfc5 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/script_detection.js @@ -0,0 +1,328 @@ +// @flow + +/* eslint-disable new-cap */ + +import isChar from './is_char_in_unicode_block'; + +export function allowsIdeographicBreaking(chars: string) { + for (const char of chars) { + if (!charAllowsIdeographicBreaking(char.charCodeAt(0))) return false; + } + return true; +} + +export function allowsVerticalWritingMode(chars: string) { + for (const char of chars) { + if (charHasUprightVerticalOrientation(char.charCodeAt(0))) return true; + } + return false; +} + +export function allowsLetterSpacing(chars: string) { + for (const char of chars) { + if (!charAllowsLetterSpacing(char.charCodeAt(0))) return false; + } + return true; +} + +export function charAllowsLetterSpacing(char: number) { + if (isChar['Arabic'](char)) return false; + if (isChar['Arabic Supplement'](char)) return false; + if (isChar['Arabic Extended-A'](char)) return false; + if (isChar['Arabic Presentation Forms-A'](char)) return false; + if (isChar['Arabic Presentation Forms-B'](char)) return false; + + return true; +} + +export function charAllowsIdeographicBreaking(char: number) { + // Return early for characters outside all ideographic ranges. + if (char < 0x2E80) return false; + + if (isChar['Bopomofo Extended'](char)) return true; + if (isChar['Bopomofo'](char)) return true; + if (isChar['CJK Compatibility Forms'](char)) return true; + if (isChar['CJK Compatibility Ideographs'](char)) return true; + if (isChar['CJK Compatibility'](char)) return true; + if (isChar['CJK Radicals Supplement'](char)) return true; + if (isChar['CJK Strokes'](char)) return true; + if (isChar['CJK Symbols and Punctuation'](char)) return true; + if (isChar['CJK Unified Ideographs Extension A'](char)) return true; + if (isChar['CJK Unified Ideographs'](char)) return true; + if (isChar['Enclosed CJK Letters and Months'](char)) return true; + if (isChar['Halfwidth and Fullwidth Forms'](char)) return true; + if (isChar['Hiragana'](char)) return true; + if (isChar['Ideographic Description Characters'](char)) return true; + if (isChar['Kangxi Radicals'](char)) return true; + if (isChar['Katakana Phonetic Extensions'](char)) return true; + if (isChar['Katakana'](char)) return true; + if (isChar['Vertical Forms'](char)) return true; + if (isChar['Yi Radicals'](char)) return true; + if (isChar['Yi Syllables'](char)) return true; + + return false; +} + +// The following logic comes from +// . +// Keep it synchronized with +// . +// The data file denotes with “U” or “Tu” any codepoint that may be drawn +// upright in vertical text but does not distinguish between upright and +// “neutral” characters. + +// Blocks in the Unicode supplementary planes are excluded from this module due +// to . + +/** + * Returns true if the given Unicode codepoint identifies a character with + * upright orientation. + * + * A character has upright orientation if it is drawn upright (unrotated) + * whether the line is oriented horizontally or vertically, even if both + * adjacent characters can be rotated. For example, a Chinese character is + * always drawn upright. An uprightly oriented character causes an adjacent + * “neutral” character to be drawn upright as well. + * @private + */ +export function charHasUprightVerticalOrientation(char: number) { + if (char === 0x02EA /* modifier letter yin departing tone mark */ || + char === 0x02EB /* modifier letter yang departing tone mark */) { + return true; + } + + // Return early for characters outside all ranges whose characters remain + // upright in vertical writing mode. + if (char < 0x1100) return false; + + if (isChar['Bopomofo Extended'](char)) return true; + if (isChar['Bopomofo'](char)) return true; + if (isChar['CJK Compatibility Forms'](char)) { + if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) { + return true; + } + } + if (isChar['CJK Compatibility Ideographs'](char)) return true; + if (isChar['CJK Compatibility'](char)) return true; + if (isChar['CJK Radicals Supplement'](char)) return true; + if (isChar['CJK Strokes'](char)) return true; + if (isChar['CJK Symbols and Punctuation'](char)) { + if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) && + !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) && + char !== 0x3030 /* wavy dash */) { + return true; + } + } + if (isChar['CJK Unified Ideographs Extension A'](char)) return true; + if (isChar['CJK Unified Ideographs'](char)) return true; + if (isChar['Enclosed CJK Letters and Months'](char)) return true; + if (isChar['Hangul Compatibility Jamo'](char)) return true; + if (isChar['Hangul Jamo Extended-A'](char)) return true; + if (isChar['Hangul Jamo Extended-B'](char)) return true; + if (isChar['Hangul Jamo'](char)) return true; + if (isChar['Hangul Syllables'](char)) return true; + if (isChar['Hiragana'](char)) return true; + if (isChar['Ideographic Description Characters'](char)) return true; + if (isChar['Kanbun'](char)) return true; + if (isChar['Kangxi Radicals'](char)) return true; + if (isChar['Katakana Phonetic Extensions'](char)) return true; + if (isChar['Katakana'](char)) { + if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) { + return true; + } + } + if (isChar['Halfwidth and Fullwidth Forms'](char)) { + if (char !== 0xFF08 /* fullwidth left parenthesis */ && + char !== 0xFF09 /* fullwidth right parenthesis */ && + char !== 0xFF0D /* fullwidth hyphen-minus */ && + !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) && + char !== 0xFF3B /* fullwidth left square bracket */ && + char !== 0xFF3D /* fullwidth right square bracket */ && + char !== 0xFF3F /* fullwidth low line */ && + !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) && + char !== 0xFFE3 /* fullwidth macron */ && + !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) { + return true; + } + } + if (isChar['Small Form Variants'](char)) { + if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) && + !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) { + return true; + } + } + if (isChar['Unified Canadian Aboriginal Syllabics'](char)) return true; + if (isChar['Unified Canadian Aboriginal Syllabics Extended'](char)) return true; + if (isChar['Vertical Forms'](char)) return true; + if (isChar['Yijing Hexagram Symbols'](char)) return true; + if (isChar['Yi Syllables'](char)) return true; + if (isChar['Yi Radicals'](char)) return true; + + return false; +} + +/** + * Returns true if the given Unicode codepoint identifies a character with + * neutral orientation. + * + * A character has neutral orientation if it may be drawn rotated or unrotated + * when the line is oriented vertically, depending on the orientation of the + * adjacent characters. For example, along a verticlly oriented line, the vulgar + * fraction ½ is drawn upright among Chinese characters but rotated among Latin + * letters. A neutrally oriented character does not influence whether an + * adjacent character is drawn upright or rotated. + * @private + */ +export function charHasNeutralVerticalOrientation(char: number) { + if (isChar['Latin-1 Supplement'](char)) { + if (char === 0x00A7 /* section sign */ || + char === 0x00A9 /* copyright sign */ || + char === 0x00AE /* registered sign */ || + char === 0x00B1 /* plus-minus sign */ || + char === 0x00BC /* vulgar fraction one quarter */ || + char === 0x00BD /* vulgar fraction one half */ || + char === 0x00BE /* vulgar fraction three quarters */ || + char === 0x00D7 /* multiplication sign */ || + char === 0x00F7 /* division sign */) { + return true; + } + } + if (isChar['General Punctuation'](char)) { + if (char === 0x2016 /* double vertical line */ || + char === 0x2020 /* dagger */ || + char === 0x2021 /* double dagger */ || + char === 0x2030 /* per mille sign */ || + char === 0x2031 /* per ten thousand sign */ || + char === 0x203B /* reference mark */ || + char === 0x203C /* double exclamation mark */ || + char === 0x2042 /* asterism */ || + char === 0x2047 /* double question mark */ || + char === 0x2048 /* question exclamation mark */ || + char === 0x2049 /* exclamation question mark */ || + char === 0x2051 /* two asterisks aligned vertically */) { + return true; + } + } + if (isChar['Letterlike Symbols'](char)) return true; + if (isChar['Number Forms'](char)) return true; + if (isChar['Miscellaneous Technical'](char)) { + if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) || + (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) || + (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) || + char === 0x232B /* erase to the left */ || + (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) || + (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) || + char === 0x23CF /* eject symbol */ || + (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) || + (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) { + return true; + } + } + if (isChar['Control Pictures'](char) && char !== 0x2423 /* open box */) return true; + if (isChar['Optical Character Recognition'](char)) return true; + if (isChar['Enclosed Alphanumerics'](char)) return true; + if (isChar['Geometric Shapes'](char)) return true; + if (isChar['Miscellaneous Symbols'](char)) { + if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) { + return true; + } + } + if (isChar['Miscellaneous Symbols and Arrows'](char)) { + if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) || + (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) || + (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) { + return true; + } + } + if (isChar['CJK Symbols and Punctuation'](char)) return true; + if (isChar['Katakana'](char)) return true; + if (isChar['Private Use Area'](char)) return true; + if (isChar['CJK Compatibility Forms'](char)) return true; + if (isChar['Small Form Variants'](char)) return true; + if (isChar['Halfwidth and Fullwidth Forms'](char)) return true; + + if (char === 0x221E /* infinity */ || + char === 0x2234 /* therefore */ || + char === 0x2235 /* because */ || + (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) || + (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) || + char === 0xFFFC /* object replacement character */ || + char === 0xFFFD /* replacement character */) { + return true; + } + + return false; +} + +/** + * Returns true if the given Unicode codepoint identifies a character with + * rotated orientation. + * + * A character has rotated orientation if it is drawn rotated when the line is + * oriented vertically, even if both adjacent characters are upright. For + * example, a Latin letter is drawn rotated along a vertical line. A rotated + * character causes an adjacent “neutral” character to be drawn rotated as well. + * @private + */ +export function charHasRotatedVerticalOrientation(char: number) { + return !(charHasUprightVerticalOrientation(char) || + charHasNeutralVerticalOrientation(char)); +} + +export function charInComplexShapingScript(char: number) { + return isChar['Arabic'](char) || + isChar['Arabic Supplement'](char) || + isChar['Arabic Extended-A'](char) || + isChar['Arabic Presentation Forms-A'](char) || + isChar['Arabic Presentation Forms-B'](char); +} + +export function charInRTLScript(char: number) { + // Main blocks for Hebrew, Arabic, Thaana and other RTL scripts + return (char >= 0x0590 && char <= 0x08FF) || + isChar['Arabic Presentation Forms-A'](char) || + isChar['Arabic Presentation Forms-B'](char); +} + +export function charInSupportedScript(char: number, canRenderRTL: boolean) { + // This is a rough heuristic: whether we "can render" a script + // actually depends on the properties of the font being used + // and whether differences from the ideal rendering are considered + // semantically significant. + + // Even in Latin script, we "can't render" combinations such as the fi + // ligature, but we don't consider that semantically significant. + if (!canRenderRTL && charInRTLScript(char)) { + return false; + } + if ((char >= 0x0900 && char <= 0x0DFF) || + // Main blocks for Indic scripts and Sinhala + (char >= 0x0F00 && char <= 0x109F) || + // Main blocks for Tibetan and Myanmar + isChar['Khmer'](char)) { + // These blocks cover common scripts that require + // complex text shaping, based on unicode script metadata: + // http://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt + // where "Web Rank <= 32" "Shaping Required = YES" + return false; + } + return true; +} + +export function stringContainsRTLText(chars: string): boolean { + for (const char of chars) { + if (charInRTLScript(char.charCodeAt(0))) { + return true; + } + } + return false; +} + +export function isStringInSupportedScript(chars: string, canRenderRTL: boolean) { + for (const char of chars) { + if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) { + return false; + } + } + return true; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/sku_token.js b/node_modules/@plotly/mapbox-gl/src/util/sku_token.js new file mode 100644 index 0000000000000000000000000000000000000000..990a1c60c1e4a3a4308735baf90335819f3fb7c2 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/sku_token.js @@ -0,0 +1,42 @@ +// @flow + +/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR +* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ****** +* The following code is used to access Mapbox's Mapping APIs. Removal or modification +* of this code when used with Mapbox's Mapping APIs can result in higher fees and/or +* termination of your account with Mapbox. +* +* Under the Mapbox Terms of Service, you may not use this code to access Mapbox +* Mapping APIs other than through Mapbox SDKs. +* +* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps +* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/ +******************************************************************************/ + +type SkuTokenObject = {| + token: string, + tokenExpiresAt: number +|}; + +const SKU_ID = '01'; + +function createSkuToken(): SkuTokenObject { + // SKU_ID and TOKEN_VERSION are specified by an internal schema and should not change + const TOKEN_VERSION = '1'; + const base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + // sessionRandomizer is a randomized 10-digit base-62 number + let sessionRandomizer = ''; + for (let i = 0; i < 10; i++) { + sessionRandomizer += base62chars[Math.floor(Math.random() * 62)]; + } + const expiration = 12 * 60 * 60 * 1000; // 12 hours + const token = [TOKEN_VERSION, SKU_ID, sessionRandomizer].join(''); + const tokenExpiresAt = Date.now() + expiration; + + return {token, tokenExpiresAt}; +} + +export {createSkuToken, SKU_ID}; + +/***** END WARNING - REMOVAL OR MODIFICATION OF THE +PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/ diff --git a/node_modules/@plotly/mapbox-gl/src/util/smart_wrap.js b/node_modules/@plotly/mapbox-gl/src/util/smart_wrap.js new file mode 100644 index 0000000000000000000000000000000000000000..a713d1e2b9dc3536777eed4340ef7220aba47777 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/smart_wrap.js @@ -0,0 +1,55 @@ +// @flow + +import LngLat from '../geo/lng_lat'; + +import type Point from '@mapbox/point-geometry'; +import type Transform from '../geo/transform'; + +/** + * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted + * n × 360° east or west for some n ≥ 0 such that: + * + * * the projected location of the result is on screen, if possible, and secondarily: + * * the difference between the projected location of the result and the prior position + * is minimized. + * + * The object is to preserve perceived object constancy for Popups and Markers as much as + * possible; they should avoid shifting large distances across the screen, even when the + * map center changes by ±360° due to automatic wrapping, and when about to go off screen, + * should wrap just enough to avoid doing so. + * + * @private + */ +export default function(lngLat: LngLat, priorPos: ?Point, transform: Transform): LngLat { + lngLat = new LngLat(lngLat.lng, lngLat.lat); + + // First, try shifting one world in either direction, and see if either is closer to the + // prior position. This preserves object constancy when the map center is auto-wrapped + // during animations. + if (priorPos) { + const left = new LngLat(lngLat.lng - 360, lngLat.lat); + const right = new LngLat(lngLat.lng + 360, lngLat.lat); + const delta = transform.locationPoint(lngLat).distSqr(priorPos); + if (transform.locationPoint(left).distSqr(priorPos) < delta) { + lngLat = left; + } else if (transform.locationPoint(right).distSqr(priorPos) < delta) { + lngLat = right; + } + } + + // Second, wrap toward the center until the new position is on screen, or we can't get + // any closer. + while (Math.abs(lngLat.lng - transform.center.lng) > 180) { + const pos = transform.locationPoint(lngLat); + if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) { + break; + } + if (lngLat.lng > transform.center.lng) { + lngLat.lng -= 360; + } else { + lngLat.lng += 360; + } + } + + return lngLat; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/struct_array.js b/node_modules/@plotly/mapbox-gl/src/util/struct_array.js new file mode 100644 index 0000000000000000000000000000000000000000..f033270be4374bd06923d7f8f25885a172e45334 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/struct_array.js @@ -0,0 +1,243 @@ +// @flow + +// Note: all "sizes" are measured in bytes + +import assert from 'assert'; + +import type {Transferable} from '../types/transferable'; + +const viewTypes = { + 'Int8': Int8Array, + 'Uint8': Uint8Array, + 'Int16': Int16Array, + 'Uint16': Uint16Array, + 'Int32': Int32Array, + 'Uint32': Uint32Array, + 'Float32': Float32Array +}; + +export type ViewType = $Keys; + +/** + * @private + */ +class Struct { + _pos1: number; + _pos2: number; + _pos4: number; + _pos8: number; + +_structArray: StructArray; + + // The following properties are defined on the prototype of sub classes. + size: number; + + /** + * @param {StructArray} structArray The StructArray the struct is stored in + * @param {number} index The index of the struct in the StructArray. + * @private + */ + constructor(structArray: StructArray, index: number) { + (this: any)._structArray = structArray; + this._pos1 = index * this.size; + this._pos2 = this._pos1 / 2; + this._pos4 = this._pos1 / 4; + this._pos8 = this._pos1 / 8; + } +} + +const DEFAULT_CAPACITY = 128; +const RESIZE_MULTIPLIER = 5; + +export type StructArrayMember = { + name: string, + type: ViewType, + components: number, + offset: number +}; + +export type StructArrayLayout = { + members: Array, + size: number, + alignment: ?number +} + +export type SerializedStructArray = { + length: number, + arrayBuffer: ArrayBuffer +}; + +/** + * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray` + * making it behave like an array of typed structs. + * + * Conceptually, a StructArray is comprised of elements, i.e., instances of its + * associated struct type. Each particular struct type, together with an + * alignment size, determines the memory layout of a StructArray whose elements + * are of that type. Thus, for each such layout that we need, we have + * a corrseponding StructArrayLayout class, inheriting from StructArray and + * implementing `emplaceBack()` and `_refreshViews()`. + * + * In some cases, where we need to access particular elements of a StructArray, + * we implement a more specific subclass that inherits from one of the + * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured + * object whose properties are proxies into the underlying memory space for the + * i-th element. This affords the convience of working with (seemingly) plain + * Javascript objects without the overhead of serializing/deserializing them + * into ArrayBuffers for efficient web worker transfer. + * + * @private + */ +class StructArray { + capacity: number; + length: number; + isTransferred: boolean; + arrayBuffer: ArrayBuffer; + uint8: Uint8Array; + + // The following properties are defined on the prototype. + members: Array; + bytesPerElement: number; + +emplaceBack: Function; + +emplace: Function; + + constructor() { + this.isTransferred = false; + this.capacity = -1; + this.resize(0); + } + + /** + * Serialize a StructArray instance. Serializes both the raw data and the + * metadata needed to reconstruct the StructArray base class during + * deserialization. + * @private + */ + static serialize(array: StructArray, transferables?: Array): SerializedStructArray { + assert(!array.isTransferred); + + array._trim(); + + if (transferables) { + array.isTransferred = true; + transferables.push(array.arrayBuffer); + } + + return { + length: array.length, + arrayBuffer: array.arrayBuffer, + }; + } + + static deserialize(input: SerializedStructArray) { + const structArray = Object.create(this.prototype); + structArray.arrayBuffer = input.arrayBuffer; + structArray.length = input.length; + structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement; + structArray._refreshViews(); + return structArray; + } + + /** + * Resize the array to discard unused capacity. + */ + _trim() { + if (this.length !== this.capacity) { + this.capacity = this.length; + this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement); + this._refreshViews(); + } + } + + /** + * Resets the the length of the array to 0 without de-allocating capcacity. + */ + clear() { + this.length = 0; + } + + /** + * Resize the array. + * If `n` is greater than the current length then additional elements with undefined values are added. + * If `n` is less than the current length then the array will be reduced to the first `n` elements. + * @param {number} n The new size of the array. + */ + resize(n: number) { + assert(!this.isTransferred); + this.reserve(n); + this.length = n; + } + + /** + * Indicate a planned increase in size, so that any necessary allocation may + * be done once, ahead of time. + * @param {number} n The expected size of the array. + */ + reserve(n: number) { + if (n > this.capacity) { + this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY); + this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement); + + const oldUint8Array = this.uint8; + this._refreshViews(); + if (oldUint8Array) this.uint8.set(oldUint8Array); + } + } + + /** + * Create TypedArray views for the current ArrayBuffer. + */ + _refreshViews() { + throw new Error('_refreshViews() must be implemented by each concrete StructArray layout'); + } +} + +/** + * Given a list of member fields, create a full StructArrayLayout, in + * particular calculating the correct byte offset for each field. This data + * is used at build time to generate StructArrayLayout_*#emplaceBack() and + * other accessors, and at runtime for binding vertex buffer attributes. + * + * @private + */ +function createLayout( + members: Array<{ name: string, type: ViewType, +components?: number, }>, + alignment: number = 1 +): StructArrayLayout { + + let offset = 0; + let maxSize = 0; + const layoutMembers = members.map((member) => { + assert(member.name.length); + const typeSize = sizeOf(member.type); + const memberOffset = offset = align(offset, Math.max(alignment, typeSize)); + const components = member.components || 1; + + maxSize = Math.max(maxSize, typeSize); + offset += typeSize * components; + + return { + name: member.name, + type: member.type, + components, + offset: memberOffset, + }; + }); + + const size = align(offset, Math.max(maxSize, alignment)); + + return { + members: layoutMembers, + size, + alignment + }; +} + +function sizeOf(type: ViewType): number { + return viewTypes[type].BYTES_PER_ELEMENT; +} + +function align(offset: number, size: number): number { + return Math.ceil(offset / size) * size; +} + +export {StructArray, Struct, viewTypes, createLayout}; diff --git a/node_modules/@plotly/mapbox-gl/src/util/struct_array.js.ejs b/node_modules/@plotly/mapbox-gl/src/util/struct_array.js.ejs new file mode 100644 index 0000000000000000000000000000000000000000..e9d062ad65ffbb5ec60b3527ff8f24c56df3bc2c --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/struct_array.js.ejs @@ -0,0 +1,112 @@ +<% +const { + arrayClass, + members, + size, + usedTypes, + hasAnchorPoint, + layoutClass, + includeStructAccessors +} = locals + +const StructTypeClass = arrayClass.replace('Array', 'Struct'); +const StructArrayClass = arrayClass; +const StructArrayLayoutClass = layoutClass; +-%> +<% +// collect components +const components = []; +for (const member of members) { + for (let c = 0; c < member.components; c++) { + let name = member.name; + if (member.components > 1) { + name += c; + } + components.push({name, member, component: c}); + } +} + +// exceptions for which we generate accessors on the array rather than a separate struct for performance +const useComponentGetters = StructArrayClass === 'GlyphOffsetArray' || StructArrayClass === 'SymbolLineVertexArray'; + +if (includeStructAccessors && !useComponentGetters) { +-%> +class <%=StructTypeClass%> extends Struct { + _structArray: <%=StructArrayClass%>; +<% + // property declarations + for (const {name} of components) {-%> + <%=name%>: number; +<% } + if (hasAnchorPoint) { -%> + anchorPoint: Point; +<% } -%> +<% +for (const {name, member, component} of components) { + const elementOffset = `this._pos${member.size.toFixed(0)}`; + const componentOffset = (member.offset / member.size + component).toFixed(0); + const index = `${elementOffset} + ${componentOffset}`; + const componentAccess = `this._structArray.${member.view}[${index}]`; +-%> + get <%=name%>() { return <%=componentAccess%>; } +<% +// generate setters for properties that are updated during runtime symbol placement; others are read-only +if (name === 'crossTileID' || name === 'placedOrientation' || name === 'hidden') { +-%> + set <%=name%>(x: number) { <%=componentAccess%> = x; } +<% +} +} +// Special case used for the CollisionBoxArray type +if (hasAnchorPoint) { +-%> + get anchorPoint() { return new Point(this.anchorPointX, this.anchorPointY); } +<% +} +-%> +} + +<%=StructTypeClass%>.prototype.size = <%=size%>; + +export type <%=StructTypeClass.replace('Struct', '')%> = <%=StructTypeClass%>; + +<% +} // end 'if (includeStructAccessors)' +-%> +/** + * @private + */ +export class <%=StructArrayClass%> extends <%=StructArrayLayoutClass%> { +<% +if (useComponentGetters) { + for (const member of members) { + for (let c = 0; c < member.components; c++) { + if (!includeStructAccessors) continue; + let name = `get${member.name}`; + if (member.components > 1) { + name += c; + } + const componentOffset = (member.offset / member.size + c).toFixed(0); + const componentStride = size / member.size; +-%> + <%=name%>(index: number) { return this.<%=member.view%>[index * <%=componentStride%> + <%=componentOffset%>]; } +<% + } + } +} else if (includeStructAccessors) { // get(i) +-%> + /** + * Return the <%=StructTypeClass%> at the given location in the array. + * @param {number} index The index of the element. + * @private + */ + get(index: number): <%=StructTypeClass%> { + assert(!this.isTransferred); + return new <%=StructTypeClass%>(this, index); + } +<% +} +-%> +} + +register('<%=StructArrayClass%>', <%=StructArrayClass%>); diff --git a/node_modules/@plotly/mapbox-gl/src/util/struct_array_layout.js.ejs b/node_modules/@plotly/mapbox-gl/src/util/struct_array_layout.js.ejs new file mode 100644 index 0000000000000000000000000000000000000000..3be26217d0caa1c7b86ea0c3a3d72335bd2bf5cd --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/struct_array_layout.js.ejs @@ -0,0 +1,98 @@ +<% +const { + className, + members, + size, + usedTypes +} = locals + +const StructArrayLayoutClass = className; +-%> +/** + * Implementation of the StructArray layout: +<% +for (const member of members) { +-%> + * [<%=member.offset%>]: <%=member.type%>[<%=member.components%>] +<% +} +-%> + * + * @private + */ +class <%=StructArrayLayoutClass%> extends StructArray { +<% +for (const type of usedTypes) { +-%> + <%=type.toLowerCase()%>: <%=type%>Array; +<% +} +-%> + + _refreshViews() { +<% +for (const type of usedTypes) { +-%> + this.<%=type.toLowerCase()%> = new <%=type%>Array(this.arrayBuffer); +<% +} +-%> + } + +<% +// prep for emplaceBack: collect type sizes and count the number of arguments +// we'll need +const bytesPerElement = size; +const usedTypeSizes = []; +const argNames = []; +const argNamesTyped = []; +for (const member of members) { + if (usedTypeSizes.indexOf(member.size) < 0) { + usedTypeSizes.push(member.size); + } + for (let c = 0; c < member.components; c++) { + // arguments v0, v1, v2, ... are, in order, the components of + // member 0, then the components of member 1, etc. + const name = `v${argNames.length}`; + argNames.push(name); + argNamesTyped.push(`${name}: number`); + } +} +-%> + emplaceBack(<%=argNamesTyped.join(', ')%>) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, <%=argNames.join(', ')%>); + } + + emplace(i: number, <%=argNamesTyped.join(', ')%>) { +<% +{ +for (const size of usedTypeSizes) { +-%> + const o<%=size.toFixed(0)%> = i * <%=(bytesPerElement / size).toFixed(0)%>; +<% +} + +let argIndex = 0; +for (const member of members) { + for (let c = 0; c < member.components; c++) { + // The index for `member` component `c` into the appropriate type array is: + // this.{TYPE}[o{SIZE} + MEMBER_OFFSET + {c}] = v{X} + // where MEMBER_OFFSET = ROUND(member.offset / size) is the per-element + // offset of this member into the array + const index = `o${member.size.toFixed(0)} + ${(member.offset / member.size + c).toFixed(0)}`; +-%> + this.<%=member.view%>[<%=index%>] = v<%=argIndex++%>; +<% + } +} +} +-%> + return i; + } +-%> +} + +<%=StructArrayLayoutClass%>.prototype.bytesPerElement = <%= size %>; +register('<%=StructArrayLayoutClass%>', <%=StructArrayLayoutClass%>); diff --git a/node_modules/@plotly/mapbox-gl/src/util/task_queue.js b/node_modules/@plotly/mapbox-gl/src/util/task_queue.js new file mode 100644 index 0000000000000000000000000000000000000000..25b28d250f991d4e74a7e80227bf2d78296b3210 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/task_queue.js @@ -0,0 +1,68 @@ +// @flow strict +import assert from 'assert'; + +export type TaskID = number; // can't mark opaque due to https://github.com/flowtype/flow-remove-types/pull/61 +type Task = { + callback: (timeStamp: number) => void; + id: TaskID; + cancelled: boolean; +}; + +class TaskQueue { + _queue: Array; + _id: TaskID; + _cleared: boolean; + _currentlyRunning: Array | false; + + constructor() { + this._queue = []; + this._id = 0; + this._cleared = false; + this._currentlyRunning = false; + } + + add(callback: (timeStamp: number) => void): TaskID { + const id = ++this._id; + const queue = this._queue; + queue.push({callback, id, cancelled: false}); + return id; + } + + remove(id: TaskID) { + const running = this._currentlyRunning; + const queue = running ? this._queue.concat(running) : this._queue; + for (const task of queue) { + if (task.id === id) { + task.cancelled = true; + return; + } + } + } + + run(timeStamp: number = 0) { + assert(!this._currentlyRunning); + const queue = this._currentlyRunning = this._queue; + + // Tasks queued by callbacks in the current queue should be executed + // on the next run, not the current run. + this._queue = []; + + for (const task of queue) { + if (task.cancelled) continue; + task.callback(timeStamp); + if (this._cleared) break; + } + + this._cleared = false; + this._currentlyRunning = false; + } + + clear() { + if (this._currentlyRunning) { + this._cleared = true; + } + this._queue = []; + } +} + +export default TaskQueue; diff --git a/node_modules/@plotly/mapbox-gl/src/util/throttle.js b/node_modules/@plotly/mapbox-gl/src/util/throttle.js new file mode 100644 index 0000000000000000000000000000000000000000..79c7b6e70916b21cac6d0397998c865a723df335 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/throttle.js @@ -0,0 +1,27 @@ +// @flow strict + +/** + * Throttle the given function to run at most every `period` milliseconds. + * @private + */ +export default function throttle(fn: () => void, time: number): () => ?TimeoutID { + let pending = false; + let timerId: ?TimeoutID = null; + + const later = () => { + timerId = null; + if (pending) { + fn(); + timerId = setTimeout(later, time); + pending = false; + } + }; + + return () => { + pending = true; + if (!timerId) { + later(); + } + return timerId; + }; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/throttled_invoker.js b/node_modules/@plotly/mapbox-gl/src/util/throttled_invoker.js new file mode 100644 index 0000000000000000000000000000000000000000..ca1b97bfce1175cd64d4963e242e0a5fad3172cb --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/throttled_invoker.js @@ -0,0 +1,46 @@ +// @flow + +/** + * Invokes the wrapped function in a non-blocking way when trigger() is called. Invocation requests + * are ignored until the function was actually invoked. + * + * @private + */ +class ThrottledInvoker { + _channel: MessageChannel; + _triggered: boolean; + _callback: Function + + constructor(callback: Function) { + this._callback = callback; + this._triggered = false; + if (typeof MessageChannel !== 'undefined') { + this._channel = new MessageChannel(); + this._channel.port2.onmessage = () => { + this._triggered = false; + this._callback(); + }; + } + } + + trigger() { + if (!this._triggered) { + this._triggered = true; + if (this._channel) { + this._channel.port1.postMessage(true); + } else { + setTimeout(() => { + this._triggered = false; + this._callback(); + }, 0); + } + } + } + + remove() { + delete this._channel; + this._callback = () => {}; + } +} + +export default ThrottledInvoker; diff --git a/node_modules/@plotly/mapbox-gl/src/util/tile_request_cache.js b/node_modules/@plotly/mapbox-gl/src/util/tile_request_cache.js new file mode 100644 index 0000000000000000000000000000000000000000..22b01780379e8c1410bab7ea0633d4cd329ea089 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/tile_request_cache.js @@ -0,0 +1,172 @@ +// @flow + +import {warnOnce, parseCacheControl} from './util'; +import window from './window'; + +import type Dispatcher from './dispatcher'; + +const CACHE_NAME = 'mapbox-tiles'; +let cacheLimit = 500; // 50MB / (100KB/tile) ~= 500 tiles +let cacheCheckThreshold = 50; + +const MIN_TIME_UNTIL_EXPIRY = 1000 * 60 * 7; // 7 minutes. Skip caching tiles with a short enough max age. + +export type ResponseOptions = { + status: number, + statusText: string, + headers: window.Headers +}; + +// We're using a global shared cache object. Normally, requesting ad-hoc Cache objects is fine, but +// Safari has a memory leak in which it fails to release memory when requesting keys() from a Cache +// object. See https://bugs.webkit.org/show_bug.cgi?id=203991 for more information. +let sharedCache: ?Promise; + +function cacheOpen() { + if (window.caches && !sharedCache) { + sharedCache = window.caches.open(CACHE_NAME); + } +} + +// We're never closing the cache, but our unit tests rely on changing out the global window.caches +// object, so we have a function specifically for unit tests that allows resetting the shared cache. +export function cacheClose() { + sharedCache = undefined; +} + +let responseConstructorSupportsReadableStream; +function prepareBody(response: Response, callback) { + if (responseConstructorSupportsReadableStream === undefined) { + try { + new Response(new ReadableStream()); // eslint-disable-line no-undef + responseConstructorSupportsReadableStream = true; + } catch (e) { + // Edge + responseConstructorSupportsReadableStream = false; + } + } + + if (responseConstructorSupportsReadableStream) { + callback(response.body); + } else { + response.blob().then(callback); + } +} + +export function cachePut(request: Request, response: Response, requestTime: number) { + cacheOpen(); + if (!sharedCache) return; + + const options: ResponseOptions = { + status: response.status, + statusText: response.statusText, + headers: new window.Headers() + }; + response.headers.forEach((v, k) => options.headers.set(k, v)); + + const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || ''); + if (cacheControl['no-store']) { + return; + } + if (cacheControl['max-age']) { + options.headers.set('Expires', new Date(requestTime + cacheControl['max-age'] * 1000).toUTCString()); + } + + const timeUntilExpiry = new Date(options.headers.get('Expires')).getTime() - requestTime; + if (timeUntilExpiry < MIN_TIME_UNTIL_EXPIRY) return; + + prepareBody(response, body => { + const clonedResponse = new window.Response(body, options); + + cacheOpen(); + if (!sharedCache) return; + sharedCache + .then(cache => cache.put(stripQueryParameters(request.url), clonedResponse)) + .catch(e => warnOnce(e.message)); + }); +} + +function stripQueryParameters(url: string) { + const start = url.indexOf('?'); + return start < 0 ? url : url.slice(0, start); +} + +export function cacheGet(request: Request, callback: (error: ?any, response: ?Response, fresh: ?boolean) => void) { + cacheOpen(); + if (!sharedCache) return callback(null); + + const strippedURL = stripQueryParameters(request.url); + + sharedCache + .then(cache => { + // manually strip URL instead of `ignoreSearch: true` because of a known + // performance issue in Chrome https://github.com/mapbox/mapbox-gl-js/issues/8431 + cache.match(strippedURL) + .then(response => { + const fresh = isFresh(response); + + // Reinsert into cache so that order of keys in the cache is the order of access. + // This line makes the cache a LRU instead of a FIFO cache. + cache.delete(strippedURL); + if (fresh) { + cache.put(strippedURL, response.clone()); + } + + callback(null, response, fresh); + }) + .catch(callback); + }) + .catch(callback); + +} + +function isFresh(response) { + if (!response) return false; + const expires = new Date(response.headers.get('Expires') || 0); + const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || ''); + return expires > Date.now() && !cacheControl['no-cache']; +} + +// `Infinity` triggers a cache check after the first tile is loaded +// so that a check is run at least once on each page load. +let globalEntryCounter = Infinity; + +// The cache check gets run on a worker. The reason for this is that +// profiling sometimes shows this as taking up significant time on the +// thread it gets called from. And sometimes it doesn't. It *may* be +// fine to run this on the main thread but out of caution this is being +// dispatched on a worker. This can be investigated further in the future. +export function cacheEntryPossiblyAdded(dispatcher: Dispatcher) { + globalEntryCounter++; + if (globalEntryCounter > cacheCheckThreshold) { + dispatcher.getActor().send('enforceCacheSizeLimit', cacheLimit); + globalEntryCounter = 0; + } +} + +// runs on worker, see above comment +export function enforceCacheSizeLimit(limit: number) { + cacheOpen(); + if (!sharedCache) return; + + sharedCache + .then(cache => { + cache.keys().then(keys => { + for (let i = 0; i < keys.length - limit; i++) { + cache.delete(keys[i]); + } + }); + }); +} + +export function clearTileCache(callback?: (err: ?Error) => void) { + const promise = window.caches.delete(CACHE_NAME); + if (callback) { + promise.catch(callback).then(() => callback()); + } +} + +export function setCacheLimits(limit: number, checkThreshold: number) { + cacheLimit = limit; + cacheCheckThreshold = checkThreshold; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/util.js b/node_modules/@plotly/mapbox-gl/src/util/util.js new file mode 100644 index 0000000000000000000000000000000000000000..f5e3d55c58a15a254524b4f27a2b84d00b87fde4 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/util.js @@ -0,0 +1,524 @@ +// @flow + +import UnitBezier from '@mapbox/unitbezier'; + +import Point from '@mapbox/point-geometry'; +import window from './window'; + +import type {Callback} from '../types/callback'; + +// Number.MAX_SAFE_INTEGER not available in IE +export const MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; + +/** + * @module util + * @private + */ + +/** + * Given a value `t` that varies between 0 and 1, return + * an interpolation function that eases between 0 and 1 in a pleasing + * cubic in-out fashion. + * + * @private + */ +export function easeCubicInOut(t: number): number { + if (t <= 0) return 0; + if (t >= 1) return 1; + const t2 = t * t, + t3 = t2 * t; + return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75); +} + +/** + * Given given (x, y), (x1, y1) control points for a bezier curve, + * return a function that interpolates along that curve. + * + * @param p1x control point 1 x coordinate + * @param p1y control point 1 y coordinate + * @param p2x control point 2 x coordinate + * @param p2y control point 2 y coordinate + * @private + */ +export function bezier(p1x: number, p1y: number, p2x: number, p2y: number): (t: number) => number { + const bezier = new UnitBezier(p1x, p1y, p2x, p2y); + return function(t: number) { + return bezier.solve(t); + }; +} + +/** + * A default bezier-curve powered easing function with + * control points (0.25, 0.1) and (0.25, 1) + * + * @private + */ +export const ease = bezier(0.25, 0.1, 0.25, 1); + +/** + * constrain n to the given range via min + max + * + * @param n value + * @param min the minimum value to be returned + * @param max the maximum value to be returned + * @returns the clamped value + * @private + */ +export function clamp(n: number, min: number, max: number): number { + return Math.min(max, Math.max(min, n)); +} + +/** + * constrain n to the given range, excluding the minimum, via modular arithmetic + * + * @param n value + * @param min the minimum value to be returned, exclusive + * @param max the maximum value to be returned, inclusive + * @returns constrained number + * @private + */ +export function wrap(n: number, min: number, max: number): number { + const d = max - min; + const w = ((n - min) % d + d) % d + min; + return (w === min) ? max : w; +} + +/* + * Call an asynchronous function on an array of arguments, + * calling `callback` with the completed results of all calls. + * + * @param array input to each call of the async function. + * @param fn an async function with signature (data, callback) + * @param callback a callback run after all async work is done. + * called with an array, containing the results of each async call. + * @private + */ +export function asyncAll( + array: Array, + fn: (item: Item, fnCallback: Callback) => void, + callback: Callback> +) { + if (!array.length) { return callback(null, []); } + let remaining = array.length; + const results = new Array(array.length); + let error = null; + array.forEach((item, i) => { + fn(item, (err, result) => { + if (err) error = err; + results[i] = ((result: any): Result); // https://github.com/facebook/flow/issues/2123 + if (--remaining === 0) callback(error, results); + }); + }); +} + +/* + * Polyfill for Object.values. Not fully spec compliant, but we don't + * need it to be. + * + * @private + */ +export function values(obj: {[key: string]: T}): Array { + const result = []; + for (const k in obj) { + result.push(obj[k]); + } + return result; +} + +/* + * Compute the difference between the keys in one object and the keys + * in another object. + * + * @returns keys difference + * @private + */ +export function keysDifference(obj: {[key: string]: S}, other: {[key: string]: T}): Array { + const difference = []; + for (const i in obj) { + if (!(i in other)) { + difference.push(i); + } + } + return difference; +} + +/** + * Given a destination object and optionally many source objects, + * copy all properties from the source objects into the destination. + * The last source object given overrides properties from previous + * source objects. + * + * @param dest destination object + * @param sources sources from which properties are pulled + * @private + */ +export function extend(dest: Object, ...sources: Array): Object { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; +} + +/** + * Given an object and a number of properties as strings, return version + * of that object with only those properties. + * + * @param src the object + * @param properties an array of property names chosen + * to appear on the resulting object. + * @returns object with limited properties. + * @example + * var foo = { name: 'Charlie', age: 10 }; + * var justName = pick(foo, ['name']); + * // justName = { name: 'Charlie' } + * @private + */ +export function pick(src: Object, properties: Array): Object { + const result = {}; + for (let i = 0; i < properties.length; i++) { + const k = properties[i]; + if (k in src) { + result[k] = src[k]; + } + } + return result; +} + +let id = 1; + +/** + * Return a unique numeric id, starting at 1 and incrementing with + * each call. + * + * @returns unique numeric id. + * @private + */ +export function uniqueId(): number { + return id++; +} + +/** + * Return a random UUID (v4). Taken from: https://gist.github.com/jed/982883 + * @private + */ +export function uuid(): string { + function b(a) { + return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : + //$FlowFixMe: Flow doesn't like the implied array literal conversion here + ([1e7] + -[1e3] + -4e3 + -8e3 + -1e11).replace(/[018]/g, b); + } + return b(); +} + +/** + * Return whether a given value is a power of two + * @private + */ +export function isPowerOfTwo(value: number): boolean { + return (Math.log(value) / Math.LN2) % 1 === 0; +} + +/** + * Return the next power of two, or the input value if already a power of two + * @private + */ +export function nextPowerOfTwo(value: number): number { + if (value <= 1) return 1; + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); +} + +/** + * Validate a string to match UUID(v4) of the + * form: xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx + * @param str string to validate. + * @private + */ +export function validateUuid(str: ?string): boolean { + return str ? /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(str) : false; +} + +/** + * Given an array of member function names as strings, replace all of them + * with bound versions that will always refer to `context` as `this`. This + * is useful for classes where otherwise event bindings would reassign + * `this` to the evented object or some other value: this lets you ensure + * the `this` value always. + * + * @param fns list of member function names + * @param context the context value + * @example + * function MyClass() { + * bindAll(['ontimer'], this); + * this.name = 'Tom'; + * } + * MyClass.prototype.ontimer = function() { + * alert(this.name); + * }; + * var myClass = new MyClass(); + * setTimeout(myClass.ontimer, 100); + * @private + */ +export function bindAll(fns: Array, context: Object): void { + fns.forEach((fn) => { + if (!context[fn]) { return; } + context[fn] = context[fn].bind(context); + }); +} + +/** + * Determine if a string ends with a particular substring + * + * @private + */ +export function endsWith(string: string, suffix: string): boolean { + return string.indexOf(suffix, string.length - suffix.length) !== -1; +} + +/** + * Create an object by mapping all the values of an existing object while + * preserving their keys. + * + * @private + */ +export function mapObject(input: Object, iterator: Function, context?: Object): Object { + const output = {}; + for (const key in input) { + output[key] = iterator.call(context || this, input[key], key, input); + } + return output; +} + +/** + * Create an object by filtering out values of an existing object. + * + * @private + */ +export function filterObject(input: Object, iterator: Function, context?: Object): Object { + const output = {}; + for (const key in input) { + if (iterator.call(context || this, input[key], key, input)) { + output[key] = input[key]; + } + } + return output; +} + +import deepEqual from '../style-spec/util/deep_equal'; +export {deepEqual}; + +/** + * Deeply clones two objects. + * + * @private + */ +export function clone(input: T): T { + if (Array.isArray(input)) { + return input.map(clone); + } else if (typeof input === 'object' && input) { + return ((mapObject(input, clone): any): T); + } else { + return input; + } +} + +/** + * Check if two arrays have at least one common element. + * + * @private + */ +export function arraysIntersect(a: Array, b: Array): boolean { + for (let l = 0; l < a.length; l++) { + if (b.indexOf(a[l]) >= 0) return true; + } + return false; +} + +/** + * Print a warning message to the console and ensure duplicate warning messages + * are not printed. + * + * @private + */ +const warnOnceHistory: {[key: string]: boolean} = {}; + +export function warnOnce(message: string): void { + if (!warnOnceHistory[message]) { + // console isn't defined in some WebWorkers, see #2558 + if (typeof console !== "undefined") console.warn(message); + warnOnceHistory[message] = true; + } +} + +/** + * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order + * + * @private + * @returns true for a counter clockwise set of points + */ +// http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ +export function isCounterClockwise(a: Point, b: Point, c: Point): boolean { + return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); +} + +/** + * Returns the signed area for the polygon ring. Postive areas are exterior rings and + * have a clockwise winding. Negative areas are interior rings and have a counter clockwise + * ordering. + * + * @private + * @param ring Exterior or interior ring + */ +export function calculateSignedArea(ring: Array): number { + let sum = 0; + for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +/** + * Detects closed polygons, first + last point are equal + * + * @private + * @param points array of points + * @return true if the points are a closed polygon + */ +export function isClosedPolygon(points: Array): boolean { + // If it is 2 points that are the same then it is a point + // If it is 3 points with start and end the same then it is a line + if (points.length < 4) + return false; + + const p1 = points[0]; + const p2 = points[points.length - 1]; + + if (Math.abs(p1.x - p2.x) > 0 || + Math.abs(p1.y - p2.y) > 0) { + return false; + } + + // polygon simplification can produce polygons with zero area and more than 3 points + return Math.abs(calculateSignedArea(points)) > 0.01; +} + +/** + * Converts spherical coordinates to cartesian coordinates. + * + * @private + * @param spherical Spherical coordinates, in [radial, azimuthal, polar] + * @return cartesian coordinates in [x, y, z] + */ + +export function sphericalToCartesian([r, azimuthal, polar]: [number, number, number]): {x: number, y: number, z: number} { + // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2): + // correct for that here + azimuthal += 90; + + // Convert azimuthal and polar angles to radians + azimuthal *= Math.PI / 180; + polar *= Math.PI / 180; + + return { + x: r * Math.cos(azimuthal) * Math.sin(polar), + y: r * Math.sin(azimuthal) * Math.sin(polar), + z: r * Math.cos(polar) + }; +} + +/* global self, WorkerGlobalScope */ +/** + * Retuns true if the when run in the web-worker context. + * + * @private + * @returns {boolean} + */ +export function isWorker(): boolean { + return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && + self instanceof WorkerGlobalScope; +} + +/** + * Parses data from 'Cache-Control' headers. + * + * @private + * @param cacheControl Value of 'Cache-Control' header + * @return object containing parsed header info. + */ + +export function parseCacheControl(cacheControl: string): Object { + // Taken from [Wreck](https://github.com/hapijs/wreck) + const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g; + + const header = {}; + cacheControl.replace(re, ($0, $1, $2, $3) => { + const value = $2 || $3; + header[$1] = value ? value.toLowerCase() : true; + return ''; + }); + + if (header['max-age']) { + const maxAge = parseInt(header['max-age'], 10); + if (isNaN(maxAge)) delete header['max-age']; + else header['max-age'] = maxAge; + } + + return header; +} + +let _isSafari = null; + +/** + * Returns true when run in WebKit derived browsers. + * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to + * transfer data between WebWorkers and the main thread. + * https://github.com/mapbox/mapbox-gl-js/issues/8771 + * + * This should be removed once the underlying Safari issue is fixed. + * + * @private + * @param scope {WindowOrWorkerGlobalScope} Since this function is used both on the main thread and WebWorker context, + * let the calling scope pass in the global scope object. + * @returns {boolean} + */ +export function isSafari(scope: any): boolean { + if (_isSafari == null) { + const userAgent = scope.navigator ? scope.navigator.userAgent : null; + _isSafari = !!scope.safari || + !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome')))); + } + return _isSafari; +} + +export function storageAvailable(type: string): boolean { + try { + const storage = window[type]; + storage.setItem('_mapbox_test_', 1); + storage.removeItem('_mapbox_test_'); + return true; + } catch (e) { + return false; + } +} + +// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem +//Unicode compliant base64 encoder for strings +export function b64EncodeUnicode(str: string) { + return window.btoa( + encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, + (match, p1) => { + return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line + } + ) + ); +} + +// Unicode compliant decoder for base64-encoded strings +export function b64DecodeUnicode(str: string) { + return decodeURIComponent(window.atob(str).split('').map((c) => { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line + }).join('')); +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/vectortile_to_geojson.js b/node_modules/@plotly/mapbox-gl/src/util/vectortile_to_geojson.js new file mode 100644 index 0000000000000000000000000000000000000000..87df3344a4f403d1a19d83c008675418f553a26b --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/vectortile_to_geojson.js @@ -0,0 +1,50 @@ +// @flow +import type {GeoJSONGeometry} from '@mapbox/geojson-types'; + +class Feature { + type: 'Feature'; + _geometry: ?GeoJSONGeometry; + properties: {}; + id: number | string | void; + + _vectorTileFeature: VectorTileFeature; + + constructor(vectorTileFeature: VectorTileFeature, z: number, x: number, y: number, id: string | number | void) { + this.type = 'Feature'; + + this._vectorTileFeature = vectorTileFeature; + (vectorTileFeature: any)._z = z; + (vectorTileFeature: any)._x = x; + (vectorTileFeature: any)._y = y; + + this.properties = vectorTileFeature.properties; + this.id = id; + } + + get geometry(): ?GeoJSONGeometry { + if (this._geometry === undefined) { + this._geometry = this._vectorTileFeature.toGeoJSON( + (this._vectorTileFeature: any)._x, + (this._vectorTileFeature: any)._y, + (this._vectorTileFeature: any)._z).geometry; + } + return this._geometry; + } + + set geometry(g: ?GeoJSONGeometry) { + this._geometry = g; + } + + toJSON() { + const json = { + geometry: this.geometry + }; + for (const i in this) { + if (i === '_geometry' || i === '_vectorTileFeature') continue; + json[i] = (this: any)[i]; + } + return json; + } +} + +export default Feature; diff --git a/node_modules/@plotly/mapbox-gl/src/util/verticalize_punctuation.js b/node_modules/@plotly/mapbox-gl/src/util/verticalize_punctuation.js new file mode 100644 index 0000000000000000000000000000000000000000..658ffdf6316d58e96f44c4e12e7494117b4ffe80 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/verticalize_punctuation.js @@ -0,0 +1,114 @@ +// @flow + +import { + charHasRotatedVerticalOrientation, +} from './script_detection'; + +export const verticalizedCharacterMap = { + '!': '︕', + '#': '#', + '$': '$', + '%': '%', + '&': '&', + '(': '︵', + ')': '︶', + '*': '*', + '+': '+', + ',': '︐', + '-': '︲', + '.': '・', + '/': '/', + ':': '︓', + ';': '︔', + '<': '︿', + '=': '=', + '>': '﹀', + '?': '︖', + '@': '@', + '[': '﹇', + '\\': '\', + ']': '﹈', + '^': '^', + '_': '︳', + '`': '`', + '{': '︷', + '|': '―', + '}': '︸', + '~': '~', + '¢': '¢', + '£': '£', + '¥': '¥', + '¦': '¦', + '¬': '¬', + '¯': ' ̄', + '–': '︲', + '—': '︱', + '‘': '﹃', + '’': '﹄', + '“': '﹁', + '”': '﹂', + '…': '︙', + '‧': '・', + '₩': '₩', + '、': '︑', + '。': '︒', + '〈': '︿', + '〉': '﹀', + '《': '︽', + '》': '︾', + '「': '﹁', + '」': '﹂', + '『': '﹃', + '』': '﹄', + '【': '︻', + '】': '︼', + '〔': '︹', + '〕': '︺', + '〖': '︗', + '〗': '︘', + '!': '︕', + '(': '︵', + ')': '︶', + ',': '︐', + '-': '︲', + '.': '・', + ':': '︓', + ';': '︔', + '<': '︿', + '>': '﹀', + '?': '︖', + '[': '﹇', + ']': '﹈', + '_': '︳', + '{': '︷', + '|': '―', + '}': '︸', + '⦅': '︵', + '⦆': '︶', + '。': '︒', + '「': '﹁', + '」': '﹂' +}; + +export default function verticalizePunctuation(input: string) { + let output = ''; + + for (let i = 0; i < input.length; i++) { + const nextCharCode = input.charCodeAt(i + 1) || null; + const prevCharCode = input.charCodeAt(i - 1) || null; + + const canReplacePunctuation = ( + (!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && + (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]]) + ); + + if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) { + output += verticalizedCharacterMap[input[i]]; + } else { + output += input[i]; + } + } + + return output; +} + diff --git a/node_modules/@plotly/mapbox-gl/src/util/web_worker.js b/node_modules/@plotly/mapbox-gl/src/util/web_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..b08477c97b3130312bf0dcd1eef3fc44c66528ae --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/web_worker.js @@ -0,0 +1,91 @@ +// @flow + +// This file is intended for use in the GL-JS test suite +// It implements a MessageBus main thread interface for use in Node environments +// In a browser environment, this file is replaced with ./src/util/browser/web_worker.js +// when Rollup builds the main bundle. +// See package.json#browser + +import Worker from '../source/worker'; + +import type {WorkerSource} from '../source/worker_source'; + +type MessageListener = ({data: Object}) => mixed; + +// The main thread interface. Provided by Worker in a browser environment, +// and MessageBus below in a node environment. +export interface WorkerInterface { + addEventListener(type: 'message', listener: MessageListener): void; + removeEventListener(type: 'message', listener: MessageListener): void; + postMessage(message: any): void; + terminate(): void; +} + +export interface WorkerGlobalScopeInterface { + importScripts(...urls: Array): void; + + registerWorkerSource: (string, Class) => void, + registerRTLTextPlugin: (_: any) => void +} + +class MessageBus implements WorkerInterface, WorkerGlobalScopeInterface { + addListeners: Array; + postListeners: Array; + target: MessageBus; + registerWorkerSource: *; + registerRTLTextPlugin: *; + + constructor(addListeners: Array, postListeners: Array) { + this.addListeners = addListeners; + this.postListeners = postListeners; + } + + addEventListener(event: 'message', callback: MessageListener) { + if (event === 'message') { + this.addListeners.push(callback); + } + } + + removeEventListener(event: 'message', callback: MessageListener) { + const i = this.addListeners.indexOf(callback); + if (i >= 0) { + this.addListeners.splice(i, 1); + } + } + + postMessage(data: Object) { + setImmediate(() => { + try { + for (const listener of this.postListeners) { + listener({data, target: this.target}); + } + } catch (e) { + console.error(e); + } + }); + } + + terminate() { + this.addListeners.splice(0, this.addListeners.length); + this.postListeners.splice(0, this.postListeners.length); + } + + importScripts() {} +} + +export default function WebWorker(): WorkerInterface { + const parentListeners = [], + workerListeners = [], + parentBus = new MessageBus(workerListeners, parentListeners), + workerBus = new MessageBus(parentListeners, workerListeners); + + parentBus.target = workerBus; + workerBus.target = parentBus; + + new WebWorker.Worker(workerBus); + + return parentBus; +} + +// expose to allow stubbing in unit tests +WebWorker.Worker = Worker; diff --git a/node_modules/@plotly/mapbox-gl/src/util/web_worker_transfer.js b/node_modules/@plotly/mapbox-gl/src/util/web_worker_transfer.js new file mode 100644 index 0000000000000000000000000000000000000000..a3625eccc42c3796e49fb7d0fe24a06f360c7842 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/web_worker_transfer.js @@ -0,0 +1,266 @@ +// @flow + +import assert from 'assert'; + +import Grid from 'grid-index'; +import Color from '../style-spec/util/color'; +import {StylePropertyFunction, StyleExpression, ZoomDependentExpression, ZoomConstantExpression} from '../style-spec/expression'; +import CompoundExpression from '../style-spec/expression/compound_expression'; +import expressions from '../style-spec/expression/definitions'; +import ResolvedImage from '../style-spec/expression/types/resolved_image'; +import window from './window'; +const {ImageData, ImageBitmap} = window; + +import type {Transferable} from '../types/transferable'; + +type SerializedObject = {[_: string]: Serialized }; // eslint-disable-line +export type Serialized = + | null + | void + | boolean + | number + | string + | Boolean + | Number + | String + | Date + | RegExp + | ArrayBuffer + | $ArrayBufferView + | ImageData + | Array + | SerializedObject; + +type Registry = { + [_: string]: { + klass: Class, + omit: $ReadOnlyArray, + shallow: $ReadOnlyArray + } +}; + +type RegisterOptions = { + omit?: $ReadOnlyArray<$Keys>, + shallow?: $ReadOnlyArray<$Keys> +} + +const registry: Registry = {}; + +/** + * Register the given class as serializable. + * + * @param options + * @param options.omit List of properties to omit from serialization (e.g., cached/computed properties) + * @param options.shallow List of properties that should be serialized by a simple shallow copy, rather than by a recursive call to serialize(). + * + * @private + */ +export function register(name: string, klass: Class, options: RegisterOptions = {}) { + assert(!registry[name], `${name} is already registered.`); + (Object.defineProperty: any)(klass, '_classRegistryKey', { + value: name, + writeable: false + }); + registry[name] = { + klass, + omit: options.omit || [], + shallow: options.shallow || [] + }; +} + +register('Object', Object); + +type SerializedGrid = { buffer: ArrayBuffer }; + +Grid.serialize = function serialize(grid: Grid, transferables?: Array): SerializedGrid { + const buffer = grid.toArrayBuffer(); + if (transferables) { + transferables.push(buffer); + } + return {buffer}; +}; + +Grid.deserialize = function deserialize(serialized: SerializedGrid): Grid { + return new Grid(serialized.buffer); +}; +register('Grid', Grid); + +register('Color', Color); +register('Error', Error); +register('ResolvedImage', ResolvedImage); + +register('StylePropertyFunction', StylePropertyFunction); +register('StyleExpression', StyleExpression, {omit: ['_evaluator']}); + +register('ZoomDependentExpression', ZoomDependentExpression); +register('ZoomConstantExpression', ZoomConstantExpression); +register('CompoundExpression', CompoundExpression, {omit: ['_evaluate']}); +for (const name in expressions) { + if ((expressions[name]: any)._classRegistryKey) continue; + register(`Expression_${name}`, expressions[name]); +} + +function isArrayBuffer(val: any): boolean { + return val && typeof ArrayBuffer !== 'undefined' && + (val instanceof ArrayBuffer || (val.constructor && val.constructor.name === 'ArrayBuffer')); +} + +function isImageBitmap(val: any): boolean { + return ImageBitmap && + val instanceof ImageBitmap; +} + +/** + * Serialize the given object for transfer to or from a web worker. + * + * For non-builtin types, recursively serialize each property (possibly + * omitting certain properties - see register()), and package the result along + * with the constructor's `name` so that the appropriate constructor can be + * looked up in `deserialize()`. + * + * If a `transferables` array is provided, add any transferable objects (i.e., + * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed, + * this should happen in the client code, before using serialize().) + * + * @private + */ +export function serialize(input: mixed, transferables: ?Array): Serialized { + if (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp) { + return input; + } + + if (isArrayBuffer(input) || isImageBitmap(input)) { + if (transferables) { + transferables.push(((input: any): ArrayBuffer)); + } + return input; + } + + if (ArrayBuffer.isView(input)) { + const view: $ArrayBufferView = (input: any); + if (transferables) { + transferables.push(view.buffer); + } + return view; + } + + if (input instanceof ImageData) { + if (transferables) { + transferables.push(input.data.buffer); + } + return input; + } + + if (Array.isArray(input)) { + const serialized: Array = []; + for (const item of input) { + serialized.push(serialize(item, transferables)); + } + return serialized; + } + + if (typeof input === 'object') { + const klass = (input.constructor: any); + const name = klass._classRegistryKey; + if (!name) { + throw new Error(`can't serialize object of unregistered class`); + } + assert(registry[name]); + + const properties: SerializedObject = klass.serialize ? + // (Temporary workaround) allow a class to provide static + // `serialize()` and `deserialize()` methods to bypass the generic + // approach. + // This temporary workaround lets us use the generic serialization + // approach for objects whose members include instances of dynamic + // StructArray types. Once we refactor StructArray to be static, + // we can remove this complexity. + (klass.serialize(input, transferables): SerializedObject) : {}; + + if (!klass.serialize) { + for (const key in input) { + // any cast due to https://github.com/facebook/flow/issues/5393 + if (!(input: any).hasOwnProperty(key)) continue; + if (registry[name].omit.indexOf(key) >= 0) continue; + const property = (input: any)[key]; + properties[key] = registry[name].shallow.indexOf(key) >= 0 ? + property : + serialize(property, transferables); + } + if (input instanceof Error) { + properties.message = input.message; + } + } else { + // make sure statically serialized object survives transfer of $name property + assert(!transferables || properties !== transferables[transferables.length - 1]); + } + + if (properties.$name) { + throw new Error('$name property is reserved for worker serialization logic.'); + } + if (name !== 'Object') { + properties.$name = name; + } + + return properties; + } + + throw new Error(`can't serialize object of type ${typeof input}`); +} + +export function deserialize(input: Serialized): mixed { + if (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp || + isArrayBuffer(input) || + isImageBitmap(input) || + ArrayBuffer.isView(input) || + input instanceof ImageData) { + return input; + } + + if (Array.isArray(input)) { + return input.map(deserialize); + } + + if (typeof input === 'object') { + const name = (input: any).$name || 'Object'; + + const {klass} = registry[name]; + if (!klass) { + throw new Error(`can't deserialize unregistered class ${name}`); + } + + if (klass.deserialize) { + return (klass.deserialize: typeof deserialize)(input); + } + + const result = Object.create(klass.prototype); + + for (const key of Object.keys(input)) { + if (key === '$name') continue; + const value = (input: SerializedObject)[key]; + result[key] = registry[name].shallow.indexOf(key) >= 0 ? value : deserialize(value); + } + + return result; + } + + throw new Error(`can't deserialize object of type ${typeof input}`); +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/webp_supported.js b/node_modules/@plotly/mapbox-gl/src/util/webp_supported.js new file mode 100644 index 0000000000000000000000000000000000000000..7c40c7c97b531c6f93a7b7f55844687beb9d027c --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/webp_supported.js @@ -0,0 +1,69 @@ +// @flow strict + +import window from './window'; + +const exported = { + supported: false, + testSupport +}; + +export default exported; + +let glForTesting; +let webpCheckComplete = false; +let webpImgTest; +let webpImgTestOnloadComplete = false; + +if (window.document) { + webpImgTest = window.document.createElement('img'); + webpImgTest.onload = function() { + if (glForTesting) testWebpTextureUpload(glForTesting); + glForTesting = null; + webpImgTestOnloadComplete = true; + }; + webpImgTest.onerror = function() { + webpCheckComplete = true; + glForTesting = null; + }; + webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA='; +} + +function testSupport(gl: WebGLRenderingContext) { + if (webpCheckComplete || !webpImgTest) return; + + // HTMLImageElement.complete is set when an image is done loading it's source + // regardless of whether the load was successful or not. + // It's possible for an error to set HTMLImageElement.complete to true which would trigger + // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp + // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload + // after a successful image load event. + if (webpImgTestOnloadComplete) { + testWebpTextureUpload(gl); + } else { + glForTesting = gl; + + } +} + +function testWebpTextureUpload(gl: WebGLRenderingContext) { + // Edge 18 supports WebP but not uploading a WebP image to a gl texture + // Test support for this before allowing WebP images. + // https://github.com/mapbox/mapbox-gl-js/issues/7671 + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + + try { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest); + + // The error does not get triggered in Edge if the context is lost + if (gl.isContextLost()) return; + + exported.supported = true; + } catch (e) { + // Catch "Unspecified Error." in Edge 18. + } + + gl.deleteTexture(texture); + + webpCheckComplete = true; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/window.js b/node_modules/@plotly/mapbox-gl/src/util/window.js new file mode 100644 index 0000000000000000000000000000000000000000..0d465f163f9e16e73805eefda9a678b6dcaadae8 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/window.js @@ -0,0 +1,102 @@ +// @flow strict + +// This file is intended for use in the GL-JS test suite +// It implements a JSDOM window object for use in Node environments +// In a browser environment, this file is replaced with ./src/util/browser/window.js +// when Rollup builds the main bundle +// See package.json#browser + +import jsdom from 'jsdom'; + +import gl from 'gl'; +import sinon from 'sinon'; + +import type {Window} from '../types/window'; + +const {window: _window} = new jsdom.JSDOM('', { + virtualConsole: new jsdom.VirtualConsole().sendTo(console) +}); + +restore(); + +export default _window; + +function restore(): Window { + // Remove previous window from exported object + const previousWindow = _window; + if (previousWindow.close) previousWindow.close(); + for (const key in previousWindow) { + if (previousWindow.hasOwnProperty(key)) { + delete previousWindow[key]; + } + } + + // Create new window and inject into exported object + const {window} = new jsdom.JSDOM('', { + // Send jsdom console output to the node console object. + virtualConsole: new jsdom.VirtualConsole().sendTo(console) + }); + + // Delete local and session storage from JSDOM and stub them out with a warning log + // Accessing these properties during extend() produces an error in Node environments + // See https://github.com/mapbox/mapbox-gl-js/pull/7455 for discussion + delete window.localStorage; + delete window.sessionStorage; + window.localStorage = window.sessionStorage = () => console.log('Local and session storage not available in Node. Use a stub implementation if needed for testing.'); + + window.devicePixelRatio = 1; + + window.requestAnimationFrame = function(callback) { + return setImmediate(callback, 0); + }; + window.cancelAnimationFrame = clearImmediate; + + // Add webgl context with the supplied GL + const originalGetContext = window.HTMLCanvasElement.prototype.getContext; + window.HTMLCanvasElement.prototype.getContext = function (type, attributes) { + if (type === 'webgl') { + if (!this._webGLContext) { + this._webGLContext = gl(this.width, this.height, attributes); + } + return this._webGLContext; + } + // Fallback to existing HTMLCanvasElement getContext behaviour + return originalGetContext.call(this, type, attributes); + }; + + window.useFakeHTMLCanvasGetContext = function() { + this.HTMLCanvasElement.prototype.getContext = function() { return '2d'; }; + }; + + window.useFakeXMLHttpRequest = function() { + sinon.xhr.supportsCORS = true; + this.server = sinon.fakeServer.create(); + this.XMLHttpRequest = this.server.xhr; + }; + + window.URL.revokeObjectURL = function () {}; + + window.fakeWorkerPresence = function() { + global.WorkerGlobalScope = function() {}; + global.self = new global.WorkerGlobalScope(); + }; + window.clearFakeWorkerPresence = function() { + global.WorkerGlobalScope = undefined; + global.self = undefined; + }; + + window.restore = restore; + + window.performance.getEntriesByName = function() {}; + window.performance.mark = function() {}; + window.performance.measure = function() {}; + window.performance.clearMarks = function() {}; + window.performance.clearMeasures = function() {}; + + window.ImageData = window.ImageData || function() { return false; }; + window.ImageBitmap = window.ImageBitmap || function() { return false; }; + window.WebGLFramebuffer = window.WebGLFramebuffer || Object; + Object.assign(_window, window); // eslint-disable-line no-restricted-properties + + return window; +} diff --git a/node_modules/@plotly/mapbox-gl/src/util/worker_pool.js b/node_modules/@plotly/mapbox-gl/src/util/worker_pool.js new file mode 100644 index 0000000000000000000000000000000000000000..f9a899dfcca8216df24445ec0c5281c930a33c23 --- /dev/null +++ b/node_modules/@plotly/mapbox-gl/src/util/worker_pool.js @@ -0,0 +1,57 @@ +// @flow + +import WebWorker from './web_worker'; +import type {WorkerInterface} from './web_worker'; +import browser from './browser'; + +export const PRELOAD_POOL_ID = 'mapboxgl_preloaded_worker_pool'; + +/** + * Constructs a worker pool. + * @private + */ +export default class WorkerPool { + static workerCount: number; + + active: {[_: number | string]: boolean}; + workers: Array; + + constructor() { + this.active = {}; + } + + acquire(mapId: number | string): Array { + if (!this.workers) { + // Lazily look up the value of mapboxgl.workerCount so that + // client code has had a chance to set it. + this.workers = []; + while (this.workers.length < WorkerPool.workerCount) { + this.workers.push(new WebWorker()); + } + } + + this.active[mapId] = true; + return this.workers.slice(); + } + + release(mapId: number | string) { + delete this.active[mapId]; + if (this.numActive() === 0) { + this.workers.forEach((w) => { + w.terminate(); + }); + this.workers = (null: any); + } + } + + isPreloaded(): boolean { + return !!this.active[PRELOAD_POOL_ID]; + } + + numActive(): number { + return Object.keys(this.active).length; + } +} + +const availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2); +WorkerPool.workerCount = Math.max(Math.min(availableLogicalProcessors, 6), 1); diff --git a/node_modules/@plotly/point-cluster/.eslintrc.json b/node_modules/@plotly/point-cluster/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..c50c250446ee6d06a87a590ecbf3905696b0871d --- /dev/null +++ b/node_modules/@plotly/point-cluster/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/@plotly/point-cluster/.github/workflows/npmpublish.yml b/node_modules/@plotly/point-cluster/.github/workflows/npmpublish.yml new file mode 100644 index 0000000000000000000000000000000000000000..ed81431b5def30dcb828998fbb0f3f435ef0f412 --- /dev/null +++ b/node_modules/@plotly/point-cluster/.github/workflows/npmpublish.yml @@ -0,0 +1,45 @@ +name: Node.js Package + +on: + release: + types: [created] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-node@v1 + with: + node-version: 12 + - run: npm ci + - run: npm test + + publish-npm: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-node@v1 + with: + node-version: 12 + registry-url: https://registry.npmjs.org/ + - run: npm ci + - run: npm publish + env: + NODE_AUTH_TOKEN: ${{secrets.npm_token}} + + publish-gpr: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-node@v1 + with: + node-version: 12 + registry-url: https://npm.pkg.github.com/ + scope: '@your-github-username' + - run: npm ci + - run: npm publish + env: + NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/node_modules/@plotly/point-cluster/README.md b/node_modules/@plotly/point-cluster/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4002ff67d81cde611797780db5a3d41a6a525b64 --- /dev/null +++ b/node_modules/@plotly/point-cluster/README.md @@ -0,0 +1,88 @@ +# point-cluster [![Build Status](https://travis-ci.org/dy/point-cluster.svg?branch=master)](https://travis-ci.org/dy/point-cluster) [![experimental](https://img.shields.io/badge/stability-experimental-yellow.svg)](http://github.com/badges/stability-badges) + +Point clustering for 2D spatial indexing. Incorporates optimized quad-tree data structure. + + + + +```js +const cluster = require('point-cluster') + +let ids = cluster(points) + +// get point ids in the indicated range +let selectedIds = ids.range([10, 10, 20, 20]) + +// get levels of details: list of ids subranges for rendering purposes +let lod = ids.range([10, 10, 20, 20], { lod: true }) +``` + +## API + +### `ids = cluster(points, options?)` + +Create index for the set of 2d `points` based on `options`. + +* `points` is an array of `[x,y, x,y, ...]` or `[[x,y], [x,y], ...]` coordinates. +* `ids` is _Uint32Array_ with point ids sorted by zoom levels, suitable for WebGL buffer, subranging or alike. +* `options` + +Option | Default | Description +---|---|--- +`bounds` | `'auto'` | Data range, if different from `points` bounds, eg. in case of subdata. +`depth` | `256` | Max number of levels. Points below the indicated level are grouped into single level. +`output` | `'array'` | Output data array or data format. For available formats see [dtype](https://npmjs.org/package/dtype). + + + + +--- + + +### `result = ids.range(box?, options?)` + +Get point ids from the indicated range. + +* `box` can be any rectangle object, eg. `[l, t, r, b]`, see [parse-rect](https://github.com/dy/parse-rect). +* `options` + +Option | Default | Description +---|---|--- +`lod` | `false` | Makes result a list of level details instead of ids, useful for obtaining subranges to render. +`px` | `0` | Min pixel size in data dimension (number or `[width, height]` couple) to search for, to ignore lower levels. +`level` | `null` | Max level to limit search. + +```js +let levels = ids.range([0,0, 100, 100], { lod: true, d: dataRange / canvas.width }) + +levels.forEach([from, to] => { + // offset and count point to range in `ids` array + render( ids.subarray( from, to ) ) +}) +``` + + +### Related + +* [snap-points-2d](https://github.com/gl-vis/snap-points-2d) − grouping points by pixels. +* [kdgrass](https://github.com/dy/kdgrass) − minimal kd-tree implementation. +* [regl-scatter2d](https://github.com/dfreative/regl-scatter2d) − highly performant scatter2d plot. + + +## License + +© 2017 Dmitry Yv. MIT License + +Development supported by [plot.ly](https://github.com/plotly/). diff --git a/node_modules/@plotly/point-cluster/index.js b/node_modules/@plotly/point-cluster/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a72eb90ffd899a0e4ce72bf6d97df96e8263fa3f --- /dev/null +++ b/node_modules/@plotly/point-cluster/index.js @@ -0,0 +1,3 @@ +'use strict' + +module.exports = require('./quad') diff --git a/node_modules/@plotly/point-cluster/kd.js b/node_modules/@plotly/point-cluster/kd.js new file mode 100644 index 0000000000000000000000000000000000000000..41a7c8faa2a6dc4248c9689cd454e854841a3fbb --- /dev/null +++ b/node_modules/@plotly/point-cluster/kd.js @@ -0,0 +1,84 @@ +/** + * kd-tree based clustering + * + * Based on kdbush package + */ + +'use strict' + + +module.exports = function clusterKD (points, ids, levels, weights, options) { + let ptr = 0 + let n = ids.length + let nodeSize = options.nodeSize + + sort(0, n - 1, 0) + + function sort(left, right, level) { + let count = right - left + weights[ptr] = count + levels[ptr++] = level + + if (count <= nodeSize) return; + + let m = Math.floor((left + right) / 2); + + select(m, left, right, level % 2); + + sort(left, m - 1, level + 1); + sort(m + 1, right, level + 1); + } + + function select(k, left, right, inc) { + while (right > left) { + if (right - left > 600) { + let n = right - left + 1; + let m = k - left + 1; + let z = Math.log(n); + let s = 0.5 * Math.exp(2 * z / 3); + let sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + let newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + let newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + select(k, newLeft, newRight, inc); + } + + let t = points[2 * k + inc]; + let i = left; + let j = right; + + swapItem(left, k); + if (points[2 * right + inc] > t) swapItem(left, right); + + while (i < j) { + swapItem(i, j); + i++; + j--; + while (points[2 * i + inc] < t) i++; + while (points[2 * j + inc] > t) j--; + } + + if (points[2 * left + inc] === t) swapItem(left, j); + else { + j++; + swapItem(j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } + } + + function swapItem(i, j) { + swap(ids, i, j); + swap(points, 2 * i, 2 * j); + swap(points, 2 * i + 1, 2 * j + 1); + } + + function swap(arr, i, j) { + let tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } +} + + diff --git a/node_modules/@plotly/point-cluster/license.md b/node_modules/@plotly/point-cluster/license.md new file mode 100644 index 0000000000000000000000000000000000000000..a8405c9e2a627a546c471ab404f3810d6e5ec4d4 --- /dev/null +++ b/node_modules/@plotly/point-cluster/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Dmitry Ivanov + +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. diff --git a/node_modules/@plotly/point-cluster/package.json b/node_modules/@plotly/point-cluster/package.json new file mode 100644 index 0000000000000000000000000000000000000000..51d4017864c15ef6ab349cbb89811c3f94f745a5 --- /dev/null +++ b/node_modules/@plotly/point-cluster/package.json @@ -0,0 +1,63 @@ +{ + "name": "@plotly/point-cluster", + "version": "3.1.9", + "description": "Fast nd point clustering.", + "main": "index.js", + "scripts": { + "test": "node test", + "build": "browserify demo.js -g bubleify | indexhtmlify | metadataify | github-cornerify > demo/index.html" + }, + "repository": { + "type": "git", + "url": "git://github.com/plotly/point-cluster.git" + }, + "keywords": [ + "snap-points-2d", + "supercluster", + "quadtree", + "quad-tree", + "kdtree", + "kd-tree", + "ann-tree", + "point", + "scatter", + "point2d", + "2d", + "cluster", + "clustering", + "geospatial", + "markers", + "round", + "data", + "vis", + "gl-vis" + ], + "browserify": { + "transform": [ + "bubleify" + ] + }, + "author": "Dmitry Yv ", + "license": "MIT", + "dependencies": { + "array-bounds": "^1.0.1", + "binary-search-bounds": "^2.0.4", + "clamp": "^1.0.1", + "defined": "^1.0.0", + "dtype": "^2.0.0", + "flatten-vertex-data": "^1.0.2", + "is-obj": "^1.0.1", + "math-log2": "^1.0.1", + "parse-rect": "^1.2.0", + "pick-by-alias": "^1.2.0" + }, + "devDependencies": { + "almost-equal": "^1.1.0", + "bubleify": "^2.0.0", + "canvas-fit": "^1.5.0", + "gauss-random": "^1.0.1", + "math-float64-from-bits": "^1.0.0", + "snap-points-2d": "^3.2.0", + "tape": "^4.8.0" + } +} diff --git a/node_modules/@plotly/point-cluster/quad.js b/node_modules/@plotly/point-cluster/quad.js new file mode 100644 index 0000000000000000000000000000000000000000..414faa569406f5087f5b77b93ecaa9b88025b7da --- /dev/null +++ b/node_modules/@plotly/point-cluster/quad.js @@ -0,0 +1,337 @@ +/** + * @module point-cluster/quad + * + * Bucket based quad tree clustering + */ + +'use strict' + +const search = require('binary-search-bounds') +const clamp = require('clamp') +const rect = require('parse-rect') +const getBounds = require('array-bounds') +const pick = require('pick-by-alias') +const defined = require('defined') +const flatten = require('flatten-vertex-data') +const isObj = require('is-obj') +const dtype = require('dtype') +const log2 = require('math-log2') + +const MAX_GROUP_ID = 1073741824 + +module.exports = function cluster (srcPoints, options) { + if (!options) options = {} + + srcPoints = flatten(srcPoints, 'float64') + + options = pick(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) + let maxDepth = defined(options.maxDepth, 255) + let bounds = defined(options.bounds, getBounds(srcPoints, 2)) + if (bounds[0] === bounds[2]) bounds[2]++ + if (bounds[1] === bounds[3]) bounds[3]++ + + let points = normalize(srcPoints, bounds) + + // init variables + let n = srcPoints.length >>> 1 + let ids + if (!options.dtype) options.dtype = 'array' + + if (typeof options.dtype === 'string') { + ids = new (dtype(options.dtype))(n) + } + else if (options.dtype) { + ids = options.dtype + if (Array.isArray(ids)) ids.length = n + } + for (let i = 0; i < n; ++i) { + ids[i] = i + } + + // representative point indexes for levels + let levels = [] + + // starting indexes of subranges in sub levels, levels.length * 4 + let sublevels = [] + + // unique group ids, sorted in z-curve fashion within levels by shifting bits + let groups = [] + + // level offsets in `ids` + let offsets = [] + + + // sort points + sort(0, 0, 1, ids, 0, 1) + + + // return reordered ids with provided methods + // save level offsets in output buffer + let offset = 0 + for (let level = 0; level < levels.length; level++) { + let levelItems = levels[level] + if (ids.set) ids.set(levelItems, offset) + else { + for (let i = 0, l = levelItems.length; i < l; i++) { + ids[i + offset] = levelItems[i] + } + } + let 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 + let levelItems = levels[level] || (levels[level] = []) + let levelGroups = groups[level] || (groups[level] = []) + let sublevel = sublevels[level] || (sublevels[level] = []) + let offset = levelItems.length + + level++ + + // max depth reached - put all items into a first group + // alternatively - if group id overflow - avoid proceeding + if (level > maxDepth || group > MAX_GROUP_ID) { + for (let 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 + } + + + let d2 = diam * .5 + let cx = x + d2, cy = y + d2 + + // distribute points by 4 buckets + let lolo = [], lohi = [], hilo = [], hihi = [] + + for (let i = 1, l = ids.length; i < l; i++) { + let idx = ids[i], + x = points[idx * 2], + y = points[idx * 2 + 1] + x < cx ? (y < cy ? lolo.push(idx) : lohi.push(idx)) : (y < 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 ( ...args ) { + let options + + if (isObj(args[args.length - 1])) { + let 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(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 + + let box = rect( ...args ) + + let [minX, minY, maxX, maxY] = [ + 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) + ] + + let [nminX, nminY, nmaxX, nmaxY] = normalize([minX, minY, maxX, maxY], bounds ) + + let maxLevel = defined(options.level, levels.length) + + // limit maxLevel by px size + if (options.d != null) { + let d + if (typeof options.d === 'number') d = [options.d, options.d] + else if (options.d.length) d = options.d + + maxLevel = Math.min( + Math.max( + Math.ceil(-log2(Math.abs(d[0]) / (bounds[2] - bounds[0]))), + Math.ceil(-log2(Math.abs(d[1]) / (bounds[3] - bounds[1]))) + ), + maxLevel + ) + } + maxLevel = Math.min(maxLevel, levels.length) + + // return levels of details + if (options.lod) { + return lod(nminX, nminY, nmaxX, nmaxY, maxLevel) + } + + + + // do selection ids + let 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 + + let hix = lox + d + let 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 + let levelItems = levels[level] + + if (to === undefined) to = levelItems.length + + for (let i = from; i < to; i++) { + let id = levelItems[i] + + let px = srcPoints[ id * 2 ] + let py = srcPoints[ id * 2 + 1 ] + + if ( px >= minX && px <= maxX && py >= minY && py <= maxY ) {selection.push(id) + } + } + + // for every subsection do select + let offsets = sublevels[ level ] + let off0 = offsets[ from * 4 + 0 ] + let off1 = offsets[ from * 4 + 1 ] + let off2 = offsets[ from * 4 + 2 ] + let off3 = offsets[ from * 4 + 3 ] + let end = nextOffset(offsets, from + 1) + + let d2 = d * .5 + let 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) { + let 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) { + let ranges = [] + + for (let level = 0; level < maxLevel; level++) { + let levelGroups = groups[level] + let from = offsets[level][0] + + let levelGroupStart = group(lox, loy, level) + let levelGroupEnd = group(hix, hiy, level) + + // FIXME: utilize sublevels to speed up search range here + let startOffset = search.ge(levelGroups, levelGroupStart) + let endOffset = search.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) { + let group = 1 + + let cx = .5, cy = .5 + let diam = .5 + + for (let 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 (pts, bounds) { + let [lox, loy, hix, hiy] = bounds + let scaleX = 1.0 / (hix - lox) + let scaleY = 1.0 / (hiy - loy) + let result = new Array(pts.length) + + for (let i = 0, n = pts.length / 2; i < n; i++) { + result[2*i] = clamp((pts[2*i] - lox) * scaleX, 0, 1) + result[2*i+1] = clamp((pts[2*i+1] - loy) * scaleY, 0, 1) + } + + return result +} diff --git a/node_modules/@plotly/point-cluster/research.js b/node_modules/@plotly/point-cluster/research.js new file mode 100644 index 0000000000000000000000000000000000000000..bf88616f6251bd84dc061d9fd01c2e3bdb9d2f16 --- /dev/null +++ b/node_modules/@plotly/point-cluster/research.js @@ -0,0 +1,119 @@ +'use strict'; + + +const t = require('tape'); +const random = require('gauss-random') +const bitsf64 = require('math-float64-from-bits') +// const f64bits = require('math-float64-bits') + + +t('packing 1e6 array', t => { + let y = new Float64Array(1e6) + + console.time(1) + y.subarray(0e5, 1e5) + y.subarray(1e5, 2e5) + y.subarray(2e5, 3e5) + y.subarray(3e5, 4e5) + y.subarray(4e5, 5e5) + y.subarray(5e5, 6e5) + y.subarray(6e5, 7e5) + y.subarray(7e5, 8e5) + y.subarray(8e5, 9e5) + console.timeEnd(1) + + t.end() +}) + +t('float64 packing', t => { + // uint8 (level) + uint32 (id) + float32→normalized uint16 (x) + + let f64 = new Float64Array(1) + let ui32 = new Uint32Array(f64.buffer) + + // view.setUint8(7, parseInt('10000000', 2)) + // view.setUint8(6, parseInt('00000000', 2)) + // ui8[7] = 0xff + // ui16[2] = 0x1000 + ui32[1] = 0x00ff0000 & 0x01 << 16 | 0x0000ffff & 0xffff + console.log(f64[0] /* , f64bits(f64[0]) */) + + let sign = '0' // ignore sign + let exp = '00000000000' // write levels as exponent + let fract = '0000000000000000000000000000000000000000000000000000' + + console.log(bitsf64(sign + exp + fract)) + + // 4 '0100000000010000000000000000000000000000000000000000000000000000' + // -0 '1000000000000000000000000000000000000000000000000000000000000000' + // NaN '0111111111111000000000000000000000000000000000000000000000000000' + // +Inf '0111111111110000000000000000000000000000000000000000000000000000' + // -Inf '1111111111110000000000000000000000000000000000000000000000000000' +}) + +t('sorting comparison', t => { + let N = 1e6 + + let f64 = data(new Float64Array(N)) + console.time(1) + f64.sort() + console.timeEnd(1) + + + let f32 = data(new Float32Array(N)) + console.time(2) + f32.sort() + console.timeEnd(2) + + + let i32 = data(new Uint32Array(N), i => Math.random() * 0xffffffff) + console.time(3) + i32.sort() + console.timeEnd(3) + + + let i32b = data(new Uint32Array(N), i => Math.random() * 0xffffffff) + console.time(4) + i32b.sort((a, b) => a - b) + console.timeEnd(4) + + + let points = data(new Float64Array(N)) + let levels = new Uint32Array(N) + let weights = new Uint32Array(N) + let ids = new Uint32Array(N) + + let level = 0, i = 0 + while (i < N) { + let amt = Math.floor(Math.random() * (N / 16)) + let end = Math.min(i + amt, N) + for (; i < end; i++) { + levels[i] = level + ids[i] = i + } + level++ + } + + const snapSort = require('snap-points-2d/lib/sort') + + console.time('snapsort') + snapSort(levels, points, ids, weights, N) + console.timeEnd('snapsort') +}) + + +function data(N=1e6, f) { + let points + if (N.length) { + points = N + } + else { + points = Array(N) + } + + for (let i = 0; i < points.length; i++) { + points[i] = f ? f(i) : random() + } + + return points +} diff --git a/node_modules/@plotly/point-cluster/test.js b/node_modules/@plotly/point-cluster/test.js new file mode 100644 index 0000000000000000000000000000000000000000..10edbc8c6d17ce175c6abb54904927b731fb273b --- /dev/null +++ b/node_modules/@plotly/point-cluster/test.js @@ -0,0 +1,303 @@ +'use strict' + +const t = require('tape') +const cluster = require('./') +const approxEqual = require('almost-equal') + +t('quad: offsets case', t => { + let points = [.15,.8, .2,.15, .6,.6, .6,.45, .8,.1, .9,.6, .91,.61] + let index = cluster(points, {bounds: [0,0,1,1]}) + + t.deepEqual(index.slice(), [0, 1,3,2, 4,5, 6]) + + t.end() +}) + +t('quad: output container', t => { + let points = [.15,.8, .2,.15, .6,.6, .6,.45, .8,.1, .9,.6, .91,.61] + let arr = [] + let index = cluster(points, {bounds: [0,0,1,1], output: arr}) + + t.deepEqual(arr.slice(), [0, 1,3,2, 4,5, 6]) + t.equal(index, arr) + + t.end() +}) + + +t('quad: max depth', t => { + let points = [] + + for (let i = 0; i < 1e4; i++) { + points.push(0, 0) + } + + let index = cluster(points) + + t.end() +}) + +t('quad: lod method', t => { + let points = [0,0, 1,1, 2,2, 3,3, 4,4, 5,5, 6,6, 7,7] + + let index = cluster(points) + + t.deepEqual(index.range({lod: true, d: 1e-10}), [[0,1], [1,3], [3,6], [6,8]]) + t.deepEqual(index.range({lod: true, level: 400}), [[0,1], [1,3], [3,6], [6,8]]) + t.deepEqual(index.range({lod: true}), [[0,1], [1,3], [3,6], [6,8]]) + t.deepEqual(index.range([1,6], {lod: true}), [[0,1], [1,2], [3,4], [6,7]]) + + t.end() +}) + +t('quad: selection', t => { + let points = [0,0, 1,1, 2,2, 3,3, 4,4, 5,5, 6,6, 7,7] + + let index = cluster(points) + + t.deepEqual(index.range(), [0, 1, 2, 3, 4, 5, 6, 7]) + t.deepEqual(index.range(1,1,6,6), [1, 2, 3, 4, 5, 6]) + t.deepEqual(index.range(2,1,5,6), [2, 3, 4, 5]) + t.deepEqual(index.range(1,2,6,5), [2, 3, 4, 5]) + t.deepEqual(index.range(1,3,5,6), [3, 4, 5]) + + t.deepEqual(index.range(5,6,1,3), [3, 4, 5]) + + t.end() +}) + +t.skip('quad: snap-points-2d cases', t => { + function verifySnap(srcPoints) { + let numPoints = srcPoints.length>>>1 + + let {levels, ids, weights, points, bounds} = cluster(srcPoints) + let npoints = points + + let sx = bounds[0] + let sy = bounds[1] + let sw = bounds[2] - bounds[0] + let sh = bounds[3] - bounds[1] + + for(let i=0; i < numPoints; ++i) { + let id = ids[i] + t.ok(approxEqual(sx + sw*npoints[2*i], srcPoints[2*id], approxEqual.FLT_EPSILON), + 'id perm ok: ' + id + ' ' + srcPoints[2*id] + ' = ' + (sx + sw*npoints[2*i])) + t.ok(approxEqual(sy + sh*npoints[2*i+1], srcPoints[2*id+1], approxEqual.FLT_EPSILON), 'id perm ok: ' + id + ' ' + srcPoints[2*id+1] + ' = ' + (sy + sh*npoints[2*i+1])) + } + + t.equals(levels[levels.length-1].offset, 0, 'last item') + t.equals(levels[0].offset+levels[0].count, numPoints, 'first item') + + for(let i=0; i < levels.length; ++i) { + let s = levels[i] + let r = s.pixelSize + let offs = s.offset + let count = s.count + + if(i > 0) { + t.equals(offs+count, levels[i-1].offset, 'offset for ' + i) + t.ok(r < levels[i-1].pixelSize, 'test scales ok') + } + k_loop: + for(let k=offs-1; k >= 0; --k) { + let ax = npoints[2*k] + let ay = npoints[2*k+1] + + let mind = Infinity + + for(let j=offs; j < offs+count; ++j) { + let x = npoints[2*j] + let y = npoints[2*j+1] + + mind = Math.min(mind, Math.max(Math.abs(ax-x), Math.abs(ay-y))) + } + + t.ok(mind <= 2.0 * r, k + ':' + ax + ',' + ay + ' is not covered - closest pt = ' + mind) + } + } + } + + verifySnap([ + 1, 1, + 2, 2, + 3, 3, + 4, 4, + 5, 5 + ]) + + verifySnap([ + 0,0, + 0,0, + 0,0, + 0,0 + ]) + + verifySnap([ + 1, 2, + 2, 5, + 3, 6, + 4, -1 + ]) + + let pts = new Array(100) + for(let i=0; i < 100; ++i) { + pts[i] = Math.random() + } + verifySnap(pts) + + t.end() +}) + +t.skip('quad: linear case', t => { + let {levels, points, ids, weights} = cluster([1,1,2,2,3,3,4,4,5,5]) + + t.deepEqual(ids, [2, 4, 1, 3, 0]) + t.deepEqual(points, [ 0.5, 0.5, 1, 1, 0.25, 0.25, 0.75, 0.75, 0, 0 ]) + t.deepEqual(weights, [1, 1, 2, 2, 5]) + t.deepEqual(levels, [ + { count: 1, offset: 4, pixelSize: 2 }, + { count: 2, offset: 2, pixelSize: 1 }, + { count: 2, offset: 0, pixelSize: 0.5 } + ]) + + t.end() +}) + +t.skip('quad: no arguments', t => { + let levels = cluster([0,0, 1,1, 2,2]) + + t.end() +}) + +t.skip('quad: larger bounds', t => { + let pos = [0,0, 1,1, 2,2, 3,3, 4,4] + + let {levels} = cluster(pos.slice(), { bounds: [0,0,4,4] }) + t.deepEqual(levels, [ + {pixelSize: 2, offset: 4, count: 1}, + {pixelSize: 1, offset: 2, count: 2}, + {pixelSize: 0.5, offset: 0, count: 2} + ]) + + let index = cluster(pos.slice(), { bounds: [0,0,40,40] }) + levels = index.levels + + t.deepEqual(levels, [ + {pixelSize: 20, offset: 4, count: 1}, + {pixelSize: 10, offset: 3, count: 1}, + {pixelSize: 5, offset: 2, count: 1}, + {pixelSize: 2.5, offset: 1, count: 1}, + {pixelSize: 1.25, offset: 0, count: 1} + ]) + + t.end() +}) + +t.skip('quad: group id', t => { + // TODO + t.end() +}) + +t.skip('kd: creates an index', t => { + var points = [ + 54,1, 97,21, 65,35, 33,54, 95,39, 54,3, 53,54, 84,72, 33,34, 43,15, 52,83, 81,23, 1,61, 38,74, + 11,91, 24,56, 90,31, 25,57, 46,61, 29,69, 49,60, 4,98, 71,15, 60,25, 38,84, 52,38, 94,51, 13,25, + 77,73, 88,87, 6,27, 58,22, 53,28, 27,91, 96,98, 93,14, 22,93, 45,94, 18,28, 35,15, 19,81, 20,81, + 67,53, 43,3, 47,66, 48,34, 46,12, 32,38, 43,12, 39,94, 88,62, 66,14, 84,30, 72,81, 41,92, 26,4, + 6,76, 47,21, 57,70, 71,82, 50,68, 96,18, 40,31, 78,53, 71,90, 32,14, 55,6, 32,88, 62,32, 21,67, + 73,81, 44,64, 29,50, 70,5, 6,22, 68,3, 11,23, 20,42, 21,73, 63,86, 9,40, 99,2, 99,76, 56,77, + 83,6, 21,72, 78,30, 75,53, 41,11, 95,20, 30,38, 96,82, 65,48, 33,18, 87,28, 10,10, 40,34, + 10,20, 47,29, 46,78]; + + var ids = [ + 97,74,95,30,77,38,76,27,80,55,72,90,88,48,43,46,65,39,62,93,9,96,47,8,3,12,15,14,21,41,36,40,69,56,85,78,17,71,44, + 19,18,13,99,24,67,33,37,49,54,57,98,45,23,31,66,68,0,32,5,51,75,73,84,35,81,22,61,89,1,11,86,52,94,16,2,6,25,92, + 42,20,60,58,83,79,64,10,59,53,26,87,4,63,50,7,28,82,70,29,34,91]; + + var coords = [ + 10,20,6,22,10,10,6,27,20,42,18,28,11,23,13,25,9,40,26,4,29,50,30,38,41,11,43,12,43,3,46,12,32,14,35,15,40,31,33,18, + 43,15,40,34,32,38,33,34,33,54,1,61,24,56,11,91,4,98,20,81,22,93,19,81,21,67,6,76,21,72,21,73,25,57,44,64,47,66,29, + 69,46,61,38,74,46,78,38,84,32,88,27,91,45,94,39,94,41,92,47,21,47,29,48,34,60,25,58,22,55,6,62,32,54,1,53,28,54,3, + 66,14,68,3,70,5,83,6,93,14,99,2,71,15,96,18,95,20,97,21,81,23,78,30,84,30,87,28,90,31,65,35,53,54,52,38,65,48,67, + 53,49,60,50,68,57,70,56,77,63,86,71,90,52,83,71,82,72,81,94,51,75,53,95,39,78,53,88,62,84,72,77,73,99,76,73,81,88, + 87,96,98,96,82]; + var index = cluster(points, { nodeSize:10, type: 'kd', sort: false }); + + t.same(index.ids, ids, 'ids are kd-sorted'); + // t.same(index.points, points, 'coords are kd-sorted'); + + t.end(); +}) + +t.skip('kd: range search', t => { + var pts = points + + var index = cluster(pts, {nodeSize:10, type: 'kd'}); + + var result = index.range(20, 30, 50, 70); + + t.same(result, [60,20,45,3,17,71,44,19,18,15,69,90,62,96,47,8,77,72], 'returns ids'); + + for (var i = 0; i < result.length; i++) { + var p = pts[result[i]]; + if (p[0] < 20 || p[0] > 50 || p[1] < 30 || p[1] > 70) + t.fail('result point in range'); + } + t.pass('result points in range'); + + for (i = 0; i < ids.length; i++) { + p = pts[ids[i]]; + if (result.indexOf(ids[i]) < 0 && p[0] >= 20 && p[0] <= 50 && p[1] >= 30 && p[1] <= 70) + t.fail('outside point not in range'); + } + t.pass('outside points not in range'); + + t.end(); +}) + +t.skip('kd: radius search', t => { + var pts = points + + var index = cluster(pts, {nodeSize:10, type: 'kd'}); + + var qp = [50, 50]; + var r = 20; + var r2 = 20 * 20; + + var result = index.within(qp[0], qp[1], r); + + t.same(result, [60,6,25,92,42,20,45,3,71,44,18,96], 'returns ids'); + + for (var i = 0; i < result.length; i++) { + var p = pts[result[i]]; + if (sqDist(p, qp) > r2) t.fail('result point in range'); + } + t.pass('result points in range'); + + for (i = 0; i < ids.length; i++) { + p = pts[ids[i]]; + if (result.indexOf(ids[i]) < 0 && sqDist(p, qp) <= r2) + t.fail('outside point not in range'); + } + t.pass('outside points not in range'); + + t.end(); +}) + +t('performance', t => { + let N = 1e6 + let points = new Float64Array(N) + let ids = new Uint32Array(N) + + for (let i = 0; i < N; i++) { + points[i] = Math.random() + ids[i] = i + } + + console.time(1) + cluster(points, {sort: false}) + console.timeEnd(1) + + t.end() +}) + diff --git a/node_modules/@reduxjs/toolkit/LICENSE b/node_modules/@reduxjs/toolkit/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1daa252487ffa02378254a6446a12b1507913baa --- /dev/null +++ b/node_modules/@reduxjs/toolkit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Mark Erikson + +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. diff --git a/node_modules/@reduxjs/toolkit/README.md b/node_modules/@reduxjs/toolkit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a2514f3e1084bb15ff7efa1a4f387693bebba929 --- /dev/null +++ b/node_modules/@reduxjs/toolkit/README.md @@ -0,0 +1,110 @@ +# Redux Toolkit + +![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/reduxjs/redux-toolkit/tests.yml?style=flat-square) +[![npm version](https://img.shields.io/npm/v/@reduxjs/toolkit.svg?style=flat-square)](https://www.npmjs.com/package/@reduxjs/toolkit) +[![npm downloads](https://img.shields.io/npm/dm/@reduxjs/toolkit.svg?style=flat-square&label=RTK+downloads)](https://www.npmjs.com/package/@reduxjs/toolkit) + +**The official, opinionated, batteries-included toolset for efficient Redux development** + +## Installation + +### Create a React Redux App + +The recommended way to start new apps with React and Redux Toolkit is by using [our official Redux Toolkit + TS template for Vite](https://github.com/reduxjs/redux-templates), or by creating a new Next.js project using [Next's `with-redux` template](https://github.com/vercel/next.js/tree/canary/examples/with-redux). + +Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features. + +```bash +# Vite with our Redux+TS template +# (using the `degit` tool to clone and extract the template) +npx degit reduxjs/redux-templates/packages/vite-template-redux my-app + +# Next.js using the `with-redux` template +npx create-next-app --example with-redux my-app +``` + +We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo: + +- https://github.com/rahsheen/react-native-template-redux-typescript +- https://github.com/rahsheen/expo-template-redux-typescript + +### An Existing App + +Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application: + +```bash +# NPM +npm install @reduxjs/toolkit + +# Yarn +yarn add @reduxjs/toolkit +``` + +The package includes a precompiled ESM build that can be used as a [` or