@tangram.gl/basemap-layers 0.0.0 → 10.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +12 -7
  2. package/THIRD-PARTY-NOTICES.md +7 -5
  3. package/dist/geojson-task-worker.js +3166 -0
  4. package/dist/geojson-task-worker.js.map +6 -0
  5. package/dist/geojson-worker.js +1089 -7
  6. package/dist/geojson-worker.js.map +3 -3
  7. package/dist/index.cjs +9588 -2093
  8. package/dist/index.cjs.map +3 -3
  9. package/dist/index.js +9599 -2090
  10. package/dist/index.js.map +3 -3
  11. package/dist/map-style.cjs +456 -20
  12. package/dist/map-style.cjs.map +3 -3
  13. package/dist/map-style.js +456 -19
  14. package/dist/map-style.js.map +2 -2
  15. package/dist/types/basemap-error.d.ts +52 -0
  16. package/dist/types/basemap-layer.d.ts +378 -25
  17. package/dist/types/basemap-protocol.d.ts +91 -0
  18. package/dist/types/basemap-request.d.ts +73 -0
  19. package/dist/types/circle-layer.d.ts +65 -8
  20. package/dist/types/color-relief-layer.d.ts +184 -0
  21. package/dist/types/dem-pixels.d.ts +40 -0
  22. package/dist/types/feature-state.d.ts +55 -0
  23. package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
  24. package/dist/types/fill-outline-extension.d.ts +2 -3
  25. package/dist/types/fill-pattern.d.ts +35 -3
  26. package/dist/types/fill-style-extensions.d.ts +11 -59
  27. package/dist/types/geojson-resource.d.ts +18 -0
  28. package/dist/types/geojson-source.d.ts +13 -2
  29. package/dist/types/geojson-task-handler.d.ts +2 -0
  30. package/dist/types/geojson-task.d.ts +26 -0
  31. package/dist/types/geojson-tiler.d.ts +29 -2
  32. package/dist/types/geojson-worker.d.ts +5 -1
  33. package/dist/types/globe-horizon-extension.d.ts +2 -45
  34. package/dist/types/globe-layers.d.ts +141 -45
  35. package/dist/types/globe-line-angle-extension.d.ts +20 -17
  36. package/dist/types/glyph-store.d.ts +10 -1
  37. package/dist/types/heatmap-layer.d.ts +99 -0
  38. package/dist/types/hillshade-layer.d.ts +159 -27
  39. package/dist/types/icon-text-fit.d.ts +92 -0
  40. package/dist/types/image-source-layer.d.ts +142 -0
  41. package/dist/types/index.d.ts +25 -1
  42. package/dist/types/line-blur-extension.d.ts +3 -11
  43. package/dist/types/line-dash-extension.d.ts +53 -0
  44. package/dist/types/line-gradient-extension.d.ts +69 -0
  45. package/dist/types/line-metrics.d.ts +24 -0
  46. package/dist/types/line-pattern-extension.d.ts +50 -0
  47. package/dist/types/line-shape-extension.d.ts +76 -0
  48. package/dist/types/map-style-loader.d.ts +1 -1
  49. package/dist/types/map-style.d.ts +2 -2
  50. package/dist/types/mvt-label-layer.d.ts +111 -20
  51. package/dist/types/pmtiles-source.d.ts +38 -0
  52. package/dist/types/projected-background-layer.d.ts +63 -0
  53. package/dist/types/projected-bitmap-layer.d.ts +58 -0
  54. package/dist/types/projected-tile-data.d.ts +16 -0
  55. package/dist/types/projected-tile-selection.d.ts +72 -0
  56. package/dist/types/projected-tileset.d.ts +92 -0
  57. package/dist/types/projected-viewport.d.ts +76 -0
  58. package/dist/types/raster-color-extension.d.ts +4 -7
  59. package/dist/types/raster-fade.d.ts +155 -0
  60. package/dist/types/raster-tile-fingerprint.d.ts +11 -0
  61. package/dist/types/raster-tile-loader.d.ts +80 -0
  62. package/dist/types/shader-injection-plugin.d.ts +8 -0
  63. package/dist/types/source-features.d.ts +58 -0
  64. package/dist/types/source-tiles.d.ts +32 -0
  65. package/dist/types/sprite.d.ts +37 -3
  66. package/dist/types/stretch-icon-layer.d.ts +28 -0
  67. package/dist/types/style-accessor.d.ts +50 -12
  68. package/dist/types/style-expression.d.ts +22 -2
  69. package/dist/types/style-resolver.d.ts +47 -2
  70. package/dist/types/terrain-query.d.ts +39 -0
  71. package/dist/types/zoom-load-gate.d.ts +22 -0
  72. package/dist/types/zoom-paint-extension.d.ts +80 -11
  73. package/package.json +24 -21
  74. package/src/basemap-error.ts +82 -0
  75. package/src/basemap-layer.ts +1289 -101
  76. package/src/basemap-protocol.ts +353 -0
  77. package/src/basemap-request.ts +212 -0
  78. package/src/circle-layer.ts +430 -54
  79. package/src/color-relief-layer.ts +572 -0
  80. package/src/dem-pixels.ts +174 -0
  81. package/src/feature-state.ts +164 -0
  82. package/src/fill-extrusion-lighting-extension.ts +126 -9
  83. package/src/fill-outline-extension.ts +4 -4
  84. package/src/fill-pattern.ts +87 -9
  85. package/src/fill-style-extensions.ts +114 -44
  86. package/src/geojson-resource.ts +58 -0
  87. package/src/geojson-source.ts +106 -85
  88. package/src/geojson-task-handler.ts +11 -0
  89. package/src/geojson-task-worker.ts +8 -0
  90. package/src/geojson-task.ts +34 -0
  91. package/src/geojson-tiler.ts +270 -4
  92. package/src/geojson-worker.ts +36 -6
  93. package/src/globe-horizon-extension.ts +14 -4
  94. package/src/globe-layers.ts +1905 -406
  95. package/src/globe-line-angle-extension.ts +183 -23
  96. package/src/glyph-store.ts +28 -6
  97. package/src/heatmap-layer.ts +591 -0
  98. package/src/hillshade-layer.ts +309 -88
  99. package/src/icon-text-fit.ts +358 -0
  100. package/src/image-source-layer.ts +380 -0
  101. package/src/index.ts +58 -1
  102. package/src/line-blur-extension.ts +14 -12
  103. package/src/line-dash-extension.ts +303 -0
  104. package/src/line-gradient-extension.ts +191 -0
  105. package/src/line-metrics.ts +90 -0
  106. package/src/line-pattern-extension.ts +173 -0
  107. package/src/line-shape-extension.ts +272 -0
  108. package/src/map-style-loader.ts +5 -4
  109. package/src/map-style.ts +2 -1
  110. package/src/mvt-label-layer.ts +568 -144
  111. package/src/pmtiles-source.ts +276 -0
  112. package/src/projected-background-layer.ts +202 -0
  113. package/src/projected-bitmap-layer.ts +262 -0
  114. package/src/projected-tile-data.ts +132 -0
  115. package/src/projected-tile-selection.ts +605 -0
  116. package/src/projected-tileset.ts +183 -0
  117. package/src/projected-viewport.ts +254 -0
  118. package/src/raster-color-extension.ts +43 -18
  119. package/src/raster-fade.ts +319 -0
  120. package/src/raster-tile-fingerprint.ts +31 -0
  121. package/src/raster-tile-loader.ts +211 -0
  122. package/src/shader-injection-plugin.ts +25 -0
  123. package/src/source-features.ts +170 -0
  124. package/src/source-tiles.ts +102 -0
  125. package/src/sprite.ts +122 -15
  126. package/src/stretch-icon-layer.ts +87 -0
  127. package/src/style-accessor.ts +105 -17
  128. package/src/style-expression.ts +80 -3
  129. package/src/style-resolver.ts +200 -22
  130. package/src/terrain-query.ts +86 -0
  131. package/src/text-layout.ts +2 -3
  132. package/src/zoom-load-gate.ts +57 -0
  133. package/src/zoom-paint-extension.ts +245 -47
  134. package/dist/types/arabic-shaping.d.ts +0 -7
  135. package/dist/types/bidi.d.ts +0 -8
  136. package/dist/types/polylabel.d.ts +0 -17
  137. package/src/arabic-shaping.ts +0 -366
  138. package/src/bidi.ts +0 -199
  139. package/src/polylabel.ts +0 -312
@@ -2,27 +2,54 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
- import {SharedMVTLayer, SharedTileset2D} from '@deck.gl-community/geo-layers';
5
+ import {
6
+ SharedMVTLayer,
7
+ SharedTile2DLayer,
8
+ SharedTileset2D,
9
+ type SharedTile2DHeader,
10
+ type SharedTileset2DAdapter
11
+ } from '@deck.gl-community/layers/geo-layers';
12
+ import type {RequestScheduler} from '@loaders.gl/core/loader-utils';
13
+ import {TileLayer, type Tile2DHeader} from '@deck.gl/geo-layers';
14
+ import {pickTerrainSurface, type TerrainSurface, type TerrainSurfaceHit} from './terrain-query';
6
15
  import {isGlobeViewport} from './is-globe-viewport';
7
- import type {BasemapSource} from './style-resolver';
16
+ import {ZoomLoadGate} from './zoom-load-gate';
17
+ import {getStyleZoom, isProjectedViewport} from './projected-viewport';
18
+ import {isGeographicFirstPersonViewport} from './projected-background-layer';
19
+ import {getBasemapTilesetAdapter} from './projected-tileset';
20
+ import {getSourceTileBounds, getSourceTileTemplates} from './source-tiles';
21
+ import {DEFAULT_MAX_STRETCH} from './projected-tile-selection';
22
+ import {fetchJson, resolveBasemapStyle, getSourceKey, loadGeoJsonData, type BasemapSource} from './style-resolver';
23
+ import type {BasemapFeatureState} from './feature-state';
8
24
  import {
9
25
  CompositeLayer,
10
26
  log,
11
27
  type DefaultProps,
28
+ type GetPickingInfoParams,
29
+ type Layer,
30
+ type LayersList,
31
+ type PickingInfo,
12
32
  type UpdateParameters,
13
33
  type Viewport
14
34
  } from '@deck.gl/core';
15
- import {load} from '@loaders.gl/core';
35
+ import {derefLayers, diff, type StyleSpecification} from '@maplibre/maplibre-gl-style-spec';
36
+ import {getBasemapTileFetch, type BasemapTransformRequest} from './basemap-request';
16
37
  import {
17
38
  createDemTileset,
18
39
  getBasemapLayers,
40
+ getInsertionError,
19
41
  getSourceLoadOptions,
20
42
  getStyleDefinitionZoomLimits,
21
43
  getStyleSourceLayers,
44
+ getStyleLayerPropsMap,
22
45
  getTilePyramidProps,
23
46
  getVectorTileLoader,
47
+ isDrawnStyleLayer,
24
48
  isVectorTileSource,
25
- VECTOR_TILE_ZOOM_OFFSET
49
+ VECTOR_TILE_ZOOM_OFFSET,
50
+ type StyleLayerPropsMap,
51
+ type StyleLayerSubLayerProps,
52
+ withTransformRequest
26
53
  } from './globe-layers';
27
54
  import {
28
55
  acquireSharedLabelPlacement,
@@ -32,13 +59,33 @@ import {
32
59
  releaseSharedLabelPlacement
33
60
  } from './label-placement';
34
61
  import {MapStyleLoader, type MapStyleLoaderOptions} from './map-style-loader';
62
+ import {BasemapStyleSchema, ResolvedBasemapStyleSchema} from './map-style-schema';
35
63
  import {getDemUnpackVector} from './hillshade-layer';
64
+ import {getTileLoadOptions} from './pmtiles-source';
36
65
  import {getStyleZoomKey} from './style-accessor';
37
- import type {BasemapStyle, ResolvedBasemapStyle} from './style-resolver';
66
+ import {getResolvedBasemapStyleBaseUrl, isResolvedBasemapStyle} from './style-resolver';
67
+ import type {
68
+ BasemapLoadOptions,
69
+ BasemapStyle,
70
+ ResolvedBasemapStyle,
71
+ ResolvedBasemapStyleLayer
72
+ } from './style-resolver';
38
73
  import {GlyphStore} from './glyph-store';
39
- import {loadSpriteAtlases} from './sprite';
74
+ import {getSpriteSources, loadSpriteAtlases} from './sprite';
40
75
  import type {SpriteAtlas} from './sprite';
41
76
  import type {LabelFontFamily} from './text-font';
77
+ import type {RejectRasterTile} from './raster-tile-loader';
78
+ import {
79
+ type BasemapLoadError,
80
+ type BasemapLoadErrorHandler,
81
+ getBasemapLoadError,
82
+ isAbortError
83
+ } from './basemap-error';
84
+ import {
85
+ querySourceFeaturesInTiles,
86
+ type BasemapSourceFeature,
87
+ type QuerySourceFeaturesOptions
88
+ } from './source-features';
42
89
 
43
90
  /**
44
91
  * Logs a non-error basemap-layer runtime event to deck.gl logging.
@@ -47,50 +94,129 @@ function logBasemapLayerEvent(message: string, details?: unknown): void {
47
94
  log.probe(1, message, details ?? '')();
48
95
  }
49
96
 
50
- /**
51
- * Logs a basemap-layer runtime error to deck.gl logging.
52
- */
97
+ /** Logs a basemap-layer runtime error to deck.gl logging. */
53
98
  function logBasemapLayerError(message: string, error: Error): void {
54
99
  log.error(`${message}: ${error.message}`)();
55
100
  }
56
101
 
57
102
  function getMapStyleLoaderOptions(
58
- loadOptions: BasemapLayerProps['loadOptions']
103
+ loadOptions: BasemapLayerProps['loadOptions'],
104
+ sourceCache: Map<string, BasemapSource>,
105
+ onError: BasemapLoadErrorHandler
59
106
  ): MapStyleLoaderOptions {
107
+ const {fetch: fetchFn, fetchOptions} = (loadOptions || {}) as NonNullable<BasemapLoadOptions>;
60
108
  return {
61
- mapStyle: (loadOptions || undefined) as NonNullable<MapStyleLoaderOptions['mapStyle']>
109
+ ...(fetchFn || fetchOptions
110
+ ? {
111
+ fetch: (url: string, init?: RequestInit) =>
112
+ (fetchFn || fetch)(url, {...init, ...fetchOptions})
113
+ }
114
+ : {}),
115
+ mapStyle: {...loadOptions, sourceCache, onError} as NonNullable<MapStyleLoaderOptions['mapStyle']>
62
116
  };
63
117
  }
64
118
 
65
119
  /**
66
- * Globe-related runtime toggles used by {@link BasemapLayer}.
120
+ * Drawing toggles of the basemap helpers (`getBasemapLayers`). They apply in every mode, not only
121
+ * on a globe. `BasemapLayer` takes them as the flat `labels` and `atmosphere` props.
67
122
  */
68
123
  export type BasemapGlobeConfig = {
69
- /** Renders the atmosphere overlays returned by the globe helpers when available. */
124
+ /** Draws the atmosphere in globe mode. Default `false`. */
70
125
  atmosphere?: boolean;
71
- /** Renders the main globe basemap content when `true`. */
126
+ /** Draws the style layers. Default `true`. `false` draws only the atmosphere. */
72
127
  basemap?: boolean;
73
- /** Enables symbol-label rendering on the globe path when `true`. */
128
+ /** Draws the style's symbol layers (labels and icons). Default `true`. */
74
129
  labels?: boolean;
75
130
  };
76
131
 
132
+ /** A tile given to `onTileLoad` and `onViewportLoad`: deck.gl's tile header. */
133
+ export type BasemapTile = Tile2DHeader | SharedTile2DHeader;
134
+
135
+ /**
136
+ * The data of a `geojson` source in {@link BasemapLayerProps.sourceData}: a GeoJSON object, or the
137
+ * URL of one, as the source's `data` in the style.
138
+ */
139
+ export type BasemapSourceData = object | string;
140
+
141
+ /**
142
+ * deck.gl layers that {@link BasemapLayer} draws inside the style order (see
143
+ * `BasemapLayerProps.insertLayers`).
144
+ */
145
+ export type BasemapInsertion = {
146
+ /**
147
+ * The id of the style layer to draw `layers` before, as the `beforeId` of MapLibre GL JS's
148
+ * `addLayer`. Omit it to draw `layers` over the whole basemap.
149
+ */
150
+ beforeId?: string | null;
151
+ /** The deck.gl layers to draw. */
152
+ layers: LayersList;
153
+ };
154
+
155
+ /** The `loadOptions` of {@link BasemapLayer}: basemap request options and loaders.gl options. */
156
+ export type BasemapLayerLoadOptions = NonNullable<BasemapLoadOptions> & Record<string, unknown>;
157
+
77
158
  /**
78
159
  * Props accepted by {@link BasemapLayer}.
79
160
  */
80
161
  export type BasemapLayerProps = {
81
162
  /** Optional deck.gl layer identifier. */
82
163
  id?: string;
83
- /** MapLibre or Mapbox style JSON, or a URL that resolves to one. */
84
- style: string | BasemapStyle | null;
85
- /** Load options forwarded to {@link resolveBasemapStyle}. */
86
- loadOptions?: Record<string, unknown> | null;
87
- /** Selects whether deck layers are generated for a flat map or a globe. */
88
- mode?: 'map' | 'globe';
89
- /** Optional globe-specific configuration used when `mode` is `'globe'`. */
164
+ /**
165
+ * MapLibre or Mapbox style JSON, a URL that resolves to one, or a resolved style. A resolved
166
+ * style draws at once without fetching its TileJSON and GeoJSON data again. A copy resolves again.
167
+ * Default `null`.
168
+ */
169
+ style?: string | BasemapStyle | ResolvedBasemapStyle | null;
170
+ /**
171
+ * Options for the requests of the layer, and loaders.gl options for its tiles:
172
+ * - `baseUrl`, `fetch` and `fetchOptions` apply to the TileJSON, GeoJSON `data`, sprite and
173
+ * glyph requests (see `resolveBasemapStyle`). With `rejectRasterTile`, they also apply to
174
+ * raster tiles.
175
+ * - loaders.gl namespaces such as `mvt` and `core` go to the tile loaders, with the deck.gl
176
+ * `fetch` prop.
177
+ * - A style URL loads with `MapStyleLoader`, with these options as its `mapStyle` options.
178
+ */
179
+ loadOptions?: BasemapLayerLoadOptions | null;
180
+ /**
181
+ * Changes each request the layer makes before it is sent, as MapLibre GL JS's `transformRequest`
182
+ * map option: the style, TileJSON, GeoJSON data, vector, raster and raster-dem tiles, sprites and
183
+ * glyphs. It receives the absolute URL and the resource type (see `BasemapResourceType`), and
184
+ * returns the URL to request, with `headers`, `credentials`, `method`, `body` or `cache`, or
185
+ * nothing to send the request as it is. The request is then sent with `loadOptions.fetch`.
186
+ * Fields it returns replace those of `loadOptions.fetchOptions`; headers merge by name. Pass a
187
+ * stable function: the style and its tiles load again when it changes.
188
+ */
189
+ transformRequest?: BasemapTransformRequest | null;
190
+ /**
191
+ * Selects whether the sublayers draw as a flat map or on a globe. `'auto'` (the default) reads
192
+ * it from the viewport: globe sublayers in a deck.gl `GlobeView`, map sublayers in other views.
193
+ * `'map'` and `'globe'` override the viewport.
194
+ */
195
+ mode?: 'auto' | 'map' | 'globe';
196
+ /**
197
+ * The state of features, which `["feature-state", key]` reads in paint properties, as MapLibre
198
+ * GL JS's `setFeatureState` sets it: by source id, then, for a `vector` source, by source layer,
199
+ * then by feature id. Pass a new object to change a state; a change computes again only the paint
200
+ * attributes of the style layers that read the changed states, and keeps their geometry.
201
+ */
202
+ featureState?: BasemapFeatureState | null;
203
+ /**
204
+ * Draws the style's symbol layers (labels and icons). Default `true`. It applies in every mode.
205
+ * With `false`, the tiles do not decode the source layers that only symbol layers read.
206
+ */
207
+ labels?: boolean;
208
+ /**
209
+ * Draws the atmosphere around the globe in globe mode. Default `false`. The atmosphere layers
210
+ * are placeholders that draw nothing yet.
211
+ */
212
+ atmosphere?: boolean;
213
+ /**
214
+ * @deprecated Use the `labels` and `atmosphere` props, and deck.gl's `visible` prop in place of
215
+ * `basemap: false`. A field set here overrides the flat prop of the same name.
216
+ */
90
217
  globe?: {
91
- /** Rendering toggles for globe-specific basemap behavior. */
92
218
  config?: BasemapGlobeConfig;
93
- };
219
+ } | null;
94
220
  /**
95
221
  * Draws labels with the browser's fonts instead of the style's `glyphs`. By default labels are
96
222
  * drawn with the style's glyphs, as in MapLibre GL JS, and a style without `glyphs` maps each
@@ -103,7 +229,9 @@ export type BasemapLayerProps = {
103
229
  /**
104
230
  * Milliseconds between two placements of the labels while the view keeps changing, as MapLibre
105
231
  * GL JS's `fadeDuration` (default 300). The view the map comes to rest in is always placed; 0
106
- * places every frame.
232
+ * places every frame. The `BasemapLayer`s of a deck share one placement (see
233
+ * `separateLabelPlacement`), which takes the interval of the last of them rendered: give them
234
+ * the same interval.
107
235
  */
108
236
  labelPlacementInterval?: number;
109
237
  /**
@@ -113,6 +241,108 @@ export type BasemapLayerProps = {
113
241
  * are placed first. With `true`, this layer's labels collide only with each other.
114
242
  */
115
243
  separateLabelPlacement?: boolean;
244
+ /**
245
+ * Milliseconds that vector tile loads wait after the last zoom change of a view (default 0: no
246
+ * wait). In a zoom gesture the view passes through several tile zooms; each tile loaded at one
247
+ * of them is decoded and triangulated, and is drawn for a fraction of a second. With a wait, a
248
+ * tile that a loaded ancestor tile draws, enlarged, waits until the zoom comes to rest, and is
249
+ * not loaded if no view selects it then. A tile without a loaded ancestor, such as the new
250
+ * tiles at the edges of a zoom out, loads at once. A pan does not change the zoom, and its
251
+ * loads do not wait.
252
+ */
253
+ zoomLoadDelay?: number;
254
+ /**
255
+ * The stretch limit of the tile selection in a projected view (deck.gl's
256
+ * `_CustomProjectionView`), see `ProjectedTileSelectionOptions.maxStretch`. The default, 4, suits
257
+ * most projections. A projection whose scale grows steeply toward the edge of its area of use,
258
+ * such as a polar stereographic projection, needs a larger limit to draw out to that edge: 16
259
+ * draws an EPSG:3031 view out to latitude 60N. A change reloads the tiles.
260
+ */
261
+ projectedMaxStretch?: number;
262
+ /**
263
+ * Returns `true` for a raster tile that has no map data, such as the placeholder image that some
264
+ * tile services return with status 200 where they have no coverage. The tile is then drawn from
265
+ * its nearest ancestor tile that has data, enlarged, and the placeholder is not drawn. The
266
+ * function receives the bytes of the response (see `RasterTileResponse`). With this prop, raster
267
+ * tiles are requested with the `fetch` and `fetchOptions` of `loadOptions`. Pass a stable
268
+ * function: raster tiles reload when it changes. See `createRasterTileFingerprintFilter`.
269
+ */
270
+ rejectRasterTile?: RejectRasterTile | null;
271
+ /**
272
+ * Called with the resolved style each time a style resolves, as MapLibre GL JS's `style.load`
273
+ * event. Its sprites, glyphs and tiles can still be loading.
274
+ */
275
+ onStyleLoad?: ((style: ResolvedBasemapStyle) => void) | null;
276
+ /**
277
+ * Called when a tile of a vector, raster, raster-dem or geojson source loads, as deck.gl's
278
+ * `TileLayer.onTileLoad`. The style layers of one source share its tiles: each load is reported
279
+ * once.
280
+ */
281
+ onTileLoad?: ((tile: BasemapTile) => void) | null;
282
+ /**
283
+ * Called with the tiles of all sources in the current viewport when they have loaded, as
284
+ * deck.gl's `TileLayer.onViewportLoad` and MapLibre GL JS's `idle` event. The style and its
285
+ * sprites have loaded too. A viewport that selects no tiles is not reported.
286
+ */
287
+ onViewportLoad?: ((tiles: BasemapTile[]) => void) | null;
288
+ /**
289
+ * Called with the `attribution` of the sources that the style draws, when they change, as
290
+ * MapLibre GL JS's `AttributionControl` collects them: a source that only hidden layers draw is
291
+ * left out, each attribution is given once, and one that another contains is left out. The
292
+ * strings are the provider's HTML, not sanitized: display them as safe linked text.
293
+ */
294
+ onAttributionChange?: ((attributions: string[]) => void) | null;
295
+ /**
296
+ * The data of `geojson` sources of the style, by source id, in place of their `data` in the
297
+ * style, as MapLibre GL JS's `GeoJSONSource.setData`. Each entry is compared by identity: when
298
+ * one changes, only that source is indexed again and its tiles cut again. The style is not
299
+ * loaded again, and the other sources keep their tiles. A URL is fetched with the `fetch` and
300
+ * `fetchOptions` of `loadOptions`, relative to the style URL or `loadOptions.baseUrl`, and again
301
+ * when the style URL or `loadOptions` change; the source keeps its previous data until it
302
+ * loads. An entry that is removed, `null` or `undefined` gives the source its data in the style
303
+ * again. An id that is not a `geojson` source of the style is ignored with a warning.
304
+ */
305
+ sourceData?: Record<string, BasemapSourceData | null | undefined> | null;
306
+ /**
307
+ * Extra deck.gl props for the sublayers that draw one style layer, or null for none: for example
308
+ * `extensions` and their props for the roads only. Called for each style layer when the style or
309
+ * the function changes, not for each tile. `extensions` are added after the sublayer's own and
310
+ * `updateTriggers` are merged with its own; `id` and `data` are ignored. A fill or line layer
311
+ * with extra props draws in a sublayer of its own, not batched with its neighbors. Pass a
312
+ * stable function: the tiles regenerate when it changes.
313
+ */
314
+ getStyleLayerProps?:
315
+ | ((styleLayer: ResolvedBasemapStyleLayer) => StyleLayerSubLayerProps | null | undefined)
316
+ | null;
317
+ /**
318
+ * deck.gl layers drawn inside the style order, as MapLibre GL JS's `addLayer(layer, beforeId)`:
319
+ * each insertion's `layers` draw before the style layer `beforeId`, and over the whole basemap
320
+ * without one. Insertions before the same style layer draw in the order of this list. The layers
321
+ * are sublayers of the basemap, and are picked as if they were top-level layers: their own
322
+ * `onHover` and `onClick` receive the events, and `info.layer` is the inserted layer. A `beforeId`
323
+ * that names no layer of the style raises an error to `onError`, and its layers are not drawn.
324
+ */
325
+ insertLayers?: BasemapInsertion[] | null;
326
+ };
327
+
328
+ /** A `sourceData` entry and its GeoJSON: the entry itself, or its URL's once it loads. */
329
+ type SourceDataEntry = {
330
+ /** The entry of the `sourceData` prop. */
331
+ input: BasemapSourceData;
332
+ /** Its GeoJSON object, or the previous entry's until a URL loads, or null. */
333
+ data: object | null;
334
+ /** For a URL, the URL that it resolves against and the `loadOptions` that it loads with. */
335
+ context?: {baseUrl: string | undefined; loadOptions: BasemapLayerProps['loadOptions']; transformRequest: BasemapLayerProps['transformRequest']};
336
+ };
337
+
338
+ /** A `geojson` source of the resolved style with the data of its `sourceData` entry. */
339
+ type SourceDataSource = {
340
+ /** The source in the resolved style. */
341
+ base: BasemapSource;
342
+ /** The data of its `sourceData` entry. */
343
+ data: object;
344
+ /** `base` with `data`: the tileset key, kept while neither changes. */
345
+ source: BasemapSource;
116
346
  };
117
347
 
118
348
  const fractionalZoomLimitsCache = new WeakMap<ResolvedBasemapStyle, number[]>();
@@ -145,6 +375,14 @@ type BasemapLayerState = {
145
375
  sharedLabelPlacementKey: object | null;
146
376
  /** The fully resolved style definition currently backing the generated sublayers. */
147
377
  resolvedStyle: ResolvedBasemapStyle | null;
378
+ /** The `style` prop that `resolvedStyle` was made from. */
379
+ styleInput: BasemapLayerProps['style'];
380
+ /**
381
+ * A copy of `styleInput` when it is an object, as it was when it was read. A style changed in
382
+ * place is compared with this copy. Null while a load runs, and when a source or the sprite of
383
+ * the style failed to load: the next style then loads.
384
+ */
385
+ styleSnapshot: BasemapStyle | null;
148
386
  /** The most recent style-resolution error, if one occurred. */
149
387
  loadError: Error | null;
150
388
  /** Monotonic token used to discard stale async style loads. */
@@ -153,6 +391,16 @@ type BasemapLayerState = {
153
391
  zoomKey: string | null;
154
392
  /** Sprites of the resolved style, once loaded. */
155
393
  spriteAtlases: SpriteAtlas[] | null;
394
+ /** The sprite URLs and pixel ratio of `spriteLoad`. */
395
+ spriteKey: string | null;
396
+ /** The load of the sprites of the resolved style, kept for a new style with the same sprites. */
397
+ spriteLoad: Promise<SpriteAtlas[]> | null;
398
+ /** The sources of the styles resolved with `sourceCacheOptions` (see `BasemapLoadOptions`). */
399
+ sourceCache: Map<string, BasemapSource>;
400
+ /** The `loadOptions` that the sources in `sourceCache` were loaded with. */
401
+ sourceCacheOptions: BasemapLayerProps['loadOptions'] | undefined;
402
+ /** The `loadOptions` that the sources, the sprites and the glyphs were loaded with. */
403
+ styleLoadOptions: BasemapLayerProps['loadOptions'] | undefined;
156
404
  /** The glyphs of the resolved style's `glyphs` URL, or null without one. */
157
405
  glyphs: GlyphStore | null;
158
406
  /** Decoded data caches owned by this basemap, shared across style runs. */
@@ -164,59 +412,215 @@ type BasemapLayerState = {
164
412
  tilesetSourceLayers: Map<BasemapSource, string>;
165
413
  /** Loading configuration used to construct the current source caches. */
166
414
  tileLoadOptions: unknown;
415
+ /** The `projectedMaxStretch` the current source caches select tiles with. */
416
+ tileMaxStretch: number | null;
167
417
  /** Fetch identity, kept separate from render-only props such as view mode. */
168
418
  tileFetch: unknown;
419
+ /** Holds the vector tile loads while a view zooms (see `zoomLoadDelay`). */
420
+ zoomLoadGate: ZoomLoadGate;
421
+ /** The `loadToken` of the last style load that ended. */
422
+ loadedToken: number;
423
+ /** The resolved style that the current sublayers were generated from. */
424
+ renderedStyle: ResolvedBasemapStyle | null;
425
+ /** The content of each tile reported to `onTileLoad`, to report a load once. */
426
+ reportedTiles: WeakMap<object, unknown>;
427
+ /** The tiles last reported to `onViewportLoad`. */
428
+ viewportTiles: BasemapTile[] | null;
429
+ /** The attributions last reported to `onAttributionChange`, as JSON. */
430
+ attributions: string;
431
+ /** The entries of the `sourceData` prop, by source id. */
432
+ sourceData: Map<string, SourceDataEntry>;
433
+ /** The sources that the `sourceData` entries replace, by source id. */
434
+ sourceDataSources: Map<string, SourceDataSource>;
435
+ /** The resolved style with the `sourceData` sources, and the resolved style it was made from. */
436
+ styleWithSourceData: {base: ResolvedBasemapStyle; style: ResolvedBasemapStyle} | null;
437
+ /** The extra sublayer props of each style layer, and the style and function they came from. */
438
+ styleLayerProps: {
439
+ style: ResolvedBasemapStyle;
440
+ getStyleLayerProps: BasemapLayerProps['getStyleLayerProps'];
441
+ value: StyleLayerPropsMap | null;
442
+ } | null;
443
+ /** The layers of `insertLayers` in the current sublayers, picked as top-level layers. */
444
+ insertedLayers: Set<Layer>;
445
+ /** The style and unknown `beforeId`s that errors were last raised for, to raise them once. */
446
+ insertionError: {style: ResolvedBasemapStyle; beforeIds: string} | null;
447
+ /** The causes of the errors given to `reportError`, which reports each once. */
448
+ reportedErrors: WeakSet<Error>;
449
+ /** The `transformRequest` the current source caches request tiles with. */
450
+ tileTransformRequest: BasemapTransformRequest | null;
451
+ /** The config `getStyleConfig` last returned, kept while its inputs do not change. */
452
+ styleConfig: {
453
+ labels: unknown;
454
+ atmosphere: unknown;
455
+ globe: unknown;
456
+ value: {config: Required<BasemapGlobeConfig>};
457
+ } | null;
169
458
  };
170
459
 
171
460
  /**
172
461
  * A deck.gl {@link CompositeLayer} that loads a style document and renders the
173
462
  * corresponding basemap sublayers.
463
+ *
464
+ * @typeParam ExtraPropsT The props of the layer's `extensions`, such as `MaskExtensionProps`.
174
465
  */
175
- export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
466
+ export class BasemapLayer<ExtraPropsT extends {} = {}> extends CompositeLayer<
467
+ ExtraPropsT & Required<BasemapLayerProps>
468
+ > {
176
469
  /** Deck.gl layer name. */
177
470
  static layerName = 'BasemapLayer';
178
471
 
179
472
  /** Default props for {@link BasemapLayer}. */
180
473
  static defaultProps: DefaultProps<BasemapLayerProps> = {
181
- mode: 'map',
182
- globe: {
183
- type: 'object',
184
- value: {
185
- config: {
186
- atmosphere: false,
187
- basemap: true,
188
- labels: true
189
- }
190
- }
191
- },
474
+ mode: 'auto',
475
+ featureState: null,
476
+ labels: true,
477
+ atmosphere: false,
478
+ globe: null,
192
479
  style: null,
193
480
  loadOptions: null,
481
+ transformRequest: null,
194
482
  fontFamily: null,
483
+ rejectRasterTile: null,
484
+ getStyleLayerProps: null,
485
+ insertLayers: {type: 'object', value: null, compare: false},
195
486
  labelPlacementInterval: DEFAULT_PLACEMENT_INTERVAL,
196
- separateLabelPlacement: false
487
+ separateLabelPlacement: false,
488
+ zoomLoadDelay: 0,
489
+ projectedMaxStretch: DEFAULT_MAX_STRETCH,
490
+ onStyleLoad: {type: 'function', optional: true, value: null},
491
+ onTileLoad: {type: 'function', optional: true, value: null},
492
+ onViewportLoad: {type: 'function', optional: true, value: null},
493
+ onAttributionChange: {type: 'function', optional: true, value: null},
494
+ // Compared by entry: a new object with the same entries changes nothing.
495
+ sourceData: {type: 'object', value: null, compare: 1}
197
496
  };
198
497
 
199
498
  /** Current layer state. */
200
499
  state: BasemapLayerState = undefined!;
201
500
 
501
+ /**
502
+ * Queries a caller-owned displayed terrain surface through the selected deck viewport. The
503
+ * layer adds nothing: this is `pickTerrainSurface(viewport, pixel, surface, commonToSurface)`.
504
+ */
505
+ getTerrainAt(
506
+ viewport: Viewport,
507
+ pixel: readonly [number, number],
508
+ surface: TerrainSurface,
509
+ commonToSurface: Readonly<ArrayLike<number>>
510
+ ): TerrainSurfaceHit | null {
511
+ return pickTerrainSurface(viewport, pixel, surface, commonToSurface);
512
+ }
513
+
202
514
  /** Initializes the asynchronous style-loading state. */
203
515
  initializeState(): void {
204
516
  this.state = {
205
517
  labelPlacement: null,
206
518
  sharedLabelPlacementKey: null,
207
519
  resolvedStyle: null,
520
+ styleInput: null,
521
+ styleSnapshot: null,
208
522
  loadError: null,
209
523
  loadToken: 0,
210
524
  zoomKey: null,
211
525
  tilesets: new Map(),
212
526
  tilesetSourceLayers: new Map(),
213
527
  tileLoadOptions: null,
528
+ tileMaxStretch: null,
214
529
  tileFetch: null,
530
+ tileTransformRequest: null,
215
531
  spriteAtlases: null,
216
- glyphs: null
532
+ spriteKey: null,
533
+ spriteLoad: null,
534
+ sourceCache: new Map(),
535
+ sourceCacheOptions: undefined,
536
+ styleLoadOptions: undefined,
537
+ glyphs: null,
538
+ zoomLoadGate: new ZoomLoadGate(),
539
+ loadedToken: 0,
540
+ renderedStyle: null,
541
+ reportedTiles: new WeakMap(),
542
+ viewportTiles: null,
543
+ // No style draws no sources: the first report is the first attribution.
544
+ attributions: '[]',
545
+ sourceData: new Map(),
546
+ sourceDataSources: new Map(),
547
+ styleWithSourceData: null,
548
+ styleLayerProps: null,
549
+ insertedLayers: new Set(),
550
+ insertionError: null,
551
+ reportedErrors: new WeakSet(),
552
+ styleConfig: null
217
553
  };
218
554
  }
219
555
 
556
+ /**
557
+ * False while the style, its sprites or the tiles of the current viewport load, as deck.gl's
558
+ * `TileLayer.isLoaded`. A style or tile that failed to load counts as loaded.
559
+ */
560
+ get isLoaded(): boolean {
561
+ const state = this.state;
562
+ if (!state || state.loadedToken !== state.loadToken) {
563
+ return false;
564
+ }
565
+ // Until the sublayers of the style exist, the sublayers that `super` checks are not its own.
566
+ const {resolvedStyle, spriteAtlases, renderedStyle} = state;
567
+ if (resolvedStyle && (!spriteAtlases || renderedStyle !== resolvedStyle)) {
568
+ return false;
569
+ }
570
+ return super.isLoaded;
571
+ }
572
+
573
+ /**
574
+ * The extra sublayer props of each style layer of `style` (see `getStyleLayerProps`), computed
575
+ * once per style and function.
576
+ */
577
+ private getStyleLayerPropsMap(style: ResolvedBasemapStyle): StyleLayerPropsMap | null {
578
+ const {getStyleLayerProps} = this.props;
579
+ const cached = this.state.styleLayerProps;
580
+ if (cached?.style === style && cached.getStyleLayerProps === getStyleLayerProps) {
581
+ return cached.value;
582
+ }
583
+ const value = getStyleLayerPropsMap(style, getStyleLayerProps ?? null);
584
+ this.state.styleLayerProps = {style, getStyleLayerProps, value};
585
+ return value;
586
+ }
587
+
588
+ /**
589
+ * The drawing toggles of the props, in the `{config}` form of the basemap helpers: `labels` and
590
+ * `atmosphere`, with the fields of the deprecated `globe.config` over them. The object keeps
591
+ * its identity while these props do not change.
592
+ */
593
+ getStyleConfig(): {config: Required<BasemapGlobeConfig>} {
594
+ const {labels, atmosphere, globe} = this.props;
595
+ const cached = this.state?.styleConfig;
596
+ if (
597
+ cached &&
598
+ cached.labels === labels &&
599
+ cached.atmosphere === atmosphere &&
600
+ cached.globe === globe
601
+ ) {
602
+ return cached.value;
603
+ }
604
+ const config = {labels: labels !== false, atmosphere: Boolean(atmosphere), basemap: true};
605
+ const legacy = globe?.config;
606
+ if (legacy) {
607
+ log.deprecated(
608
+ 'BasemapLayer prop `globe.config`',
609
+ 'the `labels` and `atmosphere` props, and `visible` for `basemap: false`'
610
+ )();
611
+ for (const key of ['labels', 'atmosphere', 'basemap'] as const) {
612
+ if (legacy[key] !== undefined) {
613
+ config[key] = Boolean(legacy[key]);
614
+ }
615
+ }
616
+ }
617
+ const value = {config};
618
+ if (this.state) {
619
+ this.state.styleConfig = {labels, atmosphere, globe, value};
620
+ }
621
+ return value;
622
+ }
623
+
220
624
  /**
221
625
  * Sublayers depend on the zoom, but only through `getStyleZoomKey`: style values step every
222
626
  * `STYLE_ZOOM_STEP`, filters at integer zooms, and layer visibility changes at
@@ -235,18 +639,43 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
235
639
 
236
640
  /** Returns the key of what the sublayers depend on in `viewport`, for a resolved style. */
237
641
  getZoomKey(resolvedStyle: ResolvedBasemapStyle, viewport: Viewport | undefined): string {
238
- const zoomKey = getStyleZoomKey(viewport?.zoom || 0, getFractionalZoomLimits(resolvedStyle));
239
- return `${this.getDrawMode(viewport)}:${zoomKey}`;
642
+ const zoomKey = getStyleZoomKey(getStyleZoom(viewport), getFractionalZoomLimits(resolvedStyle));
643
+ // These views need different background geometry from MapView.
644
+ const drawMode = isProjectedViewport(viewport)
645
+ ? 'projected'
646
+ : isGeographicFirstPersonViewport(viewport) ? 'first-person' : this.getDrawMode(viewport);
647
+ return `${drawMode}:${zoomKey}`;
240
648
  }
241
649
 
242
650
  /**
243
- * The mode the sublayers are drawn in. Above zoom 12, `GlobeView` draws with a Web Mercator
244
- * viewport, so a globe basemap draws as a map there: globe depth and culling parameters assume
245
- * longitude/latitude geometry on a sphere.
651
+ * The mode the sublayers are drawn in. With `mode: 'auto'`, a globe viewport draws globe
652
+ * sublayers and any other viewport draws map sublayers. Above zoom 12, `GlobeView` draws with a
653
+ * Web Mercator viewport, so a globe basemap draws as a map there: globe depth and culling
654
+ * parameters assume longitude/latitude geometry on a sphere.
246
655
  */
247
656
  getDrawMode(viewport: Viewport | undefined): 'map' | 'globe' {
248
- const {mode = 'map'} = this.props;
249
- return mode === 'globe' && viewport && !isGlobeViewport(viewport) ? 'map' : mode;
657
+ const {mode = 'auto'} = this.props;
658
+ if (mode === 'map') {
659
+ return 'map';
660
+ }
661
+ if (!viewport) {
662
+ return mode === 'globe' ? 'globe' : 'map';
663
+ }
664
+ return isGlobeViewport(viewport) ? 'globe' : 'map';
665
+ }
666
+
667
+ /**
668
+ * Raises a load failure (see `BasemapLoadError`) to the layer's `onError`, and to the deck's
669
+ * `onError` unless the layer's returns `true`. A cancelled request is not a failure. Tile layers
670
+ * that share a tileset each report its failed tiles: a failure is raised once.
671
+ */
672
+ reportError(error: BasemapLoadError): void {
673
+ if (isAbortError(error.cause) || this.state.reportedErrors.has(error.cause)) {
674
+ return;
675
+ }
676
+ this.state.reportedErrors.add(error.cause);
677
+ // A load that ends after the props changed raises the error with the current props.
678
+ (this.getCurrentLayer() ?? this).raiseError(error, '');
250
679
  }
251
680
 
252
681
  /** Reacts to changes in the input style definition. */
@@ -255,10 +684,166 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
255
684
  if (
256
685
  changeFlags.dataChanged ||
257
686
  props.style !== oldProps.style ||
258
- props.loadOptions !== oldProps.loadOptions
687
+ props.loadOptions !== oldProps.loadOptions ||
688
+ props.transformRequest !== oldProps.transformRequest
689
+ ) {
690
+ const updated =
691
+ !changeFlags.dataChanged &&
692
+ props.loadOptions === oldProps.loadOptions &&
693
+ props.transformRequest === oldProps.transformRequest &&
694
+ oldProps.style === this.state.styleInput &&
695
+ this.updateStyleByDiff(props.style);
696
+ if (!updated) {
697
+ this.loadStyle(props.style, props.loadOptions, props.transformRequest);
698
+ }
699
+ }
700
+ if (
701
+ props.sourceData !== oldProps.sourceData ||
702
+ props.style !== oldProps.style ||
703
+ props.loadOptions !== oldProps.loadOptions ||
704
+ props.transformRequest !== oldProps.transformRequest
705
+ ) {
706
+ this.updateSourceData(props);
707
+ }
708
+ }
709
+
710
+ /**
711
+ * Takes the entries of the `sourceData` prop. An entry that is the same as before keeps its data;
712
+ * a GeoJSON object is used as it is, and a URL is fetched. A URL is fetched again when the URL
713
+ * that it resolves against or the `loadOptions` change.
714
+ */
715
+ private updateSourceData({sourceData, style, loadOptions, transformRequest}: BasemapLayerProps): void {
716
+ const previous = this.state.sourceData;
717
+ const entries = new Map<string, SourceDataEntry>();
718
+ const baseUrl = getStyleBaseUrl(style, ((loadOptions || {}) as {baseUrl?: string}).baseUrl);
719
+ for (const [sourceId, input] of Object.entries(sourceData || {})) {
720
+ if (input === null || input === undefined) {
721
+ continue;
722
+ }
723
+ const previousEntry = previous.get(sourceId);
724
+ if (
725
+ previousEntry?.input === input &&
726
+ (typeof input !== 'string' ||
727
+ (previousEntry.context?.baseUrl === baseUrl &&
728
+ previousEntry.context?.loadOptions === loadOptions &&
729
+ previousEntry.context?.transformRequest === transformRequest))
730
+ ) {
731
+ entries.set(sourceId, previousEntry);
732
+ } else if (typeof input !== 'string') {
733
+ entries.set(sourceId, {input, data: input});
734
+ } else {
735
+ // As MapLibre's `setData`, the source keeps the data it has until the new data loads.
736
+ const entry: SourceDataEntry = {
737
+ input,
738
+ data: previousEntry?.data ?? null,
739
+ context: {baseUrl, loadOptions, transformRequest}
740
+ };
741
+ entries.set(sourceId, entry);
742
+ this.loadSourceData(sourceId, entry);
743
+ }
744
+ }
745
+ this.setState({sourceData: entries});
746
+ }
747
+
748
+ /** Fetches the GeoJSON of a `sourceData` URL, unless the entry has changed by then. */
749
+ private loadSourceData(sourceId: string, entry: SourceDataEntry): void {
750
+ const {baseUrl, loadOptions, transformRequest} = entry.context!;
751
+ const isCurrent = () => this.state.sourceData.get(sourceId) === entry;
752
+ loadGeoJsonData(entry.input as string, baseUrl, withTransformRequest(loadOptions, transformRequest))
753
+ .then(data => {
754
+ if (isCurrent()) {
755
+ const entries = new Map(this.state.sourceData);
756
+ entries.set(sourceId, {...entry, data});
757
+ this.setState({sourceData: entries});
758
+ }
759
+ })
760
+ .catch((error: Error) => {
761
+ if (isCurrent()) {
762
+ logBasemapLayerError(`Failed to load the data of GeoJSON source "${sourceId}"`, error);
763
+ }
764
+ });
765
+ }
766
+
767
+ /**
768
+ * The resolved style with the data of the `sourceData` entries in its `geojson` sources. A source
769
+ * is a new object only when its entry or its source in the resolved style changes, and the style
770
+ * only when one of its sources does: the tilesets are keyed by source object, so the other sources
771
+ * keep their tiles.
772
+ */
773
+ private getStyleWithSourceData(resolvedStyle: ResolvedBasemapStyle): ResolvedBasemapStyle {
774
+ const {sourceData, sourceDataSources: previous, styleWithSourceData} = this.state;
775
+ const replaced = new Map<string, SourceDataSource>();
776
+ let changed = styleWithSourceData?.base !== resolvedStyle;
777
+ for (const [sourceId, {data}] of sourceData) {
778
+ const base = resolvedStyle.sources?.[sourceId];
779
+ if (base?.type !== 'geojson') {
780
+ log.warn(`[BasemapLayer] sourceData "${sourceId}" is not a geojson source of the style`)();
781
+ continue;
782
+ }
783
+ if (!data) {
784
+ continue;
785
+ }
786
+ let entry = previous.get(sourceId);
787
+ if (!entry || entry.base !== base || entry.data !== data) {
788
+ entry = {base, data, source: {...base, data}};
789
+ changed = true;
790
+ }
791
+ replaced.set(sourceId, entry);
792
+ }
793
+ if (replaced.size !== previous.size) {
794
+ changed = true;
795
+ }
796
+ this.state.sourceDataSources = replaced;
797
+ if (!replaced.size) {
798
+ this.state.styleWithSourceData = null;
799
+ return resolvedStyle;
800
+ }
801
+ if (changed || !styleWithSourceData) {
802
+ const sources = {...resolvedStyle.sources};
803
+ for (const [sourceId, {source}] of replaced) {
804
+ sources[sourceId] = source;
805
+ }
806
+ this.state.styleWithSourceData = {base: resolvedStyle, style: {...resolvedStyle, sources}};
807
+ }
808
+ return this.state.styleWithSourceData!.style;
809
+ }
810
+
811
+ /**
812
+ * Applies a new style object as MapLibre GL JS's `setStyle(style, {diff: true})` applies it. A
813
+ * change that loads nothing, such as a paint or layout value, a filter, a zoom range or the order
814
+ * of the layers, makes a new resolved style with the sources of the current one, in this update.
815
+ * Returns false when the style must load: a source, the sprite or the glyphs changed, or the
816
+ * styles cannot be compared.
817
+ */
818
+ private updateStyleByDiff(style: BasemapLayerProps['style']): boolean {
819
+ const {resolvedStyle, styleSnapshot} = this.state;
820
+ // A glyph range that failed loads again with the next load.
821
+ if (
822
+ !resolvedStyle ||
823
+ !styleSnapshot ||
824
+ !isStyleObject(style) ||
825
+ isResolvedBasemapStyle(style) ||
826
+ this.state.glyphs?.failed
259
827
  ) {
260
- this.loadStyle(props.style, props.loadOptions);
828
+ return false;
261
829
  }
830
+ const snapshot = copyStyle(style);
831
+ let commands: ReturnType<typeof diff>;
832
+ try {
833
+ commands = diff(styleSnapshot as StyleSpecification, snapshot as StyleSpecification);
834
+ } catch {
835
+ return false;
836
+ }
837
+ if (commands.some(({command}) => LOADING_DIFF_COMMANDS.has(command))) {
838
+ return false;
839
+ }
840
+ const updatedStyle = commands.length ? getUpdatedStyle(snapshot, resolvedStyle) : resolvedStyle;
841
+ if (!updatedStyle) {
842
+ return false;
843
+ }
844
+ logBasemapLayerEvent('Updated basemap style', {commands: commands.length});
845
+ this.setState({resolvedStyle: updatedStyle, styleInput: style, styleSnapshot: snapshot});
846
+ return true;
262
847
  }
263
848
 
264
849
  /**
@@ -267,16 +852,25 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
267
852
  */
268
853
  loadStyle(
269
854
  style: BasemapLayerProps['style'],
270
- loadOptions: BasemapLayerProps['loadOptions']
855
+ layerLoadOptions: BasemapLayerProps['loadOptions'],
856
+ transformRequest?: BasemapTransformRequest | null
271
857
  ): void {
858
+ // The load options of the requests the layer makes itself, with `transformRequest`.
859
+ const loadOptions = withTransformRequest(
860
+ (layerLoadOptions || undefined) as BasemapLoadOptions | undefined,
861
+ transformRequest
862
+ ) as BasemapLayerProps['loadOptions'];
272
863
  if (!style) {
273
864
  const loadToken = this.state.loadToken + 1;
274
865
  logBasemapLayerEvent('Clearing basemap style');
275
866
  this.clearSourceTilesets();
276
867
  this.setState({
277
868
  resolvedStyle: null,
869
+ styleInput: null,
870
+ styleSnapshot: null,
278
871
  loadError: null,
279
872
  loadToken,
873
+ loadedToken: loadToken,
280
874
  spriteAtlases: null,
281
875
  glyphs: null
282
876
  });
@@ -285,17 +879,38 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
285
879
 
286
880
  const loadToken = this.state.loadToken + 1;
287
881
  this.setState({loadToken});
882
+ const styleJson = isStyleObject(style) && !isResolvedBasemapStyle(style) ? JSON.stringify(style) : null;
883
+ const styleSnapshot: BasemapStyle | null = styleJson ? JSON.parse(styleJson) : null;
884
+ // A style update by diff waits for this load (see `updateStyleByDiff`).
885
+ this.state.styleSnapshot = null;
886
+ // A load with other options takes a new cache: a load still running fills only its own.
887
+ if (loadOptions !== this.state.sourceCacheOptions) {
888
+ this.state.sourceCache = new Map();
889
+ this.state.sourceCacheOptions = loadOptions;
890
+ }
891
+ const {sourceCache} = this.state;
892
+ if (isResolvedBasemapStyle(style)) {
893
+ logBasemapLayerEvent('Using resolved basemap style', {loadToken});
894
+ this.setResolvedStyle(style, style, loadOptions, loadToken, null);
895
+ return;
896
+ }
288
897
  logBasemapLayerEvent('Resolving basemap style', {
289
898
  style: typeof style === 'string' ? style : 'inline-style-object',
290
899
  loadToken
291
900
  });
292
901
 
902
+ // A source, sprite or glyph range of a style that was replaced is not reported.
903
+ const onStyleResourceError = (error: BasemapLoadError) => {
904
+ if (this.state.loadToken === loadToken) {
905
+ this.reportError(error);
906
+ }
907
+ };
293
908
  Promise.resolve(
294
909
  typeof style === 'string'
295
- ? load(style, MapStyleLoader, getMapStyleLoaderOptions(loadOptions))
910
+ ? loadStyleUrl(style, loadOptions, sourceCache, onStyleResourceError)
296
911
  : MapStyleLoader.parse(
297
- new TextEncoder().encode(JSON.stringify(style)).buffer,
298
- getMapStyleLoaderOptions(loadOptions)
912
+ new TextEncoder().encode(styleJson!).buffer,
913
+ getMapStyleLoaderOptions(loadOptions, sourceCache, onStyleResourceError)
299
914
  )
300
915
  )
301
916
  .then(resolvedStyle => {
@@ -305,24 +920,65 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
305
920
  sources: Object.keys(resolvedStyle.sources || {}),
306
921
  layers: resolvedStyle.layers?.length || 0
307
922
  });
308
- this.setState({
309
- resolvedStyle,
310
- loadError: null,
311
- spriteAtlases: null,
312
- glyphs: getGlyphStore(resolvedStyle, style, loadOptions)
313
- });
314
- this.loadSprites(resolvedStyle, style, loadOptions, loadToken);
923
+ this.setResolvedStyle(resolvedStyle, style, loadOptions, loadToken, styleSnapshot);
315
924
  }
316
925
  })
317
926
  .catch((error: Error) => {
318
927
  if (this.state.loadToken === loadToken) {
319
- logBasemapLayerError('Failed to resolve basemap style', error);
320
928
  this.clearSourceTilesets();
321
- this.setState({resolvedStyle: null, loadError: error});
929
+ this.setState({
930
+ resolvedStyle: null,
931
+ styleInput: null,
932
+ styleSnapshot: null,
933
+ loadError: error,
934
+ loadedToken: loadToken
935
+ });
936
+ if (!(loadOptions as BasemapLoadOptions)?.fetchOptions?.signal?.aborted) {
937
+ this.reportError(
938
+ getBasemapLoadError('style', error, typeof style === 'string' ? {url: style} : {})
939
+ );
940
+ }
322
941
  }
323
942
  });
324
943
  }
325
944
 
945
+ /** Draws `resolvedStyle`, the resolved form of the `style` prop, and loads its sprites. */
946
+ private setResolvedStyle(
947
+ resolvedStyle: ResolvedBasemapStyle,
948
+ style: BasemapLayerProps['style'],
949
+ loadOptions: BasemapLayerProps['loadOptions'],
950
+ loadToken: number,
951
+ styleSnapshot: BasemapStyle | null
952
+ ): void {
953
+ const sameOptions = loadOptions === this.state.styleLoadOptions;
954
+ if (sameOptions && this.state.resolvedStyle && !isResolvedBasemapStyle(style)) {
955
+ reuseSources(resolvedStyle, this.state.resolvedStyle);
956
+ }
957
+ const glyphs = getGlyphStore(resolvedStyle, style, loadOptions, error => {
958
+ if (this.state.glyphs === glyphs) {
959
+ this.reportError(error);
960
+ }
961
+ });
962
+ const keepGlyphs =
963
+ sameOptions && glyphs?.url === this.state.glyphs?.url && !this.state.glyphs?.failed;
964
+ this.setState({
965
+ resolvedStyle,
966
+ styleInput: style,
967
+ styleSnapshot: hasFailedSource(styleSnapshot, resolvedStyle) ? null : styleSnapshot,
968
+ loadError: null,
969
+ loadedToken: loadToken,
970
+ styleLoadOptions: loadOptions,
971
+ glyphs: keepGlyphs ? this.state.glyphs : glyphs
972
+ });
973
+ this.loadSprites(resolvedStyle, style, loadOptions, loadToken, sameOptions);
974
+ // An error of the app's callback is not a load failure: it must not clear the style.
975
+ try {
976
+ this.getCurrentProps().onStyleLoad?.(resolvedStyle);
977
+ } catch (error) {
978
+ (this.getCurrentLayer() ?? this).raiseError(error as Error, 'onStyleLoad');
979
+ }
980
+ }
981
+
326
982
  /**
327
983
  * Loads the resolved style's sprites, if it has any, and stores them for the icon layers.
328
984
  * Relative sprite URLs resolve against the style URL.
@@ -331,33 +987,79 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
331
987
  resolvedStyle: ResolvedBasemapStyle,
332
988
  style: BasemapLayerProps['style'],
333
989
  loadOptions: BasemapLayerProps['loadOptions'],
334
- loadToken: number
990
+ loadToken: number,
991
+ sameOptions: boolean
335
992
  ): void {
336
993
  if (!resolvedStyle.sprite) {
337
994
  // No sprites to wait for (`null` means loading, see `MVTLabelLayerProps.spriteAtlases`).
338
- this.setState({spriteAtlases: []});
995
+ this.setState({spriteAtlases: [], spriteKey: null, spriteLoad: null});
339
996
  return;
340
997
  }
341
- const options = (loadOptions || {}) as {
342
- baseUrl?: string;
343
- fetch?: typeof fetch;
344
- fetchOptions?: RequestInit;
345
- };
346
- loadSpriteAtlases(resolvedStyle.sprite, {
347
- baseUrl: typeof style === 'string' ? style : options.baseUrl,
348
- fetch: options.fetch,
349
- fetchOptions: options.fetchOptions,
350
- pixelRatio: typeof devicePixelRatio === 'number' ? devicePixelRatio : 1
351
- }).then(spriteAtlases => {
352
- if (this.state.loadToken === loadToken) {
998
+ const options = (loadOptions || {}) as NonNullable<BasemapLoadOptions>;
999
+ const baseUrl = getStyleBaseUrl(style, options.baseUrl);
1000
+ const pixelRatio = typeof devicePixelRatio === 'number' ? devicePixelRatio : 1;
1001
+ const spriteKey = JSON.stringify([getSpriteSources(resolvedStyle.sprite, baseUrl), pixelRatio]);
1002
+ if (!sameOptions || spriteKey !== this.state.spriteKey || !this.state.spriteLoad) {
1003
+ const spriteCount = getSpriteSources(resolvedStyle.sprite, baseUrl).length;
1004
+ const spriteLoad = loadSpriteAtlases(resolvedStyle.sprite, {
1005
+ baseUrl,
1006
+ fetch: options.fetch,
1007
+ fetchOptions: options.fetchOptions,
1008
+ transformRequest: options.transformRequest,
1009
+ pixelRatio,
1010
+ onError: error => {
1011
+ if (this.state.spriteLoad === spriteLoad) {
1012
+ this.reportError(error);
1013
+ }
1014
+ }
1015
+ });
1016
+ this.setState({spriteAtlases: null, spriteKey, spriteLoad});
1017
+ spriteLoad.then(spriteAtlases => {
1018
+ // A sprite that failed loads again with the next style.
1019
+ if (spriteAtlases.length < spriteCount && this.state.spriteLoad === spriteLoad) {
1020
+ this.state.spriteKey = null;
1021
+ this.state.styleSnapshot = null;
1022
+ }
1023
+ });
1024
+ }
1025
+ this.state.spriteLoad!.then(spriteAtlases => {
1026
+ if (this.state.loadToken === loadToken && this.state.spriteAtlases !== spriteAtlases) {
353
1027
  this.setState({spriteAtlases});
1028
+ // The tiles can have loaded before the sprites.
1029
+ (this.getCurrentLayer() as this | null)?.checkViewportLoad();
354
1030
  }
355
1031
  });
356
1032
  }
357
1033
 
1034
+ /**
1035
+ * Returns the features of a `vector` or `geojson` source in the tiles that are loaded and drawn
1036
+ * now, as MapLibre GL JS's `Map#querySourceFeatures`: every feature of `sourceLayer` that matches
1037
+ * `filter`, whether a style layer draws it or not, in longitude and latitude. Tiles outside the
1038
+ * view are not read. A feature that crosses a tile edge, or a point in the buffer of two tiles,
1039
+ * is returned once per tile: compare `id`s to merge them. A source with no loaded tiles, a raster
1040
+ * source, or an unknown id returns `[]`.
1041
+ *
1042
+ * Tiles decode only the source layers that the style draws, so a source layer that no style layer
1043
+ * reads has no features here.
1044
+ */
1045
+ querySourceFeatures(
1046
+ sourceId: string,
1047
+ options?: QuerySourceFeaturesOptions | null
1048
+ ): BasemapSourceFeature[] {
1049
+ const style = this.state?.styleWithSourceData?.style || this.state?.resolvedStyle;
1050
+ const source = style?.sources?.[sourceId];
1051
+ const tileset = source && isVectorTileSource(source) && this.state.tilesets.get(source);
1052
+ if (!tileset) {
1053
+ return [];
1054
+ }
1055
+ return querySourceFeaturesInTiles(tileset.visibleTiles, sourceId, source, options || {});
1056
+ }
1057
+
358
1058
  /** The basemap owns caches; style-run consumers only attach/detach. */
359
1059
  finalizeState(): void {
360
1060
  this.state.loadToken++;
1061
+ // Loads of `sourceData` URLs that finish later find no entry.
1062
+ this.state.sourceData = new Map();
361
1063
  this.clearSourceTilesets();
362
1064
  this.releaseLabelPlacement();
363
1065
  }
@@ -401,6 +1103,7 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
401
1103
  }
402
1104
 
403
1105
  private updateSourceTilesets(style: ResolvedBasemapStyle): void {
1106
+ const {transformRequest = null} = this.props;
404
1107
  const sources = new Set(
405
1108
  Object.values(style.sources || {}).filter(source => isVectorTileSource(source))
406
1109
  );
@@ -412,15 +1115,30 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
412
1115
  );
413
1116
  const optionsChanged =
414
1117
  this.state.tileLoadOptions !== this.props.loadOptions ||
415
- this.state.tileFetch !== this.props.fetch;
1118
+ this.state.tileFetch !== this.props.fetch ||
1119
+ this.state.tileTransformRequest !== transformRequest ||
1120
+ this.state.tileMaxStretch !== this.props.projectedMaxStretch;
416
1121
  // Tiles decode only the source layers the style draws: a style edit or a labels toggle that
417
1122
  // changes the layers the loader decodes reloads the source's tiles.
418
- const sourceLayers = getStyleSourceLayers(style, this.props.globe);
1123
+ const sourceLayers = getStyleSourceLayers(style, this.getStyleConfig());
419
1124
  const getDecodedLayers = (source: BasemapSource) =>
420
1125
  (getSourceLoadOptions(this.props.loadOptions, sourceLayers.get(source)) as any)?.mvt?.layers;
1126
+ // Projected views and globes show latitudes past the edges of Web Mercator tiles: GeoJSON is
1127
+ // cut at them there, and tiled again when the view changes from one to the other.
1128
+ const geoJson = {
1129
+ clipToMercatorRange:
1130
+ this.props.mode === 'globe' ||
1131
+ (this.props.mode !== 'map' && isGlobeViewport(this.context.viewport)) ||
1132
+ isProjectedViewport(this.context.viewport)
1133
+ };
421
1134
  const sourceLayerKeys = new Map([
422
1135
  ...[...sources].map(
423
- source => [source, JSON.stringify(getDecodedLayers(source) ?? null)] as const
1136
+ source =>
1137
+ [
1138
+ source,
1139
+ JSON.stringify(getDecodedLayers(source) ?? null) +
1140
+ (source.type === 'geojson' ? `:${geoJson.clipToMercatorRange}` : '')
1141
+ ] as const
424
1142
  ),
425
1143
  // An encoding edited in place reloads the source's tiles.
426
1144
  ...[...demSources].map(source => [source, `dem:${getDemUnpackVector(source)}`] as const)
@@ -438,29 +1156,45 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
438
1156
  }
439
1157
  this.state.tileLoadOptions = this.props.loadOptions;
440
1158
  this.state.tileFetch = this.props.fetch;
1159
+ this.state.tileTransformRequest = transformRequest;
1160
+ this.state.tileMaxStretch = this.props.projectedMaxStretch ?? null;
441
1161
  for (const source of sources) {
442
1162
  if (!this.state.tilesets.has(source)) {
443
1163
  const loader = new SharedMVTLayer({
444
1164
  id: `${this.id}-loader`,
445
- data: source.tiles!,
446
- fetch: this.props.fetch,
447
- loadOptions: getSourceLoadOptions(this.props.loadOptions, sourceLayers.get(source))
1165
+ data: getSourceTileTemplates(source)!,
1166
+ fetch: getBasemapTileFetch(this.props.fetch, 'arrayBuffer', transformRequest),
1167
+ loadOptions: getTileLoadOptions(
1168
+ source,
1169
+ getSourceLoadOptions(withTransformRequest(this.props.loadOptions, transformRequest), sourceLayers.get(source))
1170
+ )
448
1171
  });
449
1172
  loader.context = this.context;
450
- const tileset = new SharedTileset2D({
1173
+ const gate = this.state.zoomLoadGate;
1174
+ const loadTile = getVectorTileLoader(source, loader, geoJson);
1175
+ const tileset: SharedTileset2D = new SharedTileset2D({
451
1176
  ...loader._getTilesetOptions(),
1177
+ adapter: getZoomGatedAdapter(
1178
+ gate,
1179
+ getBasemapTilesetAdapter(this.props.projectedMaxStretch, getSourceTileBounds(source))
1180
+ ),
452
1181
  ...getTilePyramidProps(source),
453
1182
  tileSize: source.tileSize || 512,
454
1183
  zoomOffset: VECTOR_TILE_ZOOM_OFFSET,
455
- getTileData: getVectorTileLoader(source, loader)
1184
+ getTileData: tile => (tile.signal?.aborted ? null : loadTile(tile))
456
1185
  });
1186
+ holdBeforeRequestSlot(tileset, gate);
457
1187
  this.state.tilesets.set(source, tileset);
458
1188
  this.state.tilesetSourceLayers.set(source, sourceLayerKeys.get(source)!);
459
1189
  }
460
1190
  }
461
1191
  for (const source of demSources) {
462
1192
  if (!this.state.tilesets.has(source)) {
463
- const tileset = createDemTileset(source, this.props.loadOptions);
1193
+ const tileset = createDemTileset(
1194
+ source,
1195
+ withTransformRequest(this.props.loadOptions as BasemapLoadOptions, transformRequest),
1196
+ this.props.projectedMaxStretch
1197
+ );
464
1198
  this.state.tilesets.set(source, tileset);
465
1199
  this.state.tilesetSourceLayers.set(source, sourceLayerKeys.get(source)!);
466
1200
  }
@@ -476,36 +1210,477 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
476
1210
  return labelPlacement;
477
1211
  }
478
1212
 
1213
+ /** The props of the current layer: an async load can end after the props changed. */
1214
+ private getCurrentProps(): BasemapLayerProps {
1215
+ return (this.getCurrentLayer() ?? this).props;
1216
+ }
1217
+
1218
+ /** Gives each tile load once to `onTileLoad`: the style layers of a source share its tiles. */
1219
+ private reportTileLoad(tile: BasemapTile): void {
1220
+ const {reportedTiles} = this.state;
1221
+ if (reportedTiles.has(tile) && reportedTiles.get(tile) === tile.content) {
1222
+ return;
1223
+ }
1224
+ reportedTiles.set(tile, tile.content);
1225
+ this.getCurrentProps().onTileLoad?.(tile);
1226
+ }
1227
+
1228
+ /**
1229
+ * Calls `onViewportLoad` when the style, its sprites and the tiles that every tile sublayer
1230
+ * selects have loaded, and the tiles are not those last reported. As in deck.gl's `TileLayer`,
1231
+ * the tiles count, not the layers drawn from them.
1232
+ */
1233
+ private checkViewportLoad(): void {
1234
+ const {resolvedStyle, renderedStyle, spriteAtlases, loadedToken, loadToken} = this.state;
1235
+ if (
1236
+ loadedToken !== loadToken ||
1237
+ !resolvedStyle ||
1238
+ renderedStyle !== resolvedStyle ||
1239
+ !spriteAtlases
1240
+ ) {
1241
+ return;
1242
+ }
1243
+ const tiles: BasemapTile[] = [];
1244
+ for (const layer of this.getSubLayers()) {
1245
+ if (this.state.insertedLayers.has(layer)) {
1246
+ continue;
1247
+ }
1248
+ const selected = getLoadedSelectedTiles(layer);
1249
+ if (!selected) {
1250
+ return;
1251
+ }
1252
+ tiles.push(...selected);
1253
+ }
1254
+ const unique = [...new Set(tiles)];
1255
+ const last = this.state.viewportTiles;
1256
+ // A viewport that selects no tiles has nothing loaded (an empty `every` is true).
1257
+ const reported =
1258
+ last?.length === unique.length && last.every((tile, i) => tile === unique[i]);
1259
+ if (!unique.length || reported) {
1260
+ return;
1261
+ }
1262
+ this.state.viewportTiles = unique;
1263
+ this.getCurrentProps().onViewportLoad?.(unique);
1264
+ }
1265
+
1266
+ /** Calls `onAttributionChange` when the attributions of the drawn sources change. */
1267
+ private updateAttributions(style: ResolvedBasemapStyle | null, zoom: number): void {
1268
+ const attributions = style ? getStyleAttributions(style, zoom, this.getStyleConfig()) : [];
1269
+ const key = JSON.stringify(attributions);
1270
+ if (key !== this.state.attributions) {
1271
+ this.state.attributions = key;
1272
+ this.getCurrentProps().onAttributionChange?.(attributions);
1273
+ }
1274
+ }
1275
+
1276
+ /**
1277
+ * Adds this layer's tile and viewport callbacks to its tile sublayers, after their own. The
1278
+ * layer manager runs a sublayer's callbacks with the props of its latest render.
1279
+ */
1280
+ private addTileCallbacks(layers: Layer[]): Layer[] {
1281
+ return layers.map(layer => {
1282
+ if (
1283
+ this.state.insertedLayers.has(layer) ||
1284
+ !(layer instanceof TileLayer || layer instanceof SharedTile2DLayer)
1285
+ ) {
1286
+ return layer;
1287
+ }
1288
+ const {onTileLoad, onViewportLoad} = layer.props as {
1289
+ onTileLoad?: ((tile: BasemapTile) => void) | null;
1290
+ onViewportLoad?: ((tiles: BasemapTile[]) => void) | null;
1291
+ };
1292
+ return layer.clone({
1293
+ onTileLoad: (tile: BasemapTile) => {
1294
+ onTileLoad?.(tile);
1295
+ this.reportTileLoad(tile);
1296
+ },
1297
+ onViewportLoad: (tiles: BasemapTile[]) => {
1298
+ onViewportLoad?.(tiles);
1299
+ // The sublayer reports during its update, before the other sublayers update.
1300
+ Promise.resolve().then(() =>
1301
+ (this.getCurrentLayer() as this | null)?.checkViewportLoad()
1302
+ );
1303
+ }
1304
+ } as any);
1305
+ });
1306
+ }
1307
+
479
1308
  /** Renders the sublayers generated from the resolved style definition. */
480
1309
  renderLayers() {
481
- const {resolvedStyle} = this.state;
482
- if (!resolvedStyle) {
483
- return [];
1310
+ const {resolvedStyle: baseStyle} = this.state;
1311
+ const {viewport} = this.context;
1312
+ // In a projected view, the zoom of the Web Mercator map of the same scale.
1313
+ const zoom = getStyleZoom(viewport);
1314
+ this.updateAttributions(baseStyle, zoom);
1315
+ // Recorded without setState: this only tracks what the current sublayers were built from.
1316
+ this.state.renderedStyle = baseStyle;
1317
+ if (!baseStyle) {
1318
+ const insertLayers = this.props.insertLayers || [];
1319
+ this.setInsertedLayers(insertLayers);
1320
+ return insertLayers.map(insertion => insertion.layers);
484
1321
  }
1322
+ const resolvedStyle = this.getStyleWithSourceData(baseStyle);
485
1323
 
1324
+ this.state.zoomLoadGate.delay = Math.max(0, Number(this.props.zoomLoadDelay) || 0);
486
1325
  this.updateSourceTilesets(resolvedStyle);
487
- const {viewport} = this.context;
488
- const zoom = viewport?.zoom || 0;
489
- // Recorded without setState: this only tracks what the current sublayers were built from.
490
1326
  this.state.zoomKey = this.getZoomKey(resolvedStyle, viewport);
491
1327
 
492
- return getBasemapLayers({
1328
+ const insertLayers = this.getValidInsertions(resolvedStyle);
1329
+ const layers = getBasemapLayers({
1330
+ insertLayers,
493
1331
  idPrefix: this.props.id,
1332
+ featureState: this.props.featureState,
1333
+ pickable: this.props.pickable,
494
1334
  mode: this.getDrawMode(viewport),
495
- globe: this.props.globe,
1335
+ globe: this.getStyleConfig(),
496
1336
  styleDefinition: resolvedStyle,
497
1337
  zoom,
498
1338
  loadOptions: this.props.loadOptions,
1339
+ fetch: this.props.fetch,
1340
+ transformRequest: this.props.transformRequest,
1341
+ rejectRasterTile: this.props.rejectRasterTile,
1342
+ onError: error => this.reportError(error),
499
1343
  spriteAtlases: this.state.spriteAtlases,
500
1344
  fontFamily: this.props.fontFamily,
501
1345
  // A label font of the caller's is drawn with the browser's fonts.
502
1346
  glyphs: this.props.fontFamily ? null : this.state.glyphs,
503
1347
  labelPlacement: this.getLabelPlacement(),
504
- tilesets: this.state.tilesets
1348
+ tilesets: this.state.tilesets,
1349
+ projected: isProjectedViewport(viewport),
1350
+ firstPerson: isGeographicFirstPersonViewport(viewport),
1351
+ projectedMaxStretch: this.props.projectedMaxStretch,
1352
+ styleLayerProps: this.getStyleLayerPropsMap(resolvedStyle)
505
1353
  });
1354
+ this.setInsertedLayers(insertLayers);
1355
+ const {extensions} = this.props;
1356
+ if (extensions.length === 0) {
1357
+ return this.addTileCallbacks(layers);
1358
+ }
1359
+ // The inserted layers are the app's: they do not take the extensions of the basemap, and stay
1360
+ // the same objects, which picking finds (see `getPickingInfo`).
1361
+ return this.addTileCallbacks(
1362
+ layers.map(layer =>
1363
+ this.state.insertedLayers.has(layer) ? layer : this.addExtensions(layer)
1364
+ )
1365
+ );
1366
+ }
1367
+
1368
+ /**
1369
+ * A basemap sublayer with the extensions of this layer and the props of those extensions, as
1370
+ * `getSubLayerProps` gives them: the sublayers are not made with `getSubLayerProps`. A sublayer
1371
+ * keeps its own extensions, and runs them first.
1372
+ */
1373
+ private addExtensions(layer: Layer): Layer {
1374
+ const {extensions} = this.props;
1375
+ const props: Record<string, any> = {
1376
+ extensions: [...(layer.props.extensions || []), ...extensions],
1377
+ updateTriggers: {...layer.props.updateTriggers}
1378
+ };
1379
+ for (const extension of extensions) {
1380
+ const {updateTriggers, ...extensionProps} = extension.getSubLayerProps.call(this, extension);
1381
+ Object.assign(props, extensionProps);
1382
+ Object.assign(props.updateTriggers, updateTriggers);
1383
+ }
1384
+ return layer.clone(props);
1385
+ }
1386
+
1387
+ /** Records the drawn layers of `insertions`, which picking reads (see `getPickingInfo`). */
1388
+ private setInsertedLayers(insertions: BasemapInsertion[]): void {
1389
+ // Recorded without setState, as `zoomKey`: it only tracks what the current sublayers are.
1390
+ this.state.insertedLayers = new Set(
1391
+ ([insertions.map(insertion => insertion.layers as unknown)].flat(Infinity) as unknown[]).filter(
1392
+ (layer): layer is Layer => Boolean(layer)
1393
+ )
1394
+ );
1395
+ }
1396
+
1397
+ /**
1398
+ * The insertions of `insertLayers` whose `beforeId` names a layer of `resolvedStyle`. Each one
1399
+ * that does not raises an error to `onError`, once for each style and `insertLayers`, as
1400
+ * MapLibre GL JS's `addLayer` fires an `error` event for an unknown `beforeId`.
1401
+ */
1402
+ private getValidInsertions(resolvedStyle: ResolvedBasemapStyle): BasemapInsertion[] {
1403
+ const {insertLayers} = this.props;
1404
+ if (!insertLayers?.length) {
1405
+ return [];
1406
+ }
1407
+ const styleLayerIds = new Set((resolvedStyle.layers || []).map(layer => layer.id));
1408
+ const isKnown = ({beforeId}: BasemapInsertion) =>
1409
+ beforeId === undefined || beforeId === null || styleLayerIds.has(beforeId);
1410
+ const unknownIds = insertLayers
1411
+ .filter(insertion => !isKnown(insertion))
1412
+ .map(insertion => insertion.beforeId as string);
1413
+ // Apps pass a new `insertLayers` on every render: an error is raised again only when the style
1414
+ // or the unknown ids change.
1415
+ const beforeIds = JSON.stringify(unknownIds);
1416
+ const reported = this.state.insertionError;
1417
+ if (unknownIds.length && (reported?.style !== resolvedStyle || reported.beforeIds !== beforeIds)) {
1418
+ for (const beforeId of unknownIds) {
1419
+ this.raiseError(getInsertionError(beforeId), '');
1420
+ }
1421
+ }
1422
+ this.state.insertionError = unknownIds.length ? {style: resolvedStyle, beforeIds} : null;
1423
+ return insertLayers.filter(isKnown);
1424
+ }
1425
+
1426
+ /**
1427
+ * Picks an inserted layer as a top-level layer: `info.layer` is the inserted layer, so that deck
1428
+ * calls its `onHover` and `onClick`, and not those of the basemap.
1429
+ */
1430
+ getPickingInfo(params: GetPickingInfoParams): PickingInfo {
1431
+ const info = super.getPickingInfo(params);
1432
+ const {sourceLayer} = params;
1433
+ if (sourceLayer && this.state.insertedLayers.has(sourceLayer)) {
1434
+ info.layer = sourceLayer;
1435
+ }
1436
+ return info;
506
1437
  }
507
1438
  }
508
1439
 
1440
+ /** Diff commands that load a source, the sprite or the glyphs (see `diff`). */
1441
+ const LOADING_DIFF_COMMANDS = new Set([
1442
+ 'setStyle',
1443
+ 'addSource',
1444
+ 'removeSource',
1445
+ 'setGeoJSONSourceData',
1446
+ 'setSprite',
1447
+ 'setGlyphs'
1448
+ ]);
1449
+
1450
+ function isStyleObject(style: BasemapLayerProps['style']): style is BasemapStyle {
1451
+ return Boolean(style) && typeof style === 'object';
1452
+ }
1453
+
1454
+ /**
1455
+ * Whether a source of `style` failed to load: the TileJSON of a source with a `url`, or the data of
1456
+ * a GeoJSON source given by URL (see `resolveBasemapStyle`).
1457
+ */
1458
+ function hasFailedSource(style: BasemapStyle | null, resolvedStyle: ResolvedBasemapStyle): boolean {
1459
+ return Object.entries(style?.sources || {}).some(([sourceId, source]) => {
1460
+ const resolved = resolvedStyle.sources[sourceId];
1461
+ return source.type === 'geojson'
1462
+ ? typeof source.data === 'string' && !resolved?.data
1463
+ : Boolean(source.url) && !resolved?.url;
1464
+ });
1465
+ }
1466
+
1467
+ /** A copy of a style object, as `loadStyle` reads it: through JSON. */
1468
+ function copyStyle(style: BasemapStyle): BasemapStyle {
1469
+ return JSON.parse(JSON.stringify(style));
1470
+ }
1471
+
1472
+ /**
1473
+ * A copy of a style (see `copyStyle`) resolved with the sources of `current`, or null if it is not
1474
+ * valid. A style layer that did not change keeps its object, and with it the caches of its paint
1475
+ * and filters.
1476
+ */
1477
+ function getUpdatedStyle(
1478
+ style: BasemapStyle,
1479
+ current: ResolvedBasemapStyle
1480
+ ): ResolvedBasemapStyle | null {
1481
+ const {sources: _sources, ...definition} = style;
1482
+ const parsed = BasemapStyleSchema.safeParse(definition);
1483
+ if (!parsed.success) {
1484
+ return null;
1485
+ }
1486
+ const resolved = ResolvedBasemapStyleSchema.safeParse({
1487
+ ...parsed.data,
1488
+ sources: {},
1489
+ layers: derefLayers([...(parsed.data.layers || [])] as Parameters<typeof derefLayers>[0])
1490
+ });
1491
+ if (!resolved.success) {
1492
+ return null;
1493
+ }
1494
+ const currentLayers = new Map(current.layers.map(layer => [layer.id, layer]));
1495
+ return {
1496
+ ...resolved.data,
1497
+ sources: current.sources,
1498
+ layers: resolved.data.layers.map(layer => {
1499
+ const currentLayer = currentLayers.get(layer.id);
1500
+ return currentLayer && getSourceKey(currentLayer) === getSourceKey(layer)
1501
+ ? currentLayer
1502
+ : layer;
1503
+ })
1504
+ };
1505
+ }
1506
+
1507
+ /**
1508
+ * Puts the source objects of `previous` back in `resolvedStyle` where the content of a source is
1509
+ * the same (see `getSourceKey`).
1510
+ */
1511
+ function reuseSources(resolvedStyle: ResolvedBasemapStyle, previous: ResolvedBasemapStyle): void {
1512
+ const previousSources = new Map(
1513
+ Object.values(previous.sources).map(source => [getSourceKey(source), source])
1514
+ );
1515
+ for (const [sourceId, source] of Object.entries(resolvedStyle.sources)) {
1516
+ resolvedStyle.sources[sourceId] = previousSources.get(getSourceKey(source)) ?? source;
1517
+ }
1518
+ }
1519
+
1520
+ /**
1521
+ * The most tile zooms between a held tile and the loaded ancestor that draws in its place. A much
1522
+ * coarser tile, such as one loaded for the first view of the map, has too little detail to draw
1523
+ * in place of a tile 8 times as fine.
1524
+ */
1525
+ const MAX_PLACEHOLDER_ZOOMS = 3;
1526
+
1527
+ /** Whether a tileset has loaded content for a near ancestor of a tile, which draws in its place. */
1528
+ function hasLoadedAncestor(
1529
+ tileset: SharedTileset2D,
1530
+ index: {x: number; y: number; z: number}
1531
+ ): boolean {
1532
+ for (let parent = index; parent.z > Math.max(0, index.z - MAX_PLACEHOLDER_ZOOMS); ) {
1533
+ parent = tileset.getParentIndex(parent);
1534
+ const ancestor = tileset.getTile(parent);
1535
+ if (ancestor?.isLoaded && ancestor.content) {
1536
+ return true;
1537
+ }
1538
+ }
1539
+ return false;
1540
+ }
1541
+
1542
+ /** A request token that does not take a slot, for a held load that a newer load replaced. */
1543
+ const NO_SLOT = {done: () => {}};
1544
+
1545
+ /**
1546
+ * Holds the vector tile loads of `tileset` in `gate` before they take a request slot, so that held
1547
+ * tiles do not keep a tile with no placeholder from loading. Only a tile that a loaded ancestor
1548
+ * draws, enlarged, meanwhile is held: in a zoom out the new tiles cover more than the old, and
1549
+ * load at once. `SharedTileset2D` has no option for its request scheduler, so this wraps its own.
1550
+ */
1551
+ function holdBeforeRequestSlot(tileset: SharedTileset2D, gate: ZoomLoadGate): void {
1552
+ const internals = tileset as unknown as {_requestScheduler: RequestScheduler};
1553
+ const scheduler = internals._requestScheduler;
1554
+ if (!scheduler) {
1555
+ throw new Error('SharedTileset2D has no request scheduler to hold zoom loads before.');
1556
+ }
1557
+ const requests = new WeakMap<SharedTile2DHeader, number>();
1558
+ internals._requestScheduler = {
1559
+ async scheduleRequest(tile: SharedTile2DHeader, getPriority?: () => number) {
1560
+ const request = (requests.get(tile) ?? 0) + 1;
1561
+ requests.set(tile, request);
1562
+ const isCurrent = () => requests.get(tile) === request;
1563
+ if (
1564
+ gate.delay > 0 &&
1565
+ (await gate.wait(null, () => isCurrent() && hasLoadedAncestor(tileset, tile.index)))
1566
+ ) {
1567
+ if (!isCurrent()) {
1568
+ // A newer load of the tile replaced this one, and aborted its signal: it fetches nothing.
1569
+ return NO_SLOT;
1570
+ }
1571
+ // The view has come to rest: a tile that no view shows or selects now is not loaded.
1572
+ // Cancelled, it loads again if a view selects it later.
1573
+ if (!tile.isLoading || !tileset.visibleTiles.includes(tile)) {
1574
+ return null;
1575
+ }
1576
+ }
1577
+ return scheduler.scheduleRequest(tile, getPriority);
1578
+ }
1579
+ } as RequestScheduler;
1580
+ }
1581
+
1582
+ /**
1583
+ * The basemap tile traversal `adapter`, which also records each view's zoom in `gate` at each tile
1584
+ * selection. This is the view's own zoom: in a projected view the Web Mercator zoom of the same
1585
+ * scale changes with the latitude, so a pan would hold loads as a zoom does.
1586
+ */
1587
+ function getZoomGatedAdapter(
1588
+ gate: ZoomLoadGate,
1589
+ adapter: ReturnType<typeof getBasemapTilesetAdapter>
1590
+ ): SharedTileset2DAdapter<unknown> {
1591
+ return {
1592
+ getTileIndices(context) {
1593
+ const viewport = context.viewState as Viewport;
1594
+ gate.noteZoom(viewport.id, viewport.zoom);
1595
+ return adapter.getTileIndices(context);
1596
+ },
1597
+ getTileBoundingBox: (context, index) => adapter.getTileBoundingBox(context, index)
1598
+ };
1599
+ }
1600
+
1601
+ /**
1602
+ * The selected tiles of a tile sublayer, once they have all loaded; null while one loads. A layer
1603
+ * that is not a tile layer selects no tiles.
1604
+ */
1605
+ function getLoadedSelectedTiles(layer: Layer): BasemapTile[] | null {
1606
+ if (layer instanceof TileLayer) {
1607
+ const tileset = layer.state?.tileset;
1608
+ return tileset?.isLoaded ? tileset.selectedTiles! : null;
1609
+ }
1610
+ if (layer instanceof SharedTile2DLayer) {
1611
+ const views = [...((layer.state as any)?.tilesetViews?.values() ?? [])];
1612
+ if (!views.length || !views.every(view => view.isLoaded)) {
1613
+ return null;
1614
+ }
1615
+ return views.flatMap(view => view.selectedTiles);
1616
+ }
1617
+ return [];
1618
+ }
1619
+
1620
+ /**
1621
+ * Whether a style layer is drawn at `zoom`, as MapLibre GL JS's `StyleLayer.isHidden`, and with
1622
+ * the globe toggles.
1623
+ */
1624
+ function isShownAt(
1625
+ layer: ResolvedBasemapStyleLayer,
1626
+ zoom: number,
1627
+ globe: ReturnType<BasemapLayer['getStyleConfig']>
1628
+ ): boolean {
1629
+ return (
1630
+ isDrawnStyleLayer(layer, globe) &&
1631
+ layer.layout?.visibility !== 'none' &&
1632
+ !(layer.minzoom !== undefined && zoom < layer.minzoom) &&
1633
+ !(layer.maxzoom !== undefined && zoom >= layer.maxzoom)
1634
+ );
1635
+ }
1636
+
1637
+ /**
1638
+ * The `attribution` of the sources that the shown layers of a style draw at `zoom`, in source
1639
+ * order, as MapLibre GL JS's `AttributionControl` collects them: each once, without blank ones,
1640
+ * and without one that another contains.
1641
+ */
1642
+ function getStyleAttributions(
1643
+ style: ResolvedBasemapStyle,
1644
+ zoom: number,
1645
+ globe: ReturnType<BasemapLayer['getStyleConfig']>
1646
+ ): string[] {
1647
+ const used = new Set(
1648
+ (style.layers || []).filter(layer => isShownAt(layer, zoom, globe)).map(layer => layer.source)
1649
+ );
1650
+ const attributions: string[] = [];
1651
+ for (const [id, source] of Object.entries(style.sources || {})) {
1652
+ const {attribution} = source || {};
1653
+ if (
1654
+ used.has(id) &&
1655
+ typeof attribution === 'string' &&
1656
+ attribution.trim() &&
1657
+ !attributions.includes(attribution)
1658
+ ) {
1659
+ attributions.push(attribution);
1660
+ }
1661
+ }
1662
+ return attributions.filter(
1663
+ attribution =>
1664
+ !attributions.some(other => other !== attribution && other.includes(attribution))
1665
+ );
1666
+ }
1667
+
1668
+ /**
1669
+ * Fetches the style document of a URL with the `fetch` and `fetchOptions` of `loadOptions`, as its
1670
+ * sources, sprites and glyphs are fetched, and resolves it. Relative URLs in the style resolve
1671
+ * against `loadOptions.baseUrl`, or else against the style URL.
1672
+ */
1673
+ async function loadStyleUrl(
1674
+ url: string,
1675
+ loadOptions: BasemapLayerProps['loadOptions'],
1676
+ sourceCache: Map<string, BasemapSource>,
1677
+ onError: BasemapLoadErrorHandler
1678
+ ): Promise<ResolvedBasemapStyle> {
1679
+ const options = (loadOptions || {}) as NonNullable<BasemapLoadOptions>;
1680
+ const style = (await fetchJson(url, options, 'Style')) as BasemapStyle;
1681
+ return resolveBasemapStyle(style, {...options, sourceCache, onError, baseUrl: options.baseUrl || url});
1682
+ }
1683
+
509
1684
  /**
510
1685
  * The glyph store of a style's `glyphs` URL, or null without one. A relative URL resolves against
511
1686
  * the style URL, as sprite URLs do.
@@ -513,21 +1688,34 @@ export class BasemapLayer extends CompositeLayer<Required<BasemapLayerProps>> {
513
1688
  function getGlyphStore(
514
1689
  resolvedStyle: ResolvedBasemapStyle,
515
1690
  style: BasemapLayerProps['style'],
516
- loadOptions: BasemapLayerProps['loadOptions']
1691
+ loadOptions: BasemapLayerProps['loadOptions'],
1692
+ onError: BasemapLoadErrorHandler
517
1693
  ): GlyphStore | null {
518
1694
  const url = resolvedStyle.glyphs;
519
1695
  if (typeof url !== 'string' || !url) {
520
1696
  return null;
521
1697
  }
522
- const options = (loadOptions || {}) as {
523
- baseUrl?: string;
524
- fetch?: typeof fetch;
525
- fetchOptions?: RequestInit;
526
- };
1698
+ const options = (loadOptions || {}) as NonNullable<BasemapLoadOptions>;
527
1699
  return new GlyphStore({
528
1700
  url,
529
- baseUrl: typeof style === 'string' ? style : options.baseUrl,
1701
+ baseUrl: getStyleBaseUrl(style, options.baseUrl),
530
1702
  fetch: options.fetch,
531
- fetchOptions: options.fetchOptions
1703
+ fetchOptions: options.fetchOptions,
1704
+ onError,
1705
+ transformRequest: options.transformRequest
532
1706
  });
533
1707
  }
1708
+
1709
+ /**
1710
+ * The URL that relative `sprite` and `glyphs` URLs resolve against: the style URL, the URL that a
1711
+ * resolved style was loaded from, or else `loadOptions.baseUrl`.
1712
+ */
1713
+ function getStyleBaseUrl(
1714
+ style: BasemapLayerProps['style'],
1715
+ baseUrl: string | undefined
1716
+ ): string | undefined {
1717
+ if (typeof style === 'string') {
1718
+ return style;
1719
+ }
1720
+ return (isResolvedBasemapStyle(style) && getResolvedBasemapStyleBaseUrl(style)) || baseUrl;
1721
+ }