@osrd-project/ui-charts 0.0.74 → 0.0.78

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 (31) hide show
  1. package/README.md +22 -19
  2. package/dist/index.esm.js +744 -413
  3. package/dist/index.esm.js.map +1 -1
  4. package/dist/manchette/components/Manchette.d.ts +4 -3
  5. package/dist/manchette/components/Waypoint.d.ts +6 -4
  6. package/dist/manchette/hooks/useManchetteWithSpaceTimeChart.d.ts +13 -3
  7. package/dist/manchette/index.d.ts +5 -4
  8. package/dist/manchette/types.d.ts +0 -5
  9. package/dist/manchette/utils/helpers.d.ts +1 -5
  10. package/dist/manchette/utils/index.d.ts +3 -2
  11. package/dist/spaceTimeChart/index.d.ts +1 -0
  12. package/dist/spaceTimeChart/lib/types.d.ts +4 -6
  13. package/dist/spaceTimeChart/utils/__tests__/scales.spec.d.ts +1 -0
  14. package/dist/spaceTimeChart/utils/scales.d.ts +29 -0
  15. package/dist/speedSpaceChart/components/common/InteractionButtons.d.ts +2 -1
  16. package/dist/speedSpaceChart/components/common/SettingsPanel.d.ts +2 -1
  17. package/dist/speedSpaceChart/components/hooks.d.ts +1 -1
  18. package/dist/theme.css +1683 -2656
  19. package/dist/theme.css.map +1 -1
  20. package/dist/trackOccupancyDiagram/components/TrackOccupancyCanvas.d.ts +10 -2
  21. package/dist/trackOccupancyDiagram/components/TrackOccupancyManchette.d.ts +5 -3
  22. package/dist/trackOccupancyDiagram/components/TrackOccupancyStandalone.d.ts +10 -0
  23. package/dist/trackOccupancyDiagram/components/consts.d.ts +3 -1
  24. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawOccupancyZones.d.ts +13 -14
  25. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawOccupancyZonesTexts.d.ts +2 -2
  26. package/dist/trackOccupancyDiagram/components/helpers/drawElements/drawTracks.d.ts +7 -15
  27. package/dist/trackOccupancyDiagram/components/layers/OccupancyZonesLayer.d.ts +9 -9
  28. package/dist/trackOccupancyDiagram/components/layers/TracksLayer.d.ts +6 -3
  29. package/dist/trackOccupancyDiagram/components/types.d.ts +14 -22
  30. package/dist/trackOccupancyDiagram/index.d.ts +4 -0
  31. package/package.json +10 -10
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);
@@ -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:
@@ -1275,6 +1279,7 @@ function validateTheme({ breakpoints, timeRanges, timeCaptionsStyles, timeCaptio
1275
1279
  throw new Error(`${PREFIX}: there should be a timeGraduationsStyles for value 1.`);
1276
1280
  }
1277
1281
 
1282
+ /* eslint-disable @typescript-eslint/no-use-before-define */
1278
1283
  /**
1279
1284
  * This function helps to index a sequence of consecutive scales into a binary tree, to make it
1280
1285
  * faster to find which scale contains any given position.
@@ -1350,6 +1355,20 @@ function spaceScalesToBinaryTree(spaceOrigin, spaceScales, skipSiblingReferences
1350
1355
  }
1351
1356
  return buildTree(normalizedScales);
1352
1357
  }
1358
+ /**
1359
+ * This function takes a sequence of SpaceScales, identifies the flat steps (i.e. the scales that do
1360
+ * not increase the position), and returns them in a set.
1361
+ */
1362
+ function getFlatSteps(spaceScales) {
1363
+ const flatSteps = [];
1364
+ for (let i = 1; i < spaceScales.length; i++) {
1365
+ const { to: previous } = spaceScales[i - 1];
1366
+ const { to: current } = spaceScales[i];
1367
+ if (previous === current)
1368
+ flatSteps.push(current);
1369
+ }
1370
+ return new Set(flatSteps);
1371
+ }
1353
1372
  /**
1354
1373
  * This function takes a NormalizedScaleTree and a position, and returns the leaf node from the
1355
1374
  * tree that contains that position.
@@ -1407,7 +1426,12 @@ function getPixelToTime(timeOrigin, pixelOffset, timeScale) {
1407
1426
  }
1408
1427
  function getSpaceToPixel(pixelOffset, binaryTree) {
1409
1428
  return (position, fromEnd) => {
1410
- const { from, pixelFrom, coefficient } = getNormalizedScaleAtPosition(position, binaryTree, fromEnd);
1429
+ const { from, pixelFrom, pixelTo, coefficient } = getNormalizedScaleAtPosition(position, binaryTree, fromEnd);
1430
+ // Rare case where coefficient is 0:
1431
+ // (occurs when there is just a flat step, for instance)
1432
+ if (coefficient === 0)
1433
+ return pixelOffset + (fromEnd ? pixelTo : pixelFrom);
1434
+ // Normal case: We simply interpolate
1411
1435
  return pixelOffset + pixelFrom + (position - from) / coefficient;
1412
1436
  };
1413
1437
  }
@@ -1470,10 +1494,37 @@ function getSpaceBreakpoints(from, to, tree) {
1470
1494
  }
1471
1495
  return res;
1472
1496
  }
1497
+ /**
1498
+ * in most cases, after the rectangle zoom, the screen will be centered
1499
+ * on the center of the rectangle the user drew.
1500
+ * In case we reach max zoom, not to break this expectation we need a different offset calculation
1501
+ */
1502
+ function computeRectZoomOffsets({ rect, timeOrigin, spaceOrigin, newTimeScale, newSpaceScale, swapAxes, chartWidth, chartHeight, }) {
1503
+ const chartTimeSizePx = !swapAxes ? chartWidth : chartHeight;
1504
+ const chartSpaceSizePx = !swapAxes ? chartHeight : chartWidth;
1505
+ const timeOffset = sideOffset(timeOrigin, newTimeScale, rect.timeStart, rect.timeEnd, chartTimeSizePx);
1506
+ const spaceOffset = sideOffset(spaceOrigin, newSpaceScale, rect.spaceStart, rect.spaceEnd, chartSpaceSizePx);
1507
+ return !swapAxes
1508
+ ? { xOffset: timeOffset, yOffset: spaceOffset }
1509
+ : { xOffset: spaceOffset, yOffset: timeOffset };
1510
+ }
1511
+ function sideOffset(origin, newScale, rectStart, rectEnd, chartSideSizePx, axisPadding = 0) {
1512
+ const rectCenter = (Number(rectStart) + Number(rectEnd)) / 2;
1513
+ const newChartSize = chartSideSizePx * newScale;
1514
+ // newChartBorder is the x or y origin after zoom
1515
+ // it’s normally the same as rectStart (the left or top most part of the rectangle)
1516
+ // but if we reach max zoom we can’t use rectStart as the chart displayed origin
1517
+ // because it doesn’t garentees that the zoom rectangle stays exactly at the center of the chart after the zoom
1518
+ const newChartBorder = rectCenter - newChartSize / 2;
1519
+ return (origin - newChartBorder) / newScale - axisPadding * 2;
1520
+ }
1473
1521
 
1474
1522
  const DEFAULT_PICKING_TOLERANCE = 5;
1475
1523
  const PAUSE_THICKNESS = 7;
1476
1524
  const PAUSE_OPACITY = 0.2;
1525
+ const CIRCLE_RADIUS = 4;
1526
+ const VERTICAL_LINE_HEIGHT = 18;
1527
+ const TEXT_PADDING = 3;
1477
1528
  function isPointPickingElement(element) {
1478
1529
  return element.type === 'point';
1479
1530
  }
@@ -1511,20 +1562,27 @@ const DEFAULT_LEVEL = 2;
1511
1562
  */
1512
1563
  const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFAULT_PICKING_TOLERANCE, border, }) => {
1513
1564
  /**
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.
1565
+ * This function returns the list of points to join to draw the path. As it can be discontinuous,
1566
+ * it is returned as a Point[][]. For now, the only case for discontinuous paths is when the path
1567
+ * stops on or crosses a flat step (in which case, we assume the path will be drawn differently
1568
+ * in the flat step layer).
1569
+ *
1570
+ * It will be both used to render the visible path, and the segments on the picking layer.
1516
1571
  */
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({
1572
+ const getPathLines = useCallback(({ getTimePixel, getSpacePixel, spaceScaleTree, flatSteps, timeAxis, spaceAxis, width, height, }) => {
1573
+ const lines = [];
1574
+ let currentLine = [];
1575
+ const { points } = path;
1576
+ for (let i = 0; i < points.length; i++) {
1577
+ const { position, time } = points[i];
1578
+ if (i === 0) {
1579
+ currentLine.push({
1522
1580
  [timeAxis]: getTimePixel(time),
1523
1581
  [spaceAxis]: getSpacePixel(position),
1524
1582
  });
1525
1583
  }
1526
1584
  else {
1527
- const { position: prevPosition, time: prevTime } = a[i - 1];
1585
+ const { position: prevPosition, time: prevTime } = points[i - 1];
1528
1586
  const spaceBreakPoints = getSpaceBreakpoints(prevPosition, position, spaceScaleTree);
1529
1587
  let previousBreakPosition = -Infinity;
1530
1588
  spaceBreakPoints.forEach((breakPosition, index) => {
@@ -1538,24 +1596,47 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1538
1596
  : false;
1539
1597
  const breakTime = prevTime +
1540
1598
  ((breakPosition - prevPosition) / (position - prevPosition)) * (time - prevTime);
1541
- res.push({
1599
+ currentLine.push({
1542
1600
  [timeAxis]: getTimePixel(breakTime),
1543
1601
  [spaceAxis]: getSpacePixel(breakPosition, readSpacePixelFromEnd),
1544
1602
  });
1545
1603
  previousBreakPosition = breakPosition;
1546
1604
  });
1547
- res.push({
1605
+ const newPoint = {
1548
1606
  [timeAxis]: getTimePixel(time),
1549
1607
  [spaceAxis]: getSpacePixel(position),
1550
- });
1608
+ };
1609
+ if (position === prevPosition && flatSteps.has(position)) {
1610
+ lines.push(currentLine);
1611
+ currentLine = [newPoint];
1612
+ }
1613
+ else if (time === prevTime) {
1614
+ lines.push(currentLine);
1615
+ currentLine = [newPoint];
1616
+ }
1617
+ else {
1618
+ currentLine.push(newPoint);
1619
+ }
1551
1620
  }
1621
+ }
1622
+ lines.push(currentLine);
1623
+ // Only keep segments that intersect with the current visible time frame:
1624
+ const visibleLines = [];
1625
+ const minPixel = 0;
1626
+ const maxPixel = timeAxis === 'x' ? width : height;
1627
+ lines.forEach((line) => {
1628
+ const lastPointBeforeMinIndex = line.findLastIndex((p) => p[timeAxis] < minPixel);
1629
+ const firstPointAfterMaxIndex = line.findIndex((p) => p[timeAxis] > maxPixel);
1630
+ const visibleLine = line.slice(lastPointBeforeMinIndex === -1 ? 0 : lastPointBeforeMinIndex, (firstPointAfterMaxIndex === -1 ? line.length : firstPointAfterMaxIndex) + 1);
1631
+ if (visibleLine.length)
1632
+ visibleLines.push(visibleLine);
1552
1633
  });
1553
- return res;
1634
+ return visibleLines;
1554
1635
  }, [path]);
1555
1636
  /**
1556
1637
  * This function returns the list of important points, where the mouse can snap.
1557
1638
  */
1558
- const getSnapPoints = useCallback(({ getTimePixel, getSpacePixel, timeAxis, spaceAxis, operationalPoints, }) => {
1639
+ const getSnapPoints = useCallback(({ getTimePixel, getSpacePixel, timeAxis, spaceAxis, operationalPoints, width, height, }) => {
1559
1640
  const res = [];
1560
1641
  const stopPositions = new Set(operationalPoints.map((p) => p.position));
1561
1642
  path.points.forEach(({ position, time }) => {
@@ -1565,8 +1646,10 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1565
1646
  [spaceAxis]: getSpacePixel(position),
1566
1647
  });
1567
1648
  });
1568
- return res;
1569
- }, [path]);
1649
+ // Only keep visible points:
1650
+ const radius = STYLES[level].width + pickingTolerance;
1651
+ return res.filter((p) => inRange(p.x, -radius, width + radius) && inRange(p.y, -radius, height + radius));
1652
+ }, [level, path.points, pickingTolerance]);
1570
1653
  /**
1571
1654
  * This function draws the stops of the path on the operational points.
1572
1655
  */
@@ -1576,9 +1659,11 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1576
1659
  if (i) {
1577
1660
  const { position: prevPosition, time: prevTime } = a[i - 1];
1578
1661
  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);
1662
+ // Only draw the stop when there is no flat step
1663
+ // (i.e. when there's only one space pixel):
1664
+ const rawPixels = getSpacePixels(getSpacePixel, position);
1665
+ if (rawPixels.length === 1) {
1666
+ const spacePixel = getCrispLineCoordinate(rawPixels[0], ctx.lineWidth);
1582
1667
  ctx.beginPath();
1583
1668
  if (!swapAxis) {
1584
1669
  ctx.moveTo(getTimePixel(prevTime), spacePixel);
@@ -1589,11 +1674,37 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1589
1674
  ctx.lineTo(spacePixel, getTimePixel(time));
1590
1675
  }
1591
1676
  ctx.stroke();
1592
- });
1677
+ }
1593
1678
  }
1594
1679
  }
1595
1680
  });
1596
1681
  }, [path]);
1682
+ /**
1683
+ * This function draws the label with a background.
1684
+ * It is used to draw the label of the path or single point, with a background to make it more readable.
1685
+ */
1686
+ const drawLabelWithBackground = useCallback((ctx, text, x, y, { textColor, background, fontSize, fontFamily, padding = TEXT_PADDING, alpha = 0.75, }) => {
1687
+ ctx.save();
1688
+ ctx.font = `${fontSize}px ${fontFamily}`;
1689
+ const measure = ctx.measureText(text);
1690
+ const left = measure.actualBoundingBoxLeft;
1691
+ const right = measure.actualBoundingBoxRight;
1692
+ const ascent = measure.actualBoundingBoxAscent;
1693
+ const descent = measure.actualBoundingBoxDescent;
1694
+ const w = left + right + 2 * padding;
1695
+ const h = ascent + descent + 2 * padding;
1696
+ const rx = x - left - padding;
1697
+ const ry = y - ascent - padding;
1698
+ // BACKGROUND
1699
+ ctx.globalAlpha = alpha;
1700
+ ctx.fillStyle = background;
1701
+ ctx.fillRect(rx, ry, w, h);
1702
+ // TEXT
1703
+ ctx.globalAlpha = 1;
1704
+ ctx.fillStyle = textColor;
1705
+ ctx.fillText(text, x, y);
1706
+ ctx.restore();
1707
+ }, []);
1597
1708
  /**
1598
1709
  * This function draws the label of the path.
1599
1710
  */
@@ -1637,23 +1748,21 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1637
1748
  ctx.save();
1638
1749
  ctx.translate(position.x, position.y);
1639
1750
  ctx.rotate(angle);
1640
- ctx.font = `${fontSize}px ${fontFamily}`;
1641
1751
  ctx.textAlign = 'start';
1642
1752
  const padding = 2;
1643
1753
  const measure = ctx.measureText(label);
1644
1754
  const w = measure.width + 2 * padding;
1645
- const actualBoundingBoxHeight = measure.actualBoundingBoxAscent + measure.actualBoundingBoxDescent;
1646
- const h = actualBoundingBoxHeight + 2 * padding;
1647
1755
  const dx = w < pathLength ? 5 : (pathLength - w) / 2; // Progressively center the label if the path is shorter than the label
1648
1756
  const dy = angle >= 0 ? -5 : 15;
1649
- ctx.globalAlpha = 0.75;
1650
- ctx.fillStyle = background;
1651
- ctx.fillRect(dx - padding, dy - h + padding, w, h);
1652
- ctx.fillStyle = labelColor;
1653
- ctx.globalAlpha = 1;
1654
- ctx.fillText(label, dx, dy);
1757
+ drawLabelWithBackground(ctx, label, dx, dy, {
1758
+ fontSize,
1759
+ fontFamily,
1760
+ textColor: labelColor,
1761
+ background,
1762
+ padding,
1763
+ });
1655
1764
  ctx.restore();
1656
- }, []);
1765
+ }, [drawLabelWithBackground]);
1657
1766
  /**
1658
1767
  * This function draws the extremities of the path.
1659
1768
  */
@@ -1667,7 +1776,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1667
1776
  drawPathExtremity(ctx, getTimePixel(from.time), getSpacePixel(from.position), swapAxis, 'from', getPathDirection(path, 0), fromEnd);
1668
1777
  drawPathExtremity(ctx, getTimePixel(to.time), getSpacePixel(to.position), swapAxis, 'to', getPathDirection(path, path.points.length - 1, true), toEnd);
1669
1778
  }, [path]);
1670
- const computePathLength = useCallback((operationalPoints, segments) => {
1779
+ const computePathLength = useCallback((operationalPoints, lines) => {
1671
1780
  let totalLength = 0;
1672
1781
  // Compute length of pauses
1673
1782
  const stopPositions = new Set(operationalPoints.map((p) => p.position));
@@ -1680,11 +1789,13 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1680
1789
  }
1681
1790
  });
1682
1791
  // 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
- }
1792
+ lines.forEach((line) => {
1793
+ line.forEach(({ x, y }, i, a) => {
1794
+ if (i > 0) {
1795
+ const { x: prevX, y: prevY } = a[i - 1];
1796
+ totalLength += Math.sqrt(Math.pow(prevX - x, 2) + Math.pow(prevY - y, 2));
1797
+ }
1798
+ });
1688
1799
  });
1689
1800
  return totalLength;
1690
1801
  }, [path]);
@@ -1695,30 +1806,66 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1695
1806
  const mainPathStyle = STYLES[level];
1696
1807
  const totalPathWidth = border.offset * 2 + mainPathStyle.width;
1697
1808
  const backgroundColor = border.backgroundColor || '#fff';
1698
- const segments = getPathSegments(stcContext);
1809
+ const lines = getPathLines(stcContext);
1699
1810
  ctx.save();
1700
- ctx.beginPath();
1701
- const drawSegments = (lineWidth, borderColor = border.color) => {
1811
+ const drawLines = (lineWidth, borderColor = border.color) => {
1702
1812
  ctx.strokeStyle = borderColor;
1703
1813
  ctx.lineWidth = lineWidth;
1704
1814
  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
- }
1815
+ lines.forEach((segments) => {
1816
+ ctx.beginPath();
1817
+ segments.forEach(({ x, y }, i) => {
1818
+ if (x === segments[i - 1]?.x && y === segments[i - 1]?.y)
1819
+ return;
1820
+ if (i === 0) {
1821
+ ctx.moveTo(x, y);
1822
+ }
1823
+ else {
1824
+ ctx.lineTo(x, y);
1825
+ }
1826
+ });
1827
+ ctx.stroke();
1714
1828
  });
1715
- ctx.stroke();
1716
1829
  };
1717
- drawSegments(totalPathWidth + borderWidth * 2);
1718
- drawSegments(totalPathWidth, backgroundColor);
1830
+ drawLines(totalPathWidth + borderWidth * 2);
1831
+ drawLines(totalPathWidth, backgroundColor);
1719
1832
  ctx.restore();
1720
- }, [border, getPathSegments, level]);
1833
+ }, [border, getPathLines, level]);
1834
+ const drawSinglePoint = useCallback((ctx, stcContext, point) => {
1835
+ const { getPoint, hidePathsLabels, theme: { background, pathsStyles: { fontSize, fontFamily }, }, } = stcContext;
1836
+ const { x, y } = getPoint(point);
1837
+ const style = STYLES[level];
1838
+ ctx.save();
1839
+ ctx.strokeStyle = color;
1840
+ ctx.lineWidth = style.width;
1841
+ ctx.setLineDash((style.dashArray || []).map((v) => v / 2));
1842
+ // Draw the vertical lines above and below the circle
1843
+ ctx.beginPath();
1844
+ ctx.moveTo(x, y - VERTICAL_LINE_HEIGHT / 2);
1845
+ ctx.lineTo(x, y + VERTICAL_LINE_HEIGHT / 2);
1846
+ ctx.stroke();
1847
+ // Draw the circle
1848
+ ctx.beginPath();
1849
+ ctx.arc(x, y, CIRCLE_RADIUS, 0, Math.PI * 2);
1850
+ ctx.stroke();
1851
+ // Draw the label
1852
+ if (!hidePathsLabels) {
1853
+ ctx.textAlign = 'center';
1854
+ const labelY = y - CIRCLE_RADIUS - VERTICAL_LINE_HEIGHT - TEXT_PADDING;
1855
+ drawLabelWithBackground(ctx, path.label, x, labelY, {
1856
+ fontFamily,
1857
+ fontSize,
1858
+ textColor: color,
1859
+ background,
1860
+ });
1861
+ }
1862
+ ctx.restore();
1863
+ }, [level, color, drawLabelWithBackground, path.label]);
1721
1864
  const drawAll = useCallback((ctx, stcContext) => {
1865
+ if (path.points.length === 1) {
1866
+ drawSinglePoint(ctx, stcContext, path.points[0]);
1867
+ return;
1868
+ }
1722
1869
  drawBorder(ctx, stcContext);
1723
1870
  // Draw stops:
1724
1871
  ctx.strokeStyle = color;
@@ -1733,42 +1880,60 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1733
1880
  ctx.setLineDash(style.dashArray || []);
1734
1881
  ctx.globalAlpha = style.opacity || 1;
1735
1882
  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
- }
1883
+ const lines = getPathLines(stcContext);
1884
+ lines.forEach((points) => {
1885
+ ctx.beginPath();
1886
+ points.forEach(({ x, y }, i) => {
1887
+ if (i === 0) {
1888
+ ctx.moveTo(x, y);
1889
+ }
1890
+ else {
1891
+ ctx.lineTo(x, y);
1892
+ }
1893
+ });
1894
+ ctx.stroke();
1745
1895
  });
1746
- ctx.stroke();
1747
1896
  // Draw extremities:
1748
1897
  ctx.setLineDash([]);
1749
1898
  ctx.lineWidth = style.endWidth;
1750
1899
  drawExtremities(ctx, stcContext);
1751
1900
  // Draw label:
1752
1901
  if (!stcContext.hidePathsLabels) {
1753
- const pathLength = computePathLength(stcContext.operationalPoints, segments);
1754
- drawLabel(ctx, stcContext, path.label, color, segments, pathLength);
1902
+ const pathLength = computePathLength(stcContext.operationalPoints, lines);
1903
+ // TODO:
1904
+ // We should improve how the labels are drawn, and handle discontinuous lines (instead of
1905
+ // flattening the points)
1906
+ drawLabel(ctx, stcContext, path.label, color, flatten(lines), pathLength);
1755
1907
  }
1756
1908
  }, [
1909
+ path.points,
1910
+ path.label,
1911
+ drawBorder,
1757
1912
  color,
1758
1913
  drawPauses,
1759
1914
  level,
1760
- getPathSegments,
1915
+ getPathLines,
1761
1916
  drawExtremities,
1917
+ drawSinglePoint,
1762
1918
  computePathLength,
1763
1919
  drawLabel,
1764
- drawBorder,
1765
- path.label,
1766
1920
  ]);
1767
1921
  useDraw('paths', drawAll);
1768
1922
  const drawPicking = useCallback((imageData, stcContext, scalingRatio) => {
1769
1923
  const { registerPickingElement } = stcContext;
1924
+ // Draw single point:
1925
+ if (path.points.length === 1) {
1926
+ const pickingElement = {
1927
+ type: 'point',
1928
+ pathId: path.id,
1929
+ point: stcContext.getPoint(path.points[0]),
1930
+ };
1931
+ const index = registerPickingElement(pickingElement);
1932
+ const pointColor = hexToRgb(indexToColor(index));
1933
+ drawAliasedDisc(imageData, pickingElement.point, VERTICAL_LINE_HEIGHT / 2, pointColor, false, scalingRatio);
1934
+ }
1770
1935
  // Draw segments:
1771
- getPathSegments(stcContext).forEach((point, i, a) => {
1936
+ getPathLines(stcContext).forEach((line) => line.forEach((point, i, a) => {
1772
1937
  if (i) {
1773
1938
  const previousPoint = a[i - 1];
1774
1939
  const pickingElement = {
@@ -1779,9 +1944,13 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1779
1944
  };
1780
1945
  const index = registerPickingElement(pickingElement);
1781
1946
  const lineColor = hexToRgb(indexToColor(index));
1947
+ // Skip segments linking two points on the same time value (these are flat steps, and paths shouldn't be
1948
+ // actionable on these steps):
1949
+ if (previousPoint[stcContext.timeAxis] === point[stcContext.timeAxis])
1950
+ return;
1782
1951
  drawAliasedLine(imageData, previousPoint, point, lineColor, STYLES[level].width + pickingTolerance, true, scalingRatio);
1783
1952
  }
1784
- });
1953
+ }));
1785
1954
  // Draw snap points:
1786
1955
  getSnapPoints(stcContext).forEach((point) => {
1787
1956
  const pickingElement = {
@@ -1793,7 +1962,7 @@ const PathLayer = ({ path, color, level = DEFAULT_LEVEL, pickingTolerance = DEFA
1793
1962
  const lineColor = hexToRgb(indexToColor(index));
1794
1963
  drawAliasedDisc(imageData, point, (STYLES[level].width + pickingTolerance) * 2, lineColor, false, scalingRatio);
1795
1964
  });
1796
- }, [getPathSegments, getSnapPoints, level, path.id, pickingTolerance]);
1965
+ }, [getPathLines, getSnapPoints, level, path.id, path.points, pickingTolerance]);
1797
1966
  usePicking('paths', drawPicking);
1798
1967
  return null;
1799
1968
  };
@@ -1850,7 +2019,7 @@ function snapPosition(mousePosition, hoveredItem) {
1850
2019
  }
1851
2020
 
1852
2021
  const SpaceTimeChart = (props) => {
1853
- const { operationalPoints, spaceOrigin, spaceScales, timeOrigin, timeScale, xOffset = 0, yOffset = 0, swapAxis, onHoveredChildUpdate, children, additionalChildren, enableSnapping, hideGrid, hidePathsLabels, showTicks, hideDates, theme,
2022
+ const { operationalPoints, spaceOrigin, spaceScales, timeOrigin, timeScale, xOffset = 0, yOffset = 0, swapAxis, onHoveredChildUpdate, children, additionalChildren, enableSnapping, hideTimeCaptions, hideGrid, hidePathsLabels, showTicks, hideDates, theme,
1854
2023
  /* eslint-disable @typescript-eslint/no-unused-vars */
1855
2024
  onPan, onZoom, onClick, onMouseMove,
1856
2025
  /* eslint-enable @typescript-eslint/no-unused-vars */
@@ -1870,6 +2039,7 @@ const SpaceTimeChart = (props) => {
1870
2039
  xOffset,
1871
2040
  yOffset,
1872
2041
  swapAxis,
2042
+ hideTimeCaptions,
1873
2043
  hideGrid,
1874
2044
  hidePathsLabels,
1875
2045
  showTicks,
@@ -1885,6 +2055,7 @@ const SpaceTimeChart = (props) => {
1885
2055
  xOffset,
1886
2056
  yOffset,
1887
2057
  swapAxis,
2058
+ hideTimeCaptions,
1888
2059
  hideGrid,
1889
2060
  hidePathsLabels,
1890
2061
  showTicks,
@@ -1892,6 +2063,7 @@ const SpaceTimeChart = (props) => {
1892
2063
  ]);
1893
2064
  const contextState = useMemo(() => {
1894
2065
  const spaceScaleTree = spaceScalesToBinaryTree(spaceOrigin, spaceScales);
2066
+ const flatSteps = getFlatSteps(spaceScales);
1895
2067
  const timeAxis = !swapAxis ? 'x' : 'y';
1896
2068
  const spaceAxis = !swapAxis ? 'y' : 'x';
1897
2069
  // Data translation helpers:
@@ -1935,6 +2107,7 @@ const SpaceTimeChart = (props) => {
1935
2107
  operationalPoints,
1936
2108
  spaceOrigin,
1937
2109
  spaceScaleTree,
2110
+ flatSteps,
1938
2111
  timeOrigin,
1939
2112
  timeScale,
1940
2113
  timePixelOffset,
@@ -1943,6 +2116,7 @@ const SpaceTimeChart = (props) => {
1943
2116
  spaceAxis,
1944
2117
  swapAxis: !!swapAxis,
1945
2118
  enableSnapping: !!enableSnapping,
2119
+ hideTimeCaptions: !!hideTimeCaptions,
1946
2120
  hideGrid: !!hideGrid,
1947
2121
  hidePathsLabels: !!hidePathsLabels,
1948
2122
  showTicks: !!showTicks,
@@ -2270,7 +2444,13 @@ const PATH_COLOR_DEFAULT = '#8A714B';
2270
2444
 
2271
2445
  const getHeightWithoutLastWaypoint = (height) => height - FOOTER_HEIGHT - BASE_WAYPOINT_HEIGHT;
2272
2446
  const positionMmToKm = (position) => Math.round((position / 1000000) * 10) / 10;
2273
- const calcTotalDistance = (ops) => ops.at(-1).position - ops.at(0).position;
2447
+ const positionKmToMm = (position) => position * 1000000;
2448
+ const calcTotalDistance = (ops) => {
2449
+ if (ops.length === 0) {
2450
+ return 0;
2451
+ }
2452
+ return ops.at(-1).position - ops.at(0).position;
2453
+ };
2274
2454
  function getDistance(a, b) {
2275
2455
  return {
2276
2456
  x: b.x - a.x,
@@ -2278,15 +2458,15 @@ function getDistance(a, b) {
2278
2458
  };
2279
2459
  }
2280
2460
 
2281
- const Waypoint = ({ waypoint: { name, secondaryCode, id, position, onClick }, nameRef, isActive, isMenuActive, }) => (React.createElement("div", { className: cx('flex waypoint items-baseline', {
2461
+ const Waypoint = ({ waypoint: { name, secondaryCode, id, position, onClick }, waypointRef, isActive, isMenuActive, }) => (React.createElement("div", { className: cx('flex waypoint items-baseline', {
2282
2462
  'waypoint-active': isActive,
2283
2463
  'menu-active': isMenuActive,
2284
- }), id: id, onClick: () => {
2464
+ }), id: id, ref: waypointRef, onClick: () => {
2285
2465
  if (onClick && !isMenuActive)
2286
2466
  onClick(id);
2287
2467
  } },
2288
2468
  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),
2469
+ React.createElement("div", { className: "waypoint-name mx-2 justify-self-start" }, name),
2290
2470
  React.createElement("div", { className: "waypoint-separator" }),
2291
2471
  React.createElement("div", { className: "waypoint-ch font-mono justify-self-end" }, secondaryCode),
2292
2472
  React.createElement("div", { className: "waypoint-separator" }),
@@ -2353,9 +2533,19 @@ const selectWaypointsToDisplay = (waypoints, { height, isProportional, yZoom })
2353
2533
  * km (isProportional): { coefficient: gives a scale in meter/pixel }
2354
2534
  * linear: { size: height in pixel } (each point distributed evenly along the height of manchette.)
2355
2535
  */
2356
- const getScales = (waypoints, { isProportional, yZoom }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx) => {
2357
- if (waypoints.length < 2)
2536
+ const getScales = (waypoints, { isProportional, yZoom, height }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx) => {
2537
+ if (!waypoints.length)
2358
2538
  return [];
2539
+ if (waypoints.length === 1) {
2540
+ const waypoint = waypoints[0];
2541
+ return [
2542
+ {
2543
+ from: waypoint.position,
2544
+ to: waypoint.position,
2545
+ size: height || 1,
2546
+ },
2547
+ ];
2548
+ }
2359
2549
  if (!isProportional) {
2360
2550
  return waypoints.slice(0, -1).map((from, index) => {
2361
2551
  const to = waypoints[index + 1];
@@ -2381,52 +2571,43 @@ const getScales = (waypoints, { isProportional, yZoom }, minZoomMillimeterPerPx,
2381
2571
  };
2382
2572
  const isInteractiveWaypoint = (item) => item != null && typeof item === 'object' && 'id' in item && 'position' in item;
2383
2573
 
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
- };
2574
+ 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" },
2575
+ React.createElement("div", { className: "bg-white-100 border-r border-grey-30 relative", style: { minHeight: `${height}px` } },
2576
+ React.createElement("div", { className: "waypoints-list" },
2577
+ contents.map((content, index) => isInteractiveWaypoint(content) ? (React.createElement("div", { key: index, className: "waypoint-wrapper flex justify-start", style: content.styles },
2578
+ React.createElement(Waypoint, { waypoint: content, waypointRef: activeWaypointId === content.id ? activeWaypointRef : undefined, isActive: activeWaypointId === content.id, isMenuActive: !!activeWaypointId }))) : (React.createElement(Fragment, { key: index }, content))),
2579
+ children)),
2580
+ React.createElement("div", { className: "manchette-actions" },
2581
+ React.createElement("div", { className: "zoom-buttons" },
2582
+ React.createElement("button", { className: "zoom-out", onClick: zoomYOut, disabled: yZoom <= MIN_ZOOM_Y || !!activeWaypointId },
2583
+ React.createElement(ZoomOut, null)),
2584
+ React.createElement("button", { className: "zoom-in", onClick: zoomYIn, disabled: yZoom >= MAX_ZOOM_Y || !!activeWaypointId },
2585
+ React.createElement(ZoomIn, null)),
2586
+ React.createElement("button", { disabled: !!activeWaypointId, className: "zoom-reset", onClick: resetZoom }, "Fit")),
2587
+ React.createElement("div", { className: "flex items-center ml-auto text-sans font-semibold" },
2588
+ React.createElement("button", { disabled: !!activeWaypointId, className: "toggle-mode", onClick: toggleMode },
2589
+ React.createElement("div", { className: "flex flex-col items-end pr-2" },
2590
+ React.createElement("span", { className: cx({ 'text-grey-30': !isProportional }) }, "Km"),
2591
+ React.createElement("span", { className: cx({ 'text-grey-30': isProportional }) }, "Lin\u00E9aire")))))));
2420
2592
 
2421
- const WAYPOINTS_OFFSET = 16;
2422
- const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChartRef, height = 561, spaceTimeChartRef, defaultTimeOrigin = 0, defaultSpaceOrigin = 0, splitPoints = [], }) => {
2593
+ const DEFAULT_MANCHETTE_WITH_SPACE_TIME_CHART_OPTIONS = {
2594
+ displayTimeCaptions: true,
2595
+ enableTimePan: true,
2596
+ enableSpacePan: true,
2597
+ enableTimeZoom: true,
2598
+ };
2599
+ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChartRef, height = 561, spaceTimeChartRef, defaultTimeOrigin = 0, defaultSpaceOrigin = 0, defaultXOffset = 0, verticalPadding = BASE_WAYPOINT_HEIGHT / 2, splitPoints = [], options = {}, }) => {
2600
+ const { displayTimeCaptions, enableTimePan, enableSpacePan, enableTimeZoom } = useMemo(() => ({
2601
+ ...DEFAULT_MANCHETTE_WITH_SPACE_TIME_CHART_OPTIONS,
2602
+ ...options,
2603
+ }), [options]);
2423
2604
  const [isShiftPressed, setIsShiftPressed] = useState(false);
2424
2605
  const [state, setState] = useState({
2425
2606
  xZoom: timeScaleToZoomValue(DEFAULT_ZOOM_MS_PER_PX),
2426
2607
  yZoom: 1,
2427
2608
  timeOrigin: defaultTimeOrigin,
2428
2609
  spaceOrigin: defaultSpaceOrigin,
2429
- xOffset: 0,
2610
+ xOffset: defaultXOffset,
2430
2611
  yOffset: 0,
2431
2612
  scrollTo: null,
2432
2613
  panning: null,
@@ -2442,20 +2623,19 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2442
2623
  const setTimeOrigin = useCallback((newTimeOrigin) => {
2443
2624
  setState((prev) => ({ ...prev, timeOrigin: newTimeOrigin }));
2444
2625
  }, []);
2445
- const canvasDrawingHeight = height - FOOTER_HEIGHT; // 521
2626
+ const canvasDrawingHeight = Math.max(1 + BASE_WAYPOINT_HEIGHT, height - FOOTER_HEIGHT); // 521
2446
2627
  const drawingHeightWithoutTopPadding = canvasDrawingHeight - BASE_WAYPOINT_HEIGHT / 2; // 505
2447
2628
  const drawingHeightWithoutBothPadding = canvasDrawingHeight - BASE_WAYPOINT_HEIGHT; // 489
2448
2629
  const totalDistance = calcTotalDistance(waypoints);
2449
2630
  const { minZoomMillimeterPerPx, maxZoomMillimeterPerPx } = getExtremaScales(drawingHeightWithoutTopPadding, drawingHeightWithoutBothPadding, totalDistance);
2450
2631
  const handleRectangleZoom = useCallback(({ scales: { chosenTimeScale, chosenSpaceScale }, overrideState, }) => {
2451
2632
  setState((prev) => {
2452
- if (prev.zoomMode || !prev.rect) {
2633
+ if (prev.zoomMode || !prev.rect || !spaceTimeChartRef?.current) {
2453
2634
  return prev;
2454
2635
  }
2455
2636
  const newTimeScale = clamp$1(chosenTimeScale, MAX_ZOOM_MS_PER_PX, MIN_ZOOM_MS_PER_PX);
2456
2637
  const timeZoomValue = timeScaleToZoomValue(newTimeScale);
2457
- const leftRectSide = Math.min(Number(prev.rect.timeStart), Number(prev.rect.timeEnd));
2458
- const newXOffset = (timeOrigin - leftRectSide) / newTimeScale;
2638
+ const newXOffset = sideOffset(timeOrigin, newTimeScale, prev.rect.timeStart, prev.rect.timeEnd, spaceTimeChartRef.current.clientWidth);
2459
2639
  let newYZoom = yZoom;
2460
2640
  let newYOffset = yOffset;
2461
2641
  if (chosenSpaceScale) {
@@ -2466,8 +2646,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2466
2646
  // that would actually zoom OUT if it wasn’t clamped.
2467
2647
  if (newSpaceScale !== minZoomMillimeterPerPx) {
2468
2648
  newYZoom = spaceScaleToZoomValue(minZoomMillimeterPerPx, maxZoomMillimeterPerPx, newSpaceScale);
2469
- const topRectSide = Math.min(prev.rect.spaceStart, prev.rect.spaceEnd);
2470
- newYOffset = Math.abs(spaceOrigin - topRectSide) / newSpaceScale;
2649
+ newYOffset = Math.abs(sideOffset(spaceOrigin, newSpaceScale, prev.rect.spaceStart, prev.rect.spaceEnd, height, verticalPadding));
2471
2650
  }
2472
2651
  }
2473
2652
  return {
@@ -2480,7 +2659,17 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2480
2659
  ...overrideState,
2481
2660
  };
2482
2661
  });
2483
- }, [timeOrigin, spaceOrigin, minZoomMillimeterPerPx, maxZoomMillimeterPerPx, yOffset, yZoom]);
2662
+ }, [
2663
+ timeOrigin,
2664
+ spaceOrigin,
2665
+ minZoomMillimeterPerPx,
2666
+ maxZoomMillimeterPerPx,
2667
+ yOffset,
2668
+ yZoom,
2669
+ height,
2670
+ spaceTimeChartRef,
2671
+ verticalPadding,
2672
+ ]);
2484
2673
  useEffect(() => {
2485
2674
  if (rect && !zoomMode && spaceTimeChartRef?.current) {
2486
2675
  const { timeStart, timeEnd, spaceStart, spaceEnd } = rect;
@@ -2608,37 +2797,47 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2608
2797
  setState((prev) => ({ ...prev, zoomMode: !prev.zoomMode }));
2609
2798
  }, []);
2610
2799
  const handleXZoom = useCallback((newXZoom, xPosition = (spaceTimeChartRef?.current?.offsetWidth || 0) / 2) => {
2611
- setState((prev) => ({
2612
- ...prev,
2613
- ...zoomX(prev.xZoom, prev.xOffset, newXZoom, xPosition),
2614
- }));
2615
- }, [spaceTimeChartRef]);
2800
+ if (enableTimeZoom)
2801
+ setState((prev) => ({
2802
+ ...prev,
2803
+ ...zoomX(prev.xZoom, prev.xOffset, newXZoom, xPosition),
2804
+ }));
2805
+ }, [enableTimeZoom, spaceTimeChartRef]);
2616
2806
  const spaceScales = useMemo(() => {
2617
2807
  // Here, we first compute the base scales, and then we insert a flat step for each split point:
2618
- const baseScales = getScales(waypoints, { isProportional, yZoom }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx);
2808
+ const baseScales = getScales(waypoints, { height, isProportional, yZoom }, minZoomMillimeterPerPx, maxZoomMillimeterPerPx);
2619
2809
  if (!splitPoints)
2620
2810
  return baseScales;
2621
2811
  // Constant scale:
2622
2812
  if (isProportional) {
2813
+ if (baseScales.length === 0)
2814
+ return baseScales;
2623
2815
  const baseScale = baseScales[0];
2624
2816
  const coefficient = 'coefficient' in baseScale && typeof baseScale.coefficient === 'number'
2625
2817
  ? baseScale.coefficient
2626
2818
  : (baseScale.to - baseScale.from) / baseScale.size;
2627
2819
  return splitPoints
2628
- .flatMap(({ position, size: splitPointHeight }) => [
2629
- {
2630
- to: position,
2631
- coefficient,
2632
- },
2633
- {
2820
+ .flatMap(({ position, size: splitPointHeight }) => coefficient > 0
2821
+ ? [
2822
+ {
2823
+ to: position,
2824
+ coefficient,
2825
+ },
2826
+ {
2827
+ to: position,
2828
+ size: splitPointHeight,
2829
+ },
2830
+ ]
2831
+ : {
2634
2832
  to: position,
2635
2833
  size: splitPointHeight,
2636
- },
2637
- ])
2638
- .concat({
2639
- to: baseScales.at(-1).to,
2640
- coefficient,
2641
- });
2834
+ })
2835
+ .concat(coefficient
2836
+ ? {
2837
+ to: baseScales.at(-1).to,
2838
+ coefficient,
2839
+ }
2840
+ : []);
2642
2841
  }
2643
2842
  // Varying scales:
2644
2843
  const allScales = [];
@@ -2665,7 +2864,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2665
2864
  size: point.size,
2666
2865
  });
2667
2866
  });
2668
- return sortBy(allScales, (scale) => scale.to + ('size' in scale ? Number.EPSILON : 0));
2867
+ return sortBy(allScales.filter((scale) => 'coefficient' in scale ? scale.coefficient > 0 : isFinite(scale.size)), (scale) => scale.to + ('size' in scale ? Number.EPSILON : 0));
2669
2868
  }, [
2670
2869
  waypoints,
2671
2870
  height,
@@ -2675,26 +2874,23 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2675
2874
  maxZoomMillimeterPerPx,
2676
2875
  splitPoints,
2677
2876
  ]);
2678
- const waypointsWithoutSplitPoints = useMemo(() => {
2679
- const splitPointPositions = new Set(splitPoints?.map((point) => point.position) || []);
2680
- const filteredWaypoints = selectWaypointsToDisplay(waypoints, {
2681
- height,
2682
- isProportional,
2683
- yZoom,
2684
- });
2685
- return filteredWaypoints.filter((waypoint) => !splitPointPositions.has(waypoint.position));
2686
- }, [splitPoints, waypoints, height, isProportional, yZoom]);
2877
+ const waypointsToDisplay = useMemo(() => selectWaypointsToDisplay(waypoints, {
2878
+ height,
2879
+ isProportional,
2880
+ yZoom,
2881
+ }), [waypoints, height, isProportional, yZoom]);
2687
2882
  const { manchetteContents, manchetteHeight } = useMemo(() => {
2688
2883
  const spaceScaleTree = spaceScalesToBinaryTree(spaceOrigin, spaceScales);
2689
2884
  const getSpacePixel = getSpaceToPixel(0, spaceScaleTree);
2690
- const totalManchetteHeight = Math.max(getSpacePixel(spaceScales.at(-1).to, true) + BASE_WAYPOINT_HEIGHT, height - FOOTER_HEIGHT);
2691
- if (!splitPoints)
2692
- return {
2693
- manchetteHeight: totalManchetteHeight,
2694
- manchetteContents: waypointsWithoutSplitPoints,
2695
- };
2885
+ let totalManchetteHeight = height - FOOTER_HEIGHT;
2886
+ if (spaceScales.length > 0) {
2887
+ totalManchetteHeight = Math.max(totalManchetteHeight, getSpacePixel(spaceScales.at(-1).to, true) + verticalPadding * 2);
2888
+ }
2696
2889
  // Identify all manchette contents (split sections and waypoints):
2697
- let allContents = waypointsWithoutSplitPoints.map((wp) => ({
2890
+ const splitPointPositions = new Set(splitPoints.map((point) => point.position) || []);
2891
+ let allContents = waypointsToDisplay
2892
+ .filter((wp) => !splitPointPositions.has(wp.position))
2893
+ .map((wp) => ({
2698
2894
  type: 'waypoint',
2699
2895
  waypoint: wp,
2700
2896
  position: wp.position,
@@ -2730,12 +2926,12 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2730
2926
  const { split: { position }, } = content;
2731
2927
  const top = getSpacePixel(position);
2732
2928
  finalContents.push(React.createElement("div", { style: {
2733
- // This WAYPOINTS_OFFSET correction is there because:
2734
- // - Waypoints are positioned so that their lines (at WAYPOINTS_OFFSET pixels from
2929
+ // This verticalPadding correction is there because:
2930
+ // - Waypoints are positioned so that their lines (at verticalPadding pixels from
2735
2931
  // the top) are aligned with SpaceTimeChart's space lines
2736
2932
  // - Split points are positioned so that their top is aligned with SpaceTimeChart's
2737
2933
  // space lines
2738
- top: `${top + WAYPOINTS_OFFSET}px`,
2934
+ top: `${top + verticalPadding}px`,
2739
2935
  height: `${getSpacePixel(position, true) - top}px`,
2740
2936
  position: 'absolute',
2741
2937
  width: '100%',
@@ -2748,7 +2944,7 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2748
2944
  manchetteHeight: totalManchetteHeight,
2749
2945
  manchetteContents: finalContents,
2750
2946
  };
2751
- }, [spaceOrigin, spaceScales, splitPoints, waypointsWithoutSplitPoints, height]);
2947
+ }, [spaceOrigin, spaceScales, verticalPadding, height, splitPoints, waypointsToDisplay]);
2752
2948
  return useMemo(() => ({
2753
2949
  manchetteProps: {
2754
2950
  contents: manchetteContents,
@@ -2762,19 +2958,21 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2762
2958
  yOffset,
2763
2959
  },
2764
2960
  spaceTimeChartProps: {
2765
- operationalPoints: waypointsWithoutSplitPoints.map((waypoint) => ({
2961
+ operationalPoints: waypointsToDisplay.map((waypoint) => ({
2766
2962
  ...waypoint,
2767
2963
  importanceLevel: 1,
2768
2964
  })),
2769
- additionalChildren: splitPoints.map((sp) => sp.spaceTimeChartNode),
2965
+ additionalChildren: splitPoints.map((sp, i) => (React.createElement(Fragment, { key: i }, sp.spaceTimeChartNode))),
2966
+ hideTimeCaptions: !displayTimeCaptions,
2770
2967
  timeScale: zoomValueToTimeScale(xZoom),
2771
2968
  xOffset,
2772
- yOffset: -yOffset + WAYPOINTS_OFFSET,
2969
+ yOffset: -yOffset + verticalPadding,
2773
2970
  timeOrigin,
2774
2971
  spaceOrigin,
2775
2972
  spaceScales,
2776
- onZoom: ({ delta, position, }) => {
2973
+ onZoom: ({ delta, position, event, }) => {
2777
2974
  if (isShiftPressed && !rect) {
2975
+ event.preventDefault();
2778
2976
  handleXZoom(xZoom + delta, position.x);
2779
2977
  }
2780
2978
  },
@@ -2824,14 +3022,18 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2824
3022
  }
2825
3023
  const newState = { ...prev };
2826
3024
  const { initialOffset } = panning;
2827
- newState.xOffset = initialOffset.x + diff.x;
2828
- const newYPos = initialOffset.y - diff.y;
2829
- if (manchetteWithSpaceTimeChartRef.current &&
2830
- newYPos >= 0 &&
2831
- newYPos + manchetteWithSpaceTimeChartRef.current.offsetHeight <
2832
- manchetteWithSpaceTimeChartRef.current.scrollHeight) {
2833
- newState.yOffset = newYPos;
2834
- manchetteWithSpaceTimeChartRef.current.scrollTop = newYPos;
3025
+ const manchette = manchetteWithSpaceTimeChartRef.current;
3026
+ if (enableTimePan) {
3027
+ newState.xOffset = initialOffset.x + diff.x;
3028
+ }
3029
+ if (enableSpacePan) {
3030
+ let newYOffset = initialOffset.y - diff.y;
3031
+ newYOffset = Math.max(newYOffset, 0);
3032
+ if (manchette) {
3033
+ newYOffset = Math.min(newYOffset, manchette.scrollHeight - manchette.offsetHeight);
3034
+ manchette.scrollTop = newYOffset;
3035
+ }
3036
+ newState.yOffset = newYOffset;
2835
3037
  }
2836
3038
  return newState;
2837
3039
  });
@@ -2856,13 +3058,14 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2856
3058
  yZoom,
2857
3059
  isProportional,
2858
3060
  yOffset,
2859
- waypointsWithoutSplitPoints,
3061
+ waypointsToDisplay,
3062
+ splitPoints,
2860
3063
  xZoom,
2861
3064
  xOffset,
3065
+ verticalPadding,
2862
3066
  timeOrigin,
2863
3067
  spaceOrigin,
2864
3068
  spaceScales,
2865
- splitPoints,
2866
3069
  handleScroll,
2867
3070
  handleXZoom,
2868
3071
  toggleZoomMode,
@@ -2871,10 +3074,13 @@ const useManchetteWithSpaceTimeChart = ({ waypoints, manchetteWithSpaceTimeChart
2871
3074
  minZoomMillimeterPerPx,
2872
3075
  maxZoomMillimeterPerPx,
2873
3076
  setTimeOrigin,
3077
+ displayTimeCaptions,
2874
3078
  isShiftPressed,
2875
3079
  panning,
2876
- manchetteWithSpaceTimeChartRef,
3080
+ enableTimePan,
3081
+ enableSpacePan,
2877
3082
  canvasDrawingHeight,
3083
+ manchetteWithSpaceTimeChartRef,
2878
3084
  ]);
2879
3085
  };
2880
3086
 
@@ -2917,17 +3123,17 @@ const ManchetteWithSpaceTimeChart = ({ waypoints, projectPathTrainResult, height
2917
3123
  children)))));
2918
3124
  };
2919
3125
 
2920
- const InteractionButtons = ({ reset, openSettingsPanel, store }) => (React.createElement("div", { id: "interaction-button-container", className: "z-10" },
3126
+ const InteractionButtons = ({ reset, openSettingsPanel, store, testIdPrefix, }) => (React.createElement("div", { id: "interaction-button-container", className: "z-10" },
2921
3127
  React.createElement("div", { className: "zoom-buttons" },
2922
3128
  React.createElement("button", { className: cx('interaction-button reset-button', {
2923
3129
  inactive: store.ratioX == 1 && store.leftOffset == 0,
2924
- }), onClick: () => reset() },
3130
+ }), onClick: () => reset(), "data-testid": testIdPrefix ? `${testIdPrefix}-reset` : undefined },
2925
3131
  React.createElement(Iterations, null)),
2926
- React.createElement("button", { className: "interaction-button plus-button inactive" },
3132
+ React.createElement("button", { className: "interaction-button plus-button inactive", "data-testid": testIdPrefix ? `${testIdPrefix}-zoom-in` : undefined },
2927
3133
  React.createElement(Plus, null)),
2928
- React.createElement("button", { className: "interaction-button inactive" },
3134
+ React.createElement("button", { className: "interaction-button inactive", "data-testid": testIdPrefix ? `${testIdPrefix}-zoom-out` : undefined },
2929
3135
  React.createElement(Dash, null))),
2930
- React.createElement("button", { className: "interaction-button elipsis-button", onClick: () => openSettingsPanel() },
3136
+ React.createElement("button", { className: "interaction-button elipsis-button", "data-testid": testIdPrefix ? `${testIdPrefix}-settings` : undefined, onClick: () => openSettingsPanel() },
2931
3137
  React.createElement(KebabHorizontal, null))));
2932
3138
 
2933
3139
  const SLOPE_FILL_COLOR = '#CFDDCE';
@@ -3291,7 +3497,7 @@ const getSnappedStop = (cursorX, width, store) => {
3291
3497
 
3292
3498
  const SETTINGS_PANEL_BASE_HEIGHT = 442;
3293
3499
  const SPEEDSPACECHART_BASE_HEIGHT = 521.5;
3294
- const SettingsPanel = ({ globalHeight, color, store, setStore, setIsMouseHoveringSettingsPanel, translations, }) => {
3500
+ const SettingsPanel = ({ globalHeight, color, store, setStore, setIsMouseHoveringSettingsPanel, translations, testIdPrefix, }) => {
3295
3501
  const [height, setHeight] = useState(`${SETTINGS_PANEL_BASE_HEIGHT}px`);
3296
3502
  const closeSettingsPanel = () => {
3297
3503
  setIsMouseHoveringSettingsPanel(false);
@@ -3311,7 +3517,7 @@ const SettingsPanel = ({ globalHeight, color, store, setStore, setIsMouseHoverin
3311
3517
  React.createElement("div", { className: "settings-panel-section-title" },
3312
3518
  React.createElement("span", null, translations?.layersDisplay.context || 'Context')),
3313
3519
  LAYERS_SELECTION.map((selection) => (React.createElement("div", { key: selection, className: "selection" },
3314
- React.createElement(Checkbox, { label: translations?.layersDisplay[selection] || selection, checked: store.layersDisplay[selection], disabled: !isLayerActive(store, selection), onChange: () => {
3520
+ React.createElement(Checkbox, { "data-testid": testIdPrefix ? `${testIdPrefix}-layer-${selection}` : undefined, label: translations?.layersDisplay[selection] || selection, checked: store.layersDisplay[selection], disabled: !isLayerActive(store, selection), onChange: () => {
3315
3521
  setStore((prev) => ({
3316
3522
  ...prev,
3317
3523
  layersDisplay: {
@@ -3333,7 +3539,7 @@ const SettingsPanel = ({ globalHeight, color, store, setStore, setIsMouseHoverin
3333
3539
  },
3334
3540
  }));
3335
3541
  } }))))),
3336
- React.createElement("button", { id: "close-settings-panel", onClick: () => closeSettingsPanel() },
3542
+ React.createElement("button", { id: "close-settings-panel", "data-testid": testIdPrefix ? `${testIdPrefix}-close` : undefined, onClick: () => closeSettingsPanel() },
3337
3543
  React.createElement("span", null,
3338
3544
  React.createElement(X, null)))));
3339
3545
  };
@@ -3513,7 +3719,7 @@ const drawSpeedLimits = ({ ctx, width, height, store }) => {
3513
3719
  }
3514
3720
  gradient.addColorStop(1, speedColor.alpha(0).hex());
3515
3721
  ctx.fillStyle = gradient;
3516
- ctx.rect(previousBoundaryX, speedY, currentBoundaryX - previousBoundaryX, -16);
3722
+ ctx.rect(previousBoundaryX, speedY, currentBoundaryX - previousBoundaryX, -GRADIENT_HEIGHT);
3517
3723
  ctx.fill();
3518
3724
  // Handle train length (only if next speed is higher than current speed)
3519
3725
  let extendedBoundaryX = null;
@@ -4266,7 +4472,7 @@ const TOOLTIP_HEIGHT = 40;
4266
4472
  const MARGIN_ADJUSTMENT = 2;
4267
4473
  const SpeedLimitTagsLayer = ({ width, marginTop, store }) => {
4268
4474
  const canvas = useRef(null);
4269
- const tooltip = useRef();
4475
+ const tooltip = useRef(null);
4270
4476
  const [images, setImages] = useState({ questionImage: null, alertFillImage: null });
4271
4477
  useEffect(() => {
4272
4478
  const fetchImages = async () => {
@@ -4619,9 +4825,9 @@ const SpeedSpaceChart = ({ width, height, backgroundColor, data, setHeight, tran
4619
4825
  backgroundColor: `${backgroundColor}`,
4620
4826
  }, tabIndex: 0 },
4621
4827
  React.createElement("div", { className: "flex justify-end absolute base-margin-top", style: { width: adjustedWidthRightAxis } },
4622
- React.createElement(InteractionButtons, { reset: reset, openSettingsPanel: openSettingsPanel, store: store })),
4828
+ React.createElement(InteractionButtons, { reset: reset, openSettingsPanel: openSettingsPanel, store: store, testIdPrefix: "interaction" })),
4623
4829
  store.isSettingsPanelOpened && (React.createElement("div", { className: "flex justify-end absolute ml-2 base-margin-top", style: { width: adjustedWidthRightAxis } },
4624
- React.createElement(SettingsPanel, { globalHeight: dynamicHeight, color: backgroundColor, store: store, setStore: setStore, setIsMouseHoveringSettingsPanel: setIsMouseHoveringSettingsPanel, translations: translations }))),
4830
+ React.createElement(SettingsPanel, { globalHeight: dynamicHeight, color: backgroundColor, store: store, setStore: setStore, setIsMouseHoveringSettingsPanel: setIsMouseHoveringSettingsPanel, translations: translations, testIdPrefix: "settings-panel" }))),
4625
4831
  store.layersDisplay.declivities && (React.createElement(DeclivityLayer, { width: WIDTH_OFFSET, height: HEIGHT_OFFSET, store: store })),
4626
4832
  React.createElement(CurveLayer, { width: WIDTH_OFFSET, height: HEIGHT_OFFSET, store: store }),
4627
4833
  store.layersDisplay.speedLimits && (React.createElement(SpeedLimitsLayer, { width: adjustedWidthRightAxis, height: height, store: store })),
@@ -4651,7 +4857,9 @@ const COLORS = {
4651
4857
  GREY_50: 'rgb(121, 118, 113)',
4652
4858
  GREY_60: 'rgb(92, 89, 85)',
4653
4859
  GREY_80: 'rgb(49, 46, 43)',
4654
- HOUR_BACKGROUND: 'rgba(243, 248, 253, 0.5)',
4860
+ MANCHETTE_BACKGROUND: '#f2f0e4',
4861
+ HOUR_BACKGROUND_1: '#faf9f5',
4862
+ HOUR_BACKGROUND_2: '#f2f0e4',
4655
4863
  RAIL_TICK: 'rgb(33, 112, 185)',
4656
4864
  REMAINING_TRAINS_BACKGROUND: 'rgba(0, 0, 0, 0.7)',
4657
4865
  SELECTION_20: 'rgb(255, 242, 179)',
@@ -4743,13 +4951,13 @@ const Y_MEDIUM_POSITION_OFFSET = 14;
4743
4951
  const ROTATE_VALUE = (-30 * Math.PI) / 180;
4744
4952
  const { SANS: SANS$1, MONO } = FONTS;
4745
4953
  const { WHITE_100: WHITE_100$2, GREY_50, GREY_60, GREY_80, SELECTION_20: SELECTION_20$1 } = COLORS;
4746
- const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePixel, yPosition, isThroughTrain, selectedTrainId, }) => {
4954
+ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePixel, yPosition, isThroughTrain, isSelected, }) => {
4747
4955
  const zoneOccupancyLength = departureTimePixel - arrivalTimePixel - STROKE_WIDTH;
4748
4956
  const isBelowBreakpoint = (breakpoint) => zoneOccupancyLength < BREAKPOINTS[breakpoint];
4749
4957
  ctx.font = '400 10px IBM Plex Mono';
4750
4958
  const originTextLength = ctx.measureText(zone.originStation || '--').width;
4751
4959
  ctx.font = '400 12px IBM Plex Mono';
4752
- const nameTextLength = ctx.measureText(zone.arrivalTrainName).width;
4960
+ const nameTextLength = ctx.measureText(zone.trainName).width;
4753
4961
  const { xOriginTrainName, yOriginTrainName } = isBelowBreakpoint('medium')
4754
4962
  ? {
4755
4963
  xOriginTrainName: arrivalTimePixel -
@@ -4765,11 +4973,11 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4765
4973
  const xArrivalPosition = isBelowBreakpoint('small') ? 'right' : 'center';
4766
4974
  const xDeparturePosition = isBelowBreakpoint('small') ? 'left' : 'center';
4767
4975
  const textStroke = {
4768
- color: selectedTrainId === zone.id ? 'transparent' : WHITE_100$2,
4976
+ color: isSelected ? 'transparent' : WHITE_100$2,
4769
4977
  width: STROKE_WIDTH,
4770
4978
  };
4771
4979
  // train name
4772
- if (selectedTrainId === zone.id) {
4980
+ if (isSelected) {
4773
4981
  const { xSelectedTrainNameBackground, ySelectedTrainNameBackground } = isBelowBreakpoint('medium')
4774
4982
  ? {
4775
4983
  xSelectedTrainNameBackground: xOriginTrainName - X_SELECTED_MEDIUM_PADDING,
@@ -4784,13 +4992,13 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4784
4992
  ctx.rotate(ROTATE_VALUE);
4785
4993
  ctx.fillStyle = SELECTION_20$1;
4786
4994
  ctx.beginPath();
4787
- ctx.roundRect(-4, 0, nameTextLength + X_BACKGROUND_PADDING$1 * 2, Y_INITIAL_POSITION_OFFSET_BACKGROUND);
4995
+ ctx.roundRect(-X_BACKGROUND_PADDING$1, 0, nameTextLength + X_BACKGROUND_PADDING$1 * 2, Y_INITIAL_POSITION_OFFSET_BACKGROUND);
4788
4996
  ctx.fill();
4789
4997
  ctx.restore();
4790
4998
  }
4791
4999
  drawText({
4792
5000
  ctx,
4793
- text: zone.arrivalTrainName,
5001
+ text: zone.trainName,
4794
5002
  x: xOriginTrainName,
4795
5003
  y: yOriginTrainName,
4796
5004
  color: GREY_50,
@@ -4803,7 +5011,9 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4803
5011
  // arrival minutes & departure minutes
4804
5012
  drawText({
4805
5013
  ctx,
4806
- text: zone.arrivalTime.getMinutes().toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
5014
+ text: new Date(zone.startTime)
5015
+ .getMinutes()
5016
+ .toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
4807
5017
  x: isThroughTrain ? arrivalTimePixel - X_THROUGHTRAIN_OFFSET : arrivalTimePixel,
4808
5018
  y: yPosition + MINUTES_TEXT_OFFSET,
4809
5019
  color: GREY_80,
@@ -4815,7 +5025,9 @@ const drawOccupancyZonesTexts = ({ ctx, zone, arrivalTimePixel, departureTimePix
4815
5025
  if (!isThroughTrain)
4816
5026
  drawText({
4817
5027
  ctx,
4818
- text: zone.departureTime.getMinutes().toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
5028
+ text: new Date(zone.endTime)
5029
+ .getMinutes()
5030
+ .toLocaleString('fr-FR', { minimumIntegerDigits: 2 }),
4819
5031
  x: departureTimePixel,
4820
5032
  y: yPosition + MINUTES_TEXT_OFFSET,
4821
5033
  color: GREY_80,
@@ -4854,15 +5066,14 @@ const { REMAINING_TRAINS_BACKGROUND, WHITE_100: WHITE_100$1, SELECTION_20 } = CO
4854
5066
  const REMAINING_TRAINS_WIDTH = 70;
4855
5067
  const REMAINING_TRAINS_HEIGHT = 24;
4856
5068
  const REMAINING_TEXT_OFFSET = 12;
4857
- const Y_OFFSET_INCREMENT = 4;
4858
- const MAX_ZONES = 9;
4859
5069
  const X_BACKGROUND_PADDING = 4;
4860
5070
  const X_TROUGHTRAIN_BACKGROUND_PADDING = 8;
4861
5071
  const BACKGROUND_HEIGHT = 40;
4862
5072
  const SELECTED_TRAIN_ID_GRADIANT = 2;
4863
- const drawDefaultZone = ({ ctx, arrivalTimePixel, departureTimePixel, yPosition }) => {
5073
+ const PATH_SIZE_DEFAULT = 1;
5074
+ const drawDefaultZone = (ctx, { x, y, width }) => {
4864
5075
  ctx.beginPath();
4865
- ctx.rect(arrivalTimePixel, yPosition, departureTimePixel - arrivalTimePixel, OCCUPANCY_ZONE_HEIGHT);
5076
+ ctx.rect(x, y, width, OCCUPANCY_ZONE_HEIGHT);
4866
5077
  ctx.fill();
4867
5078
  ctx.stroke();
4868
5079
  };
@@ -4871,7 +5082,7 @@ const ARROW_OFFSET_Y = 1.5;
4871
5082
  const ARROW_WIDTH = 4.5;
4872
5083
  const ARROW_TOP_Y = 3.5;
4873
5084
  const ARROW_BOTTOM_Y = 6.5;
4874
- const drawThroughTrain = ({ ctx, arrivalTimePixel, }) => {
5085
+ const drawThroughTrain = (ctx, x, y) => {
4875
5086
  // Through trains are materialized by converging arrows like the following ones
4876
5087
  // ___
4877
5088
  // \_/
@@ -4879,209 +5090,253 @@ const drawThroughTrain = ({ ctx, arrivalTimePixel, }) => {
4879
5090
  // ‾‾‾
4880
5091
  ctx.beginPath();
4881
5092
  // draw the upper part
4882
- ctx.moveTo(arrivalTimePixel - ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
4883
- ctx.lineTo(arrivalTimePixel - ARROW_WIDTH, OCCUPANCY_ZONE_Y_START - ARROW_TOP_Y);
4884
- ctx.lineTo(arrivalTimePixel + ARROW_WIDTH, OCCUPANCY_ZONE_Y_START - ARROW_TOP_Y);
4885
- ctx.lineTo(arrivalTimePixel + ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
5093
+ ctx.moveTo(x - ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
5094
+ ctx.lineTo(x - ARROW_WIDTH, y - ARROW_TOP_Y);
5095
+ ctx.lineTo(x + ARROW_WIDTH, y - ARROW_TOP_Y);
5096
+ ctx.lineTo(x + ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4886
5097
  // draw the lower part
4887
- ctx.lineTo(arrivalTimePixel + ARROW_WIDTH, OCCUPANCY_ZONE_Y_START + ARROW_BOTTOM_Y);
4888
- ctx.lineTo(arrivalTimePixel - ARROW_WIDTH, OCCUPANCY_ZONE_Y_START + ARROW_BOTTOM_Y);
4889
- ctx.lineTo(arrivalTimePixel - ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
5098
+ ctx.lineTo(x + ARROW_WIDTH, y + ARROW_BOTTOM_Y);
5099
+ ctx.lineTo(x - ARROW_WIDTH, y + ARROW_BOTTOM_Y);
5100
+ ctx.lineTo(x - ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4890
5101
  ctx.fill();
4891
5102
  // draw the white separator in the middle
4892
- ctx.moveTo(arrivalTimePixel - ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
4893
- ctx.lineTo(arrivalTimePixel + ARROW_OFFSET_X, OCCUPANCY_ZONE_Y_START + ARROW_OFFSET_Y);
5103
+ ctx.moveTo(x - ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
5104
+ ctx.lineTo(x + ARROW_OFFSET_X, y + ARROW_OFFSET_Y);
4894
5105
  ctx.stroke();
4895
5106
  };
4896
- const drawRemainingTrainsBox = ({ ctx, remainingTrainsNb, xPosition }) => {
4897
- const textY = OCCUPANCY_ZONE_Y_START - REMAINING_TEXT_OFFSET;
5107
+ const drawRemainingTrainsBox = (ctx, { getTimePixel, getSpacePixel }, { time, position, yOffset, remainingTrainsNb, }) => {
5108
+ const x = getTimePixel(time);
5109
+ const y = getSpacePixel(position) + yOffset;
5110
+ const textY = y + OCCUPANCY_ZONE_Y_START - REMAINING_TEXT_OFFSET;
4898
5111
  ctx.fillStyle = REMAINING_TRAINS_BACKGROUND;
4899
5112
  ctx.beginPath();
4900
- ctx.rect(xPosition, textY, REMAINING_TRAINS_WIDTH, REMAINING_TRAINS_HEIGHT);
5113
+ ctx.rect(x - REMAINING_TRAINS_WIDTH / 2, textY, REMAINING_TRAINS_WIDTH, REMAINING_TRAINS_HEIGHT);
4901
5114
  ctx.fill();
4902
5115
  ctx.stroke();
4903
5116
  ctx.fillStyle = WHITE_100$1;
4904
5117
  ctx.font = SANS;
4905
5118
  ctx.textAlign = 'center';
4906
5119
  ctx.textBaseline = 'middle';
4907
- ctx.fillText(`+${remainingTrainsNb} trains`, xPosition + REMAINING_TRAINS_WIDTH / 2, textY + REMAINING_TRAINS_HEIGHT / 2);
5120
+ ctx.fillText(`+${remainingTrainsNb} trains`, x, textY + REMAINING_TRAINS_HEIGHT / 2);
4908
5121
  };
4909
- const drawOccupationZone = ({ ctx, zone, tracks, arrivalTimePixel, departureTimePixel, yPosition, isThroughTrain, selectedTrainId, setSelectedTrainId, xMousePosition, yMousePosition, index, }) => {
4910
- let currentSelectedTrainId = selectedTrainId;
4911
- const trackN = CANVAS_PADDING + TRACK_HEIGHT_CONTAINER * index + yPosition;
4912
- const canvasHeight = CANVAS_PADDING * 2 + TRACK_HEIGHT_CONTAINER * tracks.length;
4913
- const trackPosition = canvasHeight - trackN;
4914
- const arrowOffset = isThroughTrain ? 4 : 0;
4915
- const xCheck = xMousePosition >= arrivalTimePixel - arrowOffset &&
4916
- xMousePosition <= departureTimePixel + arrowOffset;
4917
- const yCheck = Math.abs(yMousePosition) >= trackPosition - OCCUPANCY_ZONE_HEIGHT - 1 - arrowOffset &&
4918
- Math.abs(yMousePosition) <= trackPosition + 1 + arrowOffset;
4919
- if (xCheck && yCheck) {
4920
- setSelectedTrainId(zone.id);
4921
- currentSelectedTrainId = zone.id;
4922
- }
4923
- ctx.fillStyle = zone.color;
5122
+ const drawOccupationZone = (ctx, stcContext, { zone, yOffset, position, isSelected, }) => {
5123
+ const size = zone.size || PATH_SIZE_DEFAULT;
5124
+ const color = zone.color || PATH_COLOR_DEFAULT;
5125
+ const isThroughTrain = zone.startTime === zone.endTime;
5126
+ ctx.fillStyle = color;
4924
5127
  ctx.strokeStyle = WHITE_100$1;
4925
5128
  ctx.lineJoin = 'round';
4926
5129
  ctx.lineCap = 'round';
4927
5130
  ctx.font = '400 10px IBM Plex Mono';
4928
- if (selectedTrainId === zone.id) {
5131
+ const { getTimePixel, getSpacePixel } = stcContext;
5132
+ const yStart = getCrispLineCoordinate(getSpacePixel(position), BACKGROUND_HEIGHT);
5133
+ const y = yStart + yOffset;
5134
+ const yEnd = getSpacePixel(position, true);
5135
+ const arrivalTimePixel = getTimePixel(zone.startTime);
5136
+ const departureTimePixel = getTimePixel(zone.endTime);
5137
+ if (isSelected) {
4929
5138
  const extraWidth = isThroughTrain ? X_TROUGHTRAIN_BACKGROUND_PADDING : X_BACKGROUND_PADDING;
4930
5139
  const originTextLength = ctx.measureText(zone.originStation || '--').width;
4931
5140
  const destinationTextLength = ctx.measureText(zone.destinationStation || '--').width;
4932
- ctx.save();
4933
5141
  ctx.fillStyle = SELECTION_20;
4934
5142
  ctx.beginPath();
4935
- ctx.roundRect(arrivalTimePixel - originTextLength - extraWidth, yPosition - BACKGROUND_HEIGHT / 2, departureTimePixel -
5143
+ ctx.roundRect(arrivalTimePixel - originTextLength - extraWidth, y - BACKGROUND_HEIGHT / 2, departureTimePixel -
4936
5144
  arrivalTimePixel +
4937
5145
  originTextLength +
4938
5146
  destinationTextLength +
4939
5147
  extraWidth * 2, BACKGROUND_HEIGHT, SELECTED_TRAIN_ID_GRADIANT);
4940
5148
  ctx.fill();
4941
- ctx.restore();
4942
5149
  }
5150
+ ctx.fillStyle = color;
4943
5151
  if (isThroughTrain) {
4944
- drawThroughTrain({ ctx, arrivalTimePixel });
5152
+ drawThroughTrain(ctx, arrivalTimePixel, y);
4945
5153
  }
4946
5154
  else {
4947
- drawDefaultZone({ ctx, arrivalTimePixel, departureTimePixel, yPosition });
5155
+ drawDefaultZone(ctx, {
5156
+ x: arrivalTimePixel,
5157
+ y,
5158
+ width: departureTimePixel - arrivalTimePixel,
5159
+ });
5160
+ }
5161
+ // Draw dashed lines linking trains tracks occupancy to their paths on the SpaceTimeChart (when relevant):
5162
+ ctx.strokeStyle = color;
5163
+ ctx.lineWidth = size;
5164
+ ctx.setLineDash([1, 4]);
5165
+ if (zone.startDirection) {
5166
+ ctx.beginPath();
5167
+ ctx.moveTo(arrivalTimePixel, y);
5168
+ ctx.lineTo(arrivalTimePixel, zone.startDirection === 'up' ? yStart : yEnd);
5169
+ ctx.stroke();
5170
+ }
5171
+ if (zone.endDirection) {
5172
+ ctx.beginPath();
5173
+ ctx.moveTo(departureTimePixel, y);
5174
+ ctx.lineTo(departureTimePixel, zone.endDirection === 'up' ? yStart : yEnd);
5175
+ ctx.stroke();
4948
5176
  }
5177
+ ctx.setLineDash([]);
5178
+ // Draw texts:
4949
5179
  drawOccupancyZonesTexts({
4950
5180
  ctx,
4951
5181
  zone,
4952
5182
  arrivalTimePixel,
4953
5183
  departureTimePixel,
4954
- yPosition,
4955
5184
  isThroughTrain,
4956
- selectedTrainId: currentSelectedTrainId,
5185
+ yPosition: y,
5186
+ isSelected,
4957
5187
  });
4958
5188
  };
4959
- const drawOccupancyZones = ({ ctx, width, height, tracks, occupancyZones, getTimePixel, selectedTrainId, setSelectedTrainId, mousePosition, }) => {
4960
- ctx.clearRect(0, 0, width, height);
4961
- ctx.save();
4962
- if (!tracks || !occupancyZones || occupancyZones.length === 0)
4963
- return;
4964
- const sortedOccupancyZones = occupancyZones.sort((a, b) => a.arrivalTime.getTime() - b.arrivalTime.getTime());
4965
- tracks.forEach((track, index) => {
4966
- const trackTranslate = index === 0 ? CANVAS_PADDING : TRACK_HEIGHT_CONTAINER;
4967
- ctx.translate(0, trackTranslate);
4968
- const { x: xMousePosition, y: yMousePosition } = mousePosition;
4969
- const filteredOccupancyZones = sortedOccupancyZones.filter((zone) => zone.trackId === track.id);
4970
- let primaryArrivalTimePixel = 0;
4971
- let primaryDepartureTimePixel = 0;
4972
- let lastDepartureTimePixel = primaryDepartureTimePixel;
4973
- let yPosition = OCCUPANCY_ZONE_Y_START;
4974
- let yOffset = Y_OFFSET_INCREMENT;
4975
- let zoneCounter = 0;
4976
- let zoneIndex = 0;
4977
- while (zoneIndex < filteredOccupancyZones.length) {
4978
- const zone = filteredOccupancyZones[zoneIndex];
4979
- const arrivalTimePixel = getTimePixel(zone.arrivalTime.getTime());
4980
- const departureTimePixel = getTimePixel(zone.departureTime.getTime());
4981
- const isThroughTrain = arrivalTimePixel === departureTimePixel;
4982
- // * if the zone is not overlapping with any previous one, draw it in the center of the track
4983
- // * and reset the primary values
4984
- // *
4985
- // * if the zone is overlapping with the previous one, draw it below or above the previous one
4986
- // * depending on the overlapping counter
4987
- // *
4988
- // * if the zone is overlapping with the previous one and the counter is higher than the max zones
4989
- // * draw the remaining trains box
4990
- // *
4991
- if (arrivalTimePixel > lastDepartureTimePixel) {
4992
- // reset to initial value if the zone is not overlapping
4993
- yPosition = OCCUPANCY_ZONE_Y_START;
4994
- primaryArrivalTimePixel = arrivalTimePixel;
4995
- primaryDepartureTimePixel = departureTimePixel;
4996
- lastDepartureTimePixel = departureTimePixel;
4997
- yOffset = Y_OFFSET_INCREMENT;
4998
- zoneCounter = 1;
4999
- drawOccupationZone({
5000
- ctx,
5001
- zone,
5002
- tracks,
5003
- arrivalTimePixel,
5004
- departureTimePixel,
5005
- yPosition,
5006
- isThroughTrain,
5007
- selectedTrainId,
5008
- setSelectedTrainId,
5009
- index,
5010
- xMousePosition,
5011
- yMousePosition,
5012
- });
5013
- zoneIndex++;
5014
- continue;
5015
- }
5016
- if (zoneCounter < MAX_ZONES) {
5189
+
5190
+ const Y_OFFSET_INCREMENT = 4;
5191
+ const MAX_ZONES = 9;
5192
+ function isOccupancyPickingElement(element) {
5193
+ return element.type === 'occupancyZone';
5194
+ }
5195
+ const OccupancyZonesLayer = ({ tracks, occupancyZones, position, topPadding, selectedTrainId, }) => {
5196
+ const instructionsToDraw = useMemo(() => {
5197
+ const instructions = [];
5198
+ if (!tracks || !occupancyZones || occupancyZones.length === 0)
5199
+ return instructions;
5200
+ const sortedOccupancyZones = occupancyZones.sort((a, b) => a.startTime - b.startTime);
5201
+ tracks.forEach((track, index) => {
5202
+ const trackY = topPadding + CANVAS_PADDING + index * TRACK_HEIGHT_CONTAINER;
5203
+ const filteredOccupancyZones = sortedOccupancyZones.filter((zone) => zone.trackId === track.id);
5204
+ let primaryStartTime = 0;
5205
+ let lastEndTime = 0;
5206
+ let yPosition = OCCUPANCY_ZONE_Y_START;
5207
+ let yOffset = Y_OFFSET_INCREMENT;
5208
+ let zoneCounter = 0;
5209
+ let zoneIndex = 0;
5210
+ while (zoneIndex < filteredOccupancyZones.length) {
5211
+ const zone = filteredOccupancyZones[zoneIndex];
5212
+ const { startTime, endTime } = zone;
5213
+ // * if the zone is not overlapping with any previous one, draw it in the center of the track
5214
+ // * and reset the primary values
5215
+ // *
5216
+ // * if the zone is overlapping with the previous one, draw it below or above the previous one
5217
+ // * depending on the overlapping counter
5218
+ // *
5219
+ // * if the zone is overlapping with the previous one and the counter is higher than the max zones
5220
+ // * draw the remaining trains box
5221
+ // *
5222
+ if (startTime > lastEndTime) {
5223
+ // reset to initial value if the zone is not overlapping
5224
+ yPosition = OCCUPANCY_ZONE_Y_START;
5225
+ primaryStartTime = startTime;
5226
+ lastEndTime = endTime;
5227
+ yOffset = Y_OFFSET_INCREMENT;
5228
+ zoneCounter = 1;
5229
+ instructions.push({
5230
+ type: 'occupancyZone',
5231
+ zone,
5232
+ offsetY: trackY + yPosition,
5233
+ isSelected: zone.trainId === selectedTrainId,
5234
+ });
5235
+ zoneIndex++;
5236
+ }
5017
5237
  // if so and it's an even index, move it to the bottom, if it's an odd index, move it to the top
5018
- if (arrivalTimePixel >= primaryArrivalTimePixel) {
5019
- if (zoneCounter % 2 === 0) {
5020
- yPosition -= yOffset;
5021
- }
5022
- else {
5023
- yPosition += yOffset;
5238
+ else if (zoneCounter < MAX_ZONES) {
5239
+ if (startTime >= primaryStartTime) {
5240
+ if (zoneCounter % 2 === 0) {
5241
+ yPosition -= yOffset;
5242
+ }
5243
+ else {
5244
+ yPosition += yOffset;
5245
+ }
5024
5246
  }
5247
+ // update the last departure time if the current zone is longer
5248
+ if (endTime >= lastEndTime)
5249
+ lastEndTime = endTime;
5250
+ instructions.push({
5251
+ type: 'occupancyZone',
5252
+ zone,
5253
+ offsetY: trackY + yPosition,
5254
+ isSelected: zone.trainId === selectedTrainId,
5255
+ });
5256
+ zoneCounter++;
5257
+ yOffset += Y_OFFSET_INCREMENT;
5258
+ zoneIndex++;
5259
+ }
5260
+ // else, if there are too much trains:
5261
+ else {
5262
+ const nextIndex = filteredOccupancyZones.findIndex((filteredZone, i) => i > zoneIndex && filteredZone.startTime >= lastEndTime);
5263
+ const remainingTrainsNb = nextIndex - zoneIndex;
5264
+ instructions.push({
5265
+ type: 'remainingTrains',
5266
+ amount: remainingTrainsNb,
5267
+ time: (startTime + endTime) / 2,
5268
+ offsetY: trackY,
5269
+ });
5270
+ zoneIndex += remainingTrainsNb;
5025
5271
  }
5026
- // update the last departure time if the current zone is longer
5027
- if (departureTimePixel >= lastDepartureTimePixel)
5028
- lastDepartureTimePixel = departureTimePixel;
5029
- drawOccupationZone({
5030
- ctx,
5031
- zone,
5032
- tracks,
5033
- arrivalTimePixel,
5034
- departureTimePixel,
5035
- yPosition,
5036
- isThroughTrain,
5037
- selectedTrainId,
5038
- setSelectedTrainId,
5039
- index,
5040
- xMousePosition,
5041
- yMousePosition,
5042
- });
5043
- zoneCounter++;
5044
- yOffset += Y_OFFSET_INCREMENT;
5045
- zoneIndex++;
5046
- continue;
5047
5272
  }
5048
- const nextIndex = filteredOccupancyZones.findIndex((filteredZone, i) => i > zoneIndex &&
5049
- getTimePixel(filteredZone.arrivalTime.getTime()) >= lastDepartureTimePixel);
5050
- const remainingTrainsNb = nextIndex - zoneIndex;
5051
- const xPosition = primaryArrivalTimePixel +
5052
- (lastDepartureTimePixel - primaryArrivalTimePixel) / 2 -
5053
- REMAINING_TRAINS_WIDTH / 2;
5054
- drawRemainingTrainsBox({ ctx, remainingTrainsNb, xPosition });
5055
- zoneIndex += remainingTrainsNb;
5056
- }
5057
- });
5058
- ctx.restore();
5059
- };
5060
-
5061
- const OccupancyZonesLayer = ({ useDraw, selectedTrainId, setSelectedTrainId, mousePosition, }) => {
5062
- const drawingFunction = useCallback((ctx, { getTimePixel, tracks, occupancyZones, trackOccupancyWidth, trackOccupancyHeight }) => {
5063
- if (trackOccupancyHeight && trackOccupancyWidth)
5064
- drawOccupancyZones({
5065
- ctx,
5066
- width: trackOccupancyWidth,
5067
- height: trackOccupancyHeight,
5068
- tracks,
5069
- occupancyZones,
5070
- getTimePixel,
5071
- selectedTrainId,
5072
- setSelectedTrainId,
5073
- mousePosition,
5074
- });
5075
- }, [mousePosition, selectedTrainId, setSelectedTrainId]);
5076
- useDraw('paths', drawingFunction);
5273
+ });
5274
+ return sortBy(instructions, (instruction) => instruction.type === 'occupancyZone' && instruction.isSelected ? 0 : 1);
5275
+ }, [occupancyZones, selectedTrainId, topPadding, tracks]);
5276
+ const drawingFunction = useCallback((ctx, stcContext) => {
5277
+ instructionsToDraw.forEach((instruction) => {
5278
+ switch (instruction.type) {
5279
+ case 'occupancyZone':
5280
+ drawOccupationZone(ctx, stcContext, {
5281
+ zone: instruction.zone,
5282
+ position,
5283
+ yOffset: instruction.offsetY,
5284
+ isSelected: instruction.isSelected,
5285
+ });
5286
+ break;
5287
+ case 'remainingTrains':
5288
+ drawRemainingTrainsBox(ctx, stcContext, {
5289
+ position,
5290
+ time: instruction.time,
5291
+ yOffset: instruction.offsetY,
5292
+ remainingTrainsNb: instruction.amount,
5293
+ });
5294
+ break;
5295
+ }
5296
+ });
5297
+ }, [position, instructionsToDraw]);
5298
+ const pickingFunction = useCallback((imageData, { registerPickingElement, getTimePixel, getSpacePixel }, scalingRatio) => {
5299
+ const flatStepOffsetY = getSpacePixel(position);
5300
+ const flatStepEndY = getSpacePixel(position, true);
5301
+ instructionsToDraw.forEach((instruction) => {
5302
+ if (instruction.type === 'occupancyZone') {
5303
+ const x = getTimePixel(instruction.zone.startTime);
5304
+ const y = instruction.offsetY + flatStepOffsetY;
5305
+ const width = getTimePixel(instruction.zone.endTime) - x;
5306
+ const height = OCCUPANCY_ZONE_HEIGHT;
5307
+ const margin = 6;
5308
+ const pickingElement = {
5309
+ type: 'occupancyZone',
5310
+ pathId: instruction.zone.trainId,
5311
+ };
5312
+ const pickingIndex = registerPickingElement(pickingElement);
5313
+ const color = hexToRgb(indexToColor(pickingIndex));
5314
+ drawAliasedRect(imageData, { x: x - margin, y: y - margin }, width + 2 * margin, height + 2 * margin, color, scalingRatio);
5315
+ if (instruction.zone.startDirection) {
5316
+ const yStart = instruction.zone.startDirection === 'up' ? flatStepOffsetY : y;
5317
+ const yStop = instruction.zone.startDirection === 'up' ? y : flatStepEndY;
5318
+ drawAliasedRect(imageData, { x: x - margin, y: yStart - margin }, 2 * margin, yStop - yStart + 2 * margin, color, scalingRatio);
5319
+ }
5320
+ if (instruction.zone.endDirection) {
5321
+ const yStart = instruction.zone.endDirection === 'up' ? flatStepOffsetY : y;
5322
+ const yStop = instruction.zone.endDirection === 'up' ? y : flatStepEndY;
5323
+ drawAliasedRect(imageData, { x: x + width - margin, y: yStart - margin }, 2 * margin, yStop - yStart + 2 * margin, color, scalingRatio);
5324
+ }
5325
+ }
5326
+ });
5327
+ }, [position, instructionsToDraw]);
5328
+ usePicking('overlay', pickingFunction);
5329
+ useDraw('overlay', drawingFunction);
5077
5330
  return null;
5078
5331
  };
5079
5332
 
5080
- const { WHITE_50, GREY_20, RAIL_TICK } = COLORS;
5333
+ const { WHITE_100, WHITE_50, GREY_20, RAIL_TICK } = COLORS;
5081
5334
  const drawRails = ({ xStart, yStart, width, stroke = GREY_20, ctx, }) => {
5082
- ctx.clearRect(xStart, yStart, width, 9);
5335
+ ctx.fillStyle = WHITE_100;
5336
+ ctx.fillRect(xStart, yStart, width, 9);
5083
5337
  ctx.fillStyle = WHITE_50;
5084
5338
  ctx.strokeStyle = stroke;
5339
+ ctx.lineWidth = 1;
5085
5340
  ctx.beginPath();
5086
5341
  ctx.rect(xStart, yStart, width, 8);
5087
5342
  ctx.fill();
@@ -5090,6 +5345,7 @@ const drawRails = ({ xStart, yStart, width, stroke = GREY_20, ctx, }) => {
5090
5345
  const drawTick = ({ ctx, xStart, yStart, ticks, stroke, }) => {
5091
5346
  const sumTicks = sum(ticks) / 2;
5092
5347
  ctx.strokeStyle = stroke;
5348
+ ctx.lineWidth = 1;
5093
5349
  ctx.beginPath();
5094
5350
  ctx.setLineDash(ticks);
5095
5351
  ctx.moveTo(xStart, yStart - sumTicks);
@@ -5115,33 +5371,30 @@ const drawTrack = ({ ctx, width, getTimePixel, labelMarks }) => {
5115
5371
  ctx.restore();
5116
5372
  };
5117
5373
 
5118
- const { WHITE_100, HOUR_BACKGROUND } = COLORS;
5119
- const drawBackground = ({ ctx, xStart, width, height, switchBackground, }) => {
5120
- if (xStart >= 0) {
5121
- ctx.clearRect(xStart, 0, width, height);
5122
- ctx.fillStyle = switchBackground ? HOUR_BACKGROUND : WHITE_100;
5123
- ctx.fillRect(xStart, 0, width, height);
5124
- }
5125
- };
5126
- const drawTracks = ({ ctx, width, height, tracks, timeOrigin, timePixelOffset, getTimePixel, timeRanges, breakpoints, timeScale, }) => {
5127
- ctx.clearRect(0, 0, width, height);
5128
- ctx.save();
5129
- const minT = timeOrigin - timeScale * timePixelOffset;
5130
- const maxT = minT + timeScale * width;
5131
- const pixelsPerMinute = (1 / timeScale) * 60_000;
5374
+ const { HOUR_BACKGROUND_1, HOUR_BACKGROUND_2 } = COLORS;
5375
+ const drawTracks = (ctx, stcContext, { position, tracks, drawBorders, topPadding = 0, }) => {
5376
+ const { width, getSpacePixel, getTime, getTimePixel, timeScale, theme: { breakpoints, timeRanges }, } = stcContext;
5377
+ const yStart = getSpacePixel(position);
5378
+ const yEnd = getSpacePixel(position, true);
5379
+ const flatStepHeight = yEnd - yStart;
5380
+ const timeStart = getTime(0);
5381
+ const timeEnd = getTime(width);
5382
+ const pixelsPerMinute = (1 / timeScale) * MINUTE;
5132
5383
  const labelLevels = getLabelLevels(breakpoints, pixelsPerMinute, TICKS_PRIORITIES);
5133
- const labelMarks = getLabelMarks(timeRanges, minT, maxT, labelLevels);
5134
- let switchBackground = false;
5135
- for (const t in labelMarks) {
5136
- const date = new Date(+t);
5137
- const minutes = date.getMinutes().toString().padStart(2, '0');
5138
- switch (minutes) {
5139
- case '00':
5140
- switchBackground = !switchBackground;
5141
- drawBackground({ ctx, xStart: getTimePixel(+t), width, height, switchBackground });
5142
- break;
5143
- }
5384
+ const labelMarks = getLabelMarks(timeRanges, timeStart, timeEnd, labelLevels);
5385
+ // Draw backgrounds:
5386
+ let hours = Math.floor(timeStart / HOUR);
5387
+ const hourEnd = timeEnd / HOUR;
5388
+ while (hours < hourEnd) {
5389
+ const x = getTimePixel(hours * HOUR);
5390
+ const w = getTimePixel((hours + 1) * HOUR) - x;
5391
+ ctx.fillStyle = hours % 2 ? HOUR_BACKGROUND_1 : HOUR_BACKGROUND_2;
5392
+ ctx.fillRect(x, yStart, w, flatStepHeight);
5393
+ hours++;
5144
5394
  }
5395
+ // Draw actual tracks:
5396
+ ctx.save();
5397
+ ctx.translate(0, yStart + topPadding);
5145
5398
  tracks?.forEach((_, index) => {
5146
5399
  const trackTranslate = index === 0 ? CANVAS_PADDING : TRACK_HEIGHT_CONTAINER;
5147
5400
  ctx.translate(0, trackTranslate);
@@ -5153,38 +5406,116 @@ const drawTracks = ({ ctx, width, height, tracks, timeOrigin, timePixelOffset, g
5153
5406
  });
5154
5407
  });
5155
5408
  ctx.restore();
5409
+ // Draw borders:
5410
+ if (drawBorders) {
5411
+ const externalBorderWidth = 1;
5412
+ const internalBorderWidth = 2;
5413
+ const fullBorderWidth = externalBorderWidth + internalBorderWidth;
5414
+ const yStartCrisp = Math.round(yStart);
5415
+ const yEndCrisp = Math.round(yEnd);
5416
+ ctx.fillStyle = GREY_50$2;
5417
+ ctx.fillRect(0, yStartCrisp, width, externalBorderWidth);
5418
+ ctx.fillRect(0, yEndCrisp - externalBorderWidth, width, externalBorderWidth);
5419
+ ctx.fillStyle = GREY_50$2;
5420
+ ctx.globalAlpha = 0.15;
5421
+ ctx.fillRect(0, yStartCrisp + externalBorderWidth, width, internalBorderWidth);
5422
+ ctx.fillRect(0, yEndCrisp - fullBorderWidth, width, internalBorderWidth);
5423
+ ctx.globalAlpha = 1;
5424
+ }
5156
5425
  };
5157
5426
 
5158
- const TracksLayer = ({ useDraw }) => {
5159
- const drawingFunction = useCallback((ctx, { timeOrigin, timePixelOffset, getTimePixel, tracks, trackOccupancyWidth, trackOccupancyHeight, timeScale, theme: { timeRanges, breakpoints }, }) => {
5160
- if (trackOccupancyHeight && trackOccupancyWidth)
5161
- drawTracks({
5162
- ctx,
5163
- width: trackOccupancyWidth,
5164
- height: trackOccupancyHeight,
5165
- tracks,
5166
- timeOrigin,
5167
- timePixelOffset,
5168
- getTimePixel,
5169
- timeRanges,
5170
- breakpoints,
5171
- timeScale,
5172
- });
5173
- }, []);
5174
- useDraw('background', drawingFunction);
5427
+ const TracksLayer = ({ tracks, position, topPadding, drawBorders, }) => {
5428
+ const drawingFunction = useCallback((ctx, stcContext) => {
5429
+ drawTracks(ctx, stcContext, { position, topPadding, tracks, drawBorders });
5430
+ }, [drawBorders, position, topPadding, tracks]);
5431
+ useDraw('overlay', drawingFunction);
5175
5432
  return null;
5176
5433
  };
5177
5434
 
5178
- const TrackOccupancyCanvas = ({ opId, useDraw, setCanvasesRoot, selectedTrainId, setSelectedTrainId, mousePosition, }) => (React.createElement("div", { id: `track-occupancy-canvas-${opId}`, className: "bg-white-100 canvas-container", ref: setCanvasesRoot },
5179
- React.createElement(TracksLayer, { useDraw: useDraw }),
5180
- React.createElement(OccupancyZonesLayer, { useDraw: useDraw, selectedTrainId: selectedTrainId, setSelectedTrainId: setSelectedTrainId, mousePosition: mousePosition })));
5435
+ const CloseButton = ({ position, onClose }) => {
5436
+ const { getSpacePixel } = useContext(SpaceTimeChartContext);
5437
+ return (React.createElement("button", { className: "close-track-occupancy-panel", onClick: () => onClose(), style: {
5438
+ top: getSpacePixel(position),
5439
+ } },
5440
+ React.createElement("span", null,
5441
+ React.createElement(X, null))));
5442
+ };
5443
+ const TrackOccupancyCanvas = ({ position, tracks, occupancyZones, selectedTrainId, onClose, topPadding = 0, hideBorders = false, }) => (React.createElement(React.Fragment, null,
5444
+ React.createElement(TracksLayer, { position: position, tracks: tracks, topPadding: topPadding, drawBorders: !hideBorders }),
5445
+ React.createElement(OccupancyZonesLayer, { tracks: tracks, position: position, topPadding: topPadding, occupancyZones: occupancyZones, selectedTrainId: selectedTrainId }),
5446
+ onClose && React.createElement(CloseButton, { position: position, onClose: onClose })));
5447
+
5448
+ const TrackOccupancyManchette = ({ tracks, children }) => (React.createElement("div", { className: "track-occupancy-manchette" },
5449
+ children,
5450
+ tracks.map((track) => (
5451
+ // height is shared between manchette and canvas components
5452
+ React.createElement("div", { className: "track", key: track.id, style: { height: TRACK_HEIGHT_CONTAINER } },
5453
+ React.createElement("span", { className: "track-line" }, track.line),
5454
+ React.createElement("div", { className: "track-name" }, track.name),
5455
+ React.createElement("div", { className: "track-rail" }))))));
5181
5456
 
5182
- const TrackOccupancyManchette = ({ tracks }) => (React.createElement("div", { id: "track-occupancy-manchette" }, tracks.map((track) => (
5183
- // height is shared between manchette and canvas components
5184
- React.createElement("div", { className: "track", key: track.id, style: { height: TRACK_HEIGHT_CONTAINER } },
5185
- React.createElement("span", { className: "track-line" }, track.line),
5186
- React.createElement("div", { className: "track-name" }, track.name),
5187
- React.createElement("div", { className: "track-rail" }))))));
5457
+ const TrackOccupancyStandalone = ({ tracks, occupancyZones, selectedTrainId, onSelectedTrainIdChange, height = TRACK_HEIGHT_CONTAINER * tracks.length + DEFAULT_THEME.timeCaptionsSize, }) => {
5458
+ const manchetteWithSpaceTimeChartRef = useRef(null);
5459
+ const spaceTimeChartRef = useRef(null);
5460
+ const defaultTimeOrigin = useMemo(() => {
5461
+ const minTime = Math.min(...(occupancyZones.map((zone) => zone.startTime) || Date.now()));
5462
+ // Take first round hour before minTime:
5463
+ return Math.floor(minTime / HOUR) * HOUR;
5464
+ }, [occupancyZones]);
5465
+ // To make SpaceTimeChart and Manchette work, we have to provide them some dummy data:
5466
+ const waypoints = useMemo(() => [
5467
+ {
5468
+ id: 'FAKE_WAYPOINT_1',
5469
+ position: 0,
5470
+ },
5471
+ ], []);
5472
+ const splitPoints = useMemo(() => [
5473
+ {
5474
+ id: 'ACTUAL_TRACK_OCCUPANCY_DIAGRAM',
5475
+ position: 0,
5476
+ size: Math.max(height, tracks.length * TRACK_HEIGHT_CONTAINER + DEFAULT_THEME.timeCaptionsSize),
5477
+ spaceTimeChartNode: (React.createElement(TrackOccupancyCanvas, { position: 0, tracks: tracks, occupancyZones: occupancyZones, selectedTrainId: selectedTrainId, hideBorders: true })),
5478
+ manchetteNode: React.createElement(TrackOccupancyManchette, { tracks: tracks }),
5479
+ },
5480
+ ], [height, tracks, occupancyZones, selectedTrainId]);
5481
+ /**
5482
+ * We now use useManchetteWithSpaceTimeChart, to get proper pan along the time (and space axis if
5483
+ * the container is smaller than the contents):
5484
+ */
5485
+ const { manchetteProps, spaceTimeChartProps, handleScroll } = useManchetteWithSpaceTimeChart({
5486
+ waypoints,
5487
+ manchetteWithSpaceTimeChartRef,
5488
+ height,
5489
+ spaceTimeChartRef,
5490
+ splitPoints,
5491
+ defaultTimeOrigin,
5492
+ verticalPadding: 0,
5493
+ options: {
5494
+ displayTimeCaptions: true,
5495
+ enableTimePan: true,
5496
+ enableSpacePan: true,
5497
+ enableTimeZoom: false,
5498
+ },
5499
+ });
5500
+ return (React.createElement("div", { className: "track-occupancy-standalone flex flex-col" },
5501
+ React.createElement("div", { className: "bg-ambientB-5 flex flex-col justify-center main-container-header grow-0 shrink-0" },
5502
+ React.createElement(KebabHorizontal, null)),
5503
+ React.createElement("div", { className: "manchette-space-time-chart-wrapper", style: { maxHeight: height } },
5504
+ React.createElement("div", { ref: manchetteWithSpaceTimeChartRef, className: "manchette flex h-100", onScroll: handleScroll, style: { height } },
5505
+ React.createElement(Manchette, { ...manchetteProps }),
5506
+ React.createElement("div", { className: "space-time-chart-container w-full sticky", ref: spaceTimeChartRef },
5507
+ React.createElement(SpaceTimeChart, { className: "inset-0 absolute h-full", ...spaceTimeChartProps, onClick: onSelectedTrainIdChange &&
5508
+ (({ hoveredItem }) => {
5509
+ if (hoveredItem?.layer === 'overlay' &&
5510
+ isOccupancyPickingElement(hoveredItem.element)) {
5511
+ const newId = hoveredItem.element.pathId;
5512
+ onSelectedTrainIdChange(newId === selectedTrainId ? undefined : newId);
5513
+ }
5514
+ else {
5515
+ onSelectedTrainIdChange(undefined);
5516
+ }
5517
+ }) }))))));
5518
+ };
5188
5519
 
5189
- 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 };
5520
+ 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, isSegmentPickingElement, positionKmToMm, positionMmToKm, timeScaleToZoomValue, useDraw, useManchetteWithSpaceTimeChart, usePaths, usePicking };
5190
5521
  //# sourceMappingURL=index.esm.js.map