diff --git a/AGENTS.md b/AGENTS.md
index 9741698..80c622c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -373,7 +373,14 @@ No abbreviations in names.
and does nothing, and it also forces an exemption into `AppMenuBarTests`, which walks the declared
`Items` and requires every leaf to carry one or the other. The chart's two marker menus, keyed
`MenuFlyout`s in `TrendChartView.axaml`, are no placeholders: each item runs a `Click` handler that acts
- on the moment and the marker under the pointer.
+ on the moment and the marker under the pointer. Every `Go` item carries a command and its `InputGesture`
+ from `Navigation/WindowGestures`, the one gesture table; `git grep -n "InputGesture=" -- SemiPlot/SemiPlot.UI`
+ prints only lines that read `WindowGestures`. A tooltip that names a gesture prints it through
+ `WindowGestures.TextOf`, the text the menu prints (`docs/architecture/ui-text.md#the-gesture-text`).
+- A window gesture runs from `MainWindow.OnKeyDown`, which runs the `Go` item whose `InputGesture` matches
+ the key (`AppMenuBar.GoItemFor`), only on a key no control handled and never on one typed into a `TextBox`. No window `KeyBinding` carries one, because a `KeyBinding` runs
+ ahead of the focused `TextBox`; `git grep -n "KeyBinding" -- SemiPlot/SemiPlot.UI/MainWindow` prints nothing
+ (`docs/architecture/trend-interaction.md#the-go-menu-and-the-gestures`).
- The sidebar row is read-only but for its visibility box, and `TrendLegendViewTests` gates it as an
allowlist over the realised row template: every control in it is a `Border`, `Grid`, `TextBlock` or
`CheckBox`, and exactly one `CheckBox` is present. `ThePanel_RealisesNoTextEditor` gates the panel's
@@ -402,6 +409,16 @@ No abbreviations in names.
re-reads `IMarkerStore.ReadAsync` every 5 s and on `ReadNow()` after each marker write, and
`Chart/ChartMarkers` reconciles each read into `Core/Trends/MarkerSet`, which keeps a marker
with a write in flight as the window shows it (`docs/architecture/overview.md#the-live-markers`).
+ The run and marker steps and the marker list read `ChartMarkers.All` in
+ `Navigation/NavigationBarViewModel` and move the chart with `Navigation.SetWindow` and nothing else; the
+ one marker list is the bar's `MarkersButton` flyout, which the `Go` menu and Ctrl+M open too, and the one
+ run list is the bar's `RecipeRunsButton` flyout, which the `Go` menu and Ctrl+R open too; both are
+ `Navigation/NavigationListView` over one row policy, `NavigationListRows`
+ (`docs/architecture/trend-interaction.md#the-marker-and-run-lists`).
+- The minimap moves the chart only through `Minimap/MinimapPager`, which lands every page step and track
+ press with `Navigation.SetWindow` and nothing else. The page has no writer but its derivation,
+ `MinimapPage.Holding` over the chart window clipped to the newest sample, so no control picks a Day, Week or
+ Month unit and no indicator names the page (`docs/architecture/trend-interaction.md#archive-overview-minimap`).
- Every chart history request comes from `Chart/ChartHistoryPlanner.Next` and names the visible pens
only; no caller builds a `HistoryRequest` of its own
(`docs/architecture/data-integration.md#what-one-history-query-covers`).
@@ -479,7 +496,7 @@ No abbreviations in names.
`ArchiveExceptionMapper`, which stays synchronous, pure and unit-testable, and nothing opens a second
connection to enrich the error. Each read supplies every relation its statement touches, which the
detail line names: one relation for the history and realtime reads, `semiplot_tags, trends` for the
- archive extent and the archive days, all three of `semiplot_tags`, `semiplot_groups` and
+ archive extent, the archive days and the archive day spans, all three of `semiplot_tags`, `semiplot_groups` and
`semiplot_pen_groups` for the pen catalogue, and `semiplot_markers` for every marker read and write.
---
diff --git a/SemiPlot/SemiPlot.Core/Data/ArchiveDaySpan.cs b/SemiPlot/SemiPlot.Core/Data/ArchiveDaySpan.cs
new file mode 100644
index 0000000..ad8d5f2
--- /dev/null
+++ b/SemiPlot/SemiPlot.Core/Data/ArchiveDaySpan.cs
@@ -0,0 +1,4 @@
+namespace SemiPlot.Core.Data;
+
+/// An archive wall-clock day that holds raw rows, with its earliest and latest raw sample in UTC.
+public sealed record ArchiveDaySpan(DateOnly Day, DateTime FirstUtc, DateTime LastUtc);
diff --git a/SemiPlot/SemiPlot.Core/Data/IDataProvider.cs b/SemiPlot/SemiPlot.Core/Data/IDataProvider.cs
index 735fe22..8e7f9cc 100644
--- a/SemiPlot/SemiPlot.Core/Data/IDataProvider.cs
+++ b/SemiPlot/SemiPlot.Core/Data/IDataProvider.cs
@@ -23,4 +23,10 @@ Task>> QueryArchiveDaysAsync(
DateOnly firstDay,
DateOnly lastDay,
CancellationToken cancellationToken = default);
+
+ // One span per archive wall-clock day in [firstDay, lastDay] that holds a raw row of a catalogue pen, ascending.
+ Task>> QueryArchiveDaySpansAsync(
+ DateOnly firstDay,
+ DateOnly lastDay,
+ CancellationToken cancellationToken = default);
}
diff --git a/SemiPlot/SemiPlot.Core/Trends/DayCalendar.cs b/SemiPlot/SemiPlot.Core/Trends/DayCalendar.cs
new file mode 100644
index 0000000..1ad1eba
--- /dev/null
+++ b/SemiPlot/SemiPlot.Core/Trends/DayCalendar.cs
@@ -0,0 +1,214 @@
+using SemiPlot.Core.Data;
+
+namespace SemiPlot.Core.Trends;
+
+/// A horizontal span of the day calendar, in pixels from its left end.
+public readonly record struct TrackSpan(double Left, double Width);
+
+/// How much of the common working hours a day's span covers; a day without rows has no cell.
+public enum DayCoverage
+{
+ Low,
+ Medium,
+ Full
+}
+
+/// One day cell of the calendar that holds rows, graded by its coverage.
+public readonly record struct CalendarCell(double Left, double Width, DayCoverage Coverage);
+
+///
+/// The minimap's day calendar: one cell per archive wall-clock day of the extent, the last day's cell ending at
+/// (docs/architecture/trend-interaction.md#archive-overview-minimap).
+///
+public readonly record struct DayCalendar(DateOnly FirstDay, int DayCount, double Pitch, double Gap, double Right)
+{
+ /// The page outline's stroke, drawn outside the cells; the calendar keeps it free at its left end.
+ public const double OutlineStroke = 2.0;
+
+ /// The month separator's width, in the gap before a month's first cell.
+ public const double SeparatorWidth = 1.0;
+
+ private const double MaximumPitch = 20.0;
+ private const int LongestMondayLabelledArchiveDays = 42;
+ private const double NarrowestGappedPitch = 4.0;
+ private const double CellGap = 1.0;
+ private const double LowCoverageCeiling = 0.25;
+ private const double MediumCoverageCeiling = 0.75;
+
+ /// A cell's drawn width; at a pitch below one pixel a cell is one pixel column wide.
+ public double CellWidth => Math.Max(Pitch - Gap, 1.0);
+
+ /// True on an archive of six weeks or less, whose label row names its Mondays beside its months.
+ public bool ShowsMondayLabels => DayCount <= LongestMondayLabelledArchiveDays;
+
+ ///
+ /// The calendar over the days from first to last, the last ending at the row's right end, at a whole pitch of
+ /// at most 20 px, a 1 px gap from a 4 px pitch; a pitch below 1 px is fractional; null when no room is left.
+ ///
+ public static DayCalendar? Over(DateOnly firstDay, DateOnly lastDay, double width)
+ {
+ var dayCount = Math.Max(lastDay.DayNumber - firstDay.DayNumber + 1, 1);
+ var available = width - OutlineStroke;
+ if (available <= 0.0)
+ {
+ return null;
+ }
+
+ var wholePitch = Math.Min(MaximumPitch, Math.Floor(available / dayCount));
+ var pitch = wholePitch >= 1.0 ? wholePitch : available / dayCount;
+
+ return new DayCalendar(firstDay, dayCount, pitch, pitch >= NarrowestGappedPitch ? CellGap : 0.0, width);
+ }
+
+ /// The grade of a day's span against the common working hours of the archive's wall clock.
+ private static DayCoverage CoverageOf(ArchiveDaySpan span, DayHours hours, TimeZoneInfo zone)
+ {
+ var midnight = ArchiveClock.Midnight(span.Day);
+ var (hoursStart, hoursEnd) = (midnight.AddHours(hours.StartHour), midnight.AddHours(hours.EndHour));
+ var first = Later(ArchiveClock.WallClockOf(span.FirstUtc, zone), hoursStart);
+ var last = Earlier(ArchiveClock.WallClockOf(span.LastUtc, zone), hoursEnd);
+ var covered = last > first ? (last - first) / (hoursEnd - hoursStart) : 0.0;
+
+ return covered switch
+ {
+ < LowCoverageCeiling => DayCoverage.Low,
+ < MediumCoverageCeiling => DayCoverage.Medium,
+ _ => DayCoverage.Full
+ };
+ }
+
+ /// A cell's left edge; a pitch below one pixel puts a day in the whole pixel column it falls in.
+ public double CellLeft(int index)
+ {
+ return Right - CellWidth - Math.Floor((DayCount - 1 - index) * Pitch);
+ }
+
+ public TrackSpan Cell(int index)
+ {
+ return new TrackSpan(CellLeft(index), CellWidth);
+ }
+
+ /// The cell index of the day; negative before the calendar, the count or more past it.
+ public int IndexOf(DateOnly day)
+ {
+ return day.DayNumber - FirstDay.DayNumber;
+ }
+
+ /// The day whose pitch holds x, its leading gap included; null outside the cells.
+ public DateOnly? DayAt(double x)
+ {
+ if (x > Right)
+ {
+ return null;
+ }
+
+ var index = DayCount - 1 - (int)Math.Floor((Right - x) / Pitch);
+
+ return index >= 0 ? FirstDay.AddDays(index) : null;
+ }
+
+ ///
+ /// One cell per ascending span on the calendar, graded by ; days that share a pixel
+ /// column share one cell of their highest grade.
+ ///
+ public IReadOnlyList Cells(IReadOnlyList spans, DayHours hours, TimeZoneInfo zone)
+ {
+ var cells = new List(spans.Count);
+ foreach (var span in spans)
+ {
+ var index = IndexOf(span.Day);
+ if (index < 0 || index >= DayCount)
+ {
+ continue;
+ }
+
+ var cell = new CalendarCell(CellLeft(index), CellWidth, CoverageOf(span, hours, zone));
+ if (cells.Count > 0 && cells[^1].Left == cell.Left)
+ {
+ var shared = cells[^1].Coverage;
+ cells[^1] = cell with { Coverage = shared > cell.Coverage ? shared : cell.Coverage };
+ }
+ else
+ {
+ cells.Add(cell);
+ }
+ }
+
+ return cells;
+ }
+
+ /// The page's cells on the calendar with the stroke around them; a week stops at the last day.
+ public TrackSpan? PageOutline(MinimapPage page)
+ {
+ var first = Math.Max(IndexOf(page.FirstDay), 0);
+ var last = Math.Min(IndexOf(page.EndDay) - 1, DayCount - 1);
+ if (first > last)
+ {
+ return null;
+ }
+
+ var left = CellLeft(first) - OutlineStroke;
+ var right = CellLeft(last) + CellWidth + OutlineStroke;
+
+ return new TrackSpan(left, right - left);
+ }
+
+ /// The count of the markers on each archive wall-clock day that holds one.
+ public static IReadOnlyDictionary MarkerCountsByDay(
+ IReadOnlyList markerTimesUtc,
+ TimeZoneInfo zone)
+ {
+ var counts = new Dictionary();
+ foreach (var markerTimeUtc in markerTimesUtc)
+ {
+ var day = ArchiveClock.DayOf(markerTimeUtc, zone);
+ counts[day] = counts.GetValueOrDefault(day) + 1;
+ }
+
+ return counts;
+ }
+
+ /// One cell-wide tick per calendar day that holds at least one of the markers, ascending.
+ public IReadOnlyList MarkerTicks(IReadOnlyList markerTimesUtc, TimeZoneInfo zone)
+ {
+ var ticks = new List();
+ foreach (var day in MarkerCountsByDay(markerTimesUtc, zone).Keys.Order())
+ {
+ var index = IndexOf(day);
+ if (index >= 0 && index < DayCount)
+ {
+ ticks.Add(Cell(index));
+ }
+ }
+
+ return ticks;
+ }
+
+ /// The x of a 1 px line before each month's first cell; none while the Mondays are named.
+ public IReadOnlyList MonthSeparators()
+ {
+ if (ShowsMondayLabels)
+ {
+ return [];
+ }
+
+ var separators = new List();
+ var month = new DateOnly(FirstDay.Year, FirstDay.Month, 1).AddMonths(1);
+ for (; IndexOf(month) < DayCount; month = month.AddMonths(1))
+ {
+ separators.Add(CellLeft(IndexOf(month)) - SeparatorWidth);
+ }
+
+ return separators;
+ }
+
+ private static DateTime Later(DateTime first, DateTime second)
+ {
+ return first > second ? first : second;
+ }
+
+ private static DateTime Earlier(DateTime first, DateTime second)
+ {
+ return first < second ? first : second;
+ }
+}
diff --git a/SemiPlot/SemiPlot.Core/Trends/DayCalendarLabels.cs b/SemiPlot/SemiPlot.Core/Trends/DayCalendarLabels.cs
new file mode 100644
index 0000000..6181e38
--- /dev/null
+++ b/SemiPlot/SemiPlot.Core/Trends/DayCalendarLabels.cs
@@ -0,0 +1,80 @@
+namespace SemiPlot.Core.Trends;
+
+public enum CalendarLabelKind
+{
+ Day,
+ Month
+}
+
+/// A label under the calendar at , naming its day or that day's month by its kind.
+public readonly record struct CalendarLabel(double X, DateOnly Day, CalendarLabelKind Kind);
+
+/// A shown candidate by its index, at the left edge the row gives it.
+public readonly record struct PlacedLabel(int Index, double Left);
+
+///
+/// The label row under the day calendar (docs/architecture/trend-interaction.md#archive-overview-minimap).
+///
+public static class DayCalendarLabels
+{
+ // A month label stands clear of the separator before its first cell.
+ private const double MonthLabelOffset = 2.0;
+ private const double LabelGap = 4.0;
+
+ ///
+ /// The first cell's month, each month's first day, and each Monday on an archive that names its Mondays.
+ ///
+ public static IReadOnlyList Candidates(DayCalendar calendar)
+ {
+ var labels = new List();
+ for (var index = 0; index < calendar.DayCount; index++)
+ {
+ var day = calendar.FirstDay.AddDays(index);
+ var left = calendar.CellLeft(index);
+ if (index == 0 || day.Day == 1)
+ {
+ labels.Add(new CalendarLabel(left + MonthLabelOffset, day, CalendarLabelKind.Month));
+ }
+ else if (calendar.ShowsMondayLabels && day.DayOfWeek == DayOfWeek.Monday)
+ {
+ labels.Add(new CalendarLabel(left, day, CalendarLabelKind.Day));
+ }
+ }
+
+ return labels;
+ }
+
+ ///
+ /// The candidates that show, by index: the first cell's label, then each month, then each Monday, keeps its
+ /// place when it starts inside the row 4 px clear of every label kept before it; one that would run past the
+ /// row ends at its right end.
+ ///
+ public static IReadOnlyList Fitted(
+ IReadOnlyList candidates,
+ IReadOnlyList widths,
+ double rowWidth)
+ {
+ var fitted = new List();
+ var byPriority = Enumerable.Range(0, candidates.Count).OrderBy(index => PriorityOf(candidates, index));
+ foreach (var index in byPriority)
+ {
+ var left = Math.Min(candidates[index].X, rowWidth - widths[index]);
+ var right = left + widths[index];
+ var isClear = fitted.TrueForAll(kept =>
+ left >= kept.Left + widths[kept.Index] + LabelGap || right + LabelGap <= kept.Left);
+ if (left >= 0.0 && isClear)
+ {
+ fitted.Add(new PlacedLabel(index, left));
+ }
+ }
+
+ fitted.Sort((first, second) => first.Index.CompareTo(second.Index));
+
+ return fitted;
+ }
+
+ private static int PriorityOf(IReadOnlyList candidates, int index)
+ {
+ return index == 0 ? 0 : candidates[index].Kind == CalendarLabelKind.Month ? 1 : 2;
+ }
+}
diff --git a/SemiPlot/SemiPlot.Core/Trends/MarkerNavigation.cs b/SemiPlot/SemiPlot.Core/Trends/MarkerNavigation.cs
new file mode 100644
index 0000000..b83c395
--- /dev/null
+++ b/SemiPlot/SemiPlot.Core/Trends/MarkerNavigation.cs
@@ -0,0 +1,105 @@
+using SemiPlot.Core.Data;
+
+namespace SemiPlot.Core.Trends;
+
+///
+/// A recipe run from its start marker to its closing marker, the next start or the newest sample; the label is the
+/// start marker's, the recipe the run names.
+///
+public readonly record struct RecipeRun(DateTime StartUtc, DateTime EndUtc, bool IsInterrupted, string? Label = null);
+
+///
+/// Recipe runs paired from the stored markers, and the steps between runs and between operator markers. Every
+/// function reads its markers in time order, then by id, as holds them; the marker
+/// steps take .
+///
+public static class MarkerNavigation
+{
+ private const int FrameMarginDivisor = 10;
+
+ ///
+ /// The runs in time order. A start without a close runs to the next start, the last one to the newest sample; a
+ /// close without a start and a run of no length are skipped.
+ ///
+ public static IReadOnlyList Runs(IReadOnlyList markers, DateTime? newestSampleUtc)
+ {
+ var runs = new List();
+ StoredMarker? openStart = null;
+ foreach (var marker in markers)
+ {
+ if (marker.Kind == MarkerKind.RecipeStart)
+ {
+ if (openStart is not null)
+ {
+ AddRun(runs, openStart, marker.TimeUtc, isInterrupted: false);
+ }
+
+ openStart = marker;
+ }
+ else if (marker.Kind is MarkerKind.RecipeEnd or MarkerKind.RecipeInterrupted && openStart is not null)
+ {
+ AddRun(runs, openStart, marker.TimeUtc, marker.Kind == MarkerKind.RecipeInterrupted);
+ openStart = null;
+ }
+ }
+
+ if (openStart is not null && newestSampleUtc is { } newestUtc)
+ {
+ AddRun(runs, openStart, newestUtc, isInterrupted: false);
+ }
+
+ return runs;
+ }
+
+ /// The first run that starts after the time, or null.
+ public static RecipeRun? NextRun(IReadOnlyList runs, DateTime timeUtc)
+ {
+ var index = SortedSearch.FirstIndex(runs.Count, position => runs[position].StartUtc > timeUtc);
+
+ return index < runs.Count ? runs[index] : null;
+ }
+
+ /// The last run that ends before the time, or null.
+ public static RecipeRun? PreviousRun(IReadOnlyList runs, DateTime timeUtc)
+ {
+ var index = SortedSearch.FirstIndex(runs.Count, position => runs[position].EndUtc >= timeUtc) - 1;
+
+ return index >= 0 ? runs[index] : null;
+ }
+
+ public static RecipeRun? LatestRun(IReadOnlyList runs)
+ {
+ return runs.Count > 0 ? runs[^1] : null;
+ }
+
+ /// The run plus a tenth of its length on each side.
+ public static (DateTime FromUtc, DateTime ToUtc) Frame(RecipeRun run)
+ {
+ var margin = TimeSpan.FromTicks((run.EndUtc - run.StartUtc).Ticks / FrameMarginDivisor);
+
+ return (run.StartUtc - margin, run.EndUtc + margin);
+ }
+
+ public static StoredMarker? NextMarker(IReadOnlyList markers, DateTime timeUtc)
+ {
+ var index = SortedSearch.FirstIndex(markers.Count, position => markers[position].TimeUtc > timeUtc);
+
+ return index < markers.Count ? markers[index] : null;
+ }
+
+ public static StoredMarker? PreviousMarker(IReadOnlyList markers, DateTime timeUtc)
+ {
+ var index = SortedSearch.FirstIndex(markers.Count, position => markers[position].TimeUtc >= timeUtc) - 1;
+
+ return index >= 0 ? markers[index] : null;
+ }
+
+ private static void AddRun(List runs, StoredMarker start, DateTime endUtc, bool isInterrupted)
+ {
+ if (endUtc > start.TimeUtc)
+ {
+ var label = string.IsNullOrWhiteSpace(start.Label) ? null : start.Label;
+ runs.Add(new RecipeRun(start.TimeUtc, endUtc, isInterrupted, label));
+ }
+ }
+}
diff --git a/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs b/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs
index 76c606f..bdf84cd 100644
--- a/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs
+++ b/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs
@@ -12,6 +12,7 @@ public sealed class MarkerSet
private readonly Dictionary _holdCounts = [];
private StoredMarker[] _all = [];
+ private StoredMarker[] _operatorMarkers = [];
private StoredMarker[] _shownMarkers = [];
/// Every marker, shown or hidden; a snapshot like .
@@ -22,12 +23,15 @@ public sealed class MarkerSet
///
public IReadOnlyList ShownMarkers => _shownMarkers;
+ /// The operator's markers, shown or hidden, as a snapshot; recipe kinds never reach it.
+ public IReadOnlyList OperatorMarkers => _operatorMarkers;
+
public bool ShowsRecipeMarkers { get; private set; } = true;
public void ToggleRecipeMarkers()
{
ShowsRecipeMarkers = !ShowsRecipeMarkers;
- RebuildShown();
+ _shownMarkers = ShowsRecipeMarkers ? _all : _operatorMarkers;
}
public bool Apply(IReadOnlyList read)
@@ -63,7 +67,7 @@ public bool Apply(IReadOnlyList read)
}
_all = [.. next];
- RebuildShown();
+ RebuildViews();
return true;
}
@@ -97,20 +101,18 @@ public bool Release(long id)
public void Place(StoredMarker marker)
{
_all = Upsert(_all, marker);
- if (ShowsRecipeMarkers)
- {
- _shownMarkers = _all;
- }
- else if (IsShownWhileRecipesHidden(marker))
+ if (IsOperatorMarker(marker))
{
- _shownMarkers = Upsert(_shownMarkers, marker);
+ _operatorMarkers = Upsert(_operatorMarkers, marker);
}
+
+ _shownMarkers = ShowsRecipeMarkers ? _all : _operatorMarkers;
}
public void Remove(long id)
{
_all = Array.FindAll(_all, marker => marker.Id != id);
- RebuildShown();
+ RebuildViews();
}
/// The marker closest to within the tolerance; the lower id wins a tie.
@@ -157,7 +159,7 @@ private static int CompareByTimeThenId(StoredMarker first, StoredMarker second)
return byTime != 0 ? byTime : first.Id.CompareTo(second.Id);
}
- private static bool IsShownWhileRecipesHidden(StoredMarker marker)
+ private static bool IsOperatorMarker(StoredMarker marker)
{
return marker.Kind == MarkerKind.User;
}
@@ -192,28 +194,14 @@ private static StoredMarker[] Upsert(StoredMarker[] sorted, StoredMarker marker)
return next;
}
- private void RebuildShown()
+ private void RebuildViews()
{
- _shownMarkers = ShowsRecipeMarkers ? _all : Array.FindAll(_all, IsShownWhileRecipesHidden);
+ _operatorMarkers = Array.FindAll(_all, IsOperatorMarker);
+ _shownMarkers = ShowsRecipeMarkers ? _all : _operatorMarkers;
}
private int FirstAtOrAfter(DateTime time)
{
- var low = 0;
- var high = _shownMarkers.Length;
- while (low < high)
- {
- var middle = low + ((high - low) / 2);
- if (_shownMarkers[middle].TimeUtc < time)
- {
- low = middle + 1;
- }
- else
- {
- high = middle;
- }
- }
-
- return low;
+ return SortedSearch.FirstIndex(_shownMarkers.Length, index => _shownMarkers[index].TimeUtc >= time);
}
}
diff --git a/SemiPlot/SemiPlot.Core/Trends/MinimapGeometry.cs b/SemiPlot/SemiPlot.Core/Trends/MinimapGeometry.cs
index f576a49..5f8794f 100644
--- a/SemiPlot/SemiPlot.Core/Trends/MinimapGeometry.cs
+++ b/SemiPlot/SemiPlot.Core/Trends/MinimapGeometry.cs
@@ -1,71 +1,16 @@
namespace SemiPlot.Core.Trends;
-/// Where the hover time sits in the label row, and which end label it hides.
-public readonly record struct HoverTimePlacement(double Left, bool CoversFirst, bool CoversLast);
-
public static class MinimapGeometry
{
private const double FlatBandPadding = 1.0;
private const double LoneColumnWidth = 2.0;
- // A zero-or-negative extent span (no data yet) yields the full strip so the highlight never collapses.
- public static (double Start, double Width) WindowFraction(
- DateTime extentFirst,
- DateTime extentLast,
- DateTime windowFrom,
- DateTime windowTo)
- {
- var span = (extentLast - extentFirst).TotalSeconds;
- if (span <= 0.0)
- {
- return (0.0, 1.0);
- }
-
- var start = Math.Clamp((windowFrom - extentFirst).TotalSeconds / span, 0.0, 1.0);
- var end = Math.Clamp((windowTo - extentFirst).TotalSeconds / span, 0.0, 1.0);
-
- return (start, end - start);
- }
-
- public static (double Left, double Width) MarkerSpan(
- double startFraction,
- double widthFraction,
- double stripWidth,
- double minimumWidth)
- {
- if (stripWidth <= 0.0)
- {
- return (0.0, 0.0);
- }
-
- var width = Math.Min(stripWidth, Math.Max(minimumWidth, widthFraction * stripWidth));
-
- return (SpanLeftWithin(startFraction * stripWidth, width, stripWidth), width);
- }
-
/// Moves a span's left edge so it lies inside [0, limit]; a wider span starts at 0.
public static double SpanLeftWithin(double left, double width, double limit)
{
return Math.Max(0.0, Math.Min(left, limit - width));
}
- /// Centres the hover time on the pointer in a label row whose end labels sit at its edges.
- public static HoverTimePlacement PlaceHoverTime(
- double pointerX,
- double timeWidth,
- double rowWidth,
- double firstLabelWidth,
- double lastLabelWidth,
- double coverDistance)
- {
- var left = SpanLeftWithin(pointerX - (timeWidth / 2.0), timeWidth, rowWidth);
-
- return new HoverTimePlacement(
- left,
- CoversFirst: left < firstLabelWidth + coverDistance,
- CoversLast: left + timeWidth > rowWidth - lastLabelWidth - coverDistance);
- }
-
public static DateTime RightBound(DateTime extentLast, DateTime? newestSample)
{
return newestSample > extentLast ? newestSample.Value : extentLast;
diff --git a/SemiPlot/SemiPlot.Core/Trends/MinimapPage.cs b/SemiPlot/SemiPlot.Core/Trends/MinimapPage.cs
new file mode 100644
index 0000000..0310dac
--- /dev/null
+++ b/SemiPlot/SemiPlot.Core/Trends/MinimapPage.cs
@@ -0,0 +1,284 @@
+using SemiPlot.Core.Data;
+
+namespace SemiPlot.Core.Trends;
+
+public enum MinimapPageUnit
+{
+ Day,
+ Week,
+ Month
+}
+
+public enum PageDirection
+{
+ Previous,
+ Next
+}
+
+/// A Day page's common hours as archive wall-clock whole hours; an end of 24 is the next midnight.
+public readonly record struct DayHours(int StartHour, int EndHour)
+{
+ public const int HoursPerDay = 24;
+
+ public static readonly DayHours FullDay = new(0, HoursPerDay);
+}
+
+///
+/// One minimap detail page: a working day, a Monday-to-Monday week or a calendar month of the archive's wall
+/// clock. Every function reads its spans ascending by day, as the provider returns them.
+///
+public readonly record struct MinimapPage(
+ MinimapPageUnit Unit,
+ DateOnly FirstDay,
+ DayHours Hours,
+ DateTime FromUtc,
+ DateTime ToUtc)
+{
+ public const int DaysPerWeek = 7;
+
+ private const int LowPercent = 5;
+ private const int HighPercent = 95;
+
+ /// The day after the page's last day.
+ public DateOnly EndDay => EndDayOf(Unit, FirstDay);
+
+ public bool Holds(DateOnly day)
+ {
+ return day >= FirstDay && day < EndDay;
+ }
+
+ public bool Holds(DateTime fromUtc, DateTime toUtc)
+ {
+ return fromUtc >= FromUtc && toUtc <= ToUtc;
+ }
+
+ ///
+ /// The smallest page that holds the window, its end clipped to the newest sample: its start's Day page, else
+ /// the Week page, else the Month page of its start, which a window wider than a month overruns.
+ ///
+ public static MinimapPage Holding(
+ DateTime windowFromUtc,
+ DateTime windowToUtc,
+ DateTime? newestSampleUtc,
+ DayHours hours,
+ IReadOnlyList spans,
+ TimeZoneInfo zone)
+ {
+ var heldToUtc = newestSampleUtc < windowToUtc ? newestSampleUtc.Value : windowToUtc;
+ var day = Snap(MinimapPageUnit.Day, windowFromUtc, hours, spans, zone);
+ if (day.Holds(windowFromUtc, heldToUtc))
+ {
+ return day;
+ }
+
+ var week = Snap(MinimapPageUnit.Week, windowFromUtc, hours, spans, zone);
+
+ return week.Holds(windowFromUtc, heldToUtc)
+ ? week
+ : Snap(MinimapPageUnit.Month, windowFromUtc, hours, spans, zone);
+ }
+
+ /// P5 of each day's first sample to P95 of each day's last, rounded out to whole hours.
+ public static DayHours WorkingHours(IReadOnlyList spans, TimeZoneInfo zone)
+ {
+ if (spans.Count == 0)
+ {
+ return DayHours.FullDay;
+ }
+
+ var firsts = new TimeSpan[spans.Count];
+ var lasts = new TimeSpan[spans.Count];
+ for (var index = 0; index < spans.Count; index++)
+ {
+ firsts[index] = TimeIntoDay(spans[index].FirstUtc, spans[index].Day, zone);
+ lasts[index] = TimeIntoDay(spans[index].LastUtc, spans[index].Day, zone);
+ }
+
+ Array.Sort(firsts);
+ Array.Sort(lasts);
+ var startHour = Math.Min(FloorHour(NearestRank(firsts, LowPercent)), DayHours.HoursPerDay - 1);
+ var endHour = Math.Max(CeilingHour(NearestRank(lasts, HighPercent)), startHour + 1);
+
+ return new DayHours(startHour, endHour);
+ }
+
+ /// The page of that holds the archive wall-clock day of the time.
+ public static MinimapPage Snap(
+ MinimapPageUnit unit,
+ DateTime timeUtc,
+ DayHours hours,
+ IReadOnlyList spans,
+ TimeZoneInfo zone)
+ {
+ return PageOn(unit, ArchiveClock.DayOf(timeUtc, zone), hours, spans, zone);
+ }
+
+ /// The nearest page in the direction whose days hold a span, or null past the last one.
+ public static MinimapPage? Step(
+ MinimapPage page,
+ PageDirection direction,
+ IReadOnlyList spans,
+ TimeZoneInfo zone)
+ {
+ var index = direction == PageDirection.Next
+ ? FirstIndexFrom(page.EndDay, spans)
+ : FirstIndexFrom(page.FirstDay, spans) - 1;
+ if (index < 0 || index >= spans.Count)
+ {
+ return null;
+ }
+
+ return PageOn(page.Unit, spans[index].Day, page.Hours, spans, zone);
+ }
+
+ /// The window at its clock offset on the page, or at the page's first sample if that misses.
+ public static (DateTime FromUtc, DateTime ToUtc) Land(
+ DateTime windowFromUtc,
+ DateTime windowToUtc,
+ MinimapPage page,
+ IReadOnlyList spans,
+ TimeZoneInfo zone)
+ {
+ var width = windowToUtc - windowFromUtc;
+ var windowWallClock = ArchiveClock.WallClockOf(windowFromUtc, zone);
+ var windowUnitStart = UnitStart(page.Unit, DateOnly.FromDateTime(windowWallClock));
+ var offset = windowWallClock - ArchiveClock.Midnight(windowUnitStart);
+ var fromUtc = ArchiveClock.ToUtc(ArchiveClock.Midnight(page.FirstDay) + offset, zone);
+ var toUtc = fromUtc + width;
+
+ var first = FirstIndexFrom(page.FirstDay, spans);
+ var end = FirstIndexFrom(page.EndDay, spans);
+ if (first == end)
+ {
+ return (fromUtc, toUtc);
+ }
+
+ for (var index = first; index < end; index++)
+ {
+ if (spans[index].FirstUtc <= toUtc && spans[index].LastUtc >= fromUtc)
+ {
+ return (fromUtc, toUtc);
+ }
+ }
+
+ return (spans[first].FirstUtc, spans[first].FirstUtc + width);
+ }
+
+ /// The span of the time's own day, else the day whose span lies nearer; a tie takes the earlier.
+ public static ArchiveDaySpan? SnapToData(DateTime timeUtc, IReadOnlyList spans, TimeZoneInfo zone)
+ {
+ if (spans.Count == 0)
+ {
+ return null;
+ }
+
+ var day = ArchiveClock.DayOf(timeUtc, zone);
+ var index = FirstIndexFrom(day, spans);
+ if (index == 0 || (index < spans.Count && spans[index].Day == day))
+ {
+ return spans[index];
+ }
+
+ if (index == spans.Count)
+ {
+ return spans[^1];
+ }
+
+ var before = spans[index - 1];
+ var after = spans[index];
+
+ return timeUtc - before.LastUtc <= after.FirstUtc - timeUtc ? before : after;
+ }
+
+ private static MinimapPage PageOn(
+ MinimapPageUnit unit,
+ DateOnly day,
+ DayHours hours,
+ IReadOnlyList spans,
+ TimeZoneInfo zone)
+ {
+ if (unit != MinimapPageUnit.Day)
+ {
+ var first = UnitStart(unit, day);
+
+ return new MinimapPage(
+ unit,
+ first,
+ hours,
+ ArchiveClock.ToUtc(ArchiveClock.Midnight(first), zone),
+ ArchiveClock.ToUtc(ArchiveClock.Midnight(EndDayOf(unit, first)), zone));
+ }
+
+ var startHour = hours.StartHour;
+ var endHour = hours.EndHour;
+ var index = FirstIndexFrom(day, spans);
+ if (index < spans.Count && spans[index].Day == day)
+ {
+ startHour = Math.Min(startHour, FloorHour(TimeIntoDay(spans[index].FirstUtc, day, zone)));
+ endHour = Math.Max(endHour, CeilingHour(TimeIntoDay(spans[index].LastUtc, day, zone)));
+ }
+
+ return new MinimapPage(
+ unit,
+ day,
+ hours,
+ ArchiveClock.ToUtc(ArchiveClock.Midnight(day).AddHours(startHour), zone),
+ ArchiveClock.ToUtc(ArchiveClock.Midnight(day).AddHours(endHour), zone));
+ }
+
+ private static DateOnly UnitStart(MinimapPageUnit unit, DateOnly day)
+ {
+ return unit switch
+ {
+ MinimapPageUnit.Week =>
+ day.AddDays(-(((int)day.DayOfWeek + DaysPerWeek - (int)DayOfWeek.Monday) % DaysPerWeek)),
+ MinimapPageUnit.Month => new DateOnly(day.Year, day.Month, 1),
+ _ => day
+ };
+ }
+
+ private static DateOnly EndDayOf(MinimapPageUnit unit, DateOnly firstDay)
+ {
+ return unit switch
+ {
+ MinimapPageUnit.Week => firstDay.AddDays(DaysPerWeek),
+ MinimapPageUnit.Month => firstDay.AddMonths(1),
+ _ => firstDay.AddDays(1)
+ };
+ }
+
+ /// The index of the first span on or after the day, or the count when none is.
+ private static int FirstIndexFrom(DateOnly day, IReadOnlyList spans)
+ {
+ return SortedSearch.FirstIndex(spans.Count, position => spans[position].Day >= day);
+ }
+
+ private static TimeSpan NearestRank(TimeSpan[] sorted, int percent)
+ {
+ var rank = ((percent * sorted.Length) + 99) / 100;
+
+ return sorted[Math.Max(rank, 1) - 1];
+ }
+
+ private static TimeSpan TimeIntoDay(DateTime utc, DateOnly day, TimeZoneInfo zone)
+ {
+ var timeIntoDay = ArchiveClock.WallClockOf(utc, zone) - ArchiveClock.Midnight(day);
+
+ return Clamp(timeIntoDay, TimeSpan.Zero, TimeSpan.FromHours(DayHours.HoursPerDay));
+ }
+
+ private static TimeSpan Clamp(TimeSpan value, TimeSpan minimum, TimeSpan maximum)
+ {
+ return value < minimum ? minimum : value > maximum ? maximum : value;
+ }
+
+ private static int FloorHour(TimeSpan timeOfDay)
+ {
+ return (int)(timeOfDay.Ticks / TimeSpan.TicksPerHour);
+ }
+
+ private static int CeilingHour(TimeSpan timeOfDay)
+ {
+ return (int)((timeOfDay.Ticks + TimeSpan.TicksPerHour - 1) / TimeSpan.TicksPerHour);
+ }
+}
diff --git a/SemiPlot/SemiPlot.Core/Trends/MinimapTrackGeometry.cs b/SemiPlot/SemiPlot.Core/Trends/MinimapTrackGeometry.cs
new file mode 100644
index 0000000..45ecc7d
--- /dev/null
+++ b/SemiPlot/SemiPlot.Core/Trends/MinimapTrackGeometry.cs
@@ -0,0 +1,147 @@
+using SemiPlot.Core.Data;
+
+namespace SemiPlot.Core.Trends;
+
+/// The chart window on the detail track, clipped to the page; a cut edge draws no border.
+public readonly record struct PageWindowBox(double Left, double Width, bool CutsLeft, bool CutsRight);
+
+/// A recipe run's shade on a Day page; an interrupted run ending on the page draws an edge there.
+public readonly record struct RunShade(double Left, double Width, bool HasEndEdge);
+
+public enum TrackTickKind
+{
+ Hour,
+ Day
+}
+
+/// A tick at for the archive wall-clock time the UI formats by its kind.
+public readonly record struct TrackTick(double X, DateTime WallClock, TrackTickKind Kind);
+
+/// The minimap's detail track over one page: the window box, the run shades and the page ticks.
+public static class MinimapTrackGeometry
+{
+ private static readonly int[] _hourStrides = [1, 2, 3, 4, 6, 12];
+ private static readonly int[] _dayStrides = [1, 2, 7];
+
+ /// The chart window over the page's width, clipped at its edges; null when it misses the page.
+ public static PageWindowBox? WindowBox(
+ MinimapPage page,
+ DateTime windowFromUtc,
+ DateTime windowToUtc,
+ double width,
+ double minimumWidth)
+ {
+ if (width <= 0.0 || windowToUtc <= page.FromUtc || windowFromUtc >= page.ToUtc)
+ {
+ return null;
+ }
+
+ var pageSpan = page.ToUtc - page.FromUtc;
+ var startFraction = Math.Max((windowFromUtc - page.FromUtc) / pageSpan, 0.0);
+ var endFraction = Math.Min((windowToUtc - page.FromUtc) / pageSpan, 1.0);
+ var boxWidth = Math.Min(width, Math.Max(minimumWidth, (endFraction - startFraction) * width));
+ var left = MinimapGeometry.SpanLeftWithin(startFraction * width, boxWidth, width);
+
+ return new PageWindowBox(left, boxWidth, windowFromUtc < page.FromUtc, windowToUtc > page.ToUtc);
+ }
+
+ /// The shade of every run that meets a Day page, clipped at its edges; a Week page shades none.
+ public static IReadOnlyList RunShades(
+ MinimapPage page,
+ IReadOnlyList runs,
+ double width,
+ double minimumWidth)
+ {
+ var shades = new List();
+ if (page.Unit != MinimapPageUnit.Day)
+ {
+ return shades;
+ }
+
+ foreach (var run in runs)
+ {
+ if (WindowBox(page, run.StartUtc, run.EndUtc, width, minimumWidth) is { } box)
+ {
+ shades.Add(new RunShade(box.Left, box.Width, run.IsInterrupted && !box.CutsRight));
+ }
+ }
+
+ return shades;
+ }
+
+ /// Whole hours on a Day page, midnights on a Week or Month page, thinned to the minimum spacing.
+ public static IReadOnlyList PageTicks(
+ MinimapPage page,
+ double width,
+ double minimumSpacing,
+ TimeZoneInfo zone)
+ {
+ var pageSpan = page.ToUtc - page.FromUtc;
+ if (width <= 0.0 || pageSpan <= TimeSpan.Zero)
+ {
+ return [];
+ }
+
+ return page.Unit == MinimapPageUnit.Day
+ ? HourTicks(page, width, minimumSpacing, zone)
+ : DayTicks(page, width, minimumSpacing, zone);
+ }
+
+ /// Steps in UTC and keeps ticks a stride of real hours apart across a skipped or repeated hour.
+ private static List HourTicks(MinimapPage page, double width, double minimumSpacing, TimeZoneInfo zone)
+ {
+ var pixelsPerHour = width / (page.ToUtc - page.FromUtc).TotalHours;
+ var stride = Stride(pixelsPerHour, minimumSpacing, _hourStrides);
+ var strideSpan = TimeSpan.FromHours(stride);
+ var ticks = new List();
+ var nextAllowedUtc = page.FromUtc;
+ for (var utc = page.FromUtc; utc < page.ToUtc; utc = utc.AddHours(1))
+ {
+ var wallClock = ArchiveClock.WallClockOf(utc, zone);
+ if (utc >= nextAllowedUtc && wallClock.Minute == 0 && wallClock.Hour % stride == 0
+ && PageX(page, utc, width) is { } x)
+ {
+ ticks.Add(new TrackTick(x, wallClock, TrackTickKind.Hour));
+ nextAllowedUtc = utc + strideSpan;
+ }
+ }
+
+ return ticks;
+ }
+
+ private static List DayTicks(MinimapPage page, double width, double minimumSpacing, TimeZoneInfo zone)
+ {
+ var dayCount = page.EndDay.DayNumber - page.FirstDay.DayNumber;
+ var stride = Stride(width / dayCount, minimumSpacing, _dayStrides);
+ var ticks = new List();
+ for (var index = 0; index < dayCount; index += stride)
+ {
+ var midnight = ArchiveClock.Midnight(page.FirstDay.AddDays(index));
+ if (PageX(page, ArchiveClock.ToUtc(midnight, zone), width) is { } x)
+ {
+ ticks.Add(new TrackTick(x, midnight, TrackTickKind.Day));
+ }
+ }
+
+ return ticks;
+ }
+
+ /// The smallest stride whose units sit at least the minimum spacing apart, else the largest.
+ private static int Stride(double pixelsPerUnit, double minimumSpacing, int[] strides)
+ {
+ foreach (var stride in strides)
+ {
+ if (stride * pixelsPerUnit >= minimumSpacing)
+ {
+ return stride;
+ }
+ }
+
+ return strides[^1];
+ }
+
+ private static double? PageX(MinimapPage page, DateTime utc, double width)
+ {
+ return MinimapGeometry.FractionAt(page.FromUtc, page.ToUtc, utc) * width;
+ }
+}
diff --git a/SemiPlot/SemiPlot.Core/Trends/SortedSearch.cs b/SemiPlot/SemiPlot.Core/Trends/SortedSearch.cs
new file mode 100644
index 0000000..7e6a237
--- /dev/null
+++ b/SemiPlot/SemiPlot.Core/Trends/SortedSearch.cs
@@ -0,0 +1,27 @@
+namespace SemiPlot.Core.Trends;
+
+internal static class SortedSearch
+{
+ ///
+ /// The first index at which holds, or the count; it must hold monotonically.
+ ///
+ public static int FirstIndex(int count, Func reached)
+ {
+ var low = 0;
+ var high = count;
+ while (low < high)
+ {
+ var middle = low + ((high - low) / 2);
+ if (reached(middle))
+ {
+ high = middle;
+ }
+ else
+ {
+ low = middle + 1;
+ }
+ }
+
+ return low;
+ }
+}
diff --git a/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs b/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs
index c2ba4e5..27e1954 100644
--- a/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs
+++ b/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs
@@ -194,6 +194,29 @@ LIMIT 1
ORDER BY 1;
""";
+ ///
+ /// The earliest and latest raw timestamp of each archive-local day of a range that holds a raw row of a
+ /// configured variable: the extent's lateral pair per pen and day. The OFFSET 0 is load-bearing, without
+ /// it the HAVING runs the first probe a second time (docs/architecture/data-integration.md#read-cost).
+ ///
+ public const string ArchiveDaySpans = """
+ SELECT day.start::date AS day, min(bounds.lo) AS first, max(bounds.hi) AS last
+ FROM generate_series(@firstDay, @lastDay, interval '1 day') AS day(start)
+ CROSS JOIN semiplot_tags tag
+ CROSS JOIN LATERAL (
+ SELECT (SELECT min(t) FROM trends
+ WHERE id = tag.id AND l = 0
+ AND t >= day.start AND t < day.start + interval '1 day') AS lo,
+ (SELECT max(t) FROM trends
+ WHERE id = tag.id AND l = 0
+ AND t >= day.start AND t < day.start + interval '1 day') AS hi
+ OFFSET 0
+ ) bounds
+ GROUP BY day.start
+ HAVING min(bounds.lo) IS NOT NULL
+ ORDER BY 1;
+ """;
+
///
/// Every raw sample newer than the last one a subscription saw, issued once per poll tick with a strict
/// > so the row that set @lastSeen never returns twice (docs/architecture/scada-archive.md).
diff --git a/SemiPlot/SemiPlot.DataSource.Postgres/PostgresDataProvider.cs b/SemiPlot/SemiPlot.DataSource.Postgres/PostgresDataProvider.cs
index 5de5ec6..06f60a3 100644
--- a/SemiPlot/SemiPlot.DataSource.Postgres/PostgresDataProvider.cs
+++ b/SemiPlot/SemiPlot.DataSource.Postgres/PostgresDataProvider.cs
@@ -190,6 +190,46 @@ public async Task>> QueryArchiveDaysAsync(
}
}
+ ///
+ /// The days bind as archive wall-clock days, as in ; the samples convert.
+ ///
+ public async Task>> QueryArchiveDaySpansAsync(
+ DateOnly firstDay,
+ DateOnly lastDay,
+ CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
+ await using var command = new NpgsqlCommand(ArchiveStatements.ArchiveDaySpans, connection);
+
+ BindArchiveDays(command, firstDay, lastDay);
+
+ await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
+
+ var spans = new List();
+
+ while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
+ {
+ spans.Add(new ArchiveDaySpan(
+ reader.GetFieldValue(0),
+ _timeConverter.ToUtc(reader.GetDateTime(1)),
+ _timeConverter.ToUtc(reader.GetDateTime(2))));
+ }
+
+ return Result.Ok>(spans);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception exception)
+ {
+ return Result.Fail>(
+ Map(exception, ArchiveStatements.TagCatalogAndTrendsRelations));
+ }
+ }
+
// docs/architecture/data-integration.md#operation-to-statement
private async Task> ReadHistoryAsync(
int[] penIds,
diff --git a/SemiPlot/SemiPlot.Tests.Integration/ExplainPlanTests.cs b/SemiPlot/SemiPlot.Tests.Integration/ExplainPlanTests.cs
index e5dc21e..9ae24c4 100644
--- a/SemiPlot/SemiPlot.Tests.Integration/ExplainPlanTests.cs
+++ b/SemiPlot/SemiPlot.Tests.Integration/ExplainPlanTests.cs
@@ -314,6 +314,33 @@ public async Task ArchiveDays_ReadsThroughTheIndex()
+ $"every row of its pen and day.{Environment.NewLine}{plan}");
}
+ // The same range as ArchiveDays_ReadsThroughTheIndex: a row-holding partition and an empty day on each side.
+ [Fact]
+ public async Task ArchiveDaySpans_ReachesEachBoundByAnIndexEdge()
+ {
+ var database = analysedArchive.Database;
+ var seededDay = DateOnly.FromDateTime(ArchiveTemplate.Slice.Start);
+
+ var plan = await ExplainAsync(
+ database.PlotConnectionString,
+ ArchiveStatements.ArchiveDaySpans,
+ command => PostgresDataProvider.BindArchiveDays(command, seededDay.AddDays(-1), seededDay.AddDays(1)),
+ TestContext.Current.CancellationToken);
+
+ _sequentialScanOverRows.IsMatch(plan).Should().BeFalse(
+ "The day spans statement no longer narrows on the primary key: the plan reads a row-holding trends "
+ + $"partition sequentially.{Environment.NewLine}{plan}");
+
+ (_indexEdgeReachedRows.Count(plan) >= BoundedSubqueryCount).Should().BeTrue(
+ "The day spans plan reaches no row-holding trends partition through an index scan from each of its "
+ + "two bounded subqueries; each must step to one index edge per pen and day."
+ + $"{Environment.NewLine}{plan}");
+
+ _bitmapReadRows.IsMatch(plan).Should().BeFalse(
+ "The day spans statement reads a row-holding trends partition as a bitmap, so one probe collects every "
+ + $"row of its pen and day.{Environment.NewLine}{plan}");
+ }
+
// An unbounded seek is one probe per older day, per pen, on every window change.
private static void AssertSeedWalkStaysWithinItsBound(
string plan, string statement, int maximumPartitionReads = MaximumDayPartitionsRead)
diff --git a/SemiPlot/SemiPlot.Tests.Integration/PostgresArchiveDaySpansReadTests.cs b/SemiPlot/SemiPlot.Tests.Integration/PostgresArchiveDaySpansReadTests.cs
new file mode 100644
index 0000000..a2ff6d8
--- /dev/null
+++ b/SemiPlot/SemiPlot.Tests.Integration/PostgresArchiveDaySpansReadTests.cs
@@ -0,0 +1,195 @@
+using AwesomeAssertions;
+
+using FluentResults;
+
+using Microsoft.Extensions.DependencyInjection;
+
+using Npgsql;
+
+using NpgsqlTypes;
+
+using SemiPlot.Core.Data;
+using SemiPlot.Core.Data.Errors;
+using SemiPlot.Tools.ArchiveSeeder;
+
+using Xunit;
+
+namespace SemiPlot.Tests.Integration;
+
+[Collection(ArchiveDatabaseCollection.Name)]
+[Trait("Component", "Core")]
+[Trait("Area", "Data")]
+[Trait("Category", "Integration")]
+public sealed class PostgresArchiveDaySpansReadTests(
+ PostgresContainerFixture postgresContainerFixture,
+ SeededArchive seededArchive)
+ : IClassFixture
+{
+ private static readonly string _appendRowCommand = $"""
+ INSERT INTO public.trends (id, l, t, v, q) VALUES (@id, @l, @t, 1, {ArchiveRow.OrdinaryQuality});
+ """;
+
+ private static readonly Lazy _seededSpans = new(GenerateSeededSpans);
+
+ private static DateOnly FirstSeededDay => DateOnly.FromDateTime(ArchiveTemplate.Slice.Start);
+
+ private static DateOnly LastSeededDay => DateOnly.FromDateTime(ArchiveTemplate.Slice.End).AddDays(-1);
+
+ [Fact]
+ public async Task ARangeAroundTheSeed_ReturnsTheRawBoundsOfEachSeededDayInUtc()
+ {
+ var result = await ReadSpansAsync(
+ seededArchive.Database.PlotConnectionString,
+ FirstSeededDay.AddDays(-3),
+ LastSeededDay.AddDays(3));
+
+ result.IsSuccess.Should().BeTrue(ArchiveReadSupport.Describe(result));
+ result.Value.Should().NotBeEmpty();
+ result.Value.Should().Equal(_seededSpans.Value);
+ result.Value.Select(span => span.FirstUtc.Kind).Should().AllBeEquivalentTo(DateTimeKind.Utc);
+ }
+
+ [Fact]
+ public async Task ARangeBeforeTheSeed_ReturnsNoSpan()
+ {
+ var result = await ReadSpansAsync(
+ seededArchive.Database.PlotConnectionString,
+ FirstSeededDay.AddDays(-30),
+ FirstSeededDay.AddDays(-1));
+
+ result.IsSuccess.Should().BeTrue(ArchiveReadSupport.Describe(result));
+ result.Value.Should().BeEmpty();
+ }
+
+ // The raw day holds one row, so its span opens and closes at that row, converted out of the archive's zone.
+ [Fact]
+ public async Task ADayHoldingOnlyACoarseRow_IsAbsentBetweenTwoDaysWithRawRows()
+ {
+ var cancellationToken = TestContext.Current.CancellationToken;
+ var penId = RawLayerGenerator.SelectPens(ArchiveTemplate.Slice.PenCount)[0].PenId;
+ var coarseDay = LastSeededDay.AddDays(1);
+ var rawDay = LastSeededDay.AddDays(2);
+ await using var database = await postgresContainerFixture.CloneAsync(
+ CloneSource.Template,
+ async clone =>
+ {
+ await AppendRowAsync(clone, penId, LayerThinner.MinuteLayer, Noon(coarseDay), cancellationToken);
+ await AppendRowAsync(clone, penId, ArchiveRow.RawLayer, Noon(rawDay), cancellationToken);
+ },
+ cancellationToken);
+
+ var result = await ReadSpansAsync(database.PlotConnectionString, FirstSeededDay, rawDay.AddDays(1));
+
+ var rawNoonUtc = ArchiveProviderFactory.TimeConverter.ToUtc(Noon(rawDay));
+
+ result.IsSuccess.Should().BeTrue(ArchiveReadSupport.Describe(result));
+ result.Value.Should().Equal([.. _seededSpans.Value, new ArchiveDaySpan(rawDay, rawNoonUtc, rawNoonUtc)]);
+ }
+
+ [Fact]
+ public async Task AnEmptiedCatalogue_ReturnsNoSpan()
+ {
+ await using var database = await postgresContainerFixture.CloneAsync(
+ CloneSource.Template,
+ clone => ArchiveDatabase.ExecuteAsync(
+ clone.AdminConnectionString,
+ ArchiveReadSupport.EmptyCatalogCommand,
+ TestContext.Current.CancellationToken),
+ TestContext.Current.CancellationToken);
+
+ var result = await ReadSpansAsync(database.PlotConnectionString, FirstSeededDay, LastSeededDay);
+
+ result.IsSuccess.Should().BeTrue(ArchiveReadSupport.Describe(result));
+ result.Value.Should().BeEmpty();
+ }
+
+ [Fact]
+ public async Task ADroppedTrendsTable_FailsNamingEveryRelationTheReadTouches()
+ {
+ await using var database = await postgresContainerFixture.CloneAsync(
+ CloneSource.Provisioned,
+ clone => ArchiveDatabase.ExecuteAsync(
+ clone.WriterConnectionString,
+ ArchiveReadSupport.DropTrendsCommand,
+ TestContext.Current.CancellationToken),
+ TestContext.Current.CancellationToken);
+
+ var result = await ReadSpansAsync(database.PlotConnectionString, FirstSeededDay, LastSeededDay);
+
+ result.IsFailed.Should().BeTrue();
+
+ var error = result.Errors.OfType().Should().ContainSingle().Which;
+
+ error.Kind.Should().Be(ArchiveFault.TableMissing);
+ error.Detail.Should().Be("semiplot_tags, trends");
+ error.Database.Should().Be(database.Name);
+ }
+
+ [Fact]
+ public async Task ACancelledRead_ThrowsInsteadOfFailing()
+ {
+ await using var services = ArchiveProviderFactory.Build(seededArchive.Database.PlotConnectionString);
+ using var cancellation = new CancellationTokenSource();
+ await cancellation.CancelAsync();
+
+ var read = () => services.GetRequiredService()
+ .QueryArchiveDaySpansAsync(FirstSeededDay, LastSeededDay, cancellation.Token);
+
+ await read.Should().ThrowAsync();
+ }
+
+ private static async Task>> ReadSpansAsync(
+ string connectionString,
+ DateOnly firstDay,
+ DateOnly lastDay)
+ {
+ await using var services = ArchiveProviderFactory.Build(connectionString);
+
+ return await services.GetRequiredService()
+ .QueryArchiveDaySpansAsync(firstDay, lastDay, TestContext.Current.CancellationToken);
+ }
+
+ // The day partition comes first: a row with no matching partition lands in the default one.
+ private static async Task AppendRowAsync(
+ ArchiveDatabase database,
+ int penId,
+ short layer,
+ DateTime archiveLocal,
+ CancellationToken cancellationToken)
+ {
+ await using var connection = new NpgsqlConnection(database.WriterConnectionString);
+
+ await connection.OpenAsync(cancellationToken);
+
+ await using var partition = new NpgsqlCommand(PartitionScript.CreateStatement(archiveLocal.Date), connection);
+
+ await partition.ExecuteNonQueryAsync(cancellationToken);
+
+ await using var command = new NpgsqlCommand(_appendRowCommand, connection);
+
+ command.Parameters.Add(new NpgsqlParameter("id", NpgsqlDbType.Integer) { Value = penId });
+ command.Parameters.Add(new NpgsqlParameter("l", NpgsqlDbType.Smallint) { Value = layer });
+ command.Parameters.Add(new NpgsqlParameter("t", NpgsqlDbType.Timestamp) { Value = archiveLocal });
+
+ await command.ExecuteNonQueryAsync(cancellationToken);
+ }
+
+ private static DateTime Noon(DateOnly day)
+ {
+ return day.ToDateTime(new TimeOnly(12, 0));
+ }
+
+ // The seeder's timestamps are the archive's own wall clock, so a row's day is its date as written; the
+ // bounds leave the provider through the same zone the factory hands it.
+ private static ArchiveDaySpan[] GenerateSeededSpans()
+ {
+ return [.. RawLayerGenerator.Generate(ArchiveTemplate.Slice)
+ .Where(row => row.Layer == ArchiveRow.RawLayer)
+ .GroupBy(row => DateOnly.FromDateTime(row.Timestamp))
+ .OrderBy(day => day.Key)
+ .Select(day => new ArchiveDaySpan(
+ day.Key,
+ ArchiveProviderFactory.TimeConverter.ToUtc(day.Min(row => row.Timestamp)),
+ ArchiveProviderFactory.TimeConverter.ToUtc(day.Max(row => row.Timestamp))))];
+ }
+}
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/BerlinClock.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/BerlinClock.cs
new file mode 100644
index 0000000..326c9c3
--- /dev/null
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/BerlinClock.cs
@@ -0,0 +1,15 @@
+namespace SemiPlot.Tests.Unit.Core.Trends;
+
+/// Europe/Berlin, the archive zone the minimap's Core tests read their wall clock in.
+internal static class BerlinClock
+{
+ public static readonly TimeZoneInfo BerlinZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
+
+ /// The instant of a whole wall-clock hour of 2026 in Berlin.
+ public static DateTime Berlin(int month, int day, int hour)
+ {
+ var wallClock = new DateTime(2026, month, day, hour, 0, 0, DateTimeKind.Unspecified);
+
+ return TimeZoneInfo.ConvertTimeToUtc(wallClock, BerlinZone);
+ }
+}
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarLabelsTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarLabelsTests.cs
new file mode 100644
index 0000000..cb9565f
--- /dev/null
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarLabelsTests.cs
@@ -0,0 +1,155 @@
+using AwesomeAssertions;
+
+using SemiPlot.Core.Trends;
+
+using Xunit;
+
+namespace SemiPlot.Tests.Unit.Core.Trends;
+
+[Trait("Component", "Core")]
+[Trait("Area", "Data")]
+[Trait("Category", "Unit")]
+public sealed class DayCalendarLabelsTests
+{
+ private const double RowWidth = 1102.0;
+ private const double NarrowRowWidth = 200.0;
+ private const double MonthLabelWidth = 30.0;
+ private const double MondayLabelWidth = 34.0;
+
+ [Fact]
+ public void Candidates_OfATwoDayArchive_AreTheMonthAtTheFirstCell()
+ {
+ var firstDay = new DateOnly(2026, 11, 10);
+ var calendar = DayCalendar.Over(firstDay, firstDay.AddDays(1), RowWidth)!.Value;
+
+ var labels = DayCalendarLabels.Candidates(calendar);
+
+ labels.Should().Equal(new CalendarLabel(calendar.CellLeft(0) + 2.0, firstDay, CalendarLabelKind.Month));
+ }
+
+ [Fact]
+ public void Candidates_OfAThreeWeekArchive_AreTheMonthsAndTheMondays()
+ {
+ var firstDay = new DateOnly(2026, 1, 22);
+ var calendar = DayCalendar.Over(firstDay, firstDay.AddDays(20), RowWidth)!.Value;
+
+ var labels = DayCalendarLabels.Candidates(calendar);
+
+ labels.Should().Equal(
+ [
+ new CalendarLabel(calendar.CellLeft(0) + 2.0, firstDay, CalendarLabelKind.Month),
+ new CalendarLabel(calendar.CellLeft(4), new DateOnly(2026, 1, 26), CalendarLabelKind.Day),
+ new CalendarLabel(calendar.CellLeft(10) + 2.0, new DateOnly(2026, 2, 1), CalendarLabelKind.Month),
+ new CalendarLabel(calendar.CellLeft(11), new DateOnly(2026, 2, 2), CalendarLabelKind.Day),
+ new CalendarLabel(calendar.CellLeft(18), new DateOnly(2026, 2, 9), CalendarLabelKind.Day)
+ ],
+ "22 January 2026 is a Thursday, and 1 February a Sunday");
+ }
+
+ [Theory]
+ [InlineData(RowWidth)]
+ [InlineData(NarrowRowWidth)]
+ public void ASixMonthArchive_NamesOnlyItsMonths_AtAnyWidth(double rowWidth)
+ {
+ var firstDay = new DateOnly(2026, 6, 15);
+ var calendar = DayCalendar.Over(firstDay, firstDay.AddDays(182), rowWidth)!.Value;
+
+ var candidates = DayCalendarLabels.Candidates(calendar);
+ var fitted = DayCalendarLabels.Fitted(candidates, [.. candidates.Select(_ => MonthLabelWidth)], rowWidth);
+
+ candidates.Select(label => label.Day).Should().Equal(
+ firstDay, new(2026, 7, 1), new(2026, 8, 1), new(2026, 9, 1), new(2026, 10, 1), new(2026, 11, 1),
+ new(2026, 12, 1));
+ candidates.Should().OnlyContain(label => label.Kind == CalendarLabelKind.Month);
+ fitted.Should().NotBeEmpty().And.Contain(label => label.Index == 0, "the first cell's month always shows");
+ }
+
+ [Fact]
+ public void Fitted_DropsAMondayThatCollidesWithAMonth_WhereverItStands()
+ {
+ var firstDay = new DateOnly(2026, 1, 22);
+ var calendar = DayCalendar.Over(firstDay, firstDay.AddDays(20), NarrowRowWidth)!.Value;
+ var candidates = DayCalendarLabels.Candidates(calendar);
+ var widths = candidates
+ .Select(label => label.Kind == CalendarLabelKind.Month ? MonthLabelWidth : MondayLabelWidth)
+ .ToList();
+
+ var fitted = DayCalendarLabels.Fitted(candidates, widths, NarrowRowWidth);
+
+ calendar.Pitch.Should().Be(9.0);
+ fitted.Select(label => candidates[label.Index].Day).Should().Equal(
+ [firstDay, new DateOnly(2026, 1, 26), new DateOnly(2026, 2, 1), new DateOnly(2026, 2, 9)],
+ "the Monday of 2 February stands on February's label one cell before it");
+ }
+
+ [Fact]
+ public void Fitted_DropsALabelCloserThanFourPixelsToALabelKeptBeforeIt()
+ {
+ var fitted = DayCalendarLabels.Fitted(Mondays(0.0, 10.0, 24.0), [20.0, 20.0, 20.0], 100.0);
+
+ fitted.Should().Equal([new PlacedLabel(0, 0.0), new PlacedLabel(2, 24.0)], "10 starts inside the first's gap");
+ }
+
+ [Fact]
+ public void Fitted_EndsALabelThatWouldRunPastTheRow_AtTheRowsRightEnd()
+ {
+ var fitted = DayCalendarLabels.Fitted(Mondays(0.0, 90.0), [20.0, 20.0], 100.0);
+
+ fitted.Should().Equal([new PlacedLabel(0, 0.0), new PlacedLabel(1, 80.0)], "90 + 20 would end past 100");
+ }
+
+ [Fact]
+ public void Fitted_DropsAShiftedLabel_ThatTheShiftBringsTooClose()
+ {
+ var fitted = DayCalendarLabels.Fitted(Mondays(60.0, 95.0), [20.0, 20.0], 100.0);
+
+ fitted.Should().Equal([new PlacedLabel(0, 60.0)], "95 shifts to 80, inside the first label's gap");
+ }
+
+ [Fact]
+ public void Fitted_KeepsAMonth_OverAnEarlierMondayItWouldCollideWith()
+ {
+ CalendarLabel[] candidates =
+ [
+ new(0.0, new DateOnly(2026, 1, 22), CalendarLabelKind.Month),
+ new(40.0, new DateOnly(2026, 1, 26), CalendarLabelKind.Day),
+ new(60.0, new DateOnly(2026, 2, 1), CalendarLabelKind.Month)
+ ];
+
+ var fitted = DayCalendarLabels.Fitted(candidates, [30.0, 30.0, 30.0], 200.0);
+
+ fitted.Should().Equal([new PlacedLabel(0, 0.0), new PlacedLabel(2, 60.0)]);
+ }
+
+ [Fact]
+ public void Fitted_OnAOneDayCalendar_ShowsItsLabel_EndingAtTheRowsRightEnd()
+ {
+ var day = new DateOnly(2026, 11, 11);
+ var calendar = DayCalendar.Over(day, day, RowWidth)!.Value;
+ var candidates = DayCalendarLabels.Candidates(calendar);
+
+ var fitted = DayCalendarLabels.Fitted(candidates, [MonthLabelWidth], RowWidth);
+
+ candidates.Should().ContainSingle().Which.X.Should().Be(RowWidth - 17.0, "the only cell ends the row");
+ fitted.Should().Equal([new PlacedLabel(0, RowWidth - MonthLabelWidth)]);
+ }
+
+ [Fact]
+ public void Fitted_KeepsTheFirstCellsLabel_OverAMondayTooCloseToIt()
+ {
+ var sunday = new DateOnly(2026, 1, 4);
+ var calendar = DayCalendar.Over(sunday, sunday.AddDays(6), RowWidth)!.Value;
+ var candidates = DayCalendarLabels.Candidates(calendar);
+
+ var fitted = DayCalendarLabels.Fitted(candidates, [MonthLabelWidth, MondayLabelWidth], RowWidth);
+
+ candidates.Select(label => label.Kind).Should().Equal(CalendarLabelKind.Month, CalendarLabelKind.Day);
+ fitted.Should().Equal(
+ [new PlacedLabel(0, calendar.CellLeft(0) + 2.0)], "the Monday starts 20 px in, inside the first label");
+ }
+
+ private static List Mondays(params double[] lefts)
+ {
+ return [.. lefts.Select(x => new CalendarLabel(x, new DateOnly(2026, 1, 5), CalendarLabelKind.Day))];
+ }
+}
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarTests.cs
new file mode 100644
index 0000000..116fe95
--- /dev/null
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarTests.cs
@@ -0,0 +1,311 @@
+using AwesomeAssertions;
+
+using SemiPlot.Core.Data;
+using SemiPlot.Core.Trends;
+
+using Xunit;
+
+using static SemiPlot.Tests.Unit.Core.Trends.BerlinClock;
+
+namespace SemiPlot.Tests.Unit.Core.Trends;
+
+[Trait("Component", "Core")]
+[Trait("Area", "Data")]
+[Trait("Category", "Unit")]
+public sealed class DayCalendarTests
+{
+ // 1 100 px right of the 2 px outline inset at the left end.
+ private const double RowWidth = 1102.0;
+
+ private static readonly DayHours _officeHours = new(7, 17);
+
+ [Theory]
+ [InlineData(2, 20.0)]
+ [InlineData(21, 20.0)]
+ [InlineData(183, 6.0)]
+ public void Over_TakesTheWholePitchThatFits_CappedAtTwentyPixels(int dayCount, double pitch)
+ {
+ var calendar = Calendar(Day(1, 5), dayCount, RowWidth);
+
+ calendar.DayCount.Should().Be(dayCount);
+ calendar.Pitch.Should().Be(pitch, "two days and three weeks cap at 20 px, six months floor 1100 / 183");
+ calendar.Gap.Should().Be(1.0);
+ calendar.CellWidth.Should().Be(pitch - 1.0);
+ }
+
+ [Theory]
+ [InlineData(4.0, 1.0)]
+ [InlineData(3.0, 0.0)]
+ public void Gap_IsOnePixelFromAFourPixelPitch(double pitch, double gap)
+ {
+ var calendar = Calendar(Day(1, 5), 100, (100 * pitch) + 2.0);
+
+ calendar.Pitch.Should().Be(pitch);
+ calendar.Gap.Should().Be(gap);
+ calendar.CellWidth.Should().Be(pitch - gap);
+ }
+
+ [Fact]
+ public void Over_OfMoreDaysThanPixels_TakesAFractionalPitch_AndStillEndsAtTheRowsRightEnd()
+ {
+ var calendar = Calendar(Day(1, 5), 2200, RowWidth);
+
+ calendar.Pitch.Should().Be(0.5);
+ calendar.Gap.Should().Be(0.0);
+ calendar.CellWidth.Should().Be(1.0, "a cell is one pixel column");
+ (calendar.CellLeft(2199) + calendar.CellWidth).Should().Be(RowWidth);
+ calendar.CellLeft(0).Should().BeGreaterThanOrEqualTo(DayCalendar.OutlineStroke - 1.0);
+ }
+
+ [Fact]
+ public void Over_WithNoRoomRightOfTheInset_IsNull()
+ {
+ DayCalendar.Over(Day(1, 5), Day(1, 6), DayCalendar.OutlineStroke).Should().BeNull();
+ }
+
+ // Two days, three weeks and six months on one row: the last day ends at the row's right end and the cells
+ // fill leftwards, one pitch apart.
+ [Theory]
+ [InlineData(2, 1063.0, 19.0)]
+ [InlineData(21, 683.0, 19.0)]
+ [InlineData(183, 5.0, 5.0)]
+ public void TheCells_EndAtTheRowsRightEnd_AndFillLeftwards(int dayCount, double firstLeft, double cellWidth)
+ {
+ var calendar = Calendar(Day(1, 5), dayCount, RowWidth);
+ var last = dayCount - 1;
+
+ calendar.Right.Should().Be(RowWidth);
+ calendar.Cell(last).Should().Be(new TrackSpan(RowWidth - cellWidth, cellWidth), "today ends the row");
+ calendar.Cell(0).Should().Be(new TrackSpan(firstLeft, cellWidth));
+ (calendar.CellLeft(last) - calendar.CellLeft(last - 1)).Should().Be(calendar.Pitch);
+ calendar.CellLeft(0).Should().BeGreaterThanOrEqualTo(DayCalendar.OutlineStroke, "the outline keeps its inset");
+ }
+
+ [Theory]
+ [InlineData(1102.0, 7)]
+ [InlineData(1082.5, 7)]
+ [InlineData(1082.0, 6)]
+ [InlineData(962.0, 0)]
+ [InlineData(942.5, 0)]
+ public void DayAt_IsThePitchUnderX_ItsLeadingGapIncluded(double x, int dayIndex)
+ {
+ var calendar = Calendar(Day(1, 5), 8, RowWidth);
+
+ calendar.DayAt(x).Should().Be(Day(1, 5).AddDays(dayIndex));
+ }
+
+ [Theory]
+ [InlineData(942.0)]
+ [InlineData(100.0)]
+ [InlineData(1102.5)]
+ public void DayAt_LeftOfTheFirstCellOrRightOfTheLast_IsNull(double x)
+ {
+ Calendar(Day(1, 5), 8, RowWidth).DayAt(x).Should().BeNull();
+ }
+
+ [Theory]
+ [InlineData(7, 17, DayCoverage.Full)]
+ [InlineData(7, 12, DayCoverage.Medium)]
+ [InlineData(9, 16, DayCoverage.Medium)]
+ [InlineData(7, 9, DayCoverage.Low)]
+ [InlineData(5, 8, DayCoverage.Low)]
+ [InlineData(18, 20, DayCoverage.Low)]
+ public void ACell_IsGradedByTheShareOfTheWorkingHoursItsSpanCovers(
+ int firstHour,
+ int lastHour,
+ DayCoverage expected)
+ {
+ var span = new ArchiveDaySpan(Day(1, 7), Berlin(1, 7, firstHour), Berlin(1, 7, lastHour));
+
+ GradeOf(span, _officeHours).Should().Be(expected);
+ }
+
+ [Theory]
+ [InlineData(0, 23, DayCoverage.Full)]
+ [InlineData(0, 12, DayCoverage.Medium)]
+ [InlineData(8, 12, DayCoverage.Low)]
+ public void ACell_OnARoundTheClockArchive_IsGradedOverTheWholeDay(int firstHour, int lastHour, DayCoverage expected)
+ {
+ var span = new ArchiveDaySpan(Day(1, 7), Berlin(1, 7, firstHour), Berlin(1, 7, lastHour));
+
+ GradeOf(span, DayHours.FullDay).Should().Be(expected);
+ }
+
+ [Fact]
+ public void TodaysCell_IsGradedByItsSpanSoFar()
+ {
+ var today = Day(1, 7);
+ var early = new ArchiveDaySpan(today, Berlin(1, 7, 7), Berlin(1, 7, 8).AddMinutes(11));
+ var later = early with { LastUtc = Berlin(1, 7, 10).AddMinutes(11) };
+
+ GradeOf(early, _officeHours).Should().Be(DayCoverage.Low, "1 h 11 min of 10 h");
+ GradeOf(later, _officeHours).Should().Be(DayCoverage.Medium, "3 h 11 min of 10 h");
+ }
+
+ [Fact]
+ public void Cells_GradeEachSpanOnTheCalendar_AndSkipDaysOffIt()
+ {
+ var calendar = Calendar(Day(1, 5), 3, RowWidth);
+ ArchiveDaySpan[] spans =
+ [
+ new(Day(1, 4), Berlin(1, 4, 7), Berlin(1, 4, 17)),
+ new(Day(1, 5), Berlin(1, 5, 7), Berlin(1, 5, 17)),
+ new(Day(1, 7), Berlin(1, 7, 7), Berlin(1, 7, 9)),
+ new(Day(1, 8), Berlin(1, 8, 7), Berlin(1, 8, 17))
+ ];
+
+ calendar.Cells(spans, _officeHours, BerlinZone).Should().Equal(
+ new CalendarCell(1043.0, 19.0, DayCoverage.Full),
+ new CalendarCell(1083.0, 19.0, DayCoverage.Low));
+ }
+
+ // 2 200 days on 1 100 px: days 2k and 2k + 1 share a pixel column. Every even day is full, every odd one
+ // short, and day 0 too, so the first column holds two short days.
+ [Fact]
+ public void Cells_OfDaysSharingAPixelColumn_AreOneCellOfTheirHighestGrade_AndNeverOverlap()
+ {
+ var calendar = Calendar(Day(1, 5), 2200, RowWidth);
+ var spans = Enumerable.Range(0, 2200)
+ .Select(index => SpanOn(Day(1, 5).AddDays(index), isFull: index % 2 == 0 && index > 0));
+
+ var cells = calendar.Cells([.. spans], _officeHours, BerlinZone);
+
+ cells.Should().HaveCount(1100, "a pixel column draws one cell");
+ cells.Zip(cells.Skip(1)).Should().OnlyContain(pair => pair.First.Left + pair.First.Width <= pair.Second.Left);
+ cells[0].Coverage.Should().Be(DayCoverage.Low, "two short days stay short, never a darker mix");
+ cells.Skip(1).Should().OnlyContain(cell => cell.Coverage == DayCoverage.Full, "a column takes its fuller day");
+ }
+
+ [Fact]
+ public void PageOutline_OfADay_RingsItsCellWithTheStroke()
+ {
+ var calendar = Calendar(Day(1, 5), 21, RowWidth);
+
+ calendar.PageOutline(Page(MinimapPageUnit.Day, Day(1, 8))).Should().Be(new TrackSpan(741.0, 23.0));
+ }
+
+ [Fact]
+ public void PageOutline_OfTheLastDay_DrawsItsStrokePastTheRowsRightEnd()
+ {
+ var calendar = Calendar(Day(1, 5), 21, RowWidth);
+
+ calendar.PageOutline(Page(MinimapPageUnit.Day, Day(1, 25))).Should().Be(
+ new TrackSpan(RowWidth - 21.0, 23.0), "the stroke runs 2 px into the gap before the step column");
+ }
+
+ [Fact]
+ public void PageOutline_OfAWeek_RingsItsSevenCells()
+ {
+ var calendar = Calendar(Day(1, 5), 21, RowWidth);
+
+ calendar.PageOutline(Page(MinimapPageUnit.Week, Day(1, 12))).Should().Be(
+ new TrackSpan(calendar.CellLeft(7) - 2.0, (6 * 20.0) + 19.0 + 4.0));
+ }
+
+ [Fact]
+ public void PageOutline_OfAWeekRunningPastTheLastDay_StopsAtItsCell()
+ {
+ var calendar = Calendar(Day(1, 5), 10, RowWidth);
+
+ calendar.PageOutline(Page(MinimapPageUnit.Week, Day(1, 12))).Should().Be(
+ new TrackSpan(calendar.CellLeft(7) - 2.0, (2 * 20.0) + 19.0 + 4.0), "the last day is Wednesday");
+ }
+
+ [Theory]
+ [InlineData(1, 1)]
+ [InlineData(1, 19)]
+ public void PageOutline_OfAPageOffTheCalendar_IsNull(int month, int day)
+ {
+ Calendar(Day(1, 5), 10, RowWidth).PageOutline(Page(MinimapPageUnit.Day, Day(month, day))).Should().BeNull();
+ }
+
+ [Fact]
+ public void MarkerTicks_AreOnePerDayWithAMarker_InTheArchiveWallClock_Ascending()
+ {
+ var calendar = Calendar(Day(1, 5), 7, RowWidth);
+ DateTime[] markers =
+ [
+ Berlin(1, 9, 12),
+ new(2026, 1, 5, 23, 30, 0, DateTimeKind.Utc),
+ Berlin(1, 6, 9),
+ Berlin(1, 20, 9)
+ ];
+
+ calendar.MarkerTicks(markers, BerlinZone).Should().Equal(calendar.Cell(1), calendar.Cell(4));
+ }
+
+ [Fact]
+ public void MarkerCountsByDay_CountTheMarkersOfEachArchiveWallClockDay()
+ {
+ DateTime[] markers =
+ [
+ Berlin(1, 9, 12),
+ new(2026, 1, 5, 23, 30, 0, DateTimeKind.Utc),
+ Berlin(1, 6, 9),
+ Berlin(1, 9, 15)
+ ];
+
+ DayCalendar.MarkerCountsByDay(markers, BerlinZone).Should().BeEquivalentTo(
+ new Dictionary { [Day(1, 6)] = 2, [Day(1, 9)] = 2 },
+ "23:30 UTC on the 5th is half past midnight on the 6th in Berlin");
+ }
+
+ [Theory]
+ [InlineData(42, true)]
+ [InlineData(43, false)]
+ public void TheMondays_AreNamedOnAnArchiveOfSixWeeksOrLess_AtAnyWidth(int dayCount, bool namesMondays)
+ {
+ Calendar(Day(1, 5), dayCount, RowWidth).ShowsMondayLabels.Should().Be(namesMondays);
+ Calendar(Day(1, 5), dayCount, 200.0).ShowsMondayLabels.Should().Be(namesMondays, "the width never decides");
+ }
+
+ [Fact]
+ public void MonthSeparators_StandInTheGapBeforeEachMonthStart_WhileOnlyTheMonthsAreNamed()
+ {
+ var calendar = Calendar(new DateOnly(2026, 6, 1), 183, RowWidth);
+
+ calendar.ShowsMondayLabels.Should().BeFalse();
+ calendar.MonthSeparators().Should().Equal(
+ new[] { 30, 61, 92, 122, 153 }.Select(index => calendar.CellLeft(index) - 1.0));
+ }
+
+ [Fact]
+ public void MonthSeparators_AreNone_WhileTheMondaysAreNamed()
+ {
+ var calendar = Calendar(new DateOnly(2026, 1, 20), 21, RowWidth);
+
+ calendar.ShowsMondayLabels.Should().BeTrue();
+ calendar.MonthSeparators().Should().BeEmpty();
+ }
+
+ private static ArchiveDaySpan SpanOn(DateOnly day, bool isFull)
+ {
+ var midnight = ArchiveClock.Midnight(day);
+
+ return new ArchiveDaySpan(
+ day,
+ ArchiveClock.ToUtc(midnight.AddHours(7), BerlinZone),
+ ArchiveClock.ToUtc(midnight.AddHours(isFull ? 17 : 8), BerlinZone));
+ }
+
+ private static DayCoverage GradeOf(ArchiveDaySpan span, DayHours hours)
+ {
+ return Calendar(span.Day, 1, RowWidth).Cells([span], hours, BerlinZone).Single().Coverage;
+ }
+
+ private static DayCalendar Calendar(DateOnly firstDay, int dayCount, double width)
+ {
+ return DayCalendar.Over(firstDay, firstDay.AddDays(dayCount - 1), width)
+ ?? throw new InvalidOperationException("The width leaves room for the cells.");
+ }
+
+ private static MinimapPage Page(MinimapPageUnit unit, DateOnly firstDay)
+ {
+ return new MinimapPage(unit, firstDay, DayHours.FullDay, default, default);
+ }
+
+ private static DateOnly Day(int month, int day)
+ {
+ return new DateOnly(2026, month, day);
+ }
+}
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerNavigationTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerNavigationTests.cs
new file mode 100644
index 0000000..39c953e
--- /dev/null
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerNavigationTests.cs
@@ -0,0 +1,267 @@
+using AwesomeAssertions;
+
+using SemiPlot.Core.Data;
+using SemiPlot.Core.Trends;
+
+using Xunit;
+
+namespace SemiPlot.Tests.Unit.Core.Trends;
+
+[Trait("Component", "Core")]
+[Trait("Area", "Chart")]
+[Trait("Category", "Unit")]
+public sealed class MarkerNavigationTests
+{
+ private static readonly DateTime _origin = new(2026, 10, 15, 8, 0, 0, DateTimeKind.Utc);
+
+ private long _nextId = 1;
+
+ [Fact]
+ public void Runs_PairAStartThroughItsEnd_PastAnOperatorMarker()
+ {
+ var markers = Markers(
+ Marker(0, MarkerKind.RecipeStart),
+ Marker(5, MarkerKind.User),
+ Marker(20, MarkerKind.RecipeEnd));
+
+ var runs = MarkerNavigation.Runs(markers, At(60));
+
+ runs.Should().Equal(new RecipeRun(At(0), At(20), IsInterrupted: false));
+ }
+
+ [Fact]
+ public void Runs_TakeTheStartMarkersLabel_AndNoneForABlankOne()
+ {
+ var markers = Markers(
+ Marker(0, MarkerKind.RecipeStart) with { Label = "Etch_Si.csv" },
+ Marker(20, MarkerKind.RecipeEnd) with { Label = "Closing.csv" },
+ Marker(30, MarkerKind.RecipeStart) with { Label = " " },
+ Marker(40, MarkerKind.RecipeEnd));
+
+ var runs = MarkerNavigation.Runs(markers, At(60));
+
+ runs.Select(run => run.Label).Should().Equal("Etch_Si.csv", null);
+ }
+
+ [Fact]
+ public void Runs_PairAStartThroughItsInterruption_AsOneInterruptedRun()
+ {
+ var markers = Markers(Marker(0, MarkerKind.RecipeStart), Marker(12, MarkerKind.RecipeInterrupted));
+
+ var runs = MarkerNavigation.Runs(markers, At(60));
+
+ runs.Should().Equal(new RecipeRun(At(0), At(12), IsInterrupted: true));
+ }
+
+ [Fact]
+ public void Runs_RunAStartWithNoClose_ToTheNextStart()
+ {
+ var markers = Markers(
+ Marker(0, MarkerKind.RecipeStart),
+ Marker(30, MarkerKind.RecipeStart),
+ Marker(45, MarkerKind.RecipeEnd));
+
+ var runs = MarkerNavigation.Runs(markers, At(60));
+
+ runs.Should().Equal(
+ new RecipeRun(At(0), At(30), IsInterrupted: false),
+ new RecipeRun(At(30), At(45), IsInterrupted: false));
+ }
+
+ [Fact]
+ public void Runs_RunTheLastStartWithNoClose_ToTheNewestSample()
+ {
+ var markers = Markers(
+ Marker(0, MarkerKind.RecipeStart),
+ Marker(10, MarkerKind.RecipeEnd),
+ Marker(30, MarkerKind.RecipeStart));
+
+ var runs = MarkerNavigation.Runs(markers, At(52));
+
+ runs.Should().Equal(
+ new RecipeRun(At(0), At(10), IsInterrupted: false),
+ new RecipeRun(At(30), At(52), IsInterrupted: false));
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData(30)]
+ [InlineData(25)]
+ public void Runs_LeaveOutAnOpenLastStart_WithNoNewestSampleAfterIt(int? newestSampleMinute)
+ {
+ var markers = Markers(Marker(30, MarkerKind.RecipeStart));
+ DateTime? newestSampleUtc = newestSampleMinute is { } minute ? At(minute) : null;
+
+ var runs = MarkerNavigation.Runs(markers, newestSampleUtc);
+
+ runs.Should().BeEmpty();
+ }
+
+ [Fact]
+ public void Runs_SkipACloseWithNoStart()
+ {
+ var markers = Markers(
+ Marker(0, MarkerKind.RecipeEnd),
+ Marker(10, MarkerKind.RecipeStart),
+ Marker(20, MarkerKind.RecipeEnd),
+ Marker(25, MarkerKind.RecipeInterrupted),
+ Marker(40, MarkerKind.RecipeStart),
+ Marker(50, MarkerKind.RecipeEnd));
+
+ var runs = MarkerNavigation.Runs(markers, At(60));
+
+ runs.Should().Equal(
+ new RecipeRun(At(10), At(20), IsInterrupted: false),
+ new RecipeRun(At(40), At(50), IsInterrupted: false));
+ }
+
+ [Fact]
+ public void Runs_SkipARunOfNoLength()
+ {
+ var markers = Markers(
+ Marker(10, MarkerKind.RecipeStart),
+ Marker(10, MarkerKind.RecipeEnd),
+ Marker(20, MarkerKind.RecipeStart),
+ Marker(30, MarkerKind.RecipeEnd));
+
+ var runs = MarkerNavigation.Runs(markers, At(60));
+
+ runs.Should().Equal(new RecipeRun(At(20), At(30), IsInterrupted: false));
+ }
+
+ [Fact]
+ public void Runs_OfNoRecipeMarker_AreEmpty()
+ {
+ var markers = Markers(Marker(10, MarkerKind.User), Marker(20, MarkerKind.User));
+
+ var runs = MarkerNavigation.Runs(markers, At(60));
+
+ runs.Should().BeEmpty();
+ }
+
+ [Fact]
+ public void RunSteps_FromAWindowCentreBetweenRuns_TakeTheRunsOnEitherSide()
+ {
+ var runs = ThreeRuns();
+
+ var next = MarkerNavigation.NextRun(runs, At(25));
+ var previous = MarkerNavigation.PreviousRun(runs, At(25));
+
+ next.Should().Be(runs[1]);
+ previous.Should().Be(runs[0]);
+ }
+
+ [Fact]
+ public void RunSteps_FromTheCentreOfAFramedRun_TakeItsNeighbours_AndNoneAtEitherEnd()
+ {
+ var runs = ThreeRuns();
+
+ var forward = new List();
+ var backward = new List();
+ foreach (var run in runs)
+ {
+ var centre = Centre(MarkerNavigation.Frame(run));
+ forward.Add(MarkerNavigation.NextRun(runs, centre));
+ backward.Add(MarkerNavigation.PreviousRun(runs, centre));
+ }
+
+ forward.Should().Equal(runs[1], runs[2], null);
+ backward.Should().Equal(null, runs[0], runs[1]);
+ }
+
+ [Fact]
+ public void RunSteps_FromACentreInsideARun_PassOverThatRun()
+ {
+ var runs = ThreeRuns();
+
+ var next = MarkerNavigation.NextRun(runs, At(32));
+ var previous = MarkerNavigation.PreviousRun(runs, At(32));
+
+ next.Should().Be(runs[2]);
+ previous.Should().Be(runs[0]);
+ }
+
+ [Fact]
+ public void RunSteps_PastTheOuterRuns_FindNone()
+ {
+ var runs = ThreeRuns();
+
+ MarkerNavigation.NextRun(runs, At(75)).Should().BeNull();
+ MarkerNavigation.PreviousRun(runs, At(-5)).Should().BeNull();
+ MarkerNavigation.NextRun([], At(0)).Should().BeNull();
+ MarkerNavigation.PreviousRun([], At(0)).Should().BeNull();
+ }
+
+ [Fact]
+ public void LatestRun_IsTheNewestRun_OrNoneWithoutRuns()
+ {
+ var runs = ThreeRuns();
+
+ MarkerNavigation.LatestRun(runs).Should().Be(runs[2]);
+ MarkerNavigation.LatestRun([]).Should().BeNull();
+ }
+
+ [Fact]
+ public void Frame_AddsATenthOfTheRunOnEachSide()
+ {
+ var run = new RecipeRun(At(10), At(30), IsInterrupted: false);
+
+ var (fromUtc, toUtc) = MarkerNavigation.Frame(run);
+
+ fromUtc.Should().Be(At(8));
+ toUtc.Should().Be(At(32));
+ }
+
+ [Fact]
+ public void MarkerSteps_FromACentreOnAMarker_MoveOffIt()
+ {
+ var markers = Markers(Marker(0, MarkerKind.User), Marker(10, MarkerKind.User), Marker(20, MarkerKind.User));
+
+ var next = MarkerNavigation.NextMarker(markers, At(10));
+ var previous = MarkerNavigation.PreviousMarker(markers, At(10));
+
+ next.Should().Be(markers[2]);
+ previous.Should().Be(markers[0]);
+ }
+
+ [Fact]
+ public void MarkerSteps_PastTheOuterMarkers_FindNone()
+ {
+ var markers = Markers(Marker(10, MarkerKind.User));
+
+ MarkerNavigation.NextMarker(markers, At(10)).Should().BeNull();
+ MarkerNavigation.PreviousMarker(markers, At(10)).Should().BeNull();
+ MarkerNavigation.NextMarker([], At(0)).Should().BeNull();
+ MarkerNavigation.PreviousMarker([], At(0)).Should().BeNull();
+ }
+
+ private static IReadOnlyList ThreeRuns()
+ {
+ return
+ [
+ new RecipeRun(At(0), At(20), IsInterrupted: false),
+ new RecipeRun(At(30), At(40), IsInterrupted: true),
+ new RecipeRun(At(50), At(70), IsInterrupted: false)
+ ];
+ }
+
+ private static IReadOnlyList Markers(params StoredMarker[] markers)
+ {
+ return markers;
+ }
+
+ private StoredMarker Marker(int minute, MarkerKind kind)
+ {
+ return new StoredMarker(_nextId++, At(minute), null, kind, IsLocked: kind != MarkerKind.User);
+ }
+
+ private static DateTime At(int minute)
+ {
+ return _origin.AddMinutes(minute);
+ }
+
+ private static DateTime Centre((DateTime FromUtc, DateTime ToUtc) window)
+ {
+ return window.FromUtc + ((window.ToUtc - window.FromUtc) / 2);
+ }
+}
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs
index 29ecf28..2534ad4 100644
--- a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs
@@ -302,6 +302,25 @@ public void WhileRecipeMarkersAreHidden_APlaceOfAUserMarker_MovesItAmongTheShown
set.All.Should().Equal(recipeStart, _etchEnd, moved);
}
+ [Fact]
+ public void OperatorMarkers_HoldTheUserKindOnly_ThroughApplyPlaceAndRemove_WhateverTheRecipeToggle()
+ {
+ var recipeStart = new StoredMarker(4, _origin.AddMinutes(5), "Etch.csv", MarkerKind.RecipeStart, true);
+ var set = SetOf(_etchStart, recipeStart, _etchEnd);
+ set.OperatorMarkers.Should().Equal(_etchStart, _etchEnd);
+ var moved = _etchStart with { TimeUtc = _origin.AddMinutes(30) };
+
+ set.Place(moved);
+ set.Place(recipeStart with { TimeUtc = _origin.AddMinutes(40) });
+ set.OperatorMarkers.Should().Equal(_etchEnd, moved);
+
+ set.ToggleRecipeMarkers();
+ set.Remove(_etchEnd.Id);
+
+ set.OperatorMarkers.Should().Equal(moved);
+ set.ShownMarkers.Should().BeSameAs(set.OperatorMarkers, "hidden recipe markers leave the operator's shown");
+ }
+
[Fact]
public void ShownMarkers_ReturnsTheSameArrayBetweenTwoChanges()
{
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapGeometryTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapGeometryTests.cs
index 514df28..1a356cf 100644
--- a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapGeometryTests.cs
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapGeometryTests.cs
@@ -12,93 +12,11 @@ namespace SemiPlot.Tests.Unit.Core.Trends;
public sealed class MinimapGeometryTests
{
private const double StripWidth = 900.0;
- private const double MinimumMarkerWidth = 6.0;
private const double BandWidth = 400.0;
private const double BandHeight = 30.0;
- private const double LabelWidth = 60.0;
- private const double CoverDistance = 6.0;
private static readonly DateTime _first = new(2026, 6, 10, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime _last = new(2026, 6, 20, 0, 0, 0, DateTimeKind.Utc);
- [Fact]
- public void WindowFraction_MidWindow_MapsToCenteredRectangle()
- {
- var from = new DateTime(2026, 6, 12, 0, 0, 0, DateTimeKind.Utc);
- var to = new DateTime(2026, 6, 16, 0, 0, 0, DateTimeKind.Utc);
-
- var (start, width) = MinimapGeometry.WindowFraction(_first, _last, from, to);
-
- start.Should().BeApproximately(0.2, 1e-9);
- width.Should().BeApproximately(0.4, 1e-9);
- }
-
- [Fact]
- public void WindowFraction_WindowEqualsExtent_FillsStrip()
- {
- var (start, width) = MinimapGeometry.WindowFraction(_first, _last, _first, _last);
-
- start.Should().Be(0.0);
- width.Should().BeApproximately(1.0, 1e-9);
- }
-
- [Fact]
- public void WindowFraction_WindowReachesBeyondExtent_ClampsToStrip()
- {
- var from = _first - TimeSpan.FromDays(5.0);
- var to = _last + TimeSpan.FromDays(5.0);
-
- var (start, width) = MinimapGeometry.WindowFraction(_first, _last, from, to);
-
- start.Should().Be(0.0);
- width.Should().Be(1.0);
- }
-
- [Fact]
- public void WindowFraction_ZeroSpanExtent_ReturnsFullStrip()
- {
- var (start, width) = MinimapGeometry.WindowFraction(_first, _first, _first, _first);
-
- start.Should().Be(0.0);
- width.Should().Be(1.0);
- }
-
- [Theory]
- [InlineData(1.0)]
- [InlineData(0.999)]
- public void MarkerSpan_AtTheRightEnd_StaysInsideTheStrip(double startFraction)
- {
- var (left, width) = MinimapGeometry.MarkerSpan(startFraction, 0.0, StripWidth, MinimumMarkerWidth);
-
- width.Should().Be(MinimumMarkerWidth);
- (left + width).Should().BeLessThanOrEqualTo(StripWidth);
- }
-
- [Fact]
- public void MarkerSpan_WindowWiderThanTheStrip_FillsItExactly()
- {
- var (left, width) = MinimapGeometry.MarkerSpan(-0.5, 2.0, StripWidth, MinimumMarkerWidth);
-
- left.Should().Be(0.0);
- width.Should().Be(StripWidth);
- }
-
- [Fact]
- public void MarkerSpan_ZeroStripWidth_IsEmpty()
- {
- var span = MinimapGeometry.MarkerSpan(0.5, 0.1, 0.0, MinimumMarkerWidth);
-
- span.Should().Be((0.0, 0.0));
- }
-
- [Fact]
- public void MarkerSpan_WindowAtTheLeftEdge_KeepsLeftAtZero()
- {
- var (left, width) = MinimapGeometry.MarkerSpan(0.0, 0.001, StripWidth, MinimumMarkerWidth);
-
- left.Should().Be(0.0);
- width.Should().Be(MinimumMarkerWidth);
- }
-
[Theory]
[InlineData(100.0, 100.0)]
[InlineData(-5.0, 0.0)]
@@ -114,42 +32,6 @@ public void SpanLeftWithin_ASpanWiderThanTheLimit_StartsAtItsLeftEdge()
MinimapGeometry.SpanLeftWithin(10.0, StripWidth + 50.0, StripWidth).Should().Be(0.0);
}
- [Fact]
- public void PlaceHoverTime_InTheMiddle_CentresOnThePointerAndCoversNeitherEndLabel()
- {
- var placement = MinimapGeometry.PlaceHoverTime(
- 450.0, LabelWidth, StripWidth, LabelWidth, LabelWidth, CoverDistance);
-
- placement.Should().Be(
- new HoverTimePlacement(450.0 - (LabelWidth / 2.0), CoversFirst: false, CoversLast: false));
- }
-
- [Theory]
- [InlineData(0.0, 0.0)]
- [InlineData(StripWidth, StripWidth - LabelWidth)]
- public void PlaceHoverTime_AtAnEnd_StaysInTheRowAndCoversThatEndLabelOnly(double pointerX, double expectedLeft)
- {
- var placement = MinimapGeometry.PlaceHoverTime(
- pointerX, LabelWidth, StripWidth, LabelWidth, LabelWidth, CoverDistance);
-
- var atLeftEnd = pointerX == 0.0;
- placement.Should().Be(new HoverTimePlacement(expectedLeft, CoversFirst: atLeftEnd, CoversLast: !atLeftEnd));
- }
-
- [Theory]
- [InlineData(CoverDistance - 3.0, true)]
- [InlineData(CoverDistance + 1.0, false)]
- public void PlaceHoverTime_ATimeWithinTheCoverDistanceOfAnEndLabel_CoversIt(double distance, bool covers)
- {
- var nearFirst = LabelWidth + distance + (LabelWidth / 2.0);
- var nearLast = StripWidth - LabelWidth - distance - (LabelWidth / 2.0);
-
- MinimapGeometry.PlaceHoverTime(nearFirst, LabelWidth, StripWidth, LabelWidth, LabelWidth, CoverDistance)
- .CoversFirst.Should().Be(covers);
- MinimapGeometry.PlaceHoverTime(nearLast, LabelWidth, StripWidth, LabelWidth, LabelWidth, CoverDistance)
- .CoversLast.Should().Be(covers);
- }
-
[Fact]
public void RightBound_IsTheLaterOfTheExtentAndTheNewestSample()
{
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapPageTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapPageTests.cs
new file mode 100644
index 0000000..570fa38
--- /dev/null
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapPageTests.cs
@@ -0,0 +1,556 @@
+using AwesomeAssertions;
+
+using SemiPlot.Core.Data;
+using SemiPlot.Core.Trends;
+
+using Xunit;
+
+namespace SemiPlot.Tests.Unit.Core.Trends;
+
+[Trait("Component", "Core")]
+[Trait("Area", "Data")]
+[Trait("Category", "Unit")]
+public sealed class MinimapPageTests
+{
+ private static readonly TimeZoneInfo _berlin = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
+ private static readonly DayHours _officeHours = new(7, 17);
+
+ // Weekdays of two weeks, a nine-day gap from Saturday 17 to Sunday 25 January, then a third week.
+ private static readonly IReadOnlyList _weeksWithMaintenance =
+ [
+ .. Weekdays(Day(1, 5), Day(1, 16)),
+ .. Weekdays(Day(1, 26), Day(1, 30))
+ ];
+
+ [Fact]
+ public void WorkingHours_ArePercentilesOfFirstAndLastSamples_RoundedOutToWholeHours()
+ {
+ // Sorted, the second-earliest first sample is 06:40 and the second-latest last sample 17:30, the
+ // nearest ranks of P5 and P95 over 22 days; the minimum, the maximum and the median all differ.
+ var spans = Weekdays(Day(1, 7), Day(2, 2), first: (7, 20), last: (16, 40))
+ .Append(Span(Day(1, 5), (6, 40), (16, 40)))
+ .Append(Span(Day(1, 6), (7, 20), (17, 30)))
+ .Append(Span(Day(1, 17), (2, 10), (23, 30)))
+ .OrderBy(span => span.Day)
+ .ToList();
+
+ var hours = MinimapPage.WorkingHours(spans, _berlin);
+
+ spans.Should().HaveCount(22);
+ hours.Should().Be(new DayHours(6, 18));
+ }
+
+ [Fact]
+ public void WorkingHours_KeepAnExactHour()
+ {
+ var spans = Weekdays(Day(1, 5), Day(2, 2), first: (7, 0), last: (17, 0));
+
+ var hours = MinimapPage.WorkingHours(spans, _berlin);
+
+ hours.Should().Be(new DayHours(7, 17));
+ }
+
+ [Fact]
+ public void WorkingHours_OfAnArchiveRunningAroundTheClock_AreTheWholeDay()
+ {
+ var spans = new List { Span(Day(1, 1), (13, 0), (23, 59)) };
+ for (var day = 2; day < 30; day++)
+ {
+ spans.Add(new ArchiveDaySpan(
+ Day(1, day),
+ At(1, day, 0, 0) + TimeSpan.FromSeconds(5),
+ At(1, day, 23, 59) + TimeSpan.FromSeconds(55)));
+ }
+
+ spans.Add(Span(Day(1, 30), (0, 0), (10, 0)));
+
+ var hours = MinimapPage.WorkingHours(spans, _berlin);
+
+ spans[1].FirstUtc.Day.Should().Be(1, "the first sample after Berlin's midnight falls on the previous UTC day");
+ hours.Should().Be(DayHours.FullDay);
+ }
+
+ [Fact]
+ public void WorkingHours_WithoutSpans_AreTheWholeDay()
+ {
+ MinimapPage.WorkingHours([], _berlin).Should().Be(new DayHours(0, 24));
+ }
+
+ [Fact]
+ public void WorkingHours_OfOneDay_AreThatDayRoundedOut()
+ {
+ var hours = MinimapPage.WorkingHours([Span(Day(1, 7), (9, 30), (11, 10))], _berlin);
+
+ hours.Should().Be(new DayHours(9, 12));
+ }
+
+ [Fact]
+ public void Snap_ADay_IsTheWorkingHoursOfThatDay()
+ {
+ var page = MinimapPage.Snap(MinimapPageUnit.Day, At(1, 7, 12, 0), _officeHours, _weeksWithMaintenance, _berlin);
+
+ page.Should().Be(
+ new MinimapPage(MinimapPageUnit.Day, Day(1, 7), _officeHours, At(1, 7, 7, 0), At(1, 7, 17, 0)));
+ }
+
+ [Fact]
+ public void Snap_ADayWithSamplesOutsideTheHours_WidensItsOwnPageInWholeHours()
+ {
+ var spans = new[] { Span(Day(1, 16), (7, 12), (16, 48)), Span(Day(1, 17), (2, 10), (23, 30)) };
+
+ var widened = MinimapPage.Snap(MinimapPageUnit.Day, At(1, 17, 12, 0), _officeHours, spans, _berlin);
+ var neighbour = MinimapPage.Snap(MinimapPageUnit.Day, At(1, 16, 12, 0), _officeHours, spans, _berlin);
+
+ widened.FromUtc.Should().Be(At(1, 17, 2, 0));
+ widened.ToUtc.Should().Be(At(1, 18, 0, 0));
+ widened.Hours.Should().Be(_officeHours);
+ neighbour.FromUtc.Should().Be(At(1, 16, 7, 0));
+ neighbour.ToUtc.Should().Be(At(1, 16, 17, 0));
+ }
+
+ [Fact]
+ public void Snap_ADayWithoutSpan_IsThePlainHours()
+ {
+ var page = MinimapPage.Snap(MinimapPageUnit.Day, At(1, 10, 3, 0), _officeHours, _weeksWithMaintenance, _berlin);
+
+ page.FirstDay.Should().Be(Day(1, 10));
+ page.FromUtc.Should().Be(At(1, 10, 7, 0));
+ page.ToUtc.Should().Be(At(1, 10, 17, 0));
+ }
+
+ [Fact]
+ public void Snap_TakesTheArchiveWallClockDay_NotTheUtcDay()
+ {
+ var halfPastMidnightInBerlin = new DateTime(2026, 1, 6, 23, 30, 0, DateTimeKind.Utc);
+
+ var page = MinimapPage.Snap(
+ MinimapPageUnit.Day, halfPastMidnightInBerlin, _officeHours, _weeksWithMaintenance, _berlin);
+
+ page.FirstDay.Should().Be(Day(1, 7));
+ }
+
+ [Theory]
+ [InlineData(5)]
+ [InlineData(8)]
+ [InlineData(11)]
+ public void Snap_AWeek_RunsFromMondayToTheNextMonday(int dayOfJanuary)
+ {
+ var page = MinimapPage.Snap(
+ MinimapPageUnit.Week, At(1, dayOfJanuary, 12, 0), _officeHours, _weeksWithMaintenance, _berlin);
+
+ page.FirstDay.Should().Be(Day(1, 5));
+ page.EndDay.Should().Be(Day(1, 12));
+ page.FromUtc.Should().Be(At(1, 5, 0, 0));
+ page.ToUtc.Should().Be(At(1, 12, 0, 0));
+ }
+
+ [Fact]
+ public void Snap_AWeekOverTheAutumnChange_RunsMondayToMondayInWallClock()
+ {
+ var page = MinimapPage.Snap(MinimapPageUnit.Week, At(10, 22, 12, 0), _officeHours, [], _berlin);
+
+ page.FromUtc.Should().Be(At(10, 19, 0, 0));
+ page.ToUtc.Should().Be(At(10, 26, 0, 0));
+ (page.ToUtc - page.FromUtc).Should().Be(TimeSpan.FromHours(169));
+ }
+
+ [Fact]
+ public void Step_NextFromFriday_SkipsTheWeekend()
+ {
+ var friday = DayPage(1, 9);
+
+ var next = MinimapPage.Step(friday, PageDirection.Next, _weeksWithMaintenance, _berlin);
+
+ next.Should().Be(DayPage(1, 12));
+ }
+
+ [Fact]
+ public void Step_PreviousFromMonday_SkipsTheWeekend()
+ {
+ var previous = MinimapPage.Step(DayPage(1, 12), PageDirection.Previous, _weeksWithMaintenance, _berlin);
+
+ previous.Should().Be(DayPage(1, 9));
+ }
+
+ [Fact]
+ public void Step_SkipsAMaintenanceWeek_InBothDirections()
+ {
+ var next = MinimapPage.Step(DayPage(1, 16), PageDirection.Next, _weeksWithMaintenance, _berlin);
+ var previous = MinimapPage.Step(DayPage(1, 26), PageDirection.Previous, _weeksWithMaintenance, _berlin);
+
+ (next?.FirstDay).Should().Be(Day(1, 26));
+ (previous?.FirstDay).Should().Be(Day(1, 16));
+ }
+
+ [Fact]
+ public void Step_PastEitherEndOfTheArchive_ReturnsNone()
+ {
+ MinimapPage.Step(DayPage(1, 5), PageDirection.Previous, _weeksWithMaintenance, _berlin).Should().BeNull();
+ MinimapPage.Step(DayPage(1, 30), PageDirection.Next, _weeksWithMaintenance, _berlin).Should().BeNull();
+ }
+
+ [Fact]
+ public void Step_FromADayWithoutSpan_GoesToTheNearestDaysWithSpans()
+ {
+ var saturday = DayPage(1, 10);
+
+ var next = MinimapPage.Step(saturday, PageDirection.Next, _weeksWithMaintenance, _berlin);
+ var previous = MinimapPage.Step(saturday, PageDirection.Previous, _weeksWithMaintenance, _berlin);
+
+ (next?.FirstDay).Should().Be(Day(1, 12));
+ (previous?.FirstDay).Should().Be(Day(1, 9));
+ }
+
+ [Fact]
+ public void Step_AWeek_SkipsAWeekWithoutSpans()
+ {
+ var secondWeek = MinimapPage.Snap(
+ MinimapPageUnit.Week, At(1, 14, 12, 0), _officeHours, _weeksWithMaintenance, _berlin);
+
+ var next = MinimapPage.Step(secondWeek, PageDirection.Next, _weeksWithMaintenance, _berlin);
+ var back = MinimapPage.Step(next!.Value, PageDirection.Previous, _weeksWithMaintenance, _berlin);
+
+ next.Value.FirstDay.Should().Be(Day(1, 26));
+ next.Value.FromUtc.Should().Be(At(1, 26, 0, 0));
+ next.Value.ToUtc.Should().Be(At(2, 2, 0, 0));
+ back.Should().Be(secondWeek);
+ }
+
+ [Fact]
+ public void Step_KeepsTheCommonHours_AndWidensTheTargetDay()
+ {
+ var spans = new[] { Span(Day(1, 9), (7, 12), (16, 48)), Span(Day(1, 12), (5, 40), (17, 10)) };
+ var friday = MinimapPage.Snap(MinimapPageUnit.Day, At(1, 9, 12, 0), _officeHours, spans, _berlin);
+
+ var monday = MinimapPage.Step(friday, PageDirection.Next, spans, _berlin);
+
+ monday.Should().Be(
+ new MinimapPage(MinimapPageUnit.Day, Day(1, 12), _officeHours, At(1, 12, 5, 0), At(1, 12, 18, 0)));
+ }
+
+ [Fact]
+ public void Step_WithoutSpans_ReturnsNone()
+ {
+ MinimapPage.Step(DayPage(1, 9), PageDirection.Next, [], _berlin).Should().BeNull();
+ }
+
+ [Fact]
+ public void Land_FromFridayToMonday_KeepsTheClockTime()
+ {
+ var window = MinimapPage.Land(At(1, 9, 10, 0), At(1, 9, 11, 0), DayPage(1, 12), _weeksWithMaintenance, _berlin);
+
+ window.Should().Be((At(1, 12, 10, 0), At(1, 12, 11, 0)));
+ }
+
+ [Fact]
+ public void Land_AnOffsetHoldingNoSample_MovesToTheDaysFirstSample_KeepingTheWidth()
+ {
+ var window = MinimapPage.Land(At(1, 9, 2, 0), At(1, 9, 3, 30), DayPage(1, 12), _weeksWithMaintenance, _berlin);
+
+ window.Should().Be((At(1, 12, 7, 12), At(1, 12, 8, 42)));
+ }
+
+ [Fact]
+ public void Land_AnOffsetTouchingTheDaysSamples_StaysAtTheOffset()
+ {
+ var window = MinimapPage.Land(At(1, 9, 6, 0), At(1, 9, 7, 30), DayPage(1, 12), _weeksWithMaintenance, _berlin);
+
+ window.Should().Be((At(1, 12, 6, 0), At(1, 12, 7, 30)));
+ }
+
+ [Fact]
+ public void Land_OnAPageWithoutSpans_KeepsTheOffset()
+ {
+ var window = MinimapPage.Land(At(1, 9, 2, 0), At(1, 9, 3, 0), DayPage(1, 10), _weeksWithMaintenance, _berlin);
+
+ window.Should().Be((At(1, 10, 2, 0), At(1, 10, 3, 0)));
+ }
+
+ [Fact]
+ public void Land_OnAWeek_KeepsTheWeekdayAndClockTime()
+ {
+ var nextWeek = MinimapPage.Snap(
+ MinimapPageUnit.Week, At(1, 12, 12, 0), _officeHours, _weeksWithMaintenance, _berlin);
+
+ var window = MinimapPage.Land(At(1, 9, 10, 0), At(1, 9, 11, 0), nextWeek, _weeksWithMaintenance, _berlin);
+
+ window.Should().Be((At(1, 16, 10, 0), At(1, 16, 11, 0)));
+ }
+
+ [Fact]
+ public void Land_OnAWeekWhoseOffsetHoldsNoSample_MovesToTheWeeksFirstSample()
+ {
+ var thirdWeek = MinimapPage.Snap(
+ MinimapPageUnit.Week, At(1, 28, 12, 0), _officeHours, _weeksWithMaintenance, _berlin);
+
+ var window = MinimapPage.Land(At(1, 10, 10, 0), At(1, 10, 14, 0), thirdWeek, _weeksWithMaintenance, _berlin);
+
+ window.Should().Be((At(1, 26, 7, 12), At(1, 26, 11, 12)));
+ }
+
+ [Fact]
+ public void Land_OverTheAutumnChange_KeepsTheWallClockTime()
+ {
+ var spans = new[] { Span(Day(10, 23), (7, 0), (17, 0)), Span(Day(10, 26), (7, 0), (17, 0)) };
+ var monday = MinimapPage.Snap(MinimapPageUnit.Day, At(10, 26, 12, 0), _officeHours, spans, _berlin);
+
+ var window = MinimapPage.Land(At(10, 23, 10, 0), At(10, 23, 11, 0), monday, spans, _berlin);
+
+ window.Should().Be((At(10, 26, 10, 0), At(10, 26, 11, 0)));
+ window.FromUtc.Should().Be(new DateTime(2026, 10, 26, 9, 0, 0, DateTimeKind.Utc));
+ }
+
+ [Fact]
+ public void Land_OnAnHourTheSpringChangeSkips_TakesTheBaseOffset()
+ {
+ var springSunday = MinimapPage.Snap(MinimapPageUnit.Day, At(3, 29, 12, 0), _officeHours, [], _berlin);
+
+ var (fromUtc, toUtc) = MinimapPage.Land(At(3, 27, 2, 30), At(3, 27, 3, 30), springSunday, [], _berlin);
+
+ fromUtc.Should().Be(new DateTime(2026, 3, 29, 1, 30, 0, DateTimeKind.Utc));
+ toUtc.Should().Be(new DateTime(2026, 3, 29, 2, 30, 0, DateTimeKind.Utc));
+ }
+
+ [Fact]
+ public void Snap_ADayStartingOnAnHourTheSpringChangeSkips_TakesTheBaseOffset()
+ {
+ var page = MinimapPage.Snap(MinimapPageUnit.Day, At(3, 29, 12, 0), new DayHours(2, 17), [], _berlin);
+
+ page.FromUtc.Should().Be(new DateTime(2026, 3, 29, 1, 0, 0, DateTimeKind.Utc));
+ page.ToUtc.Should().Be(At(3, 29, 17, 0));
+ }
+
+ [Fact]
+ public void SnapToData_OnASaturday_TakesTheNearerFriday()
+ {
+ var span = MinimapPage.SnapToData(At(1, 10, 10, 0), _weeksWithMaintenance, _berlin);
+
+ (span?.Day).Should().Be(Day(1, 9));
+ }
+
+ [Fact]
+ public void SnapToData_OnASundayEvening_TakesTheNearerMonday()
+ {
+ var span = MinimapPage.SnapToData(At(1, 11, 18, 0), _weeksWithMaintenance, _berlin);
+
+ (span?.Day).Should().Be(Day(1, 12));
+ }
+
+ [Fact]
+ public void SnapToData_HalfwayBetweenTwoDays_TakesTheEarlierDay()
+ {
+ var spans = new[] { Span(Day(1, 9), (7, 0), (17, 0)), Span(Day(1, 12), (7, 0), (17, 0)) };
+
+ var span = MinimapPage.SnapToData(At(1, 11, 0, 0), spans, _berlin);
+
+ (span?.Day).Should().Be(Day(1, 9));
+ }
+
+ [Fact]
+ public void SnapToData_OnADayWithSpan_TakesThatDayEvenWhenTheNextLiesNearer()
+ {
+ var spans = new[] { Span(Day(1, 7), (7, 0), (9, 0)), Span(Day(1, 8), (7, 0), (17, 0)) };
+
+ var span = MinimapPage.SnapToData(At(1, 7, 23, 0), spans, _berlin);
+
+ (span?.Day).Should().Be(Day(1, 7));
+ }
+
+ [Fact]
+ public void SnapToData_OutsideTheArchive_TakesTheEdgeDay()
+ {
+ (MinimapPage.SnapToData(At(1, 1, 12, 0), _weeksWithMaintenance, _berlin)?.Day).Should().Be(Day(1, 5));
+ (MinimapPage.SnapToData(At(2, 7, 12, 0), _weeksWithMaintenance, _berlin)?.Day).Should().Be(Day(1, 30));
+ }
+
+ [Fact]
+ public void SnapToData_WithoutSpans_ReturnsNone()
+ {
+ MinimapPage.SnapToData(At(1, 10, 10, 0), [], _berlin).Should().BeNull();
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(15)]
+ [InlineData(31)]
+ public void Snap_AMonth_RunsFromTheFirstToTheNextFirst(int dayOfJanuary)
+ {
+ var page = MinimapPage.Snap(
+ MinimapPageUnit.Month, At(1, dayOfJanuary, 12, 0), _officeHours, _weeksWithMaintenance, _berlin);
+
+ page.FirstDay.Should().Be(Day(1, 1));
+ page.EndDay.Should().Be(Day(2, 1));
+ page.FromUtc.Should().Be(At(1, 1, 0, 0));
+ page.ToUtc.Should().Be(At(2, 1, 0, 0));
+ }
+
+ [Fact]
+ public void Snap_AMonthOverTheAutumnChange_RunsFirstToFirstInWallClock()
+ {
+ var page = MinimapPage.Snap(MinimapPageUnit.Month, At(10, 22, 12, 0), _officeHours, [], _berlin);
+
+ page.FromUtc.Should().Be(At(10, 1, 0, 0));
+ page.ToUtc.Should().Be(At(11, 1, 0, 0));
+ (page.ToUtc - page.FromUtc).Should().Be(TimeSpan.FromHours((31 * 24) + 1));
+ }
+
+ [Fact]
+ public void Step_AMonth_SkipsAMonthWithoutSpans_AndStopsPastTheLast()
+ {
+ var spans = new[] { Span(Day(1, 20), (8, 0), (16, 0)), Span(Day(4, 2), (8, 0), (16, 0)) };
+ var january = MinimapPage.Snap(MinimapPageUnit.Month, At(1, 20, 12, 0), _officeHours, spans, _berlin);
+
+ var next = MinimapPage.Step(january, PageDirection.Next, spans, _berlin);
+
+ next?.Unit.Should().Be(MinimapPageUnit.Month);
+ next?.FirstDay.Should().Be(Day(4, 1), "February and March hold no span");
+ MinimapPage.Step(next!.Value, PageDirection.Next, spans, _berlin).Should().BeNull();
+ MinimapPage.Step(next.Value, PageDirection.Previous, spans, _berlin)?.FirstDay.Should().Be(Day(1, 1));
+ }
+
+ [Fact]
+ public void Land_OnAMonth_KeepsTheDayOfTheMonthAndClockTime()
+ {
+ var spans = new[] { Span(Day(1, 12), (8, 0), (16, 0)), Span(Day(2, 12), (8, 0), (16, 0)) };
+ var february = MinimapPage.Snap(MinimapPageUnit.Month, At(2, 12, 12, 0), _officeHours, spans, _berlin);
+
+ var landed = MinimapPage.Land(At(1, 10, 9, 0), At(1, 16, 9, 0), february, spans, _berlin);
+
+ landed.Should().Be((At(2, 10, 9, 0), At(2, 16, 9, 0)));
+ }
+
+ [Fact]
+ public void Holding_AWindowInsideTheDaysHours_IsTheDayPage()
+ {
+ var page = HoldingOnTheWeeks(At(1, 7, 9, 0), At(1, 7, 15, 0));
+
+ page.Should().Be(DayPage(1, 7));
+ }
+
+ [Fact]
+ public void Holding_ATwelveHourWindow_OnTenWorkingHours_IsTheWeekPage()
+ {
+ var page = HoldingOnTheWeeks(At(1, 7, 6, 0), At(1, 7, 18, 0));
+
+ page.Unit.Should().Be(MinimapPageUnit.Week, "the Day page is its working hours, 07:00 to 17:00");
+ page.FirstDay.Should().Be(Day(1, 5));
+ }
+
+ [Fact]
+ public void Holding_AnHourBeforeTheWorkingHours_IsTheWeekPage()
+ {
+ var page = HoldingOnTheWeeks(At(1, 7, 5, 0), At(1, 7, 6, 0));
+
+ page.Unit.Should().Be(MinimapPageUnit.Week);
+ }
+
+ [Fact]
+ public void Holding_AWindowAcrossAWeekend_IsTheMonthPage()
+ {
+ var page = HoldingOnTheWeeks(At(1, 9, 9, 0), At(1, 13, 9, 0));
+
+ page.Should().Be(new MinimapPage(MinimapPageUnit.Month, Day(1, 1), _officeHours, At(1, 1, 0, 0), At(2, 1, 0, 0)));
+ }
+
+ [Fact]
+ public void Holding_AWindowWiderThanAMonth_IsTheMonthOfItsStart()
+ {
+ var page = HoldingOnTheWeeks(At(1, 20, 0, 0), At(3, 20, 0, 0));
+
+ page.Unit.Should().Be(MinimapPageUnit.Month);
+ page.FirstDay.Should().Be(Day(1, 1));
+ }
+
+ [Fact]
+ public void Holding_AWindowAcrossTheAutumnChange_IsTheWeekThatHoldsTheRepeatedHour()
+ {
+ var page = MinimapPage.Holding(At(10, 24, 12, 0), At(10, 25, 12, 0), null, _officeHours, [], _berlin);
+
+ page.Unit.Should().Be(MinimapPageUnit.Week);
+ page.FromUtc.Should().Be(At(10, 19, 0, 0));
+ page.ToUtc.Should().Be(At(10, 26, 0, 0));
+ }
+
+ [Fact]
+ public void Holding_ASlidingWindowPastTheDaysEnd_KeepsTheDayPage_WhileTheNewestSampleLiesOnIt()
+ {
+ var page = HoldingOnTheWeeks(At(1, 7, 16, 30), At(1, 7, 17, 30), newestSampleUtc: At(1, 7, 16, 48));
+
+ page.Should().Be(DayPage(1, 7), "the window holds no sample past 16:48, inside the 07:00-17:00 page");
+ }
+
+ [Fact]
+ public void Holding_AWindowWhollyPastTheNewestSample_KeepsTheDayPageOfItsStart()
+ {
+ var page = HoldingOnTheWeeks(At(1, 7, 19, 0), At(1, 7, 20, 0), newestSampleUtc: At(1, 7, 16, 48));
+
+ page.Should().Be(DayPage(1, 7), "the evening after the shift holds no sample past the day's last");
+ }
+
+ [Fact]
+ public void Holding_AHistoricalWindowWiderThanTheDay_IsStillTheWeekPage()
+ {
+ var page = HoldingOnTheWeeks(At(1, 7, 6, 0), At(1, 7, 18, 0), newestSampleUtc: At(1, 30, 16, 48));
+
+ page.Unit.Should().Be(MinimapPageUnit.Week, "a newest sample after the window clips nothing");
+ }
+
+ [Fact]
+ public void Holding_WithNoNewestSample_JudgesTheWholeWindow()
+ {
+ var page = HoldingOnTheWeeks(At(1, 7, 16, 30), At(1, 7, 17, 30));
+
+ page.Unit.Should().Be(MinimapPageUnit.Week, "the window's end passes the 17:00 page end");
+ }
+
+ private static MinimapPage HoldingOnTheWeeks(
+ DateTime windowFromUtc,
+ DateTime windowToUtc,
+ DateTime? newestSampleUtc = null)
+ {
+ return MinimapPage.Holding(
+ windowFromUtc, windowToUtc, newestSampleUtc, _officeHours, _weeksWithMaintenance, _berlin);
+ }
+
+ private static MinimapPage DayPage(int month, int day)
+ {
+ return MinimapPage.Snap(
+ MinimapPageUnit.Day, At(month, day, 12, 0), _officeHours, _weeksWithMaintenance, _berlin);
+ }
+
+ private static List Weekdays(
+ DateOnly firstDay,
+ DateOnly lastDay,
+ (int Hour, int Minute)? first = null,
+ (int Hour, int Minute)? last = null)
+ {
+ var spans = new List();
+ for (var day = firstDay; day <= lastDay; day = day.AddDays(1))
+ {
+ if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
+ {
+ spans.Add(Span(day, first ?? (7, 12), last ?? (16, 48)));
+ }
+ }
+
+ return spans;
+ }
+
+ private static ArchiveDaySpan Span(DateOnly day, (int Hour, int Minute) first, (int Hour, int Minute) last)
+ {
+ return new ArchiveDaySpan(
+ day,
+ At(day.Month, day.Day, first.Hour, first.Minute),
+ At(day.Month, day.Day, last.Hour, last.Minute));
+ }
+
+ private static DateOnly Day(int month, int day)
+ {
+ return new DateOnly(2026, month, day);
+ }
+
+ private static DateTime At(int month, int day, int hour, int minute)
+ {
+ return TimeZoneInfo.ConvertTimeToUtc(new DateTime(2026, month, day, hour, minute, 0), _berlin);
+ }
+}
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapTrackGeometryTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapTrackGeometryTests.cs
new file mode 100644
index 0000000..3866a2b
--- /dev/null
+++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapTrackGeometryTests.cs
@@ -0,0 +1,211 @@
+using AwesomeAssertions;
+
+using SemiPlot.Core.Trends;
+
+using Xunit;
+
+using static SemiPlot.Tests.Unit.Core.Trends.BerlinClock;
+
+namespace SemiPlot.Tests.Unit.Core.Trends;
+
+[Trait("Component", "Core")]
+[Trait("Area", "Data")]
+[Trait("Category", "Unit")]
+public sealed class MinimapTrackGeometryTests
+{
+ private const double PageWidth = 1000.0;
+ private const double MinimumBoxWidth = 6.0;
+ private static readonly DayHours _officeHours = new(7, 17);
+
+ // Wednesday 7 January 2026, 07:00-17:00 Berlin, 100 px per hour over the page width.
+ private static readonly MinimapPage _dayPage = DayPage(1, 7, _officeHours);
+
+ [Fact]
+ public void WindowBox_InsideThePage_CutsNoEdge()
+ {
+ var box = Box(Berlin(1, 7, 9), Berlin(1, 7, 11));
+
+ ShouldBe(box, 200.0, 200.0, cutsLeft: false, cutsRight: false);
+ }
+
+ [Fact]
+ public void WindowBox_StraddlingTheLeftEdge_IsCutThere()
+ {
+ var box = Box(Berlin(1, 7, 6), Berlin(1, 7, 8));
+
+ ShouldBe(box, 0.0, 100.0, cutsLeft: true, cutsRight: false);
+ }
+
+ [Fact]
+ public void WindowBox_StraddlingTheRightEdge_IsCutThere()
+ {
+ var box = Box(Berlin(1, 7, 16), Berlin(1, 8, 9));
+
+ ShouldBe(box, 900.0, 100.0, cutsLeft: false, cutsRight: true);
+ }
+
+ [Fact]
+ public void WindowBox_WiderThanThePage_IsCutAtBothEdges()
+ {
+ var box = Box(Berlin(1, 6, 9), Berlin(1, 8, 9));
+
+ ShouldBe(box, 0.0, PageWidth, cutsLeft: true, cutsRight: true);
+ }
+
+ [Fact]
+ public void WindowBox_OnThePageEdges_CutsNoEdge()
+ {
+ var box = Box(_dayPage.FromUtc, _dayPage.ToUtc);
+
+ ShouldBe(box, 0.0, PageWidth, cutsLeft: false, cutsRight: false);
+ }
+
+ [Fact]
+ public void WindowBox_OfANarrowWindowCutAtTheRightEdge_KeepsTheMinimumWidthInside()
+ {
+ var box = Box(_dayPage.ToUtc.AddSeconds(-30), _dayPage.ToUtc.AddMinutes(1));
+
+ ShouldBe(box, PageWidth - MinimumBoxWidth, MinimumBoxWidth, cutsLeft: false, cutsRight: true);
+ }
+
+ [Theory]
+ [InlineData(5, 6)]
+ [InlineData(17, 18)]
+ public void WindowBox_MissingThePage_IsNull(int fromHour, int toHour)
+ {
+ Box(Berlin(1, 7, fromHour), Berlin(1, 7, toHour)).Should().BeNull();
+ }
+
+ [Fact]
+ public void WindowBox_EndingOnThePageStart_IsNull()
+ {
+ Box(Berlin(1, 7, 6), _dayPage.FromUtc).Should().BeNull();
+ }
+
+ [Fact]
+ public void RunShades_OnADayPage_ClipEachRunAndEdgeOnlyAnInterruptionOnThePage()
+ {
+ RecipeRun[] runs =
+ [
+ new(Berlin(1, 7, 6), Berlin(1, 7, 8), IsInterrupted: true),
+ new(Berlin(1, 7, 9), Berlin(1, 7, 10), IsInterrupted: false),
+ new(Berlin(1, 7, 12), Berlin(1, 7, 13), IsInterrupted: true),
+ new(Berlin(1, 7, 16), Berlin(1, 7, 18), IsInterrupted: true),
+ new(Berlin(1, 7, 18), Berlin(1, 7, 19), IsInterrupted: false)
+ ];
+
+ var shades = MinimapTrackGeometry.RunShades(_dayPage, runs, PageWidth, MinimumBoxWidth);
+
+ shades.Select(shade => (Math.Round(shade.Left, 6), Math.Round(shade.Width, 6), shade.HasEndEdge))
+ .Should().Equal(
+ (0.0, 100.0, true),
+ (200.0, 100.0, false),
+ (500.0, 100.0, true),
+ (900.0, 100.0, false));
+ }
+
+ [Fact]
+ public void RunShades_OnAWeekPage_AreNone()
+ {
+ var week = MinimapPage.Snap(MinimapPageUnit.Week, Berlin(1, 7, 12), _officeHours, [], BerlinZone);
+ RecipeRun[] runs = [new(Berlin(1, 7, 9), Berlin(1, 7, 10), IsInterrupted: false)];
+
+ MinimapTrackGeometry.RunShades(week, runs, PageWidth, MinimumBoxWidth).Should().BeEmpty();
+ }
+
+ [Fact]
+ public void PageTicks_OfADay_AreEveryWholeHour_WhenTheLabelsFit()
+ {
+ var ticks = MinimapTrackGeometry.PageTicks(_dayPage, PageWidth, minimumSpacing: 60.0, BerlinZone);
+
+ ticks.Select(tick => tick.WallClock.Hour).Should().Equal(7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
+ ticks.Select(tick => tick.X).Should().Equal(0.0, 100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0);
+ ticks.Should().AllSatisfy(tick => tick.Kind.Should().Be(TrackTickKind.Hour));
+ }
+
+ [Fact]
+ public void PageTicks_OfADay_TakeTheSmallestStrideThatFits_AlignedToMidnight()
+ {
+ var ticks = MinimapTrackGeometry.PageTicks(_dayPage, PageWidth, minimumSpacing: 150.0, BerlinZone);
+
+ ticks.Select(tick => tick.WallClock.Hour).Should().Equal(8, 10, 12, 14, 16);
+ ticks[0].X.Should().Be(100.0);
+ }
+
+ [Fact]
+ public void PageTicks_OverTheSpringChange_SkipTheMissingHourWithoutStacking()
+ {
+ // Berlin skips 02:00-03:00 on Sunday 29 March 2026, so the whole day holds 23 hours.
+ var page = DayPage(3, 29, DayHours.FullDay);
+
+ var ticks = MinimapTrackGeometry.PageTicks(page, 230.0, minimumSpacing: 10.0, BerlinZone);
+
+ ticks.Should().HaveCount(23);
+ ticks.Select(tick => tick.WallClock.Hour).Should().NotContain(2);
+ ticks.Select(tick => tick.X).Should().BeInAscendingOrder().And.OnlyHaveUniqueItems();
+ ticks.Single(tick => tick.WallClock.Hour == 3).X.Should().BeApproximately(20.0, 1e-9);
+ }
+
+ [Fact]
+ public void PageTicks_OverTheAutumnChange_KeepTheStrideOfRealHours()
+ {
+ // Berlin repeats 02:00-03:00 on Sunday 25 October 2026; at 10 px per hour a 15 px minimum takes a
+ // two-hour stride, so the second 02:00, one real hour after the first, is dropped.
+ var page = DayPage(10, 25, DayHours.FullDay);
+
+ var ticks = MinimapTrackGeometry.PageTicks(page, 250.0, minimumSpacing: 15.0, BerlinZone);
+
+ ticks.Select(tick => tick.WallClock.Hour).Should().Equal(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22);
+ ticks.Select(tick => tick.X).Take(3).Should().Equal(0.0, 20.0, 50.0);
+ }
+
+ [Fact]
+ public void PageTicks_OfAWeek_AreItsMidnights_OverTheAutumnChange()
+ {
+ // Berlin repeats 02:00-03:00 on Sunday 25 October 2026, so the week of 19 October holds 169 hours.
+ var page = MinimapPage.Snap(MinimapPageUnit.Week, Berlin(10, 21, 12), _officeHours, [], BerlinZone);
+
+ var ticks = MinimapTrackGeometry.PageTicks(page, 1690.0, minimumSpacing: 60.0, BerlinZone);
+
+ ticks.Select(tick => tick.WallClock).Should().Equal(
+ Enumerable.Range(19, 7).Select(day => new DateTime(2026, 10, day, 0, 0, 0, DateTimeKind.Unspecified)));
+ ticks.Select(tick => tick.X).Should().Equal(0.0, 240.0, 480.0, 720.0, 960.0, 1200.0, 1440.0);
+ ticks.Should().AllSatisfy(tick => tick.Kind.Should().Be(TrackTickKind.Day));
+ }
+
+ [Theory]
+ [InlineData(25.0, new[] { 5, 7, 9, 11 })]
+ [InlineData(30.0, new[] { 5 })]
+ public void PageTicks_OfANarrowWeek_ThinTheDays(double minimumSpacing, int[] expectedDays)
+ {
+ var page = MinimapPage.Snap(MinimapPageUnit.Week, Berlin(1, 7, 12), _officeHours, [], BerlinZone);
+
+ var ticks = MinimapTrackGeometry.PageTicks(page, 100.0, minimumSpacing, BerlinZone);
+
+ ticks.Select(tick => tick.WallClock.Day).Should().Equal(expectedDays);
+ }
+
+ [Fact]
+ public void PageTicks_OverAZeroWidth_AreEmpty()
+ {
+ MinimapTrackGeometry.PageTicks(_dayPage, 0.0, minimumSpacing: 60.0, BerlinZone).Should().BeEmpty();
+ }
+
+ private static PageWindowBox? Box(DateTime windowFromUtc, DateTime windowToUtc)
+ {
+ return MinimapTrackGeometry.WindowBox(_dayPage, windowFromUtc, windowToUtc, PageWidth, MinimumBoxWidth);
+ }
+
+ private static void ShouldBe(PageWindowBox? box, double left, double width, bool cutsLeft, bool cutsRight)
+ {
+ box.Should().NotBeNull();
+ box.Value.Left.Should().BeApproximately(left, 1e-9);
+ box.Value.Width.Should().BeApproximately(width, 1e-9);
+ (box.Value.CutsLeft, box.Value.CutsRight).Should().Be((cutsLeft, cutsRight));
+ }
+
+ private static MinimapPage DayPage(int month, int day, DayHours hours)
+ {
+ return MinimapPage.Snap(MinimapPageUnit.Day, Berlin(month, day, 12), hours, [], BerlinZone);
+ }
+}
diff --git a/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveStatementTextTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveStatementTextTests.cs
index 1cd17de..28b79ef 100644
--- a/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveStatementTextTests.cs
+++ b/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveStatementTextTests.cs
@@ -34,6 +34,7 @@ public sealed class ArchiveStatementTextTests
[InlineData(ArchiveStatements.ExportSliceRows, "ORDER BY t, array_position(@ids, id);")]
// The calendar takes the days as an ascending list.
[InlineData(ArchiveStatements.ArchiveDays, "ORDER BY 1;")]
+ [InlineData(ArchiveStatements.ArchiveDaySpans, "ORDER BY 1;")]
public void AStatementEndsWithItsOuterOrdering(string statement, string ordering)
{
statement.ReplaceLineEndings("\n").Should().EndWith(ordering);
@@ -131,6 +132,16 @@ public void NoExportStatementSelectsTheQualityColumn(string statement)
[InlineData(ArchiveStatements.ArchiveDays, new[] { "ORDER BY t", "LIMIT 1" })]
[InlineData(
ArchiveStatements.ArchiveDays, new[] { "t >= day.start AND t < day.start + interval '1 day'" })]
+ [InlineData(ArchiveStatements.ArchiveDaySpans, new[] { "AND l = 0", "CROSS JOIN semiplot_tags tag" })]
+ [InlineData(
+ ArchiveStatements.ArchiveDaySpans, new[] { "AND t >= day.start AND t < day.start + interval '1 day') AS lo" })]
+ [InlineData(
+ ArchiveStatements.ArchiveDaySpans, new[] { "AND t >= day.start AND t < day.start + interval '1 day') AS hi" })]
+ // A day of the range with no raw row has no span, rather than a span of nulls.
+ [InlineData(ArchiveStatements.ArchiveDaySpans, new[] { "HAVING min(bounds.lo) IS NOT NULL" })]
+ // Without the fence the planner flattens the pair into the aggregate and the HAVING runs the first probe
+ // a second time per pen and day.
+ [InlineData(ArchiveStatements.ArchiveDaySpans, new[] { "OFFSET 0" })]
public void AStatementCarriesTheClauseItsReaderDependsOn(string statement, string[] fragments)
{
foreach (var fragment in fragments)
@@ -155,14 +166,16 @@ public void TheBucketedWindowBinderNamesExactlyTheStatementsOwnParameters()
AssertBinderNamesTheStatementsOwnParameters(command, ArchiveStatements.BucketedHistoryWindow);
}
- [Fact]
- public void TheArchiveDaysBinderNamesExactlyTheStatementsOwnParameters()
+ [Theory]
+ [InlineData(ArchiveStatements.ArchiveDays)]
+ [InlineData(ArchiveStatements.ArchiveDaySpans)]
+ public void TheArchiveDaysBinderNamesExactlyTheParametersOfEachStatementItBinds(string statement)
{
- using var command = new NpgsqlCommand(ArchiveStatements.ArchiveDays);
+ using var command = new NpgsqlCommand(statement);
PostgresDataProvider.BindArchiveDays(command, new DateOnly(2026, 1, 1), new DateOnly(2026, 1, 31));
- AssertBinderNamesTheStatementsOwnParameters(command, ArchiveStatements.ArchiveDays);
+ AssertBinderNamesTheStatementsOwnParameters(command, statement);
}
[Fact]
diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/FakeDataProvider.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/FakeDataProvider.cs
index 52e1db3..2eea861 100644
--- a/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/FakeDataProvider.cs
+++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/FakeDataProvider.cs
@@ -9,6 +9,7 @@
using SemiPlot.Core.Data;
using SemiPlot.Core.Data.Errors;
using SemiPlot.Core.Trends;
+using SemiPlot.UI.Chart;
using SemiPlot.UI.Minimap;
namespace SemiPlot.Tests.Unit.UI.Bridge;
@@ -36,6 +37,8 @@ internal sealed class FakeDataProvider(
private bool _previousRealtimePollFailed;
+ private Func, DateTime, DateTime, int, bool> _isBandRead = (_, _, _, _) => false;
+
public DateTime ArchiveFirstUtc { get; set; } = new(2025, 12, 25, 0, 0, 0, DateTimeKind.Utc);
public DateTime ArchiveLastUtc { get; set; } = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
@@ -83,6 +86,23 @@ internal sealed class FakeDataProvider(
public CancellationToken LastDaysCancellationToken { get; private set; }
+ // The day spans; a read answers the ones inside its range, ascending, as the real statement does.
+ public IReadOnlyList ArchiveDaySpans { get; set; } = [];
+
+ public bool FailDaySpans { get; set; }
+
+ // A spans read that throws instead of answering, the shape of a defect rather than of an outage.
+ public Exception? DaySpansReadException { get; set; }
+
+ // Plain, for the reason stated at CatalogueGate. A gated spans read waits on the gate in place when it starts.
+ public TaskCompletionSource>> DaySpansGate { get; set; } = new();
+
+ public bool GateDaySpans { get; set; }
+
+ public List<(DateOnly FirstDay, DateOnly LastDay)> DaySpansRanges { get; } = [];
+
+ public CancellationToken LastDaySpansCancellationToken { get; private set; }
+
// When set, a query for this layer returns the gate's task, holding it in flight so a newer query can
// complete first (cross-path race).
public AggregationLayer? GatedLayer { get; set; }
@@ -102,8 +122,7 @@ internal sealed class FakeDataProvider(
// A history read that throws instead of answering, the shape of a defect rather than of an outage.
public Exception? HistoryReadException { get; set; }
- public IReadOnlyList BandHistoryQueries =>
- [.. HistoryQueries.Where(query => query.TargetColumnCount == MinimapBandFeed.MinimapColumns)];
+ public IReadOnlyList BandHistoryQueries => [.. HistoryQueries.Where(query => query.IsBandRead)];
/// The chart's query count; like every LastQueried member below, it ignores the band's reads.
public int HistoryQueryCount => ChartHistoryQueries.Count;
@@ -120,12 +139,11 @@ internal sealed class FakeDataProvider(
public CancellationToken LastQueriedCancellationToken => LastHistoryQuery?.CancellationToken ?? default;
- public IReadOnlyList ChartHistoryQueries =>
- [.. HistoryQueries.Where(query => query.TargetColumnCount != MinimapBandFeed.MinimapColumns)];
+ public IReadOnlyList ChartHistoryQueries => [.. HistoryQueries.Where(query => !query.IsBandRead)];
private HistoryQuery? LastHistoryQuery => ChartHistoryQueries is [.., var last] ? last : null;
- private IReadOnlyList HistoryQueries
+ public IReadOnlyList HistoryQueries
{
get
{
@@ -331,7 +349,9 @@ public Task>> QueryHistoryAsync(
{
lock (_historyQueriesGate)
{
- _historyQueries.Add(new HistoryQuery(penIds, fromUtc, toUtc, layer, targetColumnCount, cancellationToken));
+ var isBandRead = _isBandRead(penIds, fromUtc, toUtc, targetColumnCount);
+ _historyQueries.Add(
+ new HistoryQuery(penIds, fromUtc, toUtc, layer, targetColumnCount, isBandRead, cancellationToken));
}
if (HistoryReadException is { } readException)
@@ -414,6 +434,36 @@ public Task>> QueryArchiveDaysAsync(
return Task.FromResult(Result.Ok(days));
}
+ public Task>> QueryArchiveDaySpansAsync(
+ DateOnly firstDay,
+ DateOnly lastDay,
+ CancellationToken cancellationToken = default)
+ {
+ DaySpansRanges.Add((firstDay, lastDay));
+ LastDaySpansCancellationToken = cancellationToken;
+
+ if (DaySpansReadException is { } readException)
+ {
+ return Task.FromException>>(readException);
+ }
+
+ if (FailDaySpans)
+ {
+ return Task.FromResult(
+ Result.Fail>(BenchArchiveError(ArchiveFault.ReadFailed, "42601")));
+ }
+
+ if (GateDaySpans)
+ {
+ return DaySpansGate.Task.WaitAsync(cancellationToken);
+ }
+
+ IReadOnlyList spans =
+ [.. ArchiveDaySpans.Where(span => span.Day >= firstDay && span.Day <= lastDay).OrderBy(span => span.Day)];
+
+ return Task.FromResult(Result.Ok(spans));
+ }
+
/// An archive failure against the bench address, which every fake answers with.
public static ArchiveError BenchArchiveError(ArchiveFault fault, string detail = "")
{
@@ -425,6 +475,21 @@ public static ArchiveError UnreachableArchive()
return BenchArchiveError(ArchiveFault.Unreachable);
}
+ ///
+ /// From now on, a read of only the drawn pen over the page in force as it is issued is the band's.
+ ///
+ public void RecognizeBandReadsOf(TrendChartViewModel chart, MinimapViewModel minimap)
+ {
+ minimap.HasExtent.Should().BeFalse("the band reads only once the minimap holds an extent");
+
+ _isBandRead = (penIds, fromUtc, toUtc, targetColumnCount) =>
+ penIds is [var penId]
+ && penId == chart.DrawnPenId
+ && fromUtc == minimap.Pager.Page.FromUtc
+ && toUtc == minimap.Pager.Page.ToUtc
+ && targetColumnCount % MinimapBandFeed.ColumnStep == 0;
+ }
+
private sealed class PoisonedSampleList : IReadOnlyList
{
public int Count => 1;
@@ -458,4 +523,5 @@ internal sealed record HistoryQuery(
DateTime ToUtc,
AggregationLayer Layer,
int TargetColumnCount,
+ bool IsBandRead,
CancellationToken CancellationToken);
diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/TrendCoordinatorTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/TrendCoordinatorTests.cs
index 24ef5da..28ad1a5 100644
--- a/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/TrendCoordinatorTests.cs
+++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Bridge/TrendCoordinatorTests.cs
@@ -318,13 +318,19 @@ await coordinator.QueryHistoryAsync(
ChartColumnCount,
TestContext.Current.CancellationToken);
await coordinator.QueryArchiveExtentAsync();
+ await coordinator.QueryArchiveDaySpansAsync(
+ DateOnly.FromDateTime(FakeDataProvider.RealtimeEpoch),
+ DateOnly.FromDateTime(FakeDataProvider.RealtimeEpoch),
+ TestContext.Current.CancellationToken);
liveSource.LiveSubscriptionsOpened.Should().Be(1);
liveSource.HistoryQueryCount.Should().Be(0);
liveSource.ExtentQueryCount.Should().Be(0);
+ liveSource.DaySpansRanges.Should().BeEmpty();
dataProvider.LiveSubscriptionsOpened.Should().Be(0);
dataProvider.HistoryQueryCount.Should().Be(1);
dataProvider.ExtentQueryCount.Should().Be(1);
+ dataProvider.DaySpansRanges.Should().ContainSingle();
}
// docs/architecture/data-integration.md#realtime
diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Export/CsvExportWindowTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Export/CsvExportWindowTests.cs
index b504a83..dcdd139 100644
--- a/SemiPlot/SemiPlot.Tests.Unit/UI/Export/CsvExportWindowTests.cs
+++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Export/CsvExportWindowTests.cs
@@ -1028,6 +1028,7 @@ public async Task AfterASuccess_TheMessageLineToolTipIsTheFullPath()
ToolTip.GetTip(message).Should().Be(path);
message.Text.Should().Contain("out.csv").And.NotContain(directory.Path);
+ ShouldShowTheWholeTip(message, path, "the line's two-line trimming stays out of its tooltip");
}
finally
{
diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Legend/TrendLegendTopRowViewTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Legend/TrendLegendTopRowViewTests.cs
index bd7ac80..a91c07a 100644
--- a/SemiPlot/SemiPlot.Tests.Unit/UI/Legend/TrendLegendTopRowViewTests.cs
+++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Legend/TrendLegendTopRowViewTests.cs
@@ -1,5 +1,3 @@
-using System.Reflection;
-
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
@@ -214,14 +212,9 @@ .. TopRowButtons(window),
foreach (var holder in holders)
{
- var text = OpenTooltipText(holder);
-
- text.Text.Should().Be(ToolTip.GetTip(holder) as string, "'{0}' at {1} px", holder.Name, width);
- text.IsEffectivelyVisible.Should().BeTrue("'{0}' at {1} px shows its tooltip text", holder.Name, width);
- text.Bounds.Width.Should().BePositive("'{0}' at {1} px lays its tooltip text out", holder.Name, width);
+ var tip = ToolTip.GetTip(holder).Should().BeOfType("'{0}' carries a text tooltip", holder.Name).Subject;
- ToolTip.SetIsOpen(holder, false);
- Dispatcher.UIThread.RunJobs();
+ ShouldShowTheWholeTip(holder, tip, $"'{holder.Name}' at {width} px");
}
}
@@ -277,22 +270,6 @@ private static Point Hover(Window window, Control control)
return centre;
}
- // Avalonia keeps the open ToolTip behind an internal property; no public member reaches it.
- private static TextBlock OpenTooltipText(Control holder)
- {
- var property = typeof(ToolTip).GetField("ToolTipProperty", BindingFlags.NonPublic | BindingFlags.Static)
- ?.GetValue(null) as AvaloniaProperty
- ?? throw new InvalidOperationException("Avalonia no longer exposes ToolTip.ToolTipProperty.");
-
- ToolTip.SetIsOpen(holder, true);
- Dispatcher.UIThread.RunJobs();
-
- var tooltip = holder.GetValue(property) as ToolTip
- ?? throw new InvalidOperationException($"'{holder.Name}' opened no tooltip.");
-
- return Descendants(tooltip).Single();
- }
-
private static IReadOnlyList