Leon4gr45 commited on
Commit
8fb9da7
·
verified ·
1 Parent(s): 5782f6c

Upload folder using huggingface_hub (part 21)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. node_modules/mapbox-gl/src/shaders/symbol_text_and_icon.vertex.glsl +116 -0
  2. node_modules/mapbox-gl/src/source/canvas_source.js +238 -0
  3. node_modules/mapbox-gl/src/source/geojson_source.js +370 -0
  4. node_modules/mapbox-gl/src/source/geojson_worker_source.js +366 -0
  5. node_modules/mapbox-gl/src/source/geojson_wrapper.js +94 -0
  6. node_modules/mapbox-gl/src/source/image_source.js +307 -0
  7. node_modules/mapbox-gl/src/source/load_tilejson.js +39 -0
  8. node_modules/mapbox-gl/src/source/pixels_to_tile_units.js +21 -0
  9. node_modules/mapbox-gl/src/source/query_features.js +208 -0
  10. node_modules/mapbox-gl/src/source/raster_dem_tile_source.js +138 -0
  11. node_modules/mapbox-gl/src/source/raster_dem_tile_worker_source.js +62 -0
  12. node_modules/mapbox-gl/src/source/raster_tile_source.js +169 -0
  13. node_modules/mapbox-gl/src/source/rtl_text_plugin.js +143 -0
  14. node_modules/mapbox-gl/src/source/source.js +137 -0
  15. node_modules/mapbox-gl/src/source/source_cache.js +953 -0
  16. node_modules/mapbox-gl/src/source/source_state.js +159 -0
  17. node_modules/mapbox-gl/src/source/tile.js +458 -0
  18. node_modules/mapbox-gl/src/source/tile_bounds.js +38 -0
  19. node_modules/mapbox-gl/src/source/tile_cache.js +212 -0
  20. node_modules/mapbox-gl/src/source/tile_id.js +199 -0
  21. node_modules/mapbox-gl/src/source/vector_tile_source.js +259 -0
  22. node_modules/mapbox-gl/src/source/vector_tile_worker_source.js +216 -0
  23. node_modules/mapbox-gl/src/source/video_source.js +206 -0
  24. node_modules/mapbox-gl/src/source/worker.js +240 -0
  25. node_modules/mapbox-gl/src/source/worker_source.js +107 -0
  26. node_modules/mapbox-gl/src/source/worker_tile.js +224 -0
  27. node_modules/mapbox-gl/src/style-spec/.eslintrc +5 -0
  28. node_modules/mapbox-gl/src/style-spec/CHANGELOG.md +468 -0
  29. node_modules/mapbox-gl/src/style-spec/README.md +59 -0
  30. node_modules/mapbox-gl/src/style-spec/bin/gl-style-composite +9 -0
  31. node_modules/mapbox-gl/src/style-spec/bin/gl-style-format +22 -0
  32. node_modules/mapbox-gl/src/style-spec/bin/gl-style-migrate +9 -0
  33. node_modules/mapbox-gl/src/style-spec/bin/gl-style-validate +50 -0
  34. node_modules/mapbox-gl/src/style-spec/composite.js +50 -0
  35. node_modules/mapbox-gl/src/style-spec/declass.js +42 -0
  36. node_modules/mapbox-gl/src/style-spec/deref.js +52 -0
  37. node_modules/mapbox-gl/src/style-spec/diff.js +393 -0
  38. node_modules/mapbox-gl/src/style-spec/dist/.gitkeep +0 -0
  39. node_modules/mapbox-gl/src/style-spec/dist/index.es.js +0 -0
  40. node_modules/mapbox-gl/src/style-spec/dist/index.es.js.map +0 -0
  41. node_modules/mapbox-gl/src/style-spec/dist/index.js +0 -0
  42. node_modules/mapbox-gl/src/style-spec/dist/index.js.map +0 -0
  43. node_modules/mapbox-gl/src/style-spec/empty.js +29 -0
  44. node_modules/mapbox-gl/src/style-spec/error/parsing_error.js +16 -0
  45. node_modules/mapbox-gl/src/style-spec/error/validation_error.js +18 -0
  46. node_modules/mapbox-gl/src/style-spec/expression/compound_expression.js +162 -0
  47. node_modules/mapbox-gl/src/style-spec/expression/definitions/assertion.js +130 -0
  48. node_modules/mapbox-gl/src/style-spec/expression/definitions/at.js +70 -0
  49. node_modules/mapbox-gl/src/style-spec/expression/definitions/case.js +85 -0
  50. node_modules/mapbox-gl/src/style-spec/expression/definitions/coalesce.js +93 -0
node_modules/mapbox-gl/src/shaders/symbol_text_and_icon.vertex.glsl ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const float PI = 3.141592653589793;
2
+
3
+ attribute vec4 a_pos_offset;
4
+ attribute vec4 a_data;
5
+ attribute vec3 a_projected_pos;
6
+ attribute float a_fade_opacity;
7
+
8
+ // contents of a_size vary based on the type of property value
9
+ // used for {text,icon}-size.
10
+ // For constants, a_size is disabled.
11
+ // For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.
12
+ // For composite functions:
13
+ // [ text-size(lowerZoomStop, feature),
14
+ // text-size(upperZoomStop, feature) ]
15
+ uniform bool u_is_size_zoom_constant;
16
+ uniform bool u_is_size_feature_constant;
17
+ uniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function
18
+ uniform highp float u_size; // used when size is both zoom and feature constant
19
+ uniform mat4 u_matrix;
20
+ uniform mat4 u_label_plane_matrix;
21
+ uniform mat4 u_coord_matrix;
22
+ uniform bool u_is_text;
23
+ uniform bool u_pitch_with_map;
24
+ uniform highp float u_pitch;
25
+ uniform bool u_rotate_symbol;
26
+ uniform highp float u_aspect_ratio;
27
+ uniform highp float u_camera_to_center_distance;
28
+ uniform float u_fade_change;
29
+ uniform vec2 u_texsize;
30
+ uniform vec2 u_texsize_icon;
31
+
32
+ varying vec4 v_data0;
33
+ varying vec4 v_data1;
34
+
35
+ #pragma mapbox: define highp vec4 fill_color
36
+ #pragma mapbox: define highp vec4 halo_color
37
+ #pragma mapbox: define lowp float opacity
38
+ #pragma mapbox: define lowp float halo_width
39
+ #pragma mapbox: define lowp float halo_blur
40
+
41
+ void main() {
42
+ #pragma mapbox: initialize highp vec4 fill_color
43
+ #pragma mapbox: initialize highp vec4 halo_color
44
+ #pragma mapbox: initialize lowp float opacity
45
+ #pragma mapbox: initialize lowp float halo_width
46
+ #pragma mapbox: initialize lowp float halo_blur
47
+
48
+ vec2 a_pos = a_pos_offset.xy;
49
+ vec2 a_offset = a_pos_offset.zw;
50
+
51
+ vec2 a_tex = a_data.xy;
52
+ vec2 a_size = a_data.zw;
53
+
54
+ float a_size_min = floor(a_size[0] * 0.5);
55
+ float is_sdf = a_size[0] - 2.0 * a_size_min;
56
+
57
+ highp float segment_angle = -a_projected_pos[2];
58
+ float size;
59
+
60
+ if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {
61
+ size = mix(a_size_min, a_size[1], u_size_t) / 128.0;
62
+ } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {
63
+ size = a_size_min / 128.0;
64
+ } else {
65
+ size = u_size;
66
+ }
67
+
68
+ vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);
69
+ highp float camera_to_anchor_distance = projectedPoint.w;
70
+ // If the label is pitched with the map, layout is done in pitched space,
71
+ // which makes labels in the distance smaller relative to viewport space.
72
+ // We counteract part of that effect by multiplying by the perspective ratio.
73
+ // If the label isn't pitched with the map, we do layout in viewport space,
74
+ // which makes labels in the distance larger relative to the features around
75
+ // them. We counteract part of that effect by dividing by the perspective ratio.
76
+ highp float distance_ratio = u_pitch_with_map ?
77
+ camera_to_anchor_distance / u_camera_to_center_distance :
78
+ u_camera_to_center_distance / camera_to_anchor_distance;
79
+ highp float perspective_ratio = clamp(
80
+ 0.5 + 0.5 * distance_ratio,
81
+ 0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles
82
+ 4.0);
83
+
84
+ size *= perspective_ratio;
85
+
86
+ float fontScale = size / 24.0;
87
+
88
+ highp float symbol_rotation = 0.0;
89
+ if (u_rotate_symbol) {
90
+ // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units
91
+ // To figure out that angle in projected space, we draw a short horizontal line in tile
92
+ // space, project it, and measure its angle in projected space.
93
+ vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);
94
+
95
+ vec2 a = projectedPoint.xy / projectedPoint.w;
96
+ vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;
97
+
98
+ symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);
99
+ }
100
+
101
+ highp float angle_sin = sin(segment_angle + symbol_rotation);
102
+ highp float angle_cos = cos(segment_angle + symbol_rotation);
103
+ mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);
104
+
105
+ vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);
106
+ gl_Position = u_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0);
107
+ float gamma_scale = gl_Position.w;
108
+
109
+ vec2 fade_opacity = unpack_opacity(a_fade_opacity);
110
+ float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;
111
+ float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));
112
+
113
+ v_data0.xy = a_tex / u_texsize;
114
+ v_data0.zw = a_tex / u_texsize_icon;
115
+ v_data1 = vec4(gamma_scale, size, interpolated_fade_opacity, is_sdf);
116
+ }
node_modules/mapbox-gl/src/source/canvas_source.js ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import ImageSource from './image_source';
4
+
5
+ import window from '../util/window';
6
+ import rasterBoundsAttributes from '../data/raster_bounds_attributes';
7
+ import SegmentVector from '../data/segment';
8
+ import Texture from '../render/texture';
9
+ import {ErrorEvent} from '../util/evented';
10
+ import ValidationError from '../style-spec/error/validation_error';
11
+
12
+ import type Map from '../ui/map';
13
+ import type Dispatcher from '../util/dispatcher';
14
+ import type {Evented} from '../util/evented';
15
+
16
+ export type CanvasSourceSpecification = {|
17
+ "type": "canvas",
18
+ "coordinates": [[number, number], [number, number], [number, number], [number, number]],
19
+ "animate"?: boolean,
20
+ "canvas": string | HTMLCanvasElement
21
+ |};
22
+
23
+ /**
24
+ * Options to add a canvas source type to the map.
25
+ *
26
+ * @typedef {Object} CanvasSourceOptions
27
+ * @property {string} type Source type. Must be `"canvas"`.
28
+ * @property {string|HTMLCanvasElement} canvas Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the `HTMLCanvasElement` itself.
29
+ * @property {Array<Array<number>>} coordinates Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs.
30
+ * @property {boolean} [animate=true] Whether the canvas source is animated. If the canvas is static (i.e. pixels do not need to be re-read on every frame), `animate` should be set to `false` to improve performance.
31
+ */
32
+
33
+ /**
34
+ * A data source containing the contents of an HTML canvas. See {@link CanvasSourceOptions} for detailed documentation of options.
35
+ *
36
+ * @example
37
+ * // add to map
38
+ * map.addSource('some id', {
39
+ * type: 'canvas',
40
+ * canvas: 'idOfMyHTMLCanvas',
41
+ * animate: true,
42
+ * coordinates: [
43
+ * [-76.54, 39.18],
44
+ * [-76.52, 39.18],
45
+ * [-76.52, 39.17],
46
+ * [-76.54, 39.17]
47
+ * ]
48
+ * });
49
+ *
50
+ * // update
51
+ * var mySource = map.getSource('some id');
52
+ * mySource.setCoordinates([
53
+ * [-76.54335737228394, 39.18579907229748],
54
+ * [-76.52803659439087, 39.1838364847587],
55
+ * [-76.5295386314392, 39.17683392507606],
56
+ * [-76.54520273208618, 39.17876344106642]
57
+ * ]);
58
+ *
59
+ * map.removeSource('some id'); // remove
60
+ */
61
+ class CanvasSource extends ImageSource {
62
+ options: CanvasSourceSpecification;
63
+ animate: boolean;
64
+ canvas: HTMLCanvasElement;
65
+ width: number;
66
+ height: number;
67
+ play: () => void;
68
+ pause: () => void;
69
+ _playing: boolean;
70
+
71
+ /**
72
+ * @private
73
+ */
74
+ constructor(id: string, options: CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {
75
+ super(id, options, dispatcher, eventedParent);
76
+
77
+ // We build in some validation here, since canvas sources aren't included in the style spec:
78
+ if (!options.coordinates) {
79
+ this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property "coordinates"')));
80
+ } else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 ||
81
+ options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) {
82
+ this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs')));
83
+ }
84
+
85
+ if (options.animate && typeof options.animate !== 'boolean') {
86
+ this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'optional "animate" property must be a boolean value')));
87
+ }
88
+
89
+ if (!options.canvas) {
90
+ this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property "canvas"')));
91
+ } else if (typeof options.canvas !== 'string' && !(options.canvas instanceof window.HTMLCanvasElement)) {
92
+ this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance')));
93
+ }
94
+
95
+ this.options = options;
96
+ this.animate = options.animate !== undefined ? options.animate : true;
97
+ }
98
+
99
+ /**
100
+ * Enables animation. The image will be copied from the canvas to the map on each frame.
101
+ * @method play
102
+ * @instance
103
+ * @memberof CanvasSource
104
+ */
105
+
106
+ /**
107
+ * Disables animation. The map will display a static copy of the canvas image.
108
+ * @method pause
109
+ * @instance
110
+ * @memberof CanvasSource
111
+ */
112
+
113
+ load() {
114
+ this._loaded = true;
115
+ if (!this.canvas) {
116
+ this.canvas = (this.options.canvas instanceof window.HTMLCanvasElement) ?
117
+ this.options.canvas :
118
+ window.document.getElementById(this.options.canvas);
119
+ }
120
+ this.width = this.canvas.width;
121
+ this.height = this.canvas.height;
122
+
123
+ if (this._hasInvalidDimensions()) {
124
+ this.fire(new ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.')));
125
+ return;
126
+ }
127
+
128
+ this.play = function() {
129
+ this._playing = true;
130
+ this.map.triggerRepaint();
131
+ };
132
+
133
+ this.pause = function() {
134
+ if (this._playing) {
135
+ this.prepare();
136
+ this._playing = false;
137
+ }
138
+ };
139
+
140
+ this._finishLoading();
141
+ }
142
+
143
+ /**
144
+ * Returns the HTML `canvas` element.
145
+ *
146
+ * @returns {HTMLCanvasElement} The HTML `canvas` element.
147
+ */
148
+ getCanvas() {
149
+ return this.canvas;
150
+ }
151
+
152
+ onAdd(map: Map) {
153
+ this.map = map;
154
+ this.load();
155
+ if (this.canvas) {
156
+ if (this.animate) this.play();
157
+ }
158
+ }
159
+
160
+ onRemove() {
161
+ this.pause();
162
+ }
163
+
164
+ /**
165
+ * Sets the canvas's coordinates and re-renders the map.
166
+ *
167
+ * @method setCoordinates
168
+ * @instance
169
+ * @memberof CanvasSource
170
+ * @param {Array<Array<number>>} coordinates Four geographical coordinates,
171
+ * represented as arrays of longitude and latitude numbers, which define the corners of the canvas.
172
+ * The coordinates start at the top left corner of the canvas and proceed in clockwise order.
173
+ * They do not have to represent a rectangle.
174
+ * @returns {CanvasSource} this
175
+ */
176
+ // setCoordinates inherited from ImageSource
177
+
178
+ prepare() {
179
+ let resize = false;
180
+ if (this.canvas.width !== this.width) {
181
+ this.width = this.canvas.width;
182
+ resize = true;
183
+ }
184
+ if (this.canvas.height !== this.height) {
185
+ this.height = this.canvas.height;
186
+ resize = true;
187
+ }
188
+
189
+ if (this._hasInvalidDimensions()) return;
190
+
191
+ if (Object.keys(this.tiles).length === 0) return; // not enough data for current position
192
+
193
+ const context = this.map.painter.context;
194
+ const gl = context.gl;
195
+
196
+ if (!this.boundsBuffer) {
197
+ this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);
198
+ }
199
+
200
+ if (!this.boundsSegments) {
201
+ this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
202
+ }
203
+
204
+ if (!this.texture) {
205
+ this.texture = new Texture(context, this.canvas, gl.RGBA, {premultiply: true});
206
+ } else if (resize || this._playing) {
207
+ this.texture.update(this.canvas, {premultiply: true});
208
+ }
209
+
210
+ for (const w in this.tiles) {
211
+ const tile = this.tiles[w];
212
+ if (tile.state !== 'loaded') {
213
+ tile.state = 'loaded';
214
+ tile.texture = this.texture;
215
+ }
216
+ }
217
+ }
218
+
219
+ serialize(): Object {
220
+ return {
221
+ type: 'canvas',
222
+ coordinates: this.coordinates
223
+ };
224
+ }
225
+
226
+ hasTransition() {
227
+ return this._playing;
228
+ }
229
+
230
+ _hasInvalidDimensions() {
231
+ for (const x of [this.canvas.width, this.canvas.height]) {
232
+ if (isNaN(x) || x <= 0) return true;
233
+ }
234
+ return false;
235
+ }
236
+ }
237
+
238
+ export default CanvasSource;
node_modules/mapbox-gl/src/source/geojson_source.js ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {Event, ErrorEvent, Evented} from '../util/evented';
4
+
5
+ import {extend} from '../util/util';
6
+ import EXTENT from '../data/extent';
7
+ import {ResourceType} from '../util/ajax';
8
+ import browser from '../util/browser';
9
+
10
+ import type {Source} from './source';
11
+ import type Map from '../ui/map';
12
+ import type Dispatcher from '../util/dispatcher';
13
+ import type Tile from './tile';
14
+ import type Actor from '../util/actor';
15
+ import type {Callback} from '../types/callback';
16
+ import type {GeoJSON, GeoJSONFeature} from '@mapbox/geojson-types';
17
+ import type {GeoJSONSourceSpecification, PromoteIdSpecification} from '../style-spec/types';
18
+
19
+ /**
20
+ * A source containing GeoJSON.
21
+ * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson) for detailed documentation of options.)
22
+ *
23
+ * @example
24
+ * map.addSource('some id', {
25
+ * type: 'geojson',
26
+ * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'
27
+ * });
28
+ *
29
+ * @example
30
+ * map.addSource('some id', {
31
+ * type: 'geojson',
32
+ * data: {
33
+ * "type": "FeatureCollection",
34
+ * "features": [{
35
+ * "type": "Feature",
36
+ * "properties": {},
37
+ * "geometry": {
38
+ * "type": "Point",
39
+ * "coordinates": [
40
+ * -76.53063297271729,
41
+ * 39.18174077994108
42
+ * ]
43
+ * }
44
+ * }]
45
+ * }
46
+ * });
47
+ *
48
+ * @example
49
+ * map.getSource('some id').setData({
50
+ * "type": "FeatureCollection",
51
+ * "features": [{
52
+ * "type": "Feature",
53
+ * "properties": { "name": "Null Island" },
54
+ * "geometry": {
55
+ * "type": "Point",
56
+ * "coordinates": [ 0, 0 ]
57
+ * }
58
+ * }]
59
+ * });
60
+ * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)
61
+ * @see [Add a GeoJSON line](https://www.mapbox.com/mapbox-gl-js/example/geojson-line/)
62
+ * @see [Create a heatmap from points](https://www.mapbox.com/mapbox-gl-js/example/heatmap/)
63
+ * @see [Create and style clusters](https://www.mapbox.com/mapbox-gl-js/example/cluster/)
64
+ */
65
+ class GeoJSONSource extends Evented implements Source {
66
+ type: 'geojson';
67
+ id: string;
68
+ minzoom: number;
69
+ maxzoom: number;
70
+ tileSize: number;
71
+ attribution: string;
72
+ promoteId: ?PromoteIdSpecification;
73
+
74
+ isTileClipped: boolean;
75
+ reparseOverscaled: boolean;
76
+ _data: GeoJSON | string;
77
+ _options: any;
78
+ workerOptions: any;
79
+ map: Map;
80
+ actor: Actor;
81
+ _loaded: boolean;
82
+ _collectResourceTiming: boolean;
83
+ _resourceTiming: Array<PerformanceResourceTiming>;
84
+ _removed: boolean;
85
+
86
+ /**
87
+ * @private
88
+ */
89
+ constructor(id: string, options: GeoJSONSourceSpecification & {workerOptions?: any, collectResourceTiming: boolean}, dispatcher: Dispatcher, eventedParent: Evented) {
90
+ super();
91
+
92
+ this.id = id;
93
+
94
+ // `type` is a property rather than a constant to make it easy for 3rd
95
+ // parties to use GeoJSONSource to build their own source types.
96
+ this.type = 'geojson';
97
+
98
+ this.minzoom = 0;
99
+ this.maxzoom = 18;
100
+ this.tileSize = 512;
101
+ this.isTileClipped = true;
102
+ this.reparseOverscaled = true;
103
+ this._removed = false;
104
+ this._loaded = false;
105
+
106
+ this.actor = dispatcher.getActor();
107
+ this.setEventedParent(eventedParent);
108
+
109
+ this._data = (options.data: any);
110
+ this._options = extend({}, options);
111
+
112
+ this._collectResourceTiming = options.collectResourceTiming;
113
+ this._resourceTiming = [];
114
+
115
+ if (options.maxzoom !== undefined) this.maxzoom = options.maxzoom;
116
+ if (options.type) this.type = options.type;
117
+ if (options.attribution) this.attribution = options.attribution;
118
+ this.promoteId = options.promoteId;
119
+
120
+ const scale = EXTENT / this.tileSize;
121
+
122
+ // sent to the worker, along with `url: ...` or `data: literal geojson`,
123
+ // so that it can load/parse/index the geojson data
124
+ // extending with `options.workerOptions` helps to make it easy for
125
+ // third-party sources to hack/reuse GeoJSONSource.
126
+ this.workerOptions = extend({
127
+ source: this.id,
128
+ cluster: options.cluster || false,
129
+ geojsonVtOptions: {
130
+ buffer: (options.buffer !== undefined ? options.buffer : 128) * scale,
131
+ tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale,
132
+ extent: EXTENT,
133
+ maxZoom: this.maxzoom,
134
+ lineMetrics: options.lineMetrics || false,
135
+ generateId: options.generateId || false
136
+ },
137
+ superclusterOptions: {
138
+ maxZoom: options.clusterMaxZoom !== undefined ?
139
+ Math.min(options.clusterMaxZoom, this.maxzoom - 1) :
140
+ (this.maxzoom - 1),
141
+ minPoints: Math.max(2, options.clusterMinPoints || 2),
142
+ extent: EXTENT,
143
+ radius: (options.clusterRadius || 50) * scale,
144
+ log: false,
145
+ generateId: options.generateId || false
146
+ },
147
+ clusterProperties: options.clusterProperties,
148
+ filter: options.filter
149
+ }, options.workerOptions);
150
+ }
151
+
152
+ load() {
153
+ this.fire(new Event('dataloading', {dataType: 'source'}));
154
+ this._updateWorkerData((err) => {
155
+ if (err) {
156
+ this.fire(new ErrorEvent(err));
157
+ return;
158
+ }
159
+
160
+ const data: Object = {dataType: 'source', sourceDataType: 'metadata'};
161
+ if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) {
162
+ data.resourceTiming = this._resourceTiming;
163
+ this._resourceTiming = [];
164
+ }
165
+
166
+ // although GeoJSON sources contain no metadata, we fire this event to let the SourceCache
167
+ // know its ok to start requesting tiles.
168
+ this.fire(new Event('data', data));
169
+ });
170
+ }
171
+
172
+ onAdd(map: Map) {
173
+ this.map = map;
174
+ this.load();
175
+ }
176
+
177
+ /**
178
+ * Sets the GeoJSON data and re-renders the map.
179
+ *
180
+ * @param {Object|string} data A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.
181
+ * @returns {GeoJSONSource} this
182
+ */
183
+ setData(data: GeoJSON | string) {
184
+ this._data = data;
185
+ this.fire(new Event('dataloading', {dataType: 'source'}));
186
+ this._updateWorkerData((err) => {
187
+ if (err) {
188
+ this.fire(new ErrorEvent(err));
189
+ return;
190
+ }
191
+
192
+ const data: Object = {dataType: 'source', sourceDataType: 'content'};
193
+ if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) {
194
+ data.resourceTiming = this._resourceTiming;
195
+ this._resourceTiming = [];
196
+ }
197
+ this.fire(new Event('data', data));
198
+ });
199
+
200
+ return this;
201
+ }
202
+
203
+ /**
204
+ * For clustered sources, fetches the zoom at which the given cluster expands.
205
+ *
206
+ * @param clusterId The value of the cluster's `cluster_id` property.
207
+ * @param callback A callback to be called when the zoom value is retrieved (`(error, zoom) => { ... }`).
208
+ * @returns {GeoJSONSource} this
209
+ */
210
+ getClusterExpansionZoom(clusterId: number, callback: Callback<number>) {
211
+ this.actor.send('geojson.getClusterExpansionZoom', {clusterId, source: this.id}, callback);
212
+ return this;
213
+ }
214
+
215
+ /**
216
+ * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).
217
+ *
218
+ * @param clusterId The value of the cluster's `cluster_id` property.
219
+ * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).
220
+ * @returns {GeoJSONSource} this
221
+ */
222
+ getClusterChildren(clusterId: number, callback: Callback<Array<GeoJSONFeature>>) {
223
+ this.actor.send('geojson.getClusterChildren', {clusterId, source: this.id}, callback);
224
+ return this;
225
+ }
226
+
227
+ /**
228
+ * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).
229
+ *
230
+ * @param clusterId The value of the cluster's `cluster_id` property.
231
+ * @param limit The maximum number of features to return.
232
+ * @param offset The number of features to skip (e.g. for pagination).
233
+ * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).
234
+ * @returns {GeoJSONSource} this
235
+ * @example
236
+ * // Retrieve cluster leaves on click
237
+ * map.on('click', 'clusters', function(e) {
238
+ * var features = map.queryRenderedFeatures(e.point, {
239
+ * layers: ['clusters']
240
+ * });
241
+ *
242
+ * var clusterId = features[0].properties.cluster_id;
243
+ * var pointCount = features[0].properties.point_count;
244
+ * var clusterSource = map.getSource('clusters');
245
+ *
246
+ * clusterSource.getClusterLeaves(clusterId, pointCount, 0, function(error, features) {
247
+ * // Print cluster leaves in the console
248
+ * console.log('Cluster leaves:', error, features);
249
+ * })
250
+ * });
251
+ */
252
+ getClusterLeaves(clusterId: number, limit: number, offset: number, callback: Callback<Array<GeoJSONFeature>>) {
253
+ this.actor.send('geojson.getClusterLeaves', {
254
+ source: this.id,
255
+ clusterId,
256
+ limit,
257
+ offset
258
+ }, callback);
259
+ return this;
260
+ }
261
+
262
+ /*
263
+ * Responsible for invoking WorkerSource's geojson.loadData target, which
264
+ * handles loading the geojson data and preparing to serve it up as tiles,
265
+ * using geojson-vt or supercluster as appropriate.
266
+ */
267
+ _updateWorkerData(callback: Callback<void>) {
268
+ this._loaded = false;
269
+ const options = extend({}, this.workerOptions);
270
+ const data = this._data;
271
+ if (typeof data === 'string') {
272
+ options.request = this.map._requestManager.transformRequest(browser.resolveURL(data), ResourceType.Source);
273
+ options.request.collectResourceTiming = this._collectResourceTiming;
274
+ } else {
275
+ options.data = JSON.stringify(data);
276
+ }
277
+
278
+ // target {this.type}.loadData rather than literally geojson.loadData,
279
+ // so that other geojson-like source types can easily reuse this
280
+ // implementation
281
+ this.actor.send(`${this.type}.loadData`, options, (err, result) => {
282
+ if (this._removed || (result && result.abandoned)) {
283
+ return;
284
+ }
285
+
286
+ this._loaded = true;
287
+
288
+ if (result && result.resourceTiming && result.resourceTiming[this.id])
289
+ this._resourceTiming = result.resourceTiming[this.id].slice(0);
290
+ // Any `loadData` calls that piled up while we were processing
291
+ // this one will get coalesced into a single call when this
292
+ // 'coalesce' message is processed.
293
+ // We would self-send from the worker if we had access to its
294
+ // message queue. Waiting instead for the 'coalesce' to round-trip
295
+ // through the foreground just means we're throttling the worker
296
+ // to run at a little less than full-throttle.
297
+ this.actor.send(`${this.type}.coalesce`, {source: options.source}, null);
298
+ callback(err);
299
+ });
300
+ }
301
+
302
+ loaded(): boolean {
303
+ return this._loaded;
304
+ }
305
+
306
+ loadTile(tile: Tile, callback: Callback<void>) {
307
+ const message = !tile.actor ? 'loadTile' : 'reloadTile';
308
+ tile.actor = this.actor;
309
+ const params = {
310
+ type: this.type,
311
+ uid: tile.uid,
312
+ tileID: tile.tileID,
313
+ zoom: tile.tileID.overscaledZ,
314
+ maxZoom: this.maxzoom,
315
+ tileSize: this.tileSize,
316
+ source: this.id,
317
+ pixelRatio: browser.devicePixelRatio,
318
+ showCollisionBoxes: this.map.showCollisionBoxes,
319
+ promoteId: this.promoteId
320
+ };
321
+
322
+ tile.request = this.actor.send(message, params, (err, data) => {
323
+ delete tile.request;
324
+ tile.unloadVectorData();
325
+
326
+ if (tile.aborted) {
327
+ return callback(null);
328
+ }
329
+
330
+ if (err) {
331
+ return callback(err);
332
+ }
333
+
334
+ tile.loadVectorData(data, this.map.painter, message === 'reloadTile');
335
+
336
+ return callback(null);
337
+ });
338
+ }
339
+
340
+ abortTile(tile: Tile) {
341
+ if (tile.request) {
342
+ tile.request.cancel();
343
+ delete tile.request;
344
+ }
345
+ tile.aborted = true;
346
+ }
347
+
348
+ unloadTile(tile: Tile) {
349
+ tile.unloadVectorData();
350
+ this.actor.send('removeTile', {uid: tile.uid, type: this.type, source: this.id});
351
+ }
352
+
353
+ onRemove() {
354
+ this._removed = true;
355
+ this.actor.send('removeSource', {type: this.type, source: this.id});
356
+ }
357
+
358
+ serialize() {
359
+ return extend({}, this._options, {
360
+ type: this.type,
361
+ data: this._data
362
+ });
363
+ }
364
+
365
+ hasTransition() {
366
+ return false;
367
+ }
368
+ }
369
+
370
+ export default GeoJSONSource;
node_modules/mapbox-gl/src/source/geojson_worker_source.js ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {getJSON} from '../util/ajax';
4
+
5
+ import {RequestPerformance} from '../util/performance';
6
+ import rewind from '@mapbox/geojson-rewind';
7
+ import GeoJSONWrapper from './geojson_wrapper';
8
+ import vtpbf from 'vt-pbf';
9
+ import Supercluster from 'supercluster';
10
+ import geojsonvt from 'geojson-vt';
11
+ import assert from 'assert';
12
+ import VectorTileWorkerSource from './vector_tile_worker_source';
13
+ import {createExpression} from '../style-spec/expression';
14
+
15
+ import type {
16
+ WorkerTileParameters,
17
+ WorkerTileCallback,
18
+ } from '../source/worker_source';
19
+
20
+ import type Actor from '../util/actor';
21
+ import type StyleLayerIndex from '../style/style_layer_index';
22
+
23
+ import type {LoadVectorDataCallback} from './vector_tile_worker_source';
24
+ import type {RequestParameters, ResponseCallback} from '../util/ajax';
25
+ import type {Callback} from '../types/callback';
26
+ import type {GeoJSONFeature} from '@mapbox/geojson-types';
27
+
28
+ export type LoadGeoJSONParameters = {
29
+ request?: RequestParameters,
30
+ data?: string,
31
+ source: string,
32
+ cluster: boolean,
33
+ superclusterOptions?: Object,
34
+ geojsonVtOptions?: Object,
35
+ clusterProperties?: Object,
36
+ filter?: Array<mixed>
37
+ };
38
+
39
+ export type LoadGeoJSON = (params: LoadGeoJSONParameters, callback: ResponseCallback<Object>) => void;
40
+
41
+ export interface GeoJSONIndex {
42
+ getTile(z: number, x: number, y: number): Object;
43
+
44
+ // supercluster methods
45
+ getClusterExpansionZoom(clusterId: number): number;
46
+ getChildren(clusterId: number): Array<GeoJSONFeature>;
47
+ getLeaves(clusterId: number, limit: number, offset: number): Array<GeoJSONFeature>;
48
+ }
49
+
50
+ function loadGeoJSONTile(params: WorkerTileParameters, callback: LoadVectorDataCallback) {
51
+ const canonical = params.tileID.canonical;
52
+
53
+ if (!this._geoJSONIndex) {
54
+ return callback(null, null); // we couldn't load the file
55
+ }
56
+
57
+ const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y);
58
+ if (!geoJSONTile) {
59
+ return callback(null, null); // nothing in the given tile
60
+ }
61
+
62
+ const geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features);
63
+
64
+ // Encode the geojson-vt tile into binary vector tile form. This
65
+ // is a convenience that allows `FeatureIndex` to operate the same way
66
+ // across `VectorTileSource` and `GeoJSONSource` data.
67
+ let pbf = vtpbf(geojsonWrapper);
68
+ if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {
69
+ // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35)
70
+ pbf = new Uint8Array(pbf);
71
+ }
72
+
73
+ callback(null, {
74
+ vectorTile: geojsonWrapper,
75
+ rawData: pbf.buffer
76
+ });
77
+ }
78
+
79
+ export type SourceState =
80
+ | 'Idle' // Source empty or data loaded
81
+ | 'Coalescing' // Data finished loading, but discard 'loadData' messages until receiving 'coalesced'
82
+ | 'NeedsLoadData'; // 'loadData' received while coalescing, trigger one more 'loadData' on receiving 'coalesced'
83
+
84
+ /**
85
+ * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}.
86
+ * This class is designed to be easily reused to support custom source types
87
+ * for data formats that can be parsed/converted into an in-memory GeoJSON
88
+ * representation. To do so, create it with
89
+ * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`.
90
+ * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson).
91
+ *
92
+ * @private
93
+ */
94
+ class GeoJSONWorkerSource extends VectorTileWorkerSource {
95
+ loadGeoJSON: LoadGeoJSON;
96
+ _state: SourceState;
97
+ _pendingCallback: Callback<{
98
+ resourceTiming?: {[_: string]: Array<PerformanceResourceTiming>},
99
+ abandoned?: boolean }>;
100
+ _pendingLoadDataParams: LoadGeoJSONParameters;
101
+ _geoJSONIndex: GeoJSONIndex
102
+
103
+ /**
104
+ * @param [loadGeoJSON] Optional method for custom loading/parsing of
105
+ * GeoJSON based on parameters passed from the main-thread Source.
106
+ * See {@link GeoJSONWorkerSource#loadGeoJSON}.
107
+ * @private
108
+ */
109
+ constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array<string>, loadGeoJSON: ?LoadGeoJSON) {
110
+ super(actor, layerIndex, availableImages, loadGeoJSONTile);
111
+ if (loadGeoJSON) {
112
+ this.loadGeoJSON = loadGeoJSON;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Fetches (if appropriate), parses, and index geojson data into tiles. This
118
+ * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile}
119
+ * can correctly serve up tiles.
120
+ *
121
+ * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching/parsing,
122
+ * expecting `callback(error, data)` to be called with either an error or a
123
+ * parsed GeoJSON object.
124
+ *
125
+ * When `loadData` requests come in faster than they can be processed,
126
+ * they are coalesced into a single request using the latest data.
127
+ * See {@link GeoJSONWorkerSource#coalesce}
128
+ *
129
+ * @param params
130
+ * @param callback
131
+ * @private
132
+ */
133
+ loadData(params: LoadGeoJSONParameters, callback: Callback<{
134
+ resourceTiming?: {[_: string]: Array<PerformanceResourceTiming>},
135
+ abandoned?: boolean }>) {
136
+ if (this._pendingCallback) {
137
+ // Tell the foreground the previous call has been abandoned
138
+ this._pendingCallback(null, {abandoned: true});
139
+ }
140
+ this._pendingCallback = callback;
141
+ this._pendingLoadDataParams = params;
142
+
143
+ if (this._state &&
144
+ this._state !== 'Idle') {
145
+ this._state = 'NeedsLoadData';
146
+ } else {
147
+ this._state = 'Coalescing';
148
+ this._loadData();
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Internal implementation: called directly by `loadData`
154
+ * or by `coalesce` using stored parameters.
155
+ */
156
+ _loadData() {
157
+ if (!this._pendingCallback || !this._pendingLoadDataParams) {
158
+ assert(false);
159
+ return;
160
+ }
161
+ const callback = this._pendingCallback;
162
+ const params = this._pendingLoadDataParams;
163
+ delete this._pendingCallback;
164
+ delete this._pendingLoadDataParams;
165
+
166
+ const perf = (params && params.request && params.request.collectResourceTiming) ?
167
+ new RequestPerformance(params.request) : false;
168
+
169
+ this.loadGeoJSON(params, (err: ?Error, data: ?Object) => {
170
+ if (err || !data) {
171
+ return callback(err);
172
+ } else if (typeof data !== 'object') {
173
+ return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));
174
+ } else {
175
+ rewind(data, true);
176
+
177
+ try {
178
+ if (params.filter) {
179
+ const compiled = createExpression(params.filter, {type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false});
180
+ if (compiled.result === 'error')
181
+ throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));
182
+
183
+ const features = data.features.filter(feature => compiled.value.evaluate({zoom: 0}, feature));
184
+ data = {type: 'FeatureCollection', features};
185
+ }
186
+
187
+ this._geoJSONIndex = params.cluster ?
188
+ new Supercluster(getSuperclusterOptions(params)).load(data.features) :
189
+ geojsonvt(data, params.geojsonVtOptions);
190
+ } catch (err) {
191
+ return callback(err);
192
+ }
193
+
194
+ this.loaded = {};
195
+
196
+ const result = {};
197
+ if (perf) {
198
+ const resourceTimingData = perf.finish();
199
+ // it's necessary to eval the result of getEntriesByName() here via parse/stringify
200
+ // late evaluation in the main thread causes TypeError: illegal invocation
201
+ if (resourceTimingData) {
202
+ result.resourceTiming = {};
203
+ result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData));
204
+ }
205
+ }
206
+ callback(null, result);
207
+ }
208
+ });
209
+ }
210
+
211
+ /**
212
+ * While processing `loadData`, we coalesce all further
213
+ * `loadData` messages into a single call to _loadData
214
+ * that will happen once we've finished processing the
215
+ * first message. {@link GeoJSONSource#_updateWorkerData}
216
+ * is responsible for sending us the `coalesce` message
217
+ * at the time it receives a response from `loadData`
218
+ *
219
+ * State: Idle
220
+ * ↑ |
221
+ * 'coalesce' 'loadData'
222
+ * | (triggers load)
223
+ * | ↓
224
+ * State: Coalescing
225
+ * ↑ |
226
+ * (triggers load) |
227
+ * 'coalesce' 'loadData'
228
+ * | ↓
229
+ * State: NeedsLoadData
230
+ */
231
+ coalesce() {
232
+ if (this._state === 'Coalescing') {
233
+ this._state = 'Idle';
234
+ } else if (this._state === 'NeedsLoadData') {
235
+ this._state = 'Coalescing';
236
+ this._loadData();
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Implements {@link WorkerSource#reloadTile}.
242
+ *
243
+ * If the tile is loaded, uses the implementation in VectorTileWorkerSource.
244
+ * Otherwise, such as after a setData() call, we load the tile fresh.
245
+ *
246
+ * @param params
247
+ * @param params.uid The UID for this tile.
248
+ * @private
249
+ */
250
+ reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {
251
+ const loaded = this.loaded,
252
+ uid = params.uid;
253
+
254
+ if (loaded && loaded[uid]) {
255
+ return super.reloadTile(params, callback);
256
+ } else {
257
+ return this.loadTile(params, callback);
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Fetch and parse GeoJSON according to the given params. Calls `callback`
263
+ * with `(err, data)`, where `data` is a parsed GeoJSON object.
264
+ *
265
+ * GeoJSON is loaded and parsed from `params.url` if it exists, or else
266
+ * expected as a literal (string or object) `params.data`.
267
+ *
268
+ * @param params
269
+ * @param [params.url] A URL to the remote GeoJSON data.
270
+ * @param [params.data] Literal GeoJSON data. Must be provided if `params.url` is not.
271
+ * @private
272
+ */
273
+ loadGeoJSON(params: LoadGeoJSONParameters, callback: ResponseCallback<Object>) {
274
+ // Because of same origin issues, urls must either include an explicit
275
+ // origin or absolute path.
276
+ // ie: /foo/bar.json or http://example.com/bar.json
277
+ // but not ../foo/bar.json
278
+ if (params.request) {
279
+ getJSON(params.request, callback);
280
+ } else if (typeof params.data === 'string') {
281
+ try {
282
+ return callback(null, JSON.parse(params.data));
283
+ } catch (e) {
284
+ return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));
285
+ }
286
+ } else {
287
+ return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));
288
+ }
289
+ }
290
+
291
+ removeSource(params: {source: string}, callback: Callback<mixed>) {
292
+ if (this._pendingCallback) {
293
+ // Don't leak callbacks
294
+ this._pendingCallback(null, {abandoned: true});
295
+ }
296
+ callback();
297
+ }
298
+
299
+ getClusterExpansionZoom(params: {clusterId: number}, callback: Callback<number>) {
300
+ try {
301
+ callback(null, this._geoJSONIndex.getClusterExpansionZoom(params.clusterId));
302
+ } catch (e) {
303
+ callback(e);
304
+ }
305
+ }
306
+
307
+ getClusterChildren(params: {clusterId: number}, callback: Callback<Array<GeoJSONFeature>>) {
308
+ try {
309
+ callback(null, this._geoJSONIndex.getChildren(params.clusterId));
310
+ } catch (e) {
311
+ callback(e);
312
+ }
313
+ }
314
+
315
+ getClusterLeaves(params: {clusterId: number, limit: number, offset: number}, callback: Callback<Array<GeoJSONFeature>>) {
316
+ try {
317
+ callback(null, this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset));
318
+ } catch (e) {
319
+ callback(e);
320
+ }
321
+ }
322
+ }
323
+
324
+ function getSuperclusterOptions({superclusterOptions, clusterProperties}) {
325
+ if (!clusterProperties || !superclusterOptions) return superclusterOptions;
326
+
327
+ const mapExpressions = {};
328
+ const reduceExpressions = {};
329
+ const globals = {accumulated: null, zoom: 0};
330
+ const feature = {properties: null};
331
+ const propertyNames = Object.keys(clusterProperties);
332
+
333
+ for (const key of propertyNames) {
334
+ const [operator, mapExpression] = clusterProperties[key];
335
+
336
+ const mapExpressionParsed = createExpression(mapExpression);
337
+ const reduceExpressionParsed = createExpression(
338
+ typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator);
339
+
340
+ assert(mapExpressionParsed.result === 'success');
341
+ assert(reduceExpressionParsed.result === 'success');
342
+
343
+ mapExpressions[key] = mapExpressionParsed.value;
344
+ reduceExpressions[key] = reduceExpressionParsed.value;
345
+ }
346
+
347
+ superclusterOptions.map = (pointProperties) => {
348
+ feature.properties = pointProperties;
349
+ const properties = {};
350
+ for (const key of propertyNames) {
351
+ properties[key] = mapExpressions[key].evaluate(globals, feature);
352
+ }
353
+ return properties;
354
+ };
355
+ superclusterOptions.reduce = (accumulated, clusterProperties) => {
356
+ feature.properties = clusterProperties;
357
+ for (const key of propertyNames) {
358
+ globals.accumulated = accumulated[key];
359
+ accumulated[key] = reduceExpressions[key].evaluate(globals, feature);
360
+ }
361
+ };
362
+
363
+ return superclusterOptions;
364
+ }
365
+
366
+ export default GeoJSONWorkerSource;
node_modules/mapbox-gl/src/source/geojson_wrapper.js ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import Point from '@mapbox/point-geometry';
4
+
5
+ import mvt from '@mapbox/vector-tile';
6
+ const toGeoJSON = mvt.VectorTileFeature.prototype.toGeoJSON;
7
+ import EXTENT from '../data/extent';
8
+
9
+ // The feature type used by geojson-vt and supercluster. Should be extracted to
10
+ // global type and used in module definitions for those two modules.
11
+ type Feature = {
12
+ type: 1,
13
+ id: mixed,
14
+ tags: {[_: string]: string | number | boolean},
15
+ geometry: Array<[number, number]>,
16
+ } | {
17
+ type: 2 | 3,
18
+ id: mixed,
19
+ tags: {[_: string]: string | number | boolean},
20
+ geometry: Array<Array<[number, number]>>,
21
+ }
22
+
23
+ class FeatureWrapper implements VectorTileFeature {
24
+ _feature: Feature;
25
+
26
+ extent: number;
27
+ type: 1 | 2 | 3;
28
+ id: number;
29
+ properties: {[_: string]: string | number | boolean};
30
+
31
+ constructor(feature: Feature) {
32
+ this._feature = feature;
33
+
34
+ this.extent = EXTENT;
35
+ this.type = feature.type;
36
+ this.properties = feature.tags;
37
+
38
+ // If the feature has a top-level `id` property, copy it over, but only
39
+ // if it can be coerced to an integer, because this wrapper is used for
40
+ // serializing geojson feature data into vector tile PBF data, and the
41
+ // vector tile spec only supports integer values for feature ids --
42
+ // allowing non-integer values here results in a non-compliant PBF
43
+ // that causes an exception when it is parsed with vector-tile-js
44
+ if ('id' in feature && !isNaN(feature.id)) {
45
+ this.id = parseInt(feature.id, 10);
46
+ }
47
+ }
48
+
49
+ loadGeometry() {
50
+ if (this._feature.type === 1) {
51
+ const geometry = [];
52
+ for (const point of this._feature.geometry) {
53
+ geometry.push([new Point(point[0], point[1])]);
54
+ }
55
+ return geometry;
56
+ } else {
57
+ const geometry = [];
58
+ for (const ring of this._feature.geometry) {
59
+ const newRing = [];
60
+ for (const point of ring) {
61
+ newRing.push(new Point(point[0], point[1]));
62
+ }
63
+ geometry.push(newRing);
64
+ }
65
+ return geometry;
66
+ }
67
+ }
68
+
69
+ toGeoJSON(x: number, y: number, z: number) {
70
+ return toGeoJSON.call(this, x, y, z);
71
+ }
72
+ }
73
+
74
+ class GeoJSONWrapper implements VectorTile, VectorTileLayer {
75
+ layers: {[_: string]: VectorTileLayer};
76
+ name: string;
77
+ extent: number;
78
+ length: number;
79
+ _features: Array<Feature>;
80
+
81
+ constructor(features: Array<Feature>) {
82
+ this.layers = {'_geojsonTileLayer': this};
83
+ this.name = '_geojsonTileLayer';
84
+ this.extent = EXTENT;
85
+ this.length = features.length;
86
+ this._features = features;
87
+ }
88
+
89
+ feature(i: number): VectorTileFeature {
90
+ return new FeatureWrapper(this._features[i]);
91
+ }
92
+ }
93
+
94
+ export default GeoJSONWrapper;
node_modules/mapbox-gl/src/source/image_source.js ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {CanonicalTileID} from './tile_id';
4
+ import {Event, ErrorEvent, Evented} from '../util/evented';
5
+ import {getImage, ResourceType} from '../util/ajax';
6
+ import EXTENT from '../data/extent';
7
+ import {RasterBoundsArray} from '../data/array_types';
8
+ import rasterBoundsAttributes from '../data/raster_bounds_attributes';
9
+ import SegmentVector from '../data/segment';
10
+ import Texture from '../render/texture';
11
+ import MercatorCoordinate from '../geo/mercator_coordinate';
12
+
13
+ import type {Source} from './source';
14
+ import type {CanvasSourceSpecification} from './canvas_source';
15
+ import type Map from '../ui/map';
16
+ import type Dispatcher from '../util/dispatcher';
17
+ import type Tile from './tile';
18
+ import type {Callback} from '../types/callback';
19
+ import type VertexBuffer from '../gl/vertex_buffer';
20
+ import type {
21
+ ImageSourceSpecification,
22
+ VideoSourceSpecification
23
+ } from '../style-spec/types';
24
+
25
+ type Coordinates = [[number, number], [number, number], [number, number], [number, number]];
26
+
27
+ /**
28
+ * A data source containing an image.
29
+ * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-image) for detailed documentation of options.)
30
+ *
31
+ * @example
32
+ * // add to map
33
+ * map.addSource('some id', {
34
+ * type: 'image',
35
+ * url: 'https://www.mapbox.com/images/foo.png',
36
+ * coordinates: [
37
+ * [-76.54, 39.18],
38
+ * [-76.52, 39.18],
39
+ * [-76.52, 39.17],
40
+ * [-76.54, 39.17]
41
+ * ]
42
+ * });
43
+ *
44
+ * // update coordinates
45
+ * var mySource = map.getSource('some id');
46
+ * mySource.setCoordinates([
47
+ * [-76.54335737228394, 39.18579907229748],
48
+ * [-76.52803659439087, 39.1838364847587],
49
+ * [-76.5295386314392, 39.17683392507606],
50
+ * [-76.54520273208618, 39.17876344106642]
51
+ * ]);
52
+ *
53
+ * // update url and coordinates simultaneously
54
+ * mySource.updateImage({
55
+ * url: 'https://www.mapbox.com/images/bar.png',
56
+ * coordinates: [
57
+ * [-76.54335737228394, 39.18579907229748],
58
+ * [-76.52803659439087, 39.1838364847587],
59
+ * [-76.5295386314392, 39.17683392507606],
60
+ * [-76.54520273208618, 39.17876344106642]
61
+ * ]
62
+ * })
63
+ *
64
+ * map.removeSource('some id'); // remove
65
+ * @see [Add an image](https://www.mapbox.com/mapbox-gl-js/example/image-on-a-map/)
66
+ */
67
+ class ImageSource extends Evented implements Source {
68
+ type: string;
69
+ id: string;
70
+ minzoom: number;
71
+ maxzoom: number;
72
+ tileSize: number;
73
+ url: string;
74
+
75
+ coordinates: Coordinates;
76
+ tiles: {[_: string]: Tile};
77
+ options: any;
78
+ dispatcher: Dispatcher;
79
+ map: Map;
80
+ texture: Texture | null;
81
+ image: HTMLImageElement | ImageBitmap;
82
+ tileID: CanonicalTileID;
83
+ _boundsArray: RasterBoundsArray;
84
+ boundsBuffer: VertexBuffer;
85
+ boundsSegments: SegmentVector;
86
+ _loaded: boolean;
87
+
88
+ /**
89
+ * @private
90
+ */
91
+ constructor(id: string, options: ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {
92
+ super();
93
+ this.id = id;
94
+ this.dispatcher = dispatcher;
95
+ this.coordinates = options.coordinates;
96
+
97
+ this.type = 'image';
98
+ this.minzoom = 0;
99
+ this.maxzoom = 22;
100
+ this.tileSize = 512;
101
+ this.tiles = {};
102
+ this._loaded = false;
103
+
104
+ this.setEventedParent(eventedParent);
105
+
106
+ this.options = options;
107
+ }
108
+
109
+ load(newCoordinates?: Coordinates, successCallback?: () => void) {
110
+ this._loaded = false;
111
+ this.fire(new Event('dataloading', {dataType: 'source'}));
112
+
113
+ this.url = this.options.url;
114
+
115
+ getImage(this.map._requestManager.transformRequest(this.url, ResourceType.Image), (err, image) => {
116
+ this._loaded = true;
117
+ if (err) {
118
+ this.fire(new ErrorEvent(err));
119
+ } else if (image) {
120
+ this.image = image;
121
+ if (newCoordinates) {
122
+ this.coordinates = newCoordinates;
123
+ }
124
+ if (successCallback) {
125
+ successCallback();
126
+ }
127
+ this._finishLoading();
128
+ }
129
+ });
130
+ }
131
+
132
+ loaded(): boolean {
133
+ return this._loaded;
134
+ }
135
+
136
+ /**
137
+ * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing,
138
+ * set the `raster-fade-duration` paint property on the raster layer to 0.
139
+ *
140
+ * @param {Object} options Options object.
141
+ * @param {string} [options.url] Required image URL.
142
+ * @param {Array<Array<number>>} [options.coordinates] Four geographical coordinates,
143
+ * represented as arrays of longitude and latitude numbers, which define the corners of the image.
144
+ * The coordinates start at the top left corner of the image and proceed in clockwise order.
145
+ * They do not have to represent a rectangle.
146
+ * @returns {ImageSource} this
147
+ */
148
+ updateImage(options: {url: string, coordinates?: Coordinates}) {
149
+ if (!this.image || !options.url) {
150
+ return this;
151
+ }
152
+ this.options.url = options.url;
153
+ this.load(options.coordinates, () => { this.texture = null; });
154
+ return this;
155
+ }
156
+
157
+ _finishLoading() {
158
+ if (this.map) {
159
+ this.setCoordinates(this.coordinates);
160
+ this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));
161
+ }
162
+ }
163
+
164
+ onAdd(map: Map) {
165
+ this.map = map;
166
+ this.load();
167
+ }
168
+
169
+ /**
170
+ * Sets the image's coordinates and re-renders the map.
171
+ *
172
+ * @param {Array<Array<number>>} coordinates Four geographical coordinates,
173
+ * represented as arrays of longitude and latitude numbers, which define the corners of the image.
174
+ * The coordinates start at the top left corner of the image and proceed in clockwise order.
175
+ * They do not have to represent a rectangle.
176
+ * @returns {ImageSource} this
177
+ */
178
+ setCoordinates(coordinates: Coordinates) {
179
+ this.coordinates = coordinates;
180
+
181
+ // Calculate which mercator tile is suitable for rendering the video in
182
+ // and create a buffer with the corner coordinates. These coordinates
183
+ // may be outside the tile, because raster tiles aren't clipped when rendering.
184
+
185
+ // transform the geo coordinates into (zoom 0) tile space coordinates
186
+ const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat);
187
+
188
+ // Compute the coordinates of the tile we'll use to hold this image's
189
+ // render data
190
+ this.tileID = getCoordinatesCenterTileID(cornerCoords);
191
+
192
+ // Constrain min/max zoom to our tile's zoom level in order to force
193
+ // SourceCache to request this tile (no matter what the map's zoom
194
+ // level)
195
+ this.minzoom = this.maxzoom = this.tileID.z;
196
+
197
+ // Transform the corner coordinates into the coordinate space of our
198
+ // tile.
199
+ const tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round());
200
+
201
+ this._boundsArray = new RasterBoundsArray();
202
+ this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0);
203
+ this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, EXTENT, 0);
204
+ this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, EXTENT);
205
+ this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, EXTENT, EXTENT);
206
+
207
+ if (this.boundsBuffer) {
208
+ this.boundsBuffer.destroy();
209
+ delete this.boundsBuffer;
210
+ }
211
+
212
+ this.fire(new Event('data', {dataType:'source', sourceDataType: 'content'}));
213
+ return this;
214
+ }
215
+
216
+ prepare() {
217
+ if (Object.keys(this.tiles).length === 0 || !this.image) {
218
+ return;
219
+ }
220
+
221
+ const context = this.map.painter.context;
222
+ const gl = context.gl;
223
+
224
+ if (!this.boundsBuffer) {
225
+ this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);
226
+ }
227
+
228
+ if (!this.boundsSegments) {
229
+ this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
230
+ }
231
+
232
+ if (!this.texture) {
233
+ this.texture = new Texture(context, this.image, gl.RGBA);
234
+ this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
235
+ }
236
+
237
+ for (const w in this.tiles) {
238
+ const tile = this.tiles[w];
239
+ if (tile.state !== 'loaded') {
240
+ tile.state = 'loaded';
241
+ tile.texture = this.texture;
242
+ }
243
+ }
244
+ }
245
+
246
+ loadTile(tile: Tile, callback: Callback<void>) {
247
+ // We have a single tile -- whoose coordinates are this.tileID -- that
248
+ // covers the image we want to render. If that's the one being
249
+ // requested, set it up with the image; otherwise, mark the tile as
250
+ // `errored` to indicate that we have no data for it.
251
+ // If the world wraps, we may have multiple "wrapped" copies of the
252
+ // single tile.
253
+ if (this.tileID && this.tileID.equals(tile.tileID.canonical)) {
254
+ this.tiles[String(tile.tileID.wrap)] = tile;
255
+ tile.buckets = {};
256
+ callback(null);
257
+ } else {
258
+ tile.state = 'errored';
259
+ callback(null);
260
+ }
261
+ }
262
+
263
+ serialize(): Object {
264
+ return {
265
+ type: 'image',
266
+ url: this.options.url,
267
+ coordinates: this.coordinates
268
+ };
269
+ }
270
+
271
+ hasTransition() {
272
+ return false;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Given a list of coordinates, get their center as a coordinate.
278
+ *
279
+ * @returns centerpoint
280
+ * @private
281
+ */
282
+ export function getCoordinatesCenterTileID(coords: Array<MercatorCoordinate>) {
283
+ let minX = Infinity;
284
+ let minY = Infinity;
285
+ let maxX = -Infinity;
286
+ let maxY = -Infinity;
287
+
288
+ for (const coord of coords) {
289
+ minX = Math.min(minX, coord.x);
290
+ minY = Math.min(minY, coord.y);
291
+ maxX = Math.max(maxX, coord.x);
292
+ maxY = Math.max(maxY, coord.y);
293
+ }
294
+
295
+ const dx = maxX - minX;
296
+ const dy = maxY - minY;
297
+ const dMax = Math.max(dx, dy);
298
+ const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2));
299
+ const tilesAtZoom = Math.pow(2, zoom);
300
+
301
+ return new CanonicalTileID(
302
+ zoom,
303
+ Math.floor((minX + maxX) / 2 * tilesAtZoom),
304
+ Math.floor((minY + maxY) / 2 * tilesAtZoom));
305
+ }
306
+
307
+ export default ImageSource;
node_modules/mapbox-gl/src/source/load_tilejson.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {pick, extend} from '../util/util';
4
+
5
+ import {getJSON, ResourceType} from '../util/ajax';
6
+ import browser from '../util/browser';
7
+
8
+ import type {RequestManager} from '../util/mapbox';
9
+ import type {Callback} from '../types/callback';
10
+ import type {TileJSON} from '../types/tilejson';
11
+ import type {Cancelable} from '../types/cancelable';
12
+
13
+ export default function(options: any, requestManager: RequestManager, callback: Callback<TileJSON>): Cancelable {
14
+ const loaded = function(err: ?Error, tileJSON: ?Object) {
15
+ if (err) {
16
+ return callback(err);
17
+ } else if (tileJSON) {
18
+ const result: any = pick(
19
+ // explicit source options take precedence over TileJSON
20
+ extend(tileJSON, options),
21
+ ['tiles', 'minzoom', 'maxzoom', 'attribution', 'mapbox_logo', 'bounds', 'scheme', 'tileSize', 'encoding']
22
+ );
23
+
24
+ if (tileJSON.vector_layers) {
25
+ result.vectorLayers = tileJSON.vector_layers;
26
+ result.vectorLayerIds = result.vectorLayers.map((layer) => { return layer.id; });
27
+ }
28
+
29
+ result.tiles = requestManager.canonicalizeTileset(result, options.url);
30
+ callback(null, result);
31
+ }
32
+ };
33
+
34
+ if (options.url) {
35
+ return getJSON(requestManager.transformRequest(requestManager.normalizeSourceURL(options.url), ResourceType.Source), loaded);
36
+ } else {
37
+ return browser.frame(() => loaded(null, options));
38
+ }
39
+ }
node_modules/mapbox-gl/src/source/pixels_to_tile_units.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import EXTENT from '../data/extent';
4
+
5
+ import type {OverscaledTileID} from './tile_id';
6
+
7
+ /**
8
+ * Converts a pixel value at a the given zoom level to tile units.
9
+ *
10
+ * The shaders mostly calculate everything in tile units so style
11
+ * properties need to be converted from pixels to tile units using this.
12
+ *
13
+ * For example, a translation by 30 pixels at zoom 6.5 will be a
14
+ * translation by pixelsToTileUnits(30, 6.5) tile units.
15
+ *
16
+ * @returns value in tile units
17
+ * @private
18
+ */
19
+ export default function(tile: {tileID: OverscaledTileID, tileSize: number}, pixelValue: number, z: number): number {
20
+ return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));
21
+ }
node_modules/mapbox-gl/src/source/query_features.js ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import type SourceCache from './source_cache';
4
+ import type StyleLayer from '../style/style_layer';
5
+ import type CollisionIndex from '../symbol/collision_index';
6
+ import type Transform from '../geo/transform';
7
+ import type {RetainedQueryData} from '../symbol/placement';
8
+ import type {FilterSpecification} from '../style-spec/types';
9
+ import assert from 'assert';
10
+ import {mat4} from 'gl-matrix';
11
+
12
+ /*
13
+ * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates.
14
+ */
15
+ function getPixelPosMatrix(transform, tileID) {
16
+ const t = mat4.identity([]);
17
+ mat4.translate(t, t, [1, 1, 0]);
18
+ mat4.scale(t, t, [transform.width * 0.5, transform.height * 0.5, 1]);
19
+ return mat4.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped()));
20
+ }
21
+
22
+ function queryIncludes3DLayer(layers?: Array<string>, styleLayers: {[_: string]: StyleLayer}, sourceID: string) {
23
+ if (layers) {
24
+ for (const layerID of layers) {
25
+ const layer = styleLayers[layerID];
26
+ if (layer && layer.source === sourceID && layer.type === 'fill-extrusion') {
27
+ return true;
28
+ }
29
+ }
30
+ } else {
31
+ for (const key in styleLayers) {
32
+ const layer = styleLayers[key];
33
+ if (layer.source === sourceID && layer.type === 'fill-extrusion') {
34
+ return true;
35
+ }
36
+ }
37
+ }
38
+ return false;
39
+ }
40
+
41
+ export function queryRenderedFeatures(sourceCache: SourceCache,
42
+ styleLayers: {[_: string]: StyleLayer},
43
+ serializedLayers: {[_: string]: Object},
44
+ queryGeometry: Array<Point>,
45
+ params: { filter: FilterSpecification, layers: Array<string>, availableImages: Array<string> },
46
+ transform: Transform) {
47
+
48
+ const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id);
49
+ const maxPitchScaleFactor = transform.maxPitchScaleFactor();
50
+ const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer);
51
+
52
+ tilesIn.sort(sortTilesIn);
53
+ const renderedFeatureLayers = [];
54
+ for (const tileIn of tilesIn) {
55
+ renderedFeatureLayers.push({
56
+ wrappedTileID: tileIn.tileID.wrapped().key,
57
+ queryResults: tileIn.tile.queryRenderedFeatures(
58
+ styleLayers,
59
+ serializedLayers,
60
+ sourceCache._state,
61
+ tileIn.queryGeometry,
62
+ tileIn.cameraQueryGeometry,
63
+ tileIn.scale,
64
+ params,
65
+ transform,
66
+ maxPitchScaleFactor,
67
+ getPixelPosMatrix(sourceCache.transform, tileIn.tileID))
68
+ });
69
+ }
70
+
71
+ const result = mergeRenderedFeatureLayers(renderedFeatureLayers);
72
+
73
+ // Merge state from SourceCache into the results
74
+ for (const layerID in result) {
75
+ result[layerID].forEach((featureWrapper) => {
76
+ const feature = featureWrapper.feature;
77
+ const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id);
78
+ feature.source = feature.layer.source;
79
+ if (feature.layer['source-layer']) {
80
+ feature.sourceLayer = feature.layer['source-layer'];
81
+ }
82
+ feature.state = state;
83
+ });
84
+ }
85
+ return result;
86
+ }
87
+
88
+ export function queryRenderedSymbols(styleLayers: {[_: string]: StyleLayer},
89
+ serializedLayers: {[_: string]: StyleLayer},
90
+ sourceCaches: {[_: string]: SourceCache},
91
+ queryGeometry: Array<Point>,
92
+ params: { filter: FilterSpecification, layers: Array<string>, availableImages: Array<string> },
93
+ collisionIndex: CollisionIndex,
94
+ retainedQueryData: {[_: number]: RetainedQueryData}) {
95
+ const result = {};
96
+ const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry);
97
+ const bucketQueryData = [];
98
+ for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) {
99
+ bucketQueryData.push(retainedQueryData[bucketInstanceId]);
100
+ }
101
+ bucketQueryData.sort(sortTilesIn);
102
+
103
+ for (const queryData of bucketQueryData) {
104
+ const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(
105
+ renderedSymbols[queryData.bucketInstanceId],
106
+ serializedLayers,
107
+ queryData.bucketIndex,
108
+ queryData.sourceLayerIndex,
109
+ params.filter,
110
+ params.layers,
111
+ params.availableImages,
112
+ styleLayers);
113
+
114
+ for (const layerID in bucketSymbols) {
115
+ const resultFeatures = result[layerID] = result[layerID] || [];
116
+ const layerSymbols = bucketSymbols[layerID];
117
+ layerSymbols.sort((a, b) => {
118
+ // Match topDownFeatureComparator from FeatureIndex, but using
119
+ // most recent sorting of features from bucket.sortFeatures
120
+ const featureSortOrder = queryData.featureSortOrder;
121
+ if (featureSortOrder) {
122
+ // queryRenderedSymbols documentation says we'll return features in
123
+ // "top-to-bottom" rendering order (aka last-to-first).
124
+ // Actually there can be multiple symbol instances per feature, so
125
+ // we sort each feature based on the first matching symbol instance.
126
+ const sortedA = featureSortOrder.indexOf(a.featureIndex);
127
+ const sortedB = featureSortOrder.indexOf(b.featureIndex);
128
+ assert(sortedA >= 0);
129
+ assert(sortedB >= 0);
130
+ return sortedB - sortedA;
131
+ } else {
132
+ // Bucket hasn't been re-sorted based on angle, so use the
133
+ // reverse of the order the features appeared in the data.
134
+ return b.featureIndex - a.featureIndex;
135
+ }
136
+ });
137
+ for (const symbolFeature of layerSymbols) {
138
+ resultFeatures.push(symbolFeature);
139
+ }
140
+ }
141
+ }
142
+
143
+ // Merge state from SourceCache into the results
144
+ for (const layerName in result) {
145
+ result[layerName].forEach((featureWrapper) => {
146
+ const feature = featureWrapper.feature;
147
+ const layer = styleLayers[layerName];
148
+ const sourceCache = sourceCaches[layer.source];
149
+ const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id);
150
+ feature.source = feature.layer.source;
151
+ if (feature.layer['source-layer']) {
152
+ feature.sourceLayer = feature.layer['source-layer'];
153
+ }
154
+ feature.state = state;
155
+ });
156
+ }
157
+ return result;
158
+ }
159
+
160
+ export function querySourceFeatures(sourceCache: SourceCache, params: any) {
161
+ const tiles = sourceCache.getRenderableIds().map((id) => {
162
+ return sourceCache.getTileByID(id);
163
+ });
164
+
165
+ const result = [];
166
+
167
+ const dataTiles = {};
168
+ for (let i = 0; i < tiles.length; i++) {
169
+ const tile = tiles[i];
170
+ const dataID = tile.tileID.canonical.key;
171
+ if (!dataTiles[dataID]) {
172
+ dataTiles[dataID] = true;
173
+ tile.querySourceFeatures(result, params);
174
+ }
175
+ }
176
+
177
+ return result;
178
+ }
179
+
180
+ function sortTilesIn(a, b) {
181
+ const idA = a.tileID;
182
+ const idB = b.tileID;
183
+ return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x);
184
+ }
185
+
186
+ function mergeRenderedFeatureLayers(tiles) {
187
+ // Merge results from all tiles, but if two tiles share the same
188
+ // wrapped ID, don't duplicate features between the two tiles
189
+ const result = {};
190
+ const wrappedIDLayerMap = {};
191
+ for (const tile of tiles) {
192
+ const queryResults = tile.queryResults;
193
+ const wrappedID = tile.wrappedTileID;
194
+ const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {};
195
+ for (const layerID in queryResults) {
196
+ const tileFeatures = queryResults[layerID];
197
+ const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {};
198
+ const resultFeatures = result[layerID] = result[layerID] || [];
199
+ for (const tileFeature of tileFeatures) {
200
+ if (!wrappedIDFeatures[tileFeature.featureIndex]) {
201
+ wrappedIDFeatures[tileFeature.featureIndex] = true;
202
+ resultFeatures.push(tileFeature);
203
+ }
204
+ }
205
+ }
206
+ }
207
+ return result;
208
+ }
node_modules/mapbox-gl/src/source/raster_dem_tile_source.js ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {getImage, ResourceType} from '../util/ajax';
4
+ import {extend} from '../util/util';
5
+ import {Evented} from '../util/evented';
6
+ import browser from '../util/browser';
7
+ import window from '../util/window';
8
+ import offscreenCanvasSupported from '../util/offscreen_canvas_supported';
9
+ import {OverscaledTileID} from './tile_id';
10
+ import RasterTileSource from './raster_tile_source';
11
+ // ensure DEMData is registered for worker transfer on main thread:
12
+ import '../data/dem_data';
13
+
14
+ import type {Source} from './source';
15
+ import type Dispatcher from '../util/dispatcher';
16
+ import type Tile from './tile';
17
+ import type {Callback} from '../types/callback';
18
+ import type {RasterDEMSourceSpecification} from '../style-spec/types';
19
+
20
+ class RasterDEMTileSource extends RasterTileSource implements Source {
21
+ encoding: "mapbox" | "terrarium";
22
+
23
+ constructor(id: string, options: RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {
24
+ super(id, options, dispatcher, eventedParent);
25
+ this.type = 'raster-dem';
26
+ this.maxzoom = 22;
27
+ this._options = extend({type: 'raster-dem'}, options);
28
+ this.encoding = options.encoding || "mapbox";
29
+ }
30
+
31
+ serialize() {
32
+ return {
33
+ type: 'raster-dem',
34
+ url: this.url,
35
+ tileSize: this.tileSize,
36
+ tiles: this.tiles,
37
+ bounds: this.bounds,
38
+ encoding: this.encoding
39
+ };
40
+ }
41
+
42
+ loadTile(tile: Tile, callback: Callback<void>) {
43
+ const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize);
44
+ tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), imageLoaded.bind(this));
45
+
46
+ tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);
47
+ function imageLoaded(err, img) {
48
+ delete tile.request;
49
+ if (tile.aborted) {
50
+ tile.state = 'unloaded';
51
+ callback(null);
52
+ } else if (err) {
53
+ tile.state = 'errored';
54
+ callback(err);
55
+ } else if (img) {
56
+ if (this.map._refreshExpiredTiles) tile.setExpiryData(img);
57
+ delete (img: any).cacheControl;
58
+ delete (img: any).expires;
59
+ const transfer = window.ImageBitmap && img instanceof window.ImageBitmap && offscreenCanvasSupported();
60
+ const rawImageData = transfer ? img : browser.getImageData(img, 1);
61
+ const params = {
62
+ uid: tile.uid,
63
+ coord: tile.tileID,
64
+ source: this.id,
65
+ rawImageData,
66
+ encoding: this.encoding
67
+ };
68
+
69
+ if (!tile.actor || tile.state === 'expired') {
70
+ tile.actor = this.dispatcher.getActor();
71
+ tile.actor.send('loadDEMTile', params, done.bind(this));
72
+ }
73
+ }
74
+ }
75
+
76
+ function done(err, dem) {
77
+ if (err) {
78
+ tile.state = 'errored';
79
+ callback(err);
80
+ }
81
+
82
+ if (dem) {
83
+ tile.dem = dem;
84
+ tile.needsHillshadePrepare = true;
85
+ tile.state = 'loaded';
86
+ callback(null);
87
+ }
88
+ }
89
+ }
90
+
91
+ _getNeighboringTiles(tileID: OverscaledTileID) {
92
+ const canonical = tileID.canonical;
93
+ const dim = Math.pow(2, canonical.z);
94
+
95
+ const px = (canonical.x - 1 + dim) % dim;
96
+ const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap;
97
+ const nx = (canonical.x + 1 + dim) % dim;
98
+ const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap;
99
+
100
+ const neighboringTiles = {};
101
+ // add adjacent tiles
102
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = {backfilled: false};
103
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = {backfilled: false};
104
+
105
+ // Add upper neighboringTiles
106
+ if (canonical.y > 0) {
107
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = {backfilled: false};
108
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = {backfilled: false};
109
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = {backfilled: false};
110
+ }
111
+ // Add lower neighboringTiles
112
+ if (canonical.y + 1 < dim) {
113
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = {backfilled: false};
114
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = {backfilled: false};
115
+ neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = {backfilled: false};
116
+ }
117
+
118
+ return neighboringTiles;
119
+ }
120
+
121
+ unloadTile(tile: Tile) {
122
+ if (tile.demTexture) this.map.painter.saveTileTexture(tile.demTexture);
123
+ if (tile.fbo) {
124
+ tile.fbo.destroy();
125
+ delete tile.fbo;
126
+ }
127
+ if (tile.dem) delete tile.dem;
128
+ delete tile.neighboringTiles;
129
+
130
+ tile.state = 'unloaded';
131
+ if (tile.actor) {
132
+ tile.actor.send('removeDEMTile', {uid: tile.uid, source: this.id});
133
+ }
134
+ }
135
+
136
+ }
137
+
138
+ export default RasterDEMTileSource;
node_modules/mapbox-gl/src/source/raster_dem_tile_worker_source.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import DEMData from '../data/dem_data';
4
+ import {RGBAImage} from '../util/image';
5
+ import window from '../util/window';
6
+
7
+ import type Actor from '../util/actor';
8
+ import type {
9
+ WorkerDEMTileParameters,
10
+ WorkerDEMTileCallback,
11
+ TileParameters
12
+ } from './worker_source';
13
+ const {ImageBitmap} = window;
14
+
15
+ class RasterDEMTileWorkerSource {
16
+ actor: Actor;
17
+ loaded: {[_: string]: DEMData};
18
+ offscreenCanvas: OffscreenCanvas;
19
+ offscreenCanvasContext: CanvasRenderingContext2D;
20
+
21
+ constructor() {
22
+ this.loaded = {};
23
+ }
24
+
25
+ loadTile(params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {
26
+ const {uid, encoding, rawImageData} = params;
27
+ // Main thread will transfer ImageBitmap if offscreen decode with OffscreenCanvas is supported, else it will transfer an already decoded image.
28
+ const imagePixels = (ImageBitmap && rawImageData instanceof ImageBitmap) ? this.getImageData(rawImageData) : rawImageData;
29
+ const dem = new DEMData(uid, imagePixels, encoding);
30
+ this.loaded = this.loaded || {};
31
+ this.loaded[uid] = dem;
32
+ callback(null, dem);
33
+ }
34
+
35
+ getImageData(imgBitmap: ImageBitmap): RGBAImage {
36
+ // Lazily initialize OffscreenCanvas
37
+ if (!this.offscreenCanvas || !this.offscreenCanvasContext) {
38
+ // Dem tiles are typically 256x256
39
+ this.offscreenCanvas = new OffscreenCanvas(imgBitmap.width, imgBitmap.height);
40
+ this.offscreenCanvasContext = this.offscreenCanvas.getContext('2d');
41
+ }
42
+
43
+ this.offscreenCanvas.width = imgBitmap.width;
44
+ this.offscreenCanvas.height = imgBitmap.height;
45
+
46
+ this.offscreenCanvasContext.drawImage(imgBitmap, 0, 0, imgBitmap.width, imgBitmap.height);
47
+ // Insert an additional 1px padding around the image to allow backfilling for neighboring data.
48
+ const imgData = this.offscreenCanvasContext.getImageData(-1, -1, imgBitmap.width + 2, imgBitmap.height + 2);
49
+ this.offscreenCanvasContext.clearRect(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height);
50
+ return new RGBAImage({width: imgData.width, height: imgData.height}, imgData.data);
51
+ }
52
+
53
+ removeTile(params: TileParameters) {
54
+ const loaded = this.loaded,
55
+ uid = params.uid;
56
+ if (loaded && loaded[uid]) {
57
+ delete loaded[uid];
58
+ }
59
+ }
60
+ }
61
+
62
+ export default RasterDEMTileWorkerSource;
node_modules/mapbox-gl/src/source/raster_tile_source.js ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {extend, pick} from '../util/util';
4
+
5
+ import {getImage, ResourceType} from '../util/ajax';
6
+ import {Event, ErrorEvent, Evented} from '../util/evented';
7
+ import loadTileJSON from './load_tilejson';
8
+ import {postTurnstileEvent, postMapLoadEvent} from '../util/mapbox';
9
+ import TileBounds from './tile_bounds';
10
+ import Texture from '../render/texture';
11
+
12
+ import {cacheEntryPossiblyAdded} from '../util/tile_request_cache';
13
+
14
+ import type {Source} from './source';
15
+ import type {OverscaledTileID} from './tile_id';
16
+ import type Map from '../ui/map';
17
+ import type Dispatcher from '../util/dispatcher';
18
+ import type Tile from './tile';
19
+ import type {Callback} from '../types/callback';
20
+ import type {Cancelable} from '../types/cancelable';
21
+ import type {
22
+ RasterSourceSpecification,
23
+ RasterDEMSourceSpecification
24
+ } from '../style-spec/types';
25
+
26
+ class RasterTileSource extends Evented implements Source {
27
+ type: 'raster' | 'raster-dem';
28
+ id: string;
29
+ minzoom: number;
30
+ maxzoom: number;
31
+ url: string;
32
+ scheme: string;
33
+ tileSize: number;
34
+
35
+ bounds: ?[number, number, number, number];
36
+ tileBounds: TileBounds;
37
+ roundZoom: boolean;
38
+ dispatcher: Dispatcher;
39
+ map: Map;
40
+ tiles: Array<string>;
41
+
42
+ _loaded: boolean;
43
+ _options: RasterSourceSpecification | RasterDEMSourceSpecification;
44
+ _tileJSONRequest: ?Cancelable;
45
+
46
+ constructor(id: string, options: RasterSourceSpecification | RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {
47
+ super();
48
+ this.id = id;
49
+ this.dispatcher = dispatcher;
50
+ this.setEventedParent(eventedParent);
51
+
52
+ this.type = 'raster';
53
+ this.minzoom = 0;
54
+ this.maxzoom = 22;
55
+ this.roundZoom = true;
56
+ this.scheme = 'xyz';
57
+ this.tileSize = 512;
58
+ this._loaded = false;
59
+
60
+ this._options = extend({type: 'raster'}, options);
61
+ extend(this, pick(options, ['url', 'scheme', 'tileSize']));
62
+ }
63
+
64
+ load() {
65
+ this._loaded = false;
66
+ this.fire(new Event('dataloading', {dataType: 'source'}));
67
+ this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => {
68
+ this._tileJSONRequest = null;
69
+ this._loaded = true;
70
+ if (err) {
71
+ this.fire(new ErrorEvent(err));
72
+ } else if (tileJSON) {
73
+ extend(this, tileJSON);
74
+ if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
75
+
76
+ postTurnstileEvent(tileJSON.tiles);
77
+ postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken);
78
+
79
+ // `content` is included here to prevent a race condition where `Style#_updateSources` is called
80
+ // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives
81
+ // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088
82
+ this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));
83
+ this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'}));
84
+ }
85
+ });
86
+ }
87
+
88
+ loaded(): boolean {
89
+ return this._loaded;
90
+ }
91
+
92
+ onAdd(map: Map) {
93
+ this.map = map;
94
+ this.load();
95
+ }
96
+
97
+ onRemove() {
98
+ if (this._tileJSONRequest) {
99
+ this._tileJSONRequest.cancel();
100
+ this._tileJSONRequest = null;
101
+ }
102
+ }
103
+
104
+ serialize() {
105
+ return extend({}, this._options);
106
+ }
107
+
108
+ hasTile(tileID: OverscaledTileID) {
109
+ return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
110
+ }
111
+
112
+ loadTile(tile: Tile, callback: Callback<void>) {
113
+ const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize);
114
+ tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), (err, img) => {
115
+ delete tile.request;
116
+
117
+ if (tile.aborted) {
118
+ tile.state = 'unloaded';
119
+ callback(null);
120
+ } else if (err) {
121
+ tile.state = 'errored';
122
+ callback(err);
123
+ } else if (img) {
124
+ if (this.map._refreshExpiredTiles) tile.setExpiryData(img);
125
+ delete (img: any).cacheControl;
126
+ delete (img: any).expires;
127
+
128
+ const context = this.map.painter.context;
129
+ const gl = context.gl;
130
+ tile.texture = this.map.painter.getTileTexture(img.width);
131
+ if (tile.texture) {
132
+ tile.texture.update(img, {useMipmap: true});
133
+ } else {
134
+ tile.texture = new Texture(context, img, gl.RGBA, {useMipmap: true});
135
+ tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
136
+
137
+ if (context.extTextureFilterAnisotropic) {
138
+ gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
139
+ }
140
+ }
141
+
142
+ tile.state = 'loaded';
143
+
144
+ cacheEntryPossiblyAdded(this.dispatcher);
145
+
146
+ callback(null);
147
+ }
148
+ });
149
+ }
150
+
151
+ abortTile(tile: Tile, callback: Callback<void>) {
152
+ if (tile.request) {
153
+ tile.request.cancel();
154
+ delete tile.request;
155
+ }
156
+ callback();
157
+ }
158
+
159
+ unloadTile(tile: Tile, callback: Callback<void>) {
160
+ if (tile.texture) this.map.painter.saveTileTexture(tile.texture);
161
+ callback();
162
+ }
163
+
164
+ hasTransition() {
165
+ return false;
166
+ }
167
+ }
168
+
169
+ export default RasterTileSource;
node_modules/mapbox-gl/src/source/rtl_text_plugin.js ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {Event, Evented} from '../util/evented';
4
+ import {getArrayBuffer} from '../util/ajax';
5
+ import browser from '../util/browser';
6
+ import assert from 'assert';
7
+ import {isWorker} from '../util/util';
8
+
9
+ const status = {
10
+ unavailable: 'unavailable', // Not loaded
11
+ deferred: 'deferred', // The plugin URL has been specified, but loading has been deferred
12
+ loading: 'loading', // request in-flight
13
+ loaded: 'loaded',
14
+ error: 'error'
15
+ };
16
+
17
+ export type PluginState = {
18
+ pluginStatus: $Values<typeof status>;
19
+ pluginURL: ?string
20
+ };
21
+
22
+ type ErrorCallback = (error: ?Error) => void;
23
+ type PluginStateSyncCallback = (state: PluginState) => void;
24
+ let _completionCallback = null;
25
+
26
+ //Variables defining the current state of the plugin
27
+ let pluginStatus = status.unavailable;
28
+ let pluginURL = null;
29
+
30
+ export const triggerPluginCompletionEvent = function(error: ?Error) {
31
+ // NetworkError's are not correctly reflected by the plugin status which prevents reloading plugin
32
+ if (error && typeof error === 'string' && error.indexOf('NetworkError') > -1) {
33
+ pluginStatus = status.error;
34
+ }
35
+
36
+ if (_completionCallback) {
37
+ _completionCallback(error);
38
+ }
39
+ };
40
+
41
+ function sendPluginStateToWorker() {
42
+ evented.fire(new Event('pluginStateChange', {pluginStatus, pluginURL}));
43
+ }
44
+
45
+ export const evented = new Evented();
46
+
47
+ export const getRTLTextPluginStatus = function () {
48
+ return pluginStatus;
49
+ };
50
+
51
+ export const registerForPluginStateChange = function(callback: PluginStateSyncCallback) {
52
+ // Do an initial sync of the state
53
+ callback({pluginStatus, pluginURL});
54
+ // Listen for all future state changes
55
+ evented.on('pluginStateChange', callback);
56
+ return callback;
57
+ };
58
+
59
+ export const clearRTLTextPlugin = function() {
60
+ pluginStatus = status.unavailable;
61
+ pluginURL = null;
62
+ };
63
+
64
+ export const setRTLTextPlugin = function(url: string, callback: ?ErrorCallback, deferred: boolean = false) {
65
+ if (pluginStatus === status.deferred || pluginStatus === status.loading || pluginStatus === status.loaded) {
66
+ throw new Error('setRTLTextPlugin cannot be called multiple times.');
67
+ }
68
+ pluginURL = browser.resolveURL(url);
69
+ pluginStatus = status.deferred;
70
+ _completionCallback = callback;
71
+ sendPluginStateToWorker();
72
+
73
+ //Start downloading the plugin immediately if not intending to lazy-load
74
+ if (!deferred) {
75
+ downloadRTLTextPlugin();
76
+ }
77
+ };
78
+
79
+ export const downloadRTLTextPlugin = function() {
80
+ if (pluginStatus !== status.deferred || !pluginURL) {
81
+ throw new Error('rtl-text-plugin cannot be downloaded unless a pluginURL is specified');
82
+ }
83
+ pluginStatus = status.loading;
84
+ sendPluginStateToWorker();
85
+ if (pluginURL) {
86
+ getArrayBuffer({url: pluginURL}, (error) => {
87
+ if (error) {
88
+ triggerPluginCompletionEvent(error);
89
+ } else {
90
+ pluginStatus = status.loaded;
91
+ sendPluginStateToWorker();
92
+ }
93
+ });
94
+ }
95
+ };
96
+
97
+ export const plugin: {
98
+ applyArabicShaping: ?Function,
99
+ processBidirectionalText: ?(string, Array<number>) => Array<string>,
100
+ processStyledBidirectionalText: ?(string, Array<number>, Array<number>) => Array<[string, Array<number>]>,
101
+ isLoaded: () => boolean,
102
+ isLoading: () => boolean,
103
+ setState: (state: PluginState) => void,
104
+ isParsed: () => boolean,
105
+ getPluginURL: () => ?string
106
+ } = {
107
+ applyArabicShaping: null,
108
+ processBidirectionalText: null,
109
+ processStyledBidirectionalText: null,
110
+ isLoaded() {
111
+ return pluginStatus === status.loaded || // Main Thread: loaded if the completion callback returned successfully
112
+ plugin.applyArabicShaping != null; // Web-worker: loaded if the plugin functions have been compiled
113
+ },
114
+ isLoading() { // Main Thread Only: query the loading status, this function does not return the correct value in the worker context.
115
+ return pluginStatus === status.loading;
116
+ },
117
+ setState(state: PluginState) { // Worker thread only: this tells the worker threads that the plugin is available on the Main thread
118
+ assert(isWorker(), 'Cannot set the state of the rtl-text-plugin when not in the web-worker context');
119
+
120
+ pluginStatus = state.pluginStatus;
121
+ pluginURL = state.pluginURL;
122
+ },
123
+ isParsed(): boolean {
124
+ assert(isWorker(), 'rtl-text-plugin is only parsed on the worker-threads');
125
+
126
+ return plugin.applyArabicShaping != null &&
127
+ plugin.processBidirectionalText != null &&
128
+ plugin.processStyledBidirectionalText != null;
129
+ },
130
+ getPluginURL(): ?string {
131
+ assert(isWorker(), 'rtl-text-plugin url can only be queried from the worker threads');
132
+ return pluginURL;
133
+ }
134
+ };
135
+
136
+ export const lazyLoadRTLTextPlugin = function() {
137
+ if (!plugin.isLoading() &&
138
+ !plugin.isLoaded() &&
139
+ getRTLTextPluginStatus() === 'deferred'
140
+ ) {
141
+ downloadRTLTextPlugin();
142
+ }
143
+ };
node_modules/mapbox-gl/src/source/source.js ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {bindAll} from '../util/util';
4
+
5
+ import type Dispatcher from '../util/dispatcher';
6
+ import type {Event, Evented} from '../util/evented';
7
+ import type Map from '../ui/map';
8
+ import type Tile from './tile';
9
+ import type {OverscaledTileID} from './tile_id';
10
+ import type {Callback} from '../types/callback';
11
+ import {CanonicalTileID} from './tile_id';
12
+
13
+ /**
14
+ * The `Source` interface must be implemented by each source type, including "core" types (`vector`, `raster`,
15
+ * `video`, etc.) and all custom, third-party types.
16
+ *
17
+ * @private
18
+ *
19
+ * @param {string} id The id for the source. Must not be used by any existing source.
20
+ * @param {Object} options Source options, specific to the source type (except for `options.type`, which is always
21
+ * required).
22
+ * @param {string} options.type The source type, matching the value of `name` used in {@link Style#addSourceType}.
23
+ * @param {Dispatcher} dispatcher A {@link Dispatcher} instance, which can be used to send messages to the workers.
24
+ *
25
+ * @fires data with `{dataType: 'source', sourceDataType: 'metadata'}` to indicate that any necessary metadata
26
+ * has been loaded so that it's okay to call `loadTile`; and with `{dataType: 'source', sourceDataType: 'content'}`
27
+ * to indicate that the source data has changed, so that any current caches should be flushed.
28
+ * @property {string} id The id for the source. Must match the id passed to the constructor.
29
+ * @property {number} minzoom
30
+ * @property {number} maxzoom
31
+ * @property {boolean} isTileClipped `false` if tiles can be drawn outside their boundaries, `true` if they cannot.
32
+ * @property {boolean} reparseOverscaled `true` if tiles should be sent back to the worker for each overzoomed zoom
33
+ * level, `false` if not.
34
+ * @property {boolean} roundZoom `true` if zoom levels are rounded to the nearest integer in the source data, `false`
35
+ * if they are floor-ed to the nearest integer.
36
+ */
37
+ export interface Source {
38
+ +type: string;
39
+ id: string;
40
+ minzoom: number,
41
+ maxzoom: number,
42
+ tileSize: number,
43
+ attribution?: string,
44
+
45
+ roundZoom?: boolean,
46
+ isTileClipped?: boolean,
47
+ mapbox_logo?: boolean,
48
+ tileID?: CanonicalTileID;
49
+ reparseOverscaled?: boolean,
50
+ vectorLayerIds?: Array<string>,
51
+
52
+ hasTransition(): boolean;
53
+ loaded(): boolean;
54
+
55
+ fire(event: Event): mixed;
56
+
57
+ +onAdd?: (map: Map) => void;
58
+ +onRemove?: (map: Map) => void;
59
+
60
+ loadTile(tile: Tile, callback: Callback<void>): void;
61
+ +hasTile?: (tileID: OverscaledTileID) => boolean;
62
+ +abortTile?: (tile: Tile, callback: Callback<void>) => void;
63
+ +unloadTile?: (tile: Tile, callback: Callback<void>) => void;
64
+
65
+ /**
66
+ * @returns A plain (stringifiable) JS object representing the current state of the source.
67
+ * Creating a source using the returned object as the `options` should result in a Source that is
68
+ * equivalent to this one.
69
+ * @private
70
+ */
71
+ serialize(): Object;
72
+
73
+ +prepare?: () => void;
74
+ }
75
+
76
+ type SourceStatics = {
77
+ /*
78
+ * An optional URL to a script which, when run by a Worker, registers a {@link WorkerSource}
79
+ * implementation for this Source type by calling `self.registerWorkerSource(workerSource: WorkerSource)`.
80
+ */
81
+ workerSourceURL?: URL;
82
+ };
83
+
84
+ export type SourceClass = Class<Source> & SourceStatics;
85
+
86
+ import vector from '../source/vector_tile_source';
87
+ import raster from '../source/raster_tile_source';
88
+ import rasterDem from '../source/raster_dem_tile_source';
89
+ import geojson from '../source/geojson_source';
90
+ import video from '../source/video_source';
91
+ import image from '../source/image_source';
92
+ import canvas from '../source/canvas_source';
93
+
94
+ import type {SourceSpecification} from '../style-spec/types';
95
+
96
+ const sourceTypes = {
97
+ vector,
98
+ raster,
99
+ 'raster-dem': rasterDem,
100
+ geojson,
101
+ video,
102
+ image,
103
+ canvas
104
+ };
105
+
106
+ /*
107
+ * Creates a tiled data source instance given an options object.
108
+ *
109
+ * @param id
110
+ * @param {Object} source A source definition object compliant with
111
+ * [`mapbox-gl-style-spec`](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or, for a third-party source type,
112
+ * with that type's requirements.
113
+ * @param {Dispatcher} dispatcher
114
+ * @returns {Source}
115
+ */
116
+ export const create = function(id: string, specification: SourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {
117
+ const source = new sourceTypes[specification.type](id, (specification: any), dispatcher, eventedParent);
118
+
119
+ if (source.id !== id) {
120
+ throw new Error(`Expected Source id to be ${id} instead of ${source.id}`);
121
+ }
122
+
123
+ bindAll(['load', 'abort', 'unload', 'serialize', 'prepare'], source);
124
+ return source;
125
+ };
126
+
127
+ export const getType = function (name: string) {
128
+ return sourceTypes[name];
129
+ };
130
+
131
+ export const setType = function (name: string, type: Class<Source>) {
132
+ sourceTypes[name] = type;
133
+ };
134
+
135
+ export interface Actor {
136
+ send(type: string, data: Object, callback: Callback<any>): void;
137
+ }
node_modules/mapbox-gl/src/source/source_cache.js ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {create as createSource} from './source';
4
+
5
+ import Tile from './tile';
6
+ import {Event, ErrorEvent, Evented} from '../util/evented';
7
+ import TileCache from './tile_cache';
8
+ import MercatorCoordinate from '../geo/mercator_coordinate';
9
+ import {keysDifference, values} from '../util/util';
10
+ import EXTENT from '../data/extent';
11
+ import Context from '../gl/context';
12
+ import Point from '@mapbox/point-geometry';
13
+ import browser from '../util/browser';
14
+ import {OverscaledTileID} from './tile_id';
15
+ import assert from 'assert';
16
+ import SourceFeatureState from './source_state';
17
+
18
+ import type {Source} from './source';
19
+ import type Map from '../ui/map';
20
+ import type Style from '../style/style';
21
+ import type Dispatcher from '../util/dispatcher';
22
+ import type Transform from '../geo/transform';
23
+ import type {TileState} from './tile';
24
+ import type {Callback} from '../types/callback';
25
+ import type {SourceSpecification} from '../style-spec/types';
26
+
27
+ /**
28
+ * `SourceCache` is responsible for
29
+ *
30
+ * - creating an instance of `Source`
31
+ * - forwarding events from `Source`
32
+ * - caching tiles loaded from an instance of `Source`
33
+ * - loading the tiles needed to render a given viewport
34
+ * - unloading the cached tiles not needed to render a given viewport
35
+ *
36
+ * @private
37
+ */
38
+ class SourceCache extends Evented {
39
+ id: string;
40
+ dispatcher: Dispatcher;
41
+ map: Map;
42
+ style: Style;
43
+
44
+ _source: Source;
45
+ _sourceLoaded: boolean;
46
+ _sourceErrored: boolean;
47
+ _tiles: {[_: string]: Tile};
48
+ _prevLng: number | void;
49
+ _cache: TileCache;
50
+ _timers: {[_: any]: TimeoutID};
51
+ _cacheTimers: {[_: any]: TimeoutID};
52
+ _maxTileCacheSize: ?number;
53
+ _paused: boolean;
54
+ _shouldReloadOnResume: boolean;
55
+ _coveredTiles: {[_: string]: boolean};
56
+ transform: Transform;
57
+ _isIdRenderable: (id: string, symbolLayer?: boolean) => boolean;
58
+ used: boolean;
59
+ _state: SourceFeatureState;
60
+ _loadedParentTiles: {[_: string]: ?Tile};
61
+
62
+ static maxUnderzooming: number;
63
+ static maxOverzooming: number;
64
+
65
+ constructor(id: string, options: SourceSpecification, dispatcher: Dispatcher) {
66
+ super();
67
+ this.id = id;
68
+ this.dispatcher = dispatcher;
69
+
70
+ this.on('data', (e) => {
71
+ // this._sourceLoaded signifies that the TileJSON is loaded if applicable.
72
+ // if the source type does not come with a TileJSON, the flag signifies the
73
+ // source data has loaded (i.e geojson has been tiled on the worker and is ready)
74
+ if (e.dataType === 'source' && e.sourceDataType === 'metadata') this._sourceLoaded = true;
75
+
76
+ // for sources with mutable data, this event fires when the underlying data
77
+ // to a source is changed. (i.e. GeoJSONSource#setData and ImageSource#serCoordinates)
78
+ if (this._sourceLoaded && !this._paused && e.dataType === "source" && e.sourceDataType === 'content') {
79
+ this.reload();
80
+ if (this.transform) {
81
+ this.update(this.transform);
82
+ }
83
+ }
84
+ });
85
+
86
+ this.on('error', () => {
87
+ this._sourceErrored = true;
88
+ });
89
+
90
+ this._source = createSource(id, options, dispatcher, this);
91
+
92
+ this._tiles = {};
93
+ this._cache = new TileCache(0, this._unloadTile.bind(this));
94
+ this._timers = {};
95
+ this._cacheTimers = {};
96
+ this._maxTileCacheSize = null;
97
+ this._loadedParentTiles = {};
98
+
99
+ this._coveredTiles = {};
100
+ this._state = new SourceFeatureState();
101
+ }
102
+
103
+ onAdd(map: Map) {
104
+ this.map = map;
105
+ this._maxTileCacheSize = map ? map._maxTileCacheSize : null;
106
+ if (this._source && this._source.onAdd) {
107
+ this._source.onAdd(map);
108
+ }
109
+ }
110
+
111
+ onRemove(map: Map) {
112
+ if (this._source && this._source.onRemove) {
113
+ this._source.onRemove(map);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Return true if no tile data is pending, tiles will not change unless
119
+ * an additional API call is received.
120
+ * @private
121
+ */
122
+ loaded(): boolean {
123
+ if (this._sourceErrored) { return true; }
124
+ if (!this._sourceLoaded) { return false; }
125
+ if (!this._source.loaded()) { return false; }
126
+ for (const t in this._tiles) {
127
+ const tile = this._tiles[t];
128
+ if (tile.state !== 'loaded' && tile.state !== 'errored')
129
+ return false;
130
+ }
131
+ return true;
132
+ }
133
+
134
+ getSource(): Source {
135
+ return this._source;
136
+ }
137
+
138
+ pause() {
139
+ this._paused = true;
140
+ }
141
+
142
+ resume() {
143
+ if (!this._paused) return;
144
+ const shouldReload = this._shouldReloadOnResume;
145
+ this._paused = false;
146
+ this._shouldReloadOnResume = false;
147
+ if (shouldReload) this.reload();
148
+ if (this.transform) this.update(this.transform);
149
+ }
150
+
151
+ _loadTile(tile: Tile, callback: Callback<void>) {
152
+ return this._source.loadTile(tile, callback);
153
+ }
154
+
155
+ _unloadTile(tile: Tile) {
156
+ if (this._source.unloadTile)
157
+ return this._source.unloadTile(tile, () => {});
158
+ }
159
+
160
+ _abortTile(tile: Tile) {
161
+ if (this._source.abortTile)
162
+ return this._source.abortTile(tile, () => {});
163
+ }
164
+
165
+ serialize() {
166
+ return this._source.serialize();
167
+ }
168
+
169
+ prepare(context: Context) {
170
+ if (this._source.prepare) {
171
+ this._source.prepare();
172
+ }
173
+
174
+ this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null);
175
+ for (const i in this._tiles) {
176
+ const tile = this._tiles[i];
177
+ tile.upload(context);
178
+ tile.prepare(this.map.style.imageManager);
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Return all tile ids ordered with z-order, and cast to numbers
184
+ * @private
185
+ */
186
+ getIds(): Array<string> {
187
+ return (values(this._tiles): any).map((tile: Tile) => tile.tileID).sort(compareTileId).map(id => id.key);
188
+ }
189
+
190
+ getRenderableIds(symbolLayer?: boolean): Array<string> {
191
+ const renderables: Array<Tile> = [];
192
+ for (const id in this._tiles) {
193
+ if (this._isIdRenderable(id, symbolLayer)) renderables.push(this._tiles[id]);
194
+ }
195
+ if (symbolLayer) {
196
+ return renderables.sort((a_: Tile, b_: Tile) => {
197
+ const a = a_.tileID;
198
+ const b = b_.tileID;
199
+ const rotatedA = (new Point(a.canonical.x, a.canonical.y))._rotate(this.transform.angle);
200
+ const rotatedB = (new Point(b.canonical.x, b.canonical.y))._rotate(this.transform.angle);
201
+ return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;
202
+ }).map(tile => tile.tileID.key);
203
+ }
204
+ return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key);
205
+ }
206
+
207
+ hasRenderableParent(tileID: OverscaledTileID) {
208
+ const parentTile = this.findLoadedParent(tileID, 0);
209
+ if (parentTile) {
210
+ return this._isIdRenderable(parentTile.tileID.key);
211
+ }
212
+ return false;
213
+ }
214
+
215
+ _isIdRenderable(id: string, symbolLayer?: boolean) {
216
+ return this._tiles[id] && this._tiles[id].hasData() &&
217
+ !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade());
218
+ }
219
+
220
+ reload() {
221
+ if (this._paused) {
222
+ this._shouldReloadOnResume = true;
223
+ return;
224
+ }
225
+
226
+ this._cache.reset();
227
+
228
+ for (const i in this._tiles) {
229
+ if (this._tiles[i].state !== "errored") this._reloadTile(i, 'reloading');
230
+ }
231
+ }
232
+
233
+ _reloadTile(id: string, state: TileState) {
234
+ const tile = this._tiles[id];
235
+
236
+ // this potentially does not address all underlying
237
+ // issues https://github.com/mapbox/mapbox-gl-js/issues/4252
238
+ // - hard to tell without repro steps
239
+ if (!tile) return;
240
+
241
+ // The difference between "loading" tiles and "reloading" or "expired"
242
+ // tiles is that "reloading"/"expired" tiles are "renderable".
243
+ // Therefore, a "loading" tile cannot become a "reloading" tile without
244
+ // first becoming a "loaded" tile.
245
+ if (tile.state !== 'loading') {
246
+ tile.state = state;
247
+ }
248
+
249
+ this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state));
250
+ }
251
+
252
+ _tileLoaded(tile: Tile, id: string, previousState: TileState, err: ?Error) {
253
+ if (err) {
254
+ tile.state = 'errored';
255
+ if ((err: any).status !== 404) this._source.fire(new ErrorEvent(err, {tile}));
256
+ // continue to try loading parent/children tiles if a tile doesn't exist (404)
257
+ else this.update(this.transform);
258
+ return;
259
+ }
260
+
261
+ tile.timeAdded = browser.now();
262
+ if (previousState === 'expired') tile.refreshedUponExpiration = true;
263
+ this._setTileReloadTimer(id, tile);
264
+ if (this.getSource().type === 'raster-dem' && tile.dem) this._backfillDEM(tile);
265
+ this._state.initializeTileState(tile, this.map ? this.map.painter : null);
266
+
267
+ this._source.fire(new Event('data', {dataType: 'source', tile, coord: tile.tileID}));
268
+ }
269
+
270
+ /**
271
+ * For raster terrain source, backfill DEM to eliminate visible tile boundaries
272
+ * @private
273
+ */
274
+ _backfillDEM(tile: Tile) {
275
+ const renderables = this.getRenderableIds();
276
+ for (let i = 0; i < renderables.length; i++) {
277
+ const borderId = renderables[i];
278
+ if (tile.neighboringTiles && tile.neighboringTiles[borderId]) {
279
+ const borderTile = this.getTileByID(borderId);
280
+ fillBorder(tile, borderTile);
281
+ fillBorder(borderTile, tile);
282
+ }
283
+ }
284
+
285
+ function fillBorder(tile, borderTile) {
286
+ tile.needsHillshadePrepare = true;
287
+ let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;
288
+ const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;
289
+ const dim = Math.pow(2, tile.tileID.canonical.z);
290
+ const borderId = borderTile.tileID.key;
291
+ if (dx === 0 && dy === 0) return;
292
+
293
+ if (Math.abs(dy) > 1) {
294
+ return;
295
+ }
296
+ if (Math.abs(dx) > 1) {
297
+ // Adjust the delta coordinate for world wraparound.
298
+ if (Math.abs(dx + dim) === 1) {
299
+ dx += dim;
300
+ } else if (Math.abs(dx - dim) === 1) {
301
+ dx -= dim;
302
+ }
303
+ }
304
+ if (!borderTile.dem || !tile.dem) return;
305
+ tile.dem.backfillBorder(borderTile.dem, dx, dy);
306
+ if (tile.neighboringTiles && tile.neighboringTiles[borderId])
307
+ tile.neighboringTiles[borderId].backfilled = true;
308
+ }
309
+ }
310
+ /**
311
+ * Get a specific tile by TileID
312
+ * @private
313
+ */
314
+ getTile(tileID: OverscaledTileID): Tile {
315
+ return this.getTileByID(tileID.key);
316
+ }
317
+
318
+ /**
319
+ * Get a specific tile by id
320
+ * @private
321
+ */
322
+ getTileByID(id: string): Tile {
323
+ return this._tiles[id];
324
+ }
325
+
326
+ /**
327
+ * For a given set of tiles, retain children that are loaded and have a zoom
328
+ * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive)
329
+ * @private
330
+ */
331
+ _retainLoadedChildren(
332
+ idealTiles: {[_: any]: OverscaledTileID},
333
+ zoom: number,
334
+ maxCoveringZoom: number,
335
+ retain: {[_: any]: OverscaledTileID}
336
+ ) {
337
+ for (const id in this._tiles) {
338
+ let tile = this._tiles[id];
339
+
340
+ // only consider renderable tiles up to maxCoveringZoom
341
+ if (retain[id] ||
342
+ !tile.hasData() ||
343
+ tile.tileID.overscaledZ <= zoom ||
344
+ tile.tileID.overscaledZ > maxCoveringZoom
345
+ ) continue;
346
+
347
+ // loop through parents and retain the topmost loaded one if found
348
+ let topmostLoadedID = tile.tileID;
349
+ while (tile && tile.tileID.overscaledZ > zoom + 1) {
350
+ const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1);
351
+
352
+ tile = this._tiles[parentID.key];
353
+
354
+ if (tile && tile.hasData()) {
355
+ topmostLoadedID = parentID;
356
+ }
357
+ }
358
+
359
+ // loop through ancestors of the topmost loaded child to see if there's one that needed it
360
+ let tileID = topmostLoadedID;
361
+ while (tileID.overscaledZ > zoom) {
362
+ tileID = tileID.scaledTo(tileID.overscaledZ - 1);
363
+
364
+ if (idealTiles[tileID.key]) {
365
+ // found a parent that needed a loaded child; retain that child
366
+ retain[topmostLoadedID.key] = topmostLoadedID;
367
+ break;
368
+ }
369
+ }
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Find a loaded parent of the given tile (up to minCoveringZoom)
375
+ * @private
376
+ */
377
+ findLoadedParent(tileID: OverscaledTileID, minCoveringZoom: number): ?Tile {
378
+ if (tileID.key in this._loadedParentTiles) {
379
+ const parent = this._loadedParentTiles[tileID.key];
380
+ if (parent && parent.tileID.overscaledZ >= minCoveringZoom) {
381
+ return parent;
382
+ } else {
383
+ return null;
384
+ }
385
+ }
386
+ for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) {
387
+ const parentTileID = tileID.scaledTo(z);
388
+ const tile = this._getLoadedTile(parentTileID);
389
+ if (tile) {
390
+ return tile;
391
+ }
392
+ }
393
+ }
394
+
395
+ _getLoadedTile(tileID: OverscaledTileID): ?Tile {
396
+ const tile = this._tiles[tileID.key];
397
+ if (tile && tile.hasData()) {
398
+ return tile;
399
+ }
400
+ // TileCache ignores wrap in lookup.
401
+ const cachedTile = this._cache.getByKey(tileID.wrapped().key);
402
+ return cachedTile;
403
+ }
404
+
405
+ /**
406
+ * Resizes the tile cache based on the current viewport's size
407
+ * or the maxTileCacheSize option passed during map creation
408
+ *
409
+ * Larger viewports use more tiles and need larger caches. Larger viewports
410
+ * are more likely to be found on devices with more memory and on pages where
411
+ * the map is more important.
412
+ * @private
413
+ */
414
+ updateCacheSize(transform: Transform) {
415
+ const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1;
416
+ const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1;
417
+ const approxTilesInView = widthInTiles * heightInTiles;
418
+ const commonZoomRange = 5;
419
+
420
+ const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);
421
+ const maxSize = typeof this._maxTileCacheSize === 'number' ? Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;
422
+
423
+ this._cache.setMaxSize(maxSize);
424
+ }
425
+
426
+ handleWrapJump(lng: number) {
427
+ // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify
428
+ // which cppy of the world the tile belongs to. For example, at `lng: 10` you
429
+ // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1.
430
+ //
431
+ // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect
432
+ // to see the same thing on the screen (370 degrees and 10 degrees is the same
433
+ // place in the world) but all the TileIDs will have different wrap values.
434
+ //
435
+ // In order to make this transition seamless, we calculate the rounded difference of
436
+ // "worlds" between the last frame and the current frame. If the map panned by
437
+ // a world, then we can assign all the tiles new TileIDs with updated wrap values.
438
+ // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered
439
+ // in a different position.
440
+ //
441
+ // This enables us to reuse the tiles at more ideal locations and prevent flickering.
442
+ const prevLng = this._prevLng === undefined ? lng : this._prevLng;
443
+ const lngDifference = lng - prevLng;
444
+ const worldDifference = lngDifference / 360;
445
+ const wrapDelta = Math.round(worldDifference);
446
+ this._prevLng = lng;
447
+
448
+ if (wrapDelta) {
449
+ const tiles: {[_: string]: Tile} = {};
450
+ for (const key in this._tiles) {
451
+ const tile = this._tiles[key];
452
+ tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);
453
+ tiles[tile.tileID.key] = tile;
454
+ }
455
+ this._tiles = tiles;
456
+
457
+ // Reset tile reload timers
458
+ for (const id in this._timers) {
459
+ clearTimeout(this._timers[id]);
460
+ delete this._timers[id];
461
+ }
462
+ for (const id in this._tiles) {
463
+ const tile = this._tiles[id];
464
+ this._setTileReloadTimer(id, tile);
465
+ }
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Removes tiles that are outside the viewport and adds new tiles that
471
+ * are inside the viewport.
472
+ * @private
473
+ */
474
+ update(transform: Transform) {
475
+ this.transform = transform;
476
+ if (!this._sourceLoaded || this._paused) { return; }
477
+
478
+ this.updateCacheSize(transform);
479
+ this.handleWrapJump(this.transform.center.lng);
480
+
481
+ // Covered is a list of retained tiles who's areas are fully covered by other,
482
+ // better, retained tiles. They are not drawn separately.
483
+ this._coveredTiles = {};
484
+
485
+ let idealTileIDs;
486
+ if (!this.used) {
487
+ idealTileIDs = [];
488
+ } else if (this._source.tileID) {
489
+ idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID)
490
+ .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));
491
+ } else {
492
+ idealTileIDs = transform.coveringTiles({
493
+ tileSize: this._source.tileSize,
494
+ minzoom: this._source.minzoom,
495
+ maxzoom: this._source.maxzoom,
496
+ roundZoom: this._source.roundZoom,
497
+ reparseOverscaled: this._source.reparseOverscaled
498
+ });
499
+
500
+ if (this._source.hasTile) {
501
+ idealTileIDs = idealTileIDs.filter((coord) => (this._source.hasTile: any)(coord));
502
+ }
503
+ }
504
+
505
+ // Determine the overzooming/underzooming amounts.
506
+ const zoom = transform.coveringZoomLevel(this._source);
507
+ const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom);
508
+ const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom);
509
+
510
+ // Retain is a list of tiles that we shouldn't delete, even if they are not
511
+ // the most ideal tile for the current viewport. This may include tiles like
512
+ // parent or child tiles that are *already* loaded.
513
+ const retain = this._updateRetainedTiles(idealTileIDs, zoom);
514
+
515
+ if (isRasterType(this._source.type)) {
516
+ const parentsForFading: {[_: string]: OverscaledTileID} = {};
517
+ const fadingTiles = {};
518
+ const ids = Object.keys(retain);
519
+ for (const id of ids) {
520
+ const tileID = retain[id];
521
+ assert(tileID.key === id);
522
+
523
+ const tile = this._tiles[id];
524
+ if (!tile || tile.fadeEndTime && tile.fadeEndTime <= browser.now()) continue;
525
+
526
+ // if the tile is loaded but still fading in, find parents to cross-fade with it
527
+ const parentTile = this.findLoadedParent(tileID, minCoveringZoom);
528
+ if (parentTile) {
529
+ this._addTile(parentTile.tileID);
530
+ parentsForFading[parentTile.tileID.key] = parentTile.tileID;
531
+ }
532
+
533
+ fadingTiles[id] = tileID;
534
+ }
535
+
536
+ // for tiles that are still fading in, also find children to cross-fade with
537
+ this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain);
538
+
539
+ for (const id in parentsForFading) {
540
+ if (!retain[id]) {
541
+ // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own.
542
+ this._coveredTiles[id] = true;
543
+ retain[id] = parentsForFading[id];
544
+ }
545
+ }
546
+ }
547
+
548
+ for (const retainedId in retain) {
549
+ // Make sure retained tiles always clear any existing fade holds
550
+ // so that if they're removed again their fade timer starts fresh.
551
+ this._tiles[retainedId].clearFadeHold();
552
+ }
553
+
554
+ // Remove the tiles we don't need anymore.
555
+ const remove = keysDifference(this._tiles, retain);
556
+ for (const tileID of remove) {
557
+ const tile = this._tiles[tileID];
558
+ if (tile.hasSymbolBuckets && !tile.holdingForFade()) {
559
+ tile.setHoldDuration(this.map._fadeDuration);
560
+ } else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) {
561
+ this._removeTile(tileID);
562
+ }
563
+ }
564
+
565
+ // Construct a cache of loaded parents
566
+ this._updateLoadedParentTileCache();
567
+ }
568
+
569
+ releaseSymbolFadeTiles() {
570
+ for (const id in this._tiles) {
571
+ if (this._tiles[id].holdingForFade()) {
572
+ this._removeTile(id);
573
+ }
574
+ }
575
+ }
576
+
577
+ _updateRetainedTiles(idealTileIDs: Array<OverscaledTileID>, zoom: number): {[_: string]: OverscaledTileID} {
578
+ const retain: {[_: string]: OverscaledTileID} = {};
579
+ const checked: {[_: string]: boolean } = {};
580
+ const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom);
581
+ const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom);
582
+
583
+ const missingTiles = {};
584
+ for (const tileID of idealTileIDs) {
585
+ const tile = this._addTile(tileID);
586
+
587
+ // retain the tile even if it's not loaded because it's an ideal tile.
588
+ retain[tileID.key] = tileID;
589
+
590
+ if (tile.hasData()) continue;
591
+
592
+ if (zoom < this._source.maxzoom) {
593
+ // save missing tiles that potentially have loaded children
594
+ missingTiles[tileID.key] = tileID;
595
+ }
596
+ }
597
+
598
+ // retain any loaded children of ideal tiles up to maxCoveringZoom
599
+ this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain);
600
+
601
+ for (const tileID of idealTileIDs) {
602
+ let tile = this._tiles[tileID.key];
603
+
604
+ if (tile.hasData()) continue;
605
+
606
+ // The tile we require is not yet loaded or does not exist;
607
+ // Attempt to find children that fully cover it.
608
+
609
+ if (zoom + 1 > this._source.maxzoom) {
610
+ // We're looking for an overzoomed child tile.
611
+ const childCoord = tileID.children(this._source.maxzoom)[0];
612
+ const childTile = this.getTile(childCoord);
613
+ if (!!childTile && childTile.hasData()) {
614
+ retain[childCoord.key] = childCoord;
615
+ continue; // tile is covered by overzoomed child
616
+ }
617
+ } else {
618
+ // check if all 4 immediate children are loaded (i.e. the missing ideal tile is covered)
619
+ const children = tileID.children(this._source.maxzoom);
620
+
621
+ if (retain[children[0].key] &&
622
+ retain[children[1].key] &&
623
+ retain[children[2].key] &&
624
+ retain[children[3].key]) continue; // tile is covered by children
625
+ }
626
+
627
+ // We couldn't find child tiles that entirely cover the ideal tile; look for parents now.
628
+
629
+ // As we ascend up the tile pyramid of the ideal tile, we check whether the parent
630
+ // tile has been previously requested (and errored because we only loop over tiles with no data)
631
+ // in order to determine if we need to request its parent.
632
+ let parentWasRequested = tile.wasRequested();
633
+
634
+ for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {
635
+ const parentId = tileID.scaledTo(overscaledZ);
636
+
637
+ // Break parent tile ascent if this route has been previously checked by another child.
638
+ if (checked[parentId.key]) break;
639
+ checked[parentId.key] = true;
640
+
641
+ tile = this.getTile(parentId);
642
+ if (!tile && parentWasRequested) {
643
+ tile = this._addTile(parentId);
644
+ }
645
+ if (tile) {
646
+ retain[parentId.key] = parentId;
647
+ // Save the current values, since they're the parent of the next iteration
648
+ // of the parent tile ascent loop.
649
+ parentWasRequested = tile.wasRequested();
650
+ if (tile.hasData()) break;
651
+ }
652
+ }
653
+ }
654
+
655
+ return retain;
656
+ }
657
+
658
+ _updateLoadedParentTileCache() {
659
+ this._loadedParentTiles = {};
660
+
661
+ for (const tileKey in this._tiles) {
662
+ const path = [];
663
+ let parentTile: ?Tile;
664
+ let currentId = this._tiles[tileKey].tileID;
665
+
666
+ // Find the closest loaded ancestor by traversing the tile tree towards the root and
667
+ // caching results along the way
668
+ while (currentId.overscaledZ > 0) {
669
+
670
+ // Do we have a cached result from previous traversals?
671
+ if (currentId.key in this._loadedParentTiles) {
672
+ parentTile = this._loadedParentTiles[currentId.key];
673
+ break;
674
+ }
675
+
676
+ path.push(currentId.key);
677
+
678
+ // Is the parent loaded?
679
+ const parentId = currentId.scaledTo(currentId.overscaledZ - 1);
680
+ parentTile = this._getLoadedTile(parentId);
681
+ if (parentTile) {
682
+ break;
683
+ }
684
+
685
+ currentId = parentId;
686
+ }
687
+
688
+ // Cache the result of this traversal to all newly visited tiles
689
+ for (const key of path) {
690
+ this._loadedParentTiles[key] = parentTile;
691
+ }
692
+ }
693
+ }
694
+
695
+ /**
696
+ * Add a tile, given its coordinate, to the pyramid.
697
+ * @private
698
+ */
699
+ _addTile(tileID: OverscaledTileID): Tile {
700
+ let tile = this._tiles[tileID.key];
701
+ if (tile)
702
+ return tile;
703
+
704
+ tile = this._cache.getAndRemove(tileID);
705
+ if (tile) {
706
+ this._setTileReloadTimer(tileID.key, tile);
707
+ // set the tileID because the cached tile could have had a different wrap value
708
+ tile.tileID = tileID;
709
+ this._state.initializeTileState(tile, this.map ? this.map.painter : null);
710
+ if (this._cacheTimers[tileID.key]) {
711
+ clearTimeout(this._cacheTimers[tileID.key]);
712
+ delete this._cacheTimers[tileID.key];
713
+ this._setTileReloadTimer(tileID.key, tile);
714
+ }
715
+ }
716
+
717
+ const cached = Boolean(tile);
718
+ if (!cached) {
719
+ tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor());
720
+ this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));
721
+ }
722
+
723
+ // Impossible, but silence flow.
724
+ if (!tile) return (null: any);
725
+
726
+ tile.uses++;
727
+ this._tiles[tileID.key] = tile;
728
+ if (!cached) this._source.fire(new Event('dataloading', {tile, coord: tile.tileID, dataType: 'source'}));
729
+
730
+ return tile;
731
+ }
732
+
733
+ _setTileReloadTimer(id: string, tile: Tile) {
734
+ if (id in this._timers) {
735
+ clearTimeout(this._timers[id]);
736
+ delete this._timers[id];
737
+ }
738
+
739
+ const expiryTimeout = tile.getExpiryTimeout();
740
+ if (expiryTimeout) {
741
+ this._timers[id] = setTimeout(() => {
742
+ this._reloadTile(id, 'expired');
743
+ delete this._timers[id];
744
+ }, expiryTimeout);
745
+ }
746
+ }
747
+
748
+ /**
749
+ * Remove a tile, given its id, from the pyramid
750
+ * @private
751
+ */
752
+ _removeTile(id: string) {
753
+ const tile = this._tiles[id];
754
+ if (!tile)
755
+ return;
756
+
757
+ tile.uses--;
758
+ delete this._tiles[id];
759
+ if (this._timers[id]) {
760
+ clearTimeout(this._timers[id]);
761
+ delete this._timers[id];
762
+ }
763
+
764
+ if (tile.uses > 0)
765
+ return;
766
+
767
+ if (tile.hasData() && tile.state !== 'reloading') {
768
+ this._cache.add(tile.tileID, tile, tile.getExpiryTimeout());
769
+ } else {
770
+ tile.aborted = true;
771
+ this._abortTile(tile);
772
+ this._unloadTile(tile);
773
+ }
774
+ }
775
+
776
+ /**
777
+ * Remove all tiles from this pyramid
778
+ */
779
+ clearTiles() {
780
+ this._shouldReloadOnResume = false;
781
+ this._paused = false;
782
+
783
+ for (const id in this._tiles)
784
+ this._removeTile(id);
785
+
786
+ this._cache.reset();
787
+ }
788
+
789
+ /**
790
+ * Search through our current tiles and attempt to find the tiles that
791
+ * cover the given bounds.
792
+ * @param pointQueryGeometry coordinates of the corners of bounding rectangle
793
+ * @returns {Array<Object>} result items have {tile, minX, maxX, minY, maxY}, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile.
794
+ * @private
795
+ */
796
+ tilesIn(pointQueryGeometry: Array<Point>, maxPitchScaleFactor: number, has3DLayer: boolean) {
797
+
798
+ const tileResults = [];
799
+
800
+ const transform = this.transform;
801
+ if (!transform) return tileResults;
802
+
803
+ const cameraPointQueryGeometry = has3DLayer ?
804
+ transform.getCameraQueryGeometry(pointQueryGeometry) :
805
+ pointQueryGeometry;
806
+
807
+ const queryGeometry = pointQueryGeometry.map((p) => transform.pointCoordinate(p));
808
+ const cameraQueryGeometry = cameraPointQueryGeometry.map((p) => transform.pointCoordinate(p));
809
+
810
+ const ids = this.getIds();
811
+
812
+ let minX = Infinity;
813
+ let minY = Infinity;
814
+ let maxX = -Infinity;
815
+ let maxY = -Infinity;
816
+
817
+ for (const p of cameraQueryGeometry) {
818
+ minX = Math.min(minX, p.x);
819
+ minY = Math.min(minY, p.y);
820
+ maxX = Math.max(maxX, p.x);
821
+ maxY = Math.max(maxY, p.y);
822
+ }
823
+
824
+ for (let i = 0; i < ids.length; i++) {
825
+ const tile = this._tiles[ids[i]];
826
+ if (tile.holdingForFade()) {
827
+ // Tiles held for fading are covered by tiles that are closer to ideal
828
+ continue;
829
+ }
830
+ const tileID = tile.tileID;
831
+ const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);
832
+ const queryPadding = maxPitchScaleFactor * tile.queryPadding * EXTENT / tile.tileSize / scale;
833
+
834
+ const tileSpaceBounds = [
835
+ tileID.getTilePoint(new MercatorCoordinate(minX, minY)),
836
+ tileID.getTilePoint(new MercatorCoordinate(maxX, maxY))
837
+ ];
838
+
839
+ if (tileSpaceBounds[0].x - queryPadding < EXTENT && tileSpaceBounds[0].y - queryPadding < EXTENT &&
840
+ tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) {
841
+
842
+ const tileSpaceQueryGeometry: Array<Point> = queryGeometry.map((c) => tileID.getTilePoint(c));
843
+ const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c));
844
+
845
+ tileResults.push({
846
+ tile,
847
+ tileID,
848
+ queryGeometry: tileSpaceQueryGeometry,
849
+ cameraQueryGeometry: tileSpaceCameraQueryGeometry,
850
+ scale
851
+ });
852
+ }
853
+ }
854
+
855
+ return tileResults;
856
+ }
857
+
858
+ getVisibleCoordinates(symbolLayer?: boolean): Array<OverscaledTileID> {
859
+ const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID);
860
+ for (const coord of coords) {
861
+ coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped());
862
+ }
863
+ return coords;
864
+ }
865
+
866
+ hasTransition() {
867
+ if (this._source.hasTransition()) {
868
+ return true;
869
+ }
870
+
871
+ if (isRasterType(this._source.type)) {
872
+ for (const id in this._tiles) {
873
+ const tile = this._tiles[id];
874
+ if (tile.fadeEndTime !== undefined && tile.fadeEndTime >= browser.now()) {
875
+ return true;
876
+ }
877
+ }
878
+ }
879
+
880
+ return false;
881
+ }
882
+
883
+ /**
884
+ * Set the value of a particular state for a feature
885
+ * @private
886
+ */
887
+ setFeatureState(sourceLayer?: string, featureId: number | string, state: Object) {
888
+ sourceLayer = sourceLayer || '_geojsonTileLayer';
889
+ this._state.updateState(sourceLayer, featureId, state);
890
+ }
891
+
892
+ /**
893
+ * Resets the value of a particular state key for a feature
894
+ * @private
895
+ */
896
+ removeFeatureState(sourceLayer?: string, featureId?: number | string, key?: string) {
897
+ sourceLayer = sourceLayer || '_geojsonTileLayer';
898
+ this._state.removeFeatureState(sourceLayer, featureId, key);
899
+ }
900
+
901
+ /**
902
+ * Get the entire state object for a feature
903
+ * @private
904
+ */
905
+ getFeatureState(sourceLayer?: string, featureId: number | string) {
906
+ sourceLayer = sourceLayer || '_geojsonTileLayer';
907
+ return this._state.getState(sourceLayer, featureId);
908
+ }
909
+
910
+ /**
911
+ * Sets the set of keys that the tile depends on. This allows tiles to
912
+ * be reloaded when their dependencies change.
913
+ * @private
914
+ */
915
+ setDependencies(tileKey: string, namespace: string, dependencies: Array<string>) {
916
+ const tile = this._tiles[tileKey];
917
+ if (tile) {
918
+ tile.setDependencies(namespace, dependencies);
919
+ }
920
+ }
921
+
922
+ /**
923
+ * Reloads all tiles that depend on the given keys.
924
+ * @private
925
+ */
926
+ reloadTilesForDependencies(namespaces: Array<string>, keys: Array<string>) {
927
+ for (const id in this._tiles) {
928
+ const tile = this._tiles[id];
929
+ if (tile.hasDependency(namespaces, keys)) {
930
+ this._reloadTile(id, 'reloading');
931
+ }
932
+ }
933
+ this._cache.filter(tile => !tile.hasDependency(namespaces, keys));
934
+ }
935
+ }
936
+
937
+ SourceCache.maxOverzooming = 10;
938
+ SourceCache.maxUnderzooming = 3;
939
+
940
+ function compareTileId(a: OverscaledTileID, b: OverscaledTileID): number {
941
+ // Different copies of the world are sorted based on their distance to the center.
942
+ // Wrap values are converted to unsigned distances by reserving odd number for copies
943
+ // with negative wrap and even numbers for copies with positive wrap.
944
+ const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0);
945
+ const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0);
946
+ return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x;
947
+ }
948
+
949
+ function isRasterType(type) {
950
+ return type === 'raster' || type === 'image' || type === 'video';
951
+ }
952
+
953
+ export default SourceCache;
node_modules/mapbox-gl/src/source/source_state.js ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {extend} from '../util/util';
4
+ import Tile from './tile';
5
+ import type {FeatureState} from '../style-spec/expression';
6
+
7
+ export type FeatureStates = {[feature_id: string]: FeatureState};
8
+ export type LayerFeatureStates = {[layer: string]: FeatureStates};
9
+
10
+ /**
11
+ * SourceFeatureState manages the state and pending changes
12
+ * to features in a source, separated by source layer.
13
+ * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively)
14
+ * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's
15
+ * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations.
16
+ * In deletedStates, all null's denote complete removal of state at that scope
17
+ * @private
18
+ */
19
+ class SourceFeatureState {
20
+ state: LayerFeatureStates;
21
+ stateChanges: LayerFeatureStates;
22
+ deletedStates: {};
23
+
24
+ constructor() {
25
+ this.state = {};
26
+ this.stateChanges = {};
27
+ this.deletedStates = {};
28
+ }
29
+
30
+ updateState(sourceLayer: string, featureId: number | string, newState: Object) {
31
+ const feature = String(featureId);
32
+ this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {};
33
+ this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {};
34
+ extend(this.stateChanges[sourceLayer][feature], newState);
35
+
36
+ if (this.deletedStates[sourceLayer] === null) {
37
+ this.deletedStates[sourceLayer] = {};
38
+ for (const ft in this.state[sourceLayer]) {
39
+ if (ft !== feature) this.deletedStates[sourceLayer][ft] = null;
40
+ }
41
+ } else {
42
+ const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null;
43
+ if (featureDeletionQueued) {
44
+ this.deletedStates[sourceLayer][feature] = {};
45
+ for (const prop in this.state[sourceLayer][feature]) {
46
+ if (!newState[prop]) this.deletedStates[sourceLayer][feature][prop] = null;
47
+ }
48
+ } else {
49
+ for (const key in newState) {
50
+ const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null;
51
+ if (deletionInQueue) delete this.deletedStates[sourceLayer][feature][key];
52
+ }
53
+ }
54
+ }
55
+ }
56
+
57
+ removeFeatureState(sourceLayer: string, featureId?: number | string, key?: string) {
58
+ const sourceLayerDeleted = this.deletedStates[sourceLayer] === null;
59
+ if (sourceLayerDeleted) return;
60
+
61
+ const feature = String(featureId);
62
+
63
+ this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {};
64
+
65
+ if (key && featureId !== undefined) {
66
+ if (this.deletedStates[sourceLayer][feature] !== null) {
67
+ this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {};
68
+ this.deletedStates[sourceLayer][feature][key] = null;
69
+ }
70
+ } else if (featureId !== undefined) {
71
+ const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature];
72
+ if (updateInQueue) {
73
+ this.deletedStates[sourceLayer][feature] = {};
74
+ for (key in this.stateChanges[sourceLayer][feature]) this.deletedStates[sourceLayer][feature][key] = null;
75
+
76
+ } else {
77
+ this.deletedStates[sourceLayer][feature] = null;
78
+ }
79
+ } else {
80
+ this.deletedStates[sourceLayer] = null;
81
+ }
82
+
83
+ }
84
+
85
+ getState(sourceLayer: string, featureId: number | string) {
86
+ const feature = String(featureId);
87
+ const base = this.state[sourceLayer] || {};
88
+ const changes = this.stateChanges[sourceLayer] || {};
89
+
90
+ const reconciledState = extend({}, base[feature], changes[feature]);
91
+
92
+ //return empty object if the whole source layer is awaiting deletion
93
+ if (this.deletedStates[sourceLayer] === null) return {};
94
+ else if (this.deletedStates[sourceLayer]) {
95
+ const featureDeletions = this.deletedStates[sourceLayer][featureId];
96
+ if (featureDeletions === null) return {};
97
+ for (const prop in featureDeletions) delete reconciledState[prop];
98
+ }
99
+ return reconciledState;
100
+ }
101
+
102
+ initializeTileState(tile: Tile, painter: any) {
103
+ tile.setFeatureState(this.state, painter);
104
+ }
105
+
106
+ coalesceChanges(tiles: {[_: any]: Tile}, painter: any) {
107
+ //track changes with full state objects, but only for features that got modified
108
+ const featuresChanged: LayerFeatureStates = {};
109
+
110
+ for (const sourceLayer in this.stateChanges) {
111
+ this.state[sourceLayer] = this.state[sourceLayer] || {};
112
+ const layerStates = {};
113
+ for (const feature in this.stateChanges[sourceLayer]) {
114
+ if (!this.state[sourceLayer][feature]) this.state[sourceLayer][feature] = {};
115
+ extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);
116
+ layerStates[feature] = this.state[sourceLayer][feature];
117
+ }
118
+ featuresChanged[sourceLayer] = layerStates;
119
+ }
120
+
121
+ for (const sourceLayer in this.deletedStates) {
122
+ this.state[sourceLayer] = this.state[sourceLayer] || {};
123
+ const layerStates = {};
124
+
125
+ if (this.deletedStates[sourceLayer] === null) {
126
+ for (const ft in this.state[sourceLayer]) {
127
+ layerStates[ft] = {};
128
+ this.state[sourceLayer][ft] = {};
129
+ }
130
+ } else {
131
+ for (const feature in this.deletedStates[sourceLayer]) {
132
+ const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null;
133
+ if (deleteWholeFeatureState) this.state[sourceLayer][feature] = {};
134
+ else {
135
+ for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) {
136
+ delete this.state[sourceLayer][feature][key];
137
+ }
138
+ }
139
+ layerStates[feature] = this.state[sourceLayer][feature];
140
+ }
141
+ }
142
+
143
+ featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {};
144
+ extend(featuresChanged[sourceLayer], layerStates);
145
+ }
146
+
147
+ this.stateChanges = {};
148
+ this.deletedStates = {};
149
+
150
+ if (Object.keys(featuresChanged).length === 0) return;
151
+
152
+ for (const id in tiles) {
153
+ const tile = tiles[id];
154
+ tile.setFeatureState(featuresChanged, painter);
155
+ }
156
+ }
157
+ }
158
+
159
+ export default SourceFeatureState;
node_modules/mapbox-gl/src/source/tile.js ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {uniqueId, parseCacheControl} from '../util/util';
4
+ import {deserialize as deserializeBucket} from '../data/bucket';
5
+ import FeatureIndex from '../data/feature_index';
6
+ import GeoJSONFeature from '../util/vectortile_to_geojson';
7
+ import featureFilter from '../style-spec/feature_filter';
8
+ import SymbolBucket from '../data/bucket/symbol_bucket';
9
+ import {CollisionBoxArray} from '../data/array_types';
10
+ import Texture from '../render/texture';
11
+ import browser from '../util/browser';
12
+ import toEvaluationFeature from '../data/evaluation_feature';
13
+ import EvaluationParameters from '../style/evaluation_parameters';
14
+ import SourceFeatureState from '../source/source_state';
15
+ import {lazyLoadRTLTextPlugin} from './rtl_text_plugin';
16
+
17
+ const CLOCK_SKEW_RETRY_TIMEOUT = 30000;
18
+
19
+ import type {Bucket} from '../data/bucket';
20
+ import type StyleLayer from '../style/style_layer';
21
+ import type {WorkerTileResult} from './worker_source';
22
+ import type Actor from '../util/actor';
23
+ import type DEMData from '../data/dem_data';
24
+ import type {AlphaImage} from '../util/image';
25
+ import type ImageAtlas from '../render/image_atlas';
26
+ import type ImageManager from '../render/image_manager';
27
+ import type Context from '../gl/context';
28
+ import type {OverscaledTileID} from './tile_id';
29
+ import type Framebuffer from '../gl/framebuffer';
30
+ import type Transform from '../geo/transform';
31
+ import type {LayerFeatureStates} from './source_state';
32
+ import type {Cancelable} from '../types/cancelable';
33
+ import type {FilterSpecification} from '../style-spec/types';
34
+
35
+ export type TileState =
36
+ | 'loading' // Tile data is in the process of loading.
37
+ | 'loaded' // Tile data has been loaded. Tile can be rendered.
38
+ | 'reloading' // Tile data has been loaded and is being updated. Tile can be rendered.
39
+ | 'unloaded' // Tile data has been deleted.
40
+ | 'errored' // Tile data was not loaded because of an error.
41
+ | 'expired'; /* Tile data was previously loaded, but has expired per its
42
+ * HTTP headers and is in the process of refreshing. */
43
+
44
+ /**
45
+ * A tile object is the combination of a Coordinate, which defines
46
+ * its place, as well as a unique ID and data tracking for its content
47
+ *
48
+ * @private
49
+ */
50
+ class Tile {
51
+ tileID: OverscaledTileID;
52
+ uid: number;
53
+ uses: number;
54
+ tileSize: number;
55
+ buckets: {[_: string]: Bucket};
56
+ latestFeatureIndex: ?FeatureIndex;
57
+ latestRawTileData: ?ArrayBuffer;
58
+ imageAtlas: ?ImageAtlas;
59
+ imageAtlasTexture: Texture;
60
+ glyphAtlasImage: ?AlphaImage;
61
+ glyphAtlasTexture: Texture;
62
+ expirationTime: any;
63
+ expiredRequestCount: number;
64
+ state: TileState;
65
+ timeAdded: any;
66
+ fadeEndTime: any;
67
+ collisionBoxArray: ?CollisionBoxArray;
68
+ redoWhenDone: boolean;
69
+ showCollisionBoxes: boolean;
70
+ placementSource: any;
71
+ actor: ?Actor;
72
+ vtLayers: {[_: string]: VectorTileLayer};
73
+
74
+ neighboringTiles: ?Object;
75
+ dem: ?DEMData;
76
+ aborted: ?boolean;
77
+ needsHillshadePrepare: ?boolean;
78
+ request: ?Cancelable;
79
+ texture: any;
80
+ fbo: ?Framebuffer;
81
+ demTexture: ?Texture;
82
+ refreshedUponExpiration: boolean;
83
+ reloadCallback: any;
84
+ resourceTiming: ?Array<PerformanceResourceTiming>;
85
+ queryPadding: number;
86
+
87
+ symbolFadeHoldUntil: ?number;
88
+ hasSymbolBuckets: boolean;
89
+ hasRTLText: boolean;
90
+ dependencies: Object;
91
+
92
+ /**
93
+ * @param {OverscaledTileID} tileID
94
+ * @param size
95
+ * @private
96
+ */
97
+ constructor(tileID: OverscaledTileID, size: number) {
98
+ this.tileID = tileID;
99
+ this.uid = uniqueId();
100
+ this.uses = 0;
101
+ this.tileSize = size;
102
+ this.buckets = {};
103
+ this.expirationTime = null;
104
+ this.queryPadding = 0;
105
+ this.hasSymbolBuckets = false;
106
+ this.hasRTLText = false;
107
+ this.dependencies = {};
108
+
109
+ // Counts the number of times a response was already expired when
110
+ // received. We're using this to add a delay when making a new request
111
+ // so we don't have to keep retrying immediately in case of a server
112
+ // serving expired tiles.
113
+ this.expiredRequestCount = 0;
114
+
115
+ this.state = 'loading';
116
+ }
117
+
118
+ registerFadeDuration(duration: number) {
119
+ const fadeEndTime = duration + this.timeAdded;
120
+ if (fadeEndTime < browser.now()) return;
121
+ if (this.fadeEndTime && fadeEndTime < this.fadeEndTime) return;
122
+
123
+ this.fadeEndTime = fadeEndTime;
124
+ }
125
+
126
+ wasRequested() {
127
+ return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading';
128
+ }
129
+
130
+ /**
131
+ * Given a data object with a 'buffers' property, load it into
132
+ * this tile's elementGroups and buffers properties and set loaded
133
+ * to true. If the data is null, like in the case of an empty
134
+ * GeoJSON tile, no-op but still set loaded to true.
135
+ * @param {Object} data
136
+ * @param painter
137
+ * @returns {undefined}
138
+ * @private
139
+ */
140
+ loadVectorData(data: WorkerTileResult, painter: any, justReloaded: ?boolean) {
141
+ if (this.hasData()) {
142
+ this.unloadVectorData();
143
+ }
144
+
145
+ this.state = 'loaded';
146
+
147
+ // empty GeoJSON tile
148
+ if (!data) {
149
+ this.collisionBoxArray = new CollisionBoxArray();
150
+ return;
151
+ }
152
+
153
+ if (data.featureIndex) {
154
+ this.latestFeatureIndex = data.featureIndex;
155
+ if (data.rawTileData) {
156
+ // Only vector tiles have rawTileData, and they won't update it for
157
+ // 'reloadTile'
158
+ this.latestRawTileData = data.rawTileData;
159
+ this.latestFeatureIndex.rawTileData = data.rawTileData;
160
+ } else if (this.latestRawTileData) {
161
+ // If rawTileData hasn't updated, hold onto a pointer to the last
162
+ // one we received
163
+ this.latestFeatureIndex.rawTileData = this.latestRawTileData;
164
+ }
165
+ }
166
+ this.collisionBoxArray = data.collisionBoxArray;
167
+ this.buckets = deserializeBucket(data.buckets, painter.style);
168
+
169
+ this.hasSymbolBuckets = false;
170
+ for (const id in this.buckets) {
171
+ const bucket = this.buckets[id];
172
+ if (bucket instanceof SymbolBucket) {
173
+ this.hasSymbolBuckets = true;
174
+ if (justReloaded) {
175
+ bucket.justReloaded = true;
176
+ } else {
177
+ break;
178
+ }
179
+ }
180
+ }
181
+
182
+ this.hasRTLText = false;
183
+ if (this.hasSymbolBuckets) {
184
+ for (const id in this.buckets) {
185
+ const bucket = this.buckets[id];
186
+ if (bucket instanceof SymbolBucket) {
187
+ if (bucket.hasRTLText) {
188
+ this.hasRTLText = true;
189
+ lazyLoadRTLTextPlugin();
190
+ break;
191
+ }
192
+ }
193
+ }
194
+ }
195
+
196
+ this.queryPadding = 0;
197
+ for (const id in this.buckets) {
198
+ const bucket = this.buckets[id];
199
+ this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket));
200
+ }
201
+
202
+ if (data.imageAtlas) {
203
+ this.imageAtlas = data.imageAtlas;
204
+ }
205
+ if (data.glyphAtlasImage) {
206
+ this.glyphAtlasImage = data.glyphAtlasImage;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Release any data or WebGL resources referenced by this tile.
212
+ * @returns {undefined}
213
+ * @private
214
+ */
215
+ unloadVectorData() {
216
+ for (const id in this.buckets) {
217
+ this.buckets[id].destroy();
218
+ }
219
+ this.buckets = {};
220
+
221
+ if (this.imageAtlasTexture) {
222
+ this.imageAtlasTexture.destroy();
223
+ }
224
+
225
+ if (this.imageAtlas) {
226
+ this.imageAtlas = null;
227
+ }
228
+
229
+ if (this.glyphAtlasTexture) {
230
+ this.glyphAtlasTexture.destroy();
231
+ }
232
+
233
+ this.latestFeatureIndex = null;
234
+ this.state = 'unloaded';
235
+ }
236
+
237
+ getBucket(layer: StyleLayer) {
238
+ return this.buckets[layer.id];
239
+ }
240
+
241
+ upload(context: Context) {
242
+ for (const id in this.buckets) {
243
+ const bucket = this.buckets[id];
244
+ if (bucket.uploadPending()) {
245
+ bucket.upload(context);
246
+ }
247
+ }
248
+
249
+ const gl = context.gl;
250
+ if (this.imageAtlas && !this.imageAtlas.uploaded) {
251
+ this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA);
252
+ this.imageAtlas.uploaded = true;
253
+ }
254
+
255
+ if (this.glyphAtlasImage) {
256
+ this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA);
257
+ this.glyphAtlasImage = null;
258
+ }
259
+ }
260
+
261
+ prepare(imageManager: ImageManager) {
262
+ if (this.imageAtlas) {
263
+ this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);
264
+ }
265
+ }
266
+
267
+ // Queries non-symbol features rendered for this tile.
268
+ // Symbol features are queried globally
269
+ queryRenderedFeatures(layers: {[_: string]: StyleLayer},
270
+ serializedLayers: {[string]: Object},
271
+ sourceFeatureState: SourceFeatureState,
272
+ queryGeometry: Array<Point>,
273
+ cameraQueryGeometry: Array<Point>,
274
+ scale: number,
275
+ params: { filter: FilterSpecification, layers: Array<string>, availableImages: Array<string> },
276
+ transform: Transform,
277
+ maxPitchScaleFactor: number,
278
+ pixelPosMatrix: Float32Array): {[_: string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>} {
279
+ if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData)
280
+ return {};
281
+
282
+ return this.latestFeatureIndex.query({
283
+ queryGeometry,
284
+ cameraQueryGeometry,
285
+ scale,
286
+ tileSize: this.tileSize,
287
+ pixelPosMatrix,
288
+ transform,
289
+ params,
290
+ queryPadding: this.queryPadding * maxPitchScaleFactor
291
+ }, layers, serializedLayers, sourceFeatureState);
292
+ }
293
+
294
+ querySourceFeatures(result: Array<GeoJSONFeature>, params: any) {
295
+ const featureIndex = this.latestFeatureIndex;
296
+ if (!featureIndex || !featureIndex.rawTileData) return;
297
+
298
+ const vtLayers = featureIndex.loadVTLayers();
299
+
300
+ const sourceLayer = params ? params.sourceLayer : '';
301
+ const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer];
302
+
303
+ if (!layer) return;
304
+
305
+ const filter = featureFilter(params && params.filter);
306
+ const {z, x, y} = this.tileID.canonical;
307
+ const coord = {z, x, y};
308
+
309
+ for (let i = 0; i < layer.length; i++) {
310
+ const feature = layer.feature(i);
311
+ if (filter.needGeometry) {
312
+ const evaluationFeature = toEvaluationFeature(feature, true);
313
+ if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue;
314
+ } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {
315
+ continue;
316
+ }
317
+ const id = featureIndex.getId(feature, sourceLayer);
318
+ const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id);
319
+ (geojsonFeature: any).tile = coord;
320
+ result.push(geojsonFeature);
321
+ }
322
+ }
323
+
324
+ hasData() {
325
+ return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired';
326
+ }
327
+
328
+ patternsLoaded() {
329
+ return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;
330
+ }
331
+
332
+ setExpiryData(data: any) {
333
+ const prior = this.expirationTime;
334
+
335
+ if (data.cacheControl) {
336
+ const parsedCC = parseCacheControl(data.cacheControl);
337
+ if (parsedCC['max-age']) this.expirationTime = Date.now() + parsedCC['max-age'] * 1000;
338
+ } else if (data.expires) {
339
+ this.expirationTime = new Date(data.expires).getTime();
340
+ }
341
+
342
+ if (this.expirationTime) {
343
+ const now = Date.now();
344
+ let isExpired = false;
345
+
346
+ if (this.expirationTime > now) {
347
+ isExpired = false;
348
+ } else if (!prior) {
349
+ isExpired = true;
350
+ } else if (this.expirationTime < prior) {
351
+ // Expiring date is going backwards:
352
+ // fall back to exponential backoff
353
+ isExpired = true;
354
+
355
+ } else {
356
+ const delta = this.expirationTime - prior;
357
+
358
+ if (!delta) {
359
+ // Server is serving the same expired resource over and over: fall
360
+ // back to exponential backoff.
361
+ isExpired = true;
362
+
363
+ } else {
364
+ // Assume that either the client or the server clock is wrong and
365
+ // try to interpolate a valid expiration date (from the client POV)
366
+ // observing a minimum timeout.
367
+ this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);
368
+
369
+ }
370
+ }
371
+
372
+ if (isExpired) {
373
+ this.expiredRequestCount++;
374
+ this.state = 'expired';
375
+ } else {
376
+ this.expiredRequestCount = 0;
377
+ }
378
+ }
379
+ }
380
+
381
+ getExpiryTimeout() {
382
+ if (this.expirationTime) {
383
+ if (this.expiredRequestCount) {
384
+ return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31));
385
+ } else {
386
+ // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly
387
+ return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1);
388
+ }
389
+ }
390
+ }
391
+
392
+ setFeatureState(states: LayerFeatureStates, painter: any) {
393
+ if (!this.latestFeatureIndex ||
394
+ !this.latestFeatureIndex.rawTileData ||
395
+ Object.keys(states).length === 0) {
396
+ return;
397
+ }
398
+
399
+ const vtLayers = this.latestFeatureIndex.loadVTLayers();
400
+
401
+ for (const id in this.buckets) {
402
+ if (!painter.style.hasLayer(id)) continue;
403
+
404
+ const bucket = this.buckets[id];
405
+ // Buckets are grouped by common source-layer
406
+ const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer';
407
+ const sourceLayer = vtLayers[sourceLayerId];
408
+ const sourceLayerStates = states[sourceLayerId];
409
+ if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) continue;
410
+
411
+ bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {});
412
+ const layer = painter && painter.style && painter.style.getLayer(id);
413
+ if (layer) {
414
+ this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));
415
+ }
416
+ }
417
+ }
418
+
419
+ holdingForFade(): boolean {
420
+ return this.symbolFadeHoldUntil !== undefined;
421
+ }
422
+
423
+ symbolFadeFinished(): boolean {
424
+ return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now();
425
+ }
426
+
427
+ clearFadeHold() {
428
+ this.symbolFadeHoldUntil = undefined;
429
+ }
430
+
431
+ setHoldDuration(duration: number) {
432
+ this.symbolFadeHoldUntil = browser.now() + duration;
433
+ }
434
+
435
+ setDependencies(namespace: string, dependencies: Array<string>) {
436
+ const index = {};
437
+ for (const dep of dependencies) {
438
+ index[dep] = true;
439
+ }
440
+ this.dependencies[namespace] = index;
441
+ }
442
+
443
+ hasDependency(namespaces: Array<string>, keys: Array<string>) {
444
+ for (const namespace of namespaces) {
445
+ const dependencies = this.dependencies[namespace];
446
+ if (dependencies) {
447
+ for (const key of keys) {
448
+ if (dependencies[key]) {
449
+ return true;
450
+ }
451
+ }
452
+ }
453
+ }
454
+ return false;
455
+ }
456
+ }
457
+
458
+ export default Tile;
node_modules/mapbox-gl/src/source/tile_bounds.js ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import LngLatBounds from '../geo/lng_lat_bounds';
4
+ import {mercatorXfromLng, mercatorYfromLat} from '../geo/mercator_coordinate';
5
+
6
+ import type {CanonicalTileID} from './tile_id';
7
+
8
+ class TileBounds {
9
+ bounds: LngLatBounds;
10
+ minzoom: number;
11
+ maxzoom: number;
12
+
13
+ constructor(bounds: [number, number, number, number], minzoom: ?number, maxzoom: ?number) {
14
+ this.bounds = LngLatBounds.convert(this.validateBounds(bounds));
15
+ this.minzoom = minzoom || 0;
16
+ this.maxzoom = maxzoom || 24;
17
+ }
18
+
19
+ validateBounds(bounds: [number, number, number, number]) {
20
+ // make sure the bounds property contains valid longitude and latitudes
21
+ if (!Array.isArray(bounds) || bounds.length !== 4) return [-180, -90, 180, 90];
22
+ return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])];
23
+ }
24
+
25
+ contains(tileID: CanonicalTileID) {
26
+ const worldSize = Math.pow(2, tileID.z);
27
+ const level = {
28
+ minX: Math.floor(mercatorXfromLng(this.bounds.getWest()) * worldSize),
29
+ minY: Math.floor(mercatorYfromLat(this.bounds.getNorth()) * worldSize),
30
+ maxX: Math.ceil(mercatorXfromLng(this.bounds.getEast()) * worldSize),
31
+ maxY: Math.ceil(mercatorYfromLat(this.bounds.getSouth()) * worldSize)
32
+ };
33
+ const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;
34
+ return hit;
35
+ }
36
+ }
37
+
38
+ export default TileBounds;
node_modules/mapbox-gl/src/source/tile_cache.js ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {OverscaledTileID} from './tile_id';
4
+ import type Tile from './tile';
5
+
6
+ /**
7
+ * A [least-recently-used cache](http://en.wikipedia.org/wiki/Cache_algorithms)
8
+ * with hash lookup made possible by keeping a list of keys in parallel to
9
+ * an array of dictionary of values
10
+ *
11
+ * @private
12
+ */
13
+ class TileCache {
14
+ max: number;
15
+ data: {[key: string]: Array<{ value: Tile, timeout: ?TimeoutID}>};
16
+ order: Array<string>;
17
+ onRemove: (element: Tile) => void;
18
+ /**
19
+ * @param {number} max number of permitted values
20
+ * @param {Function} onRemove callback called with items when they expire
21
+ */
22
+ constructor(max: number, onRemove: (element: Tile) => void) {
23
+ this.max = max;
24
+ this.onRemove = onRemove;
25
+ this.reset();
26
+ }
27
+
28
+ /**
29
+ * Clear the cache
30
+ *
31
+ * @returns {TileCache} this cache
32
+ * @private
33
+ */
34
+ reset() {
35
+ for (const key in this.data) {
36
+ for (const removedData of this.data[key]) {
37
+ if (removedData.timeout) clearTimeout(removedData.timeout);
38
+ this.onRemove(removedData.value);
39
+ }
40
+ }
41
+
42
+ this.data = {};
43
+ this.order = [];
44
+
45
+ return this;
46
+ }
47
+
48
+ /**
49
+ * Add a key, value combination to the cache, trimming its size if this pushes
50
+ * it over max length.
51
+ *
52
+ * @param {OverscaledTileID} tileID lookup key for the item
53
+ * @param {*} data any value
54
+ *
55
+ * @returns {TileCache} this cache
56
+ * @private
57
+ */
58
+ add(tileID: OverscaledTileID, data: Tile, expiryTimeout: number | void) {
59
+ const key = tileID.wrapped().key;
60
+ if (this.data[key] === undefined) {
61
+ this.data[key] = [];
62
+ }
63
+
64
+ const dataWrapper = {
65
+ value: data,
66
+ timeout: undefined
67
+ };
68
+
69
+ if (expiryTimeout !== undefined) {
70
+ dataWrapper.timeout = setTimeout(() => {
71
+ this.remove(tileID, dataWrapper);
72
+ }, expiryTimeout);
73
+ }
74
+
75
+ this.data[key].push(dataWrapper);
76
+ this.order.push(key);
77
+
78
+ if (this.order.length > this.max) {
79
+ const removedData = this._getAndRemoveByKey(this.order[0]);
80
+ if (removedData) this.onRemove(removedData);
81
+ }
82
+
83
+ return this;
84
+ }
85
+
86
+ /**
87
+ * Determine whether the value attached to `key` is present
88
+ *
89
+ * @param {OverscaledTileID} tileID the key to be looked-up
90
+ * @returns {boolean} whether the cache has this value
91
+ * @private
92
+ */
93
+ has(tileID: OverscaledTileID): boolean {
94
+ return tileID.wrapped().key in this.data;
95
+ }
96
+
97
+ /**
98
+ * Get the value attached to a specific key and remove data from cache.
99
+ * If the key is not found, returns `null`
100
+ *
101
+ * @param {OverscaledTileID} tileID the key to look up
102
+ * @returns {*} the data, or null if it isn't found
103
+ * @private
104
+ */
105
+ getAndRemove(tileID: OverscaledTileID): ?Tile {
106
+ if (!this.has(tileID)) { return null; }
107
+ return this._getAndRemoveByKey(tileID.wrapped().key);
108
+ }
109
+
110
+ /*
111
+ * Get and remove the value with the specified key.
112
+ */
113
+ _getAndRemoveByKey(key: string): ?Tile {
114
+ const data = this.data[key].shift();
115
+ if (data.timeout) clearTimeout(data.timeout);
116
+
117
+ if (this.data[key].length === 0) {
118
+ delete this.data[key];
119
+ }
120
+ this.order.splice(this.order.indexOf(key), 1);
121
+
122
+ return data.value;
123
+ }
124
+
125
+ /*
126
+ * Get the value with the specified (wrapped tile) key.
127
+ */
128
+ getByKey(key: string): ?Tile {
129
+ const data = this.data[key];
130
+ return data ? data[0].value : null;
131
+ }
132
+
133
+ /**
134
+ * Get the value attached to a specific key without removing data
135
+ * from the cache. If the key is not found, returns `null`
136
+ *
137
+ * @param {OverscaledTileID} tileID the key to look up
138
+ * @returns {*} the data, or null if it isn't found
139
+ * @private
140
+ */
141
+ get(tileID: OverscaledTileID): ?Tile {
142
+ if (!this.has(tileID)) { return null; }
143
+
144
+ const data = this.data[tileID.wrapped().key][0];
145
+ return data.value;
146
+ }
147
+
148
+ /**
149
+ * Remove a key/value combination from the cache.
150
+ *
151
+ * @param {OverscaledTileID} tileID the key for the pair to delete
152
+ * @param {Tile} value If a value is provided, remove that exact version of the value.
153
+ * @returns {TileCache} this cache
154
+ * @private
155
+ */
156
+ remove(tileID: OverscaledTileID, value: ?{ value: Tile, timeout: ?TimeoutID}) {
157
+ if (!this.has(tileID)) { return this; }
158
+ const key = tileID.wrapped().key;
159
+
160
+ const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value);
161
+ const data = this.data[key][dataIndex];
162
+ this.data[key].splice(dataIndex, 1);
163
+ if (data.timeout) clearTimeout(data.timeout);
164
+ if (this.data[key].length === 0) {
165
+ delete this.data[key];
166
+ }
167
+ this.onRemove(data.value);
168
+ this.order.splice(this.order.indexOf(key), 1);
169
+
170
+ return this;
171
+ }
172
+
173
+ /**
174
+ * Change the max size of the cache.
175
+ *
176
+ * @param {number} max the max size of the cache
177
+ * @returns {TileCache} this cache
178
+ * @private
179
+ */
180
+ setMaxSize(max: number): TileCache {
181
+ this.max = max;
182
+
183
+ while (this.order.length > this.max) {
184
+ const removedData = this._getAndRemoveByKey(this.order[0]);
185
+ if (removedData) this.onRemove(removedData);
186
+ }
187
+
188
+ return this;
189
+ }
190
+
191
+ /**
192
+ * Remove entries that do not pass a filter function. Used for removing
193
+ * stale tiles from the cache.
194
+ *
195
+ * @param {function} filterFn Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out.
196
+ */
197
+ filter(filterFn: (tile: Tile) => boolean) {
198
+ const removed = [];
199
+ for (const key in this.data) {
200
+ for (const entry of this.data[key]) {
201
+ if (!filterFn(entry.value)) {
202
+ removed.push(entry);
203
+ }
204
+ }
205
+ }
206
+ for (const r of removed) {
207
+ this.remove(r.value.tileID, r);
208
+ }
209
+ }
210
+ }
211
+
212
+ export default TileCache;
node_modules/mapbox-gl/src/source/tile_id.js ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {getTileBBox} from '@mapbox/whoots-js';
4
+ import EXTENT from '../data/extent';
5
+ import Point from '@mapbox/point-geometry';
6
+ import MercatorCoordinate from '../geo/mercator_coordinate';
7
+
8
+ import assert from 'assert';
9
+ import {register} from '../util/web_worker_transfer';
10
+
11
+ export class CanonicalTileID {
12
+ z: number;
13
+ x: number;
14
+ y: number;
15
+ key: string;
16
+
17
+ constructor(z: number, x: number, y: number) {
18
+ assert(z >= 0 && z <= 25);
19
+ assert(x >= 0 && x < Math.pow(2, z));
20
+ assert(y >= 0 && y < Math.pow(2, z));
21
+ this.z = z;
22
+ this.x = x;
23
+ this.y = y;
24
+ this.key = calculateKey(0, z, z, x, y);
25
+ }
26
+
27
+ equals(id: CanonicalTileID) {
28
+ return this.z === id.z && this.x === id.x && this.y === id.y;
29
+ }
30
+
31
+ // given a list of urls, choose a url template and return a tile URL
32
+ url(urls: Array<string>, scheme: ?string) {
33
+ const bbox = getTileBBox(this.x, this.y, this.z);
34
+ const quadkey = getQuadkey(this.z, this.x, this.y);
35
+
36
+ return urls[(this.x + this.y) % urls.length]
37
+ .replace('{prefix}', (this.x % 16).toString(16) + (this.y % 16).toString(16))
38
+ .replace('{z}', String(this.z))
39
+ .replace('{x}', String(this.x))
40
+ .replace('{y}', String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y))
41
+ .replace('{quadkey}', quadkey)
42
+ .replace('{bbox-epsg-3857}', bbox);
43
+ }
44
+
45
+ getTilePoint(coord: MercatorCoordinate) {
46
+ const tilesAtZoom = Math.pow(2, this.z);
47
+ return new Point(
48
+ (coord.x * tilesAtZoom - this.x) * EXTENT,
49
+ (coord.y * tilesAtZoom - this.y) * EXTENT);
50
+ }
51
+
52
+ toString() {
53
+ return `${this.z}/${this.x}/${this.y}`;
54
+ }
55
+ }
56
+
57
+ export class UnwrappedTileID {
58
+ wrap: number;
59
+ canonical: CanonicalTileID;
60
+ key: string;
61
+
62
+ constructor(wrap: number, canonical: CanonicalTileID) {
63
+ this.wrap = wrap;
64
+ this.canonical = canonical;
65
+ this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y);
66
+ }
67
+ }
68
+
69
+ export class OverscaledTileID {
70
+ overscaledZ: number;
71
+ wrap: number;
72
+ canonical: CanonicalTileID;
73
+ key: string;
74
+ posMatrix: Float32Array;
75
+
76
+ constructor(overscaledZ: number, wrap: number, z: number, x: number, y: number) {
77
+ assert(overscaledZ >= z);
78
+ this.overscaledZ = overscaledZ;
79
+ this.wrap = wrap;
80
+ this.canonical = new CanonicalTileID(z, +x, +y);
81
+ this.key = calculateKey(wrap, overscaledZ, z, x, y);
82
+ }
83
+
84
+ equals(id: OverscaledTileID) {
85
+ return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical);
86
+ }
87
+
88
+ scaledTo(targetZ: number) {
89
+ assert(targetZ <= this.overscaledZ);
90
+ const zDifference = this.canonical.z - targetZ;
91
+ if (targetZ > this.canonical.z) {
92
+ return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);
93
+ } else {
94
+ return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);
95
+ }
96
+ }
97
+
98
+ /*
99
+ * calculateScaledKey is an optimization:
100
+ * when withWrap == true, implements the same as this.scaledTo(z).key,
101
+ * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key.
102
+ */
103
+ calculateScaledKey(targetZ: number, withWrap: boolean): string {
104
+ assert(targetZ <= this.overscaledZ);
105
+ const zDifference = this.canonical.z - targetZ;
106
+ if (targetZ > this.canonical.z) {
107
+ return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);
108
+ } else {
109
+ return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);
110
+ }
111
+ }
112
+
113
+ isChildOf(parent: OverscaledTileID) {
114
+ if (parent.wrap !== this.wrap) {
115
+ // We can't be a child if we're in a different world copy
116
+ return false;
117
+ }
118
+ const zDifference = this.canonical.z - parent.canonical.z;
119
+ // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined.
120
+ return parent.overscaledZ === 0 || (
121
+ parent.overscaledZ < this.overscaledZ &&
122
+ parent.canonical.x === (this.canonical.x >> zDifference) &&
123
+ parent.canonical.y === (this.canonical.y >> zDifference));
124
+ }
125
+
126
+ children(sourceMaxZoom: number) {
127
+ if (this.overscaledZ >= sourceMaxZoom) {
128
+ // return a single tile coord representing a an overscaled tile
129
+ return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];
130
+ }
131
+
132
+ const z = this.canonical.z + 1;
133
+ const x = this.canonical.x * 2;
134
+ const y = this.canonical.y * 2;
135
+ return [
136
+ new OverscaledTileID(z, this.wrap, z, x, y),
137
+ new OverscaledTileID(z, this.wrap, z, x + 1, y),
138
+ new OverscaledTileID(z, this.wrap, z, x, y + 1),
139
+ new OverscaledTileID(z, this.wrap, z, x + 1, y + 1)
140
+ ];
141
+ }
142
+
143
+ isLessThan(rhs: OverscaledTileID) {
144
+ if (this.wrap < rhs.wrap) return true;
145
+ if (this.wrap > rhs.wrap) return false;
146
+
147
+ if (this.overscaledZ < rhs.overscaledZ) return true;
148
+ if (this.overscaledZ > rhs.overscaledZ) return false;
149
+
150
+ if (this.canonical.x < rhs.canonical.x) return true;
151
+ if (this.canonical.x > rhs.canonical.x) return false;
152
+
153
+ if (this.canonical.y < rhs.canonical.y) return true;
154
+ return false;
155
+ }
156
+
157
+ wrapped() {
158
+ return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);
159
+ }
160
+
161
+ unwrapTo(wrap: number) {
162
+ return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y);
163
+ }
164
+
165
+ overscaleFactor() {
166
+ return Math.pow(2, this.overscaledZ - this.canonical.z);
167
+ }
168
+
169
+ toUnwrapped() {
170
+ return new UnwrappedTileID(this.wrap, this.canonical);
171
+ }
172
+
173
+ toString() {
174
+ return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`;
175
+ }
176
+
177
+ getTilePoint(coord: MercatorCoordinate) {
178
+ return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y));
179
+ }
180
+ }
181
+
182
+ function calculateKey(wrap: number, overscaledZ: number, z: number, x: number, y: number): string {
183
+ wrap *= 2;
184
+ if (wrap < 0) wrap = wrap * -1 - 1;
185
+ const dim = 1 << z;
186
+ return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36);
187
+ }
188
+
189
+ function getQuadkey(z, x, y) {
190
+ let quadkey = '', mask;
191
+ for (let i = z; i > 0; i--) {
192
+ mask = 1 << (i - 1);
193
+ quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0));
194
+ }
195
+ return quadkey;
196
+ }
197
+
198
+ register('CanonicalTileID', CanonicalTileID);
199
+ register('OverscaledTileID', OverscaledTileID, {omit: ['posMatrix']});
node_modules/mapbox-gl/src/source/vector_tile_source.js ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {Event, ErrorEvent, Evented} from '../util/evented';
4
+
5
+ import {extend, pick} from '../util/util';
6
+ import loadTileJSON from './load_tilejson';
7
+ import {postTurnstileEvent, postMapLoadEvent} from '../util/mapbox';
8
+ import TileBounds from './tile_bounds';
9
+ import {ResourceType} from '../util/ajax';
10
+ import browser from '../util/browser';
11
+ import {cacheEntryPossiblyAdded} from '../util/tile_request_cache';
12
+
13
+ import type {Source} from './source';
14
+ import type {OverscaledTileID} from './tile_id';
15
+ import type Map from '../ui/map';
16
+ import type Dispatcher from '../util/dispatcher';
17
+ import type Tile from './tile';
18
+ import type {Callback} from '../types/callback';
19
+ import type {Cancelable} from '../types/cancelable';
20
+ import type {VectorSourceSpecification, PromoteIdSpecification} from '../style-spec/types';
21
+
22
+ /**
23
+ * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/).
24
+ * (See the [Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector) for detailed documentation of options.)
25
+ *
26
+ * @example
27
+ * map.addSource('some id', {
28
+ * type: 'vector',
29
+ * url: 'mapbox://mapbox.mapbox-streets-v6'
30
+ * });
31
+ *
32
+ * @example
33
+ * map.addSource('some id', {
34
+ * type: 'vector',
35
+ * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'],
36
+ * minzoom: 6,
37
+ * maxzoom: 14
38
+ * });
39
+ *
40
+ * @example
41
+ * map.getSource('some id').setUrl("mapbox://mapbox.mapbox-streets-v6");
42
+ *
43
+ * @example
44
+ * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']);
45
+ * @see [Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/)
46
+ * @see [Add a third party vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/third-party/)
47
+ */
48
+ class VectorTileSource extends Evented implements Source {
49
+ type: 'vector';
50
+ id: string;
51
+ minzoom: number;
52
+ maxzoom: number;
53
+ url: string;
54
+ scheme: string;
55
+ tileSize: number;
56
+ promoteId: ?PromoteIdSpecification;
57
+
58
+ _options: VectorSourceSpecification;
59
+ _collectResourceTiming: boolean;
60
+ dispatcher: Dispatcher;
61
+ map: Map;
62
+ bounds: ?[number, number, number, number];
63
+ tiles: Array<string>;
64
+ tileBounds: TileBounds;
65
+ reparseOverscaled: boolean;
66
+ isTileClipped: boolean;
67
+ _tileJSONRequest: ?Cancelable;
68
+ _loaded: boolean;
69
+
70
+ constructor(id: string, options: VectorSourceSpecification & {collectResourceTiming: boolean}, dispatcher: Dispatcher, eventedParent: Evented) {
71
+ super();
72
+ this.id = id;
73
+ this.dispatcher = dispatcher;
74
+
75
+ this.type = 'vector';
76
+ this.minzoom = 0;
77
+ this.maxzoom = 22;
78
+ this.scheme = 'xyz';
79
+ this.tileSize = 512;
80
+ this.reparseOverscaled = true;
81
+ this.isTileClipped = true;
82
+ this._loaded = false;
83
+
84
+ extend(this, pick(options, ['url', 'scheme', 'tileSize', 'promoteId']));
85
+ this._options = extend({type: 'vector'}, options);
86
+
87
+ this._collectResourceTiming = options.collectResourceTiming;
88
+
89
+ if (this.tileSize !== 512) {
90
+ throw new Error('vector tile sources must have a tileSize of 512');
91
+ }
92
+
93
+ this.setEventedParent(eventedParent);
94
+ }
95
+
96
+ load() {
97
+ this._loaded = false;
98
+ this.fire(new Event('dataloading', {dataType: 'source'}));
99
+ this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => {
100
+ this._tileJSONRequest = null;
101
+ this._loaded = true;
102
+ if (err) {
103
+ this.fire(new ErrorEvent(err));
104
+ } else if (tileJSON) {
105
+ extend(this, tileJSON);
106
+ if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
107
+ postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken);
108
+ postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken, this.map._requestManager._customAccessToken);
109
+
110
+ // `content` is included here to prevent a race condition where `Style#_updateSources` is called
111
+ // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives
112
+ // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088
113
+ this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));
114
+ this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'}));
115
+ }
116
+ });
117
+ }
118
+
119
+ loaded(): boolean {
120
+ return this._loaded;
121
+ }
122
+
123
+ hasTile(tileID: OverscaledTileID) {
124
+ return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
125
+ }
126
+
127
+ onAdd(map: Map) {
128
+ this.map = map;
129
+ this.load();
130
+ }
131
+
132
+ setSourceProperty(callback: Function) {
133
+ if (this._tileJSONRequest) {
134
+ this._tileJSONRequest.cancel();
135
+ }
136
+
137
+ callback();
138
+
139
+ const sourceCache = this.map.style.sourceCaches[this.id];
140
+ sourceCache.clearTiles();
141
+ this.load();
142
+ }
143
+
144
+ /**
145
+ * Sets the source `tiles` property and re-renders the map.
146
+ *
147
+ * @param {string[]} tiles An array of one or more tile source URLs, as in the TileJSON spec.
148
+ * @returns {VectorTileSource} this
149
+ */
150
+ setTiles(tiles: Array<string>) {
151
+ this.setSourceProperty(() => {
152
+ this._options.tiles = tiles;
153
+ });
154
+
155
+ return this;
156
+ }
157
+
158
+ /**
159
+ * Sets the source `url` property and re-renders the map.
160
+ *
161
+ * @param {string} url A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://<Tileset ID>`.
162
+ * @returns {VectorTileSource} this
163
+ */
164
+ setUrl(url: string) {
165
+ this.setSourceProperty(() => {
166
+ this.url = url;
167
+ this._options.url = url;
168
+ });
169
+
170
+ return this;
171
+ }
172
+
173
+ onRemove() {
174
+ if (this._tileJSONRequest) {
175
+ this._tileJSONRequest.cancel();
176
+ this._tileJSONRequest = null;
177
+ }
178
+ }
179
+
180
+ serialize() {
181
+ return extend({}, this._options);
182
+ }
183
+
184
+ loadTile(tile: Tile, callback: Callback<void>) {
185
+ const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme));
186
+ const params = {
187
+ request: this.map._requestManager.transformRequest(url, ResourceType.Tile),
188
+ uid: tile.uid,
189
+ tileID: tile.tileID,
190
+ zoom: tile.tileID.overscaledZ,
191
+ tileSize: this.tileSize * tile.tileID.overscaleFactor(),
192
+ type: this.type,
193
+ source: this.id,
194
+ pixelRatio: browser.devicePixelRatio,
195
+ showCollisionBoxes: this.map.showCollisionBoxes,
196
+ promoteId: this.promoteId
197
+ };
198
+ params.request.collectResourceTiming = this._collectResourceTiming;
199
+
200
+ if (!tile.actor || tile.state === 'expired') {
201
+ tile.actor = this.dispatcher.getActor();
202
+ tile.request = tile.actor.send('loadTile', params, done.bind(this));
203
+ } else if (tile.state === 'loading') {
204
+ // schedule tile reloading after it has been loaded
205
+ tile.reloadCallback = callback;
206
+ } else {
207
+ tile.request = tile.actor.send('reloadTile', params, done.bind(this));
208
+ }
209
+
210
+ function done(err, data) {
211
+ delete tile.request;
212
+
213
+ if (tile.aborted)
214
+ return callback(null);
215
+
216
+ if (err && err.status !== 404) {
217
+ return callback(err);
218
+ }
219
+
220
+ if (data && data.resourceTiming)
221
+ tile.resourceTiming = data.resourceTiming;
222
+
223
+ if (this.map._refreshExpiredTiles && data) tile.setExpiryData(data);
224
+ tile.loadVectorData(data, this.map.painter);
225
+
226
+ cacheEntryPossiblyAdded(this.dispatcher);
227
+
228
+ callback(null);
229
+
230
+ if (tile.reloadCallback) {
231
+ this.loadTile(tile, tile.reloadCallback);
232
+ tile.reloadCallback = null;
233
+ }
234
+ }
235
+ }
236
+
237
+ abortTile(tile: Tile) {
238
+ if (tile.request) {
239
+ tile.request.cancel();
240
+ delete tile.request;
241
+ }
242
+ if (tile.actor) {
243
+ tile.actor.send('abortTile', {uid: tile.uid, type: this.type, source: this.id}, undefined);
244
+ }
245
+ }
246
+
247
+ unloadTile(tile: Tile) {
248
+ tile.unloadVectorData();
249
+ if (tile.actor) {
250
+ tile.actor.send('removeTile', {uid: tile.uid, type: this.type, source: this.id}, undefined);
251
+ }
252
+ }
253
+
254
+ hasTransition() {
255
+ return false;
256
+ }
257
+ }
258
+
259
+ export default VectorTileSource;
node_modules/mapbox-gl/src/source/vector_tile_worker_source.js ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {getArrayBuffer} from '../util/ajax';
4
+
5
+ import vt from '@mapbox/vector-tile';
6
+ import Protobuf from 'pbf';
7
+ import WorkerTile from './worker_tile';
8
+ import {extend} from '../util/util';
9
+ import {RequestPerformance} from '../util/performance';
10
+
11
+ import type {
12
+ WorkerSource,
13
+ WorkerTileParameters,
14
+ WorkerTileCallback,
15
+ TileParameters
16
+ } from '../source/worker_source';
17
+
18
+ import type Actor from '../util/actor';
19
+ import type StyleLayerIndex from '../style/style_layer_index';
20
+ import type {Callback} from '../types/callback';
21
+
22
+ export type LoadVectorTileResult = {
23
+ vectorTile: VectorTile;
24
+ rawData: ArrayBuffer;
25
+ expires?: any;
26
+ cacheControl?: any;
27
+ resourceTiming?: Array<PerformanceResourceTiming>;
28
+ };
29
+
30
+ /**
31
+ * @callback LoadVectorDataCallback
32
+ * @param error
33
+ * @param vectorTile
34
+ * @private
35
+ */
36
+ export type LoadVectorDataCallback = Callback<?LoadVectorTileResult>;
37
+
38
+ export type AbortVectorData = () => void;
39
+ export type LoadVectorData = (params: WorkerTileParameters, callback: LoadVectorDataCallback) => ?AbortVectorData;
40
+
41
+ /**
42
+ * @private
43
+ */
44
+ function loadVectorTile(params: WorkerTileParameters, callback: LoadVectorDataCallback) {
45
+ const request = getArrayBuffer(params.request, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => {
46
+ if (err) {
47
+ callback(err);
48
+ } else if (data) {
49
+ callback(null, {
50
+ vectorTile: new vt.VectorTile(new Protobuf(data)),
51
+ rawData: data,
52
+ cacheControl,
53
+ expires
54
+ });
55
+ }
56
+ });
57
+ return () => {
58
+ request.cancel();
59
+ callback();
60
+ };
61
+ }
62
+
63
+ /**
64
+ * The {@link WorkerSource} implementation that supports {@link VectorTileSource}.
65
+ * This class is designed to be easily reused to support custom source types
66
+ * for data formats that can be parsed/converted into an in-memory VectorTile
67
+ * representation. To do so, create it with
68
+ * `new VectorTileWorkerSource(actor, styleLayers, customLoadVectorDataFunction)`.
69
+ *
70
+ * @private
71
+ */
72
+ class VectorTileWorkerSource implements WorkerSource {
73
+ actor: Actor;
74
+ layerIndex: StyleLayerIndex;
75
+ availableImages: Array<string>;
76
+ loadVectorData: LoadVectorData;
77
+ loading: {[_: string]: WorkerTile };
78
+ loaded: {[_: string]: WorkerTile };
79
+
80
+ /**
81
+ * @param [loadVectorData] Optional method for custom loading of a VectorTile
82
+ * object based on parameters passed from the main-thread Source. See
83
+ * {@link VectorTileWorkerSource#loadTile}. The default implementation simply
84
+ * loads the pbf at `params.url`.
85
+ * @private
86
+ */
87
+ constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array<string>, loadVectorData: ?LoadVectorData) {
88
+ this.actor = actor;
89
+ this.layerIndex = layerIndex;
90
+ this.availableImages = availableImages;
91
+ this.loadVectorData = loadVectorData || loadVectorTile;
92
+ this.loading = {};
93
+ this.loaded = {};
94
+ }
95
+
96
+ /**
97
+ * Implements {@link WorkerSource#loadTile}. Delegates to
98
+ * {@link VectorTileWorkerSource#loadVectorData} (which by default expects
99
+ * a `params.url` property) for fetching and producing a VectorTile object.
100
+ * @private
101
+ */
102
+ loadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {
103
+ const uid = params.uid;
104
+
105
+ if (!this.loading)
106
+ this.loading = {};
107
+
108
+ const perf = (params && params.request && params.request.collectResourceTiming) ?
109
+ new RequestPerformance(params.request) : false;
110
+
111
+ const workerTile = this.loading[uid] = new WorkerTile(params);
112
+ workerTile.abort = this.loadVectorData(params, (err, response) => {
113
+ delete this.loading[uid];
114
+
115
+ if (err || !response) {
116
+ workerTile.status = 'done';
117
+ this.loaded[uid] = workerTile;
118
+ return callback(err);
119
+ }
120
+
121
+ const rawTileData = response.rawData;
122
+ const cacheControl = {};
123
+ if (response.expires) cacheControl.expires = response.expires;
124
+ if (response.cacheControl) cacheControl.cacheControl = response.cacheControl;
125
+
126
+ const resourceTiming = {};
127
+ if (perf) {
128
+ const resourceTimingData = perf.finish();
129
+ // it's necessary to eval the result of getEntriesByName() here via parse/stringify
130
+ // late evaluation in the main thread causes TypeError: illegal invocation
131
+ if (resourceTimingData)
132
+ resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData));
133
+ }
134
+
135
+ workerTile.vectorTile = response.vectorTile;
136
+ workerTile.parse(response.vectorTile, this.layerIndex, this.availableImages, this.actor, (err, result) => {
137
+ if (err || !result) return callback(err);
138
+
139
+ // Transferring a copy of rawTileData because the worker needs to retain its copy.
140
+ callback(null, extend({rawTileData: rawTileData.slice(0)}, result, cacheControl, resourceTiming));
141
+ });
142
+
143
+ this.loaded = this.loaded || {};
144
+ this.loaded[uid] = workerTile;
145
+ });
146
+ }
147
+
148
+ /**
149
+ * Implements {@link WorkerSource#reloadTile}.
150
+ * @private
151
+ */
152
+ reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {
153
+ const loaded = this.loaded,
154
+ uid = params.uid,
155
+ vtSource = this;
156
+ if (loaded && loaded[uid]) {
157
+ const workerTile = loaded[uid];
158
+ workerTile.showCollisionBoxes = params.showCollisionBoxes;
159
+
160
+ const done = (err, data) => {
161
+ const reloadCallback = workerTile.reloadCallback;
162
+ if (reloadCallback) {
163
+ delete workerTile.reloadCallback;
164
+ workerTile.parse(workerTile.vectorTile, vtSource.layerIndex, this.availableImages, vtSource.actor, reloadCallback);
165
+ }
166
+ callback(err, data);
167
+ };
168
+
169
+ if (workerTile.status === 'parsing') {
170
+ workerTile.reloadCallback = done;
171
+ } else if (workerTile.status === 'done') {
172
+ // if there was no vector tile data on the initial load, don't try and re-parse tile
173
+ if (workerTile.vectorTile) {
174
+ workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, done);
175
+ } else {
176
+ done();
177
+ }
178
+ }
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Implements {@link WorkerSource#abortTile}.
184
+ *
185
+ * @param params
186
+ * @param params.uid The UID for this tile.
187
+ * @private
188
+ */
189
+ abortTile(params: TileParameters, callback: WorkerTileCallback) {
190
+ const loading = this.loading,
191
+ uid = params.uid;
192
+ if (loading && loading[uid] && loading[uid].abort) {
193
+ loading[uid].abort();
194
+ delete loading[uid];
195
+ }
196
+ callback();
197
+ }
198
+
199
+ /**
200
+ * Implements {@link WorkerSource#removeTile}.
201
+ *
202
+ * @param params
203
+ * @param params.uid The UID for this tile.
204
+ * @private
205
+ */
206
+ removeTile(params: TileParameters, callback: WorkerTileCallback) {
207
+ const loaded = this.loaded,
208
+ uid = params.uid;
209
+ if (loaded && loaded[uid]) {
210
+ delete loaded[uid];
211
+ }
212
+ callback();
213
+ }
214
+ }
215
+
216
+ export default VectorTileWorkerSource;
node_modules/mapbox-gl/src/source/video_source.js ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {getVideo, ResourceType} from '../util/ajax';
4
+
5
+ import ImageSource from './image_source';
6
+ import rasterBoundsAttributes from '../data/raster_bounds_attributes';
7
+ import SegmentVector from '../data/segment';
8
+ import Texture from '../render/texture';
9
+ import {ErrorEvent} from '../util/evented';
10
+ import ValidationError from '../style-spec/error/validation_error';
11
+
12
+ import type Map from '../ui/map';
13
+ import type Dispatcher from '../util/dispatcher';
14
+ import type {Evented} from '../util/evented';
15
+ import type {VideoSourceSpecification} from '../style-spec/types';
16
+
17
+ /**
18
+ * A data source containing video.
19
+ * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-video) for detailed documentation of options.)
20
+ *
21
+ * @example
22
+ * // add to map
23
+ * map.addSource('some id', {
24
+ * type: 'video',
25
+ * url: [
26
+ * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',
27
+ * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'
28
+ * ],
29
+ * coordinates: [
30
+ * [-76.54, 39.18],
31
+ * [-76.52, 39.18],
32
+ * [-76.52, 39.17],
33
+ * [-76.54, 39.17]
34
+ * ]
35
+ * });
36
+ *
37
+ * // update
38
+ * var mySource = map.getSource('some id');
39
+ * mySource.setCoordinates([
40
+ * [-76.54335737228394, 39.18579907229748],
41
+ * [-76.52803659439087, 39.1838364847587],
42
+ * [-76.5295386314392, 39.17683392507606],
43
+ * [-76.54520273208618, 39.17876344106642]
44
+ * ]);
45
+ *
46
+ * map.removeSource('some id'); // remove
47
+ * @see [Add a video](https://www.mapbox.com/mapbox-gl-js/example/video-on-a-map/)
48
+ */
49
+ class VideoSource extends ImageSource {
50
+ options: VideoSourceSpecification;
51
+ urls: Array<string>;
52
+ video: HTMLVideoElement;
53
+ roundZoom: boolean;
54
+
55
+ /**
56
+ * @private
57
+ */
58
+ constructor(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {
59
+ super(id, options, dispatcher, eventedParent);
60
+ this.roundZoom = true;
61
+ this.type = 'video';
62
+ this.options = options;
63
+ }
64
+
65
+ load() {
66
+ this._loaded = false;
67
+ const options = this.options;
68
+
69
+ this.urls = [];
70
+ for (const url of options.urls) {
71
+ this.urls.push(this.map._requestManager.transformRequest(url, ResourceType.Source).url);
72
+ }
73
+
74
+ getVideo(this.urls, (err, video) => {
75
+ this._loaded = true;
76
+ if (err) {
77
+ this.fire(new ErrorEvent(err));
78
+ } else if (video) {
79
+ this.video = video;
80
+ this.video.loop = true;
81
+
82
+ // Prevent the video from taking over the screen in iOS
83
+ this.video.setAttribute('playsinline', '');
84
+
85
+ // Start repainting when video starts playing. hasTransition() will then return
86
+ // true to trigger additional frames as long as the videos continues playing.
87
+ this.video.addEventListener('playing', () => {
88
+ this.map.triggerRepaint();
89
+ });
90
+
91
+ if (this.map) {
92
+ this.video.play();
93
+ }
94
+
95
+ this._finishLoading();
96
+ }
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Pauses the video.
102
+ */
103
+ pause() {
104
+ if (this.video) {
105
+ this.video.pause();
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Plays the video.
111
+ */
112
+ play() {
113
+ if (this.video) {
114
+ this.video.play();
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Sets playback to a timestamp, in seconds.
120
+ * @private
121
+ */
122
+ seek(seconds: number) {
123
+ if (this.video) {
124
+ const seekableRange = this.video.seekable;
125
+ if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) {
126
+ this.fire(new ErrorEvent(new ValidationError(`sources.${this.id}`, null, `Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`)));
127
+ } else this.video.currentTime = seconds;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Returns the HTML `video` element.
133
+ *
134
+ * @returns {HTMLVideoElement} The HTML `video` element.
135
+ */
136
+ getVideo() {
137
+ return this.video;
138
+ }
139
+
140
+ onAdd(map: Map) {
141
+ if (this.map) return;
142
+ this.map = map;
143
+ this.load();
144
+ if (this.video) {
145
+ this.video.play();
146
+ this.setCoordinates(this.coordinates);
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Sets the video's coordinates and re-renders the map.
152
+ *
153
+ * @method setCoordinates
154
+ * @instance
155
+ * @memberof VideoSource
156
+ * @returns {VideoSource} this
157
+ */
158
+ // setCoordinates inherited from ImageSource
159
+
160
+ prepare() {
161
+ if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) {
162
+ return; // not enough data for current position
163
+ }
164
+
165
+ const context = this.map.painter.context;
166
+ const gl = context.gl;
167
+
168
+ if (!this.boundsBuffer) {
169
+ this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);
170
+ }
171
+
172
+ if (!this.boundsSegments) {
173
+ this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
174
+ }
175
+
176
+ if (!this.texture) {
177
+ this.texture = new Texture(context, this.video, gl.RGBA);
178
+ this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
179
+ } else if (!this.video.paused) {
180
+ this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
181
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video);
182
+ }
183
+
184
+ for (const w in this.tiles) {
185
+ const tile = this.tiles[w];
186
+ if (tile.state !== 'loaded') {
187
+ tile.state = 'loaded';
188
+ tile.texture = this.texture;
189
+ }
190
+ }
191
+ }
192
+
193
+ serialize() {
194
+ return {
195
+ type: 'video',
196
+ urls: this.urls,
197
+ coordinates: this.coordinates
198
+ };
199
+ }
200
+
201
+ hasTransition() {
202
+ return this.video && !this.video.paused;
203
+ }
204
+ }
205
+
206
+ export default VideoSource;
node_modules/mapbox-gl/src/source/worker.js ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import Actor from '../util/actor';
4
+
5
+ import StyleLayerIndex from '../style/style_layer_index';
6
+ import VectorTileWorkerSource from './vector_tile_worker_source';
7
+ import RasterDEMTileWorkerSource from './raster_dem_tile_worker_source';
8
+ import GeoJSONWorkerSource from './geojson_worker_source';
9
+ import assert from 'assert';
10
+ import {plugin as globalRTLTextPlugin} from './rtl_text_plugin';
11
+ import {enforceCacheSizeLimit} from '../util/tile_request_cache';
12
+
13
+ import type {
14
+ WorkerSource,
15
+ WorkerTileParameters,
16
+ WorkerDEMTileParameters,
17
+ WorkerTileCallback,
18
+ WorkerDEMTileCallback,
19
+ TileParameters
20
+ } from '../source/worker_source';
21
+
22
+ import type {WorkerGlobalScopeInterface} from '../util/web_worker';
23
+ import type {Callback} from '../types/callback';
24
+ import type {LayerSpecification} from '../style-spec/types';
25
+ import type {PluginState} from './rtl_text_plugin';
26
+
27
+ /**
28
+ * @private
29
+ */
30
+ export default class Worker {
31
+ self: WorkerGlobalScopeInterface;
32
+ actor: Actor;
33
+ layerIndexes: {[_: string]: StyleLayerIndex };
34
+ availableImages: {[_: string]: Array<string> };
35
+ workerSourceTypes: {[_: string]: Class<WorkerSource> };
36
+ workerSources: {[_: string]: {[_: string]: {[_: string]: WorkerSource } } };
37
+ demWorkerSources: {[_: string]: {[_: string]: RasterDEMTileWorkerSource } };
38
+ referrer: ?string;
39
+
40
+ constructor(self: WorkerGlobalScopeInterface) {
41
+ this.self = self;
42
+ this.actor = new Actor(self, this);
43
+
44
+ this.layerIndexes = {};
45
+ this.availableImages = {};
46
+
47
+ this.workerSourceTypes = {
48
+ vector: VectorTileWorkerSource,
49
+ geojson: GeoJSONWorkerSource
50
+ };
51
+
52
+ // [mapId][sourceType][sourceName] => worker source instance
53
+ this.workerSources = {};
54
+ this.demWorkerSources = {};
55
+
56
+ this.self.registerWorkerSource = (name: string, WorkerSource: Class<WorkerSource>) => {
57
+ if (this.workerSourceTypes[name]) {
58
+ throw new Error(`Worker source with name "${name}" already registered.`);
59
+ }
60
+ this.workerSourceTypes[name] = WorkerSource;
61
+ };
62
+
63
+ // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed.
64
+ this.self.registerRTLTextPlugin = (rtlTextPlugin: {applyArabicShaping: Function, processBidirectionalText: Function, processStyledBidirectionalText?: Function}) => {
65
+ if (globalRTLTextPlugin.isParsed()) {
66
+ throw new Error('RTL text plugin already registered.');
67
+ }
68
+ globalRTLTextPlugin['applyArabicShaping'] = rtlTextPlugin.applyArabicShaping;
69
+ globalRTLTextPlugin['processBidirectionalText'] = rtlTextPlugin.processBidirectionalText;
70
+ globalRTLTextPlugin['processStyledBidirectionalText'] = rtlTextPlugin.processStyledBidirectionalText;
71
+ };
72
+ }
73
+
74
+ setReferrer(mapID: string, referrer: string) {
75
+ this.referrer = referrer;
76
+ }
77
+
78
+ setImages(mapId: string, images: Array<string>, callback: WorkerTileCallback) {
79
+ this.availableImages[mapId] = images;
80
+ for (const workerSource in this.workerSources[mapId]) {
81
+ const ws = this.workerSources[mapId][workerSource];
82
+ for (const source in ws) {
83
+ ws[source].availableImages = images;
84
+ }
85
+ }
86
+ callback();
87
+ }
88
+
89
+ setLayers(mapId: string, layers: Array<LayerSpecification>, callback: WorkerTileCallback) {
90
+ this.getLayerIndex(mapId).replace(layers);
91
+ callback();
92
+ }
93
+
94
+ updateLayers(mapId: string, params: {layers: Array<LayerSpecification>, removedIds: Array<string>}, callback: WorkerTileCallback) {
95
+ this.getLayerIndex(mapId).update(params.layers, params.removedIds);
96
+ callback();
97
+ }
98
+
99
+ loadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) {
100
+ assert(params.type);
101
+ this.getWorkerSource(mapId, params.type, params.source).loadTile(params, callback);
102
+ }
103
+
104
+ loadDEMTile(mapId: string, params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {
105
+ this.getDEMWorkerSource(mapId, params.source).loadTile(params, callback);
106
+ }
107
+
108
+ reloadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) {
109
+ assert(params.type);
110
+ this.getWorkerSource(mapId, params.type, params.source).reloadTile(params, callback);
111
+ }
112
+
113
+ abortTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) {
114
+ assert(params.type);
115
+ this.getWorkerSource(mapId, params.type, params.source).abortTile(params, callback);
116
+ }
117
+
118
+ removeTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) {
119
+ assert(params.type);
120
+ this.getWorkerSource(mapId, params.type, params.source).removeTile(params, callback);
121
+ }
122
+
123
+ removeDEMTile(mapId: string, params: TileParameters) {
124
+ this.getDEMWorkerSource(mapId, params.source).removeTile(params);
125
+ }
126
+
127
+ removeSource(mapId: string, params: {source: string} & {type: string}, callback: WorkerTileCallback) {
128
+ assert(params.type);
129
+ assert(params.source);
130
+
131
+ if (!this.workerSources[mapId] ||
132
+ !this.workerSources[mapId][params.type] ||
133
+ !this.workerSources[mapId][params.type][params.source]) {
134
+ return;
135
+ }
136
+
137
+ const worker = this.workerSources[mapId][params.type][params.source];
138
+ delete this.workerSources[mapId][params.type][params.source];
139
+
140
+ if (worker.removeSource !== undefined) {
141
+ worker.removeSource(params, callback);
142
+ } else {
143
+ callback();
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Load a {@link WorkerSource} script at params.url. The script is run
149
+ * (using importScripts) with `registerWorkerSource` in scope, which is a
150
+ * function taking `(name, workerSourceObject)`.
151
+ * @private
152
+ */
153
+ loadWorkerSource(map: string, params: { url: string }, callback: Callback<void>) {
154
+ try {
155
+ this.self.importScripts(params.url);
156
+ callback();
157
+ } catch (e) {
158
+ callback(e.toString());
159
+ }
160
+ }
161
+
162
+ syncRTLPluginState(map: string, state: PluginState, callback: Callback<boolean>) {
163
+ try {
164
+ globalRTLTextPlugin.setState(state);
165
+ const pluginURL = globalRTLTextPlugin.getPluginURL();
166
+ if (
167
+ globalRTLTextPlugin.isLoaded() &&
168
+ !globalRTLTextPlugin.isParsed() &&
169
+ pluginURL != null // Not possible when `isLoaded` is true, but keeps flow happy
170
+ ) {
171
+ this.self.importScripts(pluginURL);
172
+ const complete = globalRTLTextPlugin.isParsed();
173
+ const error = complete ? undefined : new Error(`RTL Text Plugin failed to import scripts from ${pluginURL}`);
174
+ callback(error, complete);
175
+ }
176
+ } catch (e) {
177
+ callback(e.toString());
178
+ }
179
+ }
180
+
181
+ getAvailableImages(mapId: string) {
182
+ let availableImages = this.availableImages[mapId];
183
+
184
+ if (!availableImages) {
185
+ availableImages = [];
186
+ }
187
+
188
+ return availableImages;
189
+ }
190
+
191
+ getLayerIndex(mapId: string) {
192
+ let layerIndexes = this.layerIndexes[mapId];
193
+ if (!layerIndexes) {
194
+ layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex();
195
+ }
196
+ return layerIndexes;
197
+ }
198
+
199
+ getWorkerSource(mapId: string, type: string, source: string) {
200
+ if (!this.workerSources[mapId])
201
+ this.workerSources[mapId] = {};
202
+ if (!this.workerSources[mapId][type])
203
+ this.workerSources[mapId][type] = {};
204
+
205
+ if (!this.workerSources[mapId][type][source]) {
206
+ // use a wrapped actor so that we can attach a target mapId param
207
+ // to any messages invoked by the WorkerSource
208
+ const actor = {
209
+ send: (type, data, callback) => {
210
+ this.actor.send(type, data, callback, mapId);
211
+ }
212
+ };
213
+ this.workerSources[mapId][type][source] = new (this.workerSourceTypes[type]: any)((actor: any), this.getLayerIndex(mapId), this.getAvailableImages(mapId));
214
+ }
215
+
216
+ return this.workerSources[mapId][type][source];
217
+ }
218
+
219
+ getDEMWorkerSource(mapId: string, source: string) {
220
+ if (!this.demWorkerSources[mapId])
221
+ this.demWorkerSources[mapId] = {};
222
+
223
+ if (!this.demWorkerSources[mapId][source]) {
224
+ this.demWorkerSources[mapId][source] = new RasterDEMTileWorkerSource();
225
+ }
226
+
227
+ return this.demWorkerSources[mapId][source];
228
+ }
229
+
230
+ enforceCacheSizeLimit(mapId: string, limit: number) {
231
+ enforceCacheSizeLimit(limit);
232
+ }
233
+ }
234
+
235
+ /* global self, WorkerGlobalScope */
236
+ if (typeof WorkerGlobalScope !== 'undefined' &&
237
+ typeof self !== 'undefined' &&
238
+ self instanceof WorkerGlobalScope) {
239
+ self.worker = new Worker(self);
240
+ }
node_modules/mapbox-gl/src/source/worker_source.js ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import type {RequestParameters} from '../util/ajax';
4
+ import type {RGBAImage, AlphaImage} from '../util/image';
5
+ import type {GlyphPositions} from '../render/glyph_atlas';
6
+ import type ImageAtlas from '../render/image_atlas';
7
+ import type {OverscaledTileID} from './tile_id';
8
+ import type {Bucket} from '../data/bucket';
9
+ import type FeatureIndex from '../data/feature_index';
10
+ import type {CollisionBoxArray} from '../data/array_types';
11
+ import type DEMData from '../data/dem_data';
12
+ import type {StyleGlyph} from '../style/style_glyph';
13
+ import type {StyleImage} from '../style/style_image';
14
+ import type {PromoteIdSpecification} from '../style-spec/types';
15
+ import window from '../util/window';
16
+ const {ImageBitmap} = window;
17
+
18
+ export type TileParameters = {
19
+ source: string,
20
+ uid: string,
21
+ };
22
+
23
+ export type WorkerTileParameters = TileParameters & {
24
+ tileID: OverscaledTileID,
25
+ request: RequestParameters,
26
+ zoom: number,
27
+ maxZoom: number,
28
+ tileSize: number,
29
+ promoteId: ?PromoteIdSpecification,
30
+ pixelRatio: number,
31
+ showCollisionBoxes: boolean,
32
+ collectResourceTiming?: boolean,
33
+ returnDependencies?: boolean
34
+ };
35
+
36
+ export type WorkerDEMTileParameters = TileParameters & {
37
+ coord: { z: number, x: number, y: number, w: number },
38
+ rawImageData: RGBAImage | ImageBitmap,
39
+ encoding: "mapbox" | "terrarium"
40
+ };
41
+
42
+ export type WorkerTileResult = {
43
+ buckets: Array<Bucket>,
44
+ imageAtlas: ImageAtlas,
45
+ glyphAtlasImage: AlphaImage,
46
+ featureIndex: FeatureIndex,
47
+ collisionBoxArray: CollisionBoxArray,
48
+ rawTileData?: ArrayBuffer,
49
+ resourceTiming?: Array<PerformanceResourceTiming>,
50
+ // Only used for benchmarking:
51
+ glyphMap?: {[_: string]: {[_: number]: ?StyleGlyph}} | null,
52
+ iconMap?: {[_: string]: StyleImage} | null,
53
+ glyphPositions?: GlyphPositions | null
54
+ };
55
+
56
+ export type WorkerTileCallback = (error: ?Error, result: ?WorkerTileResult) => void;
57
+ export type WorkerDEMTileCallback = (err: ?Error, result: ?DEMData) => void;
58
+
59
+ /**
60
+ * May be implemented by custom source types to provide code that can be run on
61
+ * the WebWorkers. In addition to providing a custom
62
+ * {@link WorkerSource#loadTile}, any other methods attached to a `WorkerSource`
63
+ * implementation may also be targeted by the {@link Source} via
64
+ * `dispatcher.getActor().send('source-type.methodname', params, callback)`.
65
+ *
66
+ * @see {@link Map#addSourceType}
67
+ * @private
68
+ *
69
+ * @class WorkerSource
70
+ * @param actor
71
+ * @param layerIndex
72
+ */
73
+ export interface WorkerSource {
74
+ availableImages: Array<string>,
75
+ // Disabled due to https://github.com/facebook/flow/issues/5208
76
+ // constructor(actor: Actor, layerIndex: StyleLayerIndex): WorkerSource;
77
+
78
+ /**
79
+ * Loads a tile from the given params and parse it into buckets ready to send
80
+ * back to the main thread for rendering. Should call the callback with:
81
+ * `{ buckets, featureIndex, collisionIndex, rawTileData}`.
82
+ */
83
+ loadTile(params: WorkerTileParameters, callback: WorkerTileCallback): void;
84
+
85
+ /**
86
+ * Re-parses a tile that has already been loaded. Yields the same data as
87
+ * {@link WorkerSource#loadTile}.
88
+ */
89
+ reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback): void;
90
+
91
+ /**
92
+ * Aborts loading a tile that is in progress.
93
+ */
94
+ abortTile(params: TileParameters, callback: WorkerTileCallback): void;
95
+
96
+ /**
97
+ * Removes this tile from any local caches.
98
+ */
99
+ removeTile(params: TileParameters, callback: WorkerTileCallback): void;
100
+
101
+ /**
102
+ * Tells the WorkerSource to abort in-progress tasks and release resources.
103
+ * The foreground Source is responsible for ensuring that 'removeSource' is
104
+ * the last message sent to the WorkerSource.
105
+ */
106
+ removeSource?: (params: {source: string}, callback: WorkerTileCallback) => void;
107
+ }
node_modules/mapbox-gl/src/source/worker_tile.js ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import FeatureIndex from '../data/feature_index';
4
+
5
+ import {performSymbolLayout} from '../symbol/symbol_layout';
6
+ import {CollisionBoxArray} from '../data/array_types';
7
+ import DictionaryCoder from '../util/dictionary_coder';
8
+ import SymbolBucket from '../data/bucket/symbol_bucket';
9
+ import LineBucket from '../data/bucket/line_bucket';
10
+ import FillBucket from '../data/bucket/fill_bucket';
11
+ import FillExtrusionBucket from '../data/bucket/fill_extrusion_bucket';
12
+ import {warnOnce, mapObject, values} from '../util/util';
13
+ import assert from 'assert';
14
+ import ImageAtlas from '../render/image_atlas';
15
+ import GlyphAtlas from '../render/glyph_atlas';
16
+ import EvaluationParameters from '../style/evaluation_parameters';
17
+ import {OverscaledTileID} from './tile_id';
18
+
19
+ import type {Bucket} from '../data/bucket';
20
+ import type Actor from '../util/actor';
21
+ import type StyleLayer from '../style/style_layer';
22
+ import type StyleLayerIndex from '../style/style_layer_index';
23
+ import type {StyleImage} from '../style/style_image';
24
+ import type {StyleGlyph} from '../style/style_glyph';
25
+ import type {
26
+ WorkerTileParameters,
27
+ WorkerTileCallback,
28
+ } from '../source/worker_source';
29
+ import type {PromoteIdSpecification} from '../style-spec/types';
30
+
31
+ class WorkerTile {
32
+ tileID: OverscaledTileID;
33
+ uid: string;
34
+ zoom: number;
35
+ pixelRatio: number;
36
+ tileSize: number;
37
+ source: string;
38
+ promoteId: ?PromoteIdSpecification;
39
+ overscaling: number;
40
+ showCollisionBoxes: boolean;
41
+ collectResourceTiming: boolean;
42
+ returnDependencies: boolean;
43
+
44
+ status: 'parsing' | 'done';
45
+ data: VectorTile;
46
+ collisionBoxArray: CollisionBoxArray;
47
+
48
+ abort: ?() => void;
49
+ reloadCallback: WorkerTileCallback;
50
+ vectorTile: VectorTile;
51
+
52
+ constructor(params: WorkerTileParameters) {
53
+ this.tileID = new OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);
54
+ this.uid = params.uid;
55
+ this.zoom = params.zoom;
56
+ this.pixelRatio = params.pixelRatio;
57
+ this.tileSize = params.tileSize;
58
+ this.source = params.source;
59
+ this.overscaling = this.tileID.overscaleFactor();
60
+ this.showCollisionBoxes = params.showCollisionBoxes;
61
+ this.collectResourceTiming = !!params.collectResourceTiming;
62
+ this.returnDependencies = !!params.returnDependencies;
63
+ this.promoteId = params.promoteId;
64
+ }
65
+
66
+ parse(data: VectorTile, layerIndex: StyleLayerIndex, availableImages: Array<string>, actor: Actor, callback: WorkerTileCallback) {
67
+ this.status = 'parsing';
68
+ this.data = data;
69
+
70
+ this.collisionBoxArray = new CollisionBoxArray();
71
+ const sourceLayerCoder = new DictionaryCoder(Object.keys(data.layers).sort());
72
+
73
+ const featureIndex = new FeatureIndex(this.tileID, this.promoteId);
74
+ featureIndex.bucketLayerIDs = [];
75
+
76
+ const buckets: {[_: string]: Bucket} = {};
77
+
78
+ const options = {
79
+ featureIndex,
80
+ iconDependencies: {},
81
+ patternDependencies: {},
82
+ glyphDependencies: {},
83
+ availableImages
84
+ };
85
+
86
+ const layerFamilies = layerIndex.familiesBySource[this.source];
87
+ for (const sourceLayerId in layerFamilies) {
88
+ const sourceLayer = data.layers[sourceLayerId];
89
+ if (!sourceLayer) {
90
+ continue;
91
+ }
92
+
93
+ if (sourceLayer.version === 1) {
94
+ warnOnce(`Vector tile source "${this.source}" layer "${sourceLayerId}" ` +
95
+ `does not use vector tile spec v2 and therefore may have some rendering errors.`);
96
+ }
97
+
98
+ const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId);
99
+ const features = [];
100
+ for (let index = 0; index < sourceLayer.length; index++) {
101
+ const feature = sourceLayer.feature(index);
102
+ const id = featureIndex.getId(feature, sourceLayerId);
103
+ features.push({feature, id, index, sourceLayerIndex});
104
+ }
105
+
106
+ for (const family of layerFamilies[sourceLayerId]) {
107
+ const layer = family[0];
108
+
109
+ assert(layer.source === this.source);
110
+ if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) continue;
111
+ if (layer.maxzoom && this.zoom >= layer.maxzoom) continue;
112
+ if (layer.visibility === 'none') continue;
113
+
114
+ recalculateLayers(family, this.zoom, availableImages);
115
+
116
+ const bucket = buckets[layer.id] = layer.createBucket({
117
+ index: featureIndex.bucketLayerIDs.length,
118
+ layers: family,
119
+ zoom: this.zoom,
120
+ pixelRatio: this.pixelRatio,
121
+ overscaling: this.overscaling,
122
+ collisionBoxArray: this.collisionBoxArray,
123
+ sourceLayerIndex,
124
+ sourceID: this.source
125
+ });
126
+
127
+ bucket.populate(features, options, this.tileID.canonical);
128
+ featureIndex.bucketLayerIDs.push(family.map((l) => l.id));
129
+ }
130
+ }
131
+
132
+ let error: ?Error;
133
+ let glyphMap: ?{[_: string]: {[_: number]: ?StyleGlyph}};
134
+ let iconMap: ?{[_: string]: StyleImage};
135
+ let patternMap: ?{[_: string]: StyleImage};
136
+
137
+ const stacks = mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number));
138
+ if (Object.keys(stacks).length) {
139
+ actor.send('getGlyphs', {uid: this.uid, stacks}, (err, result) => {
140
+ if (!error) {
141
+ error = err;
142
+ glyphMap = result;
143
+ maybePrepare.call(this);
144
+ }
145
+ });
146
+ } else {
147
+ glyphMap = {};
148
+ }
149
+
150
+ const icons = Object.keys(options.iconDependencies);
151
+ if (icons.length) {
152
+ actor.send('getImages', {icons, source: this.source, tileID: this.tileID, type: 'icons'}, (err, result) => {
153
+ if (!error) {
154
+ error = err;
155
+ iconMap = result;
156
+ maybePrepare.call(this);
157
+ }
158
+ });
159
+ } else {
160
+ iconMap = {};
161
+ }
162
+
163
+ const patterns = Object.keys(options.patternDependencies);
164
+ if (patterns.length) {
165
+ actor.send('getImages', {icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns'}, (err, result) => {
166
+ if (!error) {
167
+ error = err;
168
+ patternMap = result;
169
+ maybePrepare.call(this);
170
+ }
171
+ });
172
+ } else {
173
+ patternMap = {};
174
+ }
175
+
176
+ maybePrepare.call(this);
177
+
178
+ function maybePrepare() {
179
+ if (error) {
180
+ return callback(error);
181
+ } else if (glyphMap && iconMap && patternMap) {
182
+ const glyphAtlas = new GlyphAtlas(glyphMap);
183
+ const imageAtlas = new ImageAtlas(iconMap, patternMap);
184
+
185
+ for (const key in buckets) {
186
+ const bucket = buckets[key];
187
+ if (bucket instanceof SymbolBucket) {
188
+ recalculateLayers(bucket.layers, this.zoom, availableImages);
189
+ performSymbolLayout(bucket, glyphMap, glyphAtlas.positions, iconMap, imageAtlas.iconPositions, this.showCollisionBoxes, this.tileID.canonical);
190
+ } else if (bucket.hasPattern &&
191
+ (bucket instanceof LineBucket ||
192
+ bucket instanceof FillBucket ||
193
+ bucket instanceof FillExtrusionBucket)) {
194
+ recalculateLayers(bucket.layers, this.zoom, availableImages);
195
+ bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions);
196
+ }
197
+ }
198
+
199
+ this.status = 'done';
200
+ callback(null, {
201
+ buckets: values(buckets).filter(b => !b.isEmpty()),
202
+ featureIndex,
203
+ collisionBoxArray: this.collisionBoxArray,
204
+ glyphAtlasImage: glyphAtlas.image,
205
+ imageAtlas,
206
+ // Only used for benchmarking:
207
+ glyphMap: this.returnDependencies ? glyphMap : null,
208
+ iconMap: this.returnDependencies ? iconMap : null,
209
+ glyphPositions: this.returnDependencies ? glyphAtlas.positions : null
210
+ });
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ function recalculateLayers(layers: $ReadOnlyArray<StyleLayer>, zoom: number, availableImages: Array<string>) {
217
+ // Layers are shared and may have been used by a WorkerTile with a different zoom.
218
+ const parameters = new EvaluationParameters(zoom);
219
+ for (const layer of layers) {
220
+ layer.recalculate(parameters, availableImages);
221
+ }
222
+ }
223
+
224
+ export default WorkerTile;
node_modules/mapbox-gl/src/style-spec/.eslintrc ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "rules": {
3
+ "flowtype/require-valid-file-annotation": [0]
4
+ }
5
+ }
node_modules/mapbox-gl/src/style-spec/CHANGELOG.md ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## 13.17.0
2
+
3
+ ### ✨ Features and improvements
4
+ * 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)
5
+
6
+ ## 13.16.0
7
+
8
+ ### ✨ Features and improvements
9
+ * Added `volatile` source property to control storing the tiles in local storage. ([9702](https://github.com/mapbox/mapbox-gl-js/pull/9702))
10
+
11
+ * 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))
12
+
13
+ ## 13.15.0
14
+
15
+ ### ✨ Features and improvements
16
+ * 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))
17
+
18
+ ## 13.14.0
19
+
20
+ ### ✨ Features and improvements
21
+ * 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))
22
+
23
+ ## 13.13.1
24
+
25
+ ### ✨ Features and improvements
26
+ * Expose `expression.isExpressionFilter(..)` from the bundle. ([#9530](https://github.com/mapbox/mapbox-gl-js/pull/9530))
27
+
28
+ ### 🐛 Bug fixes
29
+ * 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))
30
+
31
+ ## 13.13.0
32
+
33
+ ### ✨ Features and improvements
34
+ * 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:<br>
35
+ `"icon-opacity": ["case", ["==", ["within", "some-polygon"], true], 1,
36
+ ["==", ["within", "some-polygon"], false], 0]`
37
+ * 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))
38
+
39
+ ### 🐛 Bug fixes
40
+ * Allow needle argument to `in` expression to be false ([#9295](https://github.com/mapbox/mapbox-gl-js/pull/9295))
41
+ * 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))
42
+ * Prevent exception resulting from `line-dash-array` of empty length ([#9385](https://github.com/mapbox/mapbox-gl-js/pull/9385))
43
+
44
+ ## 13.12.0
45
+
46
+ * Update `image` expression SDK support table ([#9228](https://github.com/mapbox/mapbox-gl-js/pull/9228))
47
+ * 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))
48
+
49
+ ## 13.11.0
50
+
51
+ ### ✨ Features and improvements
52
+ * Add `promoteId` option to use a feature property as ID for feature state ([#8987](https://github.com/mapbox/mapbox-gl-js/pull/8987))
53
+ * Update `symbol-avoid-edges` documentation regarding global collision detection ([#9157](https://github.com/mapbox/mapbox-gl-js/pull/9157))
54
+ * Remove reference to `in` function which has been replaced by the `in` expression ([#9102](https://github.com/mapbox/mapbox-gl-js/pull/9102))
55
+
56
+ ### 🐛 Bug fixes
57
+ * 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))
58
+
59
+ ## 13.10.2
60
+
61
+ ### 🐛 Bug fixes
62
+ * Fix style validation error messages not being displayed ([#9073](https://github.com/mapbox/mapbox-gl-js/pull/9073))
63
+
64
+ ## 13.10.0
65
+
66
+ ### ✨ Features and improvements
67
+ * 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))
68
+ * 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))
69
+ * 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))
70
+ * 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))
71
+
72
+ ## 13.9.1
73
+
74
+ ### ✨ Improvement
75
+ * 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))
76
+
77
+ ## 13.9.0
78
+
79
+ * Add `image` expression operator to determine image availability ([#8684](https://github.com/mapbox/mapbox-gl-js/pull/8684))
80
+ * 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))
81
+
82
+ ## 13.8.0
83
+
84
+ - Introduce `text-writing-mode` symbol layer property to allow placing point labels vertically. [#8399](https://github.com/mapbox/mapbox-gl-js/pull/8399)
85
+ - 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)
86
+ - Improve conversion of legacy filters with duplicate values. [#8542](https://github.com/mapbox/mapbox-gl-js/pull/8542)
87
+
88
+ ## 13.7.2
89
+
90
+ ### 🐛 Bug fixes
91
+ * 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))
92
+
93
+ ### ✨ Features and improvements
94
+ * Add SDK support spec section for text-radial-offset ([#8401](https://github.com/mapbox/mapbox-gl-js/pull/8401))
95
+ * Add `*-sort-key` layout property for circle, fill, line ([#8467](https://github.com/mapbox/mapbox-gl-js/pull/8467))
96
+ * Expose convertFilter API in the style specification ([#8493](https://github.com/mapbox/mapbox-gl-js/pull/8493))
97
+
98
+ ## 13.7.1
99
+
100
+ ### 🐛 Bug fixes
101
+ * Fix format expression options validation ([#8339](https://github.com/mapbox/mapbox-gl-js/pull/8339))
102
+ * Fix SDK support information for style properties added in v13.7.0: ([#8384](https://github.com/mapbox/mapbox-gl-js/pull/8384))
103
+ * Add missing SDK support section for `text-radial-offset` property
104
+ * Assign SDK versions for `text-variable-anchor` and `text-justify: auto`
105
+
106
+ ## 13.7.0
107
+
108
+ ### ✨ Features and improvements
109
+ * Add `text-radial-offset` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596))
110
+ * Add `text-variable-anchor` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596))
111
+ * Add `auto` value to `text-justify` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596))
112
+
113
+ ## 13.6.0
114
+
115
+ ### ✨ Features and improvements
116
+ * 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))
117
+ * Add `number-format` expression ([#7626](https://github.com/mapbox/mapbox-gl-js/pull/7626))
118
+ * Add `symbol-sort-key` style property ([#7678](https://github.com/mapbox/mapbox-gl-js/pull/7678))
119
+
120
+ ## 13.5.0
121
+
122
+ ### Features and improvements
123
+ * Flattens `all` expressions in converted filters ([#7679](https://github.com/mapbox/mapbox-gl-js/pull/7679))
124
+ * Compatibility tables are updated ([#7574](https://github.com/mapbox/mapbox-gl-js/pull/7574))
125
+
126
+ ## 13.4.0
127
+
128
+ ### ✨ Features and improvements
129
+ * **Tighten style validation**
130
+ * Disallow expressions as stop values ([#7396](https://github.com/mapbox/mapbox-gl-js/pull/7396))
131
+ * Disallow `feature-state` expressions in filters ([#7366](https://github.com/mapbox/mapbox-gl-js/pull/7366))
132
+
133
+ ## 13.3.0
134
+
135
+ ### 🐛 Bug fixes
136
+ * **Expressions**
137
+ * 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))
138
+ * 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))
139
+ * Allow calling `to-color` on values that are already of type `Color` ([#7260](https://github.com/mapbox/mapbox-gl-js/pull/7260))
140
+ * Fix `to-array` for empty arrays (([#7261](https://github.com/mapbox/mapbox-gl-js/pull/7261)))
141
+ * Fix identity functions for `text-field` when using formatted text ([#7351](https://github.com/mapbox/mapbox-gl-js/pull/7351))
142
+ * 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))
143
+
144
+ ### ✨ Features and improvements
145
+ * 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))
146
+
147
+ ## 13.2.0
148
+
149
+ ### 🐛 Bug fixes
150
+ * 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))
151
+
152
+ ### ✨ Features and improvements
153
+ * Add `symbol-z-order` symbol layout property to style spec ([#7219](https://github.com/mapbox/mapbox-gl-js/pull/7219))
154
+ * Implement data-driven styling support for `*-pattern properties` ([#6289](https://github.com/mapbox/mapbox-gl-js/pull/6289))
155
+
156
+ ## 13.1.1
157
+
158
+ ### 🐛 Bug fixes
159
+ * 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))
160
+
161
+ ### ✨ Features and improvements
162
+ * Improve formatting for style output ([#7029](https://github.com/mapbox/mapbox-gl-js/pull/7029))
163
+
164
+ ## 13.1.0
165
+
166
+ ### ✨ Features and improvements
167
+ * Add `raster-resampling` raster paint property ([#6411](https://github.com/mapbox/mapbox-gl-js/pull/6411)) (h/t [andrewharvey](https://github.com/andrewharvey))
168
+ * Add `symbol-placement: line-center` ([#6821](https://github.com/mapbox/mapbox-gl-js/pull/6821))
169
+
170
+ ## 13.0.1
171
+
172
+ ### ⚠️ Breaking changes
173
+ * Align implicit type behavior of `match` expressions with with `case/==` ([#6684](https://github.com/mapbox/mapbox-gl-js/pull/6684))
174
+ * 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))
175
+
176
+ ### ✨ Features and improvements
177
+ * Add `feature-state` [#6263](https://github.com/mapbox/mapbox-gl-js/pull/6263)
178
+ * Add support for GeoJSON attribution ([#6364](https://github.com/mapbox/mapbox-gl-js/pull/6364)) (h/t [andrewharvey](https://github.com/andrewharvey))
179
+ * Upgrade to Flow 0.69 ([#6594](https://github.com/mapbox/mapbox-gl-js/pull/6594))
180
+
181
+ ### 🐛 Bug fixes
182
+ * Use named exports for style-spec entrypoint module ([#6601](https://github.com/mapbox/mapbox-gl-js/issues/6601)
183
+
184
+ ## 13.0.0
185
+ Malformed package published to NPM.
186
+
187
+ ## 12.0.0
188
+
189
+ ### ⚠️ Breaking changes
190
+ * 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)
191
+
192
+ ### ✨ Features and improvements
193
+ * 🌈 Add line-gradient property [#6303](https://github.com/mapbox/mapbox-gl-js/pull/6303)
194
+ * Add collator expression for controlling case and diacritic sensitivity in string comparisons [#6270](https://github.com/mapbox/mapbox-gl-js/pull/6270)
195
+ * Add `is-supported-script` expression for determining if a script is supported. [#6260](https://github.com/mapbox/mapbox-gl-js/pull/6260)
196
+ * Add `collator` expression for controlling case and diacritic sensitivity in string comparisons [#6270](https://github.com/mapbox/mapbox-gl-js/pull/6270)
197
+ * Add `abs`, `round`, `floor`, and `ceil` expression operators [#6496](https://github.com/mapbox/mapbox-gl-js/pull/6496)
198
+ * Add support for Mapzen Terrarium tiles in raster-dem sources [#6110](https://github.com/mapbox/mapbox-gl-js/pull/6110)
199
+
200
+ ### 🐛 Bug fixes
201
+ - Fix Rollup build [6575](https://github.com/mapbox/mapbox-gl-js/pull/6575)
202
+
203
+ ## 11.1.1
204
+
205
+ ### 🐛 Bug fixes
206
+
207
+ * Update SDK support information for `text-font`, and `heatmap-color`, and `hillshade` layer properties.
208
+
209
+ ## 11.1.0
210
+
211
+ ### ✨ Features and improvements
212
+
213
+ * Avoid use of `new Function` for filters by converting old-style filters to expressions [#5665](https://github.com/mapbox/mapbox-gl-js/pull/5665).
214
+
215
+ ## 11.0.0
216
+
217
+ ### ⚠️ Breaking changes
218
+
219
+ * Remove constants validating code [#5885](https://github.com/mapbox/mapbox-gl-js/pull/5885)
220
+ * `"colorSpace": "hcl"` now uses shortest-path interpolation for hue [#5811](https://github.com/mapbox/mapbox-gl-js/issues/5811)
221
+
222
+ ### ✨ Features and improvements
223
+
224
+ * Introduce client-side hillshading with `raster-dem` source type and `hillshade` layer type [#5286](https://github.com/mapbox/mapbox-gl-js/pull/5286)
225
+ * Add Color#toString and expose Color publicly [#5866](https://github.com/mapbox/mapbox-gl-js/pull/5866)
226
+ * Improve typing for `==` and `!=` expressions [#5840](https://github.com/mapbox/mapbox-gl-js/pull/5840)
227
+ * Made `coalesce` expressions more useful [#5755](https://github.com/mapbox/mapbox-gl-js/issues/5755)
228
+ * Enable implicit type assertions for array types [#5738](https://github.com/mapbox/mapbox-gl-js/pull/5738)
229
+
230
+ ### 🐛 Bug fixes
231
+
232
+ * Fix standalone browser build [#5736](https://github.com/mapbox/mapbox-gl-js/pull/5736), [#5906](https://github.com/mapbox/mapbox-gl-js/pull/5906)
233
+ * Handle NaN as input to step and interpolate expressions [#5757](https://github.com/mapbox/mapbox-gl-js/pull/5757)
234
+ * Fix style diffing for changes to GeoJSON sources [#5745](https://github.com/mapbox/mapbox-gl-js/pull/5745)
235
+ * Mark layer "type" property as required [#5849](https://github.com/mapbox/mapbox-gl-js/pull/5849)
236
+
237
+ ## 10.1.0
238
+
239
+ * Remove support for validating and migrating v6 styles [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604)
240
+ * Remove support for validating v7 styles [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604)
241
+ * Remove spaces after commas in `to-string` representation of colors [#5480](https://github.com/mapbox/mapbox-gl-js/pull/5480)
242
+ * Fix bugs preventing `mapbox-gl-style-spec` package on NPM from being used externally [#5502](https://github.com/mapbox/mapbox-gl-js/pull/5502)
243
+ * Fix flow-typed interface generator [#5478](https://github.com/mapbox/mapbox-gl-js/pull/5478)
244
+ * Export `function` [#5584](https://github.com/mapbox/mapbox-gl-js/pull/5584)
245
+ * Export `StylePropertySpecification` type [#5593](https://github.com/mapbox/mapbox-gl-js/pull/5593)
246
+ * 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)
247
+
248
+ ### Validation Changes
249
+
250
+ * Require that `heatmap-color` use expressions instead of stop functions [#5624](https://github.com/mapbox/mapbox-gl-js/issues/5624)
251
+ * Remove support for including `{tokens}` in expressions for `text-field` and `icon-image` [#5599](https://github.com/mapbox/mapbox-gl-js/issues/5599)
252
+ * Disallow interpolation in expressions for `line-dasharray` [#5519](https://github.com/mapbox/mapbox-gl-js/pull/5519)
253
+ * Validate that zoom expressions only appear at the top level of an expression [#5609](https://github.com/mapbox/mapbox-gl-js/issues/5609)
254
+ * Validate that `step` and `interpolate` expressions don't have any duplicate stops [#5605](https://github.com/mapbox/mapbox-gl-js/issues/5605)
255
+ * Split `curve` expression into `step` and `interpolate` expressions [#5542](https://github.com/mapbox/mapbox-gl-js/pull/5542)
256
+ * Validate expression values for enum-typed properties [#5589](https://github.com/mapbox/mapbox-gl-js/pull/5589)
257
+ * Improve validation to catch uses of deprecated function syntax [#5667](https://github.com/mapbox/mapbox-gl-js/pull/5667)
258
+
259
+ ## 10.0.1
260
+
261
+ * Fix bug preventing @mapbox/mapbox-gl-style-spec package from being usable outside of mapbox-gl-js (#5502)
262
+
263
+ ## 10.0.0
264
+
265
+ * Add expression and heatmap layer support. See Mapbox GL JS v0.40.1 changelog entry for details.
266
+
267
+ ## 9.0.1
268
+
269
+ * Remove `fast-stable-stringify` dependency (#5152)
270
+
271
+ ## 9.0.0
272
+
273
+ * Fix validation error on categorical zoom-and-property functions (#4220)
274
+ * Relax requirement that styles using "icon-image" must have a "sprite"
275
+ * Prevent infinite loop in binarySearchForIndex when duplicate stops are present. (#4503)
276
+ * Ensure generated composite function stops are in the correct order (#4509)
277
+ * Update SDK support matrices to be current as of GL JS v0.35.1, iOS SDK v3.5.0, Android SDK 5.0.0
278
+ * Remove support for implicitly-categorical functions
279
+ * BREAKING CHANGE: the API for the `function` module has changed. The `interpolated` and `piecewise-constant` exports
280
+ were replaced with a single unnamed export, a function which accepts an object conforming to the style spec "function"
281
+ definition, and an object defining a style spec property. It handles color parsing and validation of feature values
282
+ internally.
283
+ * Functions now support a "default" property.
284
+ * `parseColor` was promoted from gl-js.
285
+
286
+ ## 8.11.0
287
+
288
+ * Merge `feature-filter` repository into this repository #639
289
+
290
+ ## 8.10.0
291
+
292
+ v8.0.0 styles are fully compatible with v8.10.0.
293
+
294
+ ### Style Specification Changes
295
+
296
+ * Added `colorSpace` option to functions
297
+ * Added `fill-extrusion` layer type
298
+ * Add top-level `light` property
299
+ * Remove increase maximum `maxzoom` to 24
300
+ * Deprecate paint classes :warning:
301
+ * Increase strictness of function validation
302
+
303
+ ### Reference JSON & API Changes
304
+
305
+ * Added `deref` utility
306
+ * Added `group_by_layout` utility
307
+ * Merge `mapbox-gl-function` repository into this repository
308
+
309
+ ## 8.9.0
310
+
311
+ v8.0.0 styles are fully compatible with v8.9.0.
312
+
313
+ * Added identity functions
314
+ * Added `auto` value which represents the calculated default value
315
+
316
+ ## 8.8.1
317
+
318
+ v8.0.0 styles are fully compatible with v8.8.1.
319
+
320
+ * Fixed style validation for layers with invalid types
321
+
322
+ ## 8.8.0
323
+
324
+ v8.0.0 styles are fully compatible with v8.8.0.
325
+
326
+ * Clarified documentation around fill-opacity.
327
+ * Update function documentation and validation for property functions.
328
+ * Add text-pitch-alignment property.
329
+ * Add icon-text-fit, icon-text-fit-padding properties.
330
+
331
+ ## 8.7.0
332
+
333
+ v8.0.0 styles are fully compatible with v8.7.0.
334
+
335
+ * Add support for has / !has operators.
336
+
337
+ ## 8.6.0
338
+
339
+ v8.0.0 styles are fully compatible with v8.6.0.
340
+
341
+ * Added support for zoom and feature driven functions.
342
+
343
+ ## 8.4.2
344
+
345
+ v8.0.0 styles are fully compatible with v8.4.2.
346
+
347
+ * Refactored style validator to expose more granular validation methods
348
+
349
+ ## 8.4.1
350
+
351
+ v8.0.0 styles are fully compatible with v8.4.1.
352
+
353
+ * Revert ramp validation checks that broke some styles.
354
+
355
+ ## 8.4.0
356
+
357
+ v8.0.0 styles are fully compatible with v8.4.0.
358
+
359
+ * Added `cluster`, `clusterRadius`, `clusterMaxZoom` GeoJSON source properties.
360
+
361
+ ## 8.3.0
362
+
363
+ v8.0.0 styles are fully compatible with v8.3.0.
364
+
365
+ * Added `line-offset` style property
366
+
367
+ ## 8.2.1
368
+
369
+ v8.0.0 styles are fully compatible with v8.2.1.
370
+
371
+ * Enforce that all layers that use a vector source specify a "source-layer"
372
+
373
+ ## 8.2.0
374
+
375
+ v8.0.0 styles are fully compatible with v8.2.0.
376
+
377
+ * Add inline `example` property.
378
+ * Enforce that all style properties must have documentation in `doc` property.
379
+ * Create minified style specs with `doc` and `example` properties removed.
380
+ * `validate` now validates against minified style spec.
381
+ * `format` now accepts `space` option to use with `JSON.stringify`.
382
+ * Remove `gl-style-spritify`. Mapbox GL sprites are now created automatically by
383
+ the Mapbox style APIs, or for hand-crafted styles, by [spritezero-cli](https://github.com/mapbox/spritezero-cli).
384
+
385
+ ## 8.1.0
386
+
387
+ v8.0.0 styles are fully compatible with v8.1.0.
388
+
389
+ * [BREAKING] Simplified layout/paint layer property types to more closely align
390
+ with v7 types.
391
+ * Fixed migration script compatibility with newer versions of Node.js and io.js
392
+ * Removed `constants` from schema, they were deprecated in v8
393
+ * Added style diff utility to generate semantic deltas between two stylesheets
394
+ * Added `visibility` property to `circle` layer type
395
+ * Added `pitch` property to stylesheet
396
+
397
+ ## 8.0.0
398
+
399
+ Introduction of Mapbox GL style specification v8. To migrate a v7 style to v8,
400
+ use the `gl-style-migrate` script as described in the README.
401
+
402
+ * [BREAKING] The value of the `text-font` property is now an array of
403
+ strings, rather than a single comma separated string.
404
+ * [BREAKING] Renamed `symbol-min-distance` to `symbol-spacing`.
405
+ * [BREAKING] Renamed `background-image` to `background-pattern`.
406
+ * [BREAKING] Renamed `line-image` to `line-pattern`.
407
+ * [BREAKING] Renamed `fill-image` to `fill-pattern`.
408
+ * [BREAKING] Renamed the `url` property of the video source type to `urls`.
409
+ * [BREAKING] Coordinates in video sources are now specified in [lon, lat] order.
410
+ * [BREAKING] Removed `text-max-size` and `icon-max-size` properties; these
411
+ are now calculated automatically.
412
+ * [BREAKING] `text-size` and `icon-size` are now layout properties instead of paint properties.
413
+ * [BREAKING] Constants are no longer supported. If you are editing styles by
414
+ hand and want to use constants, you can use a preprocessing step with a tool
415
+ like [ScreeSS](https://github.com/screee/screess).
416
+ * [BREAKING] The format for `mapbox://` glyphs URLs has changed; you should
417
+ now use `mapbox://fonts/mapbox/{fontstack}/{range}.pbf`.
418
+ * [BREAKING] Reversed the priority of layers for calculating label placement:
419
+ labels for layers that appear later in the style now have priority over earlier
420
+ layers.
421
+ * Added a new `image` source type.
422
+ * Added a new `circle` layer type.
423
+ * Default map center location can now be set in the style.
424
+ * Added `mapbox://` sprite URLs `mapbox://sprite/{user | "mapbox"}/{id}`
425
+
426
+ ## 7.5.0
427
+
428
+ * Added gl-style-composite script, for auto-compositing sources in a style.
429
+
430
+ ## 7.4.1
431
+
432
+ * Use JSON.stringify for formatting instead of js-beautify
433
+
434
+ ## 7.0.0
435
+
436
+ Introduction of Mapbox GL style specification v7.
437
+
438
+ * [BREAKING] Improve dashed lines (#234)
439
+ * [BREAKING] Remove prerendered layers (#232)
440
+ * Explicit visibility property (#212)
441
+ * Functions for all properties (#237)
442
+
443
+ ## 6.0.0 (Style spec v6)
444
+
445
+ Introduction of Mapbox GL style specification v6.
446
+
447
+ * [BREAKING] New filter syntax (#178)
448
+ * [BREAKING] Line gap property (#131)
449
+ * [BREAKING] Remove dashes from min/max-zoom (#175)
450
+ * [BREAKING] New layout/paint terminology (#166)
451
+ * [BREAKING] Single text positioning property (#197)
452
+ * Added requirements (#200)
453
+ * Added minimum, maximum, and period values (#198)
454
+
455
+ ## 0.0.5 (in progress)
456
+
457
+ * [BREAKING] Switch to suffix for transition properties (`transition-*` -> `*-transition`).
458
+ * Added support for remote, non-Mapbox TileJSON sources.
459
+ * [BREAKING] Source `minZoom` and `maxZoom` renamed to `minzoom` and `maxzoom to match TileJSON.
460
+ * Added support for `mapbox://` glyph URLs.
461
+ * [BREAKING] Renamed `raster-fade` to `raster-fade-duration`.
462
+ * Added background-opacity property.
463
+ * Added "tokens" property to string values that can autocomplete fields from layers
464
+ * Added "units" property to describe value types
465
+
466
+ ## 0.0.4 (Aug 8 2014)
467
+
468
+ * Initial public release
node_modules/mapbox-gl/src/style-spec/README.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mapbox GL style specification & utilities
2
+
3
+ This directory contains code and reference files that define the Mapbox GL style specification and provides some utilities for working with Mapbox styles.
4
+
5
+ ## npm package
6
+
7
+ The Mapbox GL style specification and utilities are published as a seperate npm
8
+ package so that they can be installed without the bulk of GL JS.
9
+
10
+ npm install @mapbox/mapbox-gl-style-spec
11
+
12
+ ## CLI Tools
13
+
14
+ If you install this package globally, you will have access to several CLI tools.
15
+
16
+ npm install @mapbox/mapbox-gl-style-spec --global
17
+
18
+
19
+ ### `gl-style-composite`
20
+ ```bash
21
+ $ gl-style-composite style.json
22
+ ```
23
+
24
+ Will take a non-composited style and produce a [composite style](https://www.mapbox.com/blog/better-label-placement-in-mapbox-studio/).
25
+
26
+ ### `gl-style-migrate`
27
+
28
+ This repo contains scripts for migrating GL styles of any version to the latest version
29
+ (currently v8). Migrate a style like this:
30
+
31
+ ```bash
32
+ $ gl-style-migrate bright-v7.json > bright-v8.json
33
+ ```
34
+
35
+ To migrate a file in place, you can use the `sponge` utility from the `moreutils` package:
36
+
37
+ ```bash
38
+ $ brew install moreutils
39
+ $ gl-style-migrate bright.json | sponge bright.json
40
+ ```
41
+
42
+ ### `gl-style-format`
43
+
44
+ ```bash
45
+ $ gl-style-format style.json
46
+ ```
47
+
48
+ Will format the given style JSON to use standard indentation and sorted object keys.
49
+
50
+ ### `gl-style-validate`
51
+
52
+ ```bash
53
+ $ gl-style-validate style.json
54
+ ```
55
+
56
+ Will validate the given style JSON and print errors to stdout. Provide a
57
+ `--json` flag to get JSON output.
58
+
59
+ To validate that a style can be uploaded to the Mapbox Styles API, use the `--mapbox-api-supported` flag.
node_modules/mapbox-gl/src/style-spec/bin/gl-style-composite ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+
4
+ var fs = require('fs'),
5
+ argv = require('minimist')(process.argv.slice(2)),
6
+ format = require('../').format,
7
+ composite = require('../').composite;
8
+
9
+ console.log(format(composite(JSON.parse(fs.readFileSync(argv._[0])))));
node_modules/mapbox-gl/src/style-spec/bin/gl-style-format ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+
4
+ var fs = require('fs'),
5
+ argv = require('minimist')(process.argv.slice(2)),
6
+ format = require('../').format;
7
+
8
+ if (argv.help || argv.h || (!argv._.length && process.stdin.isTTY)) {
9
+ return help();
10
+ }
11
+
12
+ console.log(format(JSON.parse(fs.readFileSync(argv._[0])), argv.space));
13
+
14
+ function help() {
15
+ console.log('usage:');
16
+ console.log(' gl-style-format source.json > destination.json');
17
+ console.log('');
18
+ console.log('options:');
19
+ console.log(' --space <num>');
20
+ console.log(' Number of spaces in output (default "2")');
21
+ console.log(' Pass "0" for minified output.');
22
+ }
node_modules/mapbox-gl/src/style-spec/bin/gl-style-migrate ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+
4
+ var fs = require('fs'),
5
+ argv = require('minimist')(process.argv.slice(2)),
6
+ format = require('../').format,
7
+ migrate = require('../').migrate;
8
+
9
+ console.log(format(migrate(JSON.parse(fs.readFileSync(argv._[0])))));
node_modules/mapbox-gl/src/style-spec/bin/gl-style-validate ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+
4
+ var argv = require('minimist')(process.argv.slice(2), {
5
+ boolean: 'json',
6
+ boolean: 'mapbox-api-supported'
7
+ }),
8
+ validate = require('../').validate,
9
+ validateMapboxApiSupported = require('../').validateMapboxApiSupported
10
+ rw = require('rw'),
11
+ status = 0;
12
+
13
+ if (argv.help || argv.h || (!argv._.length && process.stdin.isTTY)) {
14
+ return help();
15
+ }
16
+
17
+ if (!argv._.length) {
18
+ argv._.push('/dev/stdin');
19
+ }
20
+
21
+ argv._.forEach(function(file) {
22
+ var errors;
23
+ if (argv['mapbox-api-supported']) {
24
+ errors = validateMapboxApiSupported(rw.readFileSync(file, 'utf8'));
25
+ } else {
26
+ errors = validate(rw.readFileSync(file, 'utf8'));
27
+ }
28
+ if (errors.length) {
29
+ if (argv.json) {
30
+ process.stdout.write(JSON.stringify(errors, null, 2));
31
+ } else {
32
+ errors.forEach(function (e) {
33
+ console.log('%s:%d: %s', file, e.line, e.message);
34
+ });
35
+ }
36
+ status = 1;
37
+ }
38
+ });
39
+
40
+ process.exit(status);
41
+
42
+ function help() {
43
+ console.log('usage:');
44
+ console.log(' gl-style-validate file.json');
45
+ console.log(' gl-style-validate < file.json');
46
+ console.log('');
47
+ console.log('options:');
48
+ console.log('--json output errors as json');
49
+ console.log('--mapbox-api-supported validate compatibility with Mapbox Styles API');
50
+ }
node_modules/mapbox-gl/src/style-spec/composite.js ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ export default function (style) {
3
+ const styleIDs = [];
4
+ const sourceIDs = [];
5
+ const compositedSourceLayers = [];
6
+
7
+ for (const id in style.sources) {
8
+ const source = style.sources[id];
9
+
10
+ if (source.type !== "vector")
11
+ continue;
12
+
13
+ const match = /^mapbox:\/\/(.*)/.exec(source.url);
14
+ if (!match)
15
+ continue;
16
+
17
+ styleIDs.push(id);
18
+ sourceIDs.push(match[1]);
19
+ }
20
+
21
+ if (styleIDs.length < 2)
22
+ return style;
23
+
24
+ styleIDs.forEach((id) => {
25
+ delete style.sources[id];
26
+ });
27
+
28
+ const compositeID = sourceIDs.join(",");
29
+
30
+ style.sources[compositeID] = {
31
+ "type": "vector",
32
+ "url": `mapbox://${compositeID}`
33
+ };
34
+
35
+ style.layers.forEach((layer) => {
36
+ if (styleIDs.indexOf(layer.source) >= 0) {
37
+ layer.source = compositeID;
38
+
39
+ if ('source-layer' in layer) {
40
+ if (compositedSourceLayers.indexOf(layer['source-layer']) >= 0) {
41
+ throw new Error('Conflicting source layer names');
42
+ } else {
43
+ compositedSourceLayers.push(layer['source-layer']);
44
+ }
45
+ }
46
+ }
47
+ });
48
+
49
+ return style;
50
+ }
node_modules/mapbox-gl/src/style-spec/declass.js ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import extend from './util/extend';
3
+
4
+ export default declassStyle;
5
+
6
+ /**
7
+ * Returns a new style with the given 'paint classes' merged into each layer's
8
+ * main `paint` definiton, and with all `paint.*` properties removed.
9
+ *
10
+ * @private
11
+ * @param {Object} style A style JSON object.
12
+ * @param {Array<string>} classes An array of paint classes to apply, in order.
13
+ *
14
+ * @example
15
+ * var declass = require('mapbox-gl-style-spec/lib/declass')
16
+ * var baseStyle = { ... style with a 'paint.night' property in some layers ... }
17
+ * var nightStyle = declass(baseStyle, ['night'])
18
+ * // nightStyle now has each layer's `paint.night` properties merged in to the
19
+ * // main `paint` property.
20
+ */
21
+ function declassStyle(style, classes) {
22
+ return extend({}, style, {
23
+ layers: style.layers.map((layer) => {
24
+ const result = classes.reduce(declassLayer, layer);
25
+
26
+ // strip away all `paint.CLASS` definitions
27
+ for (const key in result) {
28
+ if (/paint\..*/.test(key)) {
29
+ delete result[key];
30
+ }
31
+ }
32
+
33
+ return result;
34
+ })
35
+ });
36
+ }
37
+
38
+ function declassLayer(layer, klass) {
39
+ return extend({}, layer, {
40
+ paint: extend({}, layer.paint, layer[`paint.${klass}`])
41
+ });
42
+ }
node_modules/mapbox-gl/src/style-spec/deref.js ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import refProperties from './util/ref_properties';
3
+
4
+ function deref(layer, parent) {
5
+ const result = {};
6
+
7
+ for (const k in layer) {
8
+ if (k !== 'ref') {
9
+ result[k] = layer[k];
10
+ }
11
+ }
12
+
13
+ refProperties.forEach((k) => {
14
+ if (k in parent) {
15
+ result[k] = parent[k];
16
+ }
17
+ });
18
+
19
+ return result;
20
+ }
21
+
22
+ export default derefLayers;
23
+
24
+ /**
25
+ * Given an array of layers, some of which may contain `ref` properties
26
+ * whose value is the `id` of another property, return a new array where
27
+ * such layers have been augmented with the 'type', 'source', etc. properties
28
+ * from the parent layer, and the `ref` property has been removed.
29
+ *
30
+ * The input is not modified. The output may contain references to portions
31
+ * of the input.
32
+ *
33
+ * @private
34
+ * @param {Array<Layer>} layers
35
+ * @returns {Array<Layer>}
36
+ */
37
+ function derefLayers(layers) {
38
+ layers = layers.slice();
39
+
40
+ const map = Object.create(null);
41
+ for (let i = 0; i < layers.length; i++) {
42
+ map[layers[i].id] = layers[i];
43
+ }
44
+
45
+ for (let i = 0; i < layers.length; i++) {
46
+ if ('ref' in layers[i]) {
47
+ layers[i] = deref(layers[i], map[layers[i].ref]);
48
+ }
49
+ }
50
+
51
+ return layers;
52
+ }
node_modules/mapbox-gl/src/style-spec/diff.js ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import isEqual from './util/deep_equal';
3
+
4
+ const operations = {
5
+
6
+ /*
7
+ * { command: 'setStyle', args: [stylesheet] }
8
+ */
9
+ setStyle: 'setStyle',
10
+
11
+ /*
12
+ * { command: 'addLayer', args: [layer, 'beforeLayerId'] }
13
+ */
14
+ addLayer: 'addLayer',
15
+
16
+ /*
17
+ * { command: 'removeLayer', args: ['layerId'] }
18
+ */
19
+ removeLayer: 'removeLayer',
20
+
21
+ /*
22
+ * { command: 'setPaintProperty', args: ['layerId', 'prop', value] }
23
+ */
24
+ setPaintProperty: 'setPaintProperty',
25
+
26
+ /*
27
+ * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] }
28
+ */
29
+ setLayoutProperty: 'setLayoutProperty',
30
+
31
+ /*
32
+ * { command: 'setFilter', args: ['layerId', filter] }
33
+ */
34
+ setFilter: 'setFilter',
35
+
36
+ /*
37
+ * { command: 'addSource', args: ['sourceId', source] }
38
+ */
39
+ addSource: 'addSource',
40
+
41
+ /*
42
+ * { command: 'removeSource', args: ['sourceId'] }
43
+ */
44
+ removeSource: 'removeSource',
45
+
46
+ /*
47
+ * { command: 'setGeoJSONSourceData', args: ['sourceId', data] }
48
+ */
49
+ setGeoJSONSourceData: 'setGeoJSONSourceData',
50
+
51
+ /*
52
+ * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] }
53
+ */
54
+ setLayerZoomRange: 'setLayerZoomRange',
55
+
56
+ /*
57
+ * { command: 'setLayerProperty', args: ['layerId', 'prop', value] }
58
+ */
59
+ setLayerProperty: 'setLayerProperty',
60
+
61
+ /*
62
+ * { command: 'setCenter', args: [[lon, lat]] }
63
+ */
64
+ setCenter: 'setCenter',
65
+
66
+ /*
67
+ * { command: 'setZoom', args: [zoom] }
68
+ */
69
+ setZoom: 'setZoom',
70
+
71
+ /*
72
+ * { command: 'setBearing', args: [bearing] }
73
+ */
74
+ setBearing: 'setBearing',
75
+
76
+ /*
77
+ * { command: 'setPitch', args: [pitch] }
78
+ */
79
+ setPitch: 'setPitch',
80
+
81
+ /*
82
+ * { command: 'setSprite', args: ['spriteUrl'] }
83
+ */
84
+ setSprite: 'setSprite',
85
+
86
+ /*
87
+ * { command: 'setGlyphs', args: ['glyphsUrl'] }
88
+ */
89
+ setGlyphs: 'setGlyphs',
90
+
91
+ /*
92
+ * { command: 'setTransition', args: [transition] }
93
+ */
94
+ setTransition: 'setTransition',
95
+
96
+ /*
97
+ * { command: 'setLighting', args: [lightProperties] }
98
+ */
99
+ setLight: 'setLight'
100
+
101
+ };
102
+
103
+ function addSource(sourceId, after, commands) {
104
+ commands.push({command: operations.addSource, args: [sourceId, after[sourceId]]});
105
+ }
106
+
107
+ function removeSource(sourceId, commands, sourcesRemoved) {
108
+ commands.push({command: operations.removeSource, args: [sourceId]});
109
+ sourcesRemoved[sourceId] = true;
110
+ }
111
+
112
+ function updateSource(sourceId, after, commands, sourcesRemoved) {
113
+ removeSource(sourceId, commands, sourcesRemoved);
114
+ addSource(sourceId, after, commands);
115
+ }
116
+
117
+ function canUpdateGeoJSON(before, after, sourceId) {
118
+ let prop;
119
+ for (prop in before[sourceId]) {
120
+ if (!before[sourceId].hasOwnProperty(prop)) continue;
121
+ if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {
122
+ return false;
123
+ }
124
+ }
125
+ for (prop in after[sourceId]) {
126
+ if (!after[sourceId].hasOwnProperty(prop)) continue;
127
+ if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {
128
+ return false;
129
+ }
130
+ }
131
+ return true;
132
+ }
133
+
134
+ function diffSources(before, after, commands, sourcesRemoved) {
135
+ before = before || {};
136
+ after = after || {};
137
+
138
+ let sourceId;
139
+
140
+ // look for sources to remove
141
+ for (sourceId in before) {
142
+ if (!before.hasOwnProperty(sourceId)) continue;
143
+ if (!after.hasOwnProperty(sourceId)) {
144
+ removeSource(sourceId, commands, sourcesRemoved);
145
+ }
146
+ }
147
+
148
+ // look for sources to add/update
149
+ for (sourceId in after) {
150
+ if (!after.hasOwnProperty(sourceId)) continue;
151
+ if (!before.hasOwnProperty(sourceId)) {
152
+ addSource(sourceId, after, commands);
153
+ } else if (!isEqual(before[sourceId], after[sourceId])) {
154
+ if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {
155
+ commands.push({command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data]});
156
+ } else {
157
+ // no update command, must remove then add
158
+ updateSource(sourceId, after, commands, sourcesRemoved);
159
+ }
160
+ }
161
+ }
162
+ }
163
+
164
+ function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {
165
+ before = before || {};
166
+ after = after || {};
167
+
168
+ let prop;
169
+
170
+ for (prop in before) {
171
+ if (!before.hasOwnProperty(prop)) continue;
172
+ if (!isEqual(before[prop], after[prop])) {
173
+ commands.push({command, args: [layerId, prop, after[prop], klass]});
174
+ }
175
+ }
176
+ for (prop in after) {
177
+ if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) continue;
178
+ if (!isEqual(before[prop], after[prop])) {
179
+ commands.push({command, args: [layerId, prop, after[prop], klass]});
180
+ }
181
+ }
182
+ }
183
+
184
+ function pluckId(layer) {
185
+ return layer.id;
186
+ }
187
+ function indexById(group, layer) {
188
+ group[layer.id] = layer;
189
+ return group;
190
+ }
191
+
192
+ function diffLayers(before, after, commands) {
193
+ before = before || [];
194
+ after = after || [];
195
+
196
+ // order of layers by id
197
+ const beforeOrder = before.map(pluckId);
198
+ const afterOrder = after.map(pluckId);
199
+
200
+ // index of layer by id
201
+ const beforeIndex = before.reduce(indexById, {});
202
+ const afterIndex = after.reduce(indexById, {});
203
+
204
+ // track order of layers as if they have been mutated
205
+ const tracker = beforeOrder.slice();
206
+
207
+ // layers that have been added do not need to be diffed
208
+ const clean = Object.create(null);
209
+
210
+ let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;
211
+
212
+ // remove layers
213
+ for (i = 0, d = 0; i < beforeOrder.length; i++) {
214
+ layerId = beforeOrder[i];
215
+ if (!afterIndex.hasOwnProperty(layerId)) {
216
+ commands.push({command: operations.removeLayer, args: [layerId]});
217
+ tracker.splice(tracker.indexOf(layerId, d), 1);
218
+ } else {
219
+ // limit where in tracker we need to look for a match
220
+ d++;
221
+ }
222
+ }
223
+
224
+ // add/reorder layers
225
+ for (i = 0, d = 0; i < afterOrder.length; i++) {
226
+ // work backwards as insert is before an existing layer
227
+ layerId = afterOrder[afterOrder.length - 1 - i];
228
+
229
+ if (tracker[tracker.length - 1 - i] === layerId) continue;
230
+
231
+ if (beforeIndex.hasOwnProperty(layerId)) {
232
+ // remove the layer before we insert at the correct position
233
+ commands.push({command: operations.removeLayer, args: [layerId]});
234
+ tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);
235
+ } else {
236
+ // limit where in tracker we need to look for a match
237
+ d++;
238
+ }
239
+
240
+ // add layer at correct position
241
+ insertBeforeLayerId = tracker[tracker.length - i];
242
+ commands.push({command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId]});
243
+ tracker.splice(tracker.length - i, 0, layerId);
244
+ clean[layerId] = true;
245
+ }
246
+
247
+ // update layers
248
+ for (i = 0; i < afterOrder.length; i++) {
249
+ layerId = afterOrder[i];
250
+ beforeLayer = beforeIndex[layerId];
251
+ afterLayer = afterIndex[layerId];
252
+
253
+ // no need to update if previously added (new or moved)
254
+ if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue;
255
+
256
+ // If source, source-layer, or type have changes, then remove the layer
257
+ // and add it back 'from scratch'.
258
+ if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) {
259
+ commands.push({command: operations.removeLayer, args: [layerId]});
260
+ // we add the layer back at the same position it was already in, so
261
+ // there's no need to update the `tracker`
262
+ insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];
263
+ commands.push({command: operations.addLayer, args: [afterLayer, insertBeforeLayerId]});
264
+ continue;
265
+ }
266
+
267
+ // layout, paint, filter, minzoom, maxzoom
268
+ diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);
269
+ diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);
270
+ if (!isEqual(beforeLayer.filter, afterLayer.filter)) {
271
+ commands.push({command: operations.setFilter, args: [layerId, afterLayer.filter]});
272
+ }
273
+ if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {
274
+ commands.push({command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom]});
275
+ }
276
+
277
+ // handle all other layer props, including paint.*
278
+ for (prop in beforeLayer) {
279
+ if (!beforeLayer.hasOwnProperty(prop)) continue;
280
+ if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||
281
+ prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;
282
+ if (prop.indexOf('paint.') === 0) {
283
+ diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
284
+ } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {
285
+ commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});
286
+ }
287
+ }
288
+ for (prop in afterLayer) {
289
+ if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) continue;
290
+ if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||
291
+ prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;
292
+ if (prop.indexOf('paint.') === 0) {
293
+ diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
294
+ } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {
295
+ commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});
296
+ }
297
+ }
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Diff two stylesheet
303
+ *
304
+ * Creates semanticly aware diffs that can easily be applied at runtime.
305
+ * Operations produced by the diff closely resemble the mapbox-gl-js API. Any
306
+ * error creating the diff will fall back to the 'setStyle' operation.
307
+ *
308
+ * Example diff:
309
+ * [
310
+ * { command: 'setConstant', args: ['@water', '#0000FF'] },
311
+ * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] }
312
+ * ]
313
+ *
314
+ * @private
315
+ * @param {*} [before] stylesheet to compare from
316
+ * @param {*} after stylesheet to compare to
317
+ * @returns Array list of changes
318
+ */
319
+ function diffStyles(before, after) {
320
+ if (!before) return [{command: operations.setStyle, args: [after]}];
321
+
322
+ let commands = [];
323
+
324
+ try {
325
+ // Handle changes to top-level properties
326
+ if (!isEqual(before.version, after.version)) {
327
+ return [{command: operations.setStyle, args: [after]}];
328
+ }
329
+ if (!isEqual(before.center, after.center)) {
330
+ commands.push({command: operations.setCenter, args: [after.center]});
331
+ }
332
+ if (!isEqual(before.zoom, after.zoom)) {
333
+ commands.push({command: operations.setZoom, args: [after.zoom]});
334
+ }
335
+ if (!isEqual(before.bearing, after.bearing)) {
336
+ commands.push({command: operations.setBearing, args: [after.bearing]});
337
+ }
338
+ if (!isEqual(before.pitch, after.pitch)) {
339
+ commands.push({command: operations.setPitch, args: [after.pitch]});
340
+ }
341
+ if (!isEqual(before.sprite, after.sprite)) {
342
+ commands.push({command: operations.setSprite, args: [after.sprite]});
343
+ }
344
+ if (!isEqual(before.glyphs, after.glyphs)) {
345
+ commands.push({command: operations.setGlyphs, args: [after.glyphs]});
346
+ }
347
+ if (!isEqual(before.transition, after.transition)) {
348
+ commands.push({command: operations.setTransition, args: [after.transition]});
349
+ }
350
+ if (!isEqual(before.light, after.light)) {
351
+ commands.push({command: operations.setLight, args: [after.light]});
352
+ }
353
+
354
+ // Handle changes to `sources`
355
+ // If a source is to be removed, we also--before the removeSource
356
+ // command--need to remove all the style layers that depend on it.
357
+ const sourcesRemoved = {};
358
+
359
+ // First collect the {add,remove}Source commands
360
+ const removeOrAddSourceCommands = [];
361
+ diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);
362
+
363
+ // Push a removeLayer command for each style layer that depends on a
364
+ // source that's being removed.
365
+ // Also, exclude any such layers them from the input to `diffLayers`
366
+ // below, so that diffLayers produces the appropriate `addLayers`
367
+ // command
368
+ const beforeLayers = [];
369
+ if (before.layers) {
370
+ before.layers.forEach((layer) => {
371
+ if (sourcesRemoved[layer.source]) {
372
+ commands.push({command: operations.removeLayer, args: [layer.id]});
373
+ } else {
374
+ beforeLayers.push(layer);
375
+ }
376
+ });
377
+ }
378
+ commands = commands.concat(removeOrAddSourceCommands);
379
+
380
+ // Handle changes to `layers`
381
+ diffLayers(beforeLayers, after.layers, commands);
382
+
383
+ } catch (e) {
384
+ // fall back to setStyle
385
+ console.warn('Unable to compute style diff:', e);
386
+ commands = [{command: operations.setStyle, args: [after]}];
387
+ }
388
+
389
+ return commands;
390
+ }
391
+
392
+ export default diffStyles;
393
+ export {operations};
node_modules/mapbox-gl/src/style-spec/dist/.gitkeep ADDED
File without changes
node_modules/mapbox-gl/src/style-spec/dist/index.es.js ADDED
The diff for this file is too large to render. See raw diff
 
node_modules/mapbox-gl/src/style-spec/dist/index.es.js.map ADDED
The diff for this file is too large to render. See raw diff
 
node_modules/mapbox-gl/src/style-spec/dist/index.js ADDED
The diff for this file is too large to render. See raw diff
 
node_modules/mapbox-gl/src/style-spec/dist/index.js.map ADDED
The diff for this file is too large to render. See raw diff
 
node_modules/mapbox-gl/src/style-spec/empty.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import latest from './reference/latest';
2
+
3
+ export default function emptyStyle() {
4
+ const style = {};
5
+
6
+ const version = latest['$version'];
7
+ for (const styleKey in latest['$root']) {
8
+ const spec = latest['$root'][styleKey];
9
+
10
+ if (spec.required) {
11
+ let value = null;
12
+ if (styleKey === 'version') {
13
+ value = version;
14
+ } else {
15
+ if (spec.type === 'array') {
16
+ value = [];
17
+ } else {
18
+ value = {};
19
+ }
20
+ }
21
+
22
+ if (value != null) {
23
+ style[styleKey] = value;
24
+ }
25
+ }
26
+ }
27
+
28
+ return style;
29
+ }
node_modules/mapbox-gl/src/style-spec/error/parsing_error.js ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ // Note: Do not inherit from Error. It breaks when transpiling to ES5.
4
+
5
+ export default class ParsingError {
6
+ message: string;
7
+ error: Error;
8
+ line: number;
9
+
10
+ constructor(error: Error) {
11
+ this.error = error;
12
+ this.message = error.message;
13
+ const match = error.message.match(/line (\d+)/);
14
+ this.line = match ? parseInt(match[1], 10) : 0;
15
+ }
16
+ }
node_modules/mapbox-gl/src/style-spec/error/validation_error.js ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ // Note: Do not inherit from Error. It breaks when transpiling to ES5.
4
+
5
+ export default class ValidationError {
6
+ message: string;
7
+ identifier: ?string;
8
+ line: ?number;
9
+
10
+ constructor(key: ?string, value: ?{ __line__: number }, message: string, identifier: ?string) {
11
+ this.message = (key ? `${key}: ` : '') + message;
12
+ if (identifier) this.identifier = identifier;
13
+
14
+ if (value !== null && value !== undefined && value.__line__) {
15
+ this.line = value.__line__;
16
+ }
17
+ }
18
+ }
node_modules/mapbox-gl/src/style-spec/expression/compound_expression.js ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {toString} from './types';
4
+
5
+ import ParsingContext from './parsing_context';
6
+ import EvaluationContext from './evaluation_context';
7
+ import assert from 'assert';
8
+
9
+ import type {Expression, ExpressionRegistry} from './expression';
10
+ import type {Type} from './types';
11
+ import type {Value} from './values';
12
+
13
+ export type Varargs = {| type: Type |};
14
+ type Signature = Array<Type> | Varargs;
15
+ type Evaluate = (EvaluationContext, Array<Expression>) => Value;
16
+ type Definition = [Type, Signature, Evaluate] |
17
+ {|type: Type, overloads: Array<[Signature, Evaluate]>|};
18
+
19
+ class CompoundExpression implements Expression {
20
+ name: string;
21
+ type: Type;
22
+ _evaluate: Evaluate;
23
+ args: Array<Expression>;
24
+
25
+ static definitions: {[_: string]: Definition };
26
+
27
+ constructor(name: string, type: Type, evaluate: Evaluate, args: Array<Expression>) {
28
+ this.name = name;
29
+ this.type = type;
30
+ this._evaluate = evaluate;
31
+ this.args = args;
32
+ }
33
+
34
+ evaluate(ctx: EvaluationContext) {
35
+ return this._evaluate(ctx, this.args);
36
+ }
37
+
38
+ eachChild(fn: (_: Expression) => void) {
39
+ this.args.forEach(fn);
40
+ }
41
+
42
+ outputDefined() {
43
+ return false;
44
+ }
45
+
46
+ serialize(): Array<mixed> {
47
+ return [this.name].concat(this.args.map(arg => arg.serialize()));
48
+ }
49
+
50
+ static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {
51
+ const op: string = (args[0]: any);
52
+ const definition = CompoundExpression.definitions[op];
53
+ if (!definition) {
54
+ return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0);
55
+ }
56
+
57
+ // Now check argument types against each signature
58
+ const type = Array.isArray(definition) ?
59
+ definition[0] : definition.type;
60
+
61
+ const availableOverloads = Array.isArray(definition) ?
62
+ [[definition[1], definition[2]]] :
63
+ definition.overloads;
64
+
65
+ const overloads = availableOverloads.filter(([signature]) => (
66
+ !Array.isArray(signature) || // varags
67
+ signature.length === args.length - 1 // correct param count
68
+ ));
69
+
70
+ let signatureContext: ParsingContext = (null: any);
71
+
72
+ for (const [params, evaluate] of overloads) {
73
+ // Use a fresh context for each attempted signature so that, if
74
+ // we eventually succeed, we haven't polluted `context.errors`.
75
+ signatureContext = new ParsingContext(context.registry, context.path, null, context.scope);
76
+
77
+ // First parse all the args, potentially coercing to the
78
+ // types expected by this overload.
79
+ const parsedArgs: Array<Expression> = [];
80
+ let argParseFailed = false;
81
+ for (let i = 1; i < args.length; i++) {
82
+ const arg = args[i];
83
+ const expectedType = Array.isArray(params) ?
84
+ params[i - 1] :
85
+ params.type;
86
+
87
+ const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);
88
+ if (!parsed) {
89
+ argParseFailed = true;
90
+ break;
91
+ }
92
+ parsedArgs.push(parsed);
93
+ }
94
+ if (argParseFailed) {
95
+ // Couldn't coerce args of this overload to expected type, move
96
+ // on to next one.
97
+ continue;
98
+ }
99
+
100
+ if (Array.isArray(params)) {
101
+ if (params.length !== parsedArgs.length) {
102
+ signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);
103
+ continue;
104
+ }
105
+ }
106
+
107
+ for (let i = 0; i < parsedArgs.length; i++) {
108
+ const expected = Array.isArray(params) ? params[i] : params.type;
109
+ const arg = parsedArgs[i];
110
+ signatureContext.concat(i + 1).checkSubtype(expected, arg.type);
111
+ }
112
+
113
+ if (signatureContext.errors.length === 0) {
114
+ return new CompoundExpression(op, type, evaluate, parsedArgs);
115
+ }
116
+ }
117
+
118
+ assert(!signatureContext || signatureContext.errors.length > 0);
119
+
120
+ if (overloads.length === 1) {
121
+ context.errors.push(...signatureContext.errors);
122
+ } else {
123
+ const expected = overloads.length ? overloads : availableOverloads;
124
+ const signatures = expected
125
+ .map(([params]) => stringifySignature(params))
126
+ .join(' | ');
127
+
128
+ const actualTypes = [];
129
+ // For error message, re-parse arguments without trying to
130
+ // apply any coercions
131
+ for (let i = 1; i < args.length; i++) {
132
+ const parsed = context.parse(args[i], 1 + actualTypes.length);
133
+ if (!parsed) return null;
134
+ actualTypes.push(toString(parsed.type));
135
+ }
136
+ context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);
137
+ }
138
+
139
+ return null;
140
+ }
141
+
142
+ static register(
143
+ registry: ExpressionRegistry,
144
+ definitions: {[_: string]: Definition }
145
+ ) {
146
+ assert(!CompoundExpression.definitions);
147
+ CompoundExpression.definitions = definitions;
148
+ for (const name in definitions) {
149
+ registry[name] = CompoundExpression;
150
+ }
151
+ }
152
+ }
153
+
154
+ function stringifySignature(signature: Signature): string {
155
+ if (Array.isArray(signature)) {
156
+ return `(${signature.map(toString).join(', ')})`;
157
+ } else {
158
+ return `(${toString(signature.type)}...)`;
159
+ }
160
+ }
161
+
162
+ export default CompoundExpression;
node_modules/mapbox-gl/src/style-spec/expression/definitions/assertion.js ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import assert from 'assert';
4
+
5
+ import {
6
+ ObjectType,
7
+ ValueType,
8
+ StringType,
9
+ NumberType,
10
+ BooleanType,
11
+ checkSubtype,
12
+ toString,
13
+ array
14
+ } from '../types';
15
+ import RuntimeError from '../runtime_error';
16
+ import {typeOf} from '../values';
17
+
18
+ import type {Expression} from '../expression';
19
+ import type ParsingContext from '../parsing_context';
20
+ import type EvaluationContext from '../evaluation_context';
21
+ import type {Type} from '../types';
22
+
23
+ const types = {
24
+ string: StringType,
25
+ number: NumberType,
26
+ boolean: BooleanType,
27
+ object: ObjectType
28
+ };
29
+
30
+ class Assertion implements Expression {
31
+ type: Type;
32
+ args: Array<Expression>;
33
+
34
+ constructor(type: Type, args: Array<Expression>) {
35
+ this.type = type;
36
+ this.args = args;
37
+ }
38
+
39
+ static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {
40
+ if (args.length < 2)
41
+ return context.error(`Expected at least one argument.`);
42
+
43
+ let i = 1;
44
+ let type;
45
+
46
+ const name: string = (args[0]: any);
47
+ if (name === 'array') {
48
+ let itemType;
49
+ if (args.length > 2) {
50
+ const type = args[1];
51
+ if (typeof type !== 'string' || !(type in types) || type === 'object')
52
+ return context.error('The item type argument of "array" must be one of string, number, boolean', 1);
53
+ itemType = types[type];
54
+ i++;
55
+ } else {
56
+ itemType = ValueType;
57
+ }
58
+
59
+ let N;
60
+ if (args.length > 3) {
61
+ if (args[2] !== null &&
62
+ (typeof args[2] !== 'number' ||
63
+ args[2] < 0 ||
64
+ args[2] !== Math.floor(args[2]))
65
+ ) {
66
+ return context.error('The length argument to "array" must be a positive integer literal', 2);
67
+ }
68
+ N = args[2];
69
+ i++;
70
+ }
71
+
72
+ type = array(itemType, N);
73
+ } else {
74
+ assert(types[name], name);
75
+ type = types[name];
76
+ }
77
+
78
+ const parsed = [];
79
+ for (; i < args.length; i++) {
80
+ const input = context.parse(args[i], i, ValueType);
81
+ if (!input) return null;
82
+ parsed.push(input);
83
+ }
84
+
85
+ return new Assertion(type, parsed);
86
+ }
87
+
88
+ evaluate(ctx: EvaluationContext) {
89
+ for (let i = 0; i < this.args.length; i++) {
90
+ const value = this.args[i].evaluate(ctx);
91
+ const error = checkSubtype(this.type, typeOf(value));
92
+ if (!error) {
93
+ return value;
94
+ } else if (i === this.args.length - 1) {
95
+ throw new RuntimeError(`Expected value to be of type ${toString(this.type)}, but found ${toString(typeOf(value))} instead.`);
96
+ }
97
+ }
98
+
99
+ assert(false);
100
+ return null;
101
+ }
102
+
103
+ eachChild(fn: (_: Expression) => void) {
104
+ this.args.forEach(fn);
105
+ }
106
+
107
+ outputDefined(): boolean {
108
+ return this.args.every(arg => arg.outputDefined());
109
+ }
110
+
111
+ serialize(): Array<mixed> {
112
+ const type = this.type;
113
+ const serialized = [type.kind];
114
+ if (type.kind === 'array') {
115
+ const itemType = type.itemType;
116
+ if (itemType.kind === 'string' ||
117
+ itemType.kind === 'number' ||
118
+ itemType.kind === 'boolean') {
119
+ serialized.push(itemType.kind);
120
+ const N = type.N;
121
+ if (typeof N === 'number' || this.args.length > 1) {
122
+ serialized.push(N);
123
+ }
124
+ }
125
+ }
126
+ return serialized.concat(this.args.map(arg => arg.serialize()));
127
+ }
128
+ }
129
+
130
+ export default Assertion;
node_modules/mapbox-gl/src/style-spec/expression/definitions/at.js ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import {array, ValueType, NumberType} from '../types';
4
+
5
+ import RuntimeError from '../runtime_error';
6
+
7
+ import type {Expression} from '../expression';
8
+ import type ParsingContext from '../parsing_context';
9
+ import type EvaluationContext from '../evaluation_context';
10
+ import type {Type, ArrayType} from '../types';
11
+ import type {Value} from '../values';
12
+
13
+ class At implements Expression {
14
+ type: Type;
15
+ index: Expression;
16
+ input: Expression;
17
+
18
+ constructor(type: Type, index: Expression, input: Expression) {
19
+ this.type = type;
20
+ this.index = index;
21
+ this.input = input;
22
+ }
23
+
24
+ static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext) {
25
+ if (args.length !== 3)
26
+ return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);
27
+
28
+ const index = context.parse(args[1], 1, NumberType);
29
+ const input = context.parse(args[2], 2, array(context.expectedType || ValueType));
30
+
31
+ if (!index || !input) return null;
32
+
33
+ const t: ArrayType = (input.type: any);
34
+ return new At(t.itemType, index, input);
35
+ }
36
+
37
+ evaluate(ctx: EvaluationContext) {
38
+ const index = ((this.index.evaluate(ctx): any): number);
39
+ const array = ((this.input.evaluate(ctx): any): Array<Value>);
40
+
41
+ if (index < 0) {
42
+ throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);
43
+ }
44
+
45
+ if (index >= array.length) {
46
+ throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);
47
+ }
48
+
49
+ if (index !== Math.floor(index)) {
50
+ throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);
51
+ }
52
+
53
+ return array[index];
54
+ }
55
+
56
+ eachChild(fn: (_: Expression) => void) {
57
+ fn(this.index);
58
+ fn(this.input);
59
+ }
60
+
61
+ outputDefined() {
62
+ return false;
63
+ }
64
+
65
+ serialize() {
66
+ return ["at", this.index.serialize(), this.input.serialize()];
67
+ }
68
+ }
69
+
70
+ export default At;
node_modules/mapbox-gl/src/style-spec/expression/definitions/case.js ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import assert from 'assert';
4
+
5
+ import {BooleanType} from '../types';
6
+
7
+ import type {Expression} from '../expression';
8
+ import type ParsingContext from '../parsing_context';
9
+ import type EvaluationContext from '../evaluation_context';
10
+ import type {Type} from '../types';
11
+
12
+ type Branches = Array<[Expression, Expression]>;
13
+
14
+ class Case implements Expression {
15
+ type: Type;
16
+
17
+ branches: Branches;
18
+ otherwise: Expression;
19
+
20
+ constructor(type: Type, branches: Branches, otherwise: Expression) {
21
+ this.type = type;
22
+ this.branches = branches;
23
+ this.otherwise = otherwise;
24
+ }
25
+
26
+ static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext) {
27
+ if (args.length < 4)
28
+ return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`);
29
+ if (args.length % 2 !== 0)
30
+ return context.error(`Expected an odd number of arguments.`);
31
+
32
+ let outputType: ?Type;
33
+ if (context.expectedType && context.expectedType.kind !== 'value') {
34
+ outputType = context.expectedType;
35
+ }
36
+
37
+ const branches = [];
38
+ for (let i = 1; i < args.length - 1; i += 2) {
39
+ const test = context.parse(args[i], i, BooleanType);
40
+ if (!test) return null;
41
+
42
+ const result = context.parse(args[i + 1], i + 1, outputType);
43
+ if (!result) return null;
44
+
45
+ branches.push([test, result]);
46
+
47
+ outputType = outputType || result.type;
48
+ }
49
+
50
+ const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);
51
+ if (!otherwise) return null;
52
+
53
+ assert(outputType);
54
+ return new Case((outputType: any), branches, otherwise);
55
+ }
56
+
57
+ evaluate(ctx: EvaluationContext) {
58
+ for (const [test, expression] of this.branches) {
59
+ if (test.evaluate(ctx)) {
60
+ return expression.evaluate(ctx);
61
+ }
62
+ }
63
+ return this.otherwise.evaluate(ctx);
64
+ }
65
+
66
+ eachChild(fn: (_: Expression) => void) {
67
+ for (const [test, expression] of this.branches) {
68
+ fn(test);
69
+ fn(expression);
70
+ }
71
+ fn(this.otherwise);
72
+ }
73
+
74
+ outputDefined(): boolean {
75
+ return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();
76
+ }
77
+
78
+ serialize() {
79
+ const serialized = ["case"];
80
+ this.eachChild(child => { serialized.push(child.serialize()); });
81
+ return serialized;
82
+ }
83
+ }
84
+
85
+ export default Case;
node_modules/mapbox-gl/src/style-spec/expression/definitions/coalesce.js ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @flow
2
+
3
+ import assert from 'assert';
4
+
5
+ import {checkSubtype, ValueType} from '../types';
6
+ import ResolvedImage from '../types/resolved_image';
7
+
8
+ import type {Expression} from '../expression';
9
+ import type ParsingContext from '../parsing_context';
10
+ import type EvaluationContext from '../evaluation_context';
11
+ import type {Type} from '../types';
12
+
13
+ class Coalesce implements Expression {
14
+ type: Type;
15
+ args: Array<Expression>;
16
+
17
+ constructor(type: Type, args: Array<Expression>) {
18
+ this.type = type;
19
+ this.args = args;
20
+ }
21
+
22
+ static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext) {
23
+ if (args.length < 2) {
24
+ return context.error("Expectected at least one argument.");
25
+ }
26
+ let outputType: Type = (null: any);
27
+ const expectedType = context.expectedType;
28
+ if (expectedType && expectedType.kind !== 'value') {
29
+ outputType = expectedType;
30
+ }
31
+ const parsedArgs = [];
32
+
33
+ for (const arg of args.slice(1)) {
34
+ const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, {typeAnnotation: 'omit'});
35
+ if (!parsed) return null;
36
+ outputType = outputType || parsed.type;
37
+ parsedArgs.push(parsed);
38
+ }
39
+ assert(outputType);
40
+
41
+ // Above, we parse arguments without inferred type annotation so that
42
+ // they don't produce a runtime error for `null` input, which would
43
+ // preempt the desired null-coalescing behavior.
44
+ // Thus, if any of our arguments would have needed an annotation, we
45
+ // need to wrap the enclosing coalesce expression with it instead.
46
+ const needsAnnotation = expectedType &&
47
+ parsedArgs.some(arg => checkSubtype(expectedType, arg.type));
48
+
49
+ return needsAnnotation ?
50
+ new Coalesce(ValueType, parsedArgs) :
51
+ new Coalesce((outputType: any), parsedArgs);
52
+ }
53
+
54
+ evaluate(ctx: EvaluationContext) {
55
+ let result = null;
56
+ let argCount = 0;
57
+ let requestedImageName;
58
+ for (const arg of this.args) {
59
+ argCount++;
60
+ result = arg.evaluate(ctx);
61
+ // we need to keep track of the first requested image in a coalesce statement
62
+ // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire
63
+ if (result && result instanceof ResolvedImage && !result.available) {
64
+ if (!requestedImageName) {
65
+ requestedImageName = result.name;
66
+ }
67
+ result = null;
68
+ if (argCount === this.args.length) {
69
+ result = requestedImageName;
70
+ }
71
+ }
72
+
73
+ if (result !== null) break;
74
+ }
75
+ return result;
76
+ }
77
+
78
+ eachChild(fn: (_: Expression) => void) {
79
+ this.args.forEach(fn);
80
+ }
81
+
82
+ outputDefined(): boolean {
83
+ return this.args.every(arg => arg.outputDefined());
84
+ }
85
+
86
+ serialize() {
87
+ const serialized = ["coalesce"];
88
+ this.eachChild(child => { serialized.push(child.serialize()); });
89
+ return serialized;
90
+ }
91
+ }
92
+
93
+ export default Coalesce;