@osrd-project/ui-charts 0.0.80 → 0.0.83

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 (78) hide show
  1. package/dist/chronogram/components/Chronogram.d.ts +3 -0
  2. package/dist/chronogram/components/ChronogramCanvas.d.ts +3 -0
  3. package/dist/chronogram/components/ChronogramManchette.d.ts +9 -0
  4. package/dist/chronogram/components/OccupancyBlocksLayer.d.ts +1 -0
  5. package/dist/chronogram/hooks/useChronogram.d.ts +35 -0
  6. package/dist/chronogram/index.d.ts +9 -0
  7. package/dist/chronogram/lib/const.d.ts +5 -0
  8. package/dist/chronogram/lib/context.d.ts +6 -0
  9. package/dist/chronogram/lib/types.d.ts +30 -0
  10. package/dist/chronogram/utils/format.d.ts +1 -0
  11. package/dist/common/consts.d.ts +5 -0
  12. package/dist/common/context.d.ts +2 -0
  13. package/dist/{spaceTimeChart/utils → common/helpers}/colors.d.ts +9 -4
  14. package/dist/common/helpers/time.d.ts +31 -0
  15. package/dist/common/helpers/utils.d.ts +8 -0
  16. package/dist/common/hooks/useCanvas.d.ts +16 -0
  17. package/dist/common/hooks/useMouseInteractions.d.ts +41 -0
  18. package/dist/{spaceTimeChart → common}/hooks/useMouseTracking.d.ts +1 -1
  19. package/dist/{spaceTimeChart → common}/hooks/useSize.d.ts +0 -1
  20. package/dist/common/index.d.ts +5 -0
  21. package/dist/common/types.d.ts +104 -0
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.esm.js +2281 -1531
  24. package/dist/index.esm.js.map +1 -1
  25. package/dist/manchette/assets/sampleData.d.ts +2 -0
  26. package/dist/manchette/components/Manchette.d.ts +6 -1
  27. package/dist/manchette/components/ManchetteWithSpaceTimeChart.d.ts +4 -4
  28. package/dist/manchette/components/Waypoint.d.ts +2 -1
  29. package/dist/manchette/hooks/useManchetteWithSpaceTimeChart.d.ts +3 -36
  30. package/dist/manchette/hooks/useSyncManchette.d.ts +94 -0
  31. package/dist/manchette/index.d.ts +1 -2
  32. package/dist/manchette/types.d.ts +13 -0
  33. package/dist/spaceTimeChart/components/ConflictLayer.d.ts +1 -1
  34. package/dist/spaceTimeChart/components/ConflictTooltip.d.ts +1 -1
  35. package/dist/spaceTimeChart/components/PathLayer.d.ts +2 -1
  36. package/dist/spaceTimeChart/components/Quadrilateral.d.ts +2 -1
  37. package/dist/spaceTimeChart/components/Tooltip.d.ts +1 -1
  38. package/dist/spaceTimeChart/index.d.ts +2 -5
  39. package/dist/spaceTimeChart/lib/consts.d.ts +0 -3
  40. package/dist/spaceTimeChart/lib/context.d.ts +3 -6
  41. package/dist/spaceTimeChart/lib/types.d.ts +4 -91
  42. package/dist/spaceTimeChart/utils/canvas.d.ts +2 -37
  43. package/dist/spaceTimeChart/utils/events.d.ts +1 -1
  44. package/dist/spaceTimeChart/utils/geometry.d.ts +1 -1
  45. package/dist/spaceTimeChart/utils/scales.d.ts +2 -3
  46. package/dist/spaceTimeChart/utils/snapping.d.ts +1 -1
  47. package/dist/spaceTimeChart/utils/vectors.d.ts +1 -1
  48. package/dist/speedSpaceChart/components/SpeedSpaceChart.d.ts +21 -2
  49. package/dist/speedSpaceChart/components/common/DetailsBox.d.ts +5 -2
  50. package/dist/speedSpaceChart/components/common/SettingsPanel.d.ts +2 -1
  51. package/dist/speedSpaceChart/components/const.d.ts +22 -6
  52. package/dist/speedSpaceChart/components/helpers/drawElements/reticle.d.ts +2 -1
  53. package/dist/speedSpaceChart/components/layers/ReticleLayer.d.ts +3 -1
  54. package/dist/speedSpaceChart/components/utils.d.ts +7 -3
  55. package/dist/speedSpaceChart/index.d.ts +2 -1
  56. package/dist/speedSpaceChart/types.d.ts +40 -0
  57. package/dist/theme.css +1382 -483
  58. package/dist/theme.css.map +1 -1
  59. package/dist/trackOccupancyDiagram/components/TrackOccupancyCanvas.d.ts +1 -1
  60. package/dist/trackOccupancyDiagram/components/TrackOccupancyManchette.d.ts +1 -1
  61. package/dist/trackOccupancyDiagram/components/TrackOccupancyStandalone.d.ts +1 -1
  62. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawOccupancyZones.d.ts +8 -2
  63. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawOccupancyZonesTexts.d.ts +1 -1
  64. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawTracks.d.ts +1 -1
  65. package/dist/trackOccupancyDiagram/components/layers/OccupancyZonesLayer.d.ts +2 -2
  66. package/dist/trackOccupancyDiagram/components/layers/TracksLayer.d.ts +1 -1
  67. package/dist/trackOccupancyDiagram/components/utils.d.ts +1 -1
  68. package/dist/trackOccupancyDiagram/index.d.ts +2 -2
  69. package/dist/trackOccupancyDiagram/{components → lib}/types.d.ts +2 -1
  70. package/package.json +10 -9
  71. package/dist/manchette/hooks/usePaths.d.ts +0 -11
  72. package/dist/spaceTimeChart/hooks/useCanvas.d.ts +0 -19
  73. package/dist/spaceTimeChart/hooks/useMouseInteractions.d.ts +0 -8
  74. /package/dist/{spaceTimeChart/utils → common/helpers}/png.d.ts +0 -0
  75. /package/dist/{spaceTimeChart → common}/hooks/useDevicePixelRatio.d.ts +0 -0
  76. /package/dist/{spaceTimeChart/components → common/layers}/TimeCaptions.d.ts +0 -0
  77. /package/dist/{spaceTimeChart/components → common/layers}/TimeGraduations.d.ts +0 -0
  78. /package/dist/trackOccupancyDiagram/{components → lib}/consts.d.ts +0 -0
package/dist/index.esm.js CHANGED
@@ -1,453 +1,361 @@
1
- import React, { useState, useEffect, createContext, useContext, useRef, useCallback, useMemo, Fragment } from 'react';
2
- import cx from 'classnames';
1
+ import React, { useMemo, useState, useCallback, useEffect, createContext, useContext, useRef, Fragment } from 'react';
2
+ import { Slider, Checkbox, CheckboxesTree } from '@osrd-project/ui-core';
3
3
  import { clamp as clamp$1, isEqual, inRange, last, flatten, sortBy, sum } from 'lodash';
4
+ import cx from 'classnames';
4
5
  import chroma from 'chroma-js';
5
- import { ZoomOut, ZoomIn, Iterations, Plus, Dash, KebabHorizontal, X } from '@osrd-project/ui-icons';
6
- import { Checkbox, Slider } from '@osrd-project/ui-core';
6
+ import { Note, XCircle, ZoomOut, ZoomIn, Iterations, Sliders, X, KebabHorizontal } from '@osrd-project/ui-icons';
7
7
  import * as d3selection from 'd3-selection';
8
8
  import * as d3zoom from 'd3-zoom';
9
9
 
10
- function useDevicePixelRatio() {
11
- const [ratio, setRatio] = useState(window.devicePixelRatio || 1);
12
- useEffect(() => {
13
- if (!window.matchMedia || !window.devicePixelRatio) {
14
- return undefined;
15
- }
16
- const handleChange = () => {
17
- setRatio(window.devicePixelRatio);
18
- };
19
- const mediaQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
20
- mediaQuery.addEventListener('change', handleChange);
21
- return () => {
22
- mediaQuery.removeEventListener('change', handleChange);
23
- };
24
- }, [ratio]);
25
- return ratio;
10
+ const INITIAL_OP_LIST_HEIGHT = 521;
11
+ const BASE_WAYPOINT_HEIGHT = 32;
12
+ const INITIAL_SPACE_TIME_CHART_HEIGHT = INITIAL_OP_LIST_HEIGHT + 40;
13
+ const MIN_ZOOM_MS_PER_PX = 600_000;
14
+ const MAX_ZOOM_MS_PER_PX = 625;
15
+ const DEFAULT_ZOOM_MS_PER_PX = 7_500;
16
+ const MIN_ZOOM_X = 0;
17
+ const MAX_ZOOM_X = 100;
18
+ const MIN_ZOOM_Y = 1;
19
+ const MAX_ZOOM_Y = 10.5;
20
+ const ZOOM_Y_DELTA = 0.5;
21
+ const MAX_ZOOM_MANCHETTE_HEIGHT_MILLIMETER = 500_000;
22
+ const FOOTER_HEIGHT = 40; // height of the manchette footer
23
+ const WAYPOINT_LINE_HEIGHT = 16;
24
+ const PATH_COLOR_DEFAULT = '#8A714B';
25
+
26
+ const getHeightWithoutLastWaypoint = (height) => height - FOOTER_HEIGHT - BASE_WAYPOINT_HEIGHT;
27
+ const positionMmToKm = (position) => Math.round((position / 1000000) * 10) / 10;
28
+ const positionKmToMm = (position) => position * 1000000;
29
+ const calcTotalDistance = (ops) => {
30
+ if (ops.length === 0) {
31
+ return 0;
32
+ }
33
+ return ops.at(-1).position - ops.at(0).position;
34
+ };
35
+ function getDistance$1(a, b) {
36
+ return {
37
+ x: b.x - a.x,
38
+ y: b.y - a.y,
39
+ };
26
40
  }
27
41
 
42
+ const zoomValueToTimeScale = (slider) => MIN_ZOOM_MS_PER_PX * Math.pow(MAX_ZOOM_MS_PER_PX / MIN_ZOOM_MS_PER_PX, slider / 100);
43
+ const timeScaleToZoomValue = (timeScale) => (100 * Math.log(timeScale / MIN_ZOOM_MS_PER_PX)) /
44
+ Math.log(MAX_ZOOM_MS_PER_PX / MIN_ZOOM_MS_PER_PX);
28
45
  /**
29
- * This hook takes a DOM element reference as input, and returns always updated width and height.
30
- * It is an internal hook, and should only be used inside SpaceTimeChart.
46
+ * min zoom is computed with manchette px height between first and last waypoint.
47
+ * max zoom just the canvas drawing height (without the x-axis scale section)
31
48
  */
32
- function useSize(dom) {
33
- const [size, setSize] = useState({
34
- width: dom?.offsetWidth || 1,
35
- height: dom?.offsetHeight || 1,
49
+ const getExtremaScales = (drawingHeightWithoutTopPadding, drawingHeightWithoutBothPadding, pathLengthMillimeter) => ({
50
+ minZoomMillimeterPerPx: pathLengthMillimeter / drawingHeightWithoutBothPadding,
51
+ maxZoomMillimeterPerPx: MAX_ZOOM_MANCHETTE_HEIGHT_MILLIMETER / drawingHeightWithoutTopPadding,
52
+ });
53
+ const zoomValueToSpaceScale = (minZoomMillimeterPerPx, maxZoomMillimeterPerPx, slider) => minZoomMillimeterPerPx *
54
+ Math.pow(maxZoomMillimeterPerPx / minZoomMillimeterPerPx, (slider - MIN_ZOOM_Y) / (MAX_ZOOM_Y - MIN_ZOOM_Y));
55
+ const spaceScaleToZoomValue = (minZoomMillimeterPerPx, maxZoomMillimeterPerPx, spaceScale) => ((MAX_ZOOM_Y - MIN_ZOOM_Y) * Math.log(spaceScale / minZoomMillimeterPerPx)) /
56
+ Math.log(maxZoomMillimeterPerPx / minZoomMillimeterPerPx) +
57
+ MIN_ZOOM_Y;
58
+ /** Zoom on X axis and center on the mouse position */
59
+ const zoomX = (currentZoom, currentOffset, newZoom, position) => {
60
+ const boundedZoom = clamp$1(newZoom, MIN_ZOOM_X, MAX_ZOOM_X);
61
+ const oldTimeScale = zoomValueToTimeScale(currentZoom);
62
+ const newTimeScale = zoomValueToTimeScale(boundedZoom);
63
+ const newOffset = position - ((position - currentOffset) * oldTimeScale) / newTimeScale;
64
+ return {
65
+ xZoom: boundedZoom,
66
+ xOffset: newOffset,
67
+ };
68
+ };
69
+ const filterVisibleElements$1 = (elements, totalDistance, heightWithoutFinalWaypoint, minSpace) => {
70
+ const getPosition = (waypoint) => (waypoint.position / totalDistance) * heightWithoutFinalWaypoint;
71
+ const firstElement = elements.at(0);
72
+ const lastElement = elements.at(-1);
73
+ if (!firstElement || !lastElement)
74
+ return elements;
75
+ const sortedElements = [...elements].sort((a, b) => (b.weight ?? 0) - (a.weight ?? 0));
76
+ const displayedElements = [firstElement, lastElement];
77
+ for (const element of sortedElements) {
78
+ const hasSpace = !displayedElements.some((displayed) => Math.abs(getPosition(element) - getPosition(displayed)) < minSpace);
79
+ if (hasSpace) {
80
+ displayedElements.push(element);
81
+ }
82
+ }
83
+ return displayedElements.sort((a, b) => a.position - b.position);
84
+ };
85
+ const selectWaypointsToDisplay = (waypoints, { height, isProportional, yZoom }) => {
86
+ if (waypoints.length < 2)
87
+ return [];
88
+ // display all waypoints in linear mode
89
+ if (!isProportional)
90
+ return waypoints;
91
+ const totalDistance = calcTotalDistance(waypoints);
92
+ const manchetteHeight = getHeightWithoutLastWaypoint(height);
93
+ // in proportional mode, hide some waypoints to avoid collisions
94
+ const minSpace = BASE_WAYPOINT_HEIGHT / yZoom;
95
+ return filterVisibleElements$1(waypoints, totalDistance, manchetteHeight, minSpace);
96
+ };
97
+ /**
98
+ * 2 modes for space scales
99
+ * km (isProportional): { coefficient: gives a scale in meter/pixel }
100
+ * linear: { size: height in pixel } (each point distributed evenly along the height of manchette.)
101
+ */
102
+ const getScales = (waypoints, { isProportional, yZoom, height }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx) => {
103
+ if (!waypoints.length)
104
+ return [];
105
+ if (waypoints.length === 1) {
106
+ const waypoint = waypoints[0];
107
+ return [
108
+ {
109
+ from: waypoint.position,
110
+ to: waypoint.position,
111
+ size: height || 1,
112
+ },
113
+ ];
114
+ }
115
+ if (!isProportional) {
116
+ return waypoints.slice(0, -1).map((from, index) => {
117
+ const to = waypoints[index + 1];
118
+ return {
119
+ from: from.position,
120
+ to: to.position,
121
+ size: BASE_WAYPOINT_HEIGHT * yZoom,
122
+ };
123
+ });
124
+ }
125
+ const from = waypoints.at(0).position;
126
+ const to = waypoints.at(-1).position;
127
+ const scaleCoeff = isProportional
128
+ ? { coefficient: zoomValueToSpaceScale(minZoomMillimeterPerPx, maxZoomMillimeterPerPx, yZoom) }
129
+ : { size: BASE_WAYPOINT_HEIGHT * (waypoints.length - 1) * yZoom };
130
+ return [
131
+ {
132
+ from,
133
+ to,
134
+ ...scaleCoeff,
135
+ },
136
+ ];
137
+ };
138
+ const isInteractiveWaypoint = (item) => item != null && typeof item === 'object' && 'id' in item && 'position' in item;
139
+
140
+ const CHRONOGRAM_HEADER_HEIGHT = 33;
141
+ const CHRONOGRAM_BOTTOM_PADDING = 40;
142
+ const INITIAL_CHRONOGRAM_HEIGHT = 600;
143
+ const LEVEL_CROSSING_ITEM_HEIGHT = 48;
144
+ const CHRONOGRAM_SLIDER_WIDTH = 122;
145
+
146
+ // TODO: manchette's existant utils => common ?
147
+ function getDistance(a, b) {
148
+ return {
149
+ x: b.x - a.x,
150
+ y: b.y - a.y,
151
+ };
152
+ }
153
+ const INITIAL_STATE$1 = {
154
+ height: 0,
155
+ xOffset: 0,
156
+ yOffset: 0,
157
+ panning: null,
158
+ xZoom: timeScaleToZoomValue(3000),
159
+ };
160
+ const useChronogram = ({ itemCount, chronogramManchetteRef, chronogramChartRef, chronogramHeight, }) => {
161
+ const calculatedInitialHeight = useMemo(() => CHRONOGRAM_HEADER_HEIGHT + itemCount * LEVEL_CROSSING_ITEM_HEIGHT + CHRONOGRAM_BOTTOM_PADDING, [itemCount]);
162
+ const [isShiftPressed, setIsShiftPressed] = useState(false);
163
+ const [state, setState] = useState({
164
+ ...INITIAL_STATE$1,
165
+ height: calculatedInitialHeight,
36
166
  });
167
+ const { height, xOffset, yOffset, xZoom } = state;
168
+ const setHeight = useCallback((newHeight) => {
169
+ setState((prev) => ({
170
+ ...prev,
171
+ height: Math.max(newHeight, calculatedInitialHeight),
172
+ }));
173
+ }, [calculatedInitialHeight]);
37
174
  useEffect(() => {
38
- // Function to update the state with the new size
39
- const updateSize = () => {
40
- const width = dom?.offsetWidth || 1;
41
- const height = dom?.offsetHeight || 1;
42
- if (width !== size.width || height !== size.height)
43
- setSize({ width, height });
44
- };
45
- if (!dom) {
46
- updateSize();
47
- return;
48
- }
49
- else {
50
- const observer = new ResizeObserver(updateSize);
51
- observer.observe(dom);
52
- return () => {
53
- observer.disconnect();
175
+ // TODO: fix this lint
176
+ /* eslint-disable-next-line react-hooks/set-state-in-effect */
177
+ setHeight(chronogramHeight);
178
+ }, [chronogramHeight, setHeight]);
179
+ // =========== Pan (horizontal time navigation) ===========
180
+ const onTimePan = useCallback((payload) => {
181
+ setState((prev) => {
182
+ if (!payload.isPanning) {
183
+ return {
184
+ ...prev,
185
+ panning: null,
186
+ };
187
+ }
188
+ if (!prev.panning) {
189
+ return {
190
+ ...prev,
191
+ panning: { initialOffset: { x: prev.xOffset, y: prev.yOffset } },
192
+ };
193
+ }
194
+ const { initialOffset } = prev.panning;
195
+ const diff = getDistance(payload.initialPosition, payload.position);
196
+ const newXOffset = initialOffset.x + diff.x;
197
+ return {
198
+ ...prev,
199
+ xOffset: newXOffset,
54
200
  };
201
+ });
202
+ }, []);
203
+ // =========== Y Scroll ===========
204
+ const handleVerticalScroll = useCallback(() => {
205
+ if (chronogramManchetteRef.current) {
206
+ const { scrollTop } = chronogramManchetteRef.current;
207
+ if (scrollTop >= 0) {
208
+ setState((prev) => ({ ...prev, yOffset: scrollTop }));
209
+ }
55
210
  }
56
- }, [dom, size.height, size.width]);
57
- return size;
58
- }
211
+ }, [chronogramManchetteRef]);
212
+ // ======== Shift key events ==========
213
+ const handleKeyDown = useCallback((event) => {
214
+ if (event.key === 'Shift') {
215
+ setIsShiftPressed(true);
216
+ }
217
+ }, []);
218
+ const handleKeyUp = useCallback((event) => {
219
+ if (event.key === 'Shift') {
220
+ setIsShiftPressed(false);
221
+ }
222
+ }, []);
223
+ useEffect(() => {
224
+ window.addEventListener('keydown', handleKeyDown);
225
+ window.addEventListener('keyup', handleKeyUp);
226
+ return () => {
227
+ window.removeEventListener('keydown', handleKeyDown);
228
+ window.removeEventListener('keyup', handleKeyUp);
229
+ };
230
+ }, [handleKeyDown, handleKeyUp]);
231
+ // =========== X Zoom ===========
232
+ const handleXZoom = useCallback((newXZoom, xPosition = (chronogramChartRef.current?.offsetWidth || 0) / 2) => {
233
+ setState((prev) => ({
234
+ ...prev,
235
+ ...zoomX(prev.xZoom, prev.xOffset, newXZoom, xPosition),
236
+ }));
237
+ }, [chronogramChartRef]);
238
+ const handleXZoomOnWheelEvent = useCallback((wheelEvent, newXZoom, xPosition) => {
239
+ if (isShiftPressed) {
240
+ wheelEvent.preventDefault();
241
+ handleXZoom(newXZoom, xPosition);
242
+ }
243
+ }, [handleXZoom, isShiftPressed]);
244
+ return useMemo(() => ({
245
+ handleVerticalScroll,
246
+ handleXZoom,
247
+ handleXZoomOnWheelEvent,
248
+ height,
249
+ onPan: onTimePan,
250
+ setHeight,
251
+ xOffset,
252
+ xZoom,
253
+ yOffset,
254
+ }), [
255
+ height,
256
+ setHeight,
257
+ xOffset,
258
+ xZoom,
259
+ yOffset,
260
+ handleVerticalScroll,
261
+ handleXZoom,
262
+ handleXZoomOnWheelEvent,
263
+ onTimePan,
264
+ ]);
265
+ };
59
266
 
60
- // There are three different contexts because they have very different lifecycles.
61
- /**
62
- * This context exports everything necessary to draw the chart.
63
- * It is updated anytime the scales are updated.
64
- */
65
- const SpaceTimeChartContext = createContext(
66
- // That value should never be used, since the context should always be accessed within a provider
67
- undefined);
68
- /**
69
- * This context only contains necessary helpers to (un)register drawing functions.
70
- * It is basically never updated.
71
- */
72
- const CanvasContext = createContext(
73
- // That value should never be used, since the context should always be accessed within a provider
74
- undefined);
75
- /**
76
- * This context exports everything necessary to draw the chart.
77
- * It is updated anytime the scales are updated or the mouse moves.
78
- */
79
- const MouseContext = createContext(
267
+ const TimeChartCanvasContext = createContext(
80
268
  // That value should never be used, since the context should always be accessed within a provider
81
269
  undefined);
82
270
 
83
- const DEFAULT_PATH_END = 'stop';
84
- // CANVAS SPECIFIC TYPES:
85
- const PICKING_LAYERS = ['paths', 'overlay'];
86
- const LAYERS = ['background', 'graduations', 'paths', 'overlay', 'captions'];
87
-
88
271
  /**
89
- * This function returns the picking layers scaling ratio. We basically take the min of the screen
90
- * pixels and the "HTML pixels", and divide it by two.
91
- *
92
- * This allows having a smaller picking stage to fill (so it's faster), while keeping a "good enough
93
- * precision".
94
- */
95
- function getPickingScalingRatio() {
96
- const PICKING_DOWNSCALING_RATIO = 0.5;
97
- const dpr = window.devicePixelRatio || 1;
98
- // When devicePixelRatio is over 1 (like for Retina displays), we downscale based on the "HTML
99
- // pixels":
100
- if (dpr > 1)
101
- return PICKING_DOWNSCALING_RATIO;
102
- // When devicePixelRatio is under or equal to 1 (like when the user zooms out for instance), we
103
- // downscale based on the actual "screen pixels" (to avoid having a too large scene to fill):
104
- return PICKING_DOWNSCALING_RATIO * dpr;
105
- }
106
- /**
107
- * This function draws a thick lines from "from" to "to" on the given ImageData, with no
108
- * antialiasing. This is very useful to handle picking, since it is not possible to disable
109
- * antialiasing with the native JavaScript canvas APIs.
272
+ * @param minT number timestamp
273
+ * @param maxT number timestamp
274
+ * @param timeRanges time frames (24h, 12h, 6h, …)
275
+ * @param gridlinesLevels width of the lines for each time frame
276
+ * @param formatter function to format de values inside the output object
277
+ * Keys are times in ms
278
+ * Values are the highest level on each time
110
279
  */
111
- function drawAliasedLine(imageData, { x: fromX, y: fromY }, { x: toX, y: toY }, [r, g, b], thickness, drawOnBottom, scalingRatio = 1) {
112
- if (fromX > toX)
113
- return drawAliasedLine(imageData, { x: toX, y: toY }, { x: fromX, y: fromY }, [r, g, b], thickness, drawOnBottom, scalingRatio);
114
- fromX = Math.round(fromX * scalingRatio);
115
- fromY = Math.round(fromY * scalingRatio);
116
- toX = Math.round(toX * scalingRatio);
117
- toY = Math.round(toY * scalingRatio);
118
- thickness = Math.round(thickness * scalingRatio);
119
- const width = imageData.width;
120
- const height = imageData.height;
121
- const dx = toX - fromX;
122
- const dy = toY - fromY;
123
- const len = Math.sqrt(dx * dx + dy * dy);
124
- // Calculate perpendicular vector
125
- const normX = -dy / len;
126
- const normY = dx / len;
127
- // Calculate the four corners of the rectangle
128
- const halfThickness = Math.ceil(thickness / 2);
129
- const corner1 = {
130
- x: fromX + (+normX - dx / len) * halfThickness,
131
- y: fromY + (+normY - dy / len) * halfThickness,
132
- };
133
- const corner2 = {
134
- x: fromX + (-normX - dx / len) * halfThickness,
135
- y: fromY + (-normY - dy / len) * halfThickness,
136
- };
137
- const corner3 = {
138
- x: toX + (-normX + dx / len) * halfThickness,
139
- y: toY + (-normY + dy / len) * halfThickness,
140
- };
141
- const corner4 = {
142
- x: toX + (+normX + dx / len) * halfThickness,
143
- y: toY + (+normY + dy / len) * halfThickness,
144
- };
145
- const ascending = fromY < toY;
146
- const top = ascending ? corner4 : corner1;
147
- const left = ascending ? corner1 : corner2;
148
- const right = ascending ? corner3 : corner4;
149
- const bottom = ascending ? corner2 : corner3;
150
- const xMin = clamp$1(Math.floor(left.x), 0, width);
151
- const xMax = clamp$1(Math.ceil(right.x), 0, width);
152
- const yMin = clamp$1(Math.floor(bottom.y), 0, height);
153
- const yMax = clamp$1(Math.ceil(top.y), 0, height);
154
- for (let y = yMin; y <= yMax; y++) {
155
- const xMinRow = clamp$1(y < left.y
156
- ? Math.floor(bottom.x + ((y - bottom.y) * (left.x - bottom.x)) / (left.y - bottom.y))
157
- : Math.floor(left.x + ((y - left.y) * (left.x - top.x)) / (left.y - top.y)), xMin, xMax);
158
- const xMaxRow = clamp$1(y < right.y
159
- ? Math.ceil(bottom.x + ((y - bottom.y) * (right.x - bottom.x)) / (right.y - bottom.y))
160
- : Math.ceil(right.x + ((y - right.y) * (right.x - top.x)) / (right.y - top.y)), xMin, xMax);
161
- for (let x = xMinRow; x <= xMaxRow; x++) {
162
- const index = (y * width + x) * 4;
163
- if (!imageData.data[index + 3]) {
164
- imageData.data[index] = r;
165
- imageData.data[index + 1] = g;
166
- imageData.data[index + 2] = b;
167
- imageData.data[index + 3] = 255;
280
+ function computeVisibleTimeMarkers(minT, maxT, timeRanges, gridlinesLevels, formatter = (level) => ({ level })) {
281
+ const result = {};
282
+ const minTLocalOffset = new Date(minT).getTimezoneOffset() * 60 * 1000;
283
+ timeRanges.forEach((range, i) => {
284
+ const gridlinesLevel = gridlinesLevels[i];
285
+ if (!gridlinesLevel)
286
+ return;
287
+ let t = Math.floor((minT - minTLocalOffset) / range) * range + minTLocalOffset;
288
+ while (t <= maxT) {
289
+ if (t >= minT) {
290
+ result[t] = { ...formatter(gridlinesLevel, i), time: t };
168
291
  }
292
+ t += range;
169
293
  }
170
- }
294
+ });
295
+ return Object.values(result);
171
296
  }
172
297
  /**
173
- * This function takes an integer radius, and returns a flat matrix of 1s and 0s, where the 1s
174
- * represent the pixels that are within the disc. The shapes are cached, to make it faster to draw
175
- * a lot of times discs of the same radius.
176
- *
177
- * Here are some examples to make it clearer what the output should look like:
178
- *
179
- * getAliasedDiscShape(0);
180
- * [1]
181
- * getAliasedDiscShape(1);
182
- * [0, 1, 0,
183
- * 1, 1, 1,
184
- * 0, 1, 0]
185
- * getAliasedDiscShape(2);
186
- * [0, 0, 1, 0, 0,
187
- * 0, 1, 1, 1, 0,
188
- * 1, 1, 1, 1, 1,
189
- * 0, 1, 1, 1, 0,
190
- * 0, 0, 1, 0, 0]
298
+ * To get crisp horizontal or vertical lines on a canvas, we must draw them as thin as possible, in
299
+ * terms of actual pixels on screen.
300
+ * The best way for this is:
301
+ * - To center lines 1, 3, 5... pixels wide in the middle of a pixel (0.5, 1.5, 2.5...)
302
+ * - To center lines 2, 4, 6... pixels wide between two pixels (0, 1, 2, 3...)
303
+ * Also, for HiDPi screens:
304
+ * - To center lines of "integer thicknesses" between two screen pixels (0, 0.5, 1, 1.5, 2...)
305
+ * - To center lines with `n + 0.5` thicknesses in the middle of a screen pixel (0.25, 0.75, 1.25, 1.75...)
306
+ * @param rawCoordinate Any input coordinate to fix
307
+ * @param lineWidth The width of the line to draw
308
+ * @param devicePixelRatio
191
309
  */
192
- const DISCS_CACHE = new Map();
193
- function getAliasedDiscShape(radius) {
194
- const cachedShape = DISCS_CACHE.get(radius);
195
- if (cachedShape)
196
- return cachedShape;
197
- const diameter = radius * 2 + 1;
198
- const shape = new Uint8Array(diameter * diameter);
199
- for (let dy = -radius; dy <= radius; dy++) {
200
- for (let dx = -radius; dx <= radius; dx++) {
201
- const distance = dx * dx + dy * dy;
202
- if (distance <= radius * radius) {
203
- const x = dx + radius;
204
- const y = dy + radius;
205
- shape[y * diameter + x] = 1;
206
- }
207
- }
208
- }
209
- DISCS_CACHE.set(radius, shape);
210
- return shape;
310
+ function getCrispLineCoordinate(rawCoordinate, lineWidth, devicePixelRatio = window.devicePixelRatio || 1) {
311
+ const centerOffset = Math.ceil(lineWidth * devicePixelRatio) / devicePixelRatio / 2;
312
+ return (Math.round((rawCoordinate - centerOffset) * devicePixelRatio) / devicePixelRatio + centerOffset);
313
+ }
314
+ // ========== Time Scaling ===========
315
+ // The following functions handle data translation to the time referential:
316
+ function getTimeToPixel(timeOrigin, pixelOffset, timeScale) {
317
+ return (time) => pixelOffset + (time - timeOrigin) / timeScale;
318
+ }
319
+ function getPixelToTime(timeOrigin, pixelOffset, timeScale) {
320
+ return (timePixel) => (timePixel - pixelOffset) * timeScale + timeOrigin;
211
321
  }
322
+
323
+ const PICKING_LAYERS = ['paths', 'overlay'];
324
+ const LAYERS = ['background', 'graduations', 'paths', 'overlay', 'captions'];
325
+ // ========== DURATION CONSTANTS ==========
326
+ const SECOND = 1000;
327
+ const MINUTE = 60 * SECOND;
328
+ const HOUR = 60 * MINUTE;
329
+
330
+ const COLORS_TO_INDICES = {};
331
+ const INDICES_TO_COLORS = {};
332
+ // COLORS DEFINITIONS:
333
+ const BLACK_100 = 'rgb(0, 0, 0)';
334
+ const BLACK_ALPHA_25 = 'rgba(0, 0, 0, 0.25)';
335
+ const GREY_90 = 'rgb(31, 27, 23)';
336
+ const GREY_50$3 = 'rgb(121, 118, 113)';
337
+ const GREY_30$1 = 'rgb(182, 178, 175)';
338
+ const RED_100 = 'rgb(221, 34, 34)';
339
+ const WHITE_100$3 = 'rgb(255, 255, 255)';
340
+ const WHITE_ALPHA_75 = 'rgba(255, 255, 255, 0.75)';
212
341
  /**
213
- * This function draws an aliased disc, using a shape computed by getDiscShape.
342
+ * This function returns a unique hex color corresponding to the given index. The colors are
343
+ * generated as #000001, #000002 ... #0000ff, #000100 etc.
344
+ * These colors aim at representing the given indices on the picking layer.
214
345
  */
215
- function drawAliasedDisc(imageData, { x: centerX, y: centerY }, radius, [r, g, b], drawOnBottom, scalingRatio = 1) {
216
- centerX = Math.round(centerX * scalingRatio);
217
- centerY = Math.round(centerY * scalingRatio);
218
- radius = Math.ceil(radius * scalingRatio);
219
- const { width, height } = imageData;
220
- const discShape = getAliasedDiscShape(radius);
221
- // Draw the disc on the imageData
222
- const diameter = radius * 2 + 1;
223
- for (let dy = -radius; dy <= radius; dy++) {
224
- for (let dx = -radius; dx <= radius; dx++) {
225
- const shapeIndex = (dy + radius) * diameter + (dx + radius);
226
- if (discShape[shapeIndex] === 1) {
227
- const x = centerX + dx;
228
- const y = centerY + dy;
229
- if (x >= 0 && x < width && y >= 0 && y < height) {
230
- const index = (y * width + x) * 4;
231
- {
232
- imageData.data[index] = r;
233
- imageData.data[index + 1] = g;
234
- imageData.data[index + 2] = b;
235
- imageData.data[index + 3] = 255;
236
- }
237
- }
238
- }
239
- }
240
- }
346
+ function indexToColor(index) {
347
+ if (INDICES_TO_COLORS[index])
348
+ return INDICES_TO_COLORS[index];
349
+ const color = `#${index.toString(16).padStart(6, '0')}`.toLowerCase();
350
+ COLORS_TO_INDICES[color] = index;
351
+ INDICES_TO_COLORS[index] = color;
352
+ return color;
241
353
  }
242
354
  /**
243
- * Draws an aliased quadrilateral
244
- *
245
- * vertices[0] ________ vertices[1]
246
- * / /
247
- * vertices[3] /________/ vertices[2]
248
- *
355
+ * This function returns the index corresponding to the given color.
249
356
  */
250
- function drawAliasedQuadrilateral(imageData, points, [r, g, b], scalingRatio = 1) {
251
- const vertices = points.map((point) => ({
252
- x: Math.round(point.x * scalingRatio),
253
- y: Math.round(point.y * scalingRatio),
254
- }));
255
- let { x: xmin, x: xmax, y: ymin, y: ymax } = vertices[0];
256
- for (let i = 1; i < vertices.length; i++) {
257
- const { x, y } = vertices[i];
258
- if (x < xmin)
259
- xmin = x;
260
- else if (x > xmax)
261
- xmax = x;
262
- if (y < ymin)
263
- ymin = y;
264
- else if (y > ymax)
265
- ymax = y;
266
- }
267
- xmin = clamp$1(xmin, 0, imageData.width - 1);
268
- ymin = clamp$1(ymin, 0, imageData.height - 1);
269
- xmax = clamp$1(xmax, 0, imageData.width - 1);
270
- ymax = clamp$1(ymax, 0, imageData.height - 1);
271
- for (let y = ymin; y < ymax; y++) {
272
- for (let x = xmin; x < xmax; x++) {
273
- // Compute whether the point is inside the quadrilateral
274
- // using the Ray casting algorithm (see https://en.wikipedia.org/wiki/Point_in_polygon)
275
- let isInside = false;
276
- for (let i = 0; i < vertices.length; i++) {
277
- const pointA = vertices[i];
278
- const pointB = i === vertices.length - 1 ? vertices[0] : vertices[i + 1];
279
- // Line equation from A to B: y(x) = m * x + c
280
- const m = (pointB.y - pointA.y) / (pointB.x - pointA.x);
281
- const c = pointB.y - m * pointB.x;
282
- // Invert the equation: x(y) = (y - c) / m
283
- // Look only for points that are on the left of the line, so for a given y, x < (y - c) / m
284
- if (pointA.y > y != pointB.y > y && x < (y - c) / m) {
285
- isInside = !isInside;
286
- }
287
- }
288
- // If the point is inside the quadrilateral, allow interactions with it
289
- if (isInside) {
290
- const index = (y * imageData.width + x) * 4;
291
- imageData.data[index] = r;
292
- imageData.data[index + 1] = g;
293
- imageData.data[index + 2] = b;
294
- imageData.data[index + 3] = 255;
295
- }
296
- }
297
- }
298
- }
299
- function drawAliasedRect(imageData, { x, y }, width, height, [r, g, b], scalingRatio = 1) {
300
- x = Math.round(x * scalingRatio);
301
- y = Math.round(y * scalingRatio);
302
- width = Math.round(width * scalingRatio);
303
- height = Math.round(height * scalingRatio);
304
- const xMin = clamp$1(x, 0, imageData.width);
305
- const yMin = clamp$1(y, 0, imageData.height);
306
- const xMax = clamp$1(x + width, 0, imageData.width);
307
- const yMax = clamp$1(y + height, 0, imageData.height);
308
- for (let i = xMin; i < xMax; i++) {
309
- for (let j = yMin; j < yMax; j++) {
310
- const index = (j * imageData.width + i) * 4;
311
- imageData.data[index] = r;
312
- imageData.data[index + 1] = g;
313
- imageData.data[index + 2] = b;
314
- imageData.data[index + 3] = 255;
315
- }
316
- }
317
- }
318
- /**
319
- * This function draws a "stop" path extremity.
320
- * That handles a path that stops or starts exactly in an operational points included in the line
321
- * represented in the chart.
322
- */
323
- const STOP_END_SIZE = 6;
324
- function drawPathStopExtremity(ctx, timePixel, spacePixel, swapAxis) {
325
- ctx.beginPath();
326
- if (!swapAxis) {
327
- ctx.moveTo(timePixel, spacePixel - STOP_END_SIZE / 2);
328
- ctx.lineTo(timePixel, spacePixel + STOP_END_SIZE / 2);
329
- }
330
- else {
331
- ctx.moveTo(spacePixel - STOP_END_SIZE / 2, timePixel);
332
- ctx.lineTo(spacePixel + STOP_END_SIZE / 2, timePixel);
333
- }
334
- ctx.stroke();
335
- }
336
- /**
337
- * This function draws an "out" path extremity.
338
- * That handles a path that leaves or joins the line represented in the chart.
339
- */
340
- const OUT_END_SIZE = 12;
341
- function drawPathOutExtremity(ctx, timePixel, spacePixel, swapAxis, extremityType, pathDirection) {
342
- let horizontalSign = extremityType === 'from' ? -1 : 1;
343
- let verticalSign = (pathDirection === 'backward' ? -1 : 1) * horizontalSign;
344
- let controlX = timePixel + 4 * horizontalSign;
345
- let controlY = spacePixel + (OUT_END_SIZE - 2) * verticalSign;
346
- let x = timePixel;
347
- let y = spacePixel;
348
- if (swapAxis) {
349
- [horizontalSign, verticalSign] = [verticalSign, horizontalSign];
350
- [controlX, controlY] = [controlY, controlX];
351
- [x, y] = [y, x];
352
- }
353
- ctx.beginPath();
354
- ctx.moveTo(x, y);
355
- ctx.bezierCurveTo(controlX, controlY, controlX, controlY, x + OUT_END_SIZE * horizontalSign, y + OUT_END_SIZE * verticalSign);
356
- ctx.stroke();
357
- }
358
- /**
359
- * This function draws a path extremity.
360
- */
361
- function drawPathExtremity(ctx, timePixel, spacePixel, swapAxis, extremityType, pathDirection, pathEnd) {
362
- if (pathEnd === 'out') {
363
- drawPathOutExtremity(ctx, timePixel, spacePixel, swapAxis, extremityType, pathDirection);
364
- }
365
- else {
366
- drawPathStopExtremity(ctx, timePixel, spacePixel, swapAxis);
367
- }
368
- }
369
- /**
370
- * @param minT number timestamp
371
- * @param maxT number timestamp
372
- * @param timeRanges time frames (24h, 12h, 6h, …)
373
- * @param gridlinesLevels width of the lines for each time frame
374
- * @param formatter function to format de values inside the output object
375
- * Keys are times in ms
376
- * Values are the highest level on each time
377
- */
378
- function computeVisibleTimeMarkers(minT, maxT, timeRanges, gridlinesLevels, formatter = (level) => ({ level })) {
379
- const result = {};
380
- const minTLocalOffset = new Date(minT).getTimezoneOffset() * 60 * 1000;
381
- timeRanges.forEach((range, i) => {
382
- const gridlinesLevel = gridlinesLevels[i];
383
- if (!gridlinesLevel)
384
- return;
385
- let t = Math.floor((minT - minTLocalOffset) / range) * range + minTLocalOffset;
386
- while (t <= maxT) {
387
- if (t >= minT) {
388
- result[t] = { ...formatter(gridlinesLevel, i), time: t };
389
- }
390
- t += range;
391
- }
392
- });
393
- return Object.values(result);
394
- }
395
- /**
396
- * To get crisp horizontal or vertical lines on a canvas, we must draw them as thin as possible, in
397
- * terms of actual pixels on screen.
398
- * The best way for this is:
399
- * - To center lines 1, 3, 5... pixels wide in the middle of a pixel (0.5, 1.5, 2.5...)
400
- * - To center lines 2, 4, 6... pixels wide between two pixels (0, 1, 2, 3...)
401
- * Also, for HiDPi screens:
402
- * - To center lines of "integer thicknesses" between two screen pixels (0, 0.5, 1, 1.5, 2...)
403
- * - To center lines with `n + 0.5` thicknesses in the middle of a screen pixel (0.25, 0.75, 1.25, 1.75...)
404
- * @param rawCoordinate Any input coordinate to fix
405
- * @param lineWidth The width of the line to draw
406
- * @param devicePixelRatio
407
- */
408
- function getCrispLineCoordinate(rawCoordinate, lineWidth, devicePixelRatio = window.devicePixelRatio || 1) {
409
- const centerOffset = Math.ceil(lineWidth * devicePixelRatio) / devicePixelRatio / 2;
410
- return (Math.round((rawCoordinate - centerOffset) * devicePixelRatio) / devicePixelRatio + centerOffset);
411
- }
412
- /**
413
- * You most likely need to wrap this function call with ctx.save ctx.restore
414
- * as it modifies ctx current transformation matrix
415
- */
416
- function fillRect(ctx, { timeStart, timeEnd, spaceStart, spaceEnd }, { getPoint }) {
417
- const startPoint = getPoint({ time: Number(timeStart), position: spaceStart });
418
- const endPoint = getPoint({ time: Number(timeEnd), position: spaceEnd });
419
- const width = endPoint.x - startPoint.x;
420
- const height = endPoint.y - startPoint.y;
421
- if (width !== 0 && height !== 0) {
422
- ctx.translate(startPoint.x, startPoint.y);
423
- ctx.fillRect(0, 0, width, height);
424
- }
425
- return { width, height };
426
- }
427
-
428
- const COLORS_TO_INDICES = {};
429
- const INDICES_TO_COLORS = {};
430
- const WHITE_ALPHA_75 = '#ffffffbf';
431
- const BLACK_ALPHA_25 = '#00000025';
432
- const GREY_50$3 = '#797671';
433
- /**
434
- * This function returns a unique hex color corresponding to the given index. The colors are
435
- * generated as #000001, #000002 ... #0000ff, #000100 etc.
436
- * These colors aim at representing the given indices on the picking layer.
437
- */
438
- function indexToColor(index) {
439
- if (INDICES_TO_COLORS[index])
440
- return INDICES_TO_COLORS[index];
441
- const color = `#${index.toString(16).padStart(6, '0')}`.toLowerCase();
442
- COLORS_TO_INDICES[color] = index;
443
- INDICES_TO_COLORS[index] = color;
444
- return color;
445
- }
446
- /**
447
- * This function returns the index corresponding to the given color.
448
- */
449
- function colorToIndex(color) {
450
- return COLORS_TO_INDICES[color.toLowerCase()];
357
+ function colorToIndex(color) {
358
+ return COLORS_TO_INDICES[color.toLowerCase()];
451
359
  }
452
360
  function componentToHex(c) {
453
361
  return c.toString(16).padStart(2, '0').toLowerCase();
@@ -494,20 +402,88 @@ async function getPNGBlob(canvases, layers, backgroundColor = '#fff') {
494
402
  });
495
403
  }
496
404
 
405
+ // ============= Canvas ==============
406
+ /**
407
+ * This function returns the picking layers scaling ratio. We basically take the min of the screen
408
+ * pixels and the "HTML pixels", and divide it by two.
409
+ *
410
+ * This allows having a smaller picking stage to fill (so it's faster), while keeping a "good enough
411
+ * precision".
412
+ */
413
+ function getPickingScalingRatio() {
414
+ const PICKING_DOWNSCALING_RATIO = 0.5;
415
+ const dpr = window.devicePixelRatio || 1;
416
+ // When devicePixelRatio is over 1 (like for Retina displays), we downscale based on the "HTML
417
+ // pixels":
418
+ if (dpr > 1)
419
+ return PICKING_DOWNSCALING_RATIO;
420
+ // When devicePixelRatio is under or equal to 1 (like when the user zooms out for instance), we
421
+ // downscale based on the actual "screen pixels" (to avoid having a too large scene to fill):
422
+ return PICKING_DOWNSCALING_RATIO * dpr;
423
+ }
424
+
425
+ function useDevicePixelRatio() {
426
+ const [ratio, setRatio] = useState(window.devicePixelRatio || 1);
427
+ useEffect(() => {
428
+ if (!window.matchMedia || !window.devicePixelRatio) {
429
+ return undefined;
430
+ }
431
+ const handleChange = () => {
432
+ setRatio(window.devicePixelRatio);
433
+ };
434
+ const mediaQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
435
+ mediaQuery.addEventListener('change', handleChange);
436
+ return () => {
437
+ mediaQuery.removeEventListener('change', handleChange);
438
+ };
439
+ }, [ratio]);
440
+ return ratio;
441
+ }
442
+
443
+ /**
444
+ * This hook takes a DOM element reference as input, and returns always updated width and height.
445
+ */
446
+ function useSize(dom) {
447
+ const [size, setSize] = useState({
448
+ width: dom?.offsetWidth || 1,
449
+ height: dom?.offsetHeight || 1,
450
+ });
451
+ useEffect(() => {
452
+ // Function to update the state with the new size
453
+ const updateSize = () => {
454
+ const width = dom?.offsetWidth || 1;
455
+ const height = dom?.offsetHeight || 1;
456
+ if (width !== size.width || height !== size.height)
457
+ setSize({ width, height });
458
+ };
459
+ if (!dom) {
460
+ updateSize();
461
+ return;
462
+ }
463
+ else {
464
+ const observer = new ResizeObserver(updateSize);
465
+ observer.observe(dom);
466
+ return () => {
467
+ observer.disconnect();
468
+ };
469
+ }
470
+ }, [dom, size.height, size.width]);
471
+ return size;
472
+ }
473
+
497
474
  const PICKING = 'picking';
498
475
  const RENDERING = 'rendering';
499
476
  /**
500
- * This hook handles the internal canvas drawing logic of the SpaceTimeChart component.
501
- * It is an internal hook, and should only be used inside SpaceTimeChart.
477
+ * This hook handles the internal canvas drawing logic of a chart component.
502
478
  */
503
- function useCanvas$1(dom, inputStcContext, position) {
479
+ function useCanvas$1(dom, chartContext, position) {
504
480
  // Most things are handled through refs here so that we have a very precise control on when to
505
481
  // render anything:
506
482
  const canvasesRef = useRef({});
507
483
  const contextsRef = useRef({});
508
484
  const pickingFunctions = useRef(PICKING_LAYERS.reduce((iter, layer) => ({ ...iter, [layer]: new Set() }), {}));
509
485
  const drawingFunctions = useRef(LAYERS.reduce((iter, layer) => ({ ...iter, [layer]: new Set() }), {}));
510
- const stcContextRef = useRef(inputStcContext);
486
+ const chartContextRef = useRef(chartContext);
511
487
  const scheduledRef = useRef(null);
512
488
  const [hoveredItem, setHoveredItem] = useState(null);
513
489
  const size = useSize(dom);
@@ -523,8 +499,8 @@ function useCanvas$1(dom, inputStcContext, position) {
523
499
  /**
524
500
  * This function renders all picking layers:
525
501
  */
526
- const drawPicking = useCallback((stcContext, layers) => {
527
- stcContext.resetPickingElements();
502
+ const drawPicking = useCallback((context, layers) => {
503
+ context.resetPickingElements();
528
504
  PICKING_LAYERS.forEach((layer) => {
529
505
  if (layers && !layers.has(layer))
530
506
  return;
@@ -535,7 +511,7 @@ function useCanvas$1(dom, inputStcContext, position) {
535
511
  ctx.clearRect(0, 0, width, height);
536
512
  const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
537
513
  const pickingScalingRatio = getPickingScalingRatio();
538
- set.forEach((fn) => fn(imageData, stcContext, pickingScalingRatio));
514
+ set.forEach((fn) => fn(imageData, context, pickingScalingRatio));
539
515
  ctx.putImageData(imageData, 0, 0);
540
516
  }
541
517
  });
@@ -543,7 +519,7 @@ function useCanvas$1(dom, inputStcContext, position) {
543
519
  /**
544
520
  * This function renders all visible / rendering layers:
545
521
  */
546
- const drawRendering = useCallback((stcContext, layers) => {
522
+ const drawRendering = useCallback((context, layers) => {
547
523
  LAYERS.forEach((layer) => {
548
524
  if (layers && !layers.has(layer))
549
525
  return;
@@ -552,7 +528,7 @@ function useCanvas$1(dom, inputStcContext, position) {
552
528
  if (ctx) {
553
529
  const { width, height } = sizeRef.current;
554
530
  ctx.clearRect(0, 0, width, height);
555
- set.forEach((fn) => fn(ctx, stcContext));
531
+ set.forEach((fn) => fn(ctx, context));
556
532
  }
557
533
  });
558
534
  }, []);
@@ -560,8 +536,8 @@ function useCanvas$1(dom, inputStcContext, position) {
560
536
  * This function draws everything that needs to be drawn, and clears the scheduleRef state:
561
537
  */
562
538
  const draw = useCallback(() => {
563
- drawRendering(stcContextRef.current);
564
- drawPicking(stcContextRef.current);
539
+ drawRendering(chartContextRef.current);
540
+ drawPicking(chartContextRef.current);
565
541
  if (scheduledRef.current) {
566
542
  window.cancelAnimationFrame(scheduledRef.current.frameId);
567
543
  scheduledRef.current = null;
@@ -617,7 +593,7 @@ function useCanvas$1(dom, inputStcContext, position) {
617
593
  scheduleRendering();
618
594
  // eslint-disable-next-line react-hooks/exhaustive-deps
619
595
  }, []);
620
- const captureCanvases = useCallback(() => getPNGBlob(canvasesRef.current, LAYERS.map((layer) => `${RENDERING}-${layer}`), stcContextRef.current.theme.background), []);
596
+ const captureCanvases = useCallback(() => getPNGBlob(canvasesRef.current, LAYERS.map((layer) => `${RENDERING}-${layer}`), chartContextRef.current.theme.background), []);
621
597
  // Create all canvas layers:
622
598
  useEffect(() => {
623
599
  if (!dom)
@@ -651,10 +627,10 @@ function useCanvas$1(dom, inputStcContext, position) {
651
627
  // Redraw all layers when fingerprint changes:
652
628
  useEffect(() => {
653
629
  // Cache latest context in ref:
654
- stcContextRef.current = inputStcContext;
630
+ chartContextRef.current = chartContext;
655
631
  scheduleRendering();
656
632
  // eslint-disable-next-line react-hooks/exhaustive-deps
657
- }, [inputStcContext.fingerprint]);
633
+ }, [chartContext.fingerprint]);
658
634
  // Handle resizing:
659
635
  useEffect(() => {
660
636
  const pickingScalingRatio = getPickingScalingRatio();
@@ -691,7 +667,7 @@ function useCanvas$1(dom, inputStcContext, position) {
691
667
  if (a === 255) {
692
668
  const color = rgbToHex(r, g, b);
693
669
  const index = colorToIndex(color);
694
- const element = stcContextRef.current.pickingElements[index];
670
+ const element = chartContextRef.current.pickingElements[index];
695
671
  newHoveredItem = {
696
672
  layer,
697
673
  element,
@@ -713,11 +689,10 @@ function useCanvas$1(dom, inputStcContext, position) {
713
689
  };
714
690
  }
715
691
  /**
716
- * This hook helps to bind a picking function to a layer in the SpaceTimeChart.
717
- * It is public and can be used outside SpaceTimeChart.
692
+ * This hook helps to bind a picking function to a layer in a Chart.
718
693
  */
719
- function usePicking(layer, fn) {
720
- const { register, unregister } = useContext(CanvasContext);
694
+ function usePicking(contextKey, layer, fn) {
695
+ const { register, unregister } = useContext(contextKey);
721
696
  useEffect(() => {
722
697
  register({ type: 'picking', layer, fn });
723
698
  return () => {
@@ -726,11 +701,10 @@ function usePicking(layer, fn) {
726
701
  }, [layer, fn, register, unregister]);
727
702
  }
728
703
  /**
729
- * This hook helps to bind a drawing function to a layer in the SpaceTimeChart.
730
- * It is public and can be used outside SpaceTimeChart.
704
+ * This hook helps to bind a drawing function to a layer in a chart.
731
705
  */
732
- function useDraw(layer, fn) {
733
- const { register, unregister } = useContext(CanvasContext);
706
+ function useDraw(contextKey, layer, fn) {
707
+ const { register, unregister } = useContext(contextKey);
734
708
  useEffect(() => {
735
709
  register({ type: 'rendering', layer, fn });
736
710
  return () => {
@@ -740,78 +714,442 @@ function useDraw(layer, fn) {
740
714
  }
741
715
 
742
716
  /**
743
- * This function takes a path, a point index and looks forward in the points order for the first
744
- * position variation. It then returns "forward" or "backward" according to that variation.
745
- *
746
- * If it does not find any variation for some reason, it returns "still" instead.
747
- *
748
- * Finally, if `reversed` is true, then, it searches points in the other direction.
717
+ * This function takes a MouseEvent and an HTMLElement, and returns the position of the mouse,
718
+ * relatively to the DOM element. This allows for instance dragging an element that is on the given
719
+ * DOM element while the events are bound to the document or the body.
749
720
  */
750
- function getPathDirection({ points }, index, reversed) {
751
- if (points.length < 2 || !points[index])
752
- return 'still';
753
- const reference = points[index].position;
754
- let i = index;
755
- let point;
756
- while ((point = points[i])) {
757
- if (point.position !== reference) {
758
- const delta = reversed ? reference - point.position : point.position - reference;
759
- return delta > 0 ? 'forward' : 'backward';
760
- }
761
- i = i + (reversed ? -1 : 1);
762
- }
763
- return 'still';
721
+ function getEventPosition(e, dom) {
722
+ const bbox = dom.getBoundingClientRect();
723
+ return {
724
+ x: e.clientX - bbox.left,
725
+ y: e.clientY - bbox.top,
726
+ };
764
727
  }
765
728
  /**
766
- * This function takes a SpaceToPixel function and a position, and checks if the function returns
767
- * the same pixel for the position, starting from both sides. It then returns one or two pixel
768
- * positions accordingly.
729
+ * This function returns a delta value for a given WheelEvent. It can be very useful, since the
730
+ * given `deltaY` and `detail` attributes are not normalized.
769
731
  */
770
- function getSpacePixels(getSpacePixel, position) {
771
- const spacePixelFromStart = getSpacePixel(position);
772
- const spacePixelFromEnd = getSpacePixel(position, true);
773
- return spacePixelFromStart === spacePixelFromEnd
774
- ? [spacePixelFromStart]
775
- : [spacePixelFromStart, spacePixelFromEnd];
776
- }
777
-
778
- const SpaceGraduations = () => {
779
- const drawingFunction = useCallback((ctx, { timePixelOffset, getSpacePixel, operationalPoints, flatSteps, swapAxis, width, height, theme: { spaceGraduationsStyles }, }) => {
780
- const axisSize = !swapAxis ? width : height;
781
- // Draw operational point lines:
782
- operationalPoints.forEach((point) => {
783
- if (flatSteps.has(point.position))
784
- return;
785
- const styles = spaceGraduationsStyles[point.importanceLevel || 0];
786
- if (!styles)
787
- return;
788
- ctx.strokeStyle = styles.color;
789
- ctx.lineWidth = styles.width;
790
- ctx.globalAlpha = styles.opacity || 1;
791
- if (styles.dashArray) {
792
- ctx.setLineDash(styles.dashArray || []);
793
- ctx.lineDashOffset = -timePixelOffset;
732
+ function getEventWheelDelta(e) {
733
+ if (typeof e.deltaY !== 'undefined')
734
+ return (e.deltaY * -3) / 360;
735
+ if (typeof e.detail !== 'undefined')
736
+ return e.detail / -9;
737
+ throw new Error('Could not extract delta from event.');
738
+ }
739
+
740
+ /**
741
+ * This hook handles SpaceTimeChart mouse interactions.
742
+ * It is an internal hook, and should only be used inside SpaceTimeChart.
743
+ */
744
+ function useMouseInteractions(dom, { position, hoveredItem, down, isHover }, handlers, context) {
745
+ const contextRef = useRef(context);
746
+ const handlersRef = useRef(handlers);
747
+ const [panningState, setPanningState] = useState({ type: 'idle' });
748
+ // Cache latest context in ref:
749
+ useEffect(() => {
750
+ contextRef.current = context;
751
+ // eslint-disable-next-line react-hooks/exhaustive-deps
752
+ }, [context.fingerprint]);
753
+ useEffect(() => {
754
+ handlersRef.current = handlers;
755
+ }, [handlers]);
756
+ // Generate event handlers:
757
+ const clickHandler = useCallback((event) => {
758
+ if (!dom)
759
+ return;
760
+ const { onClick } = handlersRef.current;
761
+ if (onClick) {
762
+ onClick({
763
+ event,
764
+ position,
765
+ data: contextRef.current.getData(position),
766
+ hoveredItem,
767
+ context: contextRef.current,
768
+ });
769
+ }
770
+ }, [dom, hoveredItem, position]);
771
+ const wheelHandler = useCallback((event) => {
772
+ const { onZoom } = handlersRef.current;
773
+ if (onZoom && dom)
774
+ onZoom({
775
+ delta: getEventWheelDelta(event),
776
+ position: getEventPosition(event, dom),
777
+ event,
778
+ context: contextRef.current,
779
+ });
780
+ }, [dom]);
781
+ // Bind event handlers:
782
+ useEffect(() => {
783
+ if (!dom)
784
+ return;
785
+ dom.addEventListener('click', clickHandler);
786
+ return () => {
787
+ dom.removeEventListener('click', clickHandler);
788
+ };
789
+ }, [dom, clickHandler]);
790
+ useEffect(() => {
791
+ if (!dom)
792
+ return;
793
+ dom.addEventListener('wheel', wheelHandler);
794
+ return () => {
795
+ dom.removeEventListener('wheel', wheelHandler);
796
+ };
797
+ }, [dom, wheelHandler]);
798
+ // Listen to "up" and "down" updates:
799
+ useEffect(() => {
800
+ const { onPan } = handlersRef.current;
801
+ if (down) {
802
+ // Start panning:
803
+ setPanningState({
804
+ type: 'panning',
805
+ initialPosition: position,
806
+ initialData: contextRef.current.getData(position),
807
+ });
808
+ }
809
+ else {
810
+ // Stop panning:
811
+ if (panningState.type === 'panning' && onPan)
812
+ onPan({
813
+ isPanning: false,
814
+ position,
815
+ initialPosition: panningState.initialPosition,
816
+ data: contextRef.current.getData(position),
817
+ initialData: panningState.initialData,
818
+ context: contextRef.current,
819
+ });
820
+ if (panningState.type !== 'idle')
821
+ setPanningState({ type: 'idle' });
822
+ }
823
+ // eslint-disable-next-line react-hooks/exhaustive-deps
824
+ }, [down]);
825
+ // Listen to "move" updates:
826
+ useEffect(() => {
827
+ const { onPan, onMouseMove } = handlersRef.current;
828
+ if (onMouseMove) {
829
+ onMouseMove({
830
+ position,
831
+ isHover,
832
+ data: contextRef.current.getData(position),
833
+ hoveredItem,
834
+ context: contextRef.current,
835
+ });
836
+ }
837
+ if (panningState.type === 'panning' && onPan)
838
+ onPan({
839
+ isPanning: true,
840
+ position,
841
+ initialPosition: panningState.initialPosition,
842
+ data: contextRef.current.getData(position),
843
+ initialData: panningState.initialData,
844
+ context: contextRef.current,
845
+ });
846
+ // eslint-disable-next-line react-hooks/exhaustive-deps
847
+ }, [position.x, position.y]);
848
+ }
849
+
850
+ /**
851
+ * This hook handles SpaceTimeChart mouse tracking.
852
+ * It is an internal hook, and should only be used inside SpaceTimeChart.
853
+ */
854
+ function useMouseTracking(dom) {
855
+ const [mouseState, setMouseState] = useState({
856
+ isHover: false,
857
+ position: { x: NaN, y: NaN },
858
+ });
859
+ // Generate event handlers:
860
+ const downHandler = useCallback((e) => {
861
+ if (!dom)
862
+ return;
863
+ setMouseState((state) => ({
864
+ ...state,
865
+ down: { ctrl: e.ctrlKey, shift: e.shiftKey },
866
+ }));
867
+ }, [dom]);
868
+ const upHandler = useCallback(() => {
869
+ if (!dom)
870
+ return;
871
+ setMouseState((state) => ({ ...state, down: undefined }));
872
+ }, [dom]);
873
+ const moveHandler = useCallback((event) => {
874
+ if (!dom)
875
+ return;
876
+ const position = getEventPosition(event, dom);
877
+ const { x, y } = position;
878
+ const width = dom.offsetWidth;
879
+ const height = dom.offsetHeight;
880
+ const isHover = x >= 0 && x <= width && y >= 0 && y <= height;
881
+ setMouseState((state) => ({
882
+ ...state,
883
+ position,
884
+ isHover,
885
+ }));
886
+ }, [dom]);
887
+ // Bind event handlers:
888
+ useEffect(() => {
889
+ if (!dom)
890
+ return;
891
+ dom.addEventListener('mousedown', downHandler);
892
+ return () => {
893
+ dom.removeEventListener('mousedown', downHandler);
894
+ };
895
+ }, [dom, downHandler]);
896
+ useEffect(() => {
897
+ document.addEventListener('mouseup', upHandler);
898
+ return () => {
899
+ document.removeEventListener('mouseup', upHandler);
900
+ };
901
+ }, [upHandler]);
902
+ useEffect(() => {
903
+ document.addEventListener('mousemove', moveHandler);
904
+ return () => {
905
+ document.removeEventListener('mousemove', moveHandler);
906
+ };
907
+ }, [moveHandler]);
908
+ return mouseState;
909
+ }
910
+
911
+ const MARGIN = 100;
912
+ const MINUTE_OPTIONS = {
913
+ minute: '2-digit',
914
+ hour12: false,
915
+ };
916
+ const HOUR_OPTIONS_SHORT = {
917
+ hour: '2-digit',
918
+ hour12: false,
919
+ };
920
+ const HOUR_OPTIONS_LONG = {
921
+ hour: '2-digit',
922
+ minute: '2-digit',
923
+ hour12: false,
924
+ };
925
+ const DATE_OPTIONS = {
926
+ day: '2-digit',
927
+ month: '2-digit',
928
+ year: 'numeric',
929
+ };
930
+ const MINUTES_FORMATTER = (t) => {
931
+ const minutes = new Date(t).toLocaleTimeString(undefined, MINUTE_OPTIONS);
932
+ return `:${minutes}`;
933
+ };
934
+ const HOURS_FORMATTER = (t, pixelsPerMinute) => new Date(t).toLocaleTimeString(undefined, pixelsPerMinute > 1 ? HOUR_OPTIONS_LONG : HOUR_OPTIONS_SHORT);
935
+ const DATES_FORMATER = (t) => new Date(t).toLocaleDateString(undefined, DATE_OPTIONS);
936
+ const RANGES_FORMATER = [
937
+ () => '',
938
+ () => '',
939
+ MINUTES_FORMATTER,
940
+ MINUTES_FORMATTER,
941
+ MINUTES_FORMATTER,
942
+ MINUTES_FORMATTER,
943
+ HOURS_FORMATTER,
944
+ HOURS_FORMATTER,
945
+ HOURS_FORMATTER,
946
+ HOURS_FORMATTER,
947
+ HOURS_FORMATTER,
948
+ ];
949
+ const TimeCaptions = () => {
950
+ const drawingFunction = useCallback((ctx, { timeScale, timeOrigin, timePixelOffset, getTimePixel, width, height, theme: { background, breakpoints, timeRanges, timeCaptionsPriorities, timeCaptionsStyles, timeGraduationsStyles, dateCaptionsStyle, }, captionSize = 40, swapAxis = false, hideTimeCaptions = false, hideDates = false, showTicks = false, }) => {
951
+ if (hideTimeCaptions)
952
+ return;
953
+ const timeAxisSize = !swapAxis ? width : height;
954
+ const spaceAxisSize = (!swapAxis ? height : width) - captionSize;
955
+ // Add some margin, so that captions of times right outside the stage are still visible:
956
+ const minT = timeOrigin - timeScale * (timePixelOffset + MARGIN);
957
+ const maxT = minT + timeScale * (width + MARGIN * 2);
958
+ // Find which styles to apply, relatively to the timescale (i.e. horizontal zoom level):
959
+ const pixelsPerMinute = (1 / timeScale) * MINUTE;
960
+ let labelLevels = [];
961
+ breakpoints.some((breakpoint, i) => {
962
+ if (pixelsPerMinute < breakpoint) {
963
+ labelLevels = timeCaptionsPriorities[i];
964
+ return true;
794
965
  }
795
- // Detect flat steps, and draw two graduations if any (one on each side of the step):
796
- getSpacePixels(getSpacePixel, point.position).forEach((rawPixel) => {
797
- const spacePixel = getCrispLineCoordinate(rawPixel, ctx.lineWidth);
966
+ return false;
967
+ });
968
+ let labelMarks = computeVisibleTimeMarkers(minT, maxT, timeRanges, labelLevels, (level, i) => ({
969
+ level,
970
+ styles: timeCaptionsStyles[level],
971
+ formatter: RANGES_FORMATER[i],
972
+ }));
973
+ if (!hideDates)
974
+ labelMarks = labelMarks.concat(computeVisibleTimeMarkers(minT, maxT, [24 * HOUR], [1], (level) => ({
975
+ level,
976
+ styles: dateCaptionsStyle,
977
+ formatter: DATES_FORMATER,
978
+ })));
979
+ // Render caption background:
980
+ ctx.fillStyle = background;
981
+ if (!swapAxis) {
982
+ ctx.fillStyle = WHITE_ALPHA_75;
983
+ ctx.fillRect(0, 0, width, 24);
984
+ ctx.fillStyle = background;
985
+ ctx.fillRect(0, spaceAxisSize, timeAxisSize, captionSize);
986
+ }
987
+ else {
988
+ ctx.fillStyle = background;
989
+ ctx.fillRect(0, 0, captionSize, timeAxisSize);
990
+ }
991
+ // Render time captions:
992
+ labelMarks.forEach(({ styles, formatter, time }) => {
993
+ const text = formatter(time, pixelsPerMinute);
994
+ ctx.textAlign = styles.textAlign || 'center';
995
+ ctx.textBaseline = 'top';
996
+ ctx.fillStyle = styles.color;
997
+ ctx.lineWidth = 5;
998
+ ctx.strokeStyle = background;
999
+ ctx.lineCap = 'butt';
1000
+ ctx.font = `${styles.fontWeight || 'normal'} ${styles.font}`;
1001
+ const timePixel = getCrispLineCoordinate(getTimePixel(time), ctx.lineWidth);
1002
+ if (!swapAxis) {
798
1003
  ctx.beginPath();
799
- if (!swapAxis) {
800
- ctx.moveTo(0, spacePixel);
801
- ctx.lineTo(axisSize, spacePixel);
1004
+ ctx.strokeStyle = timeCaptionsStyles[1].color;
1005
+ ctx.lineWidth = 1;
1006
+ let tickHeight = 4;
1007
+ const mod = time % (60 * 60 * 1000);
1008
+ if (mod === 0) {
1009
+ tickHeight = 8;
802
1010
  }
803
- else {
804
- ctx.moveTo(spacePixel, 0);
805
- ctx.lineTo(spacePixel, axisSize);
1011
+ else if (mod % (30 * 60 * 1000) === 0) {
1012
+ tickHeight = 6;
806
1013
  }
1014
+ ctx.moveTo(timePixel, spaceAxisSize);
1015
+ ctx.lineTo(timePixel, spaceAxisSize + tickHeight);
1016
+ ctx.moveTo(timePixel, 0);
1017
+ ctx.lineTo(timePixel, tickHeight);
807
1018
  ctx.stroke();
808
- });
1019
+ ctx.fillStyle = timeCaptionsStyles[1].color;
1020
+ ctx.fillText(text, timePixel, styles.topOffset || 0);
1021
+ ctx.fillText(text, timePixel, spaceAxisSize + (styles.topOffset || 0));
1022
+ }
1023
+ else {
1024
+ ctx.save();
1025
+ ctx.translate(captionSize - (styles.topOffset || 0), timePixel);
1026
+ ctx.rotate(Math.PI / 2);
1027
+ ctx.strokeText(text, 0, 0);
1028
+ ctx.fillText(text, 0, 0);
1029
+ ctx.restore();
1030
+ }
1031
+ });
1032
+ // Render caption top border:
1033
+ ctx.strokeStyle = timeGraduationsStyles[1].color;
1034
+ ctx.lineWidth = timeGraduationsStyles[1].width;
1035
+ if (!showTicks) {
1036
+ ctx.beginPath();
1037
+ if (!swapAxis) {
1038
+ const y = getCrispLineCoordinate(spaceAxisSize, ctx.lineWidth);
1039
+ ctx.moveTo(0, y);
1040
+ ctx.lineTo(timeAxisSize, y);
1041
+ }
1042
+ else {
1043
+ const x = getCrispLineCoordinate(captionSize, ctx.lineWidth);
1044
+ ctx.moveTo(x, 0);
1045
+ ctx.lineTo(x, timeAxisSize);
1046
+ }
1047
+ ctx.stroke();
1048
+ }
1049
+ }, []);
1050
+ useDraw(TimeChartCanvasContext, 'captions', drawingFunction);
1051
+ return null;
1052
+ };
1053
+
1054
+ // There are three different contexts because they have very different lifecycles:
1055
+ // - MouseContext
1056
+ // - SpaceTimeChartContext
1057
+ // - SpaceTimeChartCanvasContext
1058
+ /**
1059
+ * This context exports everything necessary to draw the chart.
1060
+ * It is updated anytime the scales are updated.
1061
+ */
1062
+ const SpaceTimeChartContext = createContext(
1063
+ // That value should never be used, since the context should always be accessed within a provider
1064
+ undefined);
1065
+ const SpaceTimeChartCanvasContext = createContext(
1066
+ // That value should never be used, since the context should always be accessed within a provider
1067
+ undefined);
1068
+ /**
1069
+ * This context exports everything necessary to draw the chart.
1070
+ * It is updated anytime the scales are updated or the mouse moves.
1071
+ */
1072
+ const MouseContext = createContext(
1073
+ // That value should never be used, since the context should always be accessed within a provider
1074
+ undefined);
1075
+
1076
+ const TimeGraduations = () => {
1077
+ const mouseContext = useContext(MouseContext);
1078
+ const mouseX = mouseContext?.position.x;
1079
+ const isHover = mouseContext?.isHover ?? false;
1080
+ const drawingFunction = useCallback((ctx, { timeScale, timeOrigin, timePixelOffset, yPixelOffset, getTimePixel, getTime, swapAxis, width, height, theme: { breakpoints, timeRanges, timeGraduationsStyles, timeGraduationsPriorities }, }) => {
1081
+ const timeAxisSize = !swapAxis ? width : height;
1082
+ const spaceAxisSize = !swapAxis ? height : width;
1083
+ const minT = timeOrigin - timeScale * timePixelOffset;
1084
+ const maxT = minT + timeScale * timeAxisSize;
1085
+ // Find which styles to apply, relatively to the timescale (i.e. horizontal zoom level):
1086
+ const pixelsPerMinute = (1 / timeScale) * MINUTE;
1087
+ let gridlinesLevels = [];
1088
+ breakpoints.some((breakpoint, i) => {
1089
+ if (pixelsPerMinute < breakpoint) {
1090
+ gridlinesLevels = timeGraduationsPriorities[i];
1091
+ return true;
1092
+ }
1093
+ return false;
1094
+ });
1095
+ const gridMarks = computeVisibleTimeMarkers(minT, maxT, timeRanges, gridlinesLevels);
1096
+ // Render grid lines:
1097
+ gridMarks.forEach(({ time, level }) => {
1098
+ const styles = timeGraduationsStyles[level];
1099
+ ctx.strokeStyle = styles.color;
1100
+ ctx.lineWidth = styles.width;
1101
+ ctx.globalAlpha = styles.opacity ?? 1;
1102
+ ctx.setLineDash(styles.dashArray ?? []);
1103
+ if (styles.dashArray) {
1104
+ ctx.lineDashOffset = -yPixelOffset;
1105
+ }
1106
+ const timePixel = getCrispLineCoordinate(getTimePixel(time), ctx.lineWidth);
1107
+ ctx.beginPath();
1108
+ if (!swapAxis) {
1109
+ ctx.moveTo(timePixel, 0);
1110
+ ctx.lineTo(timePixel, spaceAxisSize);
1111
+ }
1112
+ else {
1113
+ ctx.moveTo(0, timePixel);
1114
+ ctx.lineTo(spaceAxisSize, timePixel);
1115
+ }
1116
+ ctx.stroke();
809
1117
  });
1118
+ if (!swapAxis && isHover && mouseX != null && !isNaN(mouseX)) {
1119
+ const crispX = getCrispLineCoordinate(mouseX, 1);
1120
+ const timeValue = getTime(crispX);
1121
+ const timeLabel = new Date(timeValue).toLocaleTimeString();
1122
+ ctx.globalAlpha = 1;
1123
+ // Vertical line:
1124
+ ctx.strokeStyle = BLACK_ALPHA_25;
1125
+ ctx.lineWidth = 1;
1126
+ ctx.setLineDash([]);
1127
+ ctx.beginPath();
1128
+ ctx.moveTo(crispX, 0);
1129
+ ctx.lineTo(crispX, spaceAxisSize);
1130
+ ctx.stroke();
1131
+ // Label
1132
+ const padding = 4;
1133
+ const fontSize = 12;
1134
+ const fontWeight = '400';
1135
+ const fontFamily = 'IBM Plex Sans, sans-regular';
1136
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1137
+ const textWidth = ctx.measureText(timeLabel).width;
1138
+ const labelX = Math.min(Math.max(crispX - textWidth / 2 - padding, 0), width - textWidth - padding * 2);
1139
+ const labelY = spaceAxisSize - 50;
1140
+ // Label background
1141
+ ctx.fillStyle = '#FFFFFF';
1142
+ ctx.fillRect(labelX, labelY - fontSize - 2, textWidth + padding * 2, fontSize + 4);
1143
+ // Text
1144
+ ctx.fillStyle = GREY_50$3;
1145
+ ctx.fillText(timeLabel, labelX + padding, labelY);
1146
+ }
1147
+ // Reset
810
1148
  ctx.setLineDash([]);
811
1149
  ctx.lineDashOffset = 0;
812
1150
  ctx.globalAlpha = 1;
813
- }, []);
814
- useDraw('graduations', drawingFunction);
1151
+ }, [mouseX, isHover]);
1152
+ useDraw(TimeChartCanvasContext, 'graduations', drawingFunction);
815
1153
  return null;
816
1154
  };
817
1155
 
@@ -823,10 +1161,6 @@ const GREY_50$2 = '#797671';
823
1161
  // Fonts:
824
1162
  const FONT_SIZE = 10;
825
1163
  const FONT = 'IBM Plex Sans, sans-serif';
826
- // Here are some helpers to write code about time in ms that is humanly readable:
827
- const SECOND = 1000;
828
- const MINUTE = 60 * SECOND;
829
- const HOUR = 60 * MINUTE;
830
1164
  const DEFAULT_THEME = {
831
1165
  background: 'white',
832
1166
  breakpoints: [0.2, 0.4, 0.7, 2, 6, 20, 60, Infinity],
@@ -953,681 +1287,833 @@ const DEFAULT_THEME = {
953
1287
  },
954
1288
  };
955
1289
 
956
- const MARGIN = 100;
957
- const MINUTES_FORMATTER = (t) => `:${new Date(t).getMinutes().toString().padStart(2, '0')}`;
958
- const HOURS_FORMATTER = (t, pixelsPerMinute) => {
959
- const date = new Date(t);
960
- if (pixelsPerMinute > 1) {
961
- const hours = date.getHours().toString().padStart(2, '0');
962
- const minutes = date.getMinutes().toString().padStart(2, '0');
963
- return `${hours}:${minutes}`;
964
- }
965
- else {
966
- return date.getHours().toString().padStart(2, '0');
1290
+ function validateTheme({ breakpoints, timeRanges, timeCaptionsStyles, timeCaptionsPriorities, timeGraduationsStyles, timeGraduationsPriorities, }) {
1291
+ const PREFIX = 'SpaceTimeChartTheme is invalid:';
1292
+ const breakpointsCount = breakpoints.length;
1293
+ const timeRangesCount = timeRanges.length;
1294
+ const timeCaptionsValues = new Set(timeCaptionsPriorities.flatMap((arr) => arr));
1295
+ const timeGraduationsValues = new Set(timeGraduationsPriorities.flatMap((arr) => arr));
1296
+ // Time captions:
1297
+ if (timeCaptionsPriorities.length !== breakpointsCount)
1298
+ throw new Error(`${PREFIX}: timeCaptionsPriorities should have as much elements as breakpoints.`);
1299
+ if (timeCaptionsPriorities.some((arr) => arr.length !== timeRangesCount))
1300
+ throw new Error(`${PREFIX}: each array in timeCaptionsPriorities should have as much elements as timeRanges.`);
1301
+ if (Array.from(timeCaptionsValues).some((v) => v !== 0 && !timeCaptionsStyles[v]))
1302
+ throw new Error(`${PREFIX}: all values (except 0s) from timeCaptionsPriorities should have a matching style in timeCaptionsStyles.`);
1303
+ // Time graduations:
1304
+ if (timeGraduationsPriorities.length !== breakpointsCount)
1305
+ throw new Error(`${PREFIX}: timeGraduationsPriorities should have as much elements as breakpoints.`);
1306
+ if (timeGraduationsPriorities.some((arr) => arr.length !== timeRangesCount))
1307
+ throw new Error(`${PREFIX}: each array in timeGraduationsPriorities should have as much elements as timeRanges.`);
1308
+ if (Array.from(timeGraduationsValues).some((v) => v !== 0 && !timeGraduationsStyles[v]))
1309
+ throw new Error(`${PREFIX}: all values (except 0s) from timeGraduationsPriorities should have a matching style in timeGraduationsStyles.`);
1310
+ if (!timeGraduationsStyles[1])
1311
+ throw new Error(`${PREFIX}: there should be a timeGraduationsStyles for value 1.`);
1312
+ }
1313
+
1314
+ /**
1315
+ * This context exports everything necessary to draw the chart.
1316
+ * It is updated anytime the scales are updated.
1317
+ */
1318
+ const ChronogramContext = createContext(
1319
+ // That value should never be used, since the context should always be accessed within a provider
1320
+ undefined);
1321
+
1322
+ function formatDuration(start, end) {
1323
+ const totalSeconds = Math.floor((end - start) / 1000);
1324
+ const minutes = Math.floor(totalSeconds / 60);
1325
+ const seconds = totalSeconds % 60;
1326
+ return `${minutes}m${String(seconds).padStart(2, '0')}s`;
1327
+ }
1328
+
1329
+ const BLOCK_HEIGHT = 10;
1330
+ const PADDING_TOP = 18;
1331
+ const STRIPE_SPACING = 24;
1332
+ const STRIPE_WIDTH = 8;
1333
+ const TRACKS_INTERVALS = 3;
1334
+ const CLOSING_TIME_Y_OFFSET = 5;
1335
+ const TRAIN_NAME_Y_OFFSET = 14;
1336
+ const drawTrackLines = (ctx, width, bandTop, bandBottom) => {
1337
+ const lineYs = [
1338
+ bandTop,
1339
+ bandTop + BLOCK_HEIGHT / TRACKS_INTERVALS,
1340
+ bandTop + (2 * BLOCK_HEIGHT) / TRACKS_INTERVALS,
1341
+ bandBottom,
1342
+ ];
1343
+ ctx.strokeStyle = GREY_30$1;
1344
+ ctx.lineWidth = 1;
1345
+ lineYs.forEach((y) => {
1346
+ ctx.beginPath();
1347
+ ctx.moveTo(0, y);
1348
+ ctx.lineTo(width, y);
1349
+ ctx.stroke();
1350
+ });
1351
+ };
1352
+ const drawStripedBlock = (ctx, x, y, width) => {
1353
+ ctx.save();
1354
+ ctx.beginPath();
1355
+ ctx.rect(x, y, width, BLOCK_HEIGHT);
1356
+ ctx.clip();
1357
+ ctx.fillStyle = WHITE_100$3;
1358
+ ctx.fillRect(x, y, width, BLOCK_HEIGHT);
1359
+ ctx.strokeStyle = RED_100;
1360
+ ctx.lineWidth = STRIPE_WIDTH;
1361
+ for (let offset = STRIPE_WIDTH / 2; offset < width + BLOCK_HEIGHT; offset += STRIPE_SPACING) {
1362
+ ctx.beginPath();
1363
+ ctx.moveTo(x + offset, y + BLOCK_HEIGHT + 2);
1364
+ ctx.lineTo(x + offset + BLOCK_HEIGHT, y - 2);
1365
+ ctx.stroke();
967
1366
  }
1367
+ ctx.restore();
1368
+ ctx.strokeStyle = GREY_90;
1369
+ ctx.lineWidth = 1;
1370
+ ctx.strokeRect(x, y, width, BLOCK_HEIGHT);
968
1371
  };
969
- const DATES_FORMATER = (t) => {
970
- const date = new Date(t);
971
- return [
972
- date.getDate().toString().padStart(2, '0'),
973
- (date.getMonth() + 1).toString().padStart(2, '0'),
974
- date.getFullYear().toString(),
975
- ].join('/');
1372
+ /** Draws a black block to indicate insufficient time between two occupancy blocks */
1373
+ const drawGapBlock = (ctx, bandTop, gapStartX, gapEndX) => {
1374
+ const gapWidth = gapEndX - gapStartX;
1375
+ if (gapWidth > 0) {
1376
+ ctx.fillStyle = BLACK_100;
1377
+ ctx.fillRect(gapStartX - 0.5, bandTop - 0.5, gapWidth + 1, BLOCK_HEIGHT + 1);
1378
+ }
976
1379
  };
977
- const RANGES_FORMATER = [
978
- () => '',
979
- () => '',
980
- MINUTES_FORMATTER,
981
- MINUTES_FORMATTER,
982
- MINUTES_FORMATTER,
983
- MINUTES_FORMATTER,
984
- HOURS_FORMATTER,
985
- HOURS_FORMATTER,
986
- HOURS_FORMATTER,
987
- HOURS_FORMATTER,
988
- HOURS_FORMATTER,
989
- ];
990
- const TimeCaptions = () => {
991
- const drawingFunction = useCallback((ctx, { timeScale, timeOrigin, timePixelOffset, getTimePixel, swapAxis, width, height, theme: { background, breakpoints, timeRanges, timeCaptionsPriorities, timeCaptionsStyles, timeGraduationsStyles, dateCaptionsStyle, }, captionSize, hideTimeCaptions, hideDates, showTicks, }) => {
992
- if (hideTimeCaptions)
993
- return;
994
- const timeAxisSize = !swapAxis ? width : height;
995
- const spaceAxisSize = (!swapAxis ? height : width) - captionSize;
996
- // Add some margin, so that captions of times right outside the stage are still visible:
997
- const minT = timeOrigin - timeScale * (timePixelOffset + MARGIN);
998
- const maxT = minT + timeScale * (width + MARGIN * 2);
999
- // Find which styles to apply, relatively to the timescale (i.e. horizontal zoom level):
1000
- const pixelsPerMinute = (1 / timeScale) * MINUTE;
1001
- let labelLevels = [];
1002
- breakpoints.some((breakpoint, i) => {
1003
- if (pixelsPerMinute < breakpoint) {
1004
- labelLevels = timeCaptionsPriorities[i];
1005
- return true;
1006
- }
1007
- return false;
1008
- });
1009
- let labelMarks = computeVisibleTimeMarkers(minT, maxT, timeRanges, labelLevels, (level, i) => ({
1010
- level,
1011
- styles: timeCaptionsStyles[level],
1012
- formatter: RANGES_FORMATER[i],
1013
- }));
1014
- if (!hideDates)
1015
- labelMarks = labelMarks.concat(computeVisibleTimeMarkers(minT, maxT, [24 * HOUR], [1], (level) => ({
1016
- level,
1017
- styles: dateCaptionsStyle,
1018
- formatter: DATES_FORMATER,
1019
- })));
1020
- // Render caption background:
1021
- ctx.fillStyle = background;
1022
- if (!swapAxis) {
1023
- ctx.fillStyle = WHITE_ALPHA_75;
1024
- ctx.fillRect(0, 0, width, 24);
1025
- ctx.fillStyle = background;
1026
- ctx.fillRect(0, spaceAxisSize, timeAxisSize, captionSize);
1027
- }
1028
- else {
1029
- ctx.fillStyle = background;
1030
- ctx.fillRect(0, 0, captionSize, timeAxisSize);
1380
+ /** Draws text around an occupancy block */
1381
+ const drawBlockText = ({ ctx, x, y, text, color, maxWidth, }) => {
1382
+ ctx.save();
1383
+ ctx.font = '12px IBM Plex Sans';
1384
+ if (color)
1385
+ ctx.fillStyle = color;
1386
+ ctx.textAlign = 'center';
1387
+ ctx.fillText(text, x, y, maxWidth);
1388
+ ctx.restore();
1389
+ };
1390
+ const drawBlocks = ({ ctx, blocks, getTimePixel, bandTop, bandBottom, }) => {
1391
+ let previousBlockEndX;
1392
+ for (const block of blocks) {
1393
+ const blockStartX = getTimePixel(block.startTime);
1394
+ const blockEndX = getTimePixel(block.endTime);
1395
+ const blockWidth = blockEndX - blockStartX;
1396
+ const blockCenterX = blockStartX + blockWidth / 2;
1397
+ if (blockWidth <= 0)
1398
+ continue;
1399
+ if (previousBlockEndX !== undefined) {
1400
+ drawGapBlock(ctx, bandTop, previousBlockEndX, blockStartX);
1031
1401
  }
1032
- // Render time captions:
1033
- labelMarks.forEach(({ styles, formatter, time }) => {
1034
- const text = formatter(time, pixelsPerMinute);
1035
- ctx.textAlign = styles.textAlign || 'center';
1036
- ctx.textBaseline = 'top';
1037
- ctx.fillStyle = styles.color;
1038
- ctx.lineWidth = 5;
1039
- ctx.strokeStyle = background;
1040
- ctx.lineCap = 'butt';
1041
- ctx.font = `${styles.fontWeight || 'normal'} ${styles.font}`;
1042
- const timePixel = getCrispLineCoordinate(getTimePixel(time), ctx.lineWidth);
1043
- if (!swapAxis) {
1044
- ctx.beginPath();
1045
- ctx.strokeStyle = timeCaptionsStyles[1].color;
1046
- ctx.lineWidth = 1;
1047
- let tickHeight = 4;
1048
- const mod = time % (60 * 60 * 1000);
1049
- if (mod === 0) {
1050
- tickHeight = 8;
1051
- }
1052
- else if (mod % (30 * 60 * 1000) === 0) {
1053
- tickHeight = 6;
1054
- }
1055
- ctx.moveTo(timePixel, spaceAxisSize);
1056
- ctx.lineTo(timePixel, spaceAxisSize + tickHeight);
1057
- ctx.moveTo(timePixel, 0);
1058
- ctx.lineTo(timePixel, tickHeight);
1059
- ctx.stroke();
1060
- ctx.fillStyle = timeCaptionsStyles[1].color;
1061
- ctx.fillText(text, timePixel, styles.topOffset || 0);
1062
- ctx.fillText(text, timePixel, spaceAxisSize + (styles.topOffset || 0));
1063
- }
1064
- else {
1065
- ctx.save();
1066
- ctx.translate(captionSize - (styles.topOffset || 0), timePixel);
1067
- ctx.rotate(Math.PI / 2);
1068
- ctx.strokeText(text, 0, 0);
1069
- ctx.fillText(text, 0, 0);
1070
- ctx.restore();
1071
- }
1402
+ drawBlockText({
1403
+ ctx,
1404
+ x: blockCenterX,
1405
+ y: bandTop - CLOSING_TIME_Y_OFFSET,
1406
+ text: formatDuration(block.startTime, block.endTime),
1407
+ maxWidth: blockWidth,
1072
1408
  });
1073
- // Render caption top border:
1074
- ctx.strokeStyle = timeGraduationsStyles[1].color;
1075
- ctx.lineWidth = timeGraduationsStyles[1].width;
1076
- if (!showTicks) {
1077
- ctx.beginPath();
1078
- if (!swapAxis) {
1079
- const y = getCrispLineCoordinate(spaceAxisSize, ctx.lineWidth);
1080
- ctx.moveTo(0, y);
1081
- ctx.lineTo(timeAxisSize, y);
1082
- }
1083
- else {
1084
- const x = getCrispLineCoordinate(captionSize, ctx.lineWidth);
1085
- ctx.moveTo(x, 0);
1086
- ctx.lineTo(x, timeAxisSize);
1409
+ drawStripedBlock(ctx, blockStartX, bandTop, blockWidth);
1410
+ drawBlockText({
1411
+ ctx,
1412
+ x: blockCenterX,
1413
+ y: bandBottom + TRAIN_NAME_Y_OFFSET,
1414
+ text: block.trainNames.join('; '),
1415
+ color: GREY_50$3,
1416
+ });
1417
+ previousBlockEndX = blockEndX;
1418
+ }
1419
+ };
1420
+ const OccupancyBlocksLayer = () => {
1421
+ const { levelCrossingsOccupancies, yPixelOffset } = useContext(ChronogramContext);
1422
+ const drawOccupancyBlocksLayer = useCallback((ctx, { getTimePixel }) => {
1423
+ const { width } = ctx.canvas.getBoundingClientRect();
1424
+ let startY = PADDING_TOP + CHRONOGRAM_HEADER_HEIGHT - yPixelOffset;
1425
+ for (const levelCrossing of levelCrossingsOccupancies) {
1426
+ const bandTop = startY;
1427
+ const bandBottom = startY + BLOCK_HEIGHT;
1428
+ drawTrackLines(ctx, width, bandTop, bandBottom);
1429
+ for (const blocks of levelCrossing) {
1430
+ if (!blocks.length)
1431
+ continue;
1432
+ drawBlocks({ ctx, blocks, getTimePixel, bandTop, bandBottom });
1087
1433
  }
1088
- ctx.stroke();
1434
+ startY += LEVEL_CROSSING_ITEM_HEIGHT;
1089
1435
  }
1090
- }, []);
1091
- useDraw('captions', drawingFunction);
1436
+ }, [levelCrossingsOccupancies, yPixelOffset]);
1437
+ useDraw(TimeChartCanvasContext, 'overlay', drawOccupancyBlocksLayer);
1092
1438
  return null;
1093
1439
  };
1094
1440
 
1095
- const TimeGraduations = () => {
1096
- const { position, isHover } = useContext(MouseContext);
1097
- const mouseX = position.x;
1098
- const drawingFunction = useCallback((ctx, { timeScale, timeOrigin, timePixelOffset, spacePixelOffset, getTimePixel, getTime, swapAxis, width, height, theme: { breakpoints, timeRanges, timeGraduationsStyles, timeGraduationsPriorities }, }) => {
1099
- const timeAxisSize = !swapAxis ? width : height;
1100
- const spaceAxisSize = !swapAxis ? height : width;
1101
- const minT = timeOrigin - timeScale * timePixelOffset;
1102
- const maxT = minT + timeScale * timeAxisSize;
1103
- // Find which styles to apply, relatively to the timescale (i.e. horizontal zoom level):
1104
- const pixelsPerMinute = (1 / timeScale) * MINUTE;
1105
- let gridlinesLevels = [];
1106
- breakpoints.some((breakpoint, i) => {
1107
- if (pixelsPerMinute < breakpoint) {
1108
- gridlinesLevels = timeGraduationsPriorities[i];
1109
- return true;
1110
- }
1111
- return false;
1112
- });
1113
- const gridMarks = computeVisibleTimeMarkers(minT, maxT, timeRanges, gridlinesLevels);
1114
- // Render grid lines:
1115
- gridMarks.forEach(({ time, level }) => {
1116
- const styles = timeGraduationsStyles[level];
1117
- ctx.strokeStyle = styles.color;
1118
- ctx.lineWidth = styles.width;
1119
- ctx.globalAlpha = styles.opacity ?? 1;
1120
- ctx.setLineDash(styles.dashArray ?? []);
1121
- if (styles.dashArray) {
1122
- ctx.lineDashOffset = -spacePixelOffset;
1123
- }
1124
- const timePixel = getCrispLineCoordinate(getTimePixel(time), ctx.lineWidth);
1125
- ctx.beginPath();
1126
- if (!swapAxis) {
1127
- ctx.moveTo(timePixel, 0);
1128
- ctx.lineTo(timePixel, spaceAxisSize);
1129
- }
1130
- else {
1131
- ctx.moveTo(0, timePixel);
1132
- ctx.lineTo(spaceAxisSize, timePixel);
1133
- }
1134
- ctx.stroke();
1441
+ const ChronogramCanvas = (props) => {
1442
+ const { levelCrossingsOccupancies, timeOrigin, timeScale, xOffset = 0, yOffset = 0, theme, onPan, onZoom, onClick, // TODO: the 3 last handlers are custom and need to be extracted but are not used for now
1443
+ onHoveredChildUpdate, onMouseMove, ...attr } = props;
1444
+ // TODO: remove this console.info once interactions are implemented and handlers are used
1445
+ console.info(onClick, onMouseMove, onHoveredChildUpdate);
1446
+ const [root, setRoot] = useState(null);
1447
+ const [canvasesRoot, setCanvasesRoot] = useState(null);
1448
+ const fullTheme = useMemo(() => ({ ...DEFAULT_THEME, ...theme }), [theme]);
1449
+ const { width, height } = useSize(root);
1450
+ const fingerprint = useMemo(() => JSON.stringify({
1451
+ levelCrossingsOccupancies,
1452
+ width,
1453
+ height,
1454
+ timeOrigin,
1455
+ timeScale,
1456
+ xOffset,
1457
+ yOffset,
1458
+ }), [levelCrossingsOccupancies, width, height, timeOrigin, timeScale, xOffset, yOffset]);
1459
+ const pickingState = useMemo(() => {
1460
+ const pickingElements = [];
1461
+ const resetPickingElements = () => {
1462
+ pickingElements.length = 0;
1463
+ };
1464
+ const registerPickingElement = (element) => {
1465
+ pickingElements.push(element);
1466
+ return pickingElements.length - 1;
1467
+ };
1468
+ return {
1469
+ pickingElements,
1470
+ resetPickingElements,
1471
+ registerPickingElement,
1472
+ };
1473
+ }, []);
1474
+ const contextState = useMemo(() => {
1475
+ const getTimePixel = getTimeToPixel(timeOrigin, xOffset, timeScale);
1476
+ const getTime = getPixelToTime(timeOrigin, xOffset, timeScale);
1477
+ // TODO: Check and fix those functions once we introduce mouse interactions
1478
+ const getData = (point) => ({ time: point.x, position: point.y });
1479
+ const getPoint = ({ time, position }) => ({
1480
+ x: getTimePixel(time),
1481
+ y: position,
1135
1482
  });
1136
- if (!swapAxis && isHover && mouseX != null && !isNaN(mouseX)) {
1137
- const crispX = getCrispLineCoordinate(mouseX, 1);
1138
- const timeValue = getTime(crispX);
1139
- const timeLabel = new Date(timeValue).toLocaleTimeString();
1140
- ctx.globalAlpha = 1;
1141
- // Vertical line:
1142
- ctx.strokeStyle = BLACK_ALPHA_25;
1143
- ctx.lineWidth = 1;
1144
- ctx.setLineDash([]);
1145
- ctx.beginPath();
1146
- ctx.moveTo(crispX, 0);
1147
- ctx.lineTo(crispX, spaceAxisSize);
1148
- ctx.stroke();
1149
- // Label
1150
- const padding = 4;
1151
- const fontSize = 12;
1152
- const fontWeight = '400';
1153
- const fontFamily = 'IBM Plex Sans, sans-regular';
1154
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1155
- const textWidth = ctx.measureText(timeLabel).width;
1156
- const labelX = Math.min(Math.max(crispX - textWidth / 2 - padding, 0), width - textWidth - padding * 2);
1157
- const labelY = spaceAxisSize - 50;
1158
- // Label background
1159
- ctx.fillStyle = '#FFFFFF';
1160
- ctx.fillRect(labelX, labelY - fontSize - 2, textWidth + padding * 2, fontSize + 4);
1161
- // Text
1162
- ctx.fillStyle = GREY_50$3;
1163
- ctx.fillText(timeLabel, labelX + padding, labelY);
1164
- }
1165
- // Reset
1166
- ctx.setLineDash([]);
1167
- ctx.lineDashOffset = 0;
1168
- ctx.globalAlpha = 1;
1169
- }, [mouseX, isHover]);
1170
- useDraw('graduations', drawingFunction);
1171
- return null;
1483
+ return {
1484
+ ...pickingState,
1485
+ fingerprint,
1486
+ width,
1487
+ height,
1488
+ getTimePixel,
1489
+ getTime,
1490
+ getData,
1491
+ getPoint,
1492
+ levelCrossingsOccupancies,
1493
+ timeOrigin,
1494
+ timeScale,
1495
+ timePixelOffset: xOffset,
1496
+ yPixelOffset: yOffset,
1497
+ theme: fullTheme,
1498
+ captionSize: fullTheme.dateCaptionsSize + fullTheme.timeCaptionsSize,
1499
+ };
1500
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1501
+ }, [fingerprint, pickingState, fullTheme]);
1502
+ const mouseState = useMouseTracking(root);
1503
+ const { position, down, isHover } = mouseState;
1504
+ const { canvasContext } = useCanvas$1(canvasesRoot, contextState, position);
1505
+ const mouseContext = useMemo(() => ({
1506
+ down,
1507
+ isHover,
1508
+ position: mouseState.position,
1509
+ hoveredItem: null,
1510
+ data: contextState.getData(mouseState.position),
1511
+ }), [mouseState.position, down, isHover, contextState]);
1512
+ // Handle interactions:
1513
+ useMouseInteractions(root, mouseContext, { onPan, onZoom }, contextState);
1514
+ // Check theme validity:
1515
+ useEffect(() => {
1516
+ validateTheme(fullTheme);
1517
+ }, [fullTheme]);
1518
+ return (React.createElement("div", { ...attr, ref: setRoot, className: cx('relative h-full', attr.className), style: { background: fullTheme.background } },
1519
+ React.createElement("div", { ref: setCanvasesRoot, className: "absolute inset-0" },
1520
+ React.createElement(ChronogramContext.Provider, { value: contextState },
1521
+ React.createElement(TimeChartCanvasContext.Provider, { value: canvasContext },
1522
+ React.createElement(MouseContext.Provider, { value: mouseContext },
1523
+ React.createElement(TimeGraduations, null),
1524
+ React.createElement(TimeCaptions, null),
1525
+ React.createElement(OccupancyBlocksLayer, null)))))));
1526
+ };
1527
+
1528
+ const ChronogramManchette = ({ levelCrossingsNames, height, width = 262, onDelete, }) => (React.createElement("div", { className: "chronogram-manchette", style: {
1529
+ height: `${height}px`,
1530
+ width: `${width}px`,
1531
+ } },
1532
+ React.createElement("div", { className: "chronogram-manchette-header" },
1533
+ React.createElement(Note, { iconColor: GREY_30$1 })),
1534
+ React.createElement("div", { className: "chronogram-manchette-list" }, levelCrossingsNames.map((lcName, index) => (React.createElement("div", { key: index, className: "level-crossing flex justify-between" },
1535
+ React.createElement("div", { className: "flex items-center" }, lcName),
1536
+ React.createElement("button", { className: "cursor-pointer", onClick: () => onDelete(lcName) },
1537
+ React.createElement(XCircle, { className: "x-circle" })))))),
1538
+ React.createElement("div", { className: "chronogram-manchette-footer" })));
1539
+
1540
+ const Chronogram = ({ levelCrossingData, timeOrigin, height = INITIAL_CHRONOGRAM_HEIGHT, }) => {
1541
+ const chronogramManchetteRef = useRef(null);
1542
+ const chronogramChartRef = useRef(null);
1543
+ const [levelCrossingsOccupancies, setLevelCrossingsOccupancies] = useState(levelCrossingData);
1544
+ const { height: chronogramHeight, handleVerticalScroll, handleXZoom, handleXZoomOnWheelEvent, onPan, xOffset, xZoom, yOffset, } = useChronogram({
1545
+ itemCount: levelCrossingsOccupancies.length,
1546
+ chronogramManchetteRef,
1547
+ chronogramChartRef,
1548
+ chronogramHeight: height,
1549
+ });
1550
+ function handleDeleteLevelCrossing(name) {
1551
+ setLevelCrossingsOccupancies((previousLevelCrossingsOccupancies) => previousLevelCrossingsOccupancies.filter((lc) => lc.name !== name));
1552
+ }
1553
+ useEffect(() => {
1554
+ // TODO: fix this lint
1555
+ /* eslint-disable-next-line react-hooks/set-state-in-effect */
1556
+ setLevelCrossingsOccupancies(levelCrossingData);
1557
+ }, [levelCrossingData]);
1558
+ return (React.createElement("div", { className: "ui-chronogram", style: { height } },
1559
+ React.createElement("div", { ref: chronogramManchetteRef, className: "chronogram-manchette-container flex", onScroll: handleVerticalScroll },
1560
+ React.createElement(ChronogramManchette, { onDelete: handleDeleteLevelCrossing, levelCrossingsNames: levelCrossingsOccupancies.map((lc) => lc.name), height: chronogramHeight }),
1561
+ React.createElement("div", { ref: chronogramChartRef, className: "chronogram-container" },
1562
+ React.createElement(ChronogramCanvas, { timeOrigin: timeOrigin, timeScale: zoomValueToTimeScale(xZoom), xOffset: xOffset, yOffset: yOffset, levelCrossingsOccupancies: levelCrossingsOccupancies.map((lc) => lc.occupancies), onPan: onPan, onZoom: ({ delta, position, event }) => {
1563
+ handleXZoomOnWheelEvent(event, xZoom + delta, position.x);
1564
+ } }))),
1565
+ React.createElement(Slider, { containerClassName: "chronogram-slider-container", className: "chronogram-slider", width: CHRONOGRAM_SLIDER_WIDTH, value: xZoom, onChange: (e) => {
1566
+ handleXZoom(Number(e.target.value));
1567
+ } })));
1172
1568
  };
1173
1569
 
1570
+ /* eslint-disable @typescript-eslint/no-use-before-define */
1174
1571
  /**
1175
- * This function takes a MouseEvent and an HTMLElement, and returns the position of the mouse,
1176
- * relatively to the DOM element. This allows for instance dragging an element that is on the given
1177
- * DOM element while the events are bound to the document or the body.
1572
+ * This function helps to index a sequence of consecutive scales into a binary tree, to make it
1573
+ * faster to find which scale contains any given position.
1574
+ *
1575
+ * The optional `skipSiblingReferences` option allows getting a serializable tree, for testing
1576
+ * purpose.
1178
1577
  */
1179
- function getEventPosition(e, dom) {
1180
- const bbox = dom.getBoundingClientRect();
1181
- return {
1182
- x: e.clientX - bbox.left,
1183
- y: e.clientY - bbox.top,
1184
- };
1578
+ function spaceScalesToBinaryTree(spaceOrigin, spaceScales, skipSiblingReferences) {
1579
+ let prev = spaceOrigin;
1580
+ // Step 1: Validate the scales
1581
+ if (spaceScales.some((scale) => {
1582
+ if (scale.to < prev)
1583
+ return true;
1584
+ prev = scale.to;
1585
+ return false;
1586
+ })) {
1587
+ throw new Error("Invalid scale: 'to' must be greater than previous 'to'.");
1588
+ }
1589
+ if (spaceScales.some((scale) => ('size' in scale ? scale.size : scale.coefficient) <= 0)) {
1590
+ throw new Error("Invalid scale: 'to' must be greater than 'from'.");
1591
+ }
1592
+ // Step 2: Normalize the scales
1593
+ const normalizedScales = [];
1594
+ let offset = 0;
1595
+ prev = spaceOrigin;
1596
+ for (let i = 0; i < spaceScales.length; i++) {
1597
+ const scale = spaceScales[i];
1598
+ const coefficient = 'coefficient' in scale ? scale.coefficient : (scale.to - prev) / scale.size;
1599
+ const size = 'coefficient' in scale ? (scale.to - prev) / scale.coefficient : scale.size;
1600
+ normalizedScales.push({
1601
+ from: prev,
1602
+ to: scale.to,
1603
+ pixelFrom: offset,
1604
+ pixelTo: offset + size,
1605
+ coefficient,
1606
+ });
1607
+ offset += size;
1608
+ prev = scale.to;
1609
+ if (i) {
1610
+ normalizedScales[i].previous = normalizedScales[i - 1];
1611
+ normalizedScales[i - 1].next = normalizedScales[i];
1612
+ }
1613
+ }
1614
+ // Step 3: Build the tree
1615
+ function buildTree(scales) {
1616
+ if (scales.length === 0) {
1617
+ return {
1618
+ coefficient: 1,
1619
+ from: -Infinity,
1620
+ to: Infinity,
1621
+ pixelFrom: -Infinity,
1622
+ pixelTo: Infinity,
1623
+ };
1624
+ }
1625
+ else if (scales.length === 1) {
1626
+ return scales[0];
1627
+ }
1628
+ else {
1629
+ const size = Math.ceil(scales.length / 2);
1630
+ const limit = scales[size - 1].to;
1631
+ const pixelLimit = scales[size - 1].pixelTo;
1632
+ return {
1633
+ limit,
1634
+ pixelLimit,
1635
+ from: scales[0].from,
1636
+ to: scales[scales.length - 1].to,
1637
+ pixelFrom: scales[0].pixelFrom,
1638
+ pixelTo: scales[scales.length - 1].pixelTo,
1639
+ left: buildTree(scales.slice(0, size)),
1640
+ right: buildTree(scales.slice(size)),
1641
+ };
1642
+ }
1643
+ }
1644
+ return buildTree(normalizedScales);
1185
1645
  }
1186
1646
  /**
1187
- * This function returns a delta value for a given WheelEvent. It can be very useful, since the
1188
- * given `deltaY` and `detail` attributes are not normalized.
1647
+ * This function takes a sequence of SpaceScales, identifies the flat steps (i.e. the scales that do
1648
+ * not increase the position), and returns them in a set.
1189
1649
  */
1190
- function getEventWheelDelta(e) {
1191
- if (typeof e.deltaY !== 'undefined')
1192
- return (e.deltaY * -3) / 360;
1193
- if (typeof e.detail !== 'undefined')
1194
- return e.detail / -9;
1195
- throw new Error('Could not extract delta from event.');
1650
+ function getFlatSteps(spaceScales) {
1651
+ const flatSteps = [];
1652
+ for (let i = 1; i < spaceScales.length; i++) {
1653
+ const { to: previous } = spaceScales[i - 1];
1654
+ const { to: current } = spaceScales[i];
1655
+ if (previous === current)
1656
+ flatSteps.push(current);
1657
+ }
1658
+ return new Set(flatSteps);
1196
1659
  }
1197
-
1198
1660
  /**
1199
- * This hook handles SpaceTimeChart mouse interactions.
1200
- * It is an internal hook, and should only be used inside SpaceTimeChart.
1661
+ * This function takes a NormalizedScaleTree and a position, and returns the leaf node from the
1662
+ * tree that contains that position.
1663
+ *
1664
+ * Also, if the position is lower than the tree's min (tree.from), then the first leaf is returned
1665
+ * and if it is higher than the max (tree.to), the last leaf is returned.
1666
+ *
1667
+ * Finally, if pickLast is truthy, then it returns the last leaf node that contains that position
1668
+ * instead of the first one. It is very important when there are flat sections.
1201
1669
  */
1202
- function useMouseInteractions(dom, { position, hoveredItem, down, isHover }, handlers, context) {
1203
- const contextRef = useRef(context);
1204
- const handlersRef = useRef(handlers);
1205
- const [panningState, setPanningState] = useState({ type: 'idle' });
1206
- // Cache latest context in ref:
1207
- useEffect(() => {
1208
- contextRef.current = context;
1209
- // eslint-disable-next-line react-hooks/exhaustive-deps
1210
- }, [context.fingerprint]);
1211
- useEffect(() => {
1212
- handlersRef.current = handlers;
1213
- }, [handlers]);
1214
- // Generate event handlers:
1215
- const clickHandler = useCallback((event) => {
1216
- if (!dom)
1217
- return;
1218
- const { onClick } = handlersRef.current;
1219
- if (onClick) {
1220
- onClick({
1221
- event,
1222
- position,
1223
- data: contextRef.current.getData(position),
1224
- hoveredItem,
1225
- context: contextRef.current,
1226
- });
1227
- }
1228
- }, [dom, hoveredItem, position]);
1229
- const wheelHandler = useCallback((event) => {
1230
- const { onZoom } = handlersRef.current;
1231
- if (onZoom && dom)
1232
- onZoom({
1233
- delta: getEventWheelDelta(event),
1234
- position: getEventPosition(event, dom),
1235
- event,
1236
- context: contextRef.current,
1237
- });
1238
- }, [dom]);
1239
- // Bind event handlers:
1240
- useEffect(() => {
1241
- if (!dom)
1242
- return;
1243
- dom.addEventListener('click', clickHandler);
1244
- return () => {
1245
- dom.removeEventListener('click', clickHandler);
1246
- };
1247
- }, [dom, clickHandler]);
1248
- useEffect(() => {
1249
- if (!dom)
1250
- return;
1251
- dom.addEventListener('wheel', wheelHandler);
1252
- return () => {
1253
- dom.removeEventListener('wheel', wheelHandler);
1254
- };
1255
- }, [dom, wheelHandler]);
1256
- // Listen to "up" and "down" updates:
1257
- useEffect(() => {
1258
- const { onPan } = handlersRef.current;
1259
- if (down) {
1260
- // Start panning:
1261
- setPanningState({
1262
- type: 'panning',
1263
- initialPosition: position,
1264
- initialData: contextRef.current.getData(position),
1265
- });
1670
+ function getNormalizedScaleAtPosition(position, tree, pickLast) {
1671
+ position = clamp$1(position, tree.from, tree.to);
1672
+ let node = tree;
1673
+ while ('limit' in node) {
1674
+ if (!pickLast) {
1675
+ if (position <= node.limit)
1676
+ node = node.left;
1677
+ else
1678
+ node = node.right;
1266
1679
  }
1267
1680
  else {
1268
- // Stop panning:
1269
- if (panningState.type === 'panning' && onPan)
1270
- onPan({
1271
- isPanning: false,
1272
- position,
1273
- initialPosition: panningState.initialPosition,
1274
- data: contextRef.current.getData(position),
1275
- initialData: panningState.initialData,
1276
- context: contextRef.current,
1277
- });
1278
- if (panningState.type !== 'idle')
1279
- setPanningState({ type: 'idle' });
1280
- }
1281
- // eslint-disable-next-line react-hooks/exhaustive-deps
1282
- }, [down]);
1283
- // Listen to "move" updates:
1284
- useEffect(() => {
1285
- const { onPan, onMouseMove } = handlersRef.current;
1286
- if (onMouseMove) {
1287
- onMouseMove({
1288
- position,
1289
- isHover,
1290
- data: contextRef.current.getData(position),
1291
- hoveredItem,
1292
- context: contextRef.current,
1293
- });
1681
+ if (position >= node.limit)
1682
+ node = node.right;
1683
+ else
1684
+ node = node.left;
1294
1685
  }
1295
- if (panningState.type === 'panning' && onPan)
1296
- onPan({
1297
- isPanning: true,
1298
- position,
1299
- initialPosition: panningState.initialPosition,
1300
- data: contextRef.current.getData(position),
1301
- initialData: panningState.initialData,
1302
- context: contextRef.current,
1303
- });
1304
- // eslint-disable-next-line react-hooks/exhaustive-deps
1305
- }, [position.x, position.y]);
1686
+ }
1687
+ return node;
1306
1688
  }
1307
-
1308
1689
  /**
1309
- * This hook handles SpaceTimeChart mouse tracking.
1310
- * It is an internal hook, and should only be used inside SpaceTimeChart.
1690
+ * This function takes a NormalizedScaleTree and a pixel position, and returns the leaf node from
1691
+ * the tree that contains that pixel.
1692
+ *
1693
+ * Also, if the position is lower than the tree's min pixel (tree.pixelFrom), then the first leaf
1694
+ * is returned and if it is higher than the max pixel (tree.pixelTo), the last leaf is returned.
1311
1695
  */
1312
- function useMouseTracking(dom) {
1313
- const [mouseState, setMouseState] = useState({
1314
- isHover: false,
1315
- position: { x: NaN, y: NaN },
1316
- });
1317
- // Generate event handlers:
1318
- const downHandler = useCallback((e) => {
1319
- if (!dom)
1320
- return;
1321
- setMouseState((state) => ({
1322
- ...state,
1323
- down: { ctrl: e.ctrlKey, shift: e.shiftKey },
1324
- }));
1325
- }, [dom]);
1326
- const upHandler = useCallback(() => {
1327
- if (!dom)
1328
- return;
1329
- setMouseState((state) => ({ ...state, down: undefined }));
1330
- }, [dom]);
1331
- const moveHandler = useCallback((event) => {
1332
- if (!dom)
1333
- return;
1334
- const position = getEventPosition(event, dom);
1335
- const { x, y } = position;
1336
- const width = dom.offsetWidth;
1337
- const height = dom.offsetHeight;
1338
- const isHover = x >= 0 && x <= width && y >= 0 && y <= height;
1339
- setMouseState((state) => ({
1340
- ...state,
1341
- position,
1342
- isHover,
1343
- }));
1344
- }, [dom]);
1345
- // Bind event handlers:
1346
- useEffect(() => {
1347
- if (!dom)
1348
- return;
1349
- dom.addEventListener('mousedown', downHandler);
1350
- return () => {
1351
- dom.removeEventListener('mousedown', downHandler);
1352
- };
1353
- }, [dom, downHandler]);
1354
- useEffect(() => {
1355
- document.addEventListener('mouseup', upHandler);
1356
- return () => {
1357
- document.removeEventListener('mouseup', upHandler);
1358
- };
1359
- }, [upHandler]);
1360
- useEffect(() => {
1361
- document.addEventListener('mousemove', moveHandler);
1362
- return () => {
1363
- document.removeEventListener('mousemove', moveHandler);
1364
- };
1365
- }, [moveHandler]);
1366
- return mouseState;
1696
+ function getNormalizedScaleAtPixel(y, tree) {
1697
+ y = clamp$1(y, tree.pixelFrom, tree.pixelTo);
1698
+ let node = tree;
1699
+ while ('pixelLimit' in node) {
1700
+ if (y <= node.pixelLimit)
1701
+ node = node.left;
1702
+ else
1703
+ node = node.right;
1704
+ }
1705
+ return node;
1706
+ }
1707
+ function getSpaceToPixel(pixelOffset, binaryTree) {
1708
+ return (position, fromEnd) => {
1709
+ const { from, pixelFrom, pixelTo, coefficient } = getNormalizedScaleAtPosition(position, binaryTree, fromEnd);
1710
+ // Rare case where coefficient is 0:
1711
+ // (occurs when there is just a flat step, for instance)
1712
+ if (coefficient === 0)
1713
+ return pixelOffset + (fromEnd ? pixelTo : pixelFrom);
1714
+ // Normal case: We simply interpolate
1715
+ return pixelOffset + pixelFrom + (position - from) / coefficient;
1716
+ };
1717
+ }
1718
+ function getPixelToSpace(pixelOffset, binaryTree) {
1719
+ return (spacePixel) => {
1720
+ const { from, pixelFrom, coefficient } = getNormalizedScaleAtPixel(spacePixel - pixelOffset, binaryTree);
1721
+ return from + (spacePixel - pixelOffset - pixelFrom) * coefficient;
1722
+ };
1723
+ }
1724
+ function getPointToData(getTime, getSpace, timeAxis, spaceAxis) {
1725
+ return (point) => ({
1726
+ time: getTime(point[timeAxis]),
1727
+ position: getSpace(point[spaceAxis]),
1728
+ });
1367
1729
  }
1368
-
1369
- function validateTheme({ breakpoints, timeRanges, timeCaptionsStyles, timeCaptionsPriorities, timeGraduationsStyles, timeGraduationsPriorities, }) {
1370
- const PREFIX = 'SpaceTimeChartTheme is invalid:';
1371
- const breakpointsCount = breakpoints.length;
1372
- const timeRangesCount = timeRanges.length;
1373
- const timeCaptionsValues = new Set(timeCaptionsPriorities.flatMap((arr) => arr));
1374
- const timeGraduationsValues = new Set(timeGraduationsPriorities.flatMap((arr) => arr));
1375
- // Time captions:
1376
- if (timeCaptionsPriorities.length !== breakpointsCount)
1377
- throw new Error(`${PREFIX}: timeCaptionsPriorities should have as much elements as breakpoints.`);
1378
- if (timeCaptionsPriorities.some((arr) => arr.length !== timeRangesCount))
1379
- throw new Error(`${PREFIX}: each array in timeCaptionsPriorities should have as much elements as timeRanges.`);
1380
- if (Array.from(timeCaptionsValues).some((v) => v !== 0 && !timeCaptionsStyles[v]))
1381
- throw new Error(`${PREFIX}: all values (except 0s) from timeCaptionsPriorities should have a matching style in timeCaptionsStyles.`);
1382
- // Time graduations:
1383
- if (timeGraduationsPriorities.length !== breakpointsCount)
1384
- throw new Error(`${PREFIX}: timeGraduationsPriorities should have as much elements as breakpoints.`);
1385
- if (timeGraduationsPriorities.some((arr) => arr.length !== timeRangesCount))
1386
- throw new Error(`${PREFIX}: each array in timeGraduationsPriorities should have as much elements as timeRanges.`);
1387
- if (Array.from(timeGraduationsValues).some((v) => v !== 0 && !timeGraduationsStyles[v]))
1388
- throw new Error(`${PREFIX}: all values (except 0s) from timeGraduationsPriorities should have a matching style in timeGraduationsStyles.`);
1389
- if (!timeGraduationsStyles[1])
1390
- throw new Error(`${PREFIX}: there should be a timeGraduationsStyles for value 1.`);
1730
+ function getDataToPoint(getTimePixel, getSpacePixel, timeAxis, spaceAxis) {
1731
+ return ({ time, position }) => ({
1732
+ [timeAxis]: getTimePixel(time),
1733
+ [spaceAxis]: getSpacePixel(position),
1734
+ });
1391
1735
  }
1392
-
1393
- /* eslint-disable @typescript-eslint/no-use-before-define */
1394
1736
  /**
1395
- * This function helps to index a sequence of consecutive scales into a binary tree, to make it
1396
- * faster to find which scale contains any given position.
1397
- *
1398
- * The optional `skipSiblingReferences` option allows getting a serializable tree, for testing
1399
- * purpose.
1737
+ * This function takes a path and a time, a returns the position of the train at the given time, or
1738
+ * the position at the closest time to the path existence.
1400
1739
  */
1401
- function spaceScalesToBinaryTree(spaceOrigin, spaceScales, skipSiblingReferences) {
1402
- let prev = spaceOrigin;
1403
- // Step 1: Validate the scales
1404
- if (spaceScales.some((scale) => {
1405
- if (scale.to < prev)
1406
- return true;
1407
- prev = scale.to;
1408
- return false;
1409
- })) {
1410
- throw new Error("Invalid scale: 'to' must be greater than previous 'to'.");
1740
+ function getSpaceAtTime(path, time) {
1741
+ const segments = path.points.slice(0, -1).map((p, i) => [p, path.points[i + 1]]);
1742
+ const matchingSegment = segments.find(([p1, p2]) => inRange(time, p1.time, p2.time));
1743
+ if (matchingSegment) {
1744
+ const [p1, p2] = matchingSegment;
1745
+ return p1.position + ((time - p1.time) / (p2.time - p1.time)) * (p2.position - p1.position);
1411
1746
  }
1412
- if (spaceScales.some((scale) => ('size' in scale ? scale.size : scale.coefficient) <= 0)) {
1413
- throw new Error("Invalid scale: 'to' must be greater than 'from'.");
1747
+ let minPoint = path.points[0];
1748
+ let maxPoint = path.points[0];
1749
+ path.points.slice(1).forEach((point) => {
1750
+ if (point.time < minPoint.time)
1751
+ minPoint = point;
1752
+ if (point.time > maxPoint.time)
1753
+ maxPoint = point;
1754
+ });
1755
+ if (minPoint.time > time)
1756
+ return minPoint.position;
1757
+ return maxPoint.position;
1758
+ }
1759
+ /**
1760
+ * This function helps to find where to "break" a straight line that crosses separations between
1761
+ * different time scales. It takes two positions (in the "space" space), and returns an array of
1762
+ * positions between these the two input positions (the array can be empty).
1763
+ */
1764
+ function getSpaceBreakpoints(from, to, tree) {
1765
+ if (to < from)
1766
+ return getSpaceBreakpoints(to, from, tree).reverse();
1767
+ from = Math.max(from, tree.from);
1768
+ to = Math.min(to, tree.to);
1769
+ let fromScale = getNormalizedScaleAtPosition(from, tree);
1770
+ const res = [];
1771
+ while (fromScale.to < to) {
1772
+ res.push(fromScale.to);
1773
+ fromScale = fromScale.next;
1414
1774
  }
1415
- // Step 2: Normalize the scales
1416
- const normalizedScales = [];
1417
- let offset = 0;
1418
- prev = spaceOrigin;
1419
- for (let i = 0; i < spaceScales.length; i++) {
1420
- const scale = spaceScales[i];
1421
- const coefficient = 'coefficient' in scale ? scale.coefficient : (scale.to - prev) / scale.size;
1422
- const size = 'coefficient' in scale ? (scale.to - prev) / scale.coefficient : scale.size;
1423
- normalizedScales.push({
1424
- from: prev,
1425
- to: scale.to,
1426
- pixelFrom: offset,
1427
- pixelTo: offset + size,
1428
- coefficient,
1429
- });
1430
- offset += size;
1431
- prev = scale.to;
1432
- if (i) {
1433
- normalizedScales[i].previous = normalizedScales[i - 1];
1434
- normalizedScales[i - 1].next = normalizedScales[i];
1775
+ return res;
1776
+ }
1777
+ /**
1778
+ * in most cases, after the rectangle zoom, the screen will be centered
1779
+ * on the center of the rectangle the user drew.
1780
+ * In case we reach max zoom, not to break this expectation we need a different offset calculation
1781
+ */
1782
+ function computeRectZoomOffsets({ rect, timeOrigin, spaceOrigin, newTimeScale, newSpaceScale, swapAxes, chartWidth, chartHeight, }) {
1783
+ const chartTimeSizePx = !swapAxes ? chartWidth : chartHeight;
1784
+ const chartSpaceSizePx = !swapAxes ? chartHeight : chartWidth;
1785
+ const timeOffset = sideOffset(timeOrigin, newTimeScale, rect.timeStart, rect.timeEnd, chartTimeSizePx);
1786
+ const spaceOffset = sideOffset(spaceOrigin, newSpaceScale, rect.spaceStart, rect.spaceEnd, chartSpaceSizePx);
1787
+ return !swapAxes
1788
+ ? { xOffset: timeOffset, yOffset: spaceOffset }
1789
+ : { xOffset: spaceOffset, yOffset: timeOffset };
1790
+ }
1791
+ function sideOffset(origin, newScale, rectStart, rectEnd, chartSideSizePx, axisPadding = 0) {
1792
+ const rectCenter = (Number(rectStart) + Number(rectEnd)) / 2;
1793
+ const newChartSize = chartSideSizePx * newScale;
1794
+ // newChartBorder is the x or y origin after zoom
1795
+ // it’s normally the same as rectStart (the left or top most part of the rectangle)
1796
+ // but if we reach max zoom we can’t use rectStart as the chart displayed origin
1797
+ // because it doesn’t garentees that the zoom rectangle stays exactly at the center of the chart after the zoom
1798
+ const newChartBorder = rectCenter - newChartSize / 2;
1799
+ return (origin - newChartBorder) / newScale - axisPadding * 2;
1800
+ }
1801
+
1802
+ const DEFAULT_PATH_END = 'stop';
1803
+
1804
+ /**
1805
+ * This function draws a thick lines from "from" to "to" on the given ImageData, with no
1806
+ * antialiasing. This is very useful to handle picking, since it is not possible to disable
1807
+ * antialiasing with the native JavaScript canvas APIs.
1808
+ */
1809
+ function drawAliasedLine(imageData, { x: fromX, y: fromY }, { x: toX, y: toY }, [r, g, b], thickness, drawOnBottom, scalingRatio = 1) {
1810
+ if (fromX > toX)
1811
+ return drawAliasedLine(imageData, { x: toX, y: toY }, { x: fromX, y: fromY }, [r, g, b], thickness, drawOnBottom, scalingRatio);
1812
+ fromX = Math.round(fromX * scalingRatio);
1813
+ fromY = Math.round(fromY * scalingRatio);
1814
+ toX = Math.round(toX * scalingRatio);
1815
+ toY = Math.round(toY * scalingRatio);
1816
+ thickness = Math.round(thickness * scalingRatio);
1817
+ const width = imageData.width;
1818
+ const height = imageData.height;
1819
+ const dx = toX - fromX;
1820
+ const dy = toY - fromY;
1821
+ const len = Math.sqrt(dx * dx + dy * dy);
1822
+ // Calculate perpendicular vector
1823
+ const normX = -dy / len;
1824
+ const normY = dx / len;
1825
+ // Calculate the four corners of the rectangle
1826
+ const halfThickness = Math.ceil(thickness / 2);
1827
+ const corner1 = {
1828
+ x: fromX + (+normX - dx / len) * halfThickness,
1829
+ y: fromY + (+normY - dy / len) * halfThickness,
1830
+ };
1831
+ const corner2 = {
1832
+ x: fromX + (-normX - dx / len) * halfThickness,
1833
+ y: fromY + (-normY - dy / len) * halfThickness,
1834
+ };
1835
+ const corner3 = {
1836
+ x: toX + (-normX + dx / len) * halfThickness,
1837
+ y: toY + (-normY + dy / len) * halfThickness,
1838
+ };
1839
+ const corner4 = {
1840
+ x: toX + (+normX + dx / len) * halfThickness,
1841
+ y: toY + (+normY + dy / len) * halfThickness,
1842
+ };
1843
+ const ascending = fromY < toY;
1844
+ const top = ascending ? corner4 : corner1;
1845
+ const left = ascending ? corner1 : corner2;
1846
+ const right = ascending ? corner3 : corner4;
1847
+ const bottom = ascending ? corner2 : corner3;
1848
+ const xMin = clamp$1(Math.floor(left.x), 0, width);
1849
+ const xMax = clamp$1(Math.ceil(right.x), 0, width);
1850
+ const yMin = clamp$1(Math.floor(bottom.y), 0, height);
1851
+ const yMax = clamp$1(Math.ceil(top.y), 0, height);
1852
+ for (let y = yMin; y <= yMax; y++) {
1853
+ const xMinRow = clamp$1(y < left.y
1854
+ ? Math.floor(bottom.x + ((y - bottom.y) * (left.x - bottom.x)) / (left.y - bottom.y))
1855
+ : Math.floor(left.x + ((y - left.y) * (left.x - top.x)) / (left.y - top.y)), xMin, xMax);
1856
+ const xMaxRow = clamp$1(y < right.y
1857
+ ? Math.ceil(bottom.x + ((y - bottom.y) * (right.x - bottom.x)) / (right.y - bottom.y))
1858
+ : Math.ceil(right.x + ((y - right.y) * (right.x - top.x)) / (right.y - top.y)), xMin, xMax);
1859
+ for (let x = xMinRow; x <= xMaxRow; x++) {
1860
+ const index = (y * width + x) * 4;
1861
+ if (!imageData.data[index + 3]) {
1862
+ imageData.data[index] = r;
1863
+ imageData.data[index + 1] = g;
1864
+ imageData.data[index + 2] = b;
1865
+ imageData.data[index + 3] = 255;
1866
+ }
1435
1867
  }
1436
1868
  }
1437
- // Step 3: Build the tree
1438
- function buildTree(scales) {
1439
- if (scales.length === 0) {
1440
- return {
1441
- coefficient: 1,
1442
- from: -Infinity,
1443
- to: Infinity,
1444
- pixelFrom: -Infinity,
1445
- pixelTo: Infinity,
1446
- };
1447
- }
1448
- else if (scales.length === 1) {
1449
- return scales[0];
1450
- }
1451
- else {
1452
- const size = Math.ceil(scales.length / 2);
1453
- const limit = scales[size - 1].to;
1454
- const pixelLimit = scales[size - 1].pixelTo;
1455
- return {
1456
- limit,
1457
- pixelLimit,
1458
- from: scales[0].from,
1459
- to: scales[scales.length - 1].to,
1460
- pixelFrom: scales[0].pixelFrom,
1461
- pixelTo: scales[scales.length - 1].pixelTo,
1462
- left: buildTree(scales.slice(0, size)),
1463
- right: buildTree(scales.slice(size)),
1464
- };
1869
+ }
1870
+ /**
1871
+ * This function takes an integer radius, and returns a flat matrix of 1s and 0s, where the 1s
1872
+ * represent the pixels that are within the disc. The shapes are cached, to make it faster to draw
1873
+ * a lot of times discs of the same radius.
1874
+ *
1875
+ * Here are some examples to make it clearer what the output should look like:
1876
+ *
1877
+ * getAliasedDiscShape(0);
1878
+ * [1]
1879
+ * getAliasedDiscShape(1);
1880
+ * [0, 1, 0,
1881
+ * 1, 1, 1,
1882
+ * 0, 1, 0]
1883
+ * getAliasedDiscShape(2);
1884
+ * [0, 0, 1, 0, 0,
1885
+ * 0, 1, 1, 1, 0,
1886
+ * 1, 1, 1, 1, 1,
1887
+ * 0, 1, 1, 1, 0,
1888
+ * 0, 0, 1, 0, 0]
1889
+ */
1890
+ const DISCS_CACHE = new Map();
1891
+ function getAliasedDiscShape(radius) {
1892
+ const cachedShape = DISCS_CACHE.get(radius);
1893
+ if (cachedShape)
1894
+ return cachedShape;
1895
+ const diameter = radius * 2 + 1;
1896
+ const shape = new Uint8Array(diameter * diameter);
1897
+ for (let dy = -radius; dy <= radius; dy++) {
1898
+ for (let dx = -radius; dx <= radius; dx++) {
1899
+ const distance = dx * dx + dy * dy;
1900
+ if (distance <= radius * radius) {
1901
+ const x = dx + radius;
1902
+ const y = dy + radius;
1903
+ shape[y * diameter + x] = 1;
1904
+ }
1465
1905
  }
1466
1906
  }
1467
- return buildTree(normalizedScales);
1907
+ DISCS_CACHE.set(radius, shape);
1908
+ return shape;
1468
1909
  }
1469
1910
  /**
1470
- * This function takes a sequence of SpaceScales, identifies the flat steps (i.e. the scales that do
1471
- * not increase the position), and returns them in a set.
1911
+ * This function draws an aliased disc, using a shape computed by getDiscShape.
1472
1912
  */
1473
- function getFlatSteps(spaceScales) {
1474
- const flatSteps = [];
1475
- for (let i = 1; i < spaceScales.length; i++) {
1476
- const { to: previous } = spaceScales[i - 1];
1477
- const { to: current } = spaceScales[i];
1478
- if (previous === current)
1479
- flatSteps.push(current);
1913
+ function drawAliasedDisc(imageData, { x: centerX, y: centerY }, radius, [r, g, b], drawOnBottom, scalingRatio = 1) {
1914
+ centerX = Math.round(centerX * scalingRatio);
1915
+ centerY = Math.round(centerY * scalingRatio);
1916
+ radius = Math.ceil(radius * scalingRatio);
1917
+ const { width, height } = imageData;
1918
+ const discShape = getAliasedDiscShape(radius);
1919
+ // Draw the disc on the imageData
1920
+ const diameter = radius * 2 + 1;
1921
+ for (let dy = -radius; dy <= radius; dy++) {
1922
+ for (let dx = -radius; dx <= radius; dx++) {
1923
+ const shapeIndex = (dy + radius) * diameter + (dx + radius);
1924
+ if (discShape[shapeIndex] === 1) {
1925
+ const x = centerX + dx;
1926
+ const y = centerY + dy;
1927
+ if (x >= 0 && x < width && y >= 0 && y < height) {
1928
+ const index = (y * width + x) * 4;
1929
+ {
1930
+ imageData.data[index] = r;
1931
+ imageData.data[index + 1] = g;
1932
+ imageData.data[index + 2] = b;
1933
+ imageData.data[index + 3] = 255;
1934
+ }
1935
+ }
1936
+ }
1937
+ }
1480
1938
  }
1481
- return new Set(flatSteps);
1482
1939
  }
1483
1940
  /**
1484
- * This function takes a NormalizedScaleTree and a position, and returns the leaf node from the
1485
- * tree that contains that position.
1941
+ * Draws an aliased quadrilateral
1486
1942
  *
1487
- * Also, if the position is lower than the tree's min (tree.from), then the first leaf is returned
1488
- * and if it is higher than the max (tree.to), the last leaf is returned.
1943
+ * vertices[0] ________ vertices[1]
1944
+ * / /
1945
+ * vertices[3] /________/ vertices[2]
1489
1946
  *
1490
- * Finally, if pickLast is truthy, then it returns the last leaf node that contains that position
1491
- * instead of the first one. It is very important when there are flat sections.
1492
1947
  */
1493
- function getNormalizedScaleAtPosition(position, tree, pickLast) {
1494
- position = clamp$1(position, tree.from, tree.to);
1495
- let node = tree;
1496
- while ('limit' in node) {
1497
- if (!pickLast) {
1498
- if (position <= node.limit)
1499
- node = node.left;
1500
- else
1501
- node = node.right;
1948
+ function drawAliasedQuadrilateral(imageData, points, [r, g, b], scalingRatio = 1) {
1949
+ const vertices = points.map((point) => ({
1950
+ x: Math.round(point.x * scalingRatio),
1951
+ y: Math.round(point.y * scalingRatio),
1952
+ }));
1953
+ let { x: xmin, x: xmax, y: ymin, y: ymax } = vertices[0];
1954
+ for (let i = 1; i < vertices.length; i++) {
1955
+ const { x, y } = vertices[i];
1956
+ if (x < xmin)
1957
+ xmin = x;
1958
+ else if (x > xmax)
1959
+ xmax = x;
1960
+ if (y < ymin)
1961
+ ymin = y;
1962
+ else if (y > ymax)
1963
+ ymax = y;
1964
+ }
1965
+ xmin = clamp$1(xmin, 0, imageData.width - 1);
1966
+ ymin = clamp$1(ymin, 0, imageData.height - 1);
1967
+ xmax = clamp$1(xmax, 0, imageData.width - 1);
1968
+ ymax = clamp$1(ymax, 0, imageData.height - 1);
1969
+ for (let y = ymin; y < ymax; y++) {
1970
+ for (let x = xmin; x < xmax; x++) {
1971
+ // Compute whether the point is inside the quadrilateral
1972
+ // using the Ray casting algorithm (see https://en.wikipedia.org/wiki/Point_in_polygon)
1973
+ let isInside = false;
1974
+ for (let i = 0; i < vertices.length; i++) {
1975
+ const pointA = vertices[i];
1976
+ const pointB = i === vertices.length - 1 ? vertices[0] : vertices[i + 1];
1977
+ // Line equation from A to B: y(x) = m * x + c
1978
+ const m = (pointB.y - pointA.y) / (pointB.x - pointA.x);
1979
+ const c = pointB.y - m * pointB.x;
1980
+ // Invert the equation: x(y) = (y - c) / m
1981
+ // Look only for points that are on the left of the line, so for a given y, x < (y - c) / m
1982
+ if (pointA.y > y != pointB.y > y && x < (y - c) / m) {
1983
+ isInside = !isInside;
1984
+ }
1985
+ }
1986
+ // If the point is inside the quadrilateral, allow interactions with it
1987
+ if (isInside) {
1988
+ const index = (y * imageData.width + x) * 4;
1989
+ imageData.data[index] = r;
1990
+ imageData.data[index + 1] = g;
1991
+ imageData.data[index + 2] = b;
1992
+ imageData.data[index + 3] = 255;
1993
+ }
1502
1994
  }
1503
- else {
1504
- if (position >= node.limit)
1505
- node = node.right;
1506
- else
1507
- node = node.left;
1995
+ }
1996
+ }
1997
+ function drawAliasedRect(imageData, { x, y }, width, height, [r, g, b], scalingRatio = 1) {
1998
+ x = Math.round(x * scalingRatio);
1999
+ y = Math.round(y * scalingRatio);
2000
+ width = Math.round(width * scalingRatio);
2001
+ height = Math.round(height * scalingRatio);
2002
+ const xMin = clamp$1(x, 0, imageData.width);
2003
+ const yMin = clamp$1(y, 0, imageData.height);
2004
+ const xMax = clamp$1(x + width, 0, imageData.width);
2005
+ const yMax = clamp$1(y + height, 0, imageData.height);
2006
+ for (let i = xMin; i < xMax; i++) {
2007
+ for (let j = yMin; j < yMax; j++) {
2008
+ const index = (j * imageData.width + i) * 4;
2009
+ imageData.data[index] = r;
2010
+ imageData.data[index + 1] = g;
2011
+ imageData.data[index + 2] = b;
2012
+ imageData.data[index + 3] = 255;
1508
2013
  }
1509
2014
  }
1510
- return node;
1511
2015
  }
1512
2016
  /**
1513
- * This function takes a NormalizedScaleTree and a pixel position, and returns the leaf node from
1514
- * the tree that contains that pixel.
1515
- *
1516
- * Also, if the position is lower than the tree's min pixel (tree.pixelFrom), then the first leaf
1517
- * is returned and if it is higher than the max pixel (tree.pixelTo), the last leaf is returned.
2017
+ * This function draws a "stop" path extremity.
2018
+ * That handles a path that stops or starts exactly in an operational points included in the line
2019
+ * represented in the chart.
1518
2020
  */
1519
- function getNormalizedScaleAtPixel(y, tree) {
1520
- y = clamp$1(y, tree.pixelFrom, tree.pixelTo);
1521
- let node = tree;
1522
- while ('pixelLimit' in node) {
1523
- if (y <= node.pixelLimit)
1524
- node = node.left;
1525
- else
1526
- node = node.right;
2021
+ const STOP_END_SIZE = 6;
2022
+ function drawPathStopExtremity(ctx, timePixel, spacePixel, swapAxis) {
2023
+ ctx.beginPath();
2024
+ if (!swapAxis) {
2025
+ ctx.moveTo(timePixel, spacePixel - STOP_END_SIZE / 2);
2026
+ ctx.lineTo(timePixel, spacePixel + STOP_END_SIZE / 2);
1527
2027
  }
1528
- return node;
1529
- }
1530
- // The following functions handle various kinds of data translation from the pixel space to the
1531
- // time/space referential:
1532
- function getTimeToPixel(timeOrigin, pixelOffset, timeScale) {
1533
- return (time) => pixelOffset + (time - timeOrigin) / timeScale;
1534
- }
1535
- function getPixelToTime(timeOrigin, pixelOffset, timeScale) {
1536
- return (timePixel) => (timePixel - pixelOffset) * timeScale + timeOrigin;
1537
- }
1538
- function getSpaceToPixel(pixelOffset, binaryTree) {
1539
- return (position, fromEnd) => {
1540
- const { from, pixelFrom, pixelTo, coefficient } = getNormalizedScaleAtPosition(position, binaryTree, fromEnd);
1541
- // Rare case where coefficient is 0:
1542
- // (occurs when there is just a flat step, for instance)
1543
- if (coefficient === 0)
1544
- return pixelOffset + (fromEnd ? pixelTo : pixelFrom);
1545
- // Normal case: We simply interpolate
1546
- return pixelOffset + pixelFrom + (position - from) / coefficient;
1547
- };
1548
- }
1549
- function getPixelToSpace(pixelOffset, binaryTree) {
1550
- return (spacePixel) => {
1551
- const { from, pixelFrom, coefficient } = getNormalizedScaleAtPixel(spacePixel - pixelOffset, binaryTree);
1552
- return from + (spacePixel - pixelOffset - pixelFrom) * coefficient;
1553
- };
1554
- }
1555
- function getPointToData(getTime, getSpace, timeAxis, spaceAxis) {
1556
- return (point) => ({
1557
- time: getTime(point[timeAxis]),
1558
- position: getSpace(point[spaceAxis]),
1559
- });
2028
+ else {
2029
+ ctx.moveTo(spacePixel - STOP_END_SIZE / 2, timePixel);
2030
+ ctx.lineTo(spacePixel + STOP_END_SIZE / 2, timePixel);
2031
+ }
2032
+ ctx.stroke();
1560
2033
  }
1561
- function getDataToPoint(getTimePixel, getSpacePixel, timeAxis, spaceAxis) {
1562
- return ({ time, position }) => ({
1563
- [timeAxis]: getTimePixel(time),
1564
- [spaceAxis]: getSpacePixel(position),
1565
- });
2034
+ /**
2035
+ * This function draws an "out" path extremity.
2036
+ * That handles a path that leaves or joins the line represented in the chart.
2037
+ */
2038
+ const OUT_END_SIZE = 12;
2039
+ function drawPathOutExtremity(ctx, timePixel, spacePixel, swapAxis, extremityType, pathDirection) {
2040
+ let horizontalSign = extremityType === 'from' ? -1 : 1;
2041
+ let verticalSign = (pathDirection === 'backward' ? -1 : 1) * horizontalSign;
2042
+ let controlX = timePixel + 4 * horizontalSign;
2043
+ let controlY = spacePixel + (OUT_END_SIZE - 2) * verticalSign;
2044
+ let x = timePixel;
2045
+ let y = spacePixel;
2046
+ if (swapAxis) {
2047
+ [horizontalSign, verticalSign] = [verticalSign, horizontalSign];
2048
+ [controlX, controlY] = [controlY, controlX];
2049
+ [x, y] = [y, x];
2050
+ }
2051
+ ctx.beginPath();
2052
+ ctx.moveTo(x, y);
2053
+ ctx.bezierCurveTo(controlX, controlY, controlX, controlY, x + OUT_END_SIZE * horizontalSign, y + OUT_END_SIZE * verticalSign);
2054
+ ctx.stroke();
1566
2055
  }
1567
2056
  /**
1568
- * This function takes a path and a time, a returns the position of the train at the given time, or
1569
- * the position at the closest time to the path existence.
2057
+ * This function draws a path extremity.
1570
2058
  */
1571
- function getSpaceAtTime(path, time) {
1572
- const segments = path.points.slice(0, -1).map((p, i) => [p, path.points[i + 1]]);
1573
- const matchingSegment = segments.find(([p1, p2]) => inRange(time, p1.time, p2.time));
1574
- if (matchingSegment) {
1575
- const [p1, p2] = matchingSegment;
1576
- return p1.position + ((time - p1.time) / (p2.time - p1.time)) * (p2.position - p1.position);
2059
+ function drawPathExtremity(ctx, timePixel, spacePixel, swapAxis, extremityType, pathDirection, pathEnd) {
2060
+ if (pathEnd === 'out') {
2061
+ drawPathOutExtremity(ctx, timePixel, spacePixel, swapAxis, extremityType, pathDirection);
1577
2062
  }
1578
- let minPoint = path.points[0];
1579
- let maxPoint = path.points[0];
1580
- path.points.slice(1).forEach((point) => {
1581
- if (point.time < minPoint.time)
1582
- minPoint = point;
1583
- if (point.time > maxPoint.time)
1584
- maxPoint = point;
1585
- });
1586
- if (minPoint.time > time)
1587
- return minPoint.position;
1588
- return maxPoint.position;
2063
+ else {
2064
+ drawPathStopExtremity(ctx, timePixel, spacePixel, swapAxis);
2065
+ }
2066
+ }
2067
+ /**
2068
+ * You most likely need to wrap this function call with ctx.save ctx.restore
2069
+ * as it modifies ctx current transformation matrix
2070
+ */
2071
+ function fillRect(ctx, { timeStart, timeEnd, spaceStart, spaceEnd }, { getPoint }) {
2072
+ const startPoint = getPoint({ time: Number(timeStart), position: spaceStart });
2073
+ const endPoint = getPoint({ time: Number(timeEnd), position: spaceEnd });
2074
+ const width = endPoint.x - startPoint.x;
2075
+ const height = endPoint.y - startPoint.y;
2076
+ if (width !== 0 && height !== 0) {
2077
+ ctx.translate(startPoint.x, startPoint.y);
2078
+ ctx.fillRect(0, 0, width, height);
2079
+ }
2080
+ return { width, height };
1589
2081
  }
2082
+
1590
2083
  /**
1591
- * This function helps to find where to "break" a straight line that crosses separations between
1592
- * different time scales. It takes two positions (in the "space" space), and returns an array of
1593
- * positions between these the two input positions (the array can be empty).
2084
+ * This function takes a path, a point index and looks forward in the points order for the first
2085
+ * position variation. It then returns "forward" or "backward" according to that variation.
2086
+ *
2087
+ * If it does not find any variation for some reason, it returns "still" instead.
2088
+ *
2089
+ * Finally, if `reversed` is true, then, it searches points in the other direction.
1594
2090
  */
1595
- function getSpaceBreakpoints(from, to, tree) {
1596
- if (to < from)
1597
- return getSpaceBreakpoints(to, from, tree).reverse();
1598
- from = Math.max(from, tree.from);
1599
- to = Math.min(to, tree.to);
1600
- let fromScale = getNormalizedScaleAtPosition(from, tree);
1601
- const res = [];
1602
- while (fromScale.to < to) {
1603
- res.push(fromScale.to);
1604
- fromScale = fromScale.next;
2091
+ function getPathDirection({ points }, index, reversed) {
2092
+ if (points.length < 2 || !points[index])
2093
+ return 'still';
2094
+ const reference = points[index].position;
2095
+ let i = index;
2096
+ let point;
2097
+ while ((point = points[i])) {
2098
+ if (point.position !== reference) {
2099
+ const delta = reversed ? reference - point.position : point.position - reference;
2100
+ return delta > 0 ? 'forward' : 'backward';
2101
+ }
2102
+ i = i + (reversed ? -1 : 1);
1605
2103
  }
1606
- return res;
2104
+ return 'still';
1607
2105
  }
1608
2106
  /**
1609
- * in most cases, after the rectangle zoom, the screen will be centered
1610
- * on the center of the rectangle the user drew.
1611
- * In case we reach max zoom, not to break this expectation we need a different offset calculation
2107
+ * This function takes a SpaceToPixel function and a position, and checks if the function returns
2108
+ * the same pixel for the position, starting from both sides. It then returns one or two pixel
2109
+ * positions accordingly.
1612
2110
  */
1613
- function computeRectZoomOffsets({ rect, timeOrigin, spaceOrigin, newTimeScale, newSpaceScale, swapAxes, chartWidth, chartHeight, }) {
1614
- const chartTimeSizePx = !swapAxes ? chartWidth : chartHeight;
1615
- const chartSpaceSizePx = !swapAxes ? chartHeight : chartWidth;
1616
- const timeOffset = sideOffset(timeOrigin, newTimeScale, rect.timeStart, rect.timeEnd, chartTimeSizePx);
1617
- const spaceOffset = sideOffset(spaceOrigin, newSpaceScale, rect.spaceStart, rect.spaceEnd, chartSpaceSizePx);
1618
- return !swapAxes
1619
- ? { xOffset: timeOffset, yOffset: spaceOffset }
1620
- : { xOffset: spaceOffset, yOffset: timeOffset };
1621
- }
1622
- function sideOffset(origin, newScale, rectStart, rectEnd, chartSideSizePx, axisPadding = 0) {
1623
- const rectCenter = (Number(rectStart) + Number(rectEnd)) / 2;
1624
- const newChartSize = chartSideSizePx * newScale;
1625
- // newChartBorder is the x or y origin after zoom
1626
- // it’s normally the same as rectStart (the left or top most part of the rectangle)
1627
- // but if we reach max zoom we can’t use rectStart as the chart displayed origin
1628
- // because it doesn’t garentees that the zoom rectangle stays exactly at the center of the chart after the zoom
1629
- const newChartBorder = rectCenter - newChartSize / 2;
1630
- return (origin - newChartBorder) / newScale - axisPadding * 2;
2111
+ function getSpacePixels(getSpacePixel, position) {
2112
+ const spacePixelFromStart = getSpacePixel(position);
2113
+ const spacePixelFromEnd = getSpacePixel(position, true);
2114
+ return spacePixelFromStart === spacePixelFromEnd
2115
+ ? [spacePixelFromStart]
2116
+ : [spacePixelFromStart, spacePixelFromEnd];
1631
2117
  }
1632
2118
 
1633
2119
  const DEFAULT_PICKING_TOLERANCE = 5;
@@ -1877,7 +2363,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1877
2363
  /**
1878
2364
  * This function draws the extremities of the path.
1879
2365
  */
1880
- const drawExtremities = useCallback((ctx, { getTimePixel, getSpacePixel, swapAxis }) => {
2366
+ const drawExtremities = useCallback((ctx, { getTimePixel, getSpacePixel, swapAxis = false }) => {
1881
2367
  if (!path.points.length)
1882
2368
  return;
1883
2369
  const from = path.points[0];
@@ -2029,7 +2515,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
2029
2515
  computePathLength,
2030
2516
  drawLabel,
2031
2517
  ]);
2032
- useDraw('paths', drawAll);
2518
+ useDraw(SpaceTimeChartCanvasContext, 'paths', drawAll);
2033
2519
  const drawPicking = useCallback((imageData, stcContext, scalingRatio) => {
2034
2520
  const { registerPickingElement } = stcContext;
2035
2521
  // Draw single point:
@@ -2074,7 +2560,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
2074
2560
  drawAliasedDisc(imageData, point, (STYLES[level].width + pickingTolerance) * 2, lineColor, false, scalingRatio);
2075
2561
  });
2076
2562
  }, [getPathLines, getSnapPoints, level, path.id, path.points, pickingTolerance]);
2077
- usePicking('paths', drawPicking);
2563
+ usePicking(SpaceTimeChartCanvasContext, 'paths', drawPicking);
2078
2564
  return null;
2079
2565
  };
2080
2566
 
@@ -2129,12 +2615,48 @@ function snapPosition(mousePosition, hoveredItem) {
2129
2615
  }
2130
2616
  }
2131
2617
 
2618
+ const SpaceGraduations = () => {
2619
+ const drawingFunction = useCallback((ctx, { timePixelOffset, getSpacePixel, operationalPoints, flatSteps, swapAxis, width, height, theme: { spaceGraduationsStyles }, }) => {
2620
+ const axisSize = !swapAxis ? width : height;
2621
+ // Draw operational point lines:
2622
+ operationalPoints.forEach((point) => {
2623
+ if (flatSteps.has(point.position))
2624
+ return;
2625
+ const styles = spaceGraduationsStyles[point.importanceLevel || 0];
2626
+ if (!styles)
2627
+ return;
2628
+ ctx.strokeStyle = styles.color;
2629
+ ctx.lineWidth = styles.width;
2630
+ ctx.globalAlpha = styles.opacity || 1;
2631
+ if (styles.dashArray) {
2632
+ ctx.setLineDash(styles.dashArray || []);
2633
+ ctx.lineDashOffset = -timePixelOffset;
2634
+ }
2635
+ // Detect flat steps, and draw two graduations if any (one on each side of the step):
2636
+ getSpacePixels(getSpacePixel, point.position).forEach((rawPixel) => {
2637
+ const spacePixel = getCrispLineCoordinate(rawPixel, ctx.lineWidth);
2638
+ ctx.beginPath();
2639
+ if (!swapAxis) {
2640
+ ctx.moveTo(0, spacePixel);
2641
+ ctx.lineTo(axisSize, spacePixel);
2642
+ }
2643
+ else {
2644
+ ctx.moveTo(spacePixel, 0);
2645
+ ctx.lineTo(spacePixel, axisSize);
2646
+ }
2647
+ ctx.stroke();
2648
+ });
2649
+ });
2650
+ ctx.setLineDash([]);
2651
+ ctx.lineDashOffset = 0;
2652
+ ctx.globalAlpha = 1;
2653
+ }, []);
2654
+ useDraw(SpaceTimeChartCanvasContext, 'graduations', drawingFunction);
2655
+ return null;
2656
+ };
2657
+
2132
2658
  const SpaceTimeChart = (props) => {
2133
- const { operationalPoints, spaceOrigin, spaceScales, timeOrigin, timeScale, xOffset = 0, yOffset = 0, swapAxis, onHoveredChildUpdate, children, additionalChildren, enableSnapping, hideTimeCaptions, hideGrid, hidePathsLabels, showTicks, hideDates, theme,
2134
- /* eslint-disable @typescript-eslint/no-unused-vars */
2135
- onPan, onZoom, onClick, onMouseMove,
2136
- /* eslint-enable @typescript-eslint/no-unused-vars */
2137
- ...attr } = props;
2659
+ const { operationalPoints, spaceOrigin, spaceScales, timeOrigin, timeScale, xOffset = 0, yOffset = 0, swapAxis, onHoveredChildUpdate, children, additionalChildren, enableSnapping, hideTimeCaptions, hideGrid, hidePathsLabels, showTicks, hideDates, theme, onPan, onZoom, onClick, onMouseMove, ...attr } = props;
2138
2660
  const [root, setRoot] = useState(null);
2139
2661
  const [canvasesRoot, setCanvasesRoot] = useState(null);
2140
2662
  const fullTheme = useMemo(() => ({ ...DEFAULT_THEME, ...theme }), [theme]);
@@ -2227,7 +2749,7 @@ const SpaceTimeChart = (props) => {
2227
2749
  timeOrigin,
2228
2750
  timeScale,
2229
2751
  timePixelOffset,
2230
- spacePixelOffset,
2752
+ yPixelOffset: spacePixelOffset,
2231
2753
  timeAxis,
2232
2754
  spaceAxis,
2233
2755
  swapAxis: !!swapAxis,
@@ -2275,14 +2797,15 @@ const SpaceTimeChart = (props) => {
2275
2797
  return (React.createElement("div", { ...attr, ref: setRoot, className: cx('relative space-time-chart', attr.className), style: { background: fullTheme.background } },
2276
2798
  React.createElement("div", { ref: setCanvasesRoot, className: "absolute inset-0" }),
2277
2799
  React.createElement(SpaceTimeChartContext.Provider, { value: contextState },
2278
- React.createElement(CanvasContext.Provider, { value: canvasContext },
2279
- React.createElement(MouseContext.Provider, { value: mouseContext },
2280
- !hideGrid && (React.createElement(React.Fragment, null,
2281
- React.createElement(SpaceGraduations, null),
2282
- React.createElement(TimeGraduations, null),
2283
- React.createElement(TimeCaptions, null))),
2284
- children,
2285
- additionalChildren)))));
2800
+ React.createElement(SpaceTimeChartCanvasContext.Provider, { value: canvasContext },
2801
+ React.createElement(TimeChartCanvasContext.Provider, { value: canvasContext },
2802
+ React.createElement(MouseContext.Provider, { value: mouseContext },
2803
+ !hideGrid && (React.createElement(React.Fragment, null,
2804
+ React.createElement(SpaceGraduations, null),
2805
+ React.createElement(TimeGraduations, null),
2806
+ React.createElement(TimeCaptions, null))),
2807
+ children,
2808
+ additionalChildren))))));
2286
2809
  };
2287
2810
 
2288
2811
  function isConflictPickingElement(element) {
@@ -2313,7 +2836,7 @@ const ConflictLayer = ({ conflicts }) => {
2313
2836
  ctx.fill(paths[i]);
2314
2837
  }
2315
2838
  }, [conflicts]);
2316
- useDraw('paths', drawConflictLayer);
2839
+ useDraw(SpaceTimeChartCanvasContext, 'paths', drawConflictLayer);
2317
2840
  const drawPicking = useCallback((imageData, { registerPickingElement, getTimePixel, getSpacePixel }, scalingRatio) => {
2318
2841
  for (const [conflictIndex, conflict] of conflicts.entries()) {
2319
2842
  const x = getTimePixel(conflict.timeStart);
@@ -2327,7 +2850,7 @@ const ConflictLayer = ({ conflicts }) => {
2327
2850
  drawAliasedRect(imageData, { x: x - border, y: y - border }, width + 2 * border, height + 2 * border, color, scalingRatio);
2328
2851
  }
2329
2852
  }, [conflicts]);
2330
- usePicking('paths', drawPicking);
2853
+ usePicking(SpaceTimeChartCanvasContext, 'paths', drawPicking);
2331
2854
  return null;
2332
2855
  };
2333
2856
 
@@ -2377,7 +2900,7 @@ const OccupancyBlockLayer = ({ occupancyBlocks }) => {
2377
2900
  ctx.fillRect(x, y, width, height);
2378
2901
  }
2379
2902
  }, [occupancyBlocks]);
2380
- useDraw('background', drawOccupancyBlockLayer);
2903
+ useDraw(SpaceTimeChartCanvasContext, 'background', drawOccupancyBlockLayer);
2381
2904
  return null;
2382
2905
  };
2383
2906
 
@@ -2394,7 +2917,7 @@ const PatternRect = ({ imageElement, ...rect }) => {
2394
2917
  ctx.restore();
2395
2918
  }
2396
2919
  }, [imageElement, rect]);
2397
- useDraw('background', drawPatternRect);
2920
+ useDraw(SpaceTimeChartCanvasContext, 'background', drawPatternRect);
2398
2921
  return null;
2399
2922
  };
2400
2923
 
@@ -2448,7 +2971,7 @@ const Quadrilateral = ({ id, vertices, style }) => {
2448
2971
  ctx.stroke();
2449
2972
  ctx.restore();
2450
2973
  }, [vertices, style]);
2451
- useDraw('background', drawRegion);
2974
+ useDraw(SpaceTimeChartCanvasContext, 'background', drawRegion);
2452
2975
  const drawPicking = useCallback((imageData, { registerPickingElement, getTimePixel, getSpacePixel }, scalingRatio) => {
2453
2976
  const points = vertices.map((vertice) => ({
2454
2977
  x: getTimePixel(vertice.time),
@@ -2459,7 +2982,7 @@ const Quadrilateral = ({ id, vertices, style }) => {
2459
2982
  const color = hexToRgb(indexToColor(index));
2460
2983
  drawAliasedQuadrilateral(imageData, points, color, scalingRatio);
2461
2984
  }, [id, vertices]);
2462
- usePicking('paths', drawPicking);
2985
+ usePicking(SpaceTimeChartCanvasContext, 'paths', drawPicking);
2463
2986
  return null;
2464
2987
  };
2465
2988
 
@@ -2496,7 +3019,7 @@ const ZoomRect = (rect) => {
2496
3019
  }
2497
3020
  ctx.restore();
2498
3021
  }, [rect]);
2499
- useDraw('background', drawZoomRect);
3022
+ useDraw(SpaceTimeChartCanvasContext, 'background', drawZoomRect);
2500
3023
  return null;
2501
3024
  };
2502
3025
 
@@ -2557,169 +3080,201 @@ function isPathOnScreen(width, height, points) {
2557
3080
  return segments.some(([from, to]) => isSegmentOnScreen(width, height, from, to));
2558
3081
  }
2559
3082
 
2560
- const INITIAL_OP_LIST_HEIGHT = 521;
2561
- const BASE_WAYPOINT_HEIGHT = 32;
2562
- const INITIAL_SPACE_TIME_CHART_HEIGHT = INITIAL_OP_LIST_HEIGHT + 40;
2563
- const MIN_ZOOM_MS_PER_PX = 600_000;
2564
- const MAX_ZOOM_MS_PER_PX = 625;
2565
- const DEFAULT_ZOOM_MS_PER_PX = 7_500;
2566
- const MIN_ZOOM_X = 0;
2567
- const MAX_ZOOM_X = 100;
2568
- const MIN_ZOOM_Y = 1;
2569
- const MAX_ZOOM_Y = 10.5;
2570
- const ZOOM_Y_DELTA = 0.5;
2571
- const MAX_ZOOM_MANCHETTE_HEIGHT_MILLIMETER = 500_000;
2572
- const FOOTER_HEIGHT = 40; // height of the manchette footer
2573
- const WAYPOINT_LINE_HEIGHT = 16;
2574
- const PATH_COLOR_DEFAULT = '#8A714B';
2575
-
2576
- const getHeightWithoutLastWaypoint = (height) => height - FOOTER_HEIGHT - BASE_WAYPOINT_HEIGHT;
2577
- const positionMmToKm = (position) => Math.round((position / 1000000) * 10) / 10;
2578
- const positionKmToMm = (position) => position * 1000000;
2579
- const calcTotalDistance = (ops) => {
2580
- if (ops.length === 0) {
2581
- return 0;
2582
- }
2583
- return ops.at(-1).position - ops.at(0).position;
2584
- };
2585
- function getDistance(a, b) {
2586
- return {
2587
- x: b.x - a.x,
2588
- y: b.y - a.y,
2589
- };
2590
- }
2591
-
2592
- const Waypoint = ({ waypoint: { name, secondaryCode, id, position, onClick }, waypointRef, isActive, isMenuActive, testIdPrefix, }) => (React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}-base-info` : undefined, className: cx('flex waypoint items-baseline', {
3083
+ const Waypoint = ({ waypoint: { name, secondaryCode, id, position, onClick, styles }, waypointRef, isActive, isMenuActive, testIdPrefix, hidePositions = false, }) => (React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}-base-info` : undefined, className: cx('flex waypoint items-baseline', {
2593
3084
  'waypoint-active': isActive,
2594
3085
  'menu-active': isMenuActive,
2595
- }), id: id, ref: waypointRef, onClick: () => {
3086
+ }), style: styles, id: id, ref: waypointRef, onClick: () => {
2596
3087
  if (onClick && !isMenuActive)
2597
3088
  onClick(id);
2598
3089
  } },
2599
- React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}-position` : undefined, className: "waypoint-position justify-self-start text-end" }, positionMmToKm(position)),
2600
- React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}-name` : undefined, className: "waypoint-name mx-2 justify-self-start" }, name),
3090
+ !hidePositions && (React.createElement("div", { "data-testid": "waypoint-position", className: "waypoint-position justify-self-start text-end" }, positionMmToKm(position))),
3091
+ React.createElement("div", { "data-testid": "waypoint-name", className: "waypoint-name mx-2 justify-self-start" }, name),
2601
3092
  React.createElement("div", { className: "waypoint-separator" }),
2602
- React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}-ch` : undefined, className: "waypoint-ch font-mono justify-self-end" }, secondaryCode),
2603
- React.createElement("div", { className: "waypoint-separator" }),
2604
- React.createElement("div", { className: "waypoint-type" }),
2605
- React.createElement("div", { className: "waypoint-separator" })));
3093
+ secondaryCode && (React.createElement(React.Fragment, null,
3094
+ React.createElement("div", { "data-testid": "waypoint-ch", className: "waypoint-ch font-mono justify-self-end" }, secondaryCode),
3095
+ React.createElement("div", { className: "waypoint-separator" })))));
2606
3096
 
2607
- const zoomValueToTimeScale = (slider) => MIN_ZOOM_MS_PER_PX * Math.pow(MAX_ZOOM_MS_PER_PX / MIN_ZOOM_MS_PER_PX, slider / 100);
2608
- const timeScaleToZoomValue = (timeScale) => (100 * Math.log(timeScale / MIN_ZOOM_MS_PER_PX)) /
2609
- Math.log(MAX_ZOOM_MS_PER_PX / MIN_ZOOM_MS_PER_PX);
3097
+ const Manchette = ({ zoomYIn, zoomYOut, resetZoom, yZoom = 1, contents, activeWaypointId, activeWaypointRef, isProportional = true, toggleMode, children, height = INITIAL_OP_LIST_HEIGHT, width = 295, hidePositions = false, translations, }) => (React.createElement("div", { className: "ui-manchette-container", style: { width: `${width}px` } },
3098
+ React.createElement("div", { className: "bg-white-100 border-r border-grey-30 relative", style: { height: `${height}px` } },
3099
+ React.createElement("div", { className: "waypoints-list", style: { width: `${width - 1}px` } },
3100
+ contents.map((content, index) => isInteractiveWaypoint(content) ? (React.createElement(Waypoint, { key: content.id, waypoint: content, waypointRef: activeWaypointId === content.id ? activeWaypointRef : undefined, isActive: activeWaypointId === content.id, isMenuActive: !!activeWaypointId, testIdPrefix: "waypoint", hidePositions: hidePositions })) : (React.createElement(Fragment, { key: index }, content))),
3101
+ children)),
3102
+ React.createElement("div", { "data-testid": "manchette-actions", className: "manchette-actions" },
3103
+ React.createElement("div", { className: "zoom-buttons" },
3104
+ React.createElement("button", { "data-testid": "zoom-out-button", className: "zoom-out", onClick: zoomYOut, disabled: yZoom <= MIN_ZOOM_Y || !!activeWaypointId },
3105
+ React.createElement(ZoomOut, null)),
3106
+ React.createElement("button", { "data-testid": "zoom-in-button", className: "zoom-in", onClick: zoomYIn, disabled: yZoom >= MAX_ZOOM_Y || !!activeWaypointId },
3107
+ React.createElement(ZoomIn, null)),
3108
+ React.createElement("button", { "data-testid": "reset-zoom-button", disabled: !!activeWaypointId, className: "zoom-reset", onClick: resetZoom }, "Fit")),
3109
+ React.createElement("div", { className: "flex items-center ml-auto text-sans font-semibold" },
3110
+ React.createElement("button", { disabled: !!activeWaypointId, className: "toggle-mode", onClick: toggleMode },
3111
+ React.createElement("div", { className: "flex flex-col items-end pr-2" },
3112
+ React.createElement("span", { className: cx({ 'text-grey-30': !isProportional }), "data-testid": "km-mode-button" }, "Km"),
3113
+ React.createElement("span", { className: cx({ 'text-grey-30': isProportional }), "data-testid": "linear-mode-button" }, translations?.linearMode || 'Linear')))))));
3114
+
3115
+ const INITIAL_STATE = {
3116
+ xZoom: timeScaleToZoomValue(DEFAULT_ZOOM_MS_PER_PX),
3117
+ yZoom: 1,
3118
+ timeOrigin: 0,
3119
+ spaceOrigin: 0,
3120
+ xOffset: 0,
3121
+ yOffset: 0,
3122
+ scrollTo: null,
3123
+ panning: null,
3124
+ zoomMode: false,
3125
+ rect: null,
3126
+ pixelRect: null,
3127
+ };
2610
3128
  /**
2611
- * min zoom is computed with manchette px height between first and last waypoint.
2612
- * max zoom just the canvas drawing height (without the x-axis scale section)
3129
+ * This hook can be used to synchronize a manchette and a diagram which has a
3130
+ * time scale for X.
3131
+ *
3132
+ * It provides offsets on both axis and functions to handle some
3133
+ * classic behaviors such as zoom, pan and scroll.
2613
3134
  */
2614
- const getExtremaScales = (drawingHeightWithoutTopPadding, drawingHeightWithoutBothPadding, pathLengthMillimeter) => ({
2615
- minZoomMillimeterPerPx: pathLengthMillimeter / drawingHeightWithoutBothPadding,
2616
- maxZoomMillimeterPerPx: MAX_ZOOM_MANCHETTE_HEIGHT_MILLIMETER / drawingHeightWithoutTopPadding,
2617
- });
2618
- const zoomValueToSpaceScale = (minZoomMillimeterPerPx, maxZoomMillimeterPerPx, slider) => minZoomMillimeterPerPx *
2619
- Math.pow(maxZoomMillimeterPerPx / minZoomMillimeterPerPx, (slider - MIN_ZOOM_Y) / (MAX_ZOOM_Y - MIN_ZOOM_Y));
2620
- const spaceScaleToZoomValue = (minZoomMillimeterPerPx, maxZoomMillimeterPerPx, spaceScale) => ((MAX_ZOOM_Y - MIN_ZOOM_Y) * Math.log(spaceScale / minZoomMillimeterPerPx)) /
2621
- Math.log(maxZoomMillimeterPerPx / minZoomMillimeterPerPx) +
2622
- MIN_ZOOM_Y;
2623
- /** Zoom on X axis and center on the mouse position */
2624
- const zoomX = (currentZoom, currentOffset, newZoom, position) => {
2625
- const boundedZoom = clamp$1(newZoom, MIN_ZOOM_X, MAX_ZOOM_X);
2626
- const oldTimeScale = zoomValueToTimeScale(currentZoom);
2627
- const newTimeScale = zoomValueToTimeScale(boundedZoom);
2628
- const newOffset = position - ((position - currentOffset) * oldTimeScale) / newTimeScale;
2629
- return {
2630
- xZoom: boundedZoom,
2631
- xOffset: newOffset,
2632
- };
2633
- };
2634
- const filterVisibleElements$1 = (elements, totalDistance, heightWithoutFinalWaypoint, minSpace) => {
2635
- const getPosition = (waypoint) => (waypoint.position / totalDistance) * heightWithoutFinalWaypoint;
2636
- const firstElement = elements.at(0);
2637
- const lastElement = elements.at(-1);
2638
- if (!firstElement || !lastElement)
2639
- return elements;
2640
- const sortedElements = [...elements].sort((a, b) => (b.weight ?? 0) - (a.weight ?? 0));
2641
- const displayedElements = [firstElement, lastElement];
2642
- for (const element of sortedElements) {
2643
- const hasSpace = !displayedElements.some((displayed) => Math.abs(getPosition(element) - getPosition(displayed)) < minSpace);
2644
- if (hasSpace) {
2645
- displayedElements.push(element);
3135
+ const useSyncManchette = ({ manchetteWithSpaceTimeChartRef, diagramRef, initialState = {
3136
+ timeOrigin: 0,
3137
+ spaceOrigin: 0,
3138
+ xOffset: 0,
3139
+ }, maxYZoom = MAX_ZOOM_Y, enableTimeZoom = true, }) => {
3140
+ const [isShiftPressed, setIsShiftPressed] = useState(false);
3141
+ const [state, setState] = useState({
3142
+ ...INITIAL_STATE,
3143
+ timeOrigin: initialState.timeOrigin || 0,
3144
+ spaceOrigin: initialState.spaceOrigin || 0,
3145
+ xOffset: initialState.xOffset || 0,
3146
+ });
3147
+ const { yZoom, yOffset, scrollTo, rect } = state;
3148
+ // =========== Shift pressed ===========
3149
+ const handleKeyDown = useCallback((event) => {
3150
+ if (event.key === 'Shift') {
3151
+ setIsShiftPressed(true);
3152
+ }
3153
+ }, []);
3154
+ const handleKeyUp = useCallback((event) => {
3155
+ if (event.key === 'Shift') {
3156
+ setIsShiftPressed(false);
3157
+ }
3158
+ }, []);
3159
+ useEffect(() => {
3160
+ window.addEventListener('keydown', handleKeyDown);
3161
+ window.addEventListener('keyup', handleKeyUp);
3162
+ return () => {
3163
+ window.removeEventListener('keydown', handleKeyDown);
3164
+ window.removeEventListener('keyup', handleKeyUp);
3165
+ };
3166
+ }, [handleKeyDown, handleKeyUp]);
3167
+ // =========== Y Zoom ===========
3168
+ const zoomYIn = useCallback(() => {
3169
+ const newYZoom = Math.min(yZoom + ZOOM_Y_DELTA, maxYZoom);
3170
+ if (newYZoom !== yZoom) {
3171
+ const newYOffset = yOffset * (newYZoom / yZoom);
3172
+ setState((prev) => ({
3173
+ ...prev,
3174
+ yZoom: newYZoom,
3175
+ yOffset: newYOffset,
3176
+ scrollTo: newYOffset,
3177
+ }));
3178
+ }
3179
+ }, [yZoom, maxYZoom, yOffset]);
3180
+ const zoomYOut = useCallback(() => {
3181
+ const newYZoom = Math.max(MIN_ZOOM_Y, yZoom - ZOOM_Y_DELTA);
3182
+ if (newYZoom !== yZoom) {
3183
+ const newYOffset = yOffset * (newYZoom / yZoom);
3184
+ setState((prev) => ({
3185
+ ...prev,
3186
+ yZoom: newYZoom,
3187
+ yOffset: newYOffset,
3188
+ scrollTo: newYOffset,
3189
+ }));
3190
+ }
3191
+ }, [yZoom, yOffset]);
3192
+ const resetYZoom = useCallback(() => {
3193
+ setState((prev) => ({ ...prev, yZoom: 1 }));
3194
+ }, []);
3195
+ // =========== X Zoom ===========
3196
+ const handleXZoom = useCallback((newXZoom, xPosition = (diagramRef?.current?.offsetWidth || 0) / 2) => {
3197
+ if (enableTimeZoom)
3198
+ setState((prev) => ({
3199
+ ...prev,
3200
+ ...zoomX(prev.xZoom, prev.xOffset, newXZoom, xPosition),
3201
+ }));
3202
+ }, [enableTimeZoom, diagramRef]);
3203
+ const handleXZoomOnWheelEvent = useCallback((wheelEvent, newXZoom, xPosition) => {
3204
+ if (isShiftPressed && !rect) {
3205
+ wheelEvent.preventDefault();
3206
+ handleXZoom(newXZoom, xPosition);
3207
+ }
3208
+ }, [handleXZoom, isShiftPressed, rect]);
3209
+ // =========== Y Scroll ===========
3210
+ const handleScrollInManchette = useCallback((e) => {
3211
+ if (rect) {
3212
+ e.preventDefault();
3213
+ return;
3214
+ }
3215
+ if (!isShiftPressed && manchetteWithSpaceTimeChartRef.current) {
3216
+ const { scrollTop } = manchetteWithSpaceTimeChartRef.current;
3217
+ if (scrollTop || scrollTop === 0) {
3218
+ setState((prev) => ({ ...prev, yOffset: scrollTop }));
3219
+ }
3220
+ }
3221
+ }, [isShiftPressed, manchetteWithSpaceTimeChartRef, rect]);
3222
+ useEffect(() => {
3223
+ if (scrollTo !== null && manchetteWithSpaceTimeChartRef.current) {
3224
+ manchetteWithSpaceTimeChartRef.current.scrollTo({
3225
+ top: scrollTo,
3226
+ behavior: 'instant',
3227
+ });
2646
3228
  }
2647
- }
2648
- return displayedElements.sort((a, b) => a.position - b.position);
2649
- };
2650
- const selectWaypointsToDisplay = (waypoints, { height, isProportional, yZoom }) => {
2651
- if (waypoints.length < 2)
2652
- return [];
2653
- // display all waypoints in linear mode
2654
- if (!isProportional)
2655
- return waypoints;
2656
- const totalDistance = calcTotalDistance(waypoints);
2657
- const manchetteHeight = getHeightWithoutLastWaypoint(height);
2658
- // in proportional mode, hide some waypoints to avoid collisions
2659
- const minSpace = BASE_WAYPOINT_HEIGHT / yZoom;
2660
- return filterVisibleElements$1(waypoints, totalDistance, manchetteHeight, minSpace);
2661
- };
2662
- /**
2663
- * 2 modes for space scales
2664
- * km (isProportional): { coefficient: gives a scale in meter/pixel }
2665
- * linear: { size: height in pixel } (each point distributed evenly along the height of manchette.)
2666
- */
2667
- const getScales = (waypoints, { isProportional, yZoom, height }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx) => {
2668
- if (!waypoints.length)
2669
- return [];
2670
- if (waypoints.length === 1) {
2671
- const waypoint = waypoints[0];
2672
- return [
2673
- {
2674
- from: waypoint.position,
2675
- to: waypoint.position,
2676
- size: height || 1,
2677
- },
2678
- ];
2679
- }
2680
- if (!isProportional) {
2681
- return waypoints.slice(0, -1).map((from, index) => {
2682
- const to = waypoints[index + 1];
3229
+ }, [scrollTo, manchetteWithSpaceTimeChartRef]);
3230
+ // =========== On Pan ===========
3231
+ const basicOnPan = useCallback((payload, prev) => {
3232
+ if (!payload.isPanning) {
2683
3233
  return {
2684
- from: from.position,
2685
- to: to.position,
2686
- size: BASE_WAYPOINT_HEIGHT * yZoom,
3234
+ ...prev,
3235
+ panning: null,
3236
+ zoomMode: false,
2687
3237
  };
2688
- });
2689
- }
2690
- const from = waypoints.at(0).position;
2691
- const to = waypoints.at(-1).position;
2692
- const scaleCoeff = isProportional
2693
- ? { coefficient: zoomValueToSpaceScale(minZoomMillimeterPerPx, maxZoomMillimeterPerPx, yZoom) }
2694
- : { size: BASE_WAYPOINT_HEIGHT * (waypoints.length - 1) * yZoom };
2695
- return [
2696
- {
2697
- from,
2698
- to,
2699
- ...scaleCoeff,
2700
- },
2701
- ];
3238
+ }
3239
+ if (!prev.panning) {
3240
+ return {
3241
+ ...prev,
3242
+ panning: { initialOffset: { x: prev.xOffset, y: prev.yOffset } },
3243
+ };
3244
+ }
3245
+ const newState = { ...prev };
3246
+ const { initialOffset } = prev.panning;
3247
+ const diff = getDistance$1(payload.initialPosition, payload.position);
3248
+ const manchette = manchetteWithSpaceTimeChartRef.current;
3249
+ newState.xOffset = initialOffset.x + diff.x;
3250
+ let newYOffset = initialOffset.y - diff.y;
3251
+ newYOffset = Math.max(newYOffset, 0);
3252
+ if (manchette) {
3253
+ newYOffset = Math.min(newYOffset, manchette.scrollHeight - manchette.offsetHeight);
3254
+ manchette.scrollTop = newYOffset;
3255
+ }
3256
+ newState.yOffset = newYOffset;
3257
+ return newState;
3258
+ }, [manchetteWithSpaceTimeChartRef]);
3259
+ return useMemo(() => ({
3260
+ state,
3261
+ setState,
3262
+ handleScrollInManchette,
3263
+ handleXZoom,
3264
+ handleXZoomOnWheelEvent,
3265
+ yZoomHelpers: { zoomYIn, zoomYOut, resetZoom: resetYZoom },
3266
+ basicOnPan,
3267
+ }), [
3268
+ state,
3269
+ handleScrollInManchette,
3270
+ handleXZoom,
3271
+ handleXZoomOnWheelEvent,
3272
+ zoomYIn,
3273
+ zoomYOut,
3274
+ resetYZoom,
3275
+ basicOnPan,
3276
+ ]);
2702
3277
  };
2703
- const isInteractiveWaypoint = (item) => item != null && typeof item === 'object' && 'id' in item && 'position' in item;
2704
-
2705
- const Manchette = ({ zoomYIn, zoomYOut, resetZoom, yZoom = 1, contents, activeWaypointId, activeWaypointRef, isProportional = true, toggleMode, children, height = INITIAL_OP_LIST_HEIGHT, }) => (React.createElement("div", { className: "ui-manchette-container" },
2706
- React.createElement("div", { className: "bg-white-100 border-r border-grey-30 relative", style: { minHeight: `${height}px` } },
2707
- React.createElement("div", { className: "waypoints-list" },
2708
- contents.map((content, index) => isInteractiveWaypoint(content) ? (React.createElement("div", { key: index, className: "waypoint-wrapper flex justify-start", style: content.styles },
2709
- React.createElement(Waypoint, { waypoint: content, waypointRef: activeWaypointId === content.id ? activeWaypointRef : undefined, isActive: activeWaypointId === content.id, isMenuActive: !!activeWaypointId, testIdPrefix: "waypoint" }))) : (React.createElement(Fragment, { key: index }, content))),
2710
- children)),
2711
- React.createElement("div", { "data-testid": "manchette-actions", className: "manchette-actions" },
2712
- React.createElement("div", { className: "zoom-buttons" },
2713
- React.createElement("button", { "data-testid": "zoom-out-button", className: "zoom-out", onClick: zoomYOut, disabled: yZoom <= MIN_ZOOM_Y || !!activeWaypointId },
2714
- React.createElement(ZoomOut, null)),
2715
- React.createElement("button", { "data-testid": "zoom-in-button", className: "zoom-in", onClick: zoomYIn, disabled: yZoom >= MAX_ZOOM_Y || !!activeWaypointId },
2716
- React.createElement(ZoomIn, null)),
2717
- React.createElement("button", { "data-testid": "reset-zoom-button", disabled: !!activeWaypointId, className: "zoom-reset", onClick: resetZoom }, "Fit")),
2718
- React.createElement("div", { className: "flex items-center ml-auto text-sans font-semibold" },
2719
- React.createElement("button", { disabled: !!activeWaypointId, className: "toggle-mode", onClick: toggleMode },
2720
- React.createElement("div", { className: "flex flex-col items-end pr-2" },
2721
- React.createElement("span", { className: cx({ 'text-grey-30': !isProportional }), "data-testid": "km-mode-button" }, "Km"),
2722
- React.createElement("span", { className: cx({ 'text-grey-30': isProportional }), "data-testid": "linear-mode-button" }, "Lin\u00E9aire")))))));
2723
3278
 
2724
3279
  const DEFAULT_MANCHETTE_WITH_SPACE_TIME_CHART_OPTIONS = {
2725
3280
  displayTimeCaptions: true,
@@ -2727,36 +3282,32 @@ const DEFAULT_MANCHETTE_WITH_SPACE_TIME_CHART_OPTIONS = {
2727
3282
  enableSpacePan: true,
2728
3283
  enableTimeZoom: true,
2729
3284
  };
2730
- const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChartRef, height = INITIAL_SPACE_TIME_CHART_HEIGHT, spaceTimeChartRef, defaultTimeOrigin = 0, defaultSpaceOrigin = 0, defaultXOffset = 0, verticalPadding = BASE_WAYPOINT_HEIGHT / 2, splitPoints = [], options = {}, }) => {
2731
- const { displayTimeCaptions, enableTimePan, enableSpacePan, enableTimeZoom } = useMemo(() => ({
3285
+ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChartRef, height = INITIAL_SPACE_TIME_CHART_HEIGHT, spaceTimeChartRef, defaultTimeOrigin = 0, defaultSpaceOrigin = 0, defaultXOffset = 0, verticalPadding = BASE_WAYPOINT_HEIGHT * 1.5, splitPoints = [], options = {}, }) => {
3286
+ const canvasDrawingHeight = Math.max(1 + BASE_WAYPOINT_HEIGHT, height - FOOTER_HEIGHT); // 521
3287
+ const drawingHeightWithoutTopPadding = canvasDrawingHeight - verticalPadding; // 473
3288
+ const drawingHeightWithoutBothPadding = canvasDrawingHeight - (verticalPadding + BASE_WAYPOINT_HEIGHT); // 441
3289
+ const { displayTimeCaptions, enableTimeZoom } = useMemo(() => ({
2732
3290
  ...DEFAULT_MANCHETTE_WITH_SPACE_TIME_CHART_OPTIONS,
2733
3291
  ...options,
2734
3292
  }), [options]);
2735
- const [isShiftPressed, setIsShiftPressed] = useState(false);
2736
- const [state, setState] = useState({
2737
- xZoom: timeScaleToZoomValue(DEFAULT_ZOOM_MS_PER_PX),
2738
- yZoom: 1,
2739
- timeOrigin: defaultTimeOrigin,
2740
- spaceOrigin: defaultSpaceOrigin,
2741
- xOffset: defaultXOffset,
2742
- yOffset: 0,
2743
- scrollTo: null,
2744
- panning: null,
2745
- zoomMode: false,
2746
- rect: null,
2747
- pixelRect: null,
2748
- isProportional: true,
2749
- waypointsChart: [],
2750
- scales: [],
3293
+ const [isProportional, setIsPropotional] = useState(true);
3294
+ const { state: { xZoom, yZoom, timeOrigin, spaceOrigin, xOffset, yOffset, zoomMode, rect }, setState: setSyncManchetteState, handleScrollInManchette, handleXZoom, handleXZoomOnWheelEvent, yZoomHelpers: { zoomYIn, zoomYOut, resetZoom }, basicOnPan, } = useSyncManchette({
3295
+ manchetteWithSpaceTimeChartRef,
3296
+ diagramRef: spaceTimeChartRef,
3297
+ initialState: {
3298
+ timeOrigin: defaultTimeOrigin,
3299
+ spaceOrigin: defaultSpaceOrigin,
3300
+ xOffset: defaultXOffset,
3301
+ },
3302
+ maxYZoom: isProportional
3303
+ ? MAX_ZOOM_Y
3304
+ : (drawingHeightWithoutTopPadding - BASE_WAYPOINT_HEIGHT) / (2 * BASE_WAYPOINT_HEIGHT),
3305
+ enableTimeZoom,
2751
3306
  });
2752
- const { xZoom, yZoom, timeOrigin, spaceOrigin, xOffset, yOffset, scrollTo, panning, zoomMode, rect, isProportional, } = state;
2753
3307
  /** used when we change the train dataset for example to center the chart on the new data */
2754
3308
  const setTimeOrigin = useCallback((newTimeOrigin) => {
2755
- setState((prev) => ({ ...prev, timeOrigin: newTimeOrigin }));
2756
- }, []);
2757
- const canvasDrawingHeight = Math.max(1 + BASE_WAYPOINT_HEIGHT, height - FOOTER_HEIGHT); // 521
2758
- const drawingHeightWithoutTopPadding = canvasDrawingHeight - BASE_WAYPOINT_HEIGHT / 2; // 505
2759
- const drawingHeightWithoutBothPadding = canvasDrawingHeight - BASE_WAYPOINT_HEIGHT; // 489
3309
+ setSyncManchetteState((prev) => ({ ...prev, timeOrigin: newTimeOrigin }));
3310
+ }, [setSyncManchetteState]);
2760
3311
  const totalDistance = calcTotalDistance(waypoints);
2761
3312
  const { minZoomMillimeterPerPx, maxZoomMillimeterPerPx } = getExtremaScales(drawingHeightWithoutTopPadding, drawingHeightWithoutBothPadding, totalDistance);
2762
3313
  const handleRectZoomEnd = useCallback((prev) => {
@@ -2772,7 +3323,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2772
3323
  const newXOffset = sideOffset(prev.timeOrigin, newTimeScale, prev.rect.timeStart, prev.rect.timeEnd, spaceTimeChartRef.current.clientWidth);
2773
3324
  let newYZoom = prev.yZoom;
2774
3325
  let newYOffset = prev.yOffset;
2775
- if (prev.isProportional) {
3326
+ if (isProportional) {
2776
3327
  const chosenSpaceScale = spaceRange / drawingHeightWithoutTopPadding;
2777
3328
  const newSpaceScale = clamp$1(chosenSpaceScale, maxZoomMillimeterPerPx, minZoomMillimeterPerPx);
2778
3329
  // we don’t need to handle this case and compute an offset
@@ -2808,93 +3359,19 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2808
3359
  };
2809
3360
  }, [
2810
3361
  spaceTimeChartRef,
3362
+ isProportional,
2811
3363
  drawingHeightWithoutTopPadding,
2812
3364
  maxZoomMillimeterPerPx,
2813
3365
  minZoomMillimeterPerPx,
2814
3366
  height,
2815
3367
  verticalPadding,
2816
3368
  ]);
2817
- const zoomYIn = useCallback(() => {
2818
- const maxZoom = isProportional
2819
- ? MAX_ZOOM_Y
2820
- : (drawingHeightWithoutTopPadding - BASE_WAYPOINT_HEIGHT) / (2 * BASE_WAYPOINT_HEIGHT);
2821
- const newYZoom = Math.min(yZoom + ZOOM_Y_DELTA, maxZoom);
2822
- if (newYZoom !== yZoom) {
2823
- const newYOffset = yOffset * (newYZoom / yZoom);
2824
- setState((prev) => ({
2825
- ...prev,
2826
- yZoom: newYZoom,
2827
- yOffset: newYOffset,
2828
- scrollTo: newYOffset,
2829
- }));
2830
- }
2831
- }, [yZoom, yOffset, drawingHeightWithoutTopPadding, isProportional]);
2832
- const zoomYOut = useCallback(() => {
2833
- const newYZoom = Math.max(MIN_ZOOM_Y, yZoom - ZOOM_Y_DELTA);
2834
- if (newYZoom !== yZoom) {
2835
- const newYOffset = yOffset * (newYZoom / yZoom);
2836
- setState((prev) => ({
2837
- ...prev,
2838
- yZoom: newYZoom,
2839
- yOffset: newYOffset,
2840
- scrollTo: newYOffset,
2841
- }));
2842
- }
2843
- }, [yZoom, yOffset]);
2844
- useEffect(() => {
2845
- if (scrollTo !== null && manchetteWithSpaceTimeChartRef.current) {
2846
- manchetteWithSpaceTimeChartRef.current.scrollTo({
2847
- top: scrollTo,
2848
- behavior: 'instant',
2849
- });
2850
- }
2851
- }, [scrollTo, manchetteWithSpaceTimeChartRef]);
2852
- const resetZoom = useCallback(() => {
2853
- setState((prev) => ({ ...prev, yZoom: 1 }));
2854
- }, []);
2855
- const handleScroll = useCallback((e) => {
2856
- if (rect) {
2857
- e.preventDefault();
2858
- return;
2859
- }
2860
- if (!isShiftPressed && manchetteWithSpaceTimeChartRef.current) {
2861
- const { scrollTop } = manchetteWithSpaceTimeChartRef.current;
2862
- if (scrollTop || scrollTop === 0) {
2863
- setState((prev) => ({ ...prev, yOffset: scrollTop }));
2864
- }
2865
- }
2866
- }, [isShiftPressed, manchetteWithSpaceTimeChartRef, rect]);
2867
- const handleKeyDown = useCallback((event) => {
2868
- if (event.key === 'Shift') {
2869
- setIsShiftPressed(true);
2870
- }
2871
- }, []);
2872
- const handleKeyUp = useCallback((event) => {
2873
- if (event.key === 'Shift') {
2874
- setIsShiftPressed(false);
2875
- }
2876
- }, []);
2877
- useEffect(() => {
2878
- window.addEventListener('keydown', handleKeyDown);
2879
- window.addEventListener('keyup', handleKeyUp);
2880
- return () => {
2881
- window.removeEventListener('keydown', handleKeyDown);
2882
- window.removeEventListener('keyup', handleKeyUp);
2883
- };
2884
- }, [handleKeyDown, handleKeyUp]);
2885
3369
  const toggleMode = useCallback(() => {
2886
- setState((prev) => ({ ...prev, isProportional: !prev.isProportional }));
3370
+ setIsPropotional((prev) => !prev);
2887
3371
  }, []);
2888
3372
  const toggleZoomMode = useCallback(() => {
2889
- setState((prev) => ({ ...prev, zoomMode: !prev.zoomMode }));
2890
- }, []);
2891
- const handleXZoom = useCallback((newXZoom, xPosition = (spaceTimeChartRef?.current?.offsetWidth || 0) / 2) => {
2892
- if (enableTimeZoom)
2893
- setState((prev) => ({
2894
- ...prev,
2895
- ...zoomX(prev.xZoom, prev.xOffset, newXZoom, xPosition),
2896
- }));
2897
- }, [enableTimeZoom, spaceTimeChartRef]);
3373
+ setSyncManchetteState((prev) => ({ ...prev, zoomMode: !prev.zoomMode }));
3374
+ }, [setSyncManchetteState]);
2898
3375
  const spaceScales = useMemo(() => {
2899
3376
  // Here, we first compute the base scales, and then we insert a flat step for each split point:
2900
3377
  const baseScales = getScales(waypoints, { height, isProportional, yZoom }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx);
@@ -2973,10 +3450,10 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2973
3450
  }), [waypoints, height, isProportional, yZoom]);
2974
3451
  const { manchetteContents, manchetteHeight } = useMemo(() => {
2975
3452
  const spaceScaleTree = spaceScalesToBinaryTree(spaceOrigin, spaceScales);
2976
- const getSpacePixel = getSpaceToPixel(0, spaceScaleTree);
3453
+ const getSpacePixel = getSpaceToPixel(BASE_WAYPOINT_HEIGHT, spaceScaleTree);
2977
3454
  let totalManchetteHeight = height - FOOTER_HEIGHT;
2978
3455
  if (spaceScales.length > 0) {
2979
- totalManchetteHeight = Math.max(totalManchetteHeight, getSpacePixel(spaceScales.at(-1).to, true) + verticalPadding * 2);
3456
+ totalManchetteHeight = Math.max(totalManchetteHeight, getSpacePixel(spaceScales.at(-1).to, true) + BASE_WAYPOINT_HEIGHT);
2980
3457
  }
2981
3458
  // Identify all manchette contents (split sections and waypoints):
2982
3459
  const splitPointPositions = new Set(splitPoints.map((point) => point.position) || []);
@@ -3019,11 +3496,11 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
3019
3496
  const top = getSpacePixel(position);
3020
3497
  finalContents.push(React.createElement("div", { style: {
3021
3498
  // This verticalPadding correction is there because:
3022
- // - Waypoints are positioned so that their lines (at verticalPadding pixels from
3499
+ // - Waypoints are positioned so that their lines (at 16 pixels from
3023
3500
  // the top) are aligned with SpaceTimeChart's space lines
3024
3501
  // - Split points are positioned so that their top is aligned with SpaceTimeChart's
3025
3502
  // space lines
3026
- top: `${top + verticalPadding}px`,
3503
+ top: `${top + BASE_WAYPOINT_HEIGHT / 2}px`,
3027
3504
  height: `${getSpacePixel(position, true) - top}px`,
3028
3505
  position: 'absolute',
3029
3506
  width: '100%',
@@ -3036,7 +3513,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
3036
3513
  manchetteHeight: totalManchetteHeight,
3037
3514
  manchetteContents: finalContents,
3038
3515
  };
3039
- }, [spaceOrigin, spaceScales, verticalPadding, height, splitPoints, waypointsToDisplay]);
3516
+ }, [spaceOrigin, spaceScales, height, splitPoints, waypointsToDisplay]);
3040
3517
  return useMemo(() => ({
3041
3518
  manchetteProps: {
3042
3519
  contents: manchetteContents,
@@ -3063,19 +3540,15 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
3063
3540
  spaceOrigin,
3064
3541
  spaceScales,
3065
3542
  onZoom: ({ delta, position, event, }) => {
3066
- if (isShiftPressed && !rect) {
3067
- event.preventDefault();
3068
- handleXZoom(xZoom + delta, position.x);
3069
- }
3543
+ handleXZoomOnWheelEvent(event, xZoom + delta, position.x);
3070
3544
  },
3071
3545
  onPan: (payload) => {
3072
3546
  const { initialData, data, initialPosition, position, isPanning, context: { width, getData }, } = payload;
3073
- const diff = getDistance(initialPosition, position);
3074
- setState((prev) => {
3075
- if (!isPanning) {
3547
+ setSyncManchetteState((prev) => {
3548
+ if (!isPanning && prev.zoomMode && prev.rect) {
3076
3549
  return {
3077
3550
  ...prev,
3078
- ...(prev.zoomMode && prev.rect ? handleRectZoomEnd(prev) : {}),
3551
+ ...handleRectZoomEnd(prev),
3079
3552
  panning: null,
3080
3553
  zoomMode: false,
3081
3554
  };
@@ -3107,32 +3580,11 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
3107
3580
  pixelRect: newPixelRect,
3108
3581
  };
3109
3582
  }
3110
- if (!panning) {
3111
- return {
3112
- ...prev,
3113
- panning: { initialOffset: { x: xOffset, y: yOffset } },
3114
- };
3115
- }
3116
- const newState = { ...prev };
3117
- const { initialOffset } = panning;
3118
- const manchette = manchetteWithSpaceTimeChartRef.current;
3119
- if (enableTimePan) {
3120
- newState.xOffset = initialOffset.x + diff.x;
3121
- }
3122
- if (enableSpacePan) {
3123
- let newYOffset = initialOffset.y - diff.y;
3124
- newYOffset = Math.max(newYOffset, 0);
3125
- if (manchette) {
3126
- newYOffset = Math.min(newYOffset, manchette.scrollHeight - manchette.offsetHeight);
3127
- manchette.scrollTop = newYOffset;
3128
- }
3129
- newState.yOffset = newYOffset;
3130
- }
3131
- return newState;
3583
+ return basicOnPan(payload, prev);
3132
3584
  });
3133
3585
  },
3134
3586
  },
3135
- handleScroll,
3587
+ handleScroll: handleScrollInManchette,
3136
3588
  handleXZoom,
3137
3589
  xZoom,
3138
3590
  toggleZoomMode,
@@ -3160,52 +3612,38 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
3160
3612
  timeOrigin,
3161
3613
  spaceOrigin,
3162
3614
  spaceScales,
3163
- handleScroll,
3615
+ handleScrollInManchette,
3164
3616
  handleXZoom,
3617
+ handleXZoomOnWheelEvent,
3165
3618
  toggleZoomMode,
3166
3619
  zoomMode,
3167
3620
  rect,
3168
3621
  minZoomMillimeterPerPx,
3169
3622
  maxZoomMillimeterPerPx,
3170
3623
  setTimeOrigin,
3171
- isShiftPressed,
3172
- panning,
3173
- manchetteWithSpaceTimeChartRef,
3174
- enableTimePan,
3175
- enableSpacePan,
3624
+ setSyncManchetteState,
3625
+ basicOnPan,
3176
3626
  handleRectZoomEnd,
3177
3627
  canvasDrawingHeight,
3178
3628
  ]);
3179
3629
  };
3180
3630
 
3181
- const transformCurve = (curve, departureTime) => curve.positions.map((position, i) => ({
3182
- time: curve.times[i] + departureTime.getTime(),
3183
- position,
3184
- }));
3185
- const usePaths = (projectPathTrainResult) => useMemo(() => projectPathTrainResult.flatMap((path) => path.spaceTimeCurves.map((spaceTimeCurve) => ({
3186
- id: path.id,
3187
- label: path.name,
3188
- color: PATH_COLOR_DEFAULT,
3189
- points: transformCurve(spaceTimeCurve, path.departureTime),
3190
- }))), [projectPathTrainResult]);
3191
-
3192
3631
  /**
3193
3632
  * A simple component to display a manchette and a space time chart.
3194
3633
  *
3195
3634
  * This only covers basic usage. For more advanced control over the manchette
3196
3635
  * and space time chart, the useManchetteWithSpaceTimeChart() hook can be used.
3197
3636
  */
3198
- const ManchetteWithSpaceTimeChart = ({ waypoints, projectPathTrainResult, height = INITIAL_SPACE_TIME_CHART_HEIGHT, children, header, manchetteProps: additionalManchetteProps, spaceTimeChartProps: additionalSpaceTimeChartProps, splitPoints, }) => {
3637
+ const ManchetteWithSpaceTimeChart = ({ waypoints, paths, height = INITIAL_SPACE_TIME_CHART_HEIGHT, children, header, manchetteProps: additionalManchetteProps, spaceTimeChartProps: additionalSpaceTimeChartProps, splitPoints, }) => {
3199
3638
  const manchetteWithSpaceTimeChartRef = useRef(null);
3200
3639
  const spaceTimeChartRef = useRef(null);
3201
- const paths = usePaths(projectPathTrainResult);
3202
3640
  const { manchetteProps, spaceTimeChartProps, handleScroll } = useManchetteWithSpaceTimeChart({
3203
3641
  waypoints,
3204
3642
  manchetteWithSpaceTimeChartRef,
3205
3643
  height,
3206
3644
  spaceTimeChartRef,
3207
3645
  splitPoints,
3208
- defaultTimeOrigin: Math.min(...projectPathTrainResult.map((p) => +p.departureTime)),
3646
+ defaultTimeOrigin: Math.min(...paths.map((p) => p.points[0]?.time)),
3209
3647
  });
3210
3648
  return (React.createElement("div", { className: "ui-manchette-space-time-chart-wrapper" },
3211
3649
  React.createElement("div", { className: "header bg-ambientB-5 w-full border-b border-grey-30", style: { height: '40px' } }, header),
@@ -3218,17 +3656,26 @@ const ManchetteWithSpaceTimeChart = ({ waypoints, projectPathTrainResult, height
3218
3656
  };
3219
3657
 
3220
3658
  const InteractionButtons = ({ reset, openSettingsPanel, store, testIdPrefix, }) => (React.createElement("div", { id: "interaction-button-container", className: "z-10" },
3221
- React.createElement("div", { className: "zoom-buttons" },
3222
- React.createElement("button", { className: cx('interaction-button reset-button', {
3223
- inactive: store.ratioX == 1 && store.leftOffset == 0,
3224
- }), onClick: () => reset(), "data-testid": testIdPrefix ? `${testIdPrefix}-reset` : undefined },
3225
- React.createElement(Iterations, null)),
3226
- React.createElement("button", { className: "interaction-button plus-button inactive", "data-testid": testIdPrefix ? `${testIdPrefix}-zoom-in` : undefined },
3227
- React.createElement(Plus, null)),
3228
- React.createElement("button", { className: "interaction-button inactive", "data-testid": testIdPrefix ? `${testIdPrefix}-zoom-out` : undefined },
3229
- React.createElement(Dash, null))),
3230
- React.createElement("button", { className: "interaction-button elipsis-button", "data-testid": testIdPrefix ? `${testIdPrefix}-settings` : undefined, onClick: () => openSettingsPanel() },
3231
- React.createElement(KebabHorizontal, null))));
3659
+ React.createElement("button", { type: "button", className: cx('reset-button', {
3660
+ 'reset-button-disabled': store.ratioX == 1 && store.leftOffset == 0,
3661
+ }), onClick: reset, "data-testid": testIdPrefix ? `${testIdPrefix}-reset` : undefined },
3662
+ React.createElement(Iterations, null)),
3663
+ React.createElement("button", { type: "button", className: "menu-button", "data-testid": testIdPrefix ? `${testIdPrefix}-settings` : undefined, onClick: openSettingsPanel },
3664
+ React.createElement(Sliders, null))));
3665
+
3666
+ var EtcsBrakingType;
3667
+ (function (EtcsBrakingType) {
3668
+ EtcsBrakingType["SLOWDOWN"] = "transition";
3669
+ EtcsBrakingType["STOP"] = "stop";
3670
+ EtcsBrakingType["SPACING"] = "spacing";
3671
+ EtcsBrakingType["ROUTING"] = "routing";
3672
+ })(EtcsBrakingType || (EtcsBrakingType = {}));
3673
+ var EtcsBrakingCurveType;
3674
+ (function (EtcsBrakingCurveType) {
3675
+ EtcsBrakingCurveType["IND"] = "IND";
3676
+ EtcsBrakingCurveType["PS"] = "PS";
3677
+ EtcsBrakingCurveType["GUI"] = "GUI";
3678
+ })(EtcsBrakingCurveType || (EtcsBrakingCurveType = {}));
3232
3679
 
3233
3680
  const SLOPE_FILL_COLOR = '#CFDDCE';
3234
3681
  const RIGHT_TICK_HEIGHT_OFFSET = 2;
@@ -3266,6 +3713,7 @@ const DETAILS_BOX_SELECTION = [
3266
3713
  'energySource',
3267
3714
  'tractionStatus',
3268
3715
  'declivities',
3716
+ 'etcs',
3269
3717
  'electricalProfiles',
3270
3718
  'powerRestrictions',
3271
3719
  ];
@@ -3277,6 +3725,28 @@ const LAYERS_SELECTION = [
3277
3725
  'powerRestrictions',
3278
3726
  'speedLimitTags',
3279
3727
  ];
3728
+ const DEFAULT_ETCS_LAYERS_DISPLAY = {
3729
+ etcsBrakingTypes: {
3730
+ stopsAndTransitions: false,
3731
+ spacing: false,
3732
+ routing: false,
3733
+ },
3734
+ etcsBrakingCurveTypes: {
3735
+ indication: true,
3736
+ permittedSpeed: true,
3737
+ guidance: true,
3738
+ },
3739
+ };
3740
+ const ETCS_BRAKING_SELECTION = {
3741
+ stopsAndTransitions: [EtcsBrakingType.SLOWDOWN, EtcsBrakingType.STOP],
3742
+ spacing: [EtcsBrakingType.SPACING],
3743
+ routing: [EtcsBrakingType.ROUTING],
3744
+ };
3745
+ const ETCS_CURVE_SELECTION = {
3746
+ indication: EtcsBrakingCurveType.IND,
3747
+ permittedSpeed: EtcsBrakingCurveType.PS,
3748
+ guidance: EtcsBrakingCurveType.GUI,
3749
+ };
3280
3750
  // Colors
3281
3751
  const BLACK = chroma(0, 0, 0);
3282
3752
  const ERROR_30 = chroma(255, 104, 104);
@@ -3286,6 +3756,27 @@ const GREY_80$1 = chroma(49, 46, 43);
3286
3756
  const LIGHT_BLUE = chroma(33, 112, 185);
3287
3757
  const WARNING_30 = chroma(234, 167, 43);
3288
3758
  const WHITE = chroma(255, 255, 255);
3759
+ const BASE_SPEED_COLOR = chroma(17, 101, 180);
3760
+ const ECO_SPEED_COLOR = chroma(7, 69, 128);
3761
+ const IND_COLOR = chroma(3, 222, 255);
3762
+ const PS_COLOR = chroma(0, 87, 218);
3763
+ const GUI_COLOR = chroma(255, 192, 3);
3764
+ const IND_ALPHA = 0.3;
3765
+ const PS_ALPHA = 0.24;
3766
+ const GUI_ALPHA = 0.4;
3767
+ const BASE_SPEED_FILL_ALPHA = 0.15;
3768
+ // Etcs color dictionary
3769
+ const ETCS_COLOR_DICTIONARY = {
3770
+ [EtcsBrakingCurveType.IND]: IND_COLOR,
3771
+ [EtcsBrakingCurveType.PS]: PS_COLOR,
3772
+ [EtcsBrakingCurveType.GUI]: GUI_COLOR,
3773
+ };
3774
+ // Etcs color transparency dictionary
3775
+ const ETCS_ALPHA_DICTIONARY = {
3776
+ [EtcsBrakingCurveType.IND]: IND_ALPHA,
3777
+ [EtcsBrakingCurveType.PS]: PS_ALPHA,
3778
+ [EtcsBrakingCurveType.GUI]: GUI_ALPHA,
3779
+ };
3289
3780
  /**
3290
3781
  * COLOR_DICTIONARY maps specific colors to their corresponding secondary colors used for speed limit tags.
3291
3782
  */
@@ -3301,6 +3792,8 @@ const ZOOM_CONFIG = {
3301
3792
  MAX_RATIO: 50,
3302
3793
  SLIDER_WIDTH: 100,
3303
3794
  };
3795
+ const SPEEDS_LINEWIDTH = 0.5;
3796
+ const ETCS_LINEWIDTH = 3;
3304
3797
 
3305
3798
  const getGraphOffsets = (width, height, declivities) => {
3306
3799
  const WIDTH_OFFSET = declivities ? width - 102 : width - 60; // +2px so that the tick appears on the right of the chart
@@ -3378,7 +3871,7 @@ const drawLinearLayerBackground = (ctx, backgroundColor, margins, width, startin
3378
3871
  ctx.fillRect(MARGIN_LEFT, startingHeight - layerHeight + LINEAR_LAYER_SEPARATOR_HEIGHT, width - MARGIN_LEFT - MARGIN_RIGHT, layerHeight);
3379
3872
  };
3380
3873
  /**
3381
- * Return wether a layer should be active or not.
3874
+ * Return whether a layer should be active or not.
3382
3875
  * Depending on the available data, some layers should be disabled.
3383
3876
  */
3384
3877
  const isLayerActive = (store, selection) => {
@@ -3562,9 +4055,17 @@ const getSnappedStop = (cursorX, width, store) => {
3562
4055
  }
3563
4056
  return null;
3564
4057
  };
4058
+ /** Retrieve list of active EtcsBrakingTypes. */
4059
+ const getActiveEtcsBrakingTypes = (layers) => Object.entries(layers.etcsBrakingTypes)
4060
+ .filter(([_, isActive]) => isActive)
4061
+ .flatMap(([key]) => ETCS_BRAKING_SELECTION[key]);
4062
+ /** Retrieve list of active EtcsBrakingCurveTypes. */
4063
+ const getActiveEtcsBrakingCurveTypes = (layers) => Object.entries(layers.etcsBrakingCurveTypes)
4064
+ .filter(([_, isActive]) => isActive)
4065
+ .map(([key]) => ETCS_CURVE_SELECTION[key]);
3565
4066
 
3566
4067
  const SETTINGS_PANEL_BASE_HEIGHT = 442;
3567
- const SettingsPanel = ({ color, store, setStore, setIsMouseHoveringSettingsPanel, adjustHeightOnLayerChange, translations, testIdPrefix, }) => {
4068
+ const SettingsPanel = ({ color, store, setStore, setIsMouseHoveringSettingsPanel, adjustHeightOnLayerChange, translations, testIdPrefix, displayEtcs, }) => {
3568
4069
  const closeSettingsPanel = () => {
3569
4070
  setIsMouseHoveringSettingsPanel(false);
3570
4071
  setStore((prev) => ({
@@ -3572,41 +4073,107 @@ const SettingsPanel = ({ color, store, setStore, setIsMouseHoveringSettingsPanel
3572
4073
  isSettingsPanelOpened: false,
3573
4074
  }));
3574
4075
  };
3575
- return (React.createElement("div", { id: "settings-panel", style: {
4076
+ const stopsAndTransitions = 'stopsAndTransitions';
4077
+ const otherEtcsBrakingTypes = ['spacing', 'routing'];
4078
+ const updateEtcsBrakingType = (etcsBrakingType, newValue) => {
4079
+ setStore((prev) => ({
4080
+ ...prev,
4081
+ etcsLayersDisplay: {
4082
+ ...prev.etcsLayersDisplay,
4083
+ etcsBrakingTypes: {
4084
+ ...prev.etcsLayersDisplay.etcsBrakingTypes,
4085
+ [etcsBrakingType]: newValue !== undefined
4086
+ ? newValue
4087
+ : !prev.etcsLayersDisplay.etcsBrakingTypes[etcsBrakingType],
4088
+ },
4089
+ },
4090
+ }));
4091
+ };
4092
+ return (React.createElement("div", { id: "settings-panel", "data-testid": testIdPrefix, style: {
3576
4093
  background: `rgba(${color.substring(4, color.length - 1)}, 0.4)`,
3577
4094
  height: `${SETTINGS_PANEL_BASE_HEIGHT}px`,
3578
4095
  }, className: "font-sans", onMouseEnter: () => setIsMouseHoveringSettingsPanel(true), onMouseLeave: () => setIsMouseHoveringSettingsPanel(false) },
3579
4096
  React.createElement("div", { className: "settings-panel-section" },
3580
4097
  React.createElement("div", { className: "settings-panel-section-title" },
3581
4098
  React.createElement("span", null, translations?.layersDisplay.context || 'Context')),
3582
- LAYERS_SELECTION.map((selection) => (React.createElement("div", { key: selection, className: "selection" },
3583
- React.createElement(Checkbox, { "data-testid": testIdPrefix ? `${testIdPrefix}-layer-${selection}` : undefined, label: translations?.layersDisplay[selection] || selection, checked: store.layersDisplay[selection], disabled: !isLayerActive(store, selection), onChange: () => {
3584
- setStore((prev) => ({
3585
- ...prev,
3586
- layersDisplay: {
3587
- ...prev.layersDisplay,
3588
- [selection]: !prev.layersDisplay[selection],
4099
+ LAYERS_SELECTION.map((selection) => (React.createElement(Checkbox, { key: selection, "data-testid": testIdPrefix ? `${testIdPrefix}-layer-${selection}` : undefined, label: translations?.layersDisplay[selection] || selection, checked: store.layersDisplay[selection], disabled: !isLayerActive(store, selection), onChange: () => {
4100
+ setStore((prev) => ({
4101
+ ...prev,
4102
+ layersDisplay: {
4103
+ ...prev.layersDisplay,
4104
+ [selection]: !prev.layersDisplay[selection],
4105
+ },
4106
+ }));
4107
+ if (selection === 'electricalProfiles' ||
4108
+ selection === 'powerRestrictions' ||
4109
+ selection === 'speedLimitTags') {
4110
+ adjustHeightOnLayerChange(selection, store.layersDisplay[selection]);
4111
+ }
4112
+ } })))),
4113
+ displayEtcs && (React.createElement("div", { className: "settings-panel-section" },
4114
+ React.createElement("div", { className: "settings-panel-section-title" },
4115
+ React.createElement("span", null, translations?.etcsLayersDisplay.title || 'ETCS')),
4116
+ React.createElement(CheckboxesTree, { id: 'etcs-braking-types', items: [
4117
+ {
4118
+ id: 0,
4119
+ props: {
4120
+ label: translations?.etcsLayersDisplay.etcsBrakingTypes[stopsAndTransitions] ||
4121
+ stopsAndTransitions,
4122
+ checked: store.etcsLayersDisplay.etcsBrakingTypes[stopsAndTransitions],
4123
+ onChange: () => {
4124
+ updateEtcsBrakingType(stopsAndTransitions);
3589
4125
  },
3590
- }));
3591
- if (selection === 'electricalProfiles' ||
3592
- selection === 'powerRestrictions' ||
3593
- selection === 'speedLimitTags') {
3594
- adjustHeightOnLayerChange(selection, store.layersDisplay[selection]);
3595
- }
3596
- } }))))),
3597
- React.createElement("div", { className: "settings-panel-section right" },
4126
+ },
4127
+ },
4128
+ {
4129
+ id: 1,
4130
+ props: {
4131
+ label: translations?.etcsLayersDisplay.etcsBrakingTypes.signals,
4132
+ checked: otherEtcsBrakingTypes.every((key) => store.etcsLayersDisplay.etcsBrakingTypes[key]),
4133
+ isIndeterminate: otherEtcsBrakingTypes.some((key) => store.etcsLayersDisplay.etcsBrakingTypes[key]) &&
4134
+ !otherEtcsBrakingTypes.every((key) => store.etcsLayersDisplay.etcsBrakingTypes[key]),
4135
+ onChange: () => {
4136
+ const newValue = !otherEtcsBrakingTypes.every((key) => store.etcsLayersDisplay.etcsBrakingTypes[key]);
4137
+ otherEtcsBrakingTypes.map((etcsBrakingType) => updateEtcsBrakingType(etcsBrakingType, newValue));
4138
+ },
4139
+ },
4140
+ items: otherEtcsBrakingTypes.map((etcsBrakingType, index) => ({
4141
+ id: index + 2,
4142
+ props: {
4143
+ label: translations?.etcsLayersDisplay.etcsBrakingTypes[etcsBrakingType] ||
4144
+ etcsBrakingType,
4145
+ checked: store.etcsLayersDisplay.etcsBrakingTypes[etcsBrakingType],
4146
+ onChange: () => {
4147
+ updateEtcsBrakingType(etcsBrakingType);
4148
+ },
4149
+ },
4150
+ })),
4151
+ },
4152
+ ] }),
4153
+ getActiveEtcsBrakingTypes(store.etcsLayersDisplay).length > 0 && (React.createElement("div", { className: "bottom-panel" }, Object.keys(ETCS_CURVE_SELECTION).map((selection) => (React.createElement(Checkbox, { key: selection, label: translations?.etcsLayersDisplay.etcsBrakingCurveTypes[selection] || selection, checked: store.etcsLayersDisplay.etcsBrakingCurveTypes[selection], onChange: () => {
4154
+ setStore((prev) => ({
4155
+ ...prev,
4156
+ etcsLayersDisplay: {
4157
+ ...prev.etcsLayersDisplay,
4158
+ etcsBrakingCurveTypes: {
4159
+ ...prev.etcsLayersDisplay.etcsBrakingCurveTypes,
4160
+ [selection]: !prev.etcsLayersDisplay.etcsBrakingCurveTypes[selection],
4161
+ },
4162
+ },
4163
+ }));
4164
+ } }))))))),
4165
+ React.createElement("div", { className: "settings-panel-section" },
3598
4166
  React.createElement("div", { className: "settings-panel-section-title" },
3599
4167
  React.createElement("span", null, translations?.detailsBoxDisplay.reticleInfos || 'Reticle infos')),
3600
- DETAILS_BOX_SELECTION.map((selection) => (React.createElement("div", { key: selection, className: "selection" },
3601
- React.createElement(Checkbox, { label: translations?.detailsBoxDisplay[selection] || selection, checked: store.detailsBoxDisplay[selection], onChange: () => {
3602
- setStore((prev) => ({
3603
- ...prev,
3604
- detailsBoxDisplay: {
3605
- ...prev.detailsBoxDisplay,
3606
- [selection]: !prev.detailsBoxDisplay[selection],
3607
- },
3608
- }));
3609
- } }))))),
4168
+ DETAILS_BOX_SELECTION.filter((detail_box) => detail_box !== 'etcs' || displayEtcs).map((selection) => (React.createElement(Checkbox, { key: selection, label: translations?.detailsBoxDisplay[selection] || selection, checked: store.detailsBoxDisplay[selection], onChange: () => {
4169
+ setStore((prev) => ({
4170
+ ...prev,
4171
+ detailsBoxDisplay: {
4172
+ ...prev.detailsBoxDisplay,
4173
+ [selection]: !prev.detailsBoxDisplay[selection],
4174
+ },
4175
+ }));
4176
+ } })))),
3610
4177
  React.createElement("button", { id: "close-settings-panel", "data-testid": testIdPrefix ? `${testIdPrefix}-close` : undefined, onClick: () => closeSettingsPanel() },
3611
4178
  React.createElement("span", null,
3612
4179
  React.createElement(X, null)))));
@@ -3849,9 +4416,7 @@ const computeCurvePoints = (canvasConfig, curveConfig, specificSpeeds) => {
3849
4416
  return points;
3850
4417
  };
3851
4418
  const drawCurve = ({ ctx, width, height, store }) => {
3852
- const { speeds, ecoSpeeds, ratioX, leftOffset } = store;
3853
- const baseSpeedColor = chroma(17, 101, 180);
3854
- const ecoSpeedColor = chroma(7, 69, 128);
4419
+ const { speeds, ecoSpeeds, etcsBrakingCurves, ratioX, leftOffset } = store;
3855
4420
  clearCanvas(ctx, width, height);
3856
4421
  ctx.save();
3857
4422
  ctx.translate(leftOffset, 0);
@@ -3859,35 +4424,64 @@ const drawCurve = ({ ctx, width, height, store }) => {
3859
4424
  const maxPosition = maxPositionValue(store.speeds);
3860
4425
  const curvePoints = computeCurvePoints({ width, height }, { maxSpeed, maxPosition, ratioX }, speeds);
3861
4426
  const ecoCurvePoints = computeCurvePoints({ width, height }, { maxSpeed, maxPosition, ratioX }, ecoSpeeds);
3862
- // Curves must be drawn twice one for the fill and one for the stroke
4427
+ // Curves must be drawn twice, once for the fill and once for the stroke.
3863
4428
  // The stroke must not draw the last two points. They're only present to close the shape but are not part of the curve.
4429
+ ctx.lineWidth = SPEEDS_LINEWIDTH;
4430
+ // Fill speed curve.
3864
4431
  ctx.beginPath();
3865
- ctx.lineWidth = 0.5;
3866
- ctx.strokeStyle = baseSpeedColor.hex();
3867
- ctx.fillStyle = baseSpeedColor.alpha(0.15).hex();
4432
+ ctx.fillStyle = BASE_SPEED_COLOR.alpha(BASE_SPEED_FILL_ALPHA).hex();
3868
4433
  curvePoints.forEach(({ x, y }) => {
3869
4434
  ctx.lineTo(x, y);
3870
4435
  });
3871
4436
  ctx.fill();
4437
+ // Stroke speed curve.
3872
4438
  ctx.beginPath();
4439
+ ctx.strokeStyle = BASE_SPEED_COLOR.hex();
3873
4440
  curvePoints.slice(0, curvePoints.length - 2).forEach(({ x, y }) => {
3874
4441
  ctx.lineTo(x, y);
3875
4442
  });
3876
4443
  ctx.stroke();
4444
+ // Fill eco speed curve.
3877
4445
  ctx.beginPath();
3878
- ctx.fillStyle = 'rgba(255, 255, 255)';
3879
- ctx.strokeStyle = ecoSpeedColor.hex();
4446
+ ctx.fillStyle = WHITE.hex();
3880
4447
  ctx.globalCompositeOperation = 'destination-out';
3881
4448
  ecoCurvePoints.forEach(({ x, y }) => {
3882
4449
  ctx.lineTo(x, y);
3883
4450
  });
3884
4451
  ctx.fill();
4452
+ // Stroke eco speed curve.
3885
4453
  ctx.beginPath();
4454
+ ctx.strokeStyle = ECO_SPEED_COLOR.hex();
3886
4455
  ctx.globalCompositeOperation = 'source-over';
3887
4456
  ecoCurvePoints.slice(0, ecoCurvePoints.length - 2).forEach(({ x, y }) => {
3888
4457
  ctx.lineTo(x, y);
3889
4458
  });
3890
4459
  ctx.stroke();
4460
+ // Stroke etcs curves.
4461
+ if (etcsBrakingCurves) {
4462
+ const strokeEtcsCurve = (etcsBrakingCurveType, etcsCurve) => {
4463
+ const etcsCurvePoints = computeCurvePoints({ width, height }, { maxSpeed, maxPosition, ratioX }, etcsCurve);
4464
+ ctx.beginPath();
4465
+ ctx.lineWidth = ETCS_LINEWIDTH;
4466
+ ctx.strokeStyle = ETCS_COLOR_DICTIONARY[etcsBrakingCurveType]
4467
+ .alpha(ETCS_ALPHA_DICTIONARY[etcsBrakingCurveType])
4468
+ .hex();
4469
+ etcsCurvePoints.slice(0, etcsCurvePoints.length - 2).forEach(({ x, y }) => {
4470
+ ctx.lineTo(x, y);
4471
+ });
4472
+ ctx.stroke();
4473
+ };
4474
+ const activeEtcsBrakingTypes = getActiveEtcsBrakingTypes(store.etcsLayersDisplay);
4475
+ const activeEtcsBrakingCurveTypes = getActiveEtcsBrakingCurveTypes(store.etcsLayersDisplay);
4476
+ activeEtcsBrakingTypes.forEach((brakingType) => {
4477
+ const etcsCurves = etcsBrakingCurves[brakingType];
4478
+ etcsCurves.forEach((etcsCurve) => {
4479
+ activeEtcsBrakingCurveTypes.forEach((curveType) => {
4480
+ strokeEtcsCurve(curveType, etcsCurve[curveType]);
4481
+ });
4482
+ });
4483
+ });
4484
+ }
3891
4485
  ctx.restore();
3892
4486
  };
3893
4487
 
@@ -4179,7 +4773,7 @@ const PowerRestrictionsLayer = ({ width, marginTop, store }) => {
4179
4773
  const DETAILBOX_MARGIN = 6;
4180
4774
  const DETAILBOX_OFFSET = 12;
4181
4775
  const DETAILBOX_LIMIT = 10;
4182
- const DetailsBox = ({ width, height, store, curveX, curveY, speedText, ecoSpeedText, effortText, electricalModeText, electricalProfileText, powerRestrictionText, previousGradientText, modeText, }) => {
4776
+ const DetailsBox = ({ width, height, store, curveX, curveY, speedText, ecoSpeedText, etcsSpeedValues, translations, effortText, electricalModeText, electricalProfileText, powerRestrictionText, previousGradientText, modeText, }) => {
4183
4777
  const { MARGIN_BOTTOM, MARGIN_RIGHT } = MARGINS;
4184
4778
  const { energySource, tractionStatus, declivities, electricalProfiles, powerRestrictions } = store.detailsBoxDisplay;
4185
4779
  let rightOffset = 0;
@@ -4196,24 +4790,59 @@ const DetailsBox = ({ width, height, store, curveX, curveY, speedText, ecoSpeedT
4196
4790
  const boxY = curveY + DETAILBOX_MARGIN - bottomOffset;
4197
4791
  const speedDifference = Number(speedText) - Number(ecoSpeedText);
4198
4792
  const speedDifferenceText = speedDifference !== 0 ? `-${speedDifference.toFixed(1)}` : null;
4199
- return (React.createElement("div", { id: "details-box", className: cx('absolute flex flex-col', { block: curveY, hidden: !curveY }), style: {
4793
+ const activeEtcsBrakingTypes = getActiveEtcsBrakingTypes(store.etcsLayersDisplay);
4794
+ const activeEtcsBrakingCurveTypes = getActiveEtcsBrakingCurveTypes(store.etcsLayersDisplay);
4795
+ const etcsEndOfCurves = etcsSpeedValues
4796
+ ? [
4797
+ ...new Set(activeEtcsBrakingTypes.flatMap((etcsBrakingType) => activeEtcsBrakingCurveTypes.flatMap((etcsBrakingCurveType) => etcsSpeedValues[etcsBrakingType][etcsBrakingCurveType].map((etcsValue) => etcsValue.etcsEndOfCurvePos)))),
4798
+ ]
4799
+ .sort((a, b) => a - b)
4800
+ .map((n) => n.toFixed(1))
4801
+ : [];
4802
+ return (React.createElement("div", { id: "details-box", className: cx('absolute flex flex-row', { block: curveY, hidden: !curveY }), style: {
4200
4803
  marginTop: boxY,
4201
4804
  marginLeft: boxX,
4202
4805
  } },
4203
- React.createElement("span", { id: "base-speed-text" }, speedText || '--'),
4204
- React.createElement("div", null,
4205
- React.createElement("span", { id: "mareco-speed-text" }, ecoSpeedText || '--'),
4206
- speedDifferenceText && React.createElement("span", { id: "speed-difference-text" }, speedDifferenceText)),
4207
- (energySource || tractionStatus || modeText || effortText) && React.createElement("hr", null),
4208
- energySource && React.createElement("span", { id: "mode-text" }, modeText || '--'),
4209
- tractionStatus && React.createElement("span", { id: "effort-text" }, effortText || '--'),
4210
- electricalModeText && (React.createElement("div", { id: "electrical-mode-text" },
4211
- React.createElement("span", null, electricalModeText || '--'),
4212
- electricalProfiles && React.createElement("span", { className: "ml-2" }, electricalProfileText || '--'))),
4213
- powerRestrictions && React.createElement("span", { id: "power-restriction-text" }, powerRestrictionText || '--'),
4214
- declivities && (React.createElement(React.Fragment, null,
4215
- React.createElement("hr", null),
4216
- React.createElement("span", { id: "previous-gradient-text" }, `${previousGradientText} ‰` || '--')))));
4806
+ React.createElement("div", { className: "default-details-box" },
4807
+ React.createElement("span", { id: "base-speed-text" }, speedText || '--'),
4808
+ React.createElement("div", null,
4809
+ React.createElement("span", { id: "mareco-speed-text" }, ecoSpeedText || '--'),
4810
+ speedDifferenceText && React.createElement("span", { id: "speed-difference-text" }, speedDifferenceText)),
4811
+ (energySource || tractionStatus || modeText || effortText) && React.createElement("hr", null),
4812
+ energySource && React.createElement("span", { id: "mode-text" }, modeText || '--'),
4813
+ tractionStatus && React.createElement("span", { id: "effort-text" }, effortText || '--'),
4814
+ electricalModeText && (React.createElement("div", { id: "electrical-mode-text" },
4815
+ React.createElement("span", null, electricalModeText || '--'),
4816
+ electricalProfiles && React.createElement("span", { className: "ml-2" }, electricalProfileText || '--'))),
4817
+ powerRestrictions && (React.createElement("span", { id: "power-restriction-text" }, powerRestrictionText || '--')),
4818
+ declivities && (React.createElement(React.Fragment, null,
4819
+ React.createElement("hr", null),
4820
+ React.createElement("span", { id: "previous-gradient-text" }, `${previousGradientText} ‰`)))),
4821
+ store.detailsBoxDisplay.etcs &&
4822
+ etcsSpeedValues &&
4823
+ activeEtcsBrakingTypes.length > 0 &&
4824
+ activeEtcsBrakingCurveTypes.length > 0 && (React.createElement("div", { className: "etcs-details-box", style: { minHeight: detailsBoxHeight } },
4825
+ React.createElement("div", { className: "etcs-grid", style: { gridTemplateColumns: `repeat(${etcsEndOfCurves.length + 2}, auto)` } },
4826
+ React.createElement("div", { className: "etcs-row-group", style: { gridColumnStart: 3 } }, etcsEndOfCurves.map((endOfCurve) => (React.createElement("div", { key: endOfCurve, className: "number-text" }, endOfCurve)))),
4827
+ activeEtcsBrakingTypes.map((brakingType) => {
4828
+ const specificEtcsSpeeds = etcsSpeedValues[brakingType];
4829
+ return (React.createElement("div", { key: brakingType, className: "etcs-row-group" }, activeEtcsBrakingCurveTypes.map((brakingCurveType, index) => {
4830
+ const speedValues = specificEtcsSpeeds[brakingCurveType];
4831
+ return (React.createElement(React.Fragment, null,
4832
+ index === 0 && (React.createElement("div", { style: {
4833
+ gridRow: `span ${activeEtcsBrakingCurveTypes.length}`,
4834
+ } }, translations?.etcsLayersDisplay.etcsBrakingTypes[brakingType] ||
4835
+ brakingType)),
4836
+ React.createElement("div", { style: {
4837
+ color: ETCS_COLOR_DICTIONARY[brakingCurveType].toString(),
4838
+ } }, brakingCurveType),
4839
+ etcsEndOfCurves.map((endOfCurve) => (React.createElement("div", { key: endOfCurve, className: "number-text", style: {
4840
+ color: ETCS_COLOR_DICTIONARY[brakingCurveType].toString(),
4841
+ } }, speedValues
4842
+ .find((speedValue) => speedValue.etcsEndOfCurvePos.toFixed(1) === endOfCurve)
4843
+ ?.etcsSpeed.toFixed(2) ?? '--')))));
4844
+ })));
4845
+ }))))));
4217
4846
  };
4218
4847
 
4219
4848
  const { MARGIN_LEFT: MARGIN_LEFT$3, MARGIN_RIGHT: MARGIN_RIGHT$2, MARGIN_TOP: MARGIN_TOP$2, MARGIN_BOTTOM: MARGIN_BOTTOM$3, CURVE_MARGIN_TOP: CURVE_MARGIN_TOP$1, CURVE_MARGIN_SIDES: CURVE_MARGIN_SIDES$1, } = MARGINS;
@@ -4221,9 +4850,71 @@ const RETICLE_LINE = 12.75;
4221
4850
  const SNAPPED_STOP_TEXT_OFFSET = 36;
4222
4851
  const CURSOR_HEIGHT = 6;
4223
4852
  const SNAPPED_CURSOR_HEIGHT = 24;
4853
+ const getEtcsSpeedsAtPosition = (curves, position) => {
4854
+ const result = {
4855
+ [EtcsBrakingType.STOP]: {
4856
+ [EtcsBrakingCurveType.IND]: [],
4857
+ [EtcsBrakingCurveType.PS]: [],
4858
+ [EtcsBrakingCurveType.GUI]: [],
4859
+ },
4860
+ [EtcsBrakingType.SLOWDOWN]: {
4861
+ [EtcsBrakingCurveType.IND]: [],
4862
+ [EtcsBrakingCurveType.PS]: [],
4863
+ [EtcsBrakingCurveType.GUI]: [],
4864
+ },
4865
+ [EtcsBrakingType.SPACING]: {
4866
+ [EtcsBrakingCurveType.IND]: [],
4867
+ [EtcsBrakingCurveType.PS]: [],
4868
+ [EtcsBrakingCurveType.GUI]: [],
4869
+ },
4870
+ [EtcsBrakingType.ROUTING]: {
4871
+ [EtcsBrakingCurveType.IND]: [],
4872
+ [EtcsBrakingCurveType.PS]: [],
4873
+ [EtcsBrakingCurveType.GUI]: [],
4874
+ },
4875
+ };
4876
+ const getEtcsSpeedAndEndOfCurveAtPosition = (speeds, pos) => {
4877
+ if (speeds.length === 0)
4878
+ return undefined;
4879
+ const first = speeds[0];
4880
+ const last = speeds[speeds.length - 1];
4881
+ const firstPosition = first.position.start;
4882
+ const lastPosition = last.position.end ? last.position.end : last.position.start;
4883
+ // Reject if position is outside the curve range
4884
+ if (pos < firstPosition || pos > lastPosition) {
4885
+ return undefined;
4886
+ }
4887
+ const index = binarySearch(speeds, pos, (p) => p.position.start);
4888
+ // If there is an exact match, return speed
4889
+ if (speeds[index].position.start === pos ||
4890
+ (speeds[index].position.end && speeds[index].position.end === pos)) {
4891
+ return { etcsSpeed: speeds[index].value, etcsEndOfCurvePos: lastPosition };
4892
+ }
4893
+ // Else, interpolate speed.
4894
+ const p1 = speeds[index];
4895
+ const p2 = speeds[index + 1];
4896
+ return {
4897
+ etcsSpeed: interpolate(p1.position.start, p1.value, p2.position.start, p2.value, pos),
4898
+ etcsEndOfCurvePos: lastPosition,
4899
+ };
4900
+ };
4901
+ for (const brakingType of Object.values(EtcsBrakingType)) {
4902
+ const curveList = curves[brakingType] ?? [];
4903
+ curveList.forEach((curve) => {
4904
+ for (const curveType of Object.values(EtcsBrakingCurveType)) {
4905
+ const etcsSpeeds = curve[curveType] ?? [];
4906
+ const value = getEtcsSpeedAndEndOfCurveAtPosition(etcsSpeeds, position);
4907
+ if (value !== undefined) {
4908
+ result[brakingType][curveType].push(value);
4909
+ }
4910
+ }
4911
+ });
4912
+ }
4913
+ return result;
4914
+ };
4224
4915
  const drawCursor = ({ ctx, width, height, store }) => {
4225
4916
  clearCanvas(ctx, width, height);
4226
- const { cursor, layersDisplay, ratioX, leftOffset, speeds, ecoSpeeds, electrifications, slopes, electricalProfiles, powerRestrictions, } = store;
4917
+ const { cursor, layersDisplay, ratioX, leftOffset, speeds, ecoSpeeds, etcsBrakingCurves, electrifications, slopes, electricalProfiles, powerRestrictions, } = store;
4227
4918
  let speedText = '';
4228
4919
  let ecoSpeedText = '';
4229
4920
  let stopText = '';
@@ -4303,6 +4994,9 @@ const drawCursor = ({ ctx, width, height, store }) => {
4303
4994
  else if (prevEcoSpeed.value > nextEcoSpeed.value) {
4304
4995
  effortText = 'decelerating';
4305
4996
  }
4997
+ const etcsSpeedValues = etcsBrakingCurves
4998
+ ? getEtcsSpeedsAtPosition(etcsBrakingCurves, cursorPosition)
4999
+ : undefined;
4306
5000
  reticleY =
4307
5001
  cursorBoxHeight -
4308
5002
  (ecoSpeedValue / maxSpeed) * (cursorBoxHeight - CURVE_MARGIN_TOP$1) +
@@ -4385,6 +5079,7 @@ const drawCursor = ({ ctx, width, height, store }) => {
4385
5079
  curveY: reticleY,
4386
5080
  speedText,
4387
5081
  ecoSpeedText,
5082
+ etcsSpeedValues,
4388
5083
  effortText,
4389
5084
  electricalModeText,
4390
5085
  electricalProfileText,
@@ -4394,7 +5089,7 @@ const drawCursor = ({ ctx, width, height, store }) => {
4394
5089
  };
4395
5090
  };
4396
5091
 
4397
- const ReticleLayer = ({ width, internalHeight: height, store }) => {
5092
+ const ReticleLayer = ({ width, internalHeight: height, store, translations, }) => {
4398
5093
  const canvas = useRef(null);
4399
5094
  const [trainDetails, setTrainDetails] = useState(null);
4400
5095
  useEffect(() => {
@@ -4412,7 +5107,7 @@ const ReticleLayer = ({ width, internalHeight: height, store }) => {
4412
5107
  }, [width, height, store]);
4413
5108
  return (React.createElement(React.Fragment, null,
4414
5109
  React.createElement("canvas", { id: "cursor-layer", className: "absolute", ref: canvas, width: width, height: height }),
4415
- trainDetails && React.createElement(DetailsBox, { width: width, height: height, store: store, ...trainDetails })));
5110
+ trainDetails && (React.createElement(DetailsBox, { width: width, height: height, store: store, translations: translations, ...trainDetails }))));
4416
5111
  };
4417
5112
 
4418
5113
  const TOOLTIP_WIDTH = 246;
@@ -4825,7 +5520,7 @@ const TickLayerYRight = ({ width, height, store }) => {
4825
5520
  return (React.createElement("canvas", { id: "tick-layer-y-right", className: "absolute rounded-t-xl", ref: canvas, width: width, height: height }));
4826
5521
  };
4827
5522
 
4828
- const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, translations, }) => {
5523
+ const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, translations, fetchEtcsBrakingCurves, etcsBrakingCurves, }) => {
4829
5524
  const [store, setStore] = useState({
4830
5525
  speeds: [],
4831
5526
  ecoSpeeds: [],
@@ -4847,6 +5542,7 @@ const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, tran
4847
5542
  energySource: true,
4848
5543
  tractionStatus: true,
4849
5544
  declivities: true,
5545
+ etcs: false,
4850
5546
  electricalProfiles: true,
4851
5547
  powerRestrictions: true,
4852
5548
  },
@@ -4858,6 +5554,7 @@ const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, tran
4858
5554
  powerRestrictions: false,
4859
5555
  speedLimitTags: false,
4860
5556
  },
5557
+ etcsLayersDisplay: DEFAULT_ETCS_LAYERS_DISPLAY,
4861
5558
  isSettingsPanelOpened: false,
4862
5559
  });
4863
5560
  const { mainChartHeight, powerRestrictionsTop, speedLimitTagsTop, electricalProfileLayerHeight, interactivityLayerHeight, } = useMemo(() => {
@@ -4924,6 +5621,22 @@ const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, tran
4924
5621
  setHeight((prevHeight) => prevHeight + (isCurrentlyActive ? -adjustment : adjustment));
4925
5622
  }, [setHeight]);
4926
5623
  useEffect(() => {
5624
+ const shouldFetchEtcsCurves = getActiveEtcsBrakingTypes(store.etcsLayersDisplay).length > 0;
5625
+ if (fetchEtcsBrakingCurves && shouldFetchEtcsCurves) {
5626
+ fetchEtcsBrakingCurves();
5627
+ }
5628
+ }, [fetchEtcsBrakingCurves, store.etcsLayersDisplay]);
5629
+ useEffect(() => {
5630
+ // TODO: fix this lint
5631
+ // eslint-disable-next-line react-hooks/set-state-in-effect
5632
+ setStore((prev) => ({
5633
+ ...prev,
5634
+ etcsBrakingCurves: etcsBrakingCurves,
5635
+ }));
5636
+ }, [etcsBrakingCurves]);
5637
+ useEffect(() => {
5638
+ // TODO: fix this lint
5639
+ // eslint-disable-next-line react-hooks/set-state-in-effect
4927
5640
  setStore((prev) => ({
4928
5641
  ...prev,
4929
5642
  ...data,
@@ -4947,7 +5660,7 @@ const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, tran
4947
5660
  React.createElement("div", { className: "flex justify-end absolute base-margin-top", style: { width: adjustedWidthRightAxis } },
4948
5661
  React.createElement(InteractionButtons, { reset: reset, openSettingsPanel: openSettingsPanel, store: store, testIdPrefix: "interaction" })),
4949
5662
  store.isSettingsPanelOpened && (React.createElement("div", { className: "flex justify-end absolute ml-2 base-margin-top", style: { width: adjustedWidthRightAxis } },
4950
- React.createElement(SettingsPanel, { color: backgroundColor, store: store, setStore: setStore, setIsMouseHoveringSettingsPanel: setIsMouseHoveringSettingsPanel, translations: translations, testIdPrefix: "settings-panel", adjustHeightOnLayerChange: adjustHeightOnLayerChange }))),
5663
+ React.createElement(SettingsPanel, { color: backgroundColor, store: store, setStore: setStore, setIsMouseHoveringSettingsPanel: setIsMouseHoveringSettingsPanel, translations: translations, testIdPrefix: "settings-panel", adjustHeightOnLayerChange: adjustHeightOnLayerChange, displayEtcs: fetchEtcsBrakingCurves !== undefined }))),
4951
5664
  store.layersDisplay.declivities && (React.createElement(DeclivityLayer, { width: WIDTH_OFFSET, height: HEIGHT_OFFSET, store: store })),
4952
5665
  React.createElement(CurveLayer, { width: WIDTH_OFFSET, height: HEIGHT_OFFSET, store: store }),
4953
5666
  store.layersDisplay.speedLimits && (React.createElement(SpeedLimitsLayer, { width: adjustedWidthRightAxis, height: mainChartHeight, store: store })),
@@ -4958,7 +5671,7 @@ const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, tran
4958
5671
  store.layersDisplay.speedLimitTags && (React.createElement(SpeedLimitTagsLayer, { width: adjustedWidthRightAxis, marginTop: speedLimitTagsTop, store: store })),
4959
5672
  React.createElement(TickLayerX, { width: adjustedWidthRightAxis, height: height, store: store }),
4960
5673
  store.layersDisplay.declivities && (React.createElement(TickLayerYRight, { width: width, height: mainChartHeight, store: store })),
4961
- !isMouseHoveringSettingsPanel && (React.createElement(ReticleLayer, { width: adjustedWidthRightAxis, internalHeight: mainChartHeight, store: store })),
5674
+ !isMouseHoveringSettingsPanel && (React.createElement(ReticleLayer, { width: adjustedWidthRightAxis, internalHeight: mainChartHeight, store: store, translations: translations })),
4962
5675
  React.createElement(FrontInteractivityLayer, { width: WIDTH_OFFSET, height: interactivityLayerHeight, store: store, setStore: setStore })));
4963
5676
  };
4964
5677
 
@@ -5191,6 +5904,8 @@ const X_TROUGHTRAIN_BACKGROUND_PADDING = 8;
5191
5904
  const BACKGROUND_HEIGHT = 40;
5192
5905
  const SELECTED_TRAIN_ID_GRADIANT = 2;
5193
5906
  const PATH_SIZE_DEFAULT = 1;
5907
+ const LABEL_OFFSET_X = 10;
5908
+ const LABEL_OFFSET_Y = 50;
5194
5909
  const drawDefaultZone = (ctx, { x, y, width }) => {
5195
5910
  ctx.beginPath();
5196
5911
  ctx.rect(x, y, width, OCCUPANCY_ZONE_HEIGHT);
@@ -5306,6 +6021,29 @@ const drawOccupationZone = (ctx, stcContext, { zone, yOffset, position, isSelect
5306
6021
  isSelected,
5307
6022
  });
5308
6023
  };
6024
+ const drawZoneTrailingText = (ctx, { getTimePixel, getSpacePixel }, { zone, position, yOffset, trailingText, }) => {
6025
+ const xEnd = getTimePixel(zone.endTime) + LABEL_OFFSET_X;
6026
+ const yCenter = getSpacePixel(position) + yOffset + OCCUPANCY_ZONE_Y_START - LABEL_OFFSET_Y;
6027
+ ctx.save();
6028
+ ctx.font = '600 12px IBM Plex Mono';
6029
+ ctx.textAlign = 'left';
6030
+ ctx.textBaseline = 'middle';
6031
+ const text = trailingText;
6032
+ const paddingX = 6;
6033
+ const textW = ctx.measureText(text).width;
6034
+ const boxW = textW + paddingX * 2;
6035
+ const boxH = 18;
6036
+ const radius = 3;
6037
+ const x = xEnd;
6038
+ const yTop = yCenter - boxH / 2;
6039
+ ctx.fillStyle = 'rgba(0,0,0,0.55)';
6040
+ ctx.beginPath();
6041
+ ctx.roundRect(x, yTop, boxW, boxH, radius);
6042
+ ctx.fill();
6043
+ ctx.fillStyle = '#FFFFFF';
6044
+ ctx.fillText(trailingText, x + paddingX, yCenter + 0.5);
6045
+ ctx.restore();
6046
+ };
5309
6047
 
5310
6048
  const Y_OFFSET_INCREMENT = 4;
5311
6049
  const MAX_ZONES = 9;
@@ -5351,6 +6089,7 @@ const OccupancyZonesLayer = ({ tracks, occupancyZones, position, topPadding, sel
5351
6089
  zone,
5352
6090
  offsetY: trackY + yPosition,
5353
6091
  isSelected: zone.trainId === selectedTrainId,
6092
+ trailingText: zone.trailingText,
5354
6093
  });
5355
6094
  zoneIndex++;
5356
6095
  }
@@ -5380,14 +6119,16 @@ const OccupancyZonesLayer = ({ tracks, occupancyZones, position, topPadding, sel
5380
6119
  // else, if there are too much trains:
5381
6120
  else {
5382
6121
  const nextIndex = filteredOccupancyZones.findIndex((filteredZone, i) => i > zoneIndex && filteredZone.startTime >= lastEndTime);
5383
- const remainingTrainsNb = nextIndex - zoneIndex;
6122
+ // nextIndex === -1 means all remaining zones overlap — skip to the end
6123
+ const endIndex = nextIndex === -1 ? filteredOccupancyZones.length : nextIndex;
6124
+ const remainingTrainsNb = endIndex - zoneIndex;
5384
6125
  instructions.push({
5385
6126
  type: 'remainingTrains',
5386
6127
  amount: remainingTrainsNb,
5387
6128
  time: (startTime + endTime) / 2,
5388
6129
  offsetY: trackY,
5389
6130
  });
5390
- zoneIndex += remainingTrainsNb;
6131
+ zoneIndex = endIndex;
5391
6132
  }
5392
6133
  }
5393
6134
  });
@@ -5396,14 +6137,23 @@ const OccupancyZonesLayer = ({ tracks, occupancyZones, position, topPadding, sel
5396
6137
  const drawingFunction = useCallback((ctx, stcContext) => {
5397
6138
  instructionsToDraw.forEach((instruction) => {
5398
6139
  switch (instruction.type) {
5399
- case 'occupancyZone':
6140
+ case 'occupancyZone': {
5400
6141
  drawOccupationZone(ctx, stcContext, {
5401
6142
  zone: instruction.zone,
5402
6143
  position,
5403
6144
  yOffset: instruction.offsetY,
5404
6145
  isSelected: instruction.isSelected,
5405
6146
  });
6147
+ if (instruction.trailingText) {
6148
+ drawZoneTrailingText(ctx, stcContext, {
6149
+ zone: instruction.zone,
6150
+ position,
6151
+ yOffset: instruction.offsetY,
6152
+ trailingText: instruction.trailingText,
6153
+ });
6154
+ }
5406
6155
  break;
6156
+ }
5407
6157
  case 'remainingTrains':
5408
6158
  drawRemainingTrainsBox(ctx, stcContext, {
5409
6159
  position,
@@ -5445,8 +6195,8 @@ const OccupancyZonesLayer = ({ tracks, occupancyZones, position, topPadding, sel
5445
6195
  }
5446
6196
  });
5447
6197
  }, [position, instructionsToDraw]);
5448
- usePicking('overlay', pickingFunction);
5449
- useDraw('overlay', drawingFunction);
6198
+ usePicking(SpaceTimeChartCanvasContext, 'overlay', pickingFunction);
6199
+ useDraw(SpaceTimeChartCanvasContext, 'overlay', drawingFunction);
5450
6200
  return null;
5451
6201
  };
5452
6202
 
@@ -5548,13 +6298,13 @@ const TracksLayer = ({ tracks, position, topPadding, drawBorders, }) => {
5548
6298
  const drawingFunction = useCallback((ctx, stcContext) => {
5549
6299
  drawTracks(ctx, stcContext, { position, topPadding, tracks, drawBorders });
5550
6300
  }, [drawBorders, position, topPadding, tracks]);
5551
- useDraw('overlay', drawingFunction);
6301
+ useDraw(SpaceTimeChartCanvasContext, 'overlay', drawingFunction);
5552
6302
  return null;
5553
6303
  };
5554
6304
 
5555
6305
  const CloseButton = ({ position, onClose }) => {
5556
6306
  const { getSpacePixel } = useContext(SpaceTimeChartContext);
5557
- return (React.createElement("button", { className: "close-track-occupancy-panel", onClick: () => onClose(), style: {
6307
+ return (React.createElement("button", { "data-testid": "close-track-occupancy-panel", className: "close-track-occupancy-panel", onClick: () => onClose(), style: {
5558
6308
  top: getSpacePixel(position),
5559
6309
  } },
5560
6310
  React.createElement("span", null,
@@ -5565,11 +6315,9 @@ const TrackOccupancyCanvas = ({ position, tracks, occupancyZones, selectedTrainI
5565
6315
  React.createElement(OccupancyZonesLayer, { tracks: tracks, position: position, topPadding: topPadding, occupancyZones: occupancyZones, selectedTrainId: selectedTrainId }),
5566
6316
  onClose && React.createElement(CloseButton, { position: position, onClose: onClose })));
5567
6317
 
5568
- const TrackOccupancyManchette = ({ tracks, children }) => (React.createElement("div", { className: "track-occupancy-manchette" },
6318
+ const TrackOccupancyManchette = ({ tracks, children }) => (React.createElement("div", { "data-testid": "track-occupancy-manchette", className: "track-occupancy-manchette" },
5569
6319
  children,
5570
- tracks.map((track) => (
5571
- // height is shared between manchette and canvas components
5572
- React.createElement("div", { className: "track", key: track.id, style: { height: TRACK_HEIGHT_CONTAINER } },
6320
+ tracks.map((track) => (React.createElement("div", { className: "track", key: track.id, style: { height: TRACK_HEIGHT_CONTAINER } },
5573
6321
  React.createElement("span", { className: "track-line" }, track.line),
5574
6322
  React.createElement("div", { className: "track-name" }, track.name),
5575
6323
  React.createElement("div", { className: "track-rail" }))))));
@@ -5578,6 +6326,8 @@ const TrackOccupancyStandalone = ({ tracks, occupancyZones, selectedTrainId, onS
5578
6326
  const manchetteWithSpaceTimeChartRef = useRef(null);
5579
6327
  const spaceTimeChartRef = useRef(null);
5580
6328
  const defaultTimeOrigin = useMemo(() => {
6329
+ // TODO: fix this lint
6330
+ /* eslint-disable-next-line react-hooks/purity */
5581
6331
  const minTime = Math.min(...(occupancyZones.map((zone) => zone.startTime) || Date.now()));
5582
6332
  // Take first round hour before minTime:
5583
6333
  return Math.floor(minTime / HOUR) * HOUR;
@@ -5637,5 +6387,5 @@ const TrackOccupancyStandalone = ({ tracks, occupancyZones, selectedTrainId, onS
5637
6387
  }) }))))));
5638
6388
  };
5639
6389
 
5640
- export { BASE_WAYPOINT_HEIGHT, CANVAS_PADDING, COLORS, CanvasContext, ConflictLayer, ConflictTooltip, DEFAULT_LEVEL, DEFAULT_THEME, DEFAULT_ZOOM_MS_PER_PX, FONTS, MINUTES_TEXT_OFFSET, Manchette, ManchetteWithSpaceTimeChart, MouseContext, OCCUPANCY_ZONE_HEIGHT, OCCUPANCY_ZONE_Y_START, OccupancyBlockLayer, PathLayer, PatternRect, Quadrilateral, STATION_TEXT_OFFSET, SpaceTimeChart, SpaceTimeChartContext, SpeedSpaceChart, TICKS_PATTERN, TICKS_PRIORITIES, TRACK_HEIGHT_CONTAINER, TimeCaptions, Tooltip$1 as Tooltip, TrackOccupancyCanvas, TrackOccupancyManchette, TrackOccupancyStandalone, Waypoint as WaypointComponent, WorkScheduleLayer, ZoomRect, computeRectZoomOffsets, getCrispLineCoordinate, getSpaceAtTime, isConflictPickingElement, isInteractiveWaypoint, isOccupancyPickingElement, isPathOnScreen, isPointPickingElement, isQuadrilaterPickingElement, isSegmentPickingElement, positionKmToMm, positionMmToKm, timeScaleToZoomValue, useDraw, useManchetteWithSpaceTimeChart, usePaths, usePicking };
6390
+ export { BASE_WAYPOINT_HEIGHT, CANVAS_PADDING, COLORS, Chronogram, ChronogramCanvas, ChronogramContext, ConflictLayer, ConflictTooltip, DEFAULT_LEVEL, DEFAULT_THEME, DEFAULT_ZOOM_MS_PER_PX, EtcsBrakingCurveType, EtcsBrakingType, FONTS, MINUTES_TEXT_OFFSET, Manchette, ManchetteWithSpaceTimeChart, MouseContext, OCCUPANCY_ZONE_HEIGHT, OCCUPANCY_ZONE_Y_START, OccupancyBlockLayer, OccupancyBlocksLayer, PathLayer, PatternRect, Quadrilateral, STATION_TEXT_OFFSET, SpaceTimeChart, SpaceTimeChartCanvasContext, SpaceTimeChartContext, SpeedSpaceChart, TICKS_PATTERN, TICKS_PRIORITIES, TRACK_HEIGHT_CONTAINER, TimeCaptions, TimeGraduations, Tooltip$1 as Tooltip, TrackOccupancyCanvas, TrackOccupancyManchette, TrackOccupancyStandalone, Waypoint as WaypointComponent, WorkScheduleLayer, ZoomRect, computeRectZoomOffsets, getCrispLineCoordinate, getSpaceAtTime, isConflictPickingElement, isInteractiveWaypoint, isOccupancyPickingElement, isPathOnScreen, isPointPickingElement, isQuadrilaterPickingElement, isSegmentPickingElement, positionKmToMm, positionMmToKm, timeScaleToZoomValue, useDraw, useManchetteWithSpaceTimeChart, usePicking };
5641
6391
  //# sourceMappingURL=index.esm.js.map