mobility-toolbox-js 3.0.0-beta.32 → 3.0.0-beta.33

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 (41) hide show
  1. package/api/HttpAPI.js +1 -3
  2. package/api/RealtimeAPI.d.ts +3 -3
  3. package/api/WebSocketAPI.js +0 -1
  4. package/common/styles/realtimeDefaultStyle.js +0 -5
  5. package/common/styles/realtimeHeadingStyle.js +0 -5
  6. package/common/styles/realtimeSimpleStyle.d.ts +0 -1
  7. package/common/styles/realtimeSimpleStyle.js +0 -1
  8. package/common/utils/RealtimeEngine.d.ts +224 -0
  9. package/common/utils/RealtimeEngine.js +565 -0
  10. package/common/utils/getLayersAsFlatArray.d.ts +0 -1
  11. package/common/utils/getLayersAsFlatArray.js +0 -1
  12. package/common/utils/realtimeConfig.d.ts +1 -1
  13. package/common/utils/realtimeConfig.js +0 -1
  14. package/maplibre/layers/RealtimeLayer.d.ts +50 -109
  15. package/maplibre/layers/RealtimeLayer.js +108 -111
  16. package/mbt.js +5122 -13362
  17. package/mbt.js.map +4 -4
  18. package/mbt.min.js +67 -70
  19. package/mbt.min.js.map +4 -4
  20. package/ol/controls/RoutingControl.d.ts +5 -4
  21. package/ol/controls/RoutingControl.js +2 -29
  22. package/ol/controls/StopFinderControl.d.ts +2 -5
  23. package/ol/controls/StopFinderControl.js +0 -3
  24. package/ol/layers/MaplibreLayer.d.ts +18 -10
  25. package/ol/layers/MaplibreLayer.js +18 -10
  26. package/ol/layers/MaplibreStyleLayer.d.ts +39 -27
  27. package/ol/layers/MaplibreStyleLayer.js +33 -28
  28. package/ol/layers/RealtimeLayer.d.ts +72 -124
  29. package/ol/layers/RealtimeLayer.js +130 -168
  30. package/ol/mixins/PropertiesLayerMixin.d.ts +4 -6
  31. package/ol/mixins/PropertiesLayerMixin.js +0 -2
  32. package/ol/renderers/RealtimeLayerRenderer.js +6 -31
  33. package/ol/styles/fullTrajectoryDelayStyle.js +5 -7
  34. package/ol/styles/fullTrajectoryStyle.d.ts +1 -2
  35. package/ol/styles/fullTrajectoryStyle.js +5 -7
  36. package/ol/styles/routingStyle.d.ts +0 -1
  37. package/ol/styles/routingStyle.js +2 -7
  38. package/package.json +31 -30
  39. package/types/common.d.ts +2 -1
  40. package/common/mixins/RealtimeLayerMixin.d.ts +0 -267
  41. package/common/mixins/RealtimeLayerMixin.js +0 -751
@@ -0,0 +1,565 @@
1
+ import debounce from 'lodash.debounce';
2
+ import throttle from 'lodash.throttle';
3
+ import { buffer, containsCoordinate, intersects } from 'ol/extent';
4
+ import GeoJSON from 'ol/format/GeoJSON';
5
+ import { fromLonLat } from 'ol/proj';
6
+ import { RealtimeAPI, RealtimeModes } from '../../api';
7
+ import realtimeDefaultStyle from '../styles/realtimeDefaultStyle';
8
+ import * as realtimeConfig from './realtimeConfig';
9
+ import renderTrajectories from './renderTrajectories';
10
+ /**
11
+ * This class is responsible for drawing trajectories from a realtime API in a canvas,
12
+ * depending on the map's view state and at a specific time.
13
+ *
14
+ * This class is totally agnostic from Maplibre or OpenLayers and must stay taht way.
15
+ */
16
+ class RealtimeEngine {
17
+ constructor(options) {
18
+ this.getViewState = () => ({});
19
+ this.shouldRender = () => true;
20
+ this._mode = options.mode || RealtimeModes.TOPOGRAPHIC;
21
+ this._speed = options.speed || 1; // If live property is true. The speed is ignored.
22
+ this._style = options.style || realtimeDefaultStyle;
23
+ this._time = options.time || new Date();
24
+ this.api = options.api || new RealtimeAPI(options);
25
+ this.bboxParameters = options.bboxParameters;
26
+ this.canvas = options.canvas || document.createElement('canvas');
27
+ this.debug = options.debug || false;
28
+ this.filter = options.filter;
29
+ this.hoverVehicleId = options.hoverVehicleId;
30
+ /**
31
+ * If true. The layer will always use Date.now() on the next tick to render the trajectories.
32
+ * When true, setting the time property has no effect.
33
+ */
34
+ this.live = options.live !== false;
35
+ this.minZoomInterpolation = options.minZoomInterpolation || 8; // Min zoom level from which trains positions are not interpolated.
36
+ this.pixelRatio =
37
+ options.pixelRatio ||
38
+ (typeof window !== 'undefined' ? window.devicePixelRatio : 1);
39
+ this.selectedVehicleId = options.selectedVehicleId;
40
+ this.sort = options.sort;
41
+ /**
42
+ * Custom options to pass as last parameter of the style function.
43
+ */
44
+ // @ts-expect-error good type must be defined
45
+ this.styleOptions = Object.assign(Object.assign({}, realtimeConfig), (options.styleOptions || {}));
46
+ this.tenant = options.tenant || ''; // sbb,sbh or sbm
47
+ this.trajectories = {};
48
+ this.useDebounce = options.useDebounce || false;
49
+ this.useRequestAnimationFrame = options.useRequestAnimationFrame || false;
50
+ this.useThrottle = options.useThrottle !== false; // the default behavior
51
+ this.getViewState = options.getViewState || (() => ({}));
52
+ this.shouldRender = options.shouldRender || (() => true);
53
+ this.onRender = options.onRender;
54
+ this.onStart = options.onStart;
55
+ this.onStop = options.onStop;
56
+ this.format = new GeoJSON();
57
+ // Server will block non train before zoom 9
58
+ this.motsByZoom = options.motsByZoom || [
59
+ realtimeConfig.MOTS_ONLY_RAIL,
60
+ realtimeConfig.MOTS_ONLY_RAIL,
61
+ realtimeConfig.MOTS_ONLY_RAIL,
62
+ realtimeConfig.MOTS_ONLY_RAIL,
63
+ realtimeConfig.MOTS_ONLY_RAIL,
64
+ realtimeConfig.MOTS_ONLY_RAIL,
65
+ realtimeConfig.MOTS_ONLY_RAIL,
66
+ realtimeConfig.MOTS_ONLY_RAIL,
67
+ realtimeConfig.MOTS_ONLY_RAIL,
68
+ realtimeConfig.MOTS_WITHOUT_CABLE,
69
+ realtimeConfig.MOTS_WITHOUT_CABLE,
70
+ ];
71
+ // Mots by zoom
72
+ this.getMotsByZoom = (zoom) => {
73
+ if (options.getMotsByZoom) {
74
+ return options.getMotsByZoom(zoom, this.motsByZoom);
75
+ }
76
+ return this.motsByZoom[zoom];
77
+ };
78
+ // Generalization levels by zoom
79
+ this.generalizationLevelByZoom = options.generalizationLevelByZoom || [];
80
+ this.getGeneralizationLevelByZoom = (zoom) => {
81
+ if (options.getGeneralizationLevelByZoom) {
82
+ return options.getGeneralizationLevelByZoom(zoom, this.generalizationLevelByZoom);
83
+ }
84
+ return this.generalizationLevelByZoom[zoom];
85
+ };
86
+ // Render time interval by zoom
87
+ this.renderTimeIntervalByZoom = options.renderTimeIntervalByZoom || [
88
+ 100000, 50000, 40000, 30000, 20000, 15000, 10000, 5000, 2000, 1000, 400,
89
+ 300, 250, 180, 90, 60, 50, 50, 50, 50, 50,
90
+ ];
91
+ this.getRenderTimeIntervalByZoom = (zoom) => {
92
+ if (options.getRenderTimeIntervalByZoom) {
93
+ return options.getRenderTimeIntervalByZoom(zoom, this.renderTimeIntervalByZoom);
94
+ }
95
+ return this.renderTimeIntervalByZoom[zoom];
96
+ };
97
+ // This property will call api.setBbox on each movend event
98
+ this.isUpdateBboxOnMoveEnd = options.isUpdateBboxOnMoveEnd !== false;
99
+ // Define throttling and debounce render function
100
+ this.throttleRenderTrajectories = throttle(this.renderTrajectoriesInternal, 50, { leading: false, trailing: true });
101
+ this.debounceRenderTrajectories = debounce(this.renderTrajectoriesInternal, 50, { leading: true, maxWait: 5000, trailing: true });
102
+ this.renderState = {
103
+ center: [0, 0],
104
+ rotation: 0,
105
+ zoom: undefined,
106
+ };
107
+ this.onTrajectoryMessage = this.onTrajectoryMessage.bind(this);
108
+ this.onDeleteTrajectoryMessage = this.onDeleteTrajectoryMessage.bind(this);
109
+ this.onDocumentVisibilityChange =
110
+ this.onDocumentVisibilityChange.bind(this);
111
+ }
112
+ /**
113
+ * Add a trajectory.
114
+ * @param {RealtimeTrajectory} trajectory The trajectory to add.
115
+ * @private
116
+ */
117
+ addTrajectory(trajectory) {
118
+ if (!this.trajectories) {
119
+ this.trajectories = {};
120
+ }
121
+ const id = trajectory.properties.train_id;
122
+ if (id !== undefined) {
123
+ this.trajectories[id] = trajectory;
124
+ }
125
+ this.renderTrajectories();
126
+ }
127
+ attachToMap() {
128
+ // To avoid browser hanging when the tab is not visible for a certain amount of time,
129
+ // We stop the rendering and the websocket when hide and start again when show.
130
+ document.addEventListener('visibilitychange', this.onDocumentVisibilityChange);
131
+ }
132
+ detachFromMap() {
133
+ document.removeEventListener('visibilitychange', this.onDocumentVisibilityChange);
134
+ this.stop();
135
+ if (this.canvas) {
136
+ const context = this.canvas.getContext('2d');
137
+ if (context) {
138
+ context.clearRect(0, 0, this.canvas.width, this.canvas.height);
139
+ }
140
+ }
141
+ }
142
+ /**
143
+ * Get the duration before the next update depending on zoom level.
144
+ *
145
+ * @private
146
+ * @param {number} zoom
147
+ */
148
+ getRefreshTimeInMs() {
149
+ var _a;
150
+ const viewState = this.getViewState();
151
+ const zoom = viewState.zoom || 0;
152
+ const roundedZoom = zoom !== undefined ? Math.round(zoom) : -1;
153
+ const timeStep = this.getRenderTimeIntervalByZoom(roundedZoom) || 25;
154
+ const nextTick = Math.max(25, timeStep / (this.speed || 1));
155
+ const nextThrottleTick = Math.min(nextTick, 500);
156
+ // TODO: see if this should go elsewhere.
157
+ if (this.useThrottle) {
158
+ this.throttleRenderTrajectories = throttle(this.renderTrajectoriesInternal, nextThrottleTick, { leading: true, trailing: true });
159
+ }
160
+ else if (this.useDebounce) {
161
+ this.debounceRenderTrajectories = debounce(this.renderTrajectoriesInternal, nextThrottleTick, { leading: true, maxWait: 5000, trailing: true });
162
+ }
163
+ if ((_a = this.api) === null || _a === void 0 ? void 0 : _a.buffer) {
164
+ const [, size] = this.api.buffer;
165
+ this.api.buffer = [nextThrottleTick, size];
166
+ }
167
+ return nextTick;
168
+ }
169
+ /**
170
+ * Get vehicle.
171
+ * @param {function} filterFc A function use to filter results.
172
+ * @return {Array<Object>} Array of vehicle.
173
+ */
174
+ getVehicle(filterFc) {
175
+ return ((this.trajectories &&
176
+ // @ts-expect-error good type must be defined
177
+ Object.values(this.trajectories).filter(filterFc)) ||
178
+ []);
179
+ }
180
+ /**
181
+ * Request feature information for a given coordinate.
182
+ *
183
+ * @param {ol/coordinate~Coordinate} coordinate Coordinate.
184
+ * @param {Object} options Options See child classes to see which options are supported.
185
+ * @param {number} [options.resolution=1] The resolution of the map.
186
+ * @param {number} [options.nb=Infinity] The max number of vehicles to return.
187
+ * @return {Promise<FeatureInfo>} Promise with features, layer and coordinate.
188
+ */
189
+ getVehiclesAtCoordinate(coordinate, options) {
190
+ const { resolution } = this.getViewState();
191
+ const { hitTolerance, nb } = options || {};
192
+ const ext = buffer([...coordinate, ...coordinate], (hitTolerance || 5) * (resolution || 1));
193
+ let trajectories = Object.values(this.trajectories || {});
194
+ if (this.sort) {
195
+ // @ts-expect-error good type must be defined
196
+ trajectories = trajectories.sort(this.sort);
197
+ }
198
+ const vehicles = [];
199
+ for (let i = 0; i < trajectories.length; i += 1) {
200
+ // @ts-expect-error coordinate is added by the RealtimeLayer
201
+ const { coordinate: trajcoord } = trajectories[i].properties;
202
+ if (trajcoord && containsCoordinate(ext, trajcoord)) {
203
+ vehicles.push(trajectories[i]);
204
+ }
205
+ if (vehicles.length === nb) {
206
+ break;
207
+ }
208
+ }
209
+ return { features: vehicles, type: 'FeatureCollection' };
210
+ }
211
+ /**
212
+ * Callback on websocket's deleted_vehicles channel events.
213
+ * It removes the trajectory from the list.
214
+ *
215
+ * @private
216
+ * @override
217
+ */
218
+ onDeleteTrajectoryMessage(data) {
219
+ if (!data.content) {
220
+ return;
221
+ }
222
+ this.removeTrajectory(data.content);
223
+ }
224
+ onDocumentVisibilityChange() {
225
+ if (document.hidden) {
226
+ this.stop();
227
+ // Since we don't receive deleted_vehicles event when docuement
228
+ // is hidden. We have to clean all the trajectories for a fresh
229
+ // start when the document is visible again.
230
+ this.trajectories = {};
231
+ }
232
+ else {
233
+ const viewState = this.getViewState();
234
+ if (!viewState.visible) {
235
+ return;
236
+ }
237
+ this.start();
238
+ }
239
+ }
240
+ /**
241
+ * Callback on websocket's trajectory channel events.
242
+ * It adds a trajectory to the list.
243
+ *
244
+ * @private
245
+ */
246
+ onTrajectoryMessage(data) {
247
+ if (!data.content) {
248
+ return;
249
+ }
250
+ const trajectory = data.content;
251
+ const { geometry, properties: { raw_coordinates: rawCoordinates, time_since_update: timeSinceUpdate, }, } = trajectory;
252
+ // ignore old events [SBAHNM-97]
253
+ // @ts-expect-error can be undefined
254
+ if (timeSinceUpdate < 0) {
255
+ return;
256
+ }
257
+ // console.time(`onTrajectoryMessage${data.content.properties.train_id}`);
258
+ if (this.purgeTrajectory(trajectory)) {
259
+ return;
260
+ }
261
+ if (this.debug &&
262
+ this.mode === RealtimeModes.TOPOGRAPHIC &&
263
+ rawCoordinates) {
264
+ // @ts-expect-error missing type definition
265
+ trajectory.properties.olGeometry = this.format.readGeometry({
266
+ coordinates: fromLonLat(rawCoordinates),
267
+ type: 'Point',
268
+ });
269
+ }
270
+ else {
271
+ // @ts-expect-error missing type definition
272
+ trajectory.properties.olGeometry = this.format.readGeometry(geometry);
273
+ }
274
+ // TODO Make sure the timeOffset is useful. May be we can remove it.
275
+ // @ts-expect-error missing type definition
276
+ trajectory.properties.timeOffset = Date.now() - data.timestamp;
277
+ this.addTrajectory(trajectory);
278
+ }
279
+ /**
280
+ * On zoomend we adjust the time interval of the update of vehicles positions.
281
+ *
282
+ * @param evt Event that triggered the function.
283
+ * @private
284
+ */
285
+ onZoomEnd() {
286
+ this.startUpdateTime();
287
+ }
288
+ /**
289
+ * Remove all trajectories that are in the past.
290
+ */
291
+ purgeOutOfDateTrajectories() {
292
+ Object.entries(this.trajectories || {}).forEach(([key, trajectory]) => {
293
+ var _a;
294
+ const timeIntervals = (_a = trajectory === null || trajectory === void 0 ? void 0 : trajectory.properties) === null || _a === void 0 ? void 0 : _a.time_intervals;
295
+ if (this.time && (timeIntervals === null || timeIntervals === void 0 ? void 0 : timeIntervals.length)) {
296
+ const lastTimeInterval = timeIntervals[timeIntervals.length - 1][0];
297
+ if (lastTimeInterval < this.time.getTime()) {
298
+ this.removeTrajectory(key);
299
+ }
300
+ }
301
+ });
302
+ }
303
+ /**
304
+ * Determine if the trajectory is useless and should be removed from the list or not.
305
+ * By default, this function exclude vehicles:
306
+ * - that have their trajectory outside the current extent and
307
+ * - that aren't in the MOT list.
308
+ *
309
+ * @param {RealtimeTrajectory} trajectory
310
+ * @param {Array<number>} extent
311
+ * @param {number} zoom
312
+ * @return {boolean} if the trajectory must be displayed or not.
313
+ * @private
314
+ */
315
+ purgeTrajectory(trajectory) {
316
+ const viewState = this.getViewState();
317
+ const extent = viewState.extent;
318
+ const { bounds, type } = trajectory.properties;
319
+ if ((this.isUpdateBboxOnMoveEnd && extent && !intersects(extent, bounds)) ||
320
+ (this.mots && !this.mots.includes(type))) {
321
+ this.removeTrajectory(trajectory);
322
+ return true;
323
+ }
324
+ return false;
325
+ }
326
+ removeTrajectory(trajectoryOrId) {
327
+ var _a;
328
+ let id;
329
+ if (typeof trajectoryOrId !== 'string') {
330
+ id = (_a = trajectoryOrId === null || trajectoryOrId === void 0 ? void 0 : trajectoryOrId.properties) === null || _a === void 0 ? void 0 : _a.train_id;
331
+ }
332
+ else {
333
+ id = trajectoryOrId;
334
+ }
335
+ if (id !== undefined && this.trajectories) {
336
+ delete this.trajectories[id];
337
+ }
338
+ }
339
+ /**
340
+ * Render the trajectories requesting an animation frame and cancelling the previous one.
341
+ * This function must be overrided by children to provide the correct parameters.
342
+ *
343
+ * @param {object} viewState The view state of the map.
344
+ * @param {number[2]} viewState.center Center coordinate of the map in mercator coordinate.
345
+ * @param {number[4]} viewState.extent Extent of the map in mercator coordinates.
346
+ * @param {number[2]} viewState.size Size ([width, height]) of the canvas to render.
347
+ * @param {number} [viewState.rotation = 0] Rotation of the map to render.
348
+ * @param {number} viewState.resolution Resolution of the map to render.
349
+ * @param {boolean} noInterpolate If true trajectories are not interpolated but
350
+ * drawn at the last known coordinate. Use this for performance optimization
351
+ * during map navigation.
352
+ * @private
353
+ */
354
+ renderTrajectories(noInterpolate) {
355
+ const viewState = this.getViewState();
356
+ if (this.requestId) {
357
+ cancelAnimationFrame(this.requestId);
358
+ this.requestId = undefined;
359
+ }
360
+ if (!(viewState === null || viewState === void 0 ? void 0 : viewState.center) || !(viewState === null || viewState === void 0 ? void 0 : viewState.extent) || !(viewState === null || viewState === void 0 ? void 0 : viewState.size)) {
361
+ return;
362
+ }
363
+ if (!noInterpolate && this.useRequestAnimationFrame) {
364
+ this.requestId = requestAnimationFrame(() => {
365
+ this.renderTrajectoriesInternal(viewState, noInterpolate);
366
+ });
367
+ }
368
+ else if (!noInterpolate && this.useDebounce) {
369
+ this.debounceRenderTrajectories(viewState, noInterpolate);
370
+ }
371
+ else if (!noInterpolate && this.useThrottle) {
372
+ this.throttleRenderTrajectories(viewState, noInterpolate);
373
+ }
374
+ else {
375
+ this.renderTrajectoriesInternal(viewState, noInterpolate);
376
+ }
377
+ }
378
+ /**
379
+ * Launch renderTrajectories. it avoids duplicating code in renderTrajectories method.
380
+ *
381
+ * @param {object} viewState The view state of the map.
382
+ * @param {number[2]} viewState.center Center coordinate of the map in mercator coordinate.
383
+ * @param {number[4]} viewState.extent Extent of the map in mercator coordinates.
384
+ * @param {number[2]} viewState.size Size ([width, height]) of the canvas to render.
385
+ * @param {number} [viewState.rotation = 0] Rotation of the map to render.
386
+ * @param {number} viewState.resolution Resolution of the map to render.
387
+ * @param {boolean} noInterpolate If true trajectories are not interpolated but
388
+ * drawn at the last known coordinate. Use this for performance optimization
389
+ * during map navigation.
390
+ * @private
391
+ */
392
+ renderTrajectoriesInternal(viewState, noInterpolate = false) {
393
+ var _a, _b;
394
+ if (!this.trajectories || !this.shouldRender()) {
395
+ return false;
396
+ }
397
+ const time = this.live ? Date.now() : (_a = this.time) === null || _a === void 0 ? void 0 : _a.getTime();
398
+ const trajectories = Object.values(this.trajectories);
399
+ // console.time('sort');
400
+ if (this.sort) {
401
+ // @ts-expect-error type problem
402
+ trajectories.sort(this.sort);
403
+ }
404
+ // console.timeEnd('sort');
405
+ if (!this.canvas || !this.style) {
406
+ return true;
407
+ }
408
+ this.renderState = renderTrajectories(this.canvas, trajectories, this.style, Object.assign(Object.assign({}, viewState), { pixelRatio: this.pixelRatio || 1, time }), Object.assign({ filter: this.filter, hoverVehicleId: this.hoverVehicleId, noInterpolate: (viewState.zoom || 0) < this.minZoomInterpolation
409
+ ? true
410
+ : noInterpolate, selectedVehicleId: this.selectedVehicleId }, this.styleOptions));
411
+ (_b = this.onRender) === null || _b === void 0 ? void 0 : _b.call(this, this.renderState, viewState);
412
+ // console.timeEnd('render');
413
+ return true;
414
+ }
415
+ setBbox() {
416
+ const viewState = this.getViewState();
417
+ const extent = viewState.extent;
418
+ const zoom = viewState.zoom || 0;
419
+ if (!extent || Number.isNaN(zoom)) {
420
+ return;
421
+ }
422
+ // Clean trajectories before sending the new bbox
423
+ // Purge trajectories:
424
+ // - which are outside the extent
425
+ // - when it's bus and zoom level is too low for them
426
+ if (this.trajectories && extent && zoom) {
427
+ const keys = Object.keys(this.trajectories);
428
+ for (let i = keys.length - 1; i >= 0; i -= 1) {
429
+ this.purgeTrajectory(this.trajectories[keys[i]]);
430
+ }
431
+ }
432
+ // The backend only supports non float value
433
+ const zoomFloor = Math.floor(zoom);
434
+ if (!extent || Number.isNaN(zoomFloor)) {
435
+ return;
436
+ }
437
+ // The extent does not need to be precise under meter, so we round floor/ceil the values.
438
+ const [minX, minY, maxX, maxY] = extent;
439
+ const bbox = [
440
+ Math.floor(minX),
441
+ Math.floor(minY),
442
+ Math.ceil(maxX),
443
+ Math.ceil(maxY),
444
+ zoomFloor,
445
+ ];
446
+ /* @private */
447
+ this.generalizationLevel = this.getGeneralizationLevelByZoom(zoomFloor);
448
+ if (this.generalizationLevel) {
449
+ bbox.push(`gen=${this.generalizationLevel}`);
450
+ }
451
+ /* @private */
452
+ this.mots = this.getMotsByZoom(zoomFloor);
453
+ if (this.mots) {
454
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
455
+ bbox.push(`mots=${this.mots}`);
456
+ }
457
+ if (this.tenant) {
458
+ bbox.push(`tenant=${this.tenant}`);
459
+ }
460
+ if (this.mode !== 'topographic') {
461
+ bbox.push(`channel_prefix=${this.mode}`);
462
+ }
463
+ if (this.bboxParameters) {
464
+ Object.entries(this.bboxParameters).forEach(([key, value]) => {
465
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
466
+ bbox.push(`${key}=${value}`);
467
+ });
468
+ }
469
+ // Extent and zoom level are mandatory.
470
+ this.api.bbox = bbox;
471
+ }
472
+ start() {
473
+ this.stop();
474
+ // Before starting to update trajectories, we remove trajectories that have
475
+ // a time_intervals in the past, it will
476
+ // avoid phantom train that are at the end of their route because we never
477
+ // received the deleted_vehicle event because we have changed the browser tab.
478
+ this.purgeOutOfDateTrajectories();
479
+ this.renderTrajectories();
480
+ this.startUpdateTime();
481
+ this.api.open();
482
+ this.api.subscribeTrajectory(this.mode, this.onTrajectoryMessage, undefined, this.isUpdateBboxOnMoveEnd);
483
+ this.api.subscribeDeletedVehicles(this.mode, this.onDeleteTrajectoryMessage, undefined, this.isUpdateBboxOnMoveEnd);
484
+ // Update the bbox on each move end
485
+ if (this.isUpdateBboxOnMoveEnd) {
486
+ this.setBbox();
487
+ }
488
+ if (this.onStart) {
489
+ this.onStart(this);
490
+ }
491
+ }
492
+ /**
493
+ * Start the clock.
494
+ * @private
495
+ */
496
+ startUpdateTime() {
497
+ this.stopUpdateTime();
498
+ this.updateTimeDelay = this.getRefreshTimeInMs() || 0;
499
+ this.updateTimeInterval = window.setInterval(() => {
500
+ // When live=true, we update the time with new Date();
501
+ if (this.live) {
502
+ this.time = new Date();
503
+ }
504
+ else if (this.time && this.updateTimeDelay && this.speed) {
505
+ this.time = new Date(this.time.getTime() + this.updateTimeDelay * this.speed);
506
+ }
507
+ }, this.updateTimeDelay);
508
+ }
509
+ stop() {
510
+ this.api.unsubscribeTrajectory(this.onTrajectoryMessage);
511
+ this.api.unsubscribeDeletedVehicles(this.onDeleteTrajectoryMessage);
512
+ this.api.close();
513
+ if (this.onStop) {
514
+ this.onStop(this);
515
+ }
516
+ }
517
+ /**
518
+ * Stop the clock.
519
+ * @private
520
+ */
521
+ stopUpdateTime() {
522
+ if (this.updateTimeInterval) {
523
+ clearInterval(this.updateTimeInterval);
524
+ this.updateTimeInterval = undefined;
525
+ }
526
+ }
527
+ get mode() {
528
+ return this._mode;
529
+ }
530
+ set mode(newMode) {
531
+ var _a, _b;
532
+ if (newMode === this._mode) {
533
+ return;
534
+ }
535
+ this._mode = newMode;
536
+ if ((_b = (_a = this.api) === null || _a === void 0 ? void 0 : _a.wsApi) === null || _b === void 0 ? void 0 : _b.open) {
537
+ this.stop();
538
+ this.start();
539
+ }
540
+ }
541
+ get speed() {
542
+ return this._speed;
543
+ }
544
+ set speed(newSpeed) {
545
+ this._speed = newSpeed;
546
+ this.start();
547
+ }
548
+ get style() {
549
+ return this._style;
550
+ }
551
+ set style(newStyle) {
552
+ this._style = newStyle;
553
+ this.renderTrajectories();
554
+ }
555
+ get time() {
556
+ return this._time;
557
+ }
558
+ set time(newTime) {
559
+ this._time = (newTime === null || newTime === void 0 ? void 0 : newTime.getTime)
560
+ ? newTime
561
+ : new Date(newTime);
562
+ this.renderTrajectories();
563
+ }
564
+ }
565
+ export default RealtimeEngine;
@@ -1,3 +1,2 @@
1
- /** @private */
2
1
  declare const getLayersAsFlatArray: (layersOrLayer: any | any[]) => any[];
3
2
  export default getLayersAsFlatArray;
@@ -1,5 +1,4 @@
1
1
  // TODO: I use any to avoid circular dependency with common/layers/layer
2
- /** @private */
3
2
  const getLayersAsFlatArray = (layersOrLayer) => {
4
3
  let layers = layersOrLayer;
5
4
  if (!Array.isArray(layers)) {
@@ -57,7 +57,7 @@ export declare const getTextSize: (ctx: AnyCanvasContext, markerSize: number, te
57
57
  * @param {boolean} cancelled true if the journey is cancelled.
58
58
  * @param {boolean} isDelayText true if the color is used for delay text of the symbol.
59
59
  */
60
- export declare const getDelayColor: (delayInMs: number | null, cancelled?: boolean, isDelayText?: boolean) => string;
60
+ export declare const getDelayColor: (delayInMs: null | number, cancelled?: boolean, isDelayText?: boolean) => string;
61
61
  /**
62
62
  * @private
63
63
  */
@@ -1,4 +1,3 @@
1
- /** @private */
2
1
  const radiusMapping = [
3
2
  [0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
4
3
  [0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7],