From 1871d3ff0371b7951a4309c0ebf39fc7ad431c93 Mon Sep 17 00:00:00 2001 From: Oleg <18466855+EvaTheSalmon@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:28:37 +0300 Subject: [PATCH] feat(minimap): page the archive by day with a calendar (#78) With six months in the archive the minimap read 250 columns over the whole extent, about 17 h per column, so a working day's shape was lost and reaching a recipe run meant panning by hand. The strip under the chart now shows one page that follows the chart zoom, a day's working hours, a week or a month, at the strip's width, and a day calendar under it marks the days with rows, the shown page and the operator's markers. Page steps skip days without rows. The navigation bar, a new Go menu and window gestures step through recipe runs and operator markers, and both open one filtered list grouped by month. A new archive day-spans read feeds the calendar. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 21 +- SemiPlot/SemiPlot.Core/Data/ArchiveDaySpan.cs | 4 + SemiPlot/SemiPlot.Core/Data/IDataProvider.cs | 6 + SemiPlot/SemiPlot.Core/Trends/DayCalendar.cs | 214 +++++ .../SemiPlot.Core/Trends/DayCalendarLabels.cs | 80 ++ .../SemiPlot.Core/Trends/MarkerNavigation.cs | 105 +++ SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs | 44 +- .../SemiPlot.Core/Trends/MinimapGeometry.cs | 55 -- SemiPlot/SemiPlot.Core/Trends/MinimapPage.cs | 284 ++++++ .../Trends/MinimapTrackGeometry.cs | 147 +++ SemiPlot/SemiPlot.Core/Trends/SortedSearch.cs | 27 + .../ArchiveStatements.cs | 23 + .../PostgresDataProvider.cs | 40 + .../ExplainPlanTests.cs | 27 + .../PostgresArchiveDaySpansReadTests.cs | 195 ++++ .../Core/Trends/BerlinClock.cs | 15 + .../Core/Trends/DayCalendarLabelsTests.cs | 155 ++++ .../Core/Trends/DayCalendarTests.cs | 311 +++++++ .../Core/Trends/MarkerNavigationTests.cs | 267 ++++++ .../Core/Trends/MarkerSetTests.cs | 19 + .../Core/Trends/MinimapGeometryTests.cs | 118 --- .../Core/Trends/MinimapPageTests.cs | 556 ++++++++++++ .../Core/Trends/MinimapTrackGeometryTests.cs | 211 +++++ .../Postgres/ArchiveStatementTextTests.cs | 21 +- .../UI/Bridge/FakeDataProvider.cs | 78 +- .../UI/Bridge/TrendCoordinatorTests.cs | 6 + .../UI/Export/CsvExportWindowTests.cs | 1 + .../UI/Legend/TrendLegendTopRowViewTests.cs | 27 +- .../UI/Localization/ResourcesTests.cs | 12 +- .../UI/MainWindow/AppMenuBarTests.cs | 96 +- .../UI/MainWindow/MainWindowTestBuilder.cs | 1 + .../UI/MainWindow/MainWindowViewTests.cs | 4 +- .../UI/MainWindow/WindowGestureTests.cs | 439 +++++++++ .../UI/Minimap/ArchivePresenceFeedTests.cs | 330 +++++++ .../UI/Minimap/MinimapBandFeedTests.cs | 317 +++++-- .../UI/Minimap/MinimapDetailTrackTests.cs | 237 +++++ .../UI/Minimap/MinimapHoverTests.cs | 225 +++-- .../UI/Minimap/MinimapLabelsTests.cs | 86 ++ .../UI/Minimap/MinimapPagerTests.cs | 366 ++++++++ .../UI/Minimap/MinimapPointerInputTests.cs | 107 ++- .../UI/Minimap/MinimapStand.cs | 56 +- .../UI/Minimap/MinimapViewModelTests.cs | 192 +--- .../UI/Minimap/MinimapViewStand.cs | 71 +- .../UI/Minimap/MinimapViewTests.cs | 394 +++++++- .../UI/Navigation/NavigationBarStand.cs | 141 +++ .../UI/Navigation/NavigationBarTestBuilder.cs | 7 +- .../Navigation/NavigationBarViewModelTests.cs | 266 ++++++ .../UI/Navigation/NavigationBarViewTests.cs | 256 +++++- .../UI/Navigation/NavigationListRowsTests.cs | 219 +++++ .../NavigationListViewModelTests.cs | 149 ++++ .../UI/Navigation/NavigationListViewTests.cs | 459 ++++++++++ SemiPlot/SemiPlot.Tests.Unit/UI/ThemeTests.cs | 252 +++++- SemiPlot/SemiPlot.Tests.Unit/UI/ViewProbe.cs | 36 + SemiPlot/SemiPlot.UI/App.axaml | 1 + .../SemiPlot.UI/Bridge/TrendCoordinator.cs | 8 + SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs | 3 + .../SemiPlot.UI/Localization/CountForms.cs | 28 + .../SemiPlot.UI/Localization/Resources.resx | 138 +++ .../Localization/Resources.ru.resx | 140 ++- .../SemiPlot.UI/MainWindow/AppMenuBar.axaml | 43 + .../MainWindow/AppMenuBar.axaml.cs | 12 + .../SemiPlot.UI/MainWindow/MainWindow.axaml | 3 +- .../MainWindow/MainWindow.axaml.cs | 21 + .../MainWindow/MainWindowViewModel.cs | 20 + .../SemiPlot.UI/MainWindow/TrendWindow.cs | 2 +- .../Minimap/ArchivePresenceFeed.cs | 277 ++++++ .../SemiPlot.UI/Minimap/DayCalendarView.axaml | 31 + .../Minimap/DayCalendarView.axaml.cs | 152 ++++ .../SemiPlot.UI/Minimap/MinimapBandFeed.cs | 76 +- .../SemiPlot.UI/Minimap/MinimapConverters.cs | 13 + .../SemiPlot.UI/Minimap/MinimapDayCalendar.cs | 181 ++++ SemiPlot/SemiPlot.UI/Minimap/MinimapHint.cs | 30 + SemiPlot/SemiPlot.UI/Minimap/MinimapLabels.cs | 107 +++ SemiPlot/SemiPlot.UI/Minimap/MinimapPager.cs | 198 +++++ .../SemiPlot.UI/Minimap/MinimapRunShading.cs | 63 ++ .../Minimap/MinimapView.DetailTrack.cs | 202 +++++ .../SemiPlot.UI/Minimap/MinimapView.axaml | 112 ++- .../SemiPlot.UI/Minimap/MinimapView.axaml.cs | 227 +---- .../SemiPlot.UI/Minimap/MinimapViewModel.cs | 211 ++--- SemiPlot/SemiPlot.UI/Minimap/TrackLabels.cs | 62 ++ SemiPlot/SemiPlot.UI/Minimap/TrackPointer.cs | 79 ++ .../Navigation/NavigationBarView.axaml | 87 +- .../Navigation/NavigationBarView.axaml.cs | 41 + .../Navigation/NavigationBarViewModel.cs | 185 ++++ .../Navigation/NavigationListRow.cs | 87 ++ .../Navigation/NavigationListRows.cs | 87 ++ .../Navigation/NavigationListView.axaml | 134 +++ .../Navigation/NavigationListView.axaml.cs | 121 +++ .../Navigation/NavigationListViewModel.cs | 130 +++ .../SemiPlot.UI/Navigation/NavigationSteps.cs | 84 ++ .../Navigation/SequenceComparer.cs | 16 + .../SemiPlot.UI/Navigation/WindowGestures.cs | 57 ++ SemiPlot/SemiPlot.UI/Styles/Buttons.axaml | 24 + SemiPlot/SemiPlot.UI/Styles/Icons.axaml | 4 + SemiPlot/SemiPlot.UI/Styles/Palette.axaml | 6 + SemiPlot/SemiPlot.UI/Styles/ToolTips.axaml | 11 + docs/architecture/bench.md | 70 +- docs/architecture/charting.md | 42 +- docs/architecture/data-integration.md | 83 +- docs/architecture/overview.md | 16 +- docs/architecture/testing-strategy.md | 9 +- docs/architecture/trend-feature-spec.md | 8 +- docs/architecture/trend-interaction.md | 688 +++++++++++--- docs/architecture/ui-text.md | 95 +- docs/architecture/ui-theme.md | 112 ++- docs/plans/backlog.md | 47 +- .../completed/20261110-two-track-minimap.md | 840 ++++++++++++++++++ readme.md | 19 +- 108 files changed, 12092 insertions(+), 1226 deletions(-) create mode 100644 SemiPlot/SemiPlot.Core/Data/ArchiveDaySpan.cs create mode 100644 SemiPlot/SemiPlot.Core/Trends/DayCalendar.cs create mode 100644 SemiPlot/SemiPlot.Core/Trends/DayCalendarLabels.cs create mode 100644 SemiPlot/SemiPlot.Core/Trends/MarkerNavigation.cs create mode 100644 SemiPlot/SemiPlot.Core/Trends/MinimapPage.cs create mode 100644 SemiPlot/SemiPlot.Core/Trends/MinimapTrackGeometry.cs create mode 100644 SemiPlot/SemiPlot.Core/Trends/SortedSearch.cs create mode 100644 SemiPlot/SemiPlot.Tests.Integration/PostgresArchiveDaySpansReadTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/Core/Trends/BerlinClock.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarLabelsTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/Core/Trends/DayCalendarTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerNavigationTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapPageTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MinimapTrackGeometryTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/WindowGestureTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/ArchivePresenceFeedTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/MinimapDetailTrackTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/MinimapLabelsTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/MinimapPagerTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Navigation/NavigationBarStand.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Navigation/NavigationListRowsTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Navigation/NavigationListViewModelTests.cs create mode 100644 SemiPlot/SemiPlot.Tests.Unit/UI/Navigation/NavigationListViewTests.cs create mode 100644 SemiPlot/SemiPlot.UI/Localization/CountForms.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/ArchivePresenceFeed.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml create mode 100644 SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/MinimapConverters.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/MinimapDayCalendar.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/MinimapHint.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/MinimapLabels.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/MinimapPager.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/MinimapRunShading.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/MinimapView.DetailTrack.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/TrackLabels.cs create mode 100644 SemiPlot/SemiPlot.UI/Minimap/TrackPointer.cs create mode 100644 SemiPlot/SemiPlot.UI/Navigation/NavigationListRow.cs create mode 100644 SemiPlot/SemiPlot.UI/Navigation/NavigationListRows.cs create mode 100644 SemiPlot/SemiPlot.UI/Navigation/NavigationListView.axaml create mode 100644 SemiPlot/SemiPlot.UI/Navigation/NavigationListView.axaml.cs create mode 100644 SemiPlot/SemiPlot.UI/Navigation/NavigationListViewModel.cs create mode 100644 SemiPlot/SemiPlot.UI/Navigation/NavigationSteps.cs create mode 100644 SemiPlot/SemiPlot.UI/Navigation/SequenceComparer.cs create mode 100644 SemiPlot/SemiPlot.UI/Navigation/WindowGestures.cs create mode 100644 SemiPlot/SemiPlot.UI/Styles/ToolTips.axaml create mode 100644 docs/plans/completed/20261110-two-track-minimap.md 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 + public Control GoMenuHeader => GoMenu; + + /// The Go item whose gesture the key is, or null; the window runs that item's command. + public MenuItem? GoItemFor(KeyEventArgs key) + { + return GoMenu.Items.OfType().FirstOrDefault(item => item.InputGesture?.Matches(key) == true); + } } diff --git a/SemiPlot/SemiPlot.UI/MainWindow/MainWindow.axaml b/SemiPlot/SemiPlot.UI/MainWindow/MainWindow.axaml index 8017b3e..6ace8fa 100644 --- a/SemiPlot/SemiPlot.UI/MainWindow/MainWindow.axaml +++ b/SemiPlot/SemiPlot.UI/MainWindow/MainWindow.axaml @@ -31,7 +31,8 @@ BorderBrush="{DynamicResource AppBorderBrush}" Padding="8,4" IsVisible="{Binding IsNavigationBarVisible}"> - + new CsvExportWindow { DataContext = export }, viewModel.ForgetClosedWindow, viewModel.ReportFailure))); + _requests.Add(viewModel.MarkerListRequests.Subscribe( + _ => NavigationBarContent.ShowMarkerList(MenuBar.GoMenuHeader))); + _requests.Add(viewModel.RecipeRunListRequests.Subscribe( + _ => NavigationBarContent.ShowRecipeRunList(MenuBar.GoMenuHeader))); viewModel.LegendViewModel.FitPanel(MaximumPanelWidth()); } @@ -69,6 +73,23 @@ protected override void OnUnloaded(RoutedEventArgs e) base.OnUnloaded(e); } + /// Runs the Go item a key no control took names, and never one typed into a text box. + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + + if (e.Handled || e.Source is TextBox) + { + return; + } + + if (MenuBar.GoItemFor(e) is { Command: { } command } item && command.CanExecute(item.CommandParameter)) + { + command.Execute(item.CommandParameter); + e.Handled = true; + } + } + private void OnPanelResizeHandleDragDelta(object? sender, VectorEventArgs e) { if (DataContext is MainWindowViewModel viewModel) diff --git a/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs b/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs index 4b9ff64..dd7215c 100644 --- a/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs +++ b/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs @@ -34,6 +34,8 @@ public sealed class MainWindowViewModel : ReactiveObject, IDisposable private readonly Subject _settingsRequests = new(); private readonly Subject _penEditorRequests = new(); private readonly Subject _exportRequests = new(); + private readonly Subject _markerListRequests = new(); + private readonly Subject _recipeRunListRequests = new(); private readonly ILoggerFactory _loggerFactory; private readonly ILogger _logger; @@ -89,6 +91,8 @@ public MainWindowViewModel( _disposables.Add(_settingsRequests); _disposables.Add(_penEditorRequests); _disposables.Add(_exportRequests); + _disposables.Add(_markerListRequests); + _disposables.Add(_recipeRunListRequests); _disposables.Add(ToggleNavigationBarCommand = ReactiveCommand.Create( () => { IsNavigationBarVisible = !IsNavigationBarVisible; })); @@ -111,6 +115,12 @@ public MainWindowViewModel( _disposables.Add(ExportCommand = ReactiveCommand.Create( RequestExport, ChartViewModel.WhenAnyValue(chart => chart.HasNoPens).Select(none => !none))); + _disposables.Add(ShowMarkerListCommand = ReactiveCommand.Create( + () => _markerListRequests.OnNext(Unit.Default), + NavigationBarViewModel.WhenAnyValue(bar => bar.HasOperatorMarkers))); + _disposables.Add(ShowRecipeRunListCommand = ReactiveCommand.Create( + () => _recipeRunListRequests.OnNext(Unit.Default), + NavigationBarViewModel.WhenAnyValue(bar => bar.HasRecipeRunEntries))); } /// The process-wide panel, owned by the container and shown in the window's panel row. @@ -130,6 +140,10 @@ public MainWindowViewModel( public IObservable ExportRequests => _exportRequests.AsObservable(); + public IObservable MarkerListRequests => _markerListRequests.AsObservable(); + + public IObservable RecipeRunListRequests => _recipeRunListRequests.AsObservable(); + public bool IsNavigationBarVisible { get; @@ -189,6 +203,12 @@ public bool IsMinimapVisible /// Snapshots the visible window and the pens into a request on ExportRequests. public ReactiveCommand ExportCommand { get; } + /// Asks the window for the operator marker list; enabled while the list holds a marker. + public ReactiveCommand ShowMarkerListCommand { get; } + + /// Asks the window for the recipe run list; enabled while the list holds a run. + public ReactiveCommand ShowRecipeRunListCommand { get; } + /// The window's own code-behind route to the panel, for a throw it cannot let escape. public void ReportFailure(Exception failure) { diff --git a/SemiPlot/SemiPlot.UI/MainWindow/TrendWindow.cs b/SemiPlot/SemiPlot.UI/MainWindow/TrendWindow.cs index e9ebb82..6079812 100644 --- a/SemiPlot/SemiPlot.UI/MainWindow/TrendWindow.cs +++ b/SemiPlot/SemiPlot.UI/MainWindow/TrendWindow.cs @@ -98,7 +98,7 @@ public static TrendWindow Build( chart.ApplyCatalogue(startupData.Catalogue.Pens); var minimapLogger = loggerFactory.CreateLogger(); - var minimap = new MinimapViewModel(coordinator, chart, uiScheduler, messagePanel, minimapLogger); + var minimap = new MinimapViewModel(coordinator, chart, uiScheduler, archiveZone, messagePanel, minimapLogger); var catalogueSync = new PenCatalogueSync( dataProvider, startupData.Catalogue, diff --git a/SemiPlot/SemiPlot.UI/Minimap/ArchivePresenceFeed.cs b/SemiPlot/SemiPlot.UI/Minimap/ArchivePresenceFeed.cs new file mode 100644 index 0000000..ed0a4e7 --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/ArchivePresenceFeed.cs @@ -0,0 +1,277 @@ +using System.Diagnostics; +using System.Reactive.Concurrency; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using System.Reactive.Subjects; + +using FluentResults; + +using Microsoft.Extensions.Logging; + +using ReactiveUI; + +using SemiPlot.Core.Data; +using SemiPlot.UI.Bridge; +using SemiPlot.UI.Chart; +using SemiPlot.UI.Messages; + +namespace SemiPlot.UI.Minimap; + +/// +/// Reads which archive wall-clock days hold rows over the strip's extent, and when each day's samples start +/// and end (docs/architecture/trend-interaction.md#archive-overview-minimap). +/// +public sealed class ArchivePresenceFeed : ReactiveObject, IDisposable +{ + private static readonly TimeSpan _failedReadRetryInterval = TimeSpan.FromSeconds(60.0); + + private readonly TrendCoordinator _coordinator; + private readonly ChartNavigationController _navigation; + private readonly TimeZoneInfo _archiveZone; + private readonly IScheduler _uiScheduler; + private readonly MessagePanelViewModel _messagePanel; + private readonly ILogger _logger; + private readonly OutageReport _outage; + private readonly CompositeDisposable _disposables = []; + private readonly Subject _requests = new(); + + private DateOnly? _firstDay; + private DateOnly _lastDay; + private DateOnly? _completeThrough; + private SpansRequest? _readInFlight; + private bool _isRetryArmed; + private DateTimeOffset _nextRetry = DateTimeOffset.MinValue; + + internal ArchivePresenceFeed( + TrendCoordinator coordinator, + ChartNavigationController navigation, + TimeZoneInfo archiveZone, + IScheduler uiScheduler, + MessagePanelViewModel messagePanel, + ILogger logger) + { + _coordinator = coordinator; + _navigation = navigation; + _archiveZone = archiveZone; + _uiScheduler = uiScheduler; + _messagePanel = messagePanel; + _logger = logger; + _outage = new OutageReport("archive day spans read", messagePanel, logger); + + _disposables.Add(SubscribeToReads()); + _disposables.Add(_requests); + } + + /// + /// The days of the extent that hold rows, ascending; the newest day's last sample follows the live edge. + /// + public IReadOnlyList Spans + { + get; + private set => this.RaiseAndSetIfChanged(ref field, value); + } = []; + + /// True from an applied extent until its first read lands or fails; page steps wait for it. + public bool IsExtentReadPending + { + get; + private set => this.RaiseAndSetIfChanged(ref field, value); + } + + public void Dispose() + { + _disposables.Dispose(); + } + + /// Reads every day of an applied extent, in place of the read in flight. + public void ReadExtent(DateTime firstUtc, DateTime lastUtc) + { + var firstDay = DayOf(firstUtc); + _firstDay = firstDay; + _lastDay = DayOf(lastUtc); + _completeThrough = null; + IsExtentReadPending = true; + Request(firstDay); + } + + /// + /// Extends the newest day to the newest sample; reads past the complete days on a new day or a due retry. + /// + public void FollowNewestSample() + { + if (_firstDay is not { } firstDay || _navigation.NewestSample is not { } newestSample) + { + return; + } + + Spans = ExtendedToNewestSample(Spans); + var newestDay = DayOf(newestSample); + _lastDay = newestDay > _lastDay ? newestDay : _lastDay; + + if (_readInFlight is not null) + { + return; + } + + if (_isRetryArmed) + { + if (_uiScheduler.Now < _nextRetry) + { + return; + } + + _nextRetry = _uiScheduler.Now + _failedReadRetryInterval; + Request(_completeThrough ?? firstDay); + + return; + } + + if (_completeThrough is not { } completeThrough || _lastDay > completeThrough) + { + Request(_completeThrough ?? firstDay); + } + } + + private DateOnly DayOf(DateTime utc) + { + return ArchiveClock.DayOf(utc, _archiveZone); + } + + private void Request(DateOnly firstDay) + { + var request = new SpansRequest(firstDay, _lastDay); + _readInFlight = request; + _requests.OnNext(request); + } + + private IDisposable SubscribeToReads() + { + return _requests + .Select(Read) + .Switch() + .ObserveOn(_uiScheduler) + .Subscribe(ApplyRead, ReportFailure); + } + + private IObservable Read(SpansRequest request) + { + return Observable.Create(async (observer, cancellation) => + observer.OnNext(new LandedRead(request, await ReadAsync(request, cancellation)))); + } + + /// Never throws: a thrown read comes back as a failed result and cannot end the pipeline. + private async Task>> ReadAsync( + SpansRequest request, + CancellationToken cancellation) + { + var started = Stopwatch.GetTimestamp(); + Result> result; + + try + { + result = await _coordinator.QueryArchiveDaySpansAsync(request.FirstDay, request.LastDay, cancellation); + } + catch (Exception readFailure) + { + result = Result.Fail(new ExceptionalError(readFailure)); + } + + _logger.LogDebug( + "The archive day spans read {FirstDay} to {LastDay} in {Elapsed}", + request.FirstDay, + request.LastDay, + Stopwatch.GetElapsedTime(started)); + + return result; + } + + private void ApplyRead(LandedRead read) + { + var isSuperseded = !ReferenceEquals(read.Request, _readInFlight); + if (isSuperseded) + { + return; + } + + _readInFlight = null; + IsExtentReadPending = false; + + try + { + ApplyResult(read.Request, read.Result); + } + catch (Exception applyFailure) + { + ReportFailure(applyFailure); + } + } + + private void ApplyResult(SpansRequest request, Result> result) + { + if (result.IsFailed) + { + _isRetryArmed = true; + _outage.Failed(result.Errors); + + return; + } + + _isRetryArmed = false; + _outage.Succeeded(); + _completeThrough = request.LastDay; + Spans = ExtendedToNewestSample(Merged(Spans, request.FirstDay, result.Value)); + } + + /// The held spans from the extent's first day to the read's first day, followed by the read. + private IReadOnlyList Merged( + IReadOnlyList held, + DateOnly firstDay, + IReadOnlyList read) + { + var merged = new List(held.Count + read.Count); + foreach (var span in held) + { + if (span.Day >= _firstDay && span.Day < firstDay) + { + merged.Add(span); + } + } + + merged.AddRange(read); + + return merged; + } + + /// A newest sample on a day no read has covered holds that day until a read replaces it. + private IReadOnlyList ExtendedToNewestSample(IReadOnlyList spans) + { + if (_navigation.NewestSample is not { } newestSample + || spans is not [.., var newest] + || newestSample <= newest.LastUtc) + { + return spans; + } + + var newestDay = DayOf(newestSample); + if (newestDay != newest.Day) + { + return newestDay > _completeThrough + ? [.. spans, new ArchiveDaySpan(newestDay, newestSample, newestSample)] + : spans; + } + + var extended = spans.ToArray(); + extended[^1] = newest with { LastUtc = newestSample }; + + return extended; + } + + private void ReportFailure(Exception failure) + { + _messagePanel.TryReportFailure(new ExceptionalError(failure), _logger); + } + + private sealed record SpansRequest(DateOnly FirstDay, DateOnly LastDay); + + private sealed record LandedRead(SpansRequest Request, Result> Result); +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml b/SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml new file mode 100644 index 0000000..70cd3b4 --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml @@ -0,0 +1,31 @@ + + + + + + + + + diff --git a/SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml.cs b/SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml.cs new file mode 100644 index 0000000..80c2ae5 --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/DayCalendarView.axaml.cs @@ -0,0 +1,152 @@ +using System.Reactive.Disposables; +using System.Reactive.Linq; + +using Avalonia; +using Avalonia.Controls; + +using ReactiveUI; + +using SemiPlot.Core.Trends; +using SemiPlot.UI.Navigation; + +namespace SemiPlot.UI.Minimap; + +/// The day calendar over the extent, its labels, its hover and its press. +public partial class DayCalendarView : UserControl +{ + private readonly CompositeDisposable _disposables = []; + private DayCalendar? _calendar; + private IReadOnlyDictionary _markerCountsByDay = new Dictionary(); + // Measured from the row's right end, where the cells hang, so a resize keeps the ring on its cell. + private double? _hoverFromRight; + + public DayCalendarView() + { + InitializeComponent(); + + _ = new TrackPointer(CalendarCellRow, NavigateToX, HoverAt); + + DataContextChanged += OnDataContextChanged; + } + + private void OnDataContextChanged(object? sender, EventArgs e) + { + _disposables.Clear(); + + if (DataContext is MinimapViewModel viewModel) + { + _disposables.Add(FollowCalendar(viewModel)); + } + } + + /// Assigns the cells only when they change, so a live sample redraws them across a step only. + private CompositeDisposable FollowCalendar(MinimapViewModel viewModel) + { + var calendars = viewModel + .WhenAnyValue(model => model.HasExtent, model => model.ExtentFirst, model => model.ExtentLast) + .CombineLatest( + CalendarCellRow.GetObservable(BoundsProperty), + (_, bounds) => viewModel.Calendar(bounds.Width)) + .DistinctUntilChanged() + .Replay(1) + .RefCount(); + var pager = viewModel.Pager; + var spans = viewModel.PresenceFeed.WhenAnyValue(feed => feed.Spans); + var hours = pager + .WhenAnyValue(model => model.Page) + .Select(page => page.Hours) + .DistinctUntilChanged(); + + return new CompositeDisposable( + calendars.Subscribe(ApplyCalendar), + calendars + .CombineLatest(spans, hours) + .Select(change => change.First is { } calendar + ? calendar.Cells(change.Second, change.Third, viewModel.ArchiveZone) + : []) + .DistinctUntilChanged(SequenceComparer.Instance) + .Subscribe(cells => CalendarCells.Cells = cells), + calendars + .CombineLatest(pager.WhenAnyValue(model => model.Page)) + .Subscribe(change => CalendarCells.PageOutline = change.First?.PageOutline(change.Second)), + calendars + .CombineLatest(viewModel.WhenAnyValue(model => model.OperatorMarkerTimes)) + .Subscribe(change => CalendarCells.MarkerTicks = + change.First?.MarkerTicks(change.Second, viewModel.ArchiveZone) ?? []), + viewModel + .WhenAnyValue(model => model.OperatorMarkerTimes) + .Subscribe(times => + { + _markerCountsByDay = DayCalendar.MarkerCountsByDay(times, viewModel.ArchiveZone); + PlaceHover(); + }), + spans.Subscribe(_ => PlaceHover())); + } + + private void ApplyCalendar(DayCalendar? calendar) + { + _calendar = calendar; + CalendarCells.MonthSeparators = calendar?.MonthSeparators() ?? []; + LayoutLabels(calendar); + PlaceHover(); + } + + /// Measures every candidate on the row, so the row's text style applies, and keeps those that fit. + private void LayoutLabels(DayCalendar? shown) + { + CalendarLabels.Children.Clear(); + if (shown is not { } calendar) + { + return; + } + + var candidates = DayCalendarLabels.Candidates(calendar); + var blocks = candidates.Select(label => new TextBlock { Text = MinimapLabels.Calendar(label) }).ToList(); + CalendarLabels.Children.AddRange(blocks); + var widths = blocks.Select(TrackLabels.MeasuredWidth).ToList(); + var fitted = DayCalendarLabels.Fitted(candidates, widths, calendar.Right); + CalendarLabels.Children.Clear(); + foreach (var label in fitted) + { + Canvas.SetLeft(blocks[label.Index], label.Left); + CalendarLabels.Children.Add(blocks[label.Index]); + } + } + + /// Rings the cell under the pointer and names its day, rows and markers in the row's tooltip. + private void PlaceHover() + { + if (_hoverFromRight is not { } fromRight + || _calendar is not { } calendar + || DataContext is not MinimapViewModel viewModel + || calendar.DayAt(calendar.Right - fromRight) is not { } day) + { + CalendarCells.HoveredCell = null; + ToolTip.SetTip(CalendarCellRow, null); + + return; + } + + CalendarCells.HoveredCell = calendar.Cell(calendar.IndexOf(day)); + var span = viewModel.PresenceFeed.Spans.FirstOrDefault(candidate => candidate.Day == day); + var tip = MinimapLabels.DayTip(day, span, _markerCountsByDay.GetValueOrDefault(day), viewModel.ArchiveZone); + if (!Equals(ToolTip.GetTip(CalendarCellRow), tip)) + { + ToolTip.SetTip(CalendarCellRow, tip); + } + } + + private void HoverAt(double? x) + { + _hoverFromRight = CalendarCellRow.Bounds.Width - x; + PlaceHover(); + } + + private void NavigateToX(double x) + { + if (DataContext is MinimapViewModel viewModel && _calendar?.DayAt(x) is { } day) + { + viewModel.Pager.NavigateToArchiveDay(day); + } + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapBandFeed.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapBandFeed.cs index 83780ea..e499770 100644 --- a/SemiPlot/SemiPlot.UI/Minimap/MinimapBandFeed.cs +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapBandFeed.cs @@ -18,13 +18,14 @@ namespace SemiPlot.UI.Minimap; /// -/// Reads the drawn pen's overview over the strip's bounds and publishes it with the pen's colour -/// (docs/architecture/trend-interaction.md#archive-overview-minimap). +/// Reads the drawn pen's overview over the pager's page at the strip's width and publishes it with the pen's +/// colour (docs/architecture/trend-interaction.md#archive-overview-minimap). /// public sealed class MinimapBandFeed : ReactiveObject, IDisposable { - /// Below HistoryColumnTarget.MinColumns, so no chart read asks for it. - internal const int MinimapColumns = 250; + internal const int ColumnStep = 250; + + internal const int MaximumColumns = 2500; private const double ReadDelayDivisor = 1000.0; private static readonly TimeSpan _fastestRead = TimeSpan.FromSeconds(2.0); @@ -32,7 +33,8 @@ public sealed class MinimapBandFeed : ReactiveObject, IDisposable private readonly TrendCoordinator _coordinator; private readonly TrendChartViewModel _chart; - private readonly Func<(DateTime First, DateTime Last)?> _readBounds; + private readonly MinimapPager _pager; + private readonly Func _hasExtent; private readonly IScheduler _uiScheduler; private readonly MessagePanelViewModel _messagePanel; private readonly ILogger _logger; @@ -44,18 +46,21 @@ public sealed class MinimapBandFeed : ReactiveObject, IDisposable private BandRequest? _latestRequest; private AggregationLayer _layer; + private int _columns = ColumnStep; internal MinimapBandFeed( TrendCoordinator coordinator, TrendChartViewModel chart, - Func<(DateTime First, DateTime Last)?> readBounds, + MinimapPager pager, + Func hasExtent, IScheduler uiScheduler, MessagePanelViewModel messagePanel, ILogger logger) { _coordinator = coordinator; _chart = chart; - _readBounds = readBounds; + _pager = pager; + _hasExtent = hasExtent; _uiScheduler = uiScheduler; _messagePanel = messagePanel; _logger = logger; @@ -65,16 +70,24 @@ internal MinimapBandFeed( _disposables.Add(_nextRead); _disposables.Add(_requests); _disposables.Add(ReadOnDrawnPenChange()); + _disposables.Add(ReadOnPageChange()); _disposables.Add(DrawnPenColor().ToProperty(this, feed => feed.BandColor, out _bandColor)); } - /// The drawn pen's overview over the strip; null with no drawn pen, no bounds or no rows. + /// The drawn pen's overview over the page; null with no drawn pen, no extent or no rows. public PenHistoryEnvelope? Band { get; private set => this.RaiseAndSetIfChanged(ref field, value); } + /// True from a failed read until the next read lands; the band it held stays as it was. + public bool HasReadFailed + { + get; + private set => this.RaiseAndSetIfChanged(ref field, value); + } + /// The drawn pen's stored colour, followed live; null with no drawn pen. public string? BandColor => _bandColor.Value; @@ -83,6 +96,26 @@ public void Dispose() _disposables.Dispose(); } + /// Reads at the strip width's column count; a width inside the same 250 px step reads nothing. + public void SetStripWidth(double stripWidth) + { + var columns = ColumnsForWidth(stripWidth); + if (columns == _columns) + { + return; + } + + _columns = columns; + RequestRead(); + } + + internal static int ColumnsForWidth(double stripWidth) + { + var steps = (int)Math.Round(stripWidth / ColumnStep, MidpointRounding.AwayFromZero); + + return Math.Clamp(steps * ColumnStep, ColumnStep, MaximumColumns); + } + /// Reads the band now, in place of the read in flight and the scheduled one. public void RequestRead() { @@ -92,6 +125,11 @@ public void RequestRead() Band = null; } + if (request is null) + { + HasReadFailed = false; + } + _latestRequest = request; _nextRead.Disposable = null; _requests.OnNext(request); @@ -126,6 +164,14 @@ private IDisposable ReadOnDrawnPenChange() .Subscribe(_ => TryRequestRead(), ReportFailure); } + private IDisposable ReadOnPageChange() + { + return _pager + .WhenAnyValue(pager => pager.Page) + .Skip(1) + .Subscribe(_ => TryRequestRead(), ReportFailure); + } + private IObservable DrawnPenColor() { return _chart @@ -138,15 +184,16 @@ private IDisposable ReadOnDrawnPenChange() private BandRequest? NextRequest() { - if (_readBounds() is not { } bounds || _chart.DrawnPenId is not { } penId) + if (!_hasExtent() || _chart.DrawnPenId is not { } penId) { return null; } + var page = _pager.Page; _layer = ChartNavigationController.LayerForWidth( - bounds.Last - bounds.First, _layer, MinimapColumns, visiblePenCount: 1); + page.ToUtc - page.FromUtc, _layer, _columns, visiblePenCount: 1); - return new BandRequest(penId, bounds.First, bounds.Last, _layer); + return new BandRequest(penId, page.FromUtc, page.ToUtc, _layer, _columns); } private IObservable Read(BandRequest? request) @@ -166,7 +213,7 @@ private IObservable Read(BandRequest? request) try { var read = await _coordinator.QueryHistoryAsync( - [request.PenId], request.FromUtc, request.ToUtc, request.Layer, MinimapColumns, cancellation); + [request.PenId], request.FromUtc, request.ToUtc, request.Layer, request.Columns, cancellation); result = read.Map(envelopes => envelopes.FirstOrDefault(envelope => envelope.PenId == request.PenId)); } catch (Exception readFailure) @@ -177,7 +224,7 @@ private IObservable Read(BandRequest? request) _logger.LogDebug( "The minimap band read {Layer} at {Columns} columns in {Elapsed}", request.Layer, - MinimapColumns, + request.Columns, Stopwatch.GetElapsedTime(started)); return result; @@ -212,6 +259,7 @@ internal static TimeSpan NextReadDelay(TimeSpan span) private void ApplyResult(Result result) { + HasReadFailed = result.IsFailed; if (result.IsFailed) { _outage.Failed(result.Errors); @@ -228,7 +276,7 @@ private void ReportFailure(Exception failure) _messagePanel.TryReportFailure(new ExceptionalError(failure), _logger); } - private sealed record BandRequest(int PenId, DateTime FromUtc, DateTime ToUtc, AggregationLayer Layer); + private sealed record BandRequest(int PenId, DateTime FromUtc, DateTime ToUtc, AggregationLayer Layer, int Columns); private sealed record LandedRead(BandRequest Request, Result Result); } diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapConverters.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapConverters.cs new file mode 100644 index 0000000..4af2cc2 --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapConverters.cs @@ -0,0 +1,13 @@ +using Avalonia.Data.Converters; + +using SemiPlot.Core.Trends; + +namespace SemiPlot.UI.Minimap; + +public static class MinimapConverters +{ + public static readonly FuncValueConverter IsWeek = new(unit => unit == MinimapPageUnit.Week); + + public static readonly FuncValueConverter IsMonth = + new(unit => unit == MinimapPageUnit.Month); +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapDayCalendar.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapDayCalendar.cs new file mode 100644 index 0000000..f94d7dc --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapDayCalendar.cs @@ -0,0 +1,181 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; + +using SemiPlot.Core.Trends; + +using Pen = Avalonia.Media.Pen; + +namespace SemiPlot.UI.Minimap; + +/// +/// The day calendar's cells, month separators, page outline, hovered cell and marker ticks +/// (docs/architecture/trend-interaction.md#archive-overview-minimap). +/// +public sealed class MinimapDayCalendar : Control +{ + public static readonly StyledProperty> CellsProperty = + AvaloniaProperty.Register>(nameof(Cells), []); + + public static readonly StyledProperty PageOutlineProperty = + AvaloniaProperty.Register(nameof(PageOutline)); + + public static readonly StyledProperty HoveredCellProperty = + AvaloniaProperty.Register(nameof(HoveredCell)); + + public static readonly StyledProperty> MarkerTicksProperty = + AvaloniaProperty.Register>(nameof(MarkerTicks), []); + + public static readonly StyledProperty> MonthSeparatorsProperty = + AvaloniaProperty.Register>(nameof(MonthSeparators), []); + + public static readonly StyledProperty PresenceBrushProperty = + AvaloniaProperty.Register(nameof(PresenceBrush)); + + public static readonly StyledProperty AccentBrushProperty = + AvaloniaProperty.Register(nameof(AccentBrush)); + + public static readonly StyledProperty HoverBrushProperty = + AvaloniaProperty.Register(nameof(HoverBrush)); + + public static readonly StyledProperty SeparatorBrushProperty = + AvaloniaProperty.Register(nameof(SeparatorBrush)); + + public static readonly StyledProperty MarkerBrushProperty = + AvaloniaProperty.Register(nameof(MarkerBrush)); + + // The cells sit under the 2 px marker ticks with room for the outline's stroke between, in the 16 px row. + private const double CellTop = 4.0; + private const double CellHeight = 10.0; + private const double MarkerTickHeight = 2.0; + private const double HoverStroke = 1.0; + + static MinimapDayCalendar() + { + AffectsRender( + CellsProperty, + PageOutlineProperty, + HoveredCellProperty, + MarkerTicksProperty, + MonthSeparatorsProperty, + PresenceBrushProperty, + AccentBrushProperty, + HoverBrushProperty, + SeparatorBrushProperty, + MarkerBrushProperty); + } + + public IReadOnlyList Cells + { + get => GetValue(CellsProperty); + set => SetValue(CellsProperty, value); + } + + public TrackSpan? PageOutline + { + get => GetValue(PageOutlineProperty); + set => SetValue(PageOutlineProperty, value); + } + + public TrackSpan? HoveredCell + { + get => GetValue(HoveredCellProperty); + set => SetValue(HoveredCellProperty, value); + } + + public IReadOnlyList MarkerTicks + { + get => GetValue(MarkerTicksProperty); + set => SetValue(MarkerTicksProperty, value); + } + + public IReadOnlyList MonthSeparators + { + get => GetValue(MonthSeparatorsProperty); + set => SetValue(MonthSeparatorsProperty, value); + } + + public IBrush? PresenceBrush + { + get => GetValue(PresenceBrushProperty); + set => SetValue(PresenceBrushProperty, value); + } + + public IBrush? AccentBrush + { + get => GetValue(AccentBrushProperty); + set => SetValue(AccentBrushProperty, value); + } + + public IBrush? HoverBrush + { + get => GetValue(HoverBrushProperty); + set => SetValue(HoverBrushProperty, value); + } + + public IBrush? SeparatorBrush + { + get => GetValue(SeparatorBrushProperty); + set => SetValue(SeparatorBrushProperty, value); + } + + public IBrush? MarkerBrush + { + get => GetValue(MarkerBrushProperty); + set => SetValue(MarkerBrushProperty, value); + } + + public override void Render(DrawingContext context) + { + if (SeparatorBrush is { } separatorBrush) + { + foreach (var x in MonthSeparators) + { + context.FillRectangle(separatorBrush, new Rect(x, 0.0, DayCalendar.SeparatorWidth, Bounds.Height)); + } + } + + if (PresenceBrush is { } presenceBrush) + { + foreach (var cell in Cells) + { + using (context.PushOpacity(OpacityOf(cell.Coverage))) + { + context.FillRectangle(presenceBrush, new Rect(cell.Left, CellTop, cell.Width, CellHeight)); + } + } + } + + if (AccentBrush is { } accentBrush && PageOutline is { } outline) + { + var stroke = DayCalendar.OutlineStroke; + var ring = new Rect(outline.Left, CellTop - stroke, outline.Width, CellHeight + (2.0 * stroke)); + context.DrawRectangle(new Pen(accentBrush, stroke), ring.Deflate(stroke / 2.0)); + } + + if (HoverBrush is { } hoverBrush && HoveredCell is { } hovered) + { + var cell = new Rect(hovered.Left, CellTop, hovered.Width, CellHeight); + context.DrawRectangle(new Pen(hoverBrush, HoverStroke), cell.Deflate(HoverStroke / 2.0)); + } + + if (MarkerBrush is { } markerBrush) + { + foreach (var tick in MarkerTicks) + { + context.FillRectangle(markerBrush, new Rect(tick.Left, 0.0, tick.Width, MarkerTickHeight)); + } + } + } + + /// The fill opacity of a cell: three steps, so a short day reads apart from a full one. + private static double OpacityOf(DayCoverage coverage) + { + return coverage switch + { + DayCoverage.Low => 0.35, + DayCoverage.Medium => 0.65, + _ => 1.0 + }; + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapHint.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapHint.cs new file mode 100644 index 0000000..ec644ef --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapHint.cs @@ -0,0 +1,30 @@ +using SemiPlot.Core.Data; +using SemiPlot.Core.Trends; +using SemiPlot.UI.Localization; + +namespace SemiPlot.UI.Minimap; + +/// The detail track's hint for a state its band cannot show; null while the band speaks for itself. +internal static class MinimapHint +{ + public static string? For( + bool isArchiveEmpty, + bool hasExtent, + MinimapPage page, + IReadOnlyList spans, + bool hasBandReadFailed) + { + if (!hasExtent) + { + return isArchiveEmpty ? Resources.MinimapNoRowsInArchive : null; + } + + // Without spans the day list is unknown, so no page is declared empty. + if (spans.Count > 0 && !spans.Any(span => page.Holds(span.Day))) + { + return Resources.FormatMinimapNoRowsOn(MinimapLabels.Page(page)); + } + + return hasBandReadFailed ? Resources.MinimapBandNotRead : null; + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapLabels.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapLabels.cs new file mode 100644 index 0000000..aa169cd --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapLabels.cs @@ -0,0 +1,107 @@ +using System.Globalization; + +using SemiPlot.Core.Data; +using SemiPlot.Core.Trends; +using SemiPlot.UI.Localization; + +namespace SemiPlot.UI.Minimap; + +/// +/// The minimap's date labels, in the machine culture's names; a day number makes Russian months genitive. +/// +internal static class MinimapLabels +{ + private const string DayFormat = "ddd d MMM yyyy"; + private const string WeekdayAndDateFormat = "ddd d MMM"; + private const string MonthFormat = "MMM"; + private const string MonthNameFormat = "MMMM"; + private const string YearFormat = "yyyy"; + private const string DayOfMonthFormat = "%d"; + private const string DayAndMonthFormat = "d MMM"; + private const string DateFormat = "d MMM yyyy"; + private const string HourTickFormat = "HH:mm"; + private const string DayTickFormat = "ddd d"; + private const string WeekHoverFormat = "ddd d HH:mm"; + + /// An archive wall-clock day, Fri 14 Aug 2026. + public static string Day(DateOnly day) + { + return day.ToString(DayFormat, CultureInfo.CurrentCulture); + } + + /// + /// A Day page as its day, Fri 14 Aug 2026; a Week page as its days inclusive, 11-17 May 2026; a + /// Month page as its month, November 2026; each with the year of its last day. + /// + public static string Page(MinimapPage page) + { + var culture = CultureInfo.CurrentCulture; + var (first, last) = (page.FirstDay, page.EndDay.AddDays(-1)); + var year = " " + last.ToString(YearFormat, culture); + if (page.Unit != MinimapPageUnit.Week) + { + var format = page.Unit == MinimapPageUnit.Day ? WeekdayAndDateFormat : MonthNameFormat; + + return first.ToString(format, culture) + year; + } + + var lastText = last.ToString(DayAndMonthFormat, culture); + if (first.Year != last.Year) + { + return first.ToString(DateFormat, culture) + " - " + lastText + year; + } + + return first.Month != last.Month + ? first.ToString(DayAndMonthFormat, culture) + " - " + lastText + year + : first.ToString(DayOfMonthFormat, culture) + "-" + lastText + year; + } + + /// An hour tick as 07:00, a day tick as Mon 11. + public static string Tick(TrackTick tick) + { + var format = tick.Kind == TrackTickKind.Hour ? HourTickFormat : DayTickFormat; + + return tick.WallClock.ToString(format, CultureInfo.CurrentCulture); + } + + /// A calendar day label as Mon 11, a month label as Aug. + public static string Calendar(CalendarLabel label) + { + var format = label.Kind == CalendarLabelKind.Day ? DayTickFormat : MonthFormat; + + return label.Day.ToString(format, CultureInfo.CurrentCulture); + } + + /// + /// A calendar day's tooltip: the day, then its first and last sample or that it holds no rows, then the count of + /// its operator markers when it holds any. + /// + public static string DayTip(DateOnly day, ArchiveDaySpan? span, int markerCount, TimeZoneInfo zone) + { + var culture = CultureInfo.CurrentCulture; + var tip = span is null + ? Resources.FormatMinimapDayNoRowsTip(Day(day)) + : Resources.FormatMinimapDayRowsTip( + Day(day), + ArchiveClock.WallClockOf(span.FirstUtc, zone).ToString(HourTickFormat, culture), + ArchiveClock.WallClockOf(span.LastUtc, zone).ToString(HourTickFormat, culture)); + + return markerCount > 0 + ? Resources.FormatMinimapDayMarkersTip( + tip, + CountForms.Pick( + markerCount, + Resources.FormatMinimapMarkerCountOne(markerCount), + Resources.FormatMinimapMarkerCountFew(markerCount), + Resources.FormatMinimapMarkerCountMany(markerCount))) + : tip; + } + + /// The wall-clock time under the pointer: the clock on a Day page, else the day and clock. + public static string HoverTime(DateTime wallClock, MinimapPageUnit unit) + { + var format = unit == MinimapPageUnit.Day ? HourTickFormat : WeekHoverFormat; + + return wallClock.ToString(format, CultureInfo.CurrentCulture); + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapPager.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapPager.cs new file mode 100644 index 0000000..26c09a3 --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapPager.cs @@ -0,0 +1,198 @@ +using System.Reactive; +using System.Reactive.Disposables; +using System.Reactive.Linq; + +using ReactiveUI; + +using SemiPlot.Core.Data; +using SemiPlot.Core.Trends; +using SemiPlot.UI.Chart; + +namespace SemiPlot.UI.Minimap; + +/// +/// The detail track's page under the chart window, and the steps that turn it and land the chart on data +/// (docs/architecture/trend-interaction.md#archive-overview-minimap). +/// +public sealed class MinimapPager : ReactiveObject, IDisposable +{ + private readonly ChartNavigationController _navigation; + private readonly ArchivePresenceFeed _presence; + private readonly TimeZoneInfo _archiveZone; + private readonly CompositeDisposable _disposables = []; + private readonly ObservableAsPropertyHelper<(DateTime From, DateTime To)> _window; + private readonly ObservableAsPropertyHelper _page; + private readonly ObservableAsPropertyHelper _previousPage; + private readonly ObservableAsPropertyHelper _nextPage; + + internal MinimapPager( + ChartNavigationController navigation, + ArchivePresenceFeed presence, + IObservable<(DateTime First, DateTime Last)?> extents, + TimeZoneInfo archiveZone) + { + _navigation = navigation; + _presence = presence; + _archiveZone = archiveZone; + NewestSample = navigation.NewestSample; + + var pagedSpans = presence + .WhenAnyValue(feed => feed.Spans) + .Select(spans => (Spans: spans, Hours: MinimapPage.WorkingHours(spans, archiveZone))); + + _disposables.Add(Windows().ToProperty(this, pager => pager.Window, out _window)); + _disposables.Add(Windows() + .CombineLatest(pagedSpans, this.WhenAnyValue(pager => pager.NewestSample), PageOf) + .ToProperty(this, pager => pager.Page, out _page)); + _disposables.Add(StepTargets(PageDirection.Previous, extents) + .ToProperty(this, pager => pager.PreviousPage, out _previousPage)); + _disposables.Add(StepTargets(PageDirection.Next, extents) + .ToProperty(this, pager => pager.NextPage, out _nextPage)); + + _disposables.Add(PreviousPageCommand = ReactiveCommand.Create( + () => TurnTo(PreviousPage), + this.WhenAnyValue(pager => pager.PreviousPage).Select(target => target is not null))); + _disposables.Add(NextPageCommand = ReactiveCommand.Create( + () => TurnTo(NextPage), + this.WhenAnyValue(pager => pager.NextPage).Select(target => target is not null))); + } + + /// The chart window the detail track boxes. + public (DateTime From, DateTime To) Window => _window.Value; + + /// + /// The smallest page that holds the chart window up to the newest sample, . + /// + public MinimapPage Page => _page.Value; + + /// The navigation's newest sample as of the last . + public DateTime? NewestSample + { + get; + private set => this.RaiseAndSetIfChanged(ref field, value); + } + + /// The page the previous step lands on; null when no earlier page holds rows. + public MinimapPage? PreviousPage => _previousPage.Value; + + /// The page the next step lands on; null when no later page holds rows. + public MinimapPage? NextPage => _nextPage.Value; + + public ReactiveCommand PreviousPageCommand { get; } + + public ReactiveCommand NextPageCommand { get; } + + public void Dispose() + { + _disposables.Dispose(); + } + + /// + /// Takes the navigation's newest sample; the caller runs it after the day spans follow the sample, so the page + /// never judges a sample its spans do not hold yet. + /// + public void FollowNewestSample() + { + NewestSample = _navigation.NewestSample; + } + + /// + /// Lands the chart on the calendar day when it holds rows, else on the day whose span lies nearer its noon, + /// once the spans are read. + /// + public void NavigateToArchiveDay(DateOnly day) + { + var spans = _presence.Spans; + if (spans.Count == 0 && _presence.IsExtentReadPending) + { + return; + } + + var noonUtc = ArchiveClock.ToUtc(ArchiveClock.Midnight(day).AddHours(DayHours.HoursPerDay / 2), _archiveZone); + var dayTimeUtc = MinimapPage.SnapToData(noonUtc, spans, _archiveZone)?.FirstUtc ?? noonUtc; + TurnTo(MinimapPage.Snap(MinimapPageUnit.Day, dayTimeUtc, Page.Hours, spans, _archiveZone)); + } + + /// Centres the chart window at a page fraction clamped to [0, 1], its start kept on the page. + public void NavigateToPageFraction(double fraction) + { + var page = Page; + var width = _navigation.To - _navigation.From; + var targetUtc = MinimapGeometry.TimeAtFraction(page.FromUtc, page.ToUtc, fraction); + var fromUtc = targetUtc - (width / 2.0); + fromUtc = fromUtc < page.FromUtc ? page.FromUtc : fromUtc; + _navigation.SetWindow(fromUtc, fromUtc + width); + } + + private MinimapPage PageOf( + (DateTime From, DateTime To) window, + (IReadOnlyList Spans, DayHours Hours) paged, + DateTime? newestSample) + { + return MinimapPage.Holding(window.From, window.To, newestSample, paged.Hours, paged.Spans, _archiveZone); + } + + private IObservable<(DateTime From, DateTime To)> Windows() + { + return Observable.Defer(() => Observable + .FromEventPattern( + handler => _navigation.WindowChanged += handler, + handler => _navigation.WindowChanged -= handler) + .Select(change => (change.EventArgs.From, change.EventArgs.To)) + .StartWith((_navigation.From, _navigation.To))); + } + + private IObservable StepTargets( + PageDirection direction, + IObservable<(DateTime First, DateTime Last)?> extents) + { + return this + .WhenAnyValue(pager => pager.Page) + .CombineLatest( + _presence.WhenAnyValue( + feed => feed.Spans, + feed => feed.IsExtentReadPending, + (spans, isReadPending) => (Spans: spans, IsReadPending: isReadPending)), + extents, + (page, presence, extent) => + StepTarget(page, direction, presence.Spans, presence.IsReadPending, extent)); + } + + /// The nearest page with rows; without spans, the calendar neighbour once the first read lands. + private MinimapPage? StepTarget( + MinimapPage page, + PageDirection direction, + IReadOnlyList spans, + bool isReadPending, + (DateTime First, DateTime Last)? extent) + { + if (extent is not { } bounds || (spans.Count == 0 && isReadPending)) + { + return null; + } + + if (spans.Count > 0) + { + return MinimapPage.Step(page, direction, spans, _archiveZone); + } + + // With no spans every page is a whole calendar day, week or month, so its edges lie inside the neighbours. + var insideNeighbourUtc = direction == PageDirection.Next + ? page.ToUtc + : page.FromUtc - TimeSpan.FromTicks(1); + var neighbour = MinimapPage.Snap(page.Unit, insideNeighbourUtc, page.Hours, spans, _archiveZone); + var meetsExtent = neighbour.FromUtc <= bounds.Last && neighbour.ToUtc > bounds.First; + + return meetsExtent ? neighbour : null; + } + + private void TurnTo(MinimapPage? target) + { + if (target is { } page) + { + var (fromUtc, toUtc) = + MinimapPage.Land(_navigation.From, _navigation.To, page, _presence.Spans, _archiveZone); + _navigation.SetWindow(fromUtc, toUtc); + } + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapRunShading.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapRunShading.cs new file mode 100644 index 0000000..ddd7d71 --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapRunShading.cs @@ -0,0 +1,63 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; + +using SemiPlot.Core.Trends; + +namespace SemiPlot.UI.Minimap; + +/// The Day page's recipe runs as full-height shades, an interrupted run's end marked by an edge. +public sealed class MinimapRunShading : Control +{ + public static readonly StyledProperty> ShadesProperty = + AvaloniaProperty.Register>(nameof(Shades), []); + + public static readonly StyledProperty FillBrushProperty = + AvaloniaProperty.Register(nameof(FillBrush)); + + public static readonly StyledProperty EdgeBrushProperty = + AvaloniaProperty.Register(nameof(EdgeBrush)); + + private const double EdgeWidth = 2.0; + + static MinimapRunShading() + { + AffectsRender(ShadesProperty, FillBrushProperty, EdgeBrushProperty); + } + + public IReadOnlyList Shades + { + get => GetValue(ShadesProperty); + set => SetValue(ShadesProperty, value); + } + + public IBrush? FillBrush + { + get => GetValue(FillBrushProperty); + set => SetValue(FillBrushProperty, value); + } + + public IBrush? EdgeBrush + { + get => GetValue(EdgeBrushProperty); + set => SetValue(EdgeBrushProperty, value); + } + + public override void Render(DrawingContext context) + { + var height = Bounds.Height; + foreach (var shade in Shades) + { + if (FillBrush is { } fill) + { + context.FillRectangle(fill, new Rect(shade.Left, 0.0, shade.Width, height)); + } + + if (shade.HasEndEdge && EdgeBrush is { } edge) + { + var edgeWidth = Math.Min(EdgeWidth, shade.Width); + context.FillRectangle(edge, new Rect(shade.Left + shade.Width - edgeWidth, 0.0, edgeWidth, height)); + } + } + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapView.DetailTrack.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapView.DetailTrack.cs new file mode 100644 index 0000000..0ca7931 --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapView.DetailTrack.cs @@ -0,0 +1,202 @@ +using System.Reactive.Disposables; + +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; + +using ReactiveUI; + +using SemiPlot.Core.Data; +using SemiPlot.Core.Trends; + +namespace SemiPlot.UI.Minimap; + +/// The detail track over the pager's page: the chart window, the runs, the ticks and the hover. +public partial class MinimapView +{ + // Floors a sub-pixel window or run so it stays visible. + private const double MinimumHighlightWidth = 6.0; + private const double MinimumRunWidth = 2.0; + private const double WindowBorderWidth = 2.0; + private const double TickLabelGap = 8.0; + + // A week of two-digit days, so the widest day tick label is among them. + private static readonly DateTime _probeMonday = new(2000, 1, 24); + + private readonly Dictionary _tickLabelSpacing = []; + private double? _detailHoverFraction; + + private void AttachDetailTrackInput() + { + _ = new TrackPointer(StripCanvas, NavigateToStripX, HoverStripAt); + } + + private CompositeDisposable FollowDetailTrack(MinimapViewModel viewModel) + { + return new CompositeDisposable( + viewModel + .WhenAnyValue(model => model.HasExtent, model => model.Pager.Page) + .Subscribe(_ => + { + LayoutPageTicks(); + PlaceDetailHover(); + }), + viewModel + .WhenAnyValue(model => model.HasExtent, model => model.Pager.Page, model => model.Pager.Window) + .Subscribe(_ => PlaceWindowBox()), + viewModel + .WhenAnyValue(model => model.HasExtent, model => model.Pager.Page, model => model.OperatorMarkerTimes) + .Subscribe(_ => PlaceTimeMarkerTicks()), + viewModel + .WhenAnyValue(model => model.HasExtent, model => model.Pager.Page, model => model.ShadedRuns) + .Subscribe(_ => LayoutRuns())); + } + + private void LayoutDetailTrack() + { + LayoutRuns(); + PlaceWindowBox(); + PlaceTimeMarkerTicks(); + LayoutPageTicks(); + PlaceDetailHover(); + } + + /// The view model while it has an extent, so the detail track has a page to draw. + private MinimapViewModel? PagedViewModel() + { + return DataContext is MinimapViewModel { HasExtent: true } viewModel ? viewModel : null; + } + + private void LayoutRuns() + { + var (width, height) = (StripCanvas.Bounds.Width, StripCanvas.Bounds.Height); + RunShading.Width = width; + RunShading.Height = height; + RunShading.Shades = PagedViewModel() is { } viewModel + ? MinimapTrackGeometry.RunShades(viewModel.Pager.Page, viewModel.ShadedRuns, width, MinimumRunWidth) + : []; + } + + private void PlaceWindowBox() + { + var viewModel = PagedViewModel(); + var (windowFrom, windowTo) = viewModel?.Pager.Window ?? default; + var box = viewModel is null + ? null + : MinimapTrackGeometry.WindowBox( + viewModel.Pager.Page, windowFrom, windowTo, StripCanvas.Bounds.Width, MinimumHighlightWidth); + if (box is not { } shown) + { + WindowHighlight.IsVisible = false; + + return; + } + + WindowHighlight.IsVisible = true; + Canvas.SetLeft(WindowHighlight, shown.Left); + WindowHighlight.Width = shown.Width; + WindowHighlight.Height = StripCanvas.Bounds.Height; + WindowHighlight.BorderThickness = new Thickness( + shown.CutsLeft ? 0.0 : WindowBorderWidth, + WindowBorderWidth, + shown.CutsRight ? 0.0 : WindowBorderWidth, + WindowBorderWidth); + } + + /// One full-height tick per operator marker on the page; recipe markers shade their runs. + private void PlaceTimeMarkerTicks() + { + var (width, height) = (StripCanvas.Bounds.Width, StripCanvas.Bounds.Height); + var ticks = new GeometryGroup(); + if (PagedViewModel() is { } viewModel) + { + var page = viewModel.Pager.Page; + foreach (var markerTime in viewModel.OperatorMarkerTimes) + { + if (MinimapGeometry.FractionAt(page.FromUtc, page.ToUtc, markerTime) is { } fraction) + { + var x = fraction * width; + ticks.Children.Add(new LineGeometry(new Point(x, 0.0), new Point(x, height))); + } + } + } + + TimeMarkerTicks.Data = ticks; + } + + private void LayoutPageTicks() + { + var width = StripCanvas.Bounds.Width; + if (PagedViewModel() is not { } viewModel || width <= 0.0) + { + TickLabels.Children.Clear(); + + return; + } + + var page = viewModel.Pager.Page; + var kind = page.Unit == MinimapPageUnit.Day ? TrackTickKind.Hour : TrackTickKind.Day; + var ticks = MinimapTrackGeometry.PageTicks(page, width, TickLabelSpacing(kind), viewModel.ArchiveZone); + TrackLabels.Layout(TickLabels, ticks.Select(tick => (tick.X, MinimapLabels.Tick(tick))), width); + } + + /// The widest label of the kind plus a gap, measured once. + private double TickLabelSpacing(TrackTickKind kind) + { + if (!_tickLabelSpacing.TryGetValue(kind, out var spacing)) + { + var count = kind == TrackTickKind.Hour ? DayHours.HoursPerDay : MinimapPage.DaysPerWeek; + var texts = Enumerable.Range(0, count).Select(index => MinimapLabels.Tick(new TrackTick( + 0.0, kind == TrackTickKind.Hour ? _probeMonday.AddHours(index) : _probeMonday.AddDays(index), kind))); + spacing = TrackLabels.Widest(TickLabels, texts) + TickLabelGap; + _tickLabelSpacing[kind] = spacing; + } + + return spacing; + } + + private void PlaceDetailHover() + { + var width = StripCanvas.Bounds.Width; + if (_detailHoverFraction is not { } fraction || PagedViewModel() is not { } viewModel || width <= 0.0) + { + HoverLine.IsVisible = false; + HoverTimeLabel.IsVisible = false; + TrackLabels.Cover(TickLabels, 0.0, 0.0); + + return; + } + + var pointerX = fraction * width; + HoverLine.IsVisible = true; + Canvas.SetLeft(HoverLine, MinimapGeometry.SpanLeftWithin(pointerX, HoverLine.Width, width)); + HoverLine.Height = StripCanvas.Bounds.Height; + + var page = viewModel.Pager.Page; + var hoverUtc = MinimapGeometry.TimeAtFraction(page.FromUtc, page.ToUtc, fraction); + HoverTimeLabel.Text = MinimapLabels.HoverTime( + ArchiveClock.WallClockOf(hoverUtc, viewModel.ArchiveZone), page.Unit); + HoverTimeLabel.IsVisible = true; + var labelWidth = TrackLabels.MeasuredWidth(HoverTimeLabel); + var left = MinimapGeometry.SpanLeftWithin(pointerX - (labelWidth / 2.0), labelWidth, width); + Canvas.SetLeft(HoverTimeLabel, left); + TrackLabels.Cover(TickLabels, left, labelWidth); + } + + private void HoverStripAt(double? x) + { + var width = StripCanvas.Bounds.Width; + _detailHoverFraction = x is { } pointerX && width > 0.0 ? pointerX / width : null; + PlaceDetailHover(); + } + + /// Centres the chart window at the pointer's fraction of the page. + private void NavigateToStripX(double x) + { + var width = StripCanvas.Bounds.Width; + if (PagedViewModel() is { } viewModel && width > 0.0) + { + viewModel.Pager.NavigateToPageFraction(x / width); + } + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml b/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml index ec19910..0438247 100644 --- a/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml @@ -3,18 +3,64 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:minimap="clr-namespace:SemiPlot.UI.Minimap" + xmlns:navigation="clr-namespace:SemiPlot.UI.Navigation" xmlns:legend="clr-namespace:SemiPlot.UI.Legend" + xmlns:text="clr-namespace:SemiPlot.UI.Localization" mc:Ignorable="d" d:DesignWidth="900" - d:DesignHeight="51" + d:DesignHeight="97" x:Class="SemiPlot.UI.Minimap.MinimapView" x:DataType="minimap:MinimapViewModel"> - + BorderBrush="{DynamicResource AppBorderBrush}" + Padding="8,4"> + + + + + + + + + + + + + + Converter={x:Static legend:LegendConverters.HexToBrush}}" /> + - - - - - - - - - - + + + + + + + diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml.cs index 030f3db..9f36a65 100644 --- a/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml.cs +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapView.axaml.cs @@ -2,8 +2,6 @@ using Avalonia; using Avalonia.Controls; -using Avalonia.Input; -using Avalonia.Media; using ReactiveUI; @@ -13,24 +11,19 @@ namespace SemiPlot.UI.Minimap; public partial class MinimapView : UserControl { - // Floors a sub-pixel window fraction so the marker stays visible. - private const double MinimumHighlightWidth = 6.0; - private const double EndLabelCoverDistance = 6.0; - private readonly CompositeDisposable _disposables = []; - private bool _isDragging; public MinimapView() { InitializeComponent(); - StripCanvas.PointerPressed += OnPointerPressed; - StripCanvas.PointerMoved += OnPointerMoved; - StripCanvas.PointerReleased += OnPointerReleased; - StripCanvas.PointerCaptureLost += OnPointerCaptureLost; - StripCanvas.PointerExited += OnPointerExited; + AttachDetailTrackInput(); - this.GetObservable(BoundsProperty).Subscribe(_ => UpdateStrip()); + StripCanvas.GetObservable(BoundsProperty).Subscribe(_ => + { + ReportStripWidth(); + UpdateStrip(); + }); DataContextChanged += OnDataContextChanged; } @@ -44,30 +37,28 @@ private void OnDataContextChanged(object? sender, EventArgs e) return; } + ReportStripWidth(); _disposables.Add(viewModel .WhenAnyValue( model => model.HasExtent, - model => model.ExtentFirst, - model => model.ExtentLast, + model => model.Pager.Page, model => model.BandFeed.Band) .Subscribe(_ => LayoutBand())); - _disposables.Add(viewModel - .WhenAnyValue(model => model.WindowStartFraction, model => model.WindowWidthFraction, model => model.HasExtent) - .Subscribe(_ => PlaceMarker())); - _disposables.Add(viewModel - .WhenAnyValue(model => model.HoverFraction, model => model.HoverLabel) - .Subscribe(_ => PlaceHover())); - _disposables.Add(viewModel - .WhenAnyValue(model => model.TimeMarkerFractions) - .Subscribe(_ => PlaceTimeMarkerTicks())); + _disposables.Add(FollowDetailTrack(viewModel)); + } + + private void ReportStripWidth() + { + if (DataContext is MinimapViewModel viewModel) + { + viewModel.BandFeed.SetStripWidth(StripCanvas.Bounds.Width); + } } private void UpdateStrip() { LayoutBand(); - PlaceMarker(); - PlaceTimeMarkerTicks(); - PlaceHover(); + LayoutDetailTrack(); } private void LayoutBand() @@ -80,187 +71,9 @@ private void LayoutBand() var (width, height) = (StripCanvas.Bounds.Width, StripCanvas.Bounds.Height); BandLayer.Width = width; BandLayer.Height = height; + var page = viewModel.Pager.Page; BandLayer.Figures = viewModel is { HasExtent: true, BandFeed.Band: { } band } - ? MinimapGeometry.BandFigures(band, viewModel.ExtentFirst, viewModel.ExtentLast, width, height) + ? MinimapGeometry.BandFigures(band, page.FromUtc, page.ToUtc, width, height) : []; } - - private void PlaceMarker() - { - if (DataContext is not MinimapViewModel viewModel) - { - return; - } - - if (!viewModel.HasExtent) - { - WindowHighlight.IsVisible = false; - - return; - } - - var stripWidth = StripCanvas.Bounds.Width; - var (left, width) = MinimapGeometry.MarkerSpan( - viewModel.WindowStartFraction, viewModel.WindowWidthFraction, stripWidth, MinimumHighlightWidth); - WindowHighlight.IsVisible = true; - Canvas.SetLeft(WindowHighlight, left); - WindowHighlight.Width = width; - WindowHighlight.Height = StripCanvas.Bounds.Height; - } - - private void PlaceTimeMarkerTicks() - { - if (DataContext is not MinimapViewModel viewModel) - { - return; - } - - var (width, height) = (StripCanvas.Bounds.Width, StripCanvas.Bounds.Height); - var ticks = new GeometryGroup(); - foreach (var fraction in viewModel.TimeMarkerFractions) - { - var x = fraction * width; - ticks.Children.Add(new LineGeometry(new Point(x, 0.0), new Point(x, height))); - } - - TimeMarkerTicks.Data = ticks; - } - - private void PlaceHover() - { - if (DataContext is not MinimapViewModel viewModel) - { - return; - } - - if (viewModel.HoverFraction is not { } fraction) - { - HideHover(); - - return; - } - - var stripWidth = StripCanvas.Bounds.Width; - var pointerX = fraction * stripWidth; - HoverLine.IsVisible = true; - Canvas.SetLeft(HoverLine, MinimapGeometry.SpanLeftWithin(pointerX, HoverLine.Width, stripWidth)); - HoverLine.Height = StripCanvas.Bounds.Height; - - PlaceHoverTime(viewModel.HoverLabel, pointerX + StripCanvas.Bounds.X - LabelRow.Bounds.X); - } - - // docs/architecture/trend-interaction.md#archive-overview-minimap - private void PlaceHoverTime(string text, double rowPointerX) - { - HoverTimeLabel.Text = text; - HoverTimeLabel.IsVisible = true; - - var placement = MinimapGeometry.PlaceHoverTime( - rowPointerX, - MeasuredWidth(HoverTimeLabel), - LabelRow.Bounds.Width, - MeasuredWidth(ExtentFirstLabel), - MeasuredWidth(ExtentLastLabel), - EndLabelCoverDistance); - Canvas.SetLeft(HoverTimeLabel, placement.Left); - ExtentFirstLabel.Opacity = placement.CoversFirst ? 0.0 : 1.0; - ExtentLastLabel.Opacity = placement.CoversLast ? 0.0 : 1.0; - } - - private static double MeasuredWidth(Control control) - { - control.Measure(Size.Infinity); - - return control.DesiredSize.Width; - } - - private void HideHover() - { - HoverLine.IsVisible = false; - HoverTimeLabel.IsVisible = false; - ExtentFirstLabel.Opacity = 1.0; - ExtentLastLabel.Opacity = 1.0; - } - - private void OnPointerPressed(object? sender, PointerPressedEventArgs args) - { - if (!args.GetCurrentPoint(StripCanvas).Properties.IsLeftButtonPressed) - { - return; - } - - _isDragging = true; - args.Pointer.Capture(StripCanvas); - NavigateToPointer(args); - args.Handled = true; - } - - private void OnPointerMoved(object? sender, PointerEventArgs args) - { - if (_isDragging) - { - NavigateToPointer(args); - } - - HoverAtPointer(args); - } - - private void OnPointerReleased(object? sender, PointerReleasedEventArgs args) - { - if (!_isDragging) - { - return; - } - - args.Pointer.Capture(null); - _isDragging = false; - } - - // Capture can be lost mid-drag without a PointerReleased (window deactivation); clear the drag flag. - private void OnPointerCaptureLost(object? sender, PointerCaptureLostEventArgs args) - { - _isDragging = false; - } - - // docs/architecture/trend-interaction.md#archive-overview-minimap - private void OnPointerExited(object? sender, PointerEventArgs args) - { - if (!_isDragging && DataContext is MinimapViewModel viewModel) - { - viewModel.ClearHover(); - } - } - - private void HoverAtPointer(PointerEventArgs args) - { - if (DataContext is not MinimapViewModel viewModel) - { - return; - } - - var position = args.GetPosition(StripCanvas); - if (new Rect(StripCanvas.Bounds.Size).Contains(position) && StripFraction(position) is { } fraction) - { - viewModel.HoverAt(fraction); - } - else - { - viewModel.ClearHover(); - } - } - - private void NavigateToPointer(PointerEventArgs args) - { - if (DataContext is MinimapViewModel viewModel && StripFraction(args.GetPosition(StripCanvas)) is { } fraction) - { - viewModel.NavigateToFraction(fraction); - } - } - - private double? StripFraction(Point position) - { - var width = StripCanvas.Bounds.Width; - - return width > 0.0 ? position.X / width : null; - } } diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs index bb522aa..2625bb6 100644 --- a/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; @@ -14,6 +14,7 @@ using SemiPlot.UI.Bridge; using SemiPlot.UI.Chart; using SemiPlot.UI.Messages; +using SemiPlot.UI.Navigation; namespace SemiPlot.UI.Minimap; @@ -29,6 +30,8 @@ public sealed class MinimapViewModel : ReactiveObject, IDisposable private readonly OutageReport _extentOutage; private readonly CompositeDisposable _disposables = []; private readonly SerialDisposable _missingExtentRead = new(); + private readonly ObservableAsPropertyHelper _hint; + private readonly ObservableAsPropertyHelper> _operatorMarkerTimes; private bool _isExtentMissing; private DateTimeOffset _nextMissingExtentRead = DateTimeOffset.MinValue; @@ -38,91 +41,88 @@ public MinimapViewModel( TrendCoordinator coordinator, TrendChartViewModel chart, IScheduler uiScheduler, + TimeZoneInfo archiveZone, MessagePanelViewModel messagePanel, ILogger logger) { _coordinator = coordinator; _chart = chart; _uiScheduler = uiScheduler; + ArchiveZone = archiveZone; _messagePanel = messagePanel; _logger = logger; _extentOutage = new OutageReport("archive extent read", messagePanel, logger); - BandFeed = new MinimapBandFeed(coordinator, chart, ReadBounds, uiScheduler, messagePanel, logger); + PresenceFeed = new ArchivePresenceFeed( + coordinator, chart.Navigation, archiveZone, uiScheduler, messagePanel, logger); + Pager = new MinimapPager(chart.Navigation, PresenceFeed, Extents(), archiveZone); + BandFeed = new MinimapBandFeed(coordinator, chart, Pager, () => HasExtent, uiScheduler, messagePanel, logger); _disposables.Add(FollowNavigation()); - _disposables.Add(chart.Markers.Changed.Subscribe(_ => RefreshTimeMarkerFractions(), ReportFailure)); + _disposables.Add(this + .WhenAnyValue( + viewModel => viewModel.IsArchiveEmpty, + viewModel => viewModel.HasExtent, + viewModel => viewModel.Pager.Page, + viewModel => viewModel.PresenceFeed.Spans, + viewModel => viewModel.BandFeed.HasReadFailed, + MinimapHint.For) + .ToProperty(this, viewModel => viewModel.Hint, out _hint)); + _disposables.Add(chart.Markers.Changed + .StartWith(Unit.Default) + .Select(_ => OperatorMarkerTimesOf(chart.Markers)) + .DistinctUntilChanged(SequenceComparer.Instance) + .ToProperty(this, viewModel => viewModel.OperatorMarkerTimes, out _operatorMarkerTimes)); + RefreshShadedRuns(); + _disposables.Add(chart.Markers.Changed.Subscribe(_ => RefreshShadedRuns(), ReportFailure)); _disposables.Add(_missingExtentRead); _disposables.Add(BandFeed); + _disposables.Add(PresenceFeed); + _disposables.Add(Pager); } public DateTime ExtentFirst { get; - private set - { - this.RaiseAndSetIfChanged(ref field, value); - this.RaisePropertyChanged(nameof(ExtentFirstLabel)); - this.RaisePropertyChanged(nameof(HoverLabel)); - } + private set => this.RaiseAndSetIfChanged(ref field, value); } - /// The strip's right bound: the later of the extent's last sample and the chart's newest sample. + /// The minimap's right bound: the later of the extent's last sample and the chart's newest sample. public DateTime ExtentLast { get; - private set - { - this.RaiseAndSetIfChanged(ref field, value); - this.RaisePropertyChanged(nameof(ExtentLastLabel)); - this.RaisePropertyChanged(nameof(HoverLabel)); - } + private set => this.RaiseAndSetIfChanged(ref field, value); } public bool HasExtent - { - get; - private set - { - this.RaiseAndSetIfChanged(ref field, value); - this.RaisePropertyChanged(nameof(ExtentFirstLabel)); - this.RaisePropertyChanged(nameof(ExtentLastLabel)); - } - } - - public string ExtentFirstLabel => HasExtent ? FormatTime(ExtentFirst) : string.Empty; - - public string ExtentLastLabel => HasExtent ? FormatTime(ExtentLast) : string.Empty; - - public double WindowStartFraction { get; private set => this.RaiseAndSetIfChanged(ref field, value); } - public double WindowWidthFraction + /// True once an extent read answered with no rows and no extent was ever read. + public bool IsArchiveEmpty { get; private set => this.RaiseAndSetIfChanged(ref field, value); - } = 1.0; - - public double? HoverFraction - { - get; - private set - { - this.RaiseAndSetIfChanged(ref field, value); - this.RaisePropertyChanged(nameof(HoverLabel)); - } } - public string HoverLabel => HoverFraction is { } fraction - ? FormatTime(MinimapGeometry.TimeAtFraction(ExtentFirst, ExtentLast, fraction)) - : string.Empty; + /// The archive's wall-clock zone, which the day calendar and the detail track read. + public TimeZoneInfo ArchiveZone { get; } public MinimapBandFeed BandFeed { get; } - /// Where each time marker inside the extent sits along the strip; empty without an extent. - public IReadOnlyList TimeMarkerFractions + public ArchivePresenceFeed PresenceFeed { get; } + + public MinimapPager Pager { get; } + + /// The detail track's hint (docs/architecture/trend-interaction.md#archive-overview-minimap). + public string? Hint => _hint.Value; + + /// The operator's markers for the day calendar's marker ticks. + public IReadOnlyList OperatorMarkerTimes => _operatorMarkerTimes.Value; + + /// The recipe runs the Day page shades; empty while the View menu hides recipe markers. + public IReadOnlyList ShadedRuns { get; private set => this.RaiseAndSetIfChanged(ref field, value); @@ -150,52 +150,30 @@ public async Task> LoadExtentAsync() return result; } - public void NavigateToFraction(double fraction) - { - ObjectDisposedException.ThrowIf(_isDisposed, this); - - if (!HasExtent) - { - return; - } - - var target = MinimapGeometry.TimeAtFraction(ExtentFirst, ExtentLast, fraction); - var navigation = _chart.Navigation; - var currentCenter = navigation.From + ((navigation.To - navigation.From) / 2.0); - navigation.PanBy(target - currentCenter); - } - - public void HoverAt(double fraction) + /// The day calendar over the extent's wall-clock days; null without an extent or a width. + public DayCalendar? Calendar(double width) { - if (!HasExtent) - { - return; - } - - HoverFraction = fraction; - } - - public void ClearHover() - { - HoverFraction = null; + return HasExtent + ? DayCalendar.Over( + ArchiveClock.DayOf(ExtentFirst, ArchiveZone), ArchiveClock.DayOf(ExtentLast, ArchiveZone), width) + : null; } private IDisposable FollowNavigation() { var navigation = _chart.Navigation; - navigation.WindowChanged += OnNavigationWindowChanged; navigation.NewestSampleMoved += OnNewestSampleMoved; - return Disposable.Create(() => - { - navigation.WindowChanged -= OnNavigationWindowChanged; - navigation.NewestSampleMoved -= OnNewestSampleMoved; - }); + return Disposable.Create(() => navigation.NewestSampleMoved -= OnNewestSampleMoved); } - private (DateTime First, DateTime Last)? ReadBounds() + private IObservable<(DateTime First, DateTime Last)?> Extents() { - return HasExtent ? (ExtentFirst, ExtentLast) : null; + return this.WhenAnyValue( + viewModel => viewModel.HasExtent, + viewModel => viewModel.ExtentFirst, + viewModel => viewModel.ExtentLast, + (hasExtent, first, last) => hasExtent ? (first, last) : ((DateTime First, DateTime Last)?)null); } private void ApplyExtent(Result result) @@ -215,6 +193,7 @@ private void ApplyExtent(Result result) } _extentOutage.Succeeded(); + IsArchiveEmpty = !HasExtent && result.Value.IsEmpty; // An empty extent is a normal state of a fresh archive: leave HasExtent false so the strip stays // blank. @@ -227,9 +206,8 @@ private void ApplyExtent(Result result) ExtentFirst = result.Value.FirstUtc; ExtentLast = MinimapGeometry.RightBound(result.Value.LastUtc, navigation.NewestSample); HasExtent = true; - RefreshWindowFraction(navigation.From, navigation.To); - RefreshTimeMarkerFractions(); BandFeed.RequestRead(); + PresenceFeed.ReadExtent(ExtentFirst, ExtentLast); } private void ReadMissingExtent() @@ -259,68 +237,37 @@ private void ReportFailure(Exception failure) _messagePanel.TryReportFailure(new ExceptionalError(failure), _logger); } - private static string FormatTime(DateTime utc) - { - return utc.ToLocalTime().ToString("MMM d HH:mm", CultureInfo.CurrentCulture); - } - - private void OnNavigationWindowChanged(object? sender, NavigationWindow window) - { - RefreshWindowFraction(window.From, window.To); - } - private void OnNewestSampleMoved(object? sender, DateTime newestSample) { - if (!HasExtent) + RefreshShadedRuns(); + if (HasExtent) { - var isRetryDue = _uiScheduler.Now >= _nextMissingExtentRead; - if (_isExtentMissing && isRetryDue) - { - ReadMissingExtent(); - } - - return; + ExtentLast = MinimapGeometry.RightBound(ExtentLast, newestSample); + PresenceFeed.FollowNewestSample(); } - - var rightBound = MinimapGeometry.RightBound(ExtentLast, newestSample); - if (rightBound == ExtentLast) + else if (_isExtentMissing && _uiScheduler.Now >= _nextMissingExtentRead) { - return; + ReadMissingExtent(); } - ExtentLast = rightBound; - RefreshWindowFraction(_chart.Navigation.From, _chart.Navigation.To); - RefreshTimeMarkerFractions(); + Pager.FollowNewestSample(); } - private void RefreshWindowFraction(DateTime from, DateTime to) + private static IReadOnlyList OperatorMarkerTimesOf(ChartMarkers markers) { - if (!HasExtent) - { - return; - } - - var (start, width) = MinimapGeometry.WindowFraction(ExtentFirst, ExtentLast, from, to); - WindowStartFraction = start; - WindowWidthFraction = width; + return [.. markers.OperatorMarkers.Select(marker => marker.TimeUtc)]; } - private void RefreshTimeMarkerFractions() + /// Reassigns only on a change, so a live sample redraws nothing while the last run is closed. + private void RefreshShadedRuns() { - if (!HasExtent) + var markers = _chart.Markers; + var runs = markers.ShowsRecipeMarkers + ? MarkerNavigation.Runs(markers.All, _chart.Navigation.NewestSample) + : []; + if (!runs.SequenceEqual(ShadedRuns)) { - return; + ShadedRuns = runs; } - - var fractions = new List(); - foreach (var marker in _chart.Markers.ShownMarkers) - { - if (MinimapGeometry.FractionAt(ExtentFirst, ExtentLast, marker.TimeUtc) is { } fraction) - { - fractions.Add(fraction); - } - } - - TimeMarkerFractions = fractions; } } diff --git a/SemiPlot/SemiPlot.UI/Minimap/TrackLabels.cs b/SemiPlot/SemiPlot.UI/Minimap/TrackLabels.cs new file mode 100644 index 0000000..525631a --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/TrackLabels.cs @@ -0,0 +1,62 @@ +using Avalonia; +using Avalonia.Controls; + +namespace SemiPlot.UI.Minimap; + +/// The minimap's label rows: measuring, placing and hiding their labels. +internal static class TrackLabels +{ + public static double MeasuredWidth(Control control) + { + control.Measure(Size.Infinity); + + return control.DesiredSize.Width; + } + + /// The widest of the texts, measured on the row so that the row's text style applies. + public static double Widest(Canvas row, IEnumerable texts) + { + var probe = new TextBlock(); + row.Children.Add(probe); + var widest = 0.0; + foreach (var text in texts) + { + probe.Text = text; + widest = Math.Max(widest, MeasuredWidth(probe)); + } + + row.Children.Remove(probe); + + return widest; + } + + /// One label per tick at its x; a label that would overflow the row's right end is dropped. + public static void Layout(Canvas row, IEnumerable<(double X, string Text)> labels, double width) + { + row.Children.Clear(); + foreach (var (x, text) in labels) + { + var label = new TextBlock { Text = text }; + row.Children.Add(label); + if (x + MeasuredWidth(label) > width) + { + row.Children.Remove(label); + + continue; + } + + Canvas.SetLeft(label, x); + } + } + + /// Hides every label of the row that the span overlaps and shows the rest. + public static void Cover(Canvas labels, double left, double width) + { + foreach (var label in labels.Children) + { + var labelLeft = Canvas.GetLeft(label); + var isCovered = width > 0.0 && labelLeft < left + width && left < labelLeft + label.DesiredSize.Width; + label.Opacity = isCovered ? 0.0 : 1.0; + } + } +} diff --git a/SemiPlot/SemiPlot.UI/Minimap/TrackPointer.cs b/SemiPlot/SemiPlot.UI/Minimap/TrackPointer.cs new file mode 100644 index 0000000..c88f24d --- /dev/null +++ b/SemiPlot/SemiPlot.UI/Minimap/TrackPointer.cs @@ -0,0 +1,79 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; + +namespace SemiPlot.UI.Minimap; + +/// +/// A minimap track's left press, drag and hover (docs/architecture/trend-interaction.md#archive-overview-minimap). +/// +internal sealed class TrackPointer +{ + private readonly Control _track; + private readonly Action _navigate; + private readonly Action _hover; + private bool _isDragging; + + public TrackPointer(Control track, Action navigate, Action hover) + { + _track = track; + _navigate = navigate; + _hover = hover; + + track.PointerPressed += OnPressed; + track.PointerMoved += OnMoved; + track.PointerReleased += OnReleased; + track.PointerCaptureLost += OnCaptureLost; + track.PointerExited += OnExited; + } + + private void OnPressed(object? sender, PointerPressedEventArgs args) + { + if (!args.GetCurrentPoint(_track).Properties.IsLeftButtonPressed) + { + return; + } + + _isDragging = true; + args.Pointer.Capture(_track); + _navigate(args.GetPosition(_track).X); + args.Handled = true; + } + + private void OnMoved(object? sender, PointerEventArgs args) + { + var position = args.GetPosition(_track); + if (_isDragging) + { + _navigate(position.X); + } + + _hover(new Rect(_track.Bounds.Size).Contains(position) ? position.X : null); + } + + private void OnReleased(object? sender, PointerReleasedEventArgs args) + { + if (!_isDragging) + { + return; + } + + args.Pointer.Capture(null); + _isDragging = false; + } + + // Capture can be lost mid-drag without a PointerReleased (window deactivation); clear the drag flag. + private void OnCaptureLost(object? sender, PointerCaptureLostEventArgs args) + { + _isDragging = false; + } + + // Capturing the pointer raises PointerExited while it is still over the track, so a drag keeps its hover. + private void OnExited(object? sender, PointerEventArgs args) + { + if (!_isDragging) + { + _hover(null); + } + } +} diff --git a/SemiPlot/SemiPlot.UI/Navigation/NavigationBarView.axaml b/SemiPlot/SemiPlot.UI/Navigation/NavigationBarView.axaml index 754a65e..139fecd 100644 --- a/SemiPlot/SemiPlot.UI/Navigation/NavigationBarView.axaml +++ b/SemiPlot/SemiPlot.UI/Navigation/NavigationBarView.axaml @@ -10,6 +10,44 @@ x:Class="SemiPlot.UI.Navigation.NavigationBarView" x:DataType="navigation:NavigationBarViewModel"> + + + + + + + + + + + + + + @@ -21,10 +59,51 @@ IsChecked="{Binding IsSticky, Mode=OneWay}" Command="{Binding ToggleStickyCommand}" /> - + + + + + + + + + + + + + + +