mobility-toolbox-js 3.0.0-beta.8 → 3.0.0

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 (130) hide show
  1. package/README.md +11 -3
  2. package/api/HttpAPI.d.ts +20 -0
  3. package/api/HttpAPI.js +1 -14
  4. package/api/RealtimeAPI.d.ts +404 -0
  5. package/api/RealtimeAPI.js +265 -206
  6. package/api/RoutingAPI.d.ts +47 -0
  7. package/api/RoutingAPI.js +17 -7
  8. package/api/StopsAPI.d.ts +44 -0
  9. package/api/StopsAPI.js +17 -11
  10. package/api/WebSocketAPI.d.ts +147 -0
  11. package/api/WebSocketAPI.js +164 -165
  12. package/api/index.d.ts +3 -0
  13. package/api/index.js +1 -1
  14. package/api/typedefs.d.ts +76 -0
  15. package/api/typedefs.js +27 -42
  16. package/common/controls/StopFinderControlCommon.d.ts +53 -0
  17. package/common/controls/StopFinderControlCommon.js +32 -32
  18. package/common/index.d.ts +2 -0
  19. package/common/index.js +1 -1
  20. package/common/styles/index.d.ts +4 -0
  21. package/common/styles/realtimeDefaultStyle.d.ts +36 -0
  22. package/common/styles/realtimeDefaultStyle.js +6 -11
  23. package/common/styles/realtimeDelayStyle.d.ts +12 -0
  24. package/common/styles/realtimeHeadingStyle.d.ts +12 -0
  25. package/common/styles/realtimeHeadingStyle.js +5 -10
  26. package/common/styles/realtimeSimpleStyle.d.ts +3 -0
  27. package/common/styles/realtimeSimpleStyle.js +0 -1
  28. package/common/typedefs.d.ts +102 -0
  29. package/common/typedefs.js +6 -31
  30. package/common/utils/RealtimeEngine.d.ts +214 -0
  31. package/common/utils/RealtimeEngine.js +554 -0
  32. package/common/utils/compareDepartures.d.ts +10 -0
  33. package/common/utils/compareDepartures.js +2 -2
  34. package/common/utils/constants.d.ts +5 -0
  35. package/common/utils/createCanvas.d.ts +10 -0
  36. package/common/utils/createDefaultCopyrightElt.d.ts +5 -0
  37. package/common/utils/createDefaultStopFinderElt.d.ts +5 -0
  38. package/common/utils/createRealtimeFilters.d.ts +12 -0
  39. package/common/utils/debounceDeparturesMessages.d.ts +12 -0
  40. package/common/utils/debounceWebsocketMessages.d.ts +11 -0
  41. package/common/utils/getLayersAsFlatArray.d.ts +2 -0
  42. package/common/utils/getLayersAsFlatArray.js +0 -1
  43. package/common/utils/getMapGlCopyrights.d.ts +17 -0
  44. package/common/utils/getMapGlCopyrights.js +3 -3
  45. package/common/utils/getRealtimeModeSuffix.d.ts +10 -0
  46. package/common/utils/getRealtimeModeSuffix.js +1 -0
  47. package/common/utils/getUrlWithParams.d.ts +8 -0
  48. package/common/utils/getVehiclePosition.d.ts +17 -0
  49. package/common/utils/getVehiclePosition.js +6 -3
  50. package/common/utils/index.d.ts +16 -0
  51. package/common/utils/realtimeConfig.d.ts +64 -0
  52. package/common/utils/realtimeConfig.js +0 -1
  53. package/common/utils/removeDuplicate.d.ts +9 -0
  54. package/common/utils/renderTrajectories.d.ts +17 -0
  55. package/common/utils/renderTrajectories.js +7 -6
  56. package/common/utils/sortAndFilterDepartures.d.ts +16 -0
  57. package/common/utils/sortAndFilterDepartures.js +2 -1
  58. package/common/utils/sortByDelay.d.ts +3 -0
  59. package/common/utils/sortByDelay.js +5 -1
  60. package/common/utils/timeUtils.d.ts +23 -0
  61. package/common/utils/toMercatorExtent.d.ts +5 -0
  62. package/iife.d.ts +2 -0
  63. package/index.d.ts +9 -0
  64. package/maplibre/controls/CopyrightControl.d.ts +38 -0
  65. package/maplibre/controls/CopyrightControl.js +11 -8
  66. package/maplibre/controls/index.d.ts +1 -0
  67. package/maplibre/index.d.ts +5 -0
  68. package/maplibre/layers/Layer.d.ts +29 -0
  69. package/maplibre/layers/Layer.js +2 -3
  70. package/maplibre/layers/RealtimeLayer.d.ts +124 -0
  71. package/maplibre/layers/RealtimeLayer.js +154 -118
  72. package/maplibre/layers/index.d.ts +2 -0
  73. package/maplibre/utils/getMercatorResolution.d.ts +7 -0
  74. package/maplibre/utils/getSourceCoordinates.d.ts +8 -0
  75. package/maplibre/utils/getSourceCoordinates.js +6 -5
  76. package/maplibre/utils/index.d.ts +2 -0
  77. package/mbt.js +14585 -14557
  78. package/mbt.js.map +4 -4
  79. package/mbt.min.js +75 -75
  80. package/mbt.min.js.map +4 -4
  81. package/ol/controls/CopyrightControl.d.ts +39 -0
  82. package/ol/controls/CopyrightControl.js +13 -5
  83. package/ol/controls/RoutingControl.d.ts +213 -0
  84. package/ol/controls/RoutingControl.js +250 -264
  85. package/ol/controls/StopFinderControl.d.ts +56 -0
  86. package/ol/controls/StopFinderControl.js +24 -5
  87. package/ol/controls/index.d.ts +3 -0
  88. package/ol/index.d.ts +6 -0
  89. package/ol/layers/Layer.d.ts +26 -0
  90. package/ol/layers/Layer.js +39 -0
  91. package/ol/layers/MaplibreLayer.d.ts +91 -0
  92. package/ol/layers/MaplibreLayer.js +154 -31
  93. package/ol/layers/MaplibreStyleLayer.d.ts +157 -0
  94. package/ol/layers/MaplibreStyleLayer.js +281 -210
  95. package/ol/layers/RealtimeLayer.d.ts +150 -0
  96. package/ol/layers/RealtimeLayer.js +210 -206
  97. package/ol/layers/VectorLayer.d.ts +17 -0
  98. package/ol/layers/VectorLayer.js +33 -0
  99. package/ol/layers/index.d.ts +5 -0
  100. package/ol/layers/index.js +3 -0
  101. package/ol/renderers/MaplibreLayerRenderer.d.ts +0 -0
  102. package/ol/renderers/MaplibreLayerRenderer.js +142 -114
  103. package/ol/renderers/MaplibreStyleLayerRenderer.d.ts +20 -0
  104. package/ol/renderers/MaplibreStyleLayerRenderer.js +20 -23
  105. package/ol/renderers/RealtimeLayerRenderer.d.ts +22 -0
  106. package/ol/renderers/RealtimeLayerRenderer.js +50 -70
  107. package/ol/styles/fullTrajectoryDelayStyle.d.ts +6 -0
  108. package/ol/styles/fullTrajectoryDelayStyle.js +5 -7
  109. package/ol/styles/fullTrajectoryStyle.d.ts +4 -0
  110. package/ol/styles/fullTrajectoryStyle.js +5 -7
  111. package/ol/styles/index.d.ts +3 -0
  112. package/ol/styles/routingStyle.d.ts +3 -0
  113. package/ol/styles/routingStyle.js +13 -10
  114. package/ol/utils/defineDeprecatedProperties.d.ts +10 -0
  115. package/ol/utils/defineDeprecatedProperties.js +180 -0
  116. package/ol/utils/getFeatureInfoAtCoordinate.d.ts +8 -0
  117. package/ol/utils/getFeatureInfoAtCoordinate.js +11 -17
  118. package/ol/utils/index.d.ts +1 -0
  119. package/package.json +44 -44
  120. package/setupTests.d.ts +1 -0
  121. package/setupTests.js +17 -4
  122. package/types/common.d.ts +53 -69
  123. package/types/index.d.ts +1 -1
  124. package/types/realtime.d.ts +98 -95
  125. package/types/routing.d.ts +60 -60
  126. package/types/stops.d.ts +62 -62
  127. package/common/mixins/RealtimeLayerMixin.js +0 -743
  128. package/ol/layers/MapGlLayer.js +0 -142
  129. package/ol/mixins/MobilityLayerMixin.js +0 -9
  130. package/ol/mixins/PropertiesLayerMixin.js +0 -142
@@ -1,743 +0,0 @@
1
- /* eslint-disable no-empty-function,@typescript-eslint/no-empty-function */
2
- /* eslint-disable no-useless-constructor,@typescript-eslint/no-useless-constructor */
3
- /* eslint-disable no-unused-vars,@typescript-eslint/no-unused-vars */
4
- /* eslint-disable class-methods-use-this */
5
- /* eslint-disable max-classes-per-file */
6
- import { buffer, containsCoordinate, intersects } from 'ol/extent';
7
- import { unByKey } from 'ol/Observable';
8
- import GeoJSON from 'ol/format/GeoJSON';
9
- import debounce from 'lodash.debounce';
10
- import throttle from 'lodash.throttle';
11
- import { fromLonLat } from 'ol/proj';
12
- import realtimeDefaultStyle from '../styles/realtimeDefaultStyle';
13
- import { RealtimeAPI, RealtimeModes } from '../../api';
14
- import renderTrajectories from '../utils/renderTrajectories';
15
- import * as realtimeConfig from '../utils/realtimeConfig';
16
- /**
17
- * RealtimeLayerInterface.
18
- * @private
19
- */
20
- export class RealtimeLayerInterface {
21
- /**
22
- * Start the clock.
23
- */
24
- start() { }
25
- /**
26
- * Stop the clock.
27
- */
28
- stop() { }
29
- /**
30
- * Set the Realtime api's bbox.
31
- *
32
- * @param {Array<number>} extent Extent to request, [minX, minY, maxX, maxY].
33
- * @param {number} zoom Zoom level to request. Must be an integer.
34
- */
35
- setBbox(extent, zoom) { }
36
- /**
37
- * Render the trajectories
38
- */
39
- renderTrajectories() { }
40
- /**
41
- * Request the stopSequence and the fullTrajectory informations for a vehicle.
42
- *
43
- * @param {string} id The vehicle identifier (the train_id property).
44
- * @param {RealtimeMode} mode The mode to request. If not defined, the layer´s mode propetrty will be used.
45
- * @return {Promise<{stopSequence: StopSequence, fullTrajectory: FullTrajectory>} A promise that will be resolved with the trajectory informations.
46
- */
47
- getTrajectoryInfos(id, mode) { }
48
- }
49
- /**
50
- * Mixin for RealtimeLayerInterface.
51
- *
52
- * @param {Class} Base A class to extend with {RealtimeLayerInterface} functionnalities.
53
- * @return {Class} A class that implements {RealtimeLayerInterface} class and extends Base;
54
- * @private
55
- */
56
- function RealtimeLayerMixin(Base) {
57
- // @ts-ignore
58
- return class Mixin extends Base {
59
- constructor(options) {
60
- super(Object.assign({ hitTolerance: 10 }, options));
61
- this.defineProperties(options);
62
- this.debug = options.debug || false;
63
- this.mode = options.mode || RealtimeModes.TOPOGRAPHIC;
64
- this.api = options.api || new RealtimeAPI(options);
65
- this.tenant = options.tenant || ''; // sbb,sbh or sbm
66
- this.minZoomInterpolation = options.minZoomInterpolation || 8; // Min zoom level from which trains positions are not interpolated.
67
- this.format = new GeoJSON();
68
- this.onStart = options.onStart;
69
- this.onStop = options.onStop;
70
- // Server will block non train before zoom 9
71
- this.motsByZoom = options.motsByZoom || [
72
- realtimeConfig.MOTS_ONLY_RAIL,
73
- realtimeConfig.MOTS_ONLY_RAIL,
74
- realtimeConfig.MOTS_ONLY_RAIL,
75
- realtimeConfig.MOTS_ONLY_RAIL,
76
- realtimeConfig.MOTS_ONLY_RAIL,
77
- realtimeConfig.MOTS_ONLY_RAIL,
78
- realtimeConfig.MOTS_ONLY_RAIL,
79
- realtimeConfig.MOTS_ONLY_RAIL,
80
- realtimeConfig.MOTS_ONLY_RAIL,
81
- realtimeConfig.MOTS_WITHOUT_CABLE,
82
- realtimeConfig.MOTS_WITHOUT_CABLE,
83
- ];
84
- this.getMotsByZoom = (zoom) => {
85
- if (options.getMotsByZoom) {
86
- return options.getMotsByZoom(zoom, this.motsByZoom);
87
- }
88
- return this.motsByZoom[zoom];
89
- };
90
- // Generalization levels by zoom
91
- this.generalizationLevelByZoom = options.generalizationLevelByZoom || [];
92
- this.getGeneralizationLevelByZoom = (zoom) => {
93
- if (options.getGeneralizationLevelByZoom) {
94
- return options.getGeneralizationLevelByZoom(zoom, this.generalizationLevelByZoom);
95
- }
96
- return this.generalizationLevelByZoom[zoom];
97
- };
98
- // Render time interval by zoom
99
- this.renderTimeIntervalByZoom = options.renderTimeIntervalByZoom || [
100
- 100000, 50000, 40000, 30000, 20000, 15000, 10000, 5000, 2000, 1000, 400,
101
- 300, 250, 180, 90, 60, 50, 50, 50, 50, 50,
102
- ];
103
- this.getRenderTimeIntervalByZoom = (zoom) => {
104
- if (options.getRenderTimeIntervalByZoom) {
105
- return options.getRenderTimeIntervalByZoom(zoom, this.renderTimeIntervalByZoom);
106
- }
107
- return this.renderTimeIntervalByZoom[zoom];
108
- };
109
- // This property will call api.setBbox on each movend event
110
- this.isUpdateBboxOnMoveEnd = options.isUpdateBboxOnMoveEnd !== false;
111
- // Define throttling and debounce render function
112
- this.throttleRenderTrajectories = throttle(this.renderTrajectoriesInternal, 50, { leading: false, trailing: true });
113
- this.debounceRenderTrajectories = debounce(this.renderTrajectoriesInternal, 50, { leading: true, trailing: true, maxWait: 5000 });
114
- // Bind callbacks
115
- // this.onFeatureHover = this.onFeatureHover.bind(this);
116
- // this.onFeatureClick = this.onFeatureClick.bind(this);
117
- this.renderTrajectoriesInternal =
118
- this.renderTrajectoriesInternal.bind(this);
119
- this.onTrajectoryMessage = this.onTrajectoryMessage.bind(this);
120
- this.onDeleteTrajectoryMessage =
121
- this.onDeleteTrajectoryMessage.bind(this);
122
- this.onDocumentVisibilityChange =
123
- this.onDocumentVisibilityChange.bind(this);
124
- }
125
- /**
126
- * Define layer's properties.
127
- *
128
- * @private
129
- */
130
- defineProperties(options) {
131
- (super.defineProperties || (() => { }))(options);
132
- const { style, speed, pixelRatio, hoverVehicleId, selectedVehicleId, filter, sort, time, live, canvas, styleOptions, mode, bboxParameters, } = options;
133
- let currCanvas = canvas;
134
- let currSpeed = speed || 1;
135
- let currTime = time || new Date();
136
- let currMode = mode || RealtimeModes.TOPOGRAPHIC;
137
- let currStyle = style || realtimeDefaultStyle;
138
- Object.defineProperties(this, {
139
- isTrackerLayer: { value: true },
140
- canvas: {
141
- get: () => {
142
- if (!currCanvas) {
143
- currCanvas = document.createElement('canvas');
144
- }
145
- return currCanvas;
146
- },
147
- set: (cnvas) => {
148
- currCanvas = cnvas;
149
- },
150
- },
151
- /**
152
- * Style function used to render a vehicle.
153
- */
154
- mode: {
155
- get: () => currMode,
156
- set: (newMode) => {
157
- var _a, _b;
158
- if (newMode === currMode) {
159
- return;
160
- }
161
- currMode = newMode;
162
- if ((_b = (_a = this.api) === null || _a === void 0 ? void 0 : _a.wsApi) === null || _b === void 0 ? void 0 : _b.open) {
163
- this.stop();
164
- this.start();
165
- }
166
- },
167
- },
168
- /**
169
- * Style function used to render a vehicle.
170
- */
171
- style: {
172
- get: () => currStyle,
173
- set: (newStyle) => {
174
- currStyle = newStyle;
175
- // @ts-ignore function without parameters is defined in subclasses
176
- this.renderTrajectories();
177
- },
178
- },
179
- /**
180
- * Custom options to pass as last parameter of the style function.
181
- */
182
- styleOptions: {
183
- value: Object.assign(Object.assign({}, realtimeConfig), (styleOptions || {})),
184
- },
185
- /**
186
- * Speed of the wheel of time.
187
- * If live property is true. The speed is ignored.
188
- */
189
- speed: {
190
- get: () => currSpeed,
191
- set: (newSpeed) => {
192
- currSpeed = newSpeed;
193
- this.start();
194
- },
195
- },
196
- /**
197
- * Custom parameters to send on each BBOX request.
198
- */
199
- bboxParameters: {
200
- value: bboxParameters,
201
- writable: true,
202
- },
203
- /**
204
- * Function to filter which vehicles to display.
205
- */
206
- filter: {
207
- value: filter,
208
- writable: true,
209
- },
210
- /**
211
- * Function to sort the vehicles to display.
212
- */
213
- sort: {
214
- value: sort,
215
- writable: true,
216
- },
217
- /**
218
- * If true. The layer will always use Date.now() on the next tick to render the trajectories.
219
- * When true, setting the time property has no effect.
220
- */
221
- live: {
222
- value: live === false ? live : true,
223
- writable: true,
224
- },
225
- /**
226
- * Time used to display the trajectories. Can be a Date or a number in ms representing a Date.
227
- * If live property is true. The setter does nothing.
228
- */
229
- time: {
230
- get: () => currTime,
231
- set: (newTime) => {
232
- currTime = newTime && newTime.getTime ? newTime : new Date(newTime);
233
- // @ts-ignore function without parameters is defined in subclasses
234
- this.renderTrajectories();
235
- },
236
- },
237
- /**
238
- * Keep track of which trajectories are stored.
239
- */
240
- trajectories: {
241
- value: {},
242
- writable: true,
243
- },
244
- /**
245
- * Id of the hovered vehicle.
246
- */
247
- hoverVehicleId: {
248
- value: hoverVehicleId,
249
- writable: true,
250
- },
251
- /**
252
- * Id of the selected vehicle.
253
- */
254
- selectedVehicleId: {
255
- value: selectedVehicleId,
256
- writable: true,
257
- },
258
- /**
259
- * Id of the selected vehicle.
260
- */
261
- pixelRatio: {
262
- value: pixelRatio ||
263
- (typeof window !== 'undefined' ? window.devicePixelRatio : 1),
264
- writable: true,
265
- },
266
- /**
267
- * If true, encapsulates the renderTrajectories calls in a requestAnimationFrame.
268
- */
269
- useRequestAnimationFrame: {
270
- value: options.useRequestAnimationFrame || false,
271
- writable: true,
272
- },
273
- /**
274
- * If true, encapsulates the renderTrajectories calls in a throttle function. Default to true.
275
- */
276
- useThrottle: {
277
- value: options.useThrottle !== false,
278
- writable: true,
279
- },
280
- /**
281
- * If true, encapsulates the renderTrajectories calls in a debounce function.
282
- */
283
- useDebounce: {
284
- value: options.useDebounce || false,
285
- writable: true,
286
- },
287
- /**
288
- * Debug properties.
289
- */
290
- // Not used anymore, but could be useful for debugging.
291
- // showVehicleTraj: {
292
- // value:
293
- // options.showVehicleTraj !== undefined
294
- // ? options.showVehicleTraj
295
- // : true,
296
- // writable: true,
297
- // },
298
- });
299
- }
300
- attachToMap(map) {
301
- super.attachToMap(map);
302
- // To avoid browser hanging when the tab is not visible for a certain amount of time,
303
- // We stop the rendering and the websocket when hide and start again when show.
304
- document.addEventListener('visibilitychange', this.onDocumentVisibilityChange);
305
- }
306
- detachFromMap() {
307
- document.removeEventListener('visibilitychange', this.onDocumentVisibilityChange);
308
- this.stop();
309
- unByKey(this.visibilityRef);
310
- if (this.canvas) {
311
- const context = this.canvas.getContext('2d');
312
- if (context) {
313
- context.clearRect(0, 0, this.canvas.width, this.canvas.height);
314
- }
315
- super.detachFromMap();
316
- }
317
- }
318
- start() {
319
- this.stop();
320
- // Before starting to update trajectories, we remove trajectories that have
321
- // a time_intervals in the past, it will
322
- // avoid phantom train that are at the end of their route because we never
323
- // received the deleted_vehicle event because we have changed the browser tab.
324
- this.purgeOutOfDateTrajectories();
325
- // @ts-ignore function without parameters must be define in subclasses
326
- this.renderTrajectories();
327
- this.startUpdateTime();
328
- this.api.open();
329
- this.api.subscribeTrajectory(this.mode, this.onTrajectoryMessage, undefined, this.isUpdateBboxOnMoveEnd);
330
- this.api.subscribeDeletedVehicles(this.mode, this.onDeleteTrajectoryMessage, undefined, this.isUpdateBboxOnMoveEnd);
331
- if (this.isUpdateBboxOnMoveEnd) {
332
- // Update the bbox on each move end
333
- // @ts-ignore function without parameters defined by subclasses
334
- this.setBbox();
335
- }
336
- if (this.onStart) {
337
- this.onStart(this);
338
- }
339
- }
340
- /**
341
- * Start the clock.
342
- * @private
343
- */
344
- startUpdateTime() {
345
- this.stopUpdateTime();
346
- this.updateTimeDelay = this.getRefreshTimeInMs() || 0;
347
- this.updateTimeInterval = window.setInterval(() => {
348
- // When live=true, we update the time with new Date();
349
- if (this.live) {
350
- this.time = new Date();
351
- }
352
- else if (this.time && this.updateTimeDelay && this.speed) {
353
- this.time = new Date(this.time.getTime() + this.updateTimeDelay * this.speed);
354
- }
355
- }, this.updateTimeDelay);
356
- }
357
- stop() {
358
- this.api.unsubscribeTrajectory(this.onTrajectoryMessage);
359
- this.api.unsubscribeDeletedVehicles(this.onDeleteTrajectoryMessage);
360
- this.api.close();
361
- if (this.onStop) {
362
- this.onStop(this);
363
- }
364
- }
365
- /**
366
- * Stop the clock.
367
- * @private
368
- */
369
- stopUpdateTime() {
370
- if (this.updateTimeInterval) {
371
- clearInterval(this.updateTimeInterval);
372
- this.updateTimeInterval = undefined;
373
- }
374
- }
375
- /**
376
- * Launch renderTrajectories. it avoids duplicating code in renderTrajectories method.
377
- *
378
- * @param {object} viewState The view state of the map.
379
- * @param {number[2]} viewState.center Center coordinate of the map in mercator coordinate.
380
- * @param {number[4]} viewState.extent Extent of the map in mercator coordinates.
381
- * @param {number[2]} viewState.size Size ([width, height]) of the canvas to render.
382
- * @param {number} [viewState.rotation = 0] Rotation of the map to render.
383
- * @param {number} viewState.resolution Resolution of the map to render.
384
- * @param {boolean} noInterpolate If true trajectories are not interpolated but
385
- * drawn at the last known coordinate. Use this for performance optimization
386
- * during map navigation.
387
- * @private
388
- */
389
- renderTrajectoriesInternal(viewState, noInterpolate = false) {
390
- var _a;
391
- if (!this.map || !this.trajectories) {
392
- return false;
393
- }
394
- const time = this.live ? Date.now() : (_a = this.time) === null || _a === void 0 ? void 0 : _a.getTime();
395
- const trajectories = Object.values(this.trajectories);
396
- // console.time('sort');
397
- if (this.sort) {
398
- // @ts-ignore
399
- trajectories.sort(this.sort);
400
- }
401
- // console.timeEnd('sort');
402
- if (!this.canvas || !this.style) {
403
- return true;
404
- }
405
- // console.time('render');
406
- this.renderState = renderTrajectories(this.canvas, trajectories, this.style, Object.assign(Object.assign({}, viewState), { pixelRatio: this.pixelRatio || 1, time }), Object.assign({ filter: this.filter, noInterpolate: (viewState.zoom || 0) < this.minZoomInterpolation
407
- ? true
408
- : noInterpolate, hoverVehicleId: this.hoverVehicleId, selectedVehicleId: this.selectedVehicleId }, this.styleOptions));
409
- // console.timeEnd('render');
410
- return true;
411
- }
412
- /**
413
- * Render the trajectories requesting an animation frame and cancelling the previous one.
414
- * This function must be overrided by children to provide the correct parameters.
415
- *
416
- * @param {object} viewState The view state of the map.
417
- * @param {number[2]} viewState.center Center coordinate of the map in mercator coordinate.
418
- * @param {number[4]} viewState.extent Extent of the map in mercator coordinates.
419
- * @param {number[2]} viewState.size Size ([width, height]) of the canvas to render.
420
- * @param {number} [viewState.rotation = 0] Rotation of the map to render.
421
- * @param {number} viewState.resolution Resolution of the map to render.
422
- * @param {boolean} noInterpolate If true trajectories are not interpolated but
423
- * drawn at the last known coordinate. Use this for performance optimization
424
- * during map navigation.
425
- * @private
426
- */
427
- renderTrajectories(viewState, noInterpolate) {
428
- if (this.requestId) {
429
- cancelAnimationFrame(this.requestId);
430
- this.requestId = undefined;
431
- }
432
- if (!viewState) {
433
- return;
434
- }
435
- if (!noInterpolate && this.useRequestAnimationFrame) {
436
- this.requestId = requestAnimationFrame(() => {
437
- this.renderTrajectoriesInternal(viewState, noInterpolate);
438
- });
439
- }
440
- else if (!noInterpolate && this.useDebounce) {
441
- this.debounceRenderTrajectories(viewState, noInterpolate);
442
- }
443
- else if (!noInterpolate && this.useThrottle) {
444
- this.throttleRenderTrajectories(viewState, noInterpolate);
445
- }
446
- else {
447
- this.renderTrajectoriesInternal(viewState, noInterpolate);
448
- }
449
- }
450
- setBbox(extent, zoom) {
451
- // Clean trajectories before sending the new bbox
452
- // Purge trajectories:
453
- // - which are outside the extent
454
- // - when it's bus and zoom level is too low for them
455
- if (this.trajectories && extent && zoom) {
456
- const keys = Object.keys(this.trajectories);
457
- for (let i = keys.length - 1; i >= 0; i -= 1) {
458
- this.purgeTrajectory(this.trajectories[keys[i]], extent, zoom);
459
- }
460
- }
461
- // The backend only supports non float value
462
- const zoomFloor = Math.floor(zoom);
463
- if (!extent || Number.isNaN(zoomFloor)) {
464
- return;
465
- }
466
- // The extent does not need to be precise under meter, so we round floor/ceil the values.
467
- const [minX, minY, maxX, maxY] = extent;
468
- const bbox = [
469
- Math.floor(minX),
470
- Math.floor(minY),
471
- Math.ceil(maxX),
472
- Math.ceil(maxY),
473
- zoomFloor,
474
- ];
475
- /* @private */
476
- const generalizationLevel = this.getGeneralizationLevelByZoom(zoomFloor);
477
- if (this.generalizationLevel) {
478
- bbox.push(`gen=${generalizationLevel}`);
479
- }
480
- /* @private */
481
- this.mots = this.getMotsByZoom(zoomFloor);
482
- if (this.mots) {
483
- bbox.push(`mots=${this.mots}`);
484
- }
485
- if (this.tenant) {
486
- bbox.push(`tenant=${this.tenant}`);
487
- }
488
- if (this.mode !== 'topographic') {
489
- bbox.push(`channel_prefix=${this.mode}`);
490
- }
491
- if (this.bboxParameters) {
492
- Object.entries(this.bboxParameters).forEach(([key, value]) => {
493
- bbox.push(`${key}=${value}`);
494
- });
495
- }
496
- // Extent and zoom level are mandatory.
497
- this.api.bbox = bbox;
498
- }
499
- /**
500
- * Get the duration before the next update depending on zoom level.
501
- *
502
- * @private
503
- * @param {number} zoom
504
- */
505
- getRefreshTimeInMs(zoom = 0) {
506
- var _a;
507
- const roundedZoom = zoom !== undefined ? Math.round(zoom) : -1;
508
- const timeStep = this.getRenderTimeIntervalByZoom(roundedZoom) || 25;
509
- const nextTick = Math.max(25, timeStep / (this.speed || 1));
510
- const nextThrottleTick = Math.min(nextTick, 500);
511
- // TODO: see if this should go elsewhere.
512
- if (this.useThrottle) {
513
- this.throttleRenderTrajectories = throttle(this.renderTrajectoriesInternal, nextThrottleTick, { leading: true, trailing: true });
514
- }
515
- else if (this.useDebounce) {
516
- this.debounceRenderTrajectories = debounce(this.renderTrajectoriesInternal, nextThrottleTick, { leading: true, trailing: true, maxWait: 5000 });
517
- }
518
- if ((_a = this.api) === null || _a === void 0 ? void 0 : _a.buffer) {
519
- const [, size] = this.api.buffer;
520
- this.api.buffer = [nextThrottleTick, size];
521
- }
522
- return nextTick;
523
- }
524
- /**
525
- * Get vehicle.
526
- * @param {function} filterFc A function use to filter results.
527
- * @return {Array<Object>} Array of vehicle.
528
- */
529
- getVehicle(filterFc) {
530
- return ((this.trajectories &&
531
- // @ts-ignore
532
- Object.values(this.trajectories).filter(filterFc)) ||
533
- []);
534
- }
535
- /**
536
- * Request feature information for a given coordinate.
537
- *
538
- * @param {ol/coordinate~Coordinate} coordinate Coordinate.
539
- * @param {Object} options Options See child classes to see which options are supported.
540
- * @param {number} [options.resolution=1] The resolution of the map.
541
- * @param {number} [options.nb=Infinity] The max number of vehicles to return.
542
- * @return {Promise<FeatureInfo>} Promise with features, layer and coordinate.
543
- */
544
- getFeatureInfoAtCoordinate(coordinate, options) {
545
- const { resolution, nb } = options;
546
- const ext = buffer([...coordinate, ...coordinate], this.hitTolerance * resolution);
547
- let trajectories = Object.values(this.trajectories || {});
548
- if (this.sort) {
549
- // @ts-ignore
550
- trajectories = trajectories.sort(this.sort);
551
- }
552
- const vehicles = [];
553
- for (let i = 0; i < trajectories.length; i += 1) {
554
- if (trajectories[i].properties.coordinate &&
555
- containsCoordinate(ext, trajectories[i].properties.coordinate)) {
556
- vehicles.push(trajectories[i]);
557
- }
558
- if (vehicles.length === nb) {
559
- break;
560
- }
561
- }
562
- return Promise.resolve({
563
- layer: this,
564
- features: vehicles,
565
- coordinate,
566
- });
567
- }
568
- /**
569
- * Request the stopSequence and the fullTrajectory informations for a vehicle.
570
- *
571
- * @param {string} id The vehicle identifier (the train_id property).
572
- * @return {Promise<{stopSequence: StopSequence, fullTrajectory: FullTrajectory>} A promise that will be resolved with the trajectory informations.
573
- */
574
- getTrajectoryInfos(id) {
575
- var _a, _b;
576
- // When a vehicle is selected, we request the complete stop sequence and the complete full trajectory.
577
- // Then we combine them in one response and send them to inherited layers.
578
- const promises = [
579
- this.api.getStopSequence(id),
580
- this.api.getFullTrajectory(id, this.mode, this.getGeneralizationLevelByZoom(Math.floor(((_b = (_a = this.map) === null || _a === void 0 ? void 0 : _a.getView()) === null || _b === void 0 ? void 0 : _b.getZoom()) || 0))),
581
- ];
582
- return Promise.all(promises).then(([stopSequence, fullTrajectory]) => {
583
- const response = {
584
- stopSequence,
585
- fullTrajectory,
586
- };
587
- return response;
588
- });
589
- }
590
- /**
591
- * Remove all trajectories that are in the past.
592
- */
593
- purgeOutOfDateTrajectories() {
594
- Object.entries(this.trajectories || {}).forEach(([key, trajectory]) => {
595
- var _a;
596
- const timeIntervals = (_a = trajectory === null || trajectory === void 0 ? void 0 : trajectory.properties) === null || _a === void 0 ? void 0 : _a.time_intervals;
597
- if (this.time && timeIntervals.length) {
598
- const lastTimeInterval = timeIntervals[timeIntervals.length - 1][0];
599
- if (lastTimeInterval < this.time) {
600
- this.removeTrajectory(key);
601
- }
602
- }
603
- });
604
- }
605
- /**
606
- * Determine if the trajectory is useless and should be removed from the list or not.
607
- * By default, this function exclude vehicles:
608
- * - that have their trajectory outside the current extent and
609
- * - that aren't in the MOT list.
610
- *
611
- * @param {RealtimeTrajectory} trajectory
612
- * @param {Array<number>} extent
613
- * @param {number} zoom
614
- * @return {boolean} if the trajectory must be displayed or not.
615
- * @private
616
- */
617
- purgeTrajectory(trajectory, extent, zoom) {
618
- const { type, bounds } = trajectory.properties;
619
- if ((this.isUpdateBboxOnMoveEnd && !intersects(extent, bounds)) ||
620
- (this.mots && !this.mots.includes(type))) {
621
- this.removeTrajectory(trajectory);
622
- return true;
623
- }
624
- return false;
625
- }
626
- /**
627
- * Add a trajectory.
628
- * @param {RealtimeTrajectory} trajectory The trajectory to add.
629
- * @private
630
- */
631
- addTrajectory(trajectory) {
632
- if (!this.trajectories) {
633
- this.trajectories = {};
634
- }
635
- this.trajectories[trajectory.properties.train_id] = trajectory;
636
- // @ts-ignore the parameter are set by subclasses
637
- this.renderTrajectories();
638
- }
639
- removeTrajectory(trajectoryOrId) {
640
- var _a;
641
- let id;
642
- if (typeof trajectoryOrId !== 'string') {
643
- id = (_a = trajectoryOrId === null || trajectoryOrId === void 0 ? void 0 : trajectoryOrId.properties) === null || _a === void 0 ? void 0 : _a.train_id;
644
- }
645
- else {
646
- id = trajectoryOrId;
647
- }
648
- if (this.trajectories) {
649
- delete this.trajectories[id];
650
- }
651
- }
652
- /**
653
- * On zoomend we adjust the time interval of the update of vehicles positions.
654
- *
655
- * @param evt Event that triggered the function.
656
- * @private
657
- */
658
- onZoomEnd() {
659
- this.startUpdateTime();
660
- }
661
- onDocumentVisibilityChange() {
662
- if (document.hidden) {
663
- this.stop();
664
- // Since we don't receive deleted_vehicles event when docuement
665
- // is hidden. We have to clean all the trajectories for a fresh
666
- // start when the document is visible again.
667
- this.trajectories = {};
668
- }
669
- else {
670
- if (this.visible === false) {
671
- return;
672
- }
673
- this.start();
674
- }
675
- }
676
- /**
677
- * Callback on websocket's trajectory channel events.
678
- * It adds a trajectory to the list.
679
- *
680
- * @private
681
- */
682
- onTrajectoryMessage(data) {
683
- if (!data.content) {
684
- return;
685
- }
686
- const trajectory = data.content;
687
- const { geometry, properties: { train_id: id, time_since_update: timeSinceUpdate, raw_coordinates: rawCoordinates, }, } = trajectory;
688
- // ignore old events [SBAHNM-97]
689
- if (timeSinceUpdate < 0) {
690
- return;
691
- }
692
- // console.time(`onTrajectoryMessage${data.content.properties.train_id}`);
693
- // @ts-ignore default value for extentand zoom are provided by subclasses
694
- if (this.purgeTrajectory(trajectory)) {
695
- return;
696
- }
697
- if (this.debug &&
698
- this.mode === RealtimeModes.TOPOGRAPHIC &&
699
- rawCoordinates) {
700
- trajectory.properties.olGeometry = this.format.readGeometry({
701
- type: 'Point',
702
- coordinates: fromLonLat(rawCoordinates, this.map.getView().getProjection()),
703
- });
704
- }
705
- else {
706
- trajectory.properties.olGeometry = this.format.readGeometry(geometry);
707
- }
708
- // TODO Make sure the timeOffset is useful. May be we can remove it.
709
- trajectory.properties.timeOffset = Date.now() - data.timestamp;
710
- this.addTrajectory(trajectory);
711
- }
712
- /**
713
- * Callback on websocket's deleted_vehicles channel events.
714
- * It removes the trajectory from the list.
715
- *
716
- * @private
717
- * @override
718
- */
719
- onDeleteTrajectoryMessage(data) {
720
- if (!data.content) {
721
- return;
722
- }
723
- this.removeTrajectory(data.content);
724
- }
725
- highlightVehicle(id) {
726
- if (this.hoverVehicleId !== id) {
727
- /** @private */
728
- this.hoverVehicleId = id;
729
- // @ts-ignore
730
- this.renderTrajectories(true);
731
- }
732
- }
733
- selectVehicle(id) {
734
- if (this.selectedVehicleId !== id) {
735
- /** @private */
736
- this.selectedVehicleId = id;
737
- // @ts-ignore
738
- this.renderTrajectories(true);
739
- }
740
- }
741
- };
742
- }
743
- export default RealtimeLayerMixin;