@osrd-project/ui-charts 0.0.73 → 0.0.76

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 (25) hide show
  1. package/dist/index.esm.js +593 -386
  2. package/dist/index.esm.js.map +1 -1
  3. package/dist/manchette/components/Manchette.d.ts +4 -3
  4. package/dist/manchette/components/Waypoint.d.ts +2 -2
  5. package/dist/manchette/hooks/useManchetteWithSpaceTimeChart.d.ts +12 -2
  6. package/dist/manchette/index.d.ts +3 -2
  7. package/dist/manchette/types.d.ts +0 -5
  8. package/dist/manchette/utils/helpers.d.ts +1 -5
  9. package/dist/manchette/utils/index.d.ts +3 -2
  10. package/dist/spaceTimeChart/lib/types.d.ts +4 -6
  11. package/dist/spaceTimeChart/utils/scales.d.ts +5 -0
  12. package/dist/theme.css +1678 -2653
  13. package/dist/theme.css.map +1 -1
  14. package/dist/trackOccupancyDiagram/components/TrackOccupancyCanvas.d.ts +10 -2
  15. package/dist/trackOccupancyDiagram/components/TrackOccupancyManchette.d.ts +5 -3
  16. package/dist/trackOccupancyDiagram/components/TrackOccupancyStandalone.d.ts +10 -0
  17. package/dist/trackOccupancyDiagram/components/consts.d.ts +3 -1
  18. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawOccupancyZones.d.ts +13 -14
  19. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawOccupancyZonesTexts.d.ts +2 -2
  20. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawTracks.d.ts +7 -15
  21. package/dist/trackOccupancyDiagram/components/layers/OccupancyZonesLayer.d.ts +7 -9
  22. package/dist/trackOccupancyDiagram/components/layers/TracksLayer.d.ts +6 -3
  23. package/dist/trackOccupancyDiagram/components/types.d.ts +8 -17
  24. package/dist/trackOccupancyDiagram/index.d.ts +3 -0
  25. package/package.json +8 -8
package/dist/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
- import React, { useState, useEffect, createContext, useContext, useRef, useCallback, useMemo, useLayoutEffect, Fragment } from 'react';
1
+ import React, { useState, useEffect, createContext, useContext, useRef, useCallback, useMemo, Fragment } from 'react';
2
2
  import cx from 'classnames';
3
- import { clamp as clamp$1, isEqual, inRange, last, sortBy, sum } from 'lodash';
3
+ import { clamp as clamp$1, isEqual, inRange, last, flatten, sortBy, sum } from 'lodash';
4
4
  import chroma from 'chroma-js';
5
5
  import { ZoomOut, ZoomIn, Iterations, Plus, Dash, KebabHorizontal, X } from '@osrd-project/ui-icons';
6
6
  import { Checkbox } from '@osrd-project/ui-core';
@@ -82,7 +82,7 @@ undefined);
82
82
 
83
83
  const DEFAULT_PATH_END = 'stop';
84
84
  // CANVAS SPECIFIC TYPES:
85
- const PICKING_LAYERS = ['paths'];
85
+ const PICKING_LAYERS = ['paths', 'overlay'];
86
86
  const LAYERS = ['background', 'graduations', 'paths', 'overlay', 'captions'];
87
87
 
88
88
  /**
@@ -467,7 +467,7 @@ function useCanvas$1(dom, inputStcContext, position) {
467
467
  return;
468
468
  const ctx = contextsRef.current[`${PICKING}-${layer}`];
469
469
  const set = pickingFunctions.current[layer];
470
- if (ctx) {
470
+ if (ctx && ctx.canvas.width && ctx.canvas.height) {
471
471
  const { width, height } = sizeRef.current;
472
472
  ctx.clearRect(0, 0, width, height);
473
473
  const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
@@ -603,8 +603,8 @@ function useCanvas$1(dom, inputStcContext, position) {
603
603
  const ratio = isPicking ? pickingScalingRatio : devicePixelRatio;
604
604
  canvas.style.width = size.width + 'px';
605
605
  canvas.style.height = size.height + 'px';
606
- canvas.setAttribute('width', size.width * ratio + 'px');
607
- canvas.setAttribute('height', size.height * ratio + 'px');
606
+ canvas.setAttribute('width', Math.max(1, size.width * ratio) + 'px');
607
+ canvas.setAttribute('height', Math.max(1, size.height * ratio) + 'px');
608
608
  if (!isPicking) {
609
609
  // Reset the transform to identity, then apply the new scale
610
610
  ctx.setTransform(1, 0, 0, 1, 0, 0);
@@ -711,10 +711,12 @@ function getSpacePixels(getSpacePixel, position) {
711
711
  }
712
712
 
713
713
  const SpaceGraduations = () => {
714
- const drawingFunction = useCallback((ctx, { timePixelOffset, getSpacePixel, operationalPoints, swapAxis, width, height, theme: { spaceGraduationsStyles }, }) => {
714
+ const drawingFunction = useCallback((ctx, { timePixelOffset, getSpacePixel, operationalPoints, flatSteps, swapAxis, width, height, theme: { spaceGraduationsStyles }, }) => {
715
715
  const axisSize = !swapAxis ? width : height;
716
716
  // Draw operational point lines:
717
717
  operationalPoints.forEach((point) => {
718
+ if (flatSteps.has(point.position))
719
+ return;
718
720
  const styles = spaceGraduationsStyles[point.importanceLevel || 0];
719
721
  if (!styles)
720
722
  return;
@@ -922,7 +924,9 @@ const RANGES_FORMATER = [
922
924
  HOURS_FORMATTER,
923
925
  ];
924
926
  const TimeCaptions = () => {
925
- const drawingFunction = useCallback((ctx, { timeScale, timeOrigin, timePixelOffset, getTimePixel, swapAxis, width, height, theme: { background, breakpoints, timeRanges, timeCaptionsPriorities, timeCaptionsStyles, timeGraduationsStyles, dateCaptionsStyle, }, captionSize, hideDates, showTicks, }) => {
927
+ const drawingFunction = useCallback((ctx, { timeScale, timeOrigin, timePixelOffset, getTimePixel, swapAxis, width, height, theme: { background, breakpoints, timeRanges, timeCaptionsPriorities, timeCaptionsStyles, timeGraduationsStyles, dateCaptionsStyle, }, captionSize, hideTimeCaptions, hideDates, showTicks, }) => {
928
+ if (hideTimeCaptions)
929
+ return;
926
930
  const timeAxisSize = !swapAxis ? width : height;
927
931
  const spaceAxisSize = (!swapAxis ? height : width) - captionSize;
928
932
  // Add some margin, so that captions of times right outside the stage are still visible:
@@ -1350,6 +1354,20 @@ function spaceScalesToBinaryTree(spaceOrigin, spaceScales, skipSiblingReferences
1350
1354
  }
1351
1355
  return buildTree(normalizedScales);
1352
1356
  }
1357
+ /**
1358
+ * This function takes a sequence of SpaceScales, identifies the flat steps (i.e. the scales that do
1359
+ * not increase the position), and returns them in a set.
1360
+ */
1361
+ function getFlatSteps(spaceScales) {
1362
+ const flatSteps = [];
1363
+ for (let i = 1; i < spaceScales.length; i++) {
1364
+ const { to: previous } = spaceScales[i - 1];
1365
+ const { to: current } = spaceScales[i];
1366
+ if (previous === current)
1367
+ flatSteps.push(current);
1368
+ }
1369
+ return new Set(flatSteps);
1370
+ }
1353
1371
  /**
1354
1372
  * This function takes a NormalizedScaleTree and a position, and returns the leaf node from the
1355
1373
  * tree that contains that position.
@@ -1407,7 +1425,12 @@ function getPixelToTime(timeOrigin, pixelOffset, timeScale) {
1407
1425
  }
1408
1426
  function getSpaceToPixel(pixelOffset, binaryTree) {
1409
1427
  return (position, fromEnd) => {
1410
- const { from, pixelFrom, coefficient } = getNormalizedScaleAtPosition(position, binaryTree, fromEnd);
1428
+ const { from, pixelFrom, pixelTo, coefficient } = getNormalizedScaleAtPosition(position, binaryTree, fromEnd);
1429
+ // Rare case where coefficient is 0:
1430
+ // (occurs when there is just a flat step, for instance)
1431
+ if (coefficient === 0)
1432
+ return pixelOffset + (fromEnd ? pixelTo : pixelFrom);
1433
+ // Normal case: We simply interpolate
1411
1434
  return pixelOffset + pixelFrom + (position - from) / coefficient;
1412
1435
  };
1413
1436
  }
@@ -1511,20 +1534,27 @@ const DEFAULT_LEVEL = 2;
1511
1534
  */
1512
1535
  const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFAULT_PICKING_TOLERANCE, border, }) => {
1513
1536
  /**
1514
- * This function returns the list of points to join to draw the path. It will be both used to
1515
- * render the visible path, and the segments on the picking layer.
1537
+ * This function returns the list of points to join to draw the path. As it can be discontinuous,
1538
+ * it is returned as a Point[][]. For now, the only case for discontinuous paths is when the path
1539
+ * stops on a flat step (in which case, we assume the path will be drawn differently in the flat
1540
+ * step layer).
1541
+ *
1542
+ * It will be both used to render the visible path, and the segments on the picking layer.
1516
1543
  */
1517
- const getPathSegments = useCallback(({ getTimePixel, getSpacePixel, spaceScaleTree, timeAxis, spaceAxis, }) => {
1518
- const res = [];
1519
- path.points.forEach(({ position, time }, i, a) => {
1520
- if (!i) {
1521
- res.push({
1544
+ const getPathLines = useCallback(({ getTimePixel, getSpacePixel, spaceScaleTree, flatSteps, timeAxis, spaceAxis, width, height, }) => {
1545
+ const lines = [];
1546
+ let currentLine = [];
1547
+ const { points } = path;
1548
+ for (let i = 0; i < points.length; i++) {
1549
+ const { position, time } = points[i];
1550
+ if (i === 0) {
1551
+ currentLine.push({
1522
1552
  [timeAxis]: getTimePixel(time),
1523
1553
  [spaceAxis]: getSpacePixel(position),
1524
1554
  });
1525
1555
  }
1526
1556
  else {
1527
- const { position: prevPosition, time: prevTime } = a[i - 1];
1557
+ const { position: prevPosition, time: prevTime } = points[i - 1];
1528
1558
  const spaceBreakPoints = getSpaceBreakpoints(prevPosition, position, spaceScaleTree);
1529
1559
  let previousBreakPosition = -Infinity;
1530
1560
  spaceBreakPoints.forEach((breakPosition, index) => {
@@ -1538,24 +1568,47 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1538
1568
  : false;
1539
1569
  const breakTime = prevTime +
1540
1570
  ((breakPosition - prevPosition) / (position - prevPosition)) * (time - prevTime);
1541
- res.push({
1571
+ currentLine.push({
1542
1572
  [timeAxis]: getTimePixel(breakTime),
1543
1573
  [spaceAxis]: getSpacePixel(breakPosition, readSpacePixelFromEnd),
1544
1574
  });
1545
1575
  previousBreakPosition = breakPosition;
1546
1576
  });
1547
- res.push({
1577
+ const newPoint = {
1548
1578
  [timeAxis]: getTimePixel(time),
1549
1579
  [spaceAxis]: getSpacePixel(position),
1550
- });
1580
+ };
1581
+ if (position === prevPosition && flatSteps.has(position)) {
1582
+ lines.push(currentLine);
1583
+ currentLine = [newPoint];
1584
+ }
1585
+ else if (time === prevTime) {
1586
+ lines.push(currentLine);
1587
+ currentLine = [newPoint];
1588
+ }
1589
+ else {
1590
+ currentLine.push(newPoint);
1591
+ }
1551
1592
  }
1593
+ }
1594
+ lines.push(currentLine);
1595
+ // Only keep segments that intersect with the current visible time frame:
1596
+ const visibleLines = [];
1597
+ const minPixel = 0;
1598
+ const maxPixel = timeAxis === 'x' ? width : height;
1599
+ lines.forEach((line) => {
1600
+ const lastPointBeforeMinIndex = line.findLastIndex((p) => p[timeAxis] < minPixel);
1601
+ const firstPointAfterMaxIndex = line.findIndex((p) => p[timeAxis] > maxPixel);
1602
+ const visibleLine = line.slice(lastPointBeforeMinIndex === -1 ? 0 : lastPointBeforeMinIndex, (firstPointAfterMaxIndex === -1 ? line.length : firstPointAfterMaxIndex) + 1);
1603
+ if (visibleLine.length)
1604
+ visibleLines.push(visibleLine);
1552
1605
  });
1553
- return res;
1606
+ return visibleLines;
1554
1607
  }, [path]);
1555
1608
  /**
1556
1609
  * This function returns the list of important points, where the mouse can snap.
1557
1610
  */
1558
- const getSnapPoints = useCallback(({ getTimePixel, getSpacePixel, timeAxis, spaceAxis, operationalPoints, }) => {
1611
+ const getSnapPoints = useCallback(({ getTimePixel, getSpacePixel, timeAxis, spaceAxis, operationalPoints, width, height, }) => {
1559
1612
  const res = [];
1560
1613
  const stopPositions = new Set(operationalPoints.map((p) => p.position));
1561
1614
  path.points.forEach(({ position, time }) => {
@@ -1565,8 +1618,10 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1565
1618
  [spaceAxis]: getSpacePixel(position),
1566
1619
  });
1567
1620
  });
1568
- return res;
1569
- }, [path]);
1621
+ // Only keep visible points:
1622
+ const radius = STYLES[level].width + pickingTolerance;
1623
+ return res.filter((p) => inRange(p.x, -radius, width + radius) && inRange(p.y, -radius, height + radius));
1624
+ }, [level, path.points, pickingTolerance]);
1570
1625
  /**
1571
1626
  * This function draws the stops of the path on the operational points.
1572
1627
  */
@@ -1576,9 +1631,11 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1576
1631
  if (i) {
1577
1632
  const { position: prevPosition, time: prevTime } = a[i - 1];
1578
1633
  if (prevPosition === position && stopPositions.has(position)) {
1579
- // Detect flat steps, and draw two graduations if any (one on each side of the step):
1580
- getSpacePixels(getSpacePixel, position).forEach((rawPixel) => {
1581
- const spacePixel = getCrispLineCoordinate(rawPixel, ctx.lineWidth);
1634
+ // Only draw the stop when there is no flat step
1635
+ // (i.e. when there's only one space pixel):
1636
+ const rawPixels = getSpacePixels(getSpacePixel, position);
1637
+ if (rawPixels.length === 1) {
1638
+ const spacePixel = getCrispLineCoordinate(rawPixels[0], ctx.lineWidth);
1582
1639
  ctx.beginPath();
1583
1640
  if (!swapAxis) {
1584
1641
  ctx.moveTo(getTimePixel(prevTime), spacePixel);
@@ -1589,7 +1646,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1589
1646
  ctx.lineTo(spacePixel, getTimePixel(time));
1590
1647
  }
1591
1648
  ctx.stroke();
1592
- });
1649
+ }
1593
1650
  }
1594
1651
  }
1595
1652
  });
@@ -1667,7 +1724,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1667
1724
  drawPathExtremity(ctx, getTimePixel(from.time), getSpacePixel(from.position), swapAxis, 'from', getPathDirection(path, 0), fromEnd);
1668
1725
  drawPathExtremity(ctx, getTimePixel(to.time), getSpacePixel(to.position), swapAxis, 'to', getPathDirection(path, path.points.length - 1, true), toEnd);
1669
1726
  }, [path]);
1670
- const computePathLength = useCallback((operationalPoints, segments) => {
1727
+ const computePathLength = useCallback((operationalPoints, lines) => {
1671
1728
  let totalLength = 0;
1672
1729
  // Compute length of pauses
1673
1730
  const stopPositions = new Set(operationalPoints.map((p) => p.position));
@@ -1680,11 +1737,13 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1680
1737
  }
1681
1738
  });
1682
1739
  // Compute length of pathSegments
1683
- segments.forEach(({ x, y }, i, segmentArray) => {
1684
- if (i > 0) {
1685
- const { x: prevX, y: prevY } = segmentArray[i - 1];
1686
- totalLength += Math.sqrt(Math.pow(prevX - x, 2) + Math.pow(prevY - y, 2));
1687
- }
1740
+ lines.forEach((line) => {
1741
+ line.forEach(({ x, y }, i, a) => {
1742
+ if (i > 0) {
1743
+ const { x: prevX, y: prevY } = a[i - 1];
1744
+ totalLength += Math.sqrt(Math.pow(prevX - x, 2) + Math.pow(prevY - y, 2));
1745
+ }
1746
+ });
1688
1747
  });
1689
1748
  return totalLength;
1690
1749
  }, [path]);
@@ -1695,29 +1754,31 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1695
1754
  const mainPathStyle = STYLES[level];
1696
1755
  const totalPathWidth = border.offset * 2 + mainPathStyle.width;
1697
1756
  const backgroundColor = border.backgroundColor || '#fff';
1698
- const segments = getPathSegments(stcContext);
1757
+ const lines = getPathLines(stcContext);
1699
1758
  ctx.save();
1700
- ctx.beginPath();
1701
- const drawSegments = (lineWidth, borderColor = border.color) => {
1759
+ const drawLines = (lineWidth, borderColor = border.color) => {
1702
1760
  ctx.strokeStyle = borderColor;
1703
1761
  ctx.lineWidth = lineWidth;
1704
1762
  ctx.lineCap = 'round';
1705
- segments.forEach(({ x, y }, i) => {
1706
- if (x === segments[i - 1]?.x && y === segments[i - 1]?.y)
1707
- return;
1708
- if (i === 0) {
1709
- ctx.moveTo(x, y);
1710
- }
1711
- else {
1712
- ctx.lineTo(x, y);
1713
- }
1763
+ lines.forEach((segments) => {
1764
+ ctx.beginPath();
1765
+ segments.forEach(({ x, y }, i) => {
1766
+ if (x === segments[i - 1]?.x && y === segments[i - 1]?.y)
1767
+ return;
1768
+ if (i === 0) {
1769
+ ctx.moveTo(x, y);
1770
+ }
1771
+ else {
1772
+ ctx.lineTo(x, y);
1773
+ }
1774
+ });
1775
+ ctx.stroke();
1714
1776
  });
1715
- ctx.stroke();
1716
1777
  };
1717
- drawSegments(totalPathWidth + borderWidth * 2);
1718
- drawSegments(totalPathWidth, backgroundColor);
1778
+ drawLines(totalPathWidth + borderWidth * 2);
1779
+ drawLines(totalPathWidth, backgroundColor);
1719
1780
  ctx.restore();
1720
- }, [border, getPathSegments, level]);
1781
+ }, [border, getPathLines, level]);
1721
1782
  const drawAll = useCallback((ctx, stcContext) => {
1722
1783
  drawBorder(ctx, stcContext);
1723
1784
  // Draw stops:
@@ -1733,31 +1794,36 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1733
1794
  ctx.setLineDash(style.dashArray || []);
1734
1795
  ctx.globalAlpha = style.opacity || 1;
1735
1796
  ctx.lineCap = style.lineCap || 'square';
1736
- ctx.beginPath();
1737
- const segments = getPathSegments(stcContext);
1738
- segments.forEach(({ x, y }, i) => {
1739
- if (!i) {
1740
- ctx.moveTo(x, y);
1741
- }
1742
- else {
1743
- ctx.lineTo(x, y);
1744
- }
1797
+ const lines = getPathLines(stcContext);
1798
+ lines.forEach((points) => {
1799
+ ctx.beginPath();
1800
+ points.forEach(({ x, y }, i) => {
1801
+ if (i === 0) {
1802
+ ctx.moveTo(x, y);
1803
+ }
1804
+ else {
1805
+ ctx.lineTo(x, y);
1806
+ }
1807
+ });
1808
+ ctx.stroke();
1745
1809
  });
1746
- ctx.stroke();
1747
1810
  // Draw extremities:
1748
1811
  ctx.setLineDash([]);
1749
1812
  ctx.lineWidth = style.endWidth;
1750
1813
  drawExtremities(ctx, stcContext);
1751
1814
  // Draw label:
1752
1815
  if (!stcContext.hidePathsLabels) {
1753
- const pathLength = computePathLength(stcContext.operationalPoints, segments);
1754
- drawLabel(ctx, stcContext, path.label, color, segments, pathLength);
1816
+ const pathLength = computePathLength(stcContext.operationalPoints, lines);
1817
+ // TODO:
1818
+ // We should improve how the labels are drawn, and handle discontinuous lines (instead of
1819
+ // flattening the points)
1820
+ drawLabel(ctx, stcContext, path.label, color, flatten(lines), pathLength);
1755
1821
  }
1756
1822
  }, [
1757
1823
  color,
1758
1824
  drawPauses,
1759
1825
  level,
1760
- getPathSegments,
1826
+ getPathLines,
1761
1827
  drawExtremities,
1762
1828
  computePathLength,
1763
1829
  drawLabel,
@@ -1768,7 +1834,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1768
1834
  const drawPicking = useCallback((imageData, stcContext, scalingRatio) => {
1769
1835
  const { registerPickingElement } = stcContext;
1770
1836
  // Draw segments:
1771
- getPathSegments(stcContext).forEach((point, i, a) => {
1837
+ getPathLines(stcContext).forEach((line) => line.forEach((point, i, a) => {
1772
1838
  if (i) {
1773
1839
  const previousPoint = a[i - 1];
1774
1840
  const pickingElement = {
@@ -1781,7 +1847,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1781
1847
  const lineColor = hexToRgb(indexToColor(index));
1782
1848
  drawAliasedLine(imageData, previousPoint, point, lineColor, STYLES[level].width + pickingTolerance, true, scalingRatio);
1783
1849
  }
1784
- });
1850
+ }));
1785
1851
  // Draw snap points:
1786
1852
  getSnapPoints(stcContext).forEach((point) => {
1787
1853
  const pickingElement = {
@@ -1793,7 +1859,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1793
1859
  const lineColor = hexToRgb(indexToColor(index));
1794
1860
  drawAliasedDisc(imageData, point, (STYLES[level].width + pickingTolerance) * 2, lineColor, false, scalingRatio);
1795
1861
  });
1796
- }, [getPathSegments, getSnapPoints, level, path.id, pickingTolerance]);
1862
+ }, [getPathLines, getSnapPoints, level, path.id, pickingTolerance]);
1797
1863
  usePicking('paths', drawPicking);
1798
1864
  return null;
1799
1865
  };
@@ -1850,7 +1916,7 @@ function snapPosition(mousePosition, hoveredItem) {
1850
1916
  }
1851
1917
 
1852
1918
  const SpaceTimeChart = (props) => {
1853
- const { operationalPoints, spaceOrigin, spaceScales, timeOrigin, timeScale, xOffset = 0, yOffset = 0, swapAxis, onHoveredChildUpdate, children, additionalChildren, enableSnapping, hideGrid, hidePathsLabels, showTicks, hideDates, theme,
1919
+ const { operationalPoints, spaceOrigin, spaceScales, timeOrigin, timeScale, xOffset = 0, yOffset = 0, swapAxis, onHoveredChildUpdate, children, additionalChildren, enableSnapping, hideTimeCaptions, hideGrid, hidePathsLabels, showTicks, hideDates, theme,
1854
1920
  /* eslint-disable @typescript-eslint/no-unused-vars */
1855
1921
  onPan, onZoom, onClick, onMouseMove,
1856
1922
  /* eslint-enable @typescript-eslint/no-unused-vars */
@@ -1870,6 +1936,7 @@ const SpaceTimeChart = (props) => {
1870
1936
  xOffset,
1871
1937
  yOffset,
1872
1938
  swapAxis,
1939
+ hideTimeCaptions,
1873
1940
  hideGrid,
1874
1941
  hidePathsLabels,
1875
1942
  showTicks,
@@ -1885,6 +1952,7 @@ const SpaceTimeChart = (props) => {
1885
1952
  xOffset,
1886
1953
  yOffset,
1887
1954
  swapAxis,
1955
+ hideTimeCaptions,
1888
1956
  hideGrid,
1889
1957
  hidePathsLabels,
1890
1958
  showTicks,
@@ -1892,6 +1960,7 @@ const SpaceTimeChart = (props) => {
1892
1960
  ]);
1893
1961
  const contextState = useMemo(() => {
1894
1962
  const spaceScaleTree = spaceScalesToBinaryTree(spaceOrigin, spaceScales);
1963
+ const flatSteps = getFlatSteps(spaceScales);
1895
1964
  const timeAxis = !swapAxis ? 'x' : 'y';
1896
1965
  const spaceAxis = !swapAxis ? 'y' : 'x';
1897
1966
  // Data translation helpers:
@@ -1935,6 +2004,7 @@ const SpaceTimeChart = (props) => {
1935
2004
  operationalPoints,
1936
2005
  spaceOrigin,
1937
2006
  spaceScaleTree,
2007
+ flatSteps,
1938
2008
  timeOrigin,
1939
2009
  timeScale,
1940
2010
  timePixelOffset,
@@ -1943,6 +2013,7 @@ const SpaceTimeChart = (props) => {
1943
2013
  spaceAxis,
1944
2014
  swapAxis: !!swapAxis,
1945
2015
  enableSnapping: !!enableSnapping,
2016
+ hideTimeCaptions: !!hideTimeCaptions,
1946
2017
  hideGrid: !!hideGrid,
1947
2018
  hidePathsLabels: !!hidePathsLabels,
1948
2019
  showTicks: !!showTicks,
@@ -2270,7 +2341,13 @@ const PATH_COLOR_DEFAULT = '#8A714B';
2270
2341
 
2271
2342
  const getHeightWithoutLastWaypoint = (height) => height - FOOTER_HEIGHT - BASE_WAYPOINT_HEIGHT;
2272
2343
  const positionMmToKm = (position) => Math.round((position / 1000000) * 10) / 10;
2273
- const calcTotalDistance = (ops) => ops.at(-1).position - ops.at(0).position;
2344
+ const positionKmToMm = (position) => position * 1000000;
2345
+ const calcTotalDistance = (ops) => {
2346
+ if (ops.length === 0) {
2347
+ return 0;
2348
+ }
2349
+ return ops.at(-1).position - ops.at(0).position;
2350
+ };
2274
2351
  function getDistance(a, b) {
2275
2352
  return {
2276
2353
  x: b.x - a.x,
@@ -2278,15 +2355,15 @@ function getDistance(a, b) {
2278
2355
  };
2279
2356
  }
2280
2357
 
2281
- const Waypoint = ({ waypoint: { name, secondaryCode, id, position, onClick }, nameRef, isActive, isMenuActive, }) => (React.createElement("div", { className: cx('flex waypoint items-baseline', {
2358
+ const Waypoint = ({ waypoint: { name, secondaryCode, id, position, onClick }, waypointRef, isActive, isMenuActive, }) => (React.createElement("div", { className: cx('flex waypoint items-baseline', {
2282
2359
  'waypoint-active': isActive,
2283
2360
  'menu-active': isMenuActive,
2284
- }), id: id, onClick: () => {
2361
+ }), id: id, ref: waypointRef, onClick: () => {
2285
2362
  if (onClick && !isMenuActive)
2286
2363
  onClick(id);
2287
2364
  } },
2288
2365
  React.createElement("div", { className: "waypoint-position justify-self-start text-end" }, positionMmToKm(position)),
2289
- React.createElement("div", { ref: nameRef, className: "waypoint-name mx-2 justify-self-start" }, name),
2366
+ React.createElement("div", { className: "waypoint-name mx-2 justify-self-start" }, name),
2290
2367
  React.createElement("div", { className: "waypoint-separator" }),
2291
2368
  React.createElement("div", { className: "waypoint-ch font-mono justify-self-end" }, secondaryCode),
2292
2369
  React.createElement("div", { className: "waypoint-separator" }),
@@ -2353,9 +2430,19 @@ const selectWaypointsToDisplay = (waypoints, { height, isProportional, yZoom })
2353
2430
  * km (isProportional): { coefficient: gives a scale in meter/pixel }
2354
2431
  * linear: { size: height in pixel } (each point distributed evenly along the height of manchette.)
2355
2432
  */
2356
- const getScales = (waypoints, { isProportional, yZoom }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx) => {
2357
- if (waypoints.length < 2)
2433
+ const getScales = (waypoints, { isProportional, yZoom, height }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx) => {
2434
+ if (!waypoints.length)
2358
2435
  return [];
2436
+ if (waypoints.length === 1) {
2437
+ const waypoint = waypoints[0];
2438
+ return [
2439
+ {
2440
+ from: waypoint.position,
2441
+ to: waypoint.position,
2442
+ size: height || 1,
2443
+ },
2444
+ ];
2445
+ }
2359
2446
  if (!isProportional) {
2360
2447
  return waypoints.slice(0, -1).map((from, index) => {
2361
2448
  const to = waypoints[index + 1];
@@ -2381,52 +2468,43 @@ const getScales = (waypoints, { isProportional, yZoom }, minZoomMillimeterPerPx,
2381
2468
  };
2382
2469
  const isInteractiveWaypoint = (item) => item != null && typeof item === 'object' && 'id' in item && 'position' in item;
2383
2470
 
2384
- const Manchette = ({ zoomYIn, zoomYOut, resetZoom, yZoom = 1, contents, waypointMenuData, isProportional = true, toggleMode, children, height = INITIAL_OP_LIST_HEIGHT, }) => {
2385
- const [menuPosition, setMenuPosition] = useState();
2386
- const activeWaypointRef = useRef(null);
2387
- // Allow to track the menu position after we might have scrolled in the page
2388
- useLayoutEffect(() => {
2389
- const manchetteWrapperPosition = waypointMenuData?.manchetteWrapperRef?.current?.getBoundingClientRect().top;
2390
- const waypointPosition = activeWaypointRef?.current?.getBoundingClientRect().top;
2391
- if (!manchetteWrapperPosition || !waypointPosition) {
2392
- setMenuPosition(undefined);
2393
- }
2394
- else {
2395
- setMenuPosition(waypointPosition - manchetteWrapperPosition);
2396
- }
2397
- }, [waypointMenuData]);
2398
- return (React.createElement("div", { className: "manchette-container" },
2399
- waypointMenuData?.menu && waypointMenuData.activeWaypointId && (React.createElement("div", { className: "menu-wrapper", style: { top: menuPosition } }, waypointMenuData.menu)),
2400
- React.createElement("div", { className: "bg-white-100 border-r border-grey-30 relative", style: { minHeight: `${height}px` } },
2401
- React.createElement("div", { className: "waypoints-list" },
2402
- contents.map((content, index) => isInteractiveWaypoint(content) ? (React.createElement("div", { key: index, className: "waypoint-wrapper flex justify-start", style: content.styles },
2403
- React.createElement(Waypoint, { waypoint: content, nameRef: waypointMenuData?.activeWaypointId === content.id
2404
- ? activeWaypointRef
2405
- : undefined, isActive: waypointMenuData?.activeWaypointId === content.id, isMenuActive: !!waypointMenuData?.activeWaypointId }))) : (React.createElement(Fragment, { key: index }, content))),
2406
- children)),
2407
- React.createElement("div", { className: "manchette-actions" },
2408
- React.createElement("div", { className: "zoom-buttons" },
2409
- React.createElement("button", { className: "zoom-out", onClick: zoomYOut, disabled: yZoom <= MIN_ZOOM_Y || !!waypointMenuData?.activeWaypointId },
2410
- React.createElement(ZoomOut, null)),
2411
- React.createElement("button", { className: "zoom-in", onClick: zoomYIn, disabled: yZoom >= MAX_ZOOM_Y || !!waypointMenuData?.activeWaypointId },
2412
- React.createElement(ZoomIn, null)),
2413
- React.createElement("button", { disabled: !!waypointMenuData?.activeWaypointId, className: "zoom-reset", onClick: resetZoom }, "Fit")),
2414
- React.createElement("div", { className: "flex items-center ml-auto text-sans font-semibold" },
2415
- React.createElement("button", { disabled: !!waypointMenuData?.activeWaypointId, className: "toggle-mode", onClick: toggleMode },
2416
- React.createElement("div", { className: "flex flex-col items-end pr-2" },
2417
- React.createElement("span", { className: cx({ 'text-grey-30': !isProportional }) }, "Km"),
2418
- React.createElement("span", { className: cx({ 'text-grey-30': isProportional }) }, "Lin\u00E9aire")))))));
2419
- };
2471
+ const Manchette = ({ zoomYIn, zoomYOut, resetZoom, yZoom = 1, contents, activeWaypointId, activeWaypointRef, isProportional = true, toggleMode, children, height = INITIAL_OP_LIST_HEIGHT, }) => (React.createElement("div", { className: "manchette-container" },
2472
+ React.createElement("div", { className: "bg-white-100 border-r border-grey-30 relative", style: { minHeight: `${height}px` } },
2473
+ React.createElement("div", { className: "waypoints-list" },
2474
+ contents.map((content, index) => isInteractiveWaypoint(content) ? (React.createElement("div", { key: index, className: "waypoint-wrapper flex justify-start", style: content.styles },
2475
+ React.createElement(Waypoint, { waypoint: content, waypointRef: activeWaypointId === content.id ? activeWaypointRef : undefined, isActive: activeWaypointId === content.id, isMenuActive: !!activeWaypointId }))) : (React.createElement(Fragment, { key: index }, content))),
2476
+ children)),
2477
+ React.createElement("div", { className: "manchette-actions" },
2478
+ React.createElement("div", { className: "zoom-buttons" },
2479
+ React.createElement("button", { className: "zoom-out", onClick: zoomYOut, disabled: yZoom <= MIN_ZOOM_Y || !!activeWaypointId },
2480
+ React.createElement(ZoomOut, null)),
2481
+ React.createElement("button", { className: "zoom-in", onClick: zoomYIn, disabled: yZoom >= MAX_ZOOM_Y || !!activeWaypointId },
2482
+ React.createElement(ZoomIn, null)),
2483
+ React.createElement("button", { disabled: !!activeWaypointId, className: "zoom-reset", onClick: resetZoom }, "Fit")),
2484
+ React.createElement("div", { className: "flex items-center ml-auto text-sans font-semibold" },
2485
+ React.createElement("button", { disabled: !!activeWaypointId, className: "toggle-mode", onClick: toggleMode },
2486
+ React.createElement("div", { className: "flex flex-col items-end pr-2" },
2487
+ React.createElement("span", { className: cx({ 'text-grey-30': !isProportional }) }, "Km"),
2488
+ React.createElement("span", { className: cx({ 'text-grey-30': isProportional }) }, "Lin\u00E9aire")))))));
2420
2489
 
2421
- const WAYPOINTS_OFFSET = 16;
2422
- const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChartRef, height = 561, spaceTimeChartRef, defaultTimeOrigin = 0, defaultSpaceOrigin = 0, splitPoints = [], }) => {
2490
+ const DEFAULT_MANCHETTE_WITH_SPACE_TIME_CHART_OPTIONS = {
2491
+ displayTimeCaptions: true,
2492
+ enableTimePan: true,
2493
+ enableSpacePan: true,
2494
+ enableTimeZoom: true,
2495
+ };
2496
+ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChartRef, height = 561, spaceTimeChartRef, defaultTimeOrigin = 0, defaultSpaceOrigin = 0, defaultXOffset = 0, verticalPadding = BASE_WAYPOINT_HEIGHT / 2, splitPoints = [], options = {}, }) => {
2497
+ const { displayTimeCaptions, enableTimePan, enableSpacePan, enableTimeZoom } = useMemo(() => ({
2498
+ ...DEFAULT_MANCHETTE_WITH_SPACE_TIME_CHART_OPTIONS,
2499
+ ...options,
2500
+ }), [options]);
2423
2501
  const [isShiftPressed, setIsShiftPressed] = useState(false);
2424
2502
  const [state, setState] = useState({
2425
2503
  xZoom: timeScaleToZoomValue(DEFAULT_ZOOM_MS_PER_PX),
2426
2504
  yZoom: 1,
2427
2505
  timeOrigin: defaultTimeOrigin,
2428
2506
  spaceOrigin: defaultSpaceOrigin,
2429
- xOffset: 0,
2507
+ xOffset: defaultXOffset,
2430
2508
  yOffset: 0,
2431
2509
  scrollTo: null,
2432
2510
  panning: null,
@@ -2442,7 +2520,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2442
2520
  const setTimeOrigin = useCallback((newTimeOrigin) => {
2443
2521
  setState((prev) => ({ ...prev, timeOrigin: newTimeOrigin }));
2444
2522
  }, []);
2445
- const canvasDrawingHeight = height - FOOTER_HEIGHT; // 521
2523
+ const canvasDrawingHeight = Math.max(1 + BASE_WAYPOINT_HEIGHT, height - FOOTER_HEIGHT); // 521
2446
2524
  const drawingHeightWithoutTopPadding = canvasDrawingHeight - BASE_WAYPOINT_HEIGHT / 2; // 505
2447
2525
  const drawingHeightWithoutBothPadding = canvasDrawingHeight - BASE_WAYPOINT_HEIGHT; // 489
2448
2526
  const totalDistance = calcTotalDistance(waypoints);
@@ -2571,14 +2649,18 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2571
2649
  const resetZoom = useCallback(() => {
2572
2650
  setState((prev) => ({ ...prev, yZoom: 1 }));
2573
2651
  }, []);
2574
- const handleScroll = useCallback(() => {
2652
+ const handleScroll = useCallback((e) => {
2653
+ if (rect) {
2654
+ e.preventDefault();
2655
+ return;
2656
+ }
2575
2657
  if (!isShiftPressed && manchetteWithSpaceTimeChartRef.current) {
2576
2658
  const { scrollTop } = manchetteWithSpaceTimeChartRef.current;
2577
2659
  if (scrollTop || scrollTop === 0) {
2578
2660
  setState((prev) => ({ ...prev, yOffset: scrollTop }));
2579
2661
  }
2580
2662
  }
2581
- }, [isShiftPressed, manchetteWithSpaceTimeChartRef]);
2663
+ }, [isShiftPressed, manchetteWithSpaceTimeChartRef, rect]);
2582
2664
  const handleKeyDown = useCallback((event) => {
2583
2665
  if (event.key === 'Shift') {
2584
2666
  setIsShiftPressed(true);
@@ -2604,37 +2686,47 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2604
2686
  setState((prev) => ({ ...prev, zoomMode: !prev.zoomMode }));
2605
2687
  }, []);
2606
2688
  const handleXZoom = useCallback((newXZoom, xPosition = (spaceTimeChartRef?.current?.offsetWidth || 0) / 2) => {
2607
- setState((prev) => ({
2608
- ...prev,
2609
- ...zoomX(prev.xZoom, prev.xOffset, newXZoom, xPosition),
2610
- }));
2611
- }, [spaceTimeChartRef]);
2689
+ if (enableTimeZoom)
2690
+ setState((prev) => ({
2691
+ ...prev,
2692
+ ...zoomX(prev.xZoom, prev.xOffset, newXZoom, xPosition),
2693
+ }));
2694
+ }, [enableTimeZoom, spaceTimeChartRef]);
2612
2695
  const spaceScales = useMemo(() => {
2613
2696
  // Here, we first compute the base scales, and then we insert a flat step for each split point:
2614
- const baseScales = getScales(waypoints, { isProportional, yZoom }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx);
2697
+ const baseScales = getScales(waypoints, { height, isProportional, yZoom }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx);
2615
2698
  if (!splitPoints)
2616
2699
  return baseScales;
2617
2700
  // Constant scale:
2618
2701
  if (isProportional) {
2702
+ if (baseScales.length === 0)
2703
+ return baseScales;
2619
2704
  const baseScale = baseScales[0];
2620
2705
  const coefficient = 'coefficient' in baseScale && typeof baseScale.coefficient === 'number'
2621
2706
  ? baseScale.coefficient
2622
2707
  : (baseScale.to - baseScale.from) / baseScale.size;
2623
2708
  return splitPoints
2624
- .flatMap(({ position, size: splitPointHeight }) => [
2625
- {
2626
- to: position,
2627
- coefficient,
2628
- },
2629
- {
2709
+ .flatMap(({ position, size: splitPointHeight }) => coefficient > 0
2710
+ ? [
2711
+ {
2712
+ to: position,
2713
+ coefficient,
2714
+ },
2715
+ {
2716
+ to: position,
2717
+ size: splitPointHeight,
2718
+ },
2719
+ ]
2720
+ : {
2630
2721
  to: position,
2631
2722
  size: splitPointHeight,
2632
- },
2633
- ])
2634
- .concat({
2635
- to: baseScales.at(-1).to,
2636
- coefficient,
2637
- });
2723
+ })
2724
+ .concat(coefficient
2725
+ ? {
2726
+ to: baseScales.at(-1).to,
2727
+ coefficient,
2728
+ }
2729
+ : []);
2638
2730
  }
2639
2731
  // Varying scales:
2640
2732
  const allScales = [];
@@ -2661,7 +2753,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2661
2753
  size: point.size,
2662
2754
  });
2663
2755
  });
2664
- return sortBy(allScales, (scale) => scale.to + ('size' in scale ? Number.EPSILON : 0));
2756
+ return sortBy(allScales.filter((scale) => 'coefficient' in scale ? scale.coefficient > 0 : isFinite(scale.size)), (scale) => scale.to + ('size' in scale ? Number.EPSILON : 0));
2665
2757
  }, [
2666
2758
  waypoints,
2667
2759
  height,
@@ -2671,26 +2763,23 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2671
2763
  maxZoomMillimeterPerPx,
2672
2764
  splitPoints,
2673
2765
  ]);
2674
- const waypointsWithoutSplitPoints = useMemo(() => {
2675
- const splitPointPositions = new Set(splitPoints?.map((point) => point.position) || []);
2676
- const filteredWaypoints = selectWaypointsToDisplay(waypoints, {
2677
- height,
2678
- isProportional,
2679
- yZoom,
2680
- });
2681
- return filteredWaypoints.filter((waypoint) => !splitPointPositions.has(waypoint.position));
2682
- }, [splitPoints, waypoints, height, isProportional, yZoom]);
2766
+ const waypointsToDisplay = useMemo(() => selectWaypointsToDisplay(waypoints, {
2767
+ height,
2768
+ isProportional,
2769
+ yZoom,
2770
+ }), [waypoints, height, isProportional, yZoom]);
2683
2771
  const { manchetteContents, manchetteHeight } = useMemo(() => {
2684
2772
  const spaceScaleTree = spaceScalesToBinaryTree(spaceOrigin, spaceScales);
2685
2773
  const getSpacePixel = getSpaceToPixel(0, spaceScaleTree);
2686
- const totalManchetteHeight = Math.max(getSpacePixel(spaceScales.at(-1).to, true) + BASE_WAYPOINT_HEIGHT, height - FOOTER_HEIGHT);
2687
- if (!splitPoints)
2688
- return {
2689
- manchetteHeight: totalManchetteHeight,
2690
- manchetteContents: waypointsWithoutSplitPoints,
2691
- };
2774
+ let totalManchetteHeight = height - FOOTER_HEIGHT;
2775
+ if (spaceScales.length > 0) {
2776
+ totalManchetteHeight = Math.max(totalManchetteHeight, getSpacePixel(spaceScales.at(-1).to, true) + verticalPadding * 2);
2777
+ }
2692
2778
  // Identify all manchette contents (split sections and waypoints):
2693
- let allContents = waypointsWithoutSplitPoints.map((wp) => ({
2779
+ const splitPointPositions = new Set(splitPoints.map((point) => point.position) || []);
2780
+ let allContents = waypointsToDisplay
2781
+ .filter((wp) => !splitPointPositions.has(wp.position))
2782
+ .map((wp) => ({
2694
2783
  type: 'waypoint',
2695
2784
  waypoint: wp,
2696
2785
  position: wp.position,
@@ -2726,12 +2815,12 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2726
2815
  const { split: { position }, } = content;
2727
2816
  const top = getSpacePixel(position);
2728
2817
  finalContents.push(React.createElement("div", { style: {
2729
- // This WAYPOINTS_OFFSET correction is there because:
2730
- // - Waypoints are positioned so that their lines (at WAYPOINTS_OFFSET pixels from
2818
+ // This verticalPadding correction is there because:
2819
+ // - Waypoints are positioned so that their lines (at verticalPadding pixels from
2731
2820
  // the top) are aligned with SpaceTimeChart's space lines
2732
2821
  // - Split points are positioned so that their top is aligned with SpaceTimeChart's
2733
2822
  // space lines
2734
- top: `${top + WAYPOINTS_OFFSET}px`,
2823
+ top: `${top + verticalPadding}px`,
2735
2824
  height: `${getSpacePixel(position, true) - top}px`,
2736
2825
  position: 'absolute',
2737
2826
  width: '100%',
@@ -2744,7 +2833,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2744
2833
  manchetteHeight: totalManchetteHeight,
2745
2834
  manchetteContents: finalContents,
2746
2835
  };
2747
- }, [spaceOrigin, spaceScales, splitPoints, waypointsWithoutSplitPoints, height]);
2836
+ }, [spaceOrigin, spaceScales, verticalPadding, height, splitPoints, waypointsToDisplay]);
2748
2837
  return useMemo(() => ({
2749
2838
  manchetteProps: {
2750
2839
  contents: manchetteContents,
@@ -2758,19 +2847,21 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2758
2847
  yOffset,
2759
2848
  },
2760
2849
  spaceTimeChartProps: {
2761
- operationalPoints: waypointsWithoutSplitPoints.map((waypoint) => ({
2850
+ operationalPoints: waypointsToDisplay.map((waypoint) => ({
2762
2851
  ...waypoint,
2763
2852
  importanceLevel: 1,
2764
2853
  })),
2765
- additionalChildren: splitPoints.map((sp) => sp.spaceTimeChartNode),
2854
+ additionalChildren: splitPoints.map((sp, i) => (React.createElement(Fragment, { key: i }, sp.spaceTimeChartNode))),
2855
+ hideTimeCaptions: !displayTimeCaptions,
2766
2856
  timeScale: zoomValueToTimeScale(xZoom),
2767
2857
  xOffset,
2768
- yOffset: -yOffset + WAYPOINTS_OFFSET,
2858
+ yOffset: -yOffset + verticalPadding,
2769
2859
  timeOrigin,
2770
2860
  spaceOrigin,
2771
2861
  spaceScales,
2772
- onZoom: ({ delta, position, }) => {
2773
- if (isShiftPressed) {
2862
+ onZoom: ({ delta, position, event, }) => {
2863
+ if (isShiftPressed && !rect) {
2864
+ event.preventDefault();
2774
2865
  handleXZoom(xZoom + delta, position.x);
2775
2866
  }
2776
2867
  },
@@ -2820,14 +2911,18 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2820
2911
  }
2821
2912
  const newState = { ...prev };
2822
2913
  const { initialOffset } = panning;
2823
- newState.xOffset = initialOffset.x + diff.x;
2824
- const newYPos = initialOffset.y - diff.y;
2825
- if (manchetteWithSpaceTimeChartRef.current &&
2826
- newYPos >= 0 &&
2827
- newYPos + manchetteWithSpaceTimeChartRef.current.offsetHeight <
2828
- manchetteWithSpaceTimeChartRef.current.scrollHeight) {
2829
- newState.yOffset = newYPos;
2830
- manchetteWithSpaceTimeChartRef.current.scrollTop = newYPos;
2914
+ const manchette = manchetteWithSpaceTimeChartRef.current;
2915
+ if (enableTimePan) {
2916
+ newState.xOffset = initialOffset.x + diff.x;
2917
+ }
2918
+ if (enableSpacePan) {
2919
+ let newYOffset = initialOffset.y - diff.y;
2920
+ newYOffset = Math.max(newYOffset, 0);
2921
+ if (manchette) {
2922
+ newYOffset = Math.min(newYOffset, manchette.scrollHeight - manchette.offsetHeight);
2923
+ manchette.scrollTop = newYOffset;
2924
+ }
2925
+ newState.yOffset = newYOffset;
2831
2926
  }
2832
2927
  return newState;
2833
2928
  });
@@ -2852,13 +2947,14 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2852
2947
  yZoom,
2853
2948
  isProportional,
2854
2949
  yOffset,
2855
- waypointsWithoutSplitPoints,
2950
+ waypointsToDisplay,
2951
+ splitPoints,
2856
2952
  xZoom,
2857
2953
  xOffset,
2954
+ verticalPadding,
2858
2955
  timeOrigin,
2859
2956
  spaceOrigin,
2860
2957
  spaceScales,
2861
- splitPoints,
2862
2958
  handleScroll,
2863
2959
  handleXZoom,
2864
2960
  toggleZoomMode,
@@ -2867,10 +2963,13 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2867
2963
  minZoomMillimeterPerPx,
2868
2964
  maxZoomMillimeterPerPx,
2869
2965
  setTimeOrigin,
2966
+ displayTimeCaptions,
2870
2967
  isShiftPressed,
2871
2968
  panning,
2872
- manchetteWithSpaceTimeChartRef,
2969
+ enableTimePan,
2970
+ enableSpacePan,
2873
2971
  canvasDrawingHeight,
2972
+ manchetteWithSpaceTimeChartRef,
2874
2973
  ]);
2875
2974
  };
2876
2975
 
@@ -3509,7 +3608,7 @@ const drawSpeedLimits = ({ ctx, width, height, store }) => {
3509
3608
  }
3510
3609
  gradient.addColorStop(1, speedColor.alpha(0).hex());
3511
3610
  ctx.fillStyle = gradient;
3512
- ctx.rect(previousBoundaryX, speedY, currentBoundaryX - previousBoundaryX, -16);
3611
+ ctx.rect(previousBoundaryX, speedY, currentBoundaryX - previousBoundaryX, -GRADIENT_HEIGHT);
3513
3612
  ctx.fill();
3514
3613
  // Handle train length (only if next speed is higher than current speed)
3515
3614
  let extendedBoundaryX = null;
@@ -4647,7 +4746,9 @@ const COLORS = {
4647
4746
  GREY_50: 'rgb(121, 118, 113)',
4648
4747
  GREY_60: 'rgb(92, 89, 85)',
4649
4748
  GREY_80: 'rgb(49, 46, 43)',
4650
- HOUR_BACKGROUND: 'rgba(243, 248, 253, 0.5)',
4749
+ MANCHETTE_BACKGROUND: '#f2f0e4',
4750
+ HOUR_BACKGROUND_1: '#faf9f5',
4751
+ HOUR_BACKGROUND_2: '#f2f0e4',
4651
4752
  RAIL_TICK: 'rgb(33, 112, 185)',
4652
4753
  REMAINING_TRAINS_BACKGROUND: 'rgba(0, 0, 0, 0.7)',
4653
4754
  SELECTION_20: 'rgb(255, 242, 179)',
@@ -4739,7 +4840,7 @@ const Y_MEDIUM_POSITION_OFFSET = 14;
4739
4840
  const ROTATE_VALUE = (-30 * Math.PI) / 180;
4740
4841
  const { SANS: SANS$1, MONO } = FONTS;
4741
4842
  const { WHITE_100: WHITE_100$2, GREY_50, GREY_60, GREY_80, SELECTION_20: SELECTION_20$1 } = COLORS;
4742
- const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePixel, yPosition, isThroughTrain, selectedTrainId, }) => {
4843
+ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePixel, yPosition, isThroughTrain, isSelected, }) => {
4743
4844
  const zoneOccupancyLength = departureTimePixel - arrivalTimePixel - STROKE_WIDTH;
4744
4845
  const isBelowBreakpoint = (breakpoint) => zoneOccupancyLength < BREAKPOINTS[breakpoint];
4745
4846
  ctx.font = '400 10px IBM Plex Mono';
@@ -4761,11 +4862,11 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4761
4862
  const xArrivalPosition = isBelowBreakpoint('small') ? 'right' : 'center';
4762
4863
  const xDeparturePosition = isBelowBreakpoint('small') ? 'left' : 'center';
4763
4864
  const textStroke = {
4764
- color: selectedTrainId === zone.id ? 'transparent' : WHITE_100$2,
4865
+ color: isSelected ? 'transparent' : WHITE_100$2,
4765
4866
  width: STROKE_WIDTH,
4766
4867
  };
4767
4868
  // train name
4768
- if (selectedTrainId === zone.id) {
4869
+ if (isSelected) {
4769
4870
  const { xSelectedTrainNameBackground, ySelectedTrainNameBackground } = isBelowBreakpoint('medium')
4770
4871
  ? {
4771
4872
  xSelectedTrainNameBackground: xOriginTrainName - X_SELECTED_MEDIUM_PADDING,
@@ -4780,7 +4881,7 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4780
4881
  ctx.rotate(ROTATE_VALUE);
4781
4882
  ctx.fillStyle = SELECTION_20$1;
4782
4883
  ctx.beginPath();
4783
- ctx.roundRect(-4, 0, nameTextLength + X_BACKGROUND_PADDING$1 * 2, Y_INITIAL_POSITION_OFFSET_BACKGROUND);
4884
+ ctx.roundRect(-X_BACKGROUND_PADDING$1, 0, nameTextLength + X_BACKGROUND_PADDING$1 * 2, Y_INITIAL_POSITION_OFFSET_BACKGROUND);
4784
4885
  ctx.fill();
4785
4886
  ctx.restore();
4786
4887
  }
@@ -4799,7 +4900,9 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4799
4900
  // arrival minutes & departure minutes
4800
4901
  drawText({
4801
4902
  ctx,
4802
- text: zone.arrivalTime.getMinutes().toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
4903
+ text: new Date(zone.arrivalTime)
4904
+ .getMinutes()
4905
+ .toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
4803
4906
  x: isThroughTrain ? arrivalTimePixel - X_THROUGHTRAIN_OFFSET : arrivalTimePixel,
4804
4907
  y: yPosition + MINUTES_TEXT_OFFSET,
4805
4908
  color: GREY_80,
@@ -4811,7 +4914,9 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4811
4914
  if (!isThroughTrain)
4812
4915
  drawText({
4813
4916
  ctx,
4814
- text: zone.departureTime.getMinutes().toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
4917
+ text: new Date(zone.departureTime)
4918
+ .getMinutes()
4919
+ .toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
4815
4920
  x: departureTimePixel,
4816
4921
  y: yPosition + MINUTES_TEXT_OFFSET,
4817
4922
  color: GREY_80,
@@ -4850,15 +4955,13 @@ const { REMAINING_TRAINS_BACKGROUND, WHITE_100: WHITE_100$1, SELECTION_20 } = CO
4850
4955
  const REMAINING_TRAINS_WIDTH = 70;
4851
4956
  const REMAINING_TRAINS_HEIGHT = 24;
4852
4957
  const REMAINING_TEXT_OFFSET = 12;
4853
- const Y_OFFSET_INCREMENT = 4;
4854
- const MAX_ZONES = 9;
4855
4958
  const X_BACKGROUND_PADDING = 4;
4856
4959
  const X_TROUGHTRAIN_BACKGROUND_PADDING = 8;
4857
4960
  const BACKGROUND_HEIGHT = 40;
4858
4961
  const SELECTED_TRAIN_ID_GRADIANT = 2;
4859
- const drawDefaultZone = ({ ctx, arrivalTimePixel, departureTimePixel, yPosition }) => {
4962
+ const drawDefaultZone = (ctx, { x, y, width }) => {
4860
4963
  ctx.beginPath();
4861
- ctx.rect(arrivalTimePixel, yPosition, departureTimePixel - arrivalTimePixel, OCCUPANCY_ZONE_HEIGHT);
4964
+ ctx.rect(x, y, width, OCCUPANCY_ZONE_HEIGHT);
4862
4965
  ctx.fill();
4863
4966
  ctx.stroke();
4864
4967
  };
@@ -4867,7 +4970,7 @@ const ARROW_OFFSET_Y = 1.5;
4867
4970
  const ARROW_WIDTH = 4.5;
4868
4971
  const ARROW_TOP_Y = 3.5;
4869
4972
  const ARROW_BOTTOM_Y = 6.5;
4870
- const drawThroughTrain = ({ ctx, arrivalTimePixel, }) => {
4973
+ const drawThroughTrain = (ctx, x, y) => {
4871
4974
  // Through trains are materialized by converging arrows like the following ones
4872
4975
  // ___
4873
4976
  // \_/
@@ -4875,209 +4978,237 @@ const drawThroughTrain = ({ ctx, arrivalTimePixel, }) => {
4875
4978
  // ‾‾‾
4876
4979
  ctx.beginPath();
4877
4980
  // draw the upper part
4878
- ctx.moveTo(arrivalTimePixel - ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
4879
- ctx.lineTo(arrivalTimePixel - ARROW_WIDTH, OCCUPANCY_ZONE_Y_START - ARROW_TOP_Y);
4880
- ctx.lineTo(arrivalTimePixel + ARROW_WIDTH, OCCUPANCY_ZONE_Y_START - ARROW_TOP_Y);
4881
- ctx.lineTo(arrivalTimePixel + ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
4981
+ ctx.moveTo(x - ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4982
+ ctx.lineTo(x - ARROW_WIDTH, y - ARROW_TOP_Y);
4983
+ ctx.lineTo(x + ARROW_WIDTH, y - ARROW_TOP_Y);
4984
+ ctx.lineTo(x + ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4882
4985
  // draw the lower part
4883
- ctx.lineTo(arrivalTimePixel + ARROW_WIDTH, OCCUPANCY_ZONE_Y_START + ARROW_BOTTOM_Y);
4884
- ctx.lineTo(arrivalTimePixel - ARROW_WIDTH, OCCUPANCY_ZONE_Y_START + ARROW_BOTTOM_Y);
4885
- ctx.lineTo(arrivalTimePixel - ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
4986
+ ctx.lineTo(x + ARROW_WIDTH, y + ARROW_BOTTOM_Y);
4987
+ ctx.lineTo(x - ARROW_WIDTH, y + ARROW_BOTTOM_Y);
4988
+ ctx.lineTo(x - ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4886
4989
  ctx.fill();
4887
4990
  // draw the white separator in the middle
4888
- ctx.moveTo(arrivalTimePixel - ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
4889
- ctx.lineTo(arrivalTimePixel + ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
4991
+ ctx.moveTo(x - ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4992
+ ctx.lineTo(x + ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4890
4993
  ctx.stroke();
4891
4994
  };
4892
- const drawRemainingTrainsBox = ({ ctx, remainingTrainsNb, xPosition }) => {
4893
- const textY = OCCUPANCY_ZONE_Y_START - REMAINING_TEXT_OFFSET;
4995
+ const drawRemainingTrainsBox = (ctx, { getTimePixel, getSpacePixel }, { time, position, yOffset, remainingTrainsNb, }) => {
4996
+ const x = getTimePixel(time);
4997
+ const y = getSpacePixel(position) + yOffset;
4998
+ const textY = y + OCCUPANCY_ZONE_Y_START - REMAINING_TEXT_OFFSET;
4894
4999
  ctx.fillStyle = REMAINING_TRAINS_BACKGROUND;
4895
5000
  ctx.beginPath();
4896
- ctx.rect(xPosition, textY, REMAINING_TRAINS_WIDTH, REMAINING_TRAINS_HEIGHT);
5001
+ ctx.rect(x - REMAINING_TRAINS_WIDTH / 2, textY, REMAINING_TRAINS_WIDTH, REMAINING_TRAINS_HEIGHT);
4897
5002
  ctx.fill();
4898
5003
  ctx.stroke();
4899
5004
  ctx.fillStyle = WHITE_100$1;
4900
5005
  ctx.font = SANS;
4901
5006
  ctx.textAlign = 'center';
4902
5007
  ctx.textBaseline = 'middle';
4903
- ctx.fillText(`+${remainingTrainsNb} trains`, xPosition + REMAINING_TRAINS_WIDTH / 2, textY + REMAINING_TRAINS_HEIGHT / 2);
5008
+ ctx.fillText(`+${remainingTrainsNb} trains`, x, textY + REMAINING_TRAINS_HEIGHT / 2);
4904
5009
  };
4905
- const drawOccupationZone = ({ ctx, zone, tracks, arrivalTimePixel, departureTimePixel, yPosition, isThroughTrain, selectedTrainId, setSelectedTrainId, xMousePosition, yMousePosition, index, }) => {
4906
- let currentSelectedTrainId = selectedTrainId;
4907
- const trackN = CANVAS_PADDING + TRACK_HEIGHT_CONTAINER * index + yPosition;
4908
- const canvasHeight = CANVAS_PADDING * 2 + TRACK_HEIGHT_CONTAINER * tracks.length;
4909
- const trackPosition = canvasHeight - trackN;
4910
- const arrowOffset = isThroughTrain ? 4 : 0;
4911
- const xCheck = xMousePosition >= arrivalTimePixel - arrowOffset &&
4912
- xMousePosition <= departureTimePixel + arrowOffset;
4913
- const yCheck = Math.abs(yMousePosition) >= trackPosition - OCCUPANCY_ZONE_HEIGHT - 1 - arrowOffset &&
4914
- Math.abs(yMousePosition) <= trackPosition + 1 + arrowOffset;
4915
- if (xCheck && yCheck) {
4916
- setSelectedTrainId(zone.id);
4917
- currentSelectedTrainId = zone.id;
4918
- }
5010
+ const drawOccupationZone = (ctx, stcContext, { zone, yOffset, position, isSelected, }) => {
5011
+ const isThroughTrain = zone.arrivalTime === zone.departureTime;
4919
5012
  ctx.fillStyle = zone.color;
4920
5013
  ctx.strokeStyle = WHITE_100$1;
4921
5014
  ctx.lineJoin = 'round';
4922
5015
  ctx.lineCap = 'round';
4923
5016
  ctx.font = '400 10px IBM Plex Mono';
4924
- if (selectedTrainId === zone.id) {
5017
+ const { getTimePixel, getSpacePixel } = stcContext;
5018
+ const yStart = getCrispLineCoordinate(getSpacePixel(position), BACKGROUND_HEIGHT);
5019
+ const y = yStart + yOffset;
5020
+ const yEnd = getSpacePixel(position, true);
5021
+ const arrivalTimePixel = getTimePixel(zone.arrivalTime);
5022
+ const departureTimePixel = getTimePixel(zone.departureTime);
5023
+ if (isSelected) {
4925
5024
  const extraWidth = isThroughTrain ? X_TROUGHTRAIN_BACKGROUND_PADDING : X_BACKGROUND_PADDING;
4926
5025
  const originTextLength = ctx.measureText(zone.originStation || '--').width;
4927
5026
  const destinationTextLength = ctx.measureText(zone.destinationStation || '--').width;
4928
- ctx.save();
4929
5027
  ctx.fillStyle = SELECTION_20;
4930
5028
  ctx.beginPath();
4931
- ctx.roundRect(arrivalTimePixel - originTextLength - extraWidth, yPosition - BACKGROUND_HEIGHT / 2, departureTimePixel -
5029
+ ctx.roundRect(arrivalTimePixel - originTextLength - extraWidth, y - BACKGROUND_HEIGHT / 2, departureTimePixel -
4932
5030
  arrivalTimePixel +
4933
5031
  originTextLength +
4934
5032
  destinationTextLength +
4935
5033
  extraWidth * 2, BACKGROUND_HEIGHT, SELECTED_TRAIN_ID_GRADIANT);
4936
5034
  ctx.fill();
4937
- ctx.restore();
4938
5035
  }
5036
+ ctx.fillStyle = zone.color;
4939
5037
  if (isThroughTrain) {
4940
- drawThroughTrain({ ctx, arrivalTimePixel });
5038
+ drawThroughTrain(ctx, arrivalTimePixel, y);
4941
5039
  }
4942
5040
  else {
4943
- drawDefaultZone({ ctx, arrivalTimePixel, departureTimePixel, yPosition });
5041
+ drawDefaultZone(ctx, {
5042
+ x: arrivalTimePixel,
5043
+ y,
5044
+ width: departureTimePixel - arrivalTimePixel,
5045
+ });
5046
+ }
5047
+ // Draw dashed lines linking trains tracks occupancy to their paths on the SpaceTimeChart (when relevant):
5048
+ ctx.strokeStyle = zone.color;
5049
+ ctx.lineWidth = 1;
5050
+ ctx.setLineDash([1, 4]);
5051
+ if (zone.arrivalDirection) {
5052
+ ctx.beginPath();
5053
+ ctx.moveTo(arrivalTimePixel, y);
5054
+ ctx.lineTo(arrivalTimePixel, zone.arrivalDirection === 'up' ? yStart : yEnd);
5055
+ ctx.stroke();
5056
+ }
5057
+ if (zone.departureDirection) {
5058
+ ctx.beginPath();
5059
+ ctx.moveTo(departureTimePixel, y);
5060
+ ctx.lineTo(departureTimePixel, zone.departureDirection === 'up' ? yStart : yEnd);
5061
+ ctx.stroke();
4944
5062
  }
5063
+ ctx.setLineDash([]);
5064
+ // Draw texts:
4945
5065
  drawOccupancyZonesTexts({
4946
5066
  ctx,
4947
5067
  zone,
4948
5068
  arrivalTimePixel,
4949
5069
  departureTimePixel,
4950
- yPosition,
4951
5070
  isThroughTrain,
4952
- selectedTrainId: currentSelectedTrainId,
5071
+ yPosition: y,
5072
+ isSelected,
4953
5073
  });
4954
5074
  };
4955
- const drawOccupancyZones = ({ ctx, width, height, tracks, occupancyZones, getTimePixel, selectedTrainId, setSelectedTrainId, mousePosition, }) => {
4956
- ctx.clearRect(0, 0, width, height);
4957
- ctx.save();
4958
- if (!tracks || !occupancyZones || occupancyZones.length === 0)
4959
- return;
4960
- const sortedOccupancyZones = occupancyZones.sort((a, b) => a.arrivalTime.getTime() - b.arrivalTime.getTime());
4961
- tracks.forEach((track, index) => {
4962
- const trackTranslate = index === 0 ? CANVAS_PADDING : TRACK_HEIGHT_CONTAINER;
4963
- ctx.translate(0, trackTranslate);
4964
- const { x: xMousePosition, y: yMousePosition } = mousePosition;
4965
- const filteredOccupancyZones = sortedOccupancyZones.filter((zone) => zone.trackId === track.id);
4966
- let primaryArrivalTimePixel = 0;
4967
- let primaryDepartureTimePixel = 0;
4968
- let lastDepartureTimePixel = primaryDepartureTimePixel;
4969
- let yPosition = OCCUPANCY_ZONE_Y_START;
4970
- let yOffset = Y_OFFSET_INCREMENT;
4971
- let zoneCounter = 0;
4972
- let zoneIndex = 0;
4973
- while (zoneIndex < filteredOccupancyZones.length) {
4974
- const zone = filteredOccupancyZones[zoneIndex];
4975
- const arrivalTimePixel = getTimePixel(zone.arrivalTime.getTime());
4976
- const departureTimePixel = getTimePixel(zone.departureTime.getTime());
4977
- const isThroughTrain = arrivalTimePixel === departureTimePixel;
4978
- // * if the zone is not overlapping with any previous one, draw it in the center of the track
4979
- // * and reset the primary values
4980
- // *
4981
- // * if the zone is overlapping with the previous one, draw it below or above the previous one
4982
- // * depending on the overlapping counter
4983
- // *
4984
- // * if the zone is overlapping with the previous one and the counter is higher than the max zones
4985
- // * draw the remaining trains box
4986
- // *
4987
- if (arrivalTimePixel > lastDepartureTimePixel) {
4988
- // reset to initial value if the zone is not overlapping
4989
- yPosition = OCCUPANCY_ZONE_Y_START;
4990
- primaryArrivalTimePixel = arrivalTimePixel;
4991
- primaryDepartureTimePixel = departureTimePixel;
4992
- lastDepartureTimePixel = departureTimePixel;
4993
- yOffset = Y_OFFSET_INCREMENT;
4994
- zoneCounter = 1;
4995
- drawOccupationZone({
4996
- ctx,
4997
- zone,
4998
- tracks,
4999
- arrivalTimePixel,
5000
- departureTimePixel,
5001
- yPosition,
5002
- isThroughTrain,
5003
- selectedTrainId,
5004
- setSelectedTrainId,
5005
- index,
5006
- xMousePosition,
5007
- yMousePosition,
5008
- });
5009
- zoneIndex++;
5010
- continue;
5011
- }
5012
- if (zoneCounter < MAX_ZONES) {
5075
+
5076
+ const Y_OFFSET_INCREMENT = 4;
5077
+ const MAX_ZONES = 9;
5078
+ const OccupancyZonesLayer = ({ tracks, occupancyZones, position, topPadding, selectedTrainId, }) => {
5079
+ const instructionsToDraw = useMemo(() => {
5080
+ const instructions = [];
5081
+ if (!tracks || !occupancyZones || occupancyZones.length === 0)
5082
+ return instructions;
5083
+ const sortedOccupancyZones = occupancyZones.sort((a, b) => a.arrivalTime - b.arrivalTime);
5084
+ tracks.forEach((track, index) => {
5085
+ const trackY = topPadding + CANVAS_PADDING + index * TRACK_HEIGHT_CONTAINER;
5086
+ const filteredOccupancyZones = sortedOccupancyZones.filter((zone) => zone.trackId === track.id);
5087
+ let primaryArrivalTime = 0;
5088
+ let lastDepartureTime = 0;
5089
+ let yPosition = OCCUPANCY_ZONE_Y_START;
5090
+ let yOffset = Y_OFFSET_INCREMENT;
5091
+ let zoneCounter = 0;
5092
+ let zoneIndex = 0;
5093
+ while (zoneIndex < filteredOccupancyZones.length) {
5094
+ const zone = filteredOccupancyZones[zoneIndex];
5095
+ const { arrivalTime, departureTime } = zone;
5096
+ // * if the zone is not overlapping with any previous one, draw it in the center of the track
5097
+ // * and reset the primary values
5098
+ // *
5099
+ // * if the zone is overlapping with the previous one, draw it below or above the previous one
5100
+ // * depending on the overlapping counter
5101
+ // *
5102
+ // * if the zone is overlapping with the previous one and the counter is higher than the max zones
5103
+ // * draw the remaining trains box
5104
+ // *
5105
+ if (arrivalTime > lastDepartureTime) {
5106
+ // reset to initial value if the zone is not overlapping
5107
+ yPosition = OCCUPANCY_ZONE_Y_START;
5108
+ primaryArrivalTime = arrivalTime;
5109
+ lastDepartureTime = departureTime;
5110
+ yOffset = Y_OFFSET_INCREMENT;
5111
+ zoneCounter = 1;
5112
+ instructions.push({
5113
+ type: 'occupancyZone',
5114
+ zone,
5115
+ offsetY: trackY + yPosition,
5116
+ isSelected: zone.trainId === selectedTrainId,
5117
+ });
5118
+ zoneIndex++;
5119
+ }
5013
5120
  // if so and it's an even index, move it to the bottom, if it's an odd index, move it to the top
5014
- if (arrivalTimePixel >= primaryArrivalTimePixel) {
5015
- if (zoneCounter % 2 === 0) {
5016
- yPosition -= yOffset;
5017
- }
5018
- else {
5019
- yPosition += yOffset;
5121
+ else if (zoneCounter < MAX_ZONES) {
5122
+ if (arrivalTime >= primaryArrivalTime) {
5123
+ if (zoneCounter % 2 === 0) {
5124
+ yPosition -= yOffset;
5125
+ }
5126
+ else {
5127
+ yPosition += yOffset;
5128
+ }
5020
5129
  }
5130
+ // update the last departure time if the current zone is longer
5131
+ if (departureTime >= lastDepartureTime)
5132
+ lastDepartureTime = departureTime;
5133
+ instructions.push({
5134
+ type: 'occupancyZone',
5135
+ zone,
5136
+ offsetY: trackY + yPosition,
5137
+ isSelected: zone.trainId === selectedTrainId,
5138
+ });
5139
+ zoneCounter++;
5140
+ yOffset += Y_OFFSET_INCREMENT;
5141
+ zoneIndex++;
5142
+ }
5143
+ // else, if there are too much trains:
5144
+ else {
5145
+ const nextIndex = filteredOccupancyZones.findIndex((filteredZone, i) => i > zoneIndex && filteredZone.arrivalTime >= lastDepartureTime);
5146
+ const remainingTrainsNb = nextIndex - zoneIndex;
5147
+ instructions.push({
5148
+ type: 'remainingTrains',
5149
+ amount: remainingTrainsNb,
5150
+ time: (arrivalTime + departureTime) / 2,
5151
+ offsetY: trackY,
5152
+ });
5153
+ zoneIndex += remainingTrainsNb;
5021
5154
  }
5022
- // update the last departure time if the current zone is longer
5023
- if (departureTimePixel >= lastDepartureTimePixel)
5024
- lastDepartureTimePixel = departureTimePixel;
5025
- drawOccupationZone({
5026
- ctx,
5027
- zone,
5028
- tracks,
5029
- arrivalTimePixel,
5030
- departureTimePixel,
5031
- yPosition,
5032
- isThroughTrain,
5033
- selectedTrainId,
5034
- setSelectedTrainId,
5035
- index,
5036
- xMousePosition,
5037
- yMousePosition,
5038
- });
5039
- zoneCounter++;
5040
- yOffset += Y_OFFSET_INCREMENT;
5041
- zoneIndex++;
5042
- continue;
5043
5155
  }
5044
- const nextIndex = filteredOccupancyZones.findIndex((filteredZone, i) => i > zoneIndex &&
5045
- getTimePixel(filteredZone.arrivalTime.getTime()) >= lastDepartureTimePixel);
5046
- const remainingTrainsNb = nextIndex - zoneIndex;
5047
- const xPosition = primaryArrivalTimePixel +
5048
- (lastDepartureTimePixel - primaryArrivalTimePixel) / 2 -
5049
- REMAINING_TRAINS_WIDTH / 2;
5050
- drawRemainingTrainsBox({ ctx, remainingTrainsNb, xPosition });
5051
- zoneIndex += remainingTrainsNb;
5052
- }
5053
- });
5054
- ctx.restore();
5055
- };
5056
-
5057
- const OccupancyZonesLayer = ({ useDraw, selectedTrainId, setSelectedTrainId, mousePosition, }) => {
5058
- const drawingFunction = useCallback((ctx, { getTimePixel, tracks, occupancyZones, trackOccupancyWidth, trackOccupancyHeight }) => {
5059
- if (trackOccupancyHeight && trackOccupancyWidth)
5060
- drawOccupancyZones({
5061
- ctx,
5062
- width: trackOccupancyWidth,
5063
- height: trackOccupancyHeight,
5064
- tracks,
5065
- occupancyZones,
5066
- getTimePixel,
5067
- selectedTrainId,
5068
- setSelectedTrainId,
5069
- mousePosition,
5070
- });
5071
- }, [mousePosition, selectedTrainId, setSelectedTrainId]);
5072
- useDraw('paths', drawingFunction);
5156
+ });
5157
+ return sortBy(instructions, (instruction) => instruction.type === 'occupancyZone' && instruction.isSelected ? 0 : 1);
5158
+ }, [occupancyZones, selectedTrainId, topPadding, tracks]);
5159
+ const drawingFunction = useCallback((ctx, stcContext) => {
5160
+ instructionsToDraw.forEach((instruction) => {
5161
+ switch (instruction.type) {
5162
+ case 'occupancyZone':
5163
+ drawOccupationZone(ctx, stcContext, {
5164
+ zone: instruction.zone,
5165
+ position,
5166
+ yOffset: instruction.offsetY,
5167
+ isSelected: instruction.isSelected,
5168
+ });
5169
+ break;
5170
+ case 'remainingTrains':
5171
+ drawRemainingTrainsBox(ctx, stcContext, {
5172
+ position,
5173
+ time: instruction.time,
5174
+ yOffset: instruction.offsetY,
5175
+ remainingTrainsNb: instruction.amount,
5176
+ });
5177
+ break;
5178
+ }
5179
+ });
5180
+ }, [position, instructionsToDraw]);
5181
+ const pickingFunction = useCallback((imageData, { registerPickingElement, getTimePixel, getSpacePixel }, scalingRatio) => {
5182
+ const flatStepOffsetY = getSpacePixel(position);
5183
+ instructionsToDraw.forEach((instruction) => {
5184
+ if (instruction.type === 'occupancyZone') {
5185
+ const x = getTimePixel(instruction.zone.arrivalTime);
5186
+ const y = instruction.offsetY + flatStepOffsetY;
5187
+ const width = getTimePixel(instruction.zone.departureTime) - x;
5188
+ const height = OCCUPANCY_ZONE_HEIGHT;
5189
+ const margin = 6;
5190
+ const pickingElement = {
5191
+ type: 'occupancyZone',
5192
+ trainId: instruction.zone.trainId,
5193
+ };
5194
+ const pickingIndex = registerPickingElement(pickingElement);
5195
+ const color = hexToRgb(indexToColor(pickingIndex));
5196
+ drawAliasedRect(imageData, { x: x - margin, y: y - margin }, width + 2 * margin, height + 2 * margin, color, scalingRatio);
5197
+ }
5198
+ });
5199
+ }, [position, instructionsToDraw]);
5200
+ usePicking('overlay', pickingFunction);
5201
+ useDraw('overlay', drawingFunction);
5073
5202
  return null;
5074
5203
  };
5075
5204
 
5076
- const { WHITE_50, GREY_20, RAIL_TICK } = COLORS;
5205
+ const { WHITE_100, WHITE_50, GREY_20, RAIL_TICK } = COLORS;
5077
5206
  const drawRails = ({ xStart, yStart, width, stroke = GREY_20, ctx, }) => {
5078
- ctx.clearRect(xStart, yStart, width, 9);
5207
+ ctx.fillStyle = WHITE_100;
5208
+ ctx.fillRect(xStart, yStart, width, 9);
5079
5209
  ctx.fillStyle = WHITE_50;
5080
5210
  ctx.strokeStyle = stroke;
5211
+ ctx.lineWidth = 1;
5081
5212
  ctx.beginPath();
5082
5213
  ctx.rect(xStart, yStart, width, 8);
5083
5214
  ctx.fill();
@@ -5086,6 +5217,7 @@ const drawRails = ({ xStart, yStart, width, stroke = GREY_20, ctx, }) => {
5086
5217
  const drawTick = ({ ctx, xStart, yStart, ticks, stroke, }) => {
5087
5218
  const sumTicks = sum(ticks) / 2;
5088
5219
  ctx.strokeStyle = stroke;
5220
+ ctx.lineWidth = 1;
5089
5221
  ctx.beginPath();
5090
5222
  ctx.setLineDash(ticks);
5091
5223
  ctx.moveTo(xStart, yStart - sumTicks);
@@ -5111,33 +5243,30 @@ const drawTrack = ({ ctx, width, getTimePixel, labelMarks }) => {
5111
5243
  ctx.restore();
5112
5244
  };
5113
5245
 
5114
- const { WHITE_100, HOUR_BACKGROUND } = COLORS;
5115
- const drawBackground = ({ ctx, xStart, width, height, switchBackground, }) => {
5116
- if (xStart >= 0) {
5117
- ctx.clearRect(xStart, 0, width, height);
5118
- ctx.fillStyle = switchBackground ? HOUR_BACKGROUND : WHITE_100;
5119
- ctx.fillRect(xStart, 0, width, height);
5120
- }
5121
- };
5122
- const drawTracks = ({ ctx, width, height, tracks, timeOrigin, timePixelOffset, getTimePixel, timeRanges, breakpoints, timeScale, }) => {
5123
- ctx.clearRect(0, 0, width, height);
5124
- ctx.save();
5125
- const minT = timeOrigin - timeScale * timePixelOffset;
5126
- const maxT = minT + timeScale * width;
5127
- const pixelsPerMinute = (1 / timeScale) * 60_000;
5246
+ const { HOUR_BACKGROUND_1, HOUR_BACKGROUND_2 } = COLORS;
5247
+ const drawTracks = (ctx, stcContext, { position, tracks, drawBorders, topPadding = 0, }) => {
5248
+ const { width, getSpacePixel, getTime, getTimePixel, timeScale, theme: { breakpoints, timeRanges }, } = stcContext;
5249
+ const yStart = getSpacePixel(position);
5250
+ const yEnd = getSpacePixel(position, true);
5251
+ const flatStepHeight = yEnd - yStart;
5252
+ const timeStart = getTime(0);
5253
+ const timeEnd = getTime(width);
5254
+ const pixelsPerMinute = (1 / timeScale) * MINUTE;
5128
5255
  const labelLevels = getLabelLevels(breakpoints, pixelsPerMinute, TICKS_PRIORITIES);
5129
- const labelMarks = getLabelMarks(timeRanges, minT, maxT, labelLevels);
5130
- let switchBackground = false;
5131
- for (const t in labelMarks) {
5132
- const date = new Date(+t);
5133
- const minutes = date.getMinutes().toString().padStart(2, '0');
5134
- switch (minutes) {
5135
- case '00':
5136
- switchBackground = !switchBackground;
5137
- drawBackground({ ctx, xStart: getTimePixel(+t), width, height, switchBackground });
5138
- break;
5139
- }
5256
+ const labelMarks = getLabelMarks(timeRanges, timeStart, timeEnd, labelLevels);
5257
+ // Draw backgrounds:
5258
+ let hours = Math.floor(timeStart / HOUR);
5259
+ const hourEnd = timeEnd / HOUR;
5260
+ while (hours < hourEnd) {
5261
+ const x = getTimePixel(hours * HOUR);
5262
+ const w = getTimePixel((hours + 1) * HOUR) - x;
5263
+ ctx.fillStyle = hours % 2 ? HOUR_BACKGROUND_1 : HOUR_BACKGROUND_2;
5264
+ ctx.fillRect(x, yStart, w, flatStepHeight);
5265
+ hours++;
5140
5266
  }
5267
+ // Draw actual tracks:
5268
+ ctx.save();
5269
+ ctx.translate(0, yStart + topPadding);
5141
5270
  tracks?.forEach((_, index) => {
5142
5271
  const trackTranslate = index === 0 ? CANVAS_PADDING : TRACK_HEIGHT_CONTAINER;
5143
5272
  ctx.translate(0, trackTranslate);
@@ -5149,38 +5278,116 @@ const drawTracks = ({ ctx, width, height, tracks, timeOrigin, timePixelOffset, g
5149
5278
  });
5150
5279
  });
5151
5280
  ctx.restore();
5281
+ // Draw borders:
5282
+ if (drawBorders) {
5283
+ const externalBorderWidth = 1;
5284
+ const internalBorderWidth = 2;
5285
+ const fullBorderWidth = externalBorderWidth + internalBorderWidth;
5286
+ const yStartCrisp = Math.round(yStart);
5287
+ const yEndCrisp = Math.round(yEnd);
5288
+ ctx.fillStyle = GREY_50$2;
5289
+ ctx.fillRect(0, yStartCrisp, width, externalBorderWidth);
5290
+ ctx.fillRect(0, yEndCrisp - externalBorderWidth, width, externalBorderWidth);
5291
+ ctx.fillStyle = GREY_50$2;
5292
+ ctx.globalAlpha = 0.15;
5293
+ ctx.fillRect(0, yStartCrisp + externalBorderWidth, width, internalBorderWidth);
5294
+ ctx.fillRect(0, yEndCrisp - fullBorderWidth, width, internalBorderWidth);
5295
+ ctx.globalAlpha = 1;
5296
+ }
5152
5297
  };
5153
5298
 
5154
- const TracksLayer = ({ useDraw }) => {
5155
- const drawingFunction = useCallback((ctx, { timeOrigin, timePixelOffset, getTimePixel, tracks, trackOccupancyWidth, trackOccupancyHeight, timeScale, theme: { timeRanges, breakpoints }, }) => {
5156
- if (trackOccupancyHeight && trackOccupancyWidth)
5157
- drawTracks({
5158
- ctx,
5159
- width: trackOccupancyWidth,
5160
- height: trackOccupancyHeight,
5161
- tracks,
5162
- timeOrigin,
5163
- timePixelOffset,
5164
- getTimePixel,
5165
- timeRanges,
5166
- breakpoints,
5167
- timeScale,
5168
- });
5169
- }, []);
5170
- useDraw('background', drawingFunction);
5299
+ const TracksLayer = ({ tracks, position, topPadding, drawBorders, }) => {
5300
+ const drawingFunction = useCallback((ctx, stcContext) => {
5301
+ drawTracks(ctx, stcContext, { position, topPadding, tracks, drawBorders });
5302
+ }, [drawBorders, position, topPadding, tracks]);
5303
+ useDraw('overlay', drawingFunction);
5171
5304
  return null;
5172
5305
  };
5173
5306
 
5174
- const TrackOccupancyCanvas = ({ opId, useDraw, setCanvasesRoot, selectedTrainId, setSelectedTrainId, mousePosition, }) => (React.createElement("div", { id: `track-occupancy-canvas-${opId}`, className: "bg-white-100 canvas-container", ref: setCanvasesRoot },
5175
- React.createElement(TracksLayer, { useDraw: useDraw }),
5176
- React.createElement(OccupancyZonesLayer, { useDraw: useDraw, selectedTrainId: selectedTrainId, setSelectedTrainId: setSelectedTrainId, mousePosition: mousePosition })));
5307
+ const CloseButton = ({ position, onClose }) => {
5308
+ const { getSpacePixel } = useContext(SpaceTimeChartContext);
5309
+ return (React.createElement("button", { className: "close-track-occupancy-panel", onClick: () => onClose(), style: {
5310
+ top: getSpacePixel(position),
5311
+ } },
5312
+ React.createElement("span", null,
5313
+ React.createElement(X, null))));
5314
+ };
5315
+ const TrackOccupancyCanvas = ({ position, tracks, occupancyZones, selectedTrainId, onClose, topPadding = 0, hideBorders = false, }) => (React.createElement(React.Fragment, null,
5316
+ React.createElement(TracksLayer, { position: position, tracks: tracks, topPadding: topPadding, drawBorders: !hideBorders }),
5317
+ React.createElement(OccupancyZonesLayer, { tracks: tracks, position: position, topPadding: topPadding, occupancyZones: occupancyZones, selectedTrainId: selectedTrainId }),
5318
+ onClose && React.createElement(CloseButton, { position: position, onClose: onClose })));
5319
+
5320
+ const TrackOccupancyManchette = ({ tracks, children }) => (React.createElement("div", { className: "track-occupancy-manchette" },
5321
+ children,
5322
+ tracks.map((track) => (
5323
+ // height is shared between manchette and canvas components
5324
+ React.createElement("div", { className: "track", key: track.id, style: { height: TRACK_HEIGHT_CONTAINER } },
5325
+ React.createElement("span", { className: "track-line" }, track.line),
5326
+ React.createElement("div", { className: "track-name" }, track.name),
5327
+ React.createElement("div", { className: "track-rail" }))))));
5177
5328
 
5178
- const TrackOccupancyManchette = ({ tracks }) => (React.createElement("div", { id: "track-occupancy-manchette" }, tracks.map((track) => (
5179
- // height is shared between manchette and canvas components
5180
- React.createElement("div", { className: "track", key: track.id, style: { height: TRACK_HEIGHT_CONTAINER } },
5181
- React.createElement("span", { className: "track-line" }, track.line),
5182
- React.createElement("div", { className: "track-name" }, track.name),
5183
- React.createElement("div", { className: "track-rail" }))))));
5329
+ const TrackOccupancyStandalone = ({ tracks, occupancyZones, selectedTrainId, onSelectedTrainIdChange, height = TRACK_HEIGHT_CONTAINER * tracks.length + DEFAULT_THEME.timeCaptionsSize, }) => {
5330
+ const manchetteWithSpaceTimeChartRef = useRef(null);
5331
+ const spaceTimeChartRef = useRef(null);
5332
+ const defaultTimeOrigin = useMemo(() => {
5333
+ const minTime = Math.min(...(occupancyZones.map((zone) => zone.arrivalTime) || Date.now()));
5334
+ // Take first round hour before minTime:
5335
+ return Math.floor(minTime / HOUR) * HOUR;
5336
+ }, [occupancyZones]);
5337
+ // To make SpaceTimeChart and Manchette work, we have to provide them some dummy data:
5338
+ const waypoints = useMemo(() => [
5339
+ {
5340
+ id: 'FAKE_WAYPOINT_1',
5341
+ position: 0,
5342
+ },
5343
+ ], []);
5344
+ const splitPoints = useMemo(() => [
5345
+ {
5346
+ id: 'ACTUAL_TRACK_OCCUPANCY_DIAGRAM',
5347
+ position: 0,
5348
+ size: Math.max(height, tracks.length * TRACK_HEIGHT_CONTAINER + DEFAULT_THEME.timeCaptionsSize),
5349
+ spaceTimeChartNode: (React.createElement(TrackOccupancyCanvas, { position: 0, tracks: tracks, occupancyZones: occupancyZones, selectedTrainId: selectedTrainId, hideBorders: true })),
5350
+ manchetteNode: React.createElement(TrackOccupancyManchette, { tracks: tracks }),
5351
+ },
5352
+ ], [height, tracks, occupancyZones, selectedTrainId]);
5353
+ /**
5354
+ * We now use useManchetteWithSpaceTimeChart, to get proper pan along the time (and space axis if
5355
+ * the container is smaller than the contents):
5356
+ */
5357
+ const { manchetteProps, spaceTimeChartProps, handleScroll } = useManchetteWithSpaceTimeChart({
5358
+ waypoints,
5359
+ manchetteWithSpaceTimeChartRef,
5360
+ height,
5361
+ spaceTimeChartRef,
5362
+ splitPoints,
5363
+ defaultTimeOrigin,
5364
+ verticalPadding: 0,
5365
+ options: {
5366
+ displayTimeCaptions: true,
5367
+ enableTimePan: true,
5368
+ enableSpacePan: true,
5369
+ enableTimeZoom: false,
5370
+ },
5371
+ });
5372
+ return (React.createElement("div", { className: "track-occupancy-standalone flex flex-col" },
5373
+ React.createElement("div", { className: "bg-ambientB-5 flex flex-col justify-center main-container-header grow-0 shrink-0" },
5374
+ React.createElement(KebabHorizontal, null)),
5375
+ React.createElement("div", { className: "manchette-space-time-chart-wrapper", style: { maxHeight: height } },
5376
+ React.createElement("div", { ref: manchetteWithSpaceTimeChartRef, className: "manchette flex h-100", onScroll: handleScroll, style: { height } },
5377
+ React.createElement(Manchette, { ...manchetteProps }),
5378
+ React.createElement("div", { className: "space-time-chart-container w-full sticky", ref: spaceTimeChartRef },
5379
+ React.createElement(SpaceTimeChart, { className: "inset-0 absolute h-full", ...spaceTimeChartProps, onClick: onSelectedTrainIdChange &&
5380
+ (({ hoveredItem }) => {
5381
+ if (hoveredItem?.layer === 'overlay' &&
5382
+ hoveredItem.element.type === 'occupancyZone') {
5383
+ const newId = hoveredItem.element.trainId;
5384
+ onSelectedTrainIdChange(newId === selectedTrainId ? undefined : newId);
5385
+ }
5386
+ else {
5387
+ onSelectedTrainIdChange(undefined);
5388
+ }
5389
+ }) }))))));
5390
+ };
5184
5391
 
5185
- export { CanvasContext, ConflictLayer, ConflictTooltip, DEFAULT_LEVEL, DEFAULT_THEME, DEFAULT_ZOOM_MS_PER_PX, Manchette, ManchetteWithSpaceTimeChart, MouseContext, OccupancyBlockLayer, PathLayer, PatternRect, Quadrilateral, SpaceTimeChart, SpaceTimeChartContext, SpeedSpaceChart, TimeCaptions, Tooltip$1 as Tooltip, TrackOccupancyCanvas, TrackOccupancyManchette, WorkScheduleLayer, ZoomRect, getCrispLineCoordinate, getSpaceAtTime, isConflictPickingElement, isInteractiveWaypoint, isPathOnScreen, isPointPickingElement, isSegmentPickingElement, positionMmToKm, timeScaleToZoomValue, useDraw, useManchetteWithSpaceTimeChart, usePaths, usePicking };
5392
+ export { 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, getCrispLineCoordinate, getSpaceAtTime, isConflictPickingElement, isInteractiveWaypoint, isPathOnScreen, isPointPickingElement, isSegmentPickingElement, positionKmToMm, positionMmToKm, timeScaleToZoomValue, useDraw, useManchetteWithSpaceTimeChart, usePaths, usePicking };
5186
5393
  //# sourceMappingURL=index.esm.js.map