diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md index f85c1ba..723a74f 100644 --- a/src/FinalToken.App/AGENTS.md +++ b/src/FinalToken.App/AGENTS.md @@ -52,11 +52,15 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned. - Estimated day bars use provider outlines and 45-degree hatching; measured days stay solid. Align past days by index and burn-ups by elapsed time. The Resets timeline puts real instances side by side - on one time axis without joining their lines; hatch skipped time and mark observed resets (D12). + on one time axis without joining their lines; mark observed resets and show skipped time as thin + hatched bars below the plot, with overlapping spans in separate lanes (D12). Its axis ends at + the latest of now and the early resets' nominal resets, never the running instance's reset. Burn-ups use solid measured and lighter dashed estimated lines, with no point markers. - Use DataTooltip for every data hover: bold title, two-column label/value grid, exact and compact counts, optional series swatches. Future days have no cumulative value. Share one date formatter - for resets and forecasts. Recent-rate captions name the actual span. + for resets and forecasts. Recent-rate captions name the actual span. Tall tooltips open beside + the pointer through `DataTooltip.BesidePointer`; a tooltip over the pointer takes the hover from + its control. Do not clear a chart's tip on pointer exit. - Custom segments and checkboxes must show keyboard focus. NeutralCheckBox owns checked state; templates bind its MarkVisible property and must never register checked handlers. diff --git a/src/FinalToken.App/DataTooltip.cs b/src/FinalToken.App/DataTooltip.cs index 89323dc..ae207b5 100644 --- a/src/FinalToken.App/DataTooltip.cs +++ b/src/FinalToken.App/DataTooltip.cs @@ -1,5 +1,6 @@ using Avalonia; using Avalonia.Controls; +using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Layout; using Avalonia.Media; using FinalToken.Core; @@ -42,5 +43,23 @@ public sealed partial class DataTooltip : Border if (!day.IsFuture && day.Cumulative is { } cumulative) rows.Add(new("Cumulative", $"{cumulative:0.##} %")); return new(day.Start.DateTime.ToString("D"), rows.ToArray()); } + /// + /// Opens a tall tooltip beside the pointer, never over it: a tooltip that covers the pointer takes + /// it from , which then loses the tooltip. Call before other pointer handlers. + /// + public static void BesidePointer(Control control) + { + var pointer = default(Point); + control.PointerMoved += (_, e) => pointer = e.GetPosition(control); + ToolTip.SetPlacement(control, PlacementMode.Custom); + ToolTip.SetCustomPopupPlacementCallback(control, placement => + { + // The anchor arrives as the control's bounds in window coordinates. The gap lives in the anchor, + // because a flip mirrors anchor and gravity but not the offset. + placement.AnchorRectangle = new Rect(placement.AnchorRectangle.TopLeft + pointer - new Point(16, 0), new Size(32, 1)); + placement.Anchor = PopupAnchor.Right; placement.Gravity = PopupGravity.Right; + placement.ConstraintAdjustment = PopupPositionerConstraintAdjustment.FlipX | PopupPositionerConstraintAdjustment.SlideY; + }); + } public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value)); } diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index 5f9f8fa..f631de9 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -149,9 +149,10 @@ public static class Display public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" }; public static string Money(decimal? value) => value is { } dollars ? "≈ $" + dollars.ToString(dollars >= 100 ? "N0" : "N2", System.Globalization.CultureInfo.InvariantCulture) : "Unpriced"; - public static string Limits(double percent) => "≈ " + (percent / 100).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture) + " limits"; + public static string Limits(double percent) => "≈ " + (percent / 100).ToString("0.0") + " limits"; public static string ResetPercent(double percent, UseOrigin origin) => (origin == UseOrigin.Estimated ? "≈ " : "") + - percent.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture) + " %"; + percent.ToString("0.#") + " %"; public static string ResetDate(DateTimeOffset time, TimeProvider clock) => TimeZoneInfo.ConvertTime(time, clock.LocalTimeZone).ToString("MM-dd HH:mm"); - public static string ResetDuration(TimeSpan span) => span <= TimeSpan.Zero ? "0 min" : Duration(span); + public static string ResetFigure(string figure) => figure.Replace(' ', '\u00a0'); + public static string ResetDuration(TimeSpan span) => ResetFigure(span <= TimeSpan.Zero ? "0 min" : Duration(span)); } diff --git a/src/FinalToken.App/ResetCard.cs b/src/FinalToken.App/ResetCard.cs index c9e9598..1b73f45 100644 --- a/src/FinalToken.App/ResetCard.cs +++ b/src/FinalToken.App/ResetCard.cs @@ -16,36 +16,43 @@ public sealed class ResetCard : StackPanel Children.Add(Ui.Text("No reset observed since " + Display.Projection(history.FirstSample, clock), 12, "Muted")); if (history.Instances.Count == 0) return; var stats = new UniformGrid { Columns = 6, Rows = 1 }; - void Stat(string label, string value, string caption, DataTooltip tooltip) + void Stat(string label, string value, string caption, DataTooltip tooltip, bool available = true) { - var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(value, 24), Ui.Text(caption, 12, "Muted")); + var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.ResetFigure(value), 24, available ? "Ink" : "Muted"), Ui.Text(caption, 12, "Muted")); tile.Margin = new Thickness(0, 0, 12, 0); ToolTip.SetTip(tile, tooltip); stats.Children.Add(tile); } DataTooltip ValueTip(string title, ResetValue value) => new(title, new("Limits", Display.Limits(value.Percent)), new("Percent", $"{value.Percent:N2} %"), new("Estimated tokens", value.Tokens is { } tokens ? "≈ " + tokens.ToString("N0") : "No qualifying instance"), new("Estimated API value", Display.Money(value.ApiValue)), new("Basis", "Own instance ≥ 5 %, else series median"), new("Coverage", "Whole listed instances; hourly boundary tokens")); - string ValueCaption(ResetValue value) => (value.Tokens is { } tokens ? "≈ " + Display.Compact(tokens) + " tokens · " : "") + Display.Money(value.ApiValue); - Stat("Resets", totals.Instances.ToString(), $"{totals.Early} early", new DataTooltip("Listed instances", + string ValueCaption(ResetValue value) => (value.Tokens is { } tokens ? Display.ResetFigure("≈ " + Display.Compact(tokens) + " tokens") + " · " : "") + Display.ResetFigure(Display.Money(value.ApiValue)); + var resetCaption = totals.Finished == 0 ? "none yet" : Display.ResetFigure($"{totals.Early} early"); + if (history.Instances[0].Running) resetCaption += " · " + Display.ResetFigure("1 running"); + Stat("Resets", totals.Finished.ToString(), resetCaption, new DataTooltip("Listed instances", new("Total", totals.Instances.ToString()), new("Finished", totals.Finished.ToString()), new("Early", totals.Early.ToString()), new("Running", (totals.Instances - totals.Finished).ToString()))); Stat("Tokens", Display.Compact(totals.Tokens.Total), "in listed instances", DataTooltip.Tokens("Reset history tokens", totals.Tokens)); Stat("API value", Display.Money(totals.ApiValue), "at API list prices", new DataTooltip("API value at list prices", new("Value", Display.Money(totals.ApiValue)), new("Unpriced tokens", DataTooltip.Count(totals.UnpricedTokens)), new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd")))); - Stat("Unused", Display.Limits(totals.Unused.Percent), ValueCaption(totals.Unused), ValueTip("Unused limit · estimated value", totals.Unused)); - Stat("Gift", Display.Limits(totals.Gift.Percent), ValueCaption(totals.Gift) + " · " + Display.ResetDuration(totals.Skipped) + " skipped", ValueTip("Early-reset gift · estimated value", totals.Gift)); - Stat("100 % reached", totals.ReachedLimit + "×", Display.ResetDuration(totals.TimeAtLimit) + " at 100 %", new DataTooltip("100 % reached", + Stat("Unused", totals.Finished > 0 ? Display.Limits(totals.Unused.Percent) : "—", + totals.Finished > 0 ? ValueCaption(totals.Unused) : "no finished instance", + totals.Finished > 0 ? ValueTip("Unused limit · estimated value", totals.Unused) : new DataTooltip("Unused limit", new TooltipRow("Coverage", "No finished instance")), totals.Finished > 0); + Stat("Gift", totals.Early > 0 ? Display.Limits(totals.Gift.Percent) : "—", + totals.Early > 0 ? ValueCaption(totals.Gift) + " · " + Display.ResetDuration(totals.Skipped) + " skipped" : "no early reset", + totals.Early > 0 ? ValueTip("Early-reset gift · estimated value", totals.Gift) : new DataTooltip("Early-reset gift", new TooltipRow("Coverage", "No early reset")), totals.Early > 0); + Stat("100 % reached", totals.ReachedLimit + "×", Display.ResetDuration(totals.TimeAtLimit) + " at 100\u00a0%", new DataTooltip("100 % reached", new("Instances", totals.ReachedLimit.ToString()), new("Total time", Display.ResetDuration(totals.TimeAtLimit)), new("Source", history.Instances.Any(r => r.BurnUp.ReachedOrigin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured"))); Children.Add(stats); - Children.Add(Ui.Text("Measured · dashed: estimated · vertical: reset · hatched: skipped · top band: time at 100 %", 12, "Muted")); + Children.Add(Ui.Text("Measured · dashed: estimated · vertical: reset · hatched bars below: skipped · top band: time at 100 %", 12, "Muted")); Children.Add(new ResetTimeline(history, clock)); - Children.Add(Ui.Columns([ + if (totals.Early == 0) Children.Add(Ui.Text("No early resets in this range", 12, "Muted")); + else Children.Add(Ui.Columns([ Ui.Stack(Ui.Text("Early resets by hour · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByHour, history.Window.Provider, false)), Ui.Stack(Ui.Text("Early resets by weekday · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByWeekday, history.Window.Provider, true))], true)); - Children.Add(Ui.Text("Median instance " + (history.MedianDuration is { } median ? Display.ResetDuration(median) : "—") + - $" · early resets {totals.Early} of {totals.Instances}", 12, "Secondary")); + Children.Add(Ui.Text((history.MedianDuration is { } median ? "Median instance " + Display.ResetDuration(median) : "No finished instance yet") + + $" · early resets {totals.Early} of {totals.Finished}", 12, "Secondary")); Children.Add(new ResetTable(history, state, clock)); } } diff --git a/src/FinalToken.App/ResetCharts.cs b/src/FinalToken.App/ResetCharts.cs index 406da38..79d591f 100644 --- a/src/FinalToken.App/ResetCharts.cs +++ b/src/FinalToken.App/ResetCharts.cs @@ -5,36 +5,53 @@ using FinalToken.Core; namespace FinalToken.App; +public sealed record ResetSkippedLane(ResetInstance Instance, int Lane); +public sealed record ResetTimelineLayout(DateTimeOffset From, DateTimeOffset To, IReadOnlyList Skipped) +{ + public int LaneCount => Skipped.Count == 0 ? 0 : Skipped.Max(s => s.Lane) + 1; +} + /// D12: real instances share a time axis; their burn-ups are never connected. public sealed class ResetTimeline(ResetHistory history, TimeProvider clock) : Control { - private Rect plot; - private DateTimeOffset from, to; + private const double LaneHeight = 10; + private readonly ResetTimelineLayout layout = CalculateLayout(history, clock.GetUtcNow()); private readonly List<(Rect Bounds, ResetInstance Instance)> hits = []; + public static ResetTimelineLayout CalculateLayout(ResetHistory history, DateTimeOffset now) + { + var from = history.Instances.Select(r => r.Start).DefaultIfEmpty(now).Min(); + var to = history.Instances.Where(r => r.Early).Select(r => r.Reset).Append(now).Max(); + if (to <= from) to = from.AddHours(1); + var laneEnds = new List(); + var skipped = new List(); + foreach (var row in history.Instances.Where(r => r.Early).OrderBy(r => r.End).ThenBy(r => r.Reset)) + { + var lane = laneEnds.FindIndex(end => end <= row.End); + if (lane < 0) { lane = laneEnds.Count; laneEnds.Add(row.Reset); } + else laneEnds[lane] = row.Reset; + skipped.Add(new(row, lane)); + } + return new(from, to, skipped); + } protected override void OnInitialized() { - base.OnInitialized(); Height = 210; ToolTip.SetShowDelay(this, 0); + base.OnInitialized(); Height = 210 + layout.LaneCount * LaneHeight; ToolTip.SetShowDelay(this, 0); DataTooltip.BesidePointer(this); PointerMoved += (_, e) => { var point = e.GetPosition(this); - if (!plot.Contains(point) || to <= from) { ToolTip.SetTip(this, null); return; } - var time = from.AddTicks((long)((to - from).Ticks * (point.X - plot.Left) / plot.Width)); var instance = hits.Where(h => h.Bounds.Contains(point)).OrderBy(h => Math.Abs(h.Bounds.Center.X - point.X)) - .Select(h => h.Instance).FirstOrDefault() ?? - history.Instances.FirstOrDefault(r => r.Early && r.End <= time && r.Reset >= time); + .Select(h => h.Instance).FirstOrDefault(); ToolTip.SetTip(this, instance is null ? null : DataTooltip.Reset(instance, clock)); }; - PointerExited += (_, _) => ToolTip.SetTip(this, null); } public override void Render(DrawingContext context) { base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); if (history.Instances.Count == 0) return; var dark = Ui.Dark(this); var colour = Ui.ProviderColour(history.Window.Provider, dark); var muted = Ui.Colour("Muted", dark); - plot = new Rect(42, 12, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 48)); - from = history.Instances.Min(r => r.Start); - to = history.Instances.Max(r => r.Early ? r.Reset : r.End); - if (to <= from) to = from.AddHours(1); + var laneSpace = layout.LaneCount * LaneHeight; + var plot = new Rect(42, 12, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 48 - laneSpace)); + var from = layout.From; var to = layout.To; double X(DateTimeOffset time) => plot.Left + (time - from).TotalSeconds / (to - from).TotalSeconds * plot.Width; double Y(double used) => plot.Bottom - used / 100 * plot.Height; foreach (var tick in new[] { 0, 25, 50, 75, 100 }) @@ -44,17 +61,6 @@ public sealed class ResetTimeline(ResetHistory history, TimeProvider clock) : Co } using (context.PushClip(plot)) { - foreach (var row in history.Instances.Where(r => r.Early)) - { - var band = new Rect(X(row.End), plot.Top, Math.Max(0, X(row.Reset) - X(row.End)), plot.Height); - using (context.PushClip(band)) - { - using (context.PushOpacity(.035)) context.DrawRectangle(colour, null, band); - using (context.PushOpacity(.14)) - for (var x = band.Left - band.Height; x < band.Right; x += 8) - context.DrawLine(new Pen(colour), new(x, band.Bottom), new(x + band.Height, band.Top)); - } - } foreach (var row in history.Instances.Reverse()) { var hitWidth = Math.Max(8, X(row.End) - X(row.Start)); @@ -78,10 +84,24 @@ public sealed class ResetTimeline(ResetHistory history, TimeProvider clock) : Co } } } + foreach (var skipped in layout.Skipped) + { + var row = skipped.Instance; + var band = new Rect(X(row.End), plot.Bottom + 4 + skipped.Lane * LaneHeight, Math.Max(0, X(row.Reset) - X(row.End)), 6); + var hitWidth = Math.Max(8, band.Width); + hits.Add((new Rect(band.Center.X - hitWidth / 2, band.Top - 1, hitWidth, 8), row)); + using (context.PushClip(band)) + { + using (context.PushOpacity(.08)) context.DrawRectangle(colour, null, band); + using (context.PushOpacity(.5)) + for (var x = band.Left - band.Height; x < band.Right; x += 8) + context.DrawLine(new Pen(colour), new(x, band.Bottom), new(x + band.Height, band.Top)); + } + } for (var i = 0; i < 5; i++) { var time = from.AddTicks((to - from).Ticks * i / 4); - ChartText.Draw(context, Display.ResetDate(time, clock), new(Math.Clamp(X(time) - 36, plot.Left, Math.Max(plot.Left, plot.Right - 86)), plot.Bottom + 12), muted); + ChartText.Draw(context, Display.ResetDate(time, clock), new(Math.Clamp(X(time) - 36, plot.Left, Math.Max(plot.Left, plot.Right - 86)), plot.Bottom + laneSpace + 12), muted); } } } @@ -99,7 +119,6 @@ public sealed class ResetHistogram(IReadOnlyList counts, Provider provider, ToolTip.SetTip(this, hit is { } index ? new DataTooltip(weekdays ? Weekdays[index] : $"{index:00}:00–{index:00}:59 local", new TooltipRow("Early resets", counts[index].ToString())) : null); }; - PointerExited += (_, _) => ToolTip.SetTip(this, null); } public override void Render(DrawingContext context) { diff --git a/src/FinalToken.App/ResetTable.cs b/src/FinalToken.App/ResetTable.cs index 73d09ae..5bf8e43 100644 --- a/src/FinalToken.App/ResetTable.cs +++ b/src/FinalToken.App/ResetTable.cs @@ -57,7 +57,7 @@ public sealed class ResetTable : StackPanel for (var c = 0; c < cells.Length; c++) { var text = Ui.TableNumber(cells[c], 12); text.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right; - ToolTip.SetTip(text, DataTooltip.Reset(row, clock)); DetailTable.Add(grid, text, r + 1, c); + ToolTip.SetTip(text, DataTooltip.Reset(row, clock)); DataTooltip.BesidePointer(text); DetailTable.Add(grid, text, r + 1, c); } } Children.Add(DetailTable.Scroll(grid)); diff --git a/src/FinalToken.App/Ui.cs b/src/FinalToken.App/Ui.cs index c6f5ebf..807171a 100644 --- a/src/FinalToken.App/Ui.cs +++ b/src/FinalToken.App/Ui.cs @@ -83,6 +83,8 @@ public static class Ui window.Styles.Add(checks); var focusCheck = new Style(s => s.OfType().Class(":focus-visible")); focusCheck.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusCheck); + // Fluent caps tooltips at 320 px, which wraps the values of a data tooltip below its own width. + var tips = new Style(s => s.OfType()); tips.Setters.Add(new Setter(Layoutable.MaxWidthProperty, 560d)); window.Styles.Add(tips); } // Explicit palettes keep every remaining Fluent control independent of the OS accent. public static FluentTheme NeutralTheme() diff --git a/src/FinalToken.Core/ResetHistory.cs b/src/FinalToken.Core/ResetHistory.cs index c36996b..e77a0a1 100644 --- a/src/FinalToken.Core/ResetHistory.cs +++ b/src/FinalToken.Core/ResetHistory.cs @@ -88,7 +88,7 @@ public static partial class LimitAnalysis TimeSpan.FromTicks(rows.Sum(r => r.Skipped.Ticks)), rows.Count(r => r.ReachedLimit is not null), TimeSpan.FromTicks(rows.Sum(r => r.TimeAtLimit.Ticks))); return new(window, rows, totals, hours, weekdays, - Median(rows.Select(r => (double)r.Duration.Ticks)) is { } ticks ? TimeSpan.FromTicks((long)ticks) : null, firstSample); + Median(rows.Where(r => !r.Running).Select(r => (double)r.Duration.Ticks)) is { } ticks ? TimeSpan.FromTicks((long)ticks) : null, firstSample); } private static decimal? SumMoney(IEnumerable values) diff --git a/tests/FinalToken.App.Tests/ResetTests.cs b/tests/FinalToken.App.Tests/ResetTests.cs index 2de9492..bb05f73 100644 --- a/tests/FinalToken.App.Tests/ResetTests.cs +++ b/tests/FinalToken.App.Tests/ResetTests.cs @@ -31,19 +31,80 @@ public sealed class ResetTests Assert.Equal(8, week.Analysis!.Past.Count); } - [Fact] public void MoneyAndLimitsStayInvariantOnAGermanDesktop() + [Theory] + [InlineData("de-DE", "≈ 4,5 limits", "≈ 94,1 %")] + [InlineData("en-US", "≈ 4.5 limits", "≈ 94.1 %")] + public void ResetFiguresFollowTheUsersCultureExceptUsd(string culture, string limits, string percent) { var previous = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); Assert.Equal("≈ $1,234", Display.Money(1234)); Assert.Equal("≈ $99.25", Display.Money(99.25m)); - Assert.Equal("Unpriced", Display.Money(null)); Assert.Equal("≈ 3.1 limits", Display.Limits(310)); - Assert.Equal("0 min", Display.ResetDuration(TimeSpan.Zero)); + Assert.Equal("Unpriced", Display.Money(null)); Assert.Equal(limits, Display.Limits(450)); + Assert.Equal(percent, Display.ResetPercent(94.1, UseOrigin.Estimated)); + Assert.Equal(percent[2..], Display.ResetPercent(94.1, UseOrigin.Measured)); } finally { CultureInfo.CurrentCulture = previous; } } + [Fact] public void ResetDurationsCannotWrapInsideTheFigure() + { + Assert.Equal("0\u00a0min", Display.ResetDuration(TimeSpan.Zero)); + Assert.Equal("39\u00a0d\u00a00\u00a0h", Display.ResetDuration(TimeSpan.FromDays(39))); + Assert.Equal("≈\u00a015,1\u00a0M\u00a0tokens", Display.ResetFigure("≈ 15,1 M tokens")); + } + + [Fact] public void OverlappingSkippedSpansGetSeparateLanesInTimeOrder() + { + var fixture = ResetFixture.Overlapping(); + var history = fixture.History.Resets[0]; + var layout = ResetTimeline.CalculateLayout(history, fixture.Now); + Assert.Equal(5, history.Totals.Early); + Assert.True(history.Instances.Max(r => r.Start) - history.Instances.Min(r => r.Start) < TimeSpan.FromDays(10)); + Assert.Equal(5, layout.LaneCount); + Assert.Equal([0, 1, 2, 3, 4], layout.Skipped.Select(s => s.Lane)); + Assert.Equal(history.Instances.Where(r => r.Early).OrderBy(r => r.End), layout.Skipped.Select(s => s.Instance)); + } + + [Fact] public void SkippedSpansReuseTheFirstLaneAsSoonAsItIsFree() + { + var fixture = ResetFixture.Create(); + var layout = ResetTimeline.CalculateLayout(fixture.History.Resets[0], fixture.Now); + Assert.Equal(4, layout.LaneCount); + Assert.Equal([0, 1, 0, 1, 2, 3, 0], layout.Skipped.Select(s => s.Lane)); + Assert.Equal(layout.Skipped[2].Instance.Reset, layout.Skipped[^1].Instance.End); + foreach (var lane in layout.Skipped.GroupBy(s => s.Lane)) + { + var rows = lane.Select(s => s.Instance).ToArray(); + for (var i = 1; i < rows.Length; i++) Assert.True(rows[i - 1].Reset <= rows[i].End); + } + } + + [Fact] public void TimelineEndsAtNowOrTheLastEarlyNominalResetAndExcludesTheRunningReset() + { + var running = ResetFixture.RunningOnly(); + var history = running.History.Resets[0]; + var layout = ResetTimeline.CalculateLayout(history, running.Now); + Assert.Equal(history.Instances[0].Start, layout.From); + Assert.Equal(running.Now, layout.To); Assert.Empty(layout.Skipped); + Assert.True(layout.To < history.Instances[0].Reset); + + var early = ResetFixture.Overlapping(); + history = early.History.Resets[0]; + layout = ResetTimeline.CalculateLayout(history, early.Now); + Assert.Equal(history.Instances.Min(r => r.Start), layout.From); + Assert.Equal(history.Instances.Where(r => r.Early).Max(r => r.Reset), layout.To); + Assert.True(layout.To > early.Now); Assert.True(layout.To < history.Instances[0].Reset); + var later = early.Now.AddDays(30); + Assert.Equal(later, ResetTimeline.CalculateLayout(history, later).To); + + var onTime = ResetFixture.OnTimeOnly(); + history = onTime.History.Resets[0]; + history = history with { Instances = history.Instances.Where(r => !r.Running).ToArray() }; + Assert.Equal(onTime.Now, ResetTimeline.CalculateLayout(history, onTime.Now).To); + } + [Fact] public void EveryInstanceColumnSortsByItsUnderlyingValue() { var fixture = ResetFixture.Create(); @@ -63,9 +124,13 @@ public sealed class ResetTests internal sealed record ResetFixture(HistoryStore Store, Snapshot Snapshot, DateTimeOffset Now, HistoryView History) { public static ResetFixture Create() + => Create([7, 1, 2, 7, 1, 2, 1, 1, 2]); + public static ResetFixture RunningOnly() => Create([]); + public static ResetFixture OnTimeOnly() => Create([7, 7]); + public static ResetFixture Overlapping() => Create([1, 1, 1, 1, 1]); + private static ResetFixture Create(int[] durations) { var start = new DateTimeOffset(2026, 9, 12, 6, 0, 0, TimeSpan.Zero); - int[] durations = [7, 1, 2, 7, 1, 2, 1, 1, 2]; var now = start.AddDays(durations.Sum()).AddHours(12); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-resets", Guid.NewGuid().ToString("N")), new(), new FixedClock(now)); var currentStart = start; LimitWindow current = null!; diff --git a/tests/FinalToken.App.Tests/ResetViews.cs b/tests/FinalToken.App.Tests/ResetViews.cs index 1e48f37..6e080f5 100644 --- a/tests/FinalToken.App.Tests/ResetViews.cs +++ b/tests/FinalToken.App.Tests/ResetViews.cs @@ -14,6 +14,7 @@ internal static class ResetViews { public static void Verify(Action save) { + VerifyScenarios(save); var fixture = ResetFixture.Create(); var clock = new FixedClock(fixture.Now); var model = new PanelViewModel { Snapshot = fixture.Snapshot, History = fixture.History, Range = HistoryRange.All }; @@ -104,4 +105,74 @@ internal static class ResetViews Ui.Theme(window); window.Show(); save(window, $"resets-tooltip-{theme}.png"); window.Close(); } } + + private static void VerifyScenarios(Action save) + { + foreach (var (name, fixture) in new[] { ("running-only", ResetFixture.RunningOnly()), + ("on-time", ResetFixture.OnTimeOnly()), ("overlapping", ResetFixture.Overlapping()) }) + foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light }) + { + var history = fixture.History.Resets[0]; + var card = new ResetCard(history, new(ResetColumn.Start), new FixedClock(fixture.Now)); + var window = new Window { Width = 1280, Height = 950, RequestedThemeVariant = theme, + Content = new Border { Padding = new Thickness(24), Child = Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), card)) } }; + Ui.Theme(window); window.Show(); Dispatcher.UIThread.RunJobs(); + using (window.CaptureRenderedFrame()) { } + save(window, $"resets-{name}-{theme}.png"); + TextBlock[] TileBlocks(string label) => card.GetVisualDescendants().OfType() + .Select(s => s.Children.OfType().ToArray()) + .Single(blocks => blocks.Length == 3 && blocks[0].Text == label); + string[] Tile(string label) => TileBlocks(label).Select(t => t.Text!).ToArray(); + Assert.Equal(history.Totals.Finished.ToString(), Tile("Resets")[1]); + var caption = history.Totals.Finished == 0 ? "none yet" : history.Totals.Early + "\u00a0early"; + Assert.Equal(caption + " · 1\u00a0running", Tile("Resets")[2]); + var texts = card.GetVisualDescendants().OfType().Select(t => t.Text).ToArray(); + Assert.Contains("early resets " + history.Totals.Early + " of " + history.Totals.Finished, + texts.Single(t => t?.StartsWith("Median instance ", StringComparison.Ordinal) == true || t?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true)); + if (history.Totals.Finished == 0) + { + Assert.Equal(["Unused", "—", "no finished instance"], Tile("Unused")); + Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Unused")[1].Foreground?.ToString()); + Assert.Contains(texts, text => text?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true); + } + if (history.Totals.Early == 0) + { + Assert.Equal(["Gift", "—", "no early reset"], Tile("Gift")); + Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Gift")[1].Foreground?.ToString()); + Assert.Contains("No early resets in this range", texts); + Assert.Empty(card.GetVisualDescendants().OfType()); + } + else + { + Assert.Equal(2, card.GetVisualDescendants().OfType().Count()); + Assert.Contains(Display.ResetDuration(history.Totals.Skipped) + " skipped", Tile("Gift")[2]); + Assert.DoesNotContain("≈ ", Tile("Gift")[2]); + var timeline = card.GetVisualDescendants().OfType().Single(); + var layout = ResetTimeline.CalculateLayout(history, fixture.Now); + foreach (var skipped in layout.Skipped) + { + ToolTip.SetIsOpen(timeline, false); + window.MouseMove(new Point(4, 4)); Dispatcher.UIThread.RunJobs(); + var mid = skipped.Instance.End + skipped.Instance.Skipped / 2; + var x = 42 + (mid - layout.From).TotalSeconds / (layout.To - layout.From).TotalSeconds * (timeline.Bounds.Width - 58); + var pointer = timeline.TranslatePoint(new Point(x, 181 + skipped.Lane * 10), window)!.Value; + window.MouseMove(pointer); + Assert.True(ToolTip.GetTip(timeline) is DataTooltip, $"{name} {theme}, lane {skipped.Lane}, timeline {timeline.Bounds}"); + var tooltip = Assert.IsType(ToolTip.GetTip(timeline)); + // The tall tooltip opens beside the pointer; over it, it would take the pointer from the timeline. + Assert.True(ToolTip.GetIsOpen(timeline)); + Assert.True(tooltip.Bounds.Width > 320, $"tooltip width {tooltip.Bounds.Width}"); + var tipBounds = new PixelRect(tooltip.PointToScreen(default), PixelSize.FromSize(tooltip.Bounds.Size, 1)); + Assert.False(tipBounds.Contains(window.PointToScreen(pointer)), $"{name} {theme}, lane {skipped.Lane}, tooltip {tipBounds}, pointer {window.PointToScreen(pointer)}, placement {ToolTip.GetPlacement(timeline)}"); + if (skipped == layout.Skipped[0] || skipped == layout.Skipped[^1]) save(window, $"resets-{name}-hover-lane{skipped.Lane}-{theme}.png"); + Assert.Contains(tooltip.Rows, r => r.Label == "End" && r.Value == Display.Projection(skipped.Instance.End, new FixedClock(fixture.Now))); + } + ToolTip.SetIsOpen(timeline, false); + window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width - 10, 80), window)!.Value); + Assert.Null(ToolTip.GetTip(timeline)); + window.MouseMove(new Point(4, 4)); + } + window.Close(); + } + } } diff --git a/tests/FinalToken.Core.Tests/ResetHistoryTests.cs b/tests/FinalToken.Core.Tests/ResetHistoryTests.cs index 0fe43e7..1e1d1ee 100644 --- a/tests/FinalToken.Core.Tests/ResetHistoryTests.cs +++ b/tests/FinalToken.Core.Tests/ResetHistoryTests.cs @@ -82,10 +82,32 @@ public sealed class ResetHistoryTests Assert.Equal(1_000_000, early.Unused.Tokens); Assert.Equal(2m, early.Unused.ApiValue); Assert.Equal(3, history.Totals.Instances); Assert.Equal(2, history.Totals.Finished); Assert.Equal(1, history.Totals.Early); Assert.Equal(3_000_000, history.Totals.Tokens.Total); Assert.Equal(6m, history.Totals.ApiValue); - Assert.Equal(110, history.Totals.Unused.Percent); Assert.Equal(TimeSpan.FromDays(2), history.MedianDuration); + Assert.Equal(110, history.Totals.Unused.Percent); Assert.Equal(TimeSpan.FromDays(4.5), history.MedianDuration); Assert.Equal(TimeSpan.FromDays(5), history.Totals.Skipped); } + [Fact] public void RunningInstanceHasNoFinishedDurationOrResetValues() + { + var history = History(Window(Day), [], []); + Assert.True(Assert.Single(history.Instances).Running); + Assert.Equal(0, history.Totals.Finished); Assert.Equal(0, history.Totals.Early); + Assert.Null(history.MedianDuration); + Assert.Null(history.Instances[0].Unused); Assert.Null(history.Instances[0].Gift); + Assert.All(history.EarlyByHour, count => Assert.Equal(0, count)); + Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count)); + } + + [Fact] public void OnTimeFinishedInstancesHaveNoEarlyResetAndExcludeRunningDurationFromMedian() + { + var history = History(Window(Day + Week * 2), [Window(Day), Window(Day + Week)], []); + Assert.Equal(2, history.Totals.Finished); Assert.Equal(0, history.Totals.Early); + Assert.Equal(Week, history.MedianDuration); + Assert.All(history.Instances.Where(r => !r.Running), row => Assert.NotNull(row.Unused)); + Assert.All(history.Instances, row => Assert.Null(row.Gift)); + Assert.All(history.EarlyByHour, count => Assert.Equal(0, count)); + Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count)); + } + [Fact] public void LowUseUsesMedianOfQualifyingListedInstances() { var first = Window(Day, 50); var second = Window(Day + Week, 25); var current = Window(Day + Week * 2, 4);