Files
Chronos/src/Titano.Ui/Visuals/StackedBar.cs
T
Claude df4af1013a feat(ui-visuals): add series, bar, heatmap, stacked and timeline charts
SeriesChart decimates each line to two points per pixel column and adds a
legend row, nice-tick gridlines, dashed markers, a playhead, click-to-seek
and a hover readout. BarChart, HeatmapStrip, StackedBar and TimelineBands
cover the Archive statistics and the Library timeline bands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 10:27:09 +00:00

204 lines
8.8 KiB
C#

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Titano.Core.Localization;
namespace Titano.Ui.Visuals;
/// <summary>
/// One bar split into proportional segments (by camera, by format) with a wrapping legend underneath
/// ("■ label share"). Segments share one theme colour and fade by rank (items may set their own brush), so no new
/// colours are introduced; 2-px gaps separate them. Hovering a segment or legend entry reads it out; clicking
/// raises <see cref="ItemActivatedEvent"/>.
/// </summary>
public sealed class StackedBar : DrawingElement
{
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
nameof(Items), typeof(IReadOnlyList<ChartItem>), typeof(StackedBar), new PropertyMetadata(null, OnDataPropertyChanged));
public static readonly DependencyProperty BrushKeyProperty = DependencyProperty.Register(
nameof(BrushKey), typeof(string), typeof(StackedBar), new FrameworkPropertyMetadata("Brush.Accent", FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty BarHeightProperty = DependencyProperty.Register(
nameof(BarHeight), typeof(double), typeof(StackedBar),
new FrameworkPropertyMetadata(12.0, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty ShowLegendProperty = DependencyProperty.Register(
nameof(ShowLegend), typeof(bool), typeof(StackedBar),
new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty ShareFormatterProperty = DependencyProperty.Register(
nameof(ShareFormatter), typeof(Func<double, string>), typeof(StackedBar),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly RoutedEvent ItemActivatedEvent = EventManager.RegisterRoutedEvent(
nameof(ItemActivated), RoutingStrategy.Bubble, typeof(ChartItemEventHandler), typeof(StackedBar));
private const double LabelSize = 11;
private const double SegmentGap = 2;
private const double LegendGap = 10;
private const double LegendLine = 18;
private const double EntryGap = 14;
private readonly List<Rect> _segments = [];
private readonly List<Rect> _entries = [];
private int _hover = -1;
/// <summary>Parts in display order (largest first reads best).</summary>
public IReadOnlyList<ChartItem>? Items { get => (IReadOnlyList<ChartItem>?)GetValue(ItemsProperty); set => SetValue(ItemsProperty, value); }
public string BrushKey { get => (string)GetValue(BrushKeyProperty); set => SetValue(BrushKeyProperty, value); }
public double BarHeight { get => (double)GetValue(BarHeightProperty); set => SetValue(BarHeightProperty, value); }
public bool ShowLegend { get => (bool)GetValue(ShowLegendProperty); set => SetValue(ShowLegendProperty, value); }
/// <summary>Formats a share 0…1 for the legend (default: culture percent without decimals).</summary>
public Func<double, string>? ShareFormatter { get => (Func<double, string>?)GetValue(ShareFormatterProperty); set => SetValue(ShareFormatterProperty, value); }
public event ChartItemEventHandler ItemActivated
{
add => AddHandler(ItemActivatedEvent, value);
remove => RemoveHandler(ItemActivatedEvent, value);
}
protected override Size MeasureOverride(Size availableSize)
{
if (Items is not { Count: > 0 } items) return new Size(0, 0);
var lines = ShowLegend ? LayoutLegend(items, availableSize.Width, null) : 0;
return new Size(0, BarHeight + (lines > 0 ? LegendGap + lines * LegendLine : 0));
}
protected override void OnDataChanged()
{
_hover = -1;
base.OnDataChanged();
}
protected override void OnRender(DrawingContext dc)
{
DrawHitArea(dc);
_segments.Clear();
_entries.Clear();
if (Items is not { Count: > 0 } items) return;
var total = Total(items);
var width = ActualWidth;
var radius = Math.Min(3, BarHeight / 2);
dc.PushClip(new RectangleGeometry(new Rect(0, 0, width, BarHeight), radius, radius));
dc.DrawRectangle(GetBrush("Brush.Track"), null, new Rect(0, 0, width, BarHeight));
var available = Math.Max(0, width - SegmentGap * (items.Count - 1));
var x = 0.0;
for (var i = 0; i < items.Count; i++)
{
var share = total > 0 ? Math.Max(0, items[i].Value) / total : 0;
var segment = new Rect(x, 0, available * share, BarHeight);
_segments.Add(segment);
dc.PushOpacity(OpacityOf(i, items));
dc.DrawRectangle(GetBrush(items[i].BrushKey ?? BrushKey), null, segment);
dc.Pop();
x = segment.Right + SegmentGap;
}
dc.Pop();
if (ShowLegend) LayoutLegend(items, width, dc);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
var p = e.GetPosition(this);
_hover = HitTest(p);
Readout.Show(_hover >= 0 ? ReadoutText(_hover) : null, p);
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
_hover = -1;
Readout.Hide();
}
protected override void OnQueryCursor(QueryCursorEventArgs e)
{
base.OnQueryCursor(e);
if (e.Handled || _hover < 0) return;
e.Cursor = Cursors.Hand;
e.Handled = true;
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
var index = HitTest(e.GetPosition(this));
if (index < 0) return;
RaiseEvent(new ChartItemEventArgs(ItemActivatedEvent, index, -1));
e.Handled = true;
}
private static double Total(IReadOnlyList<ChartItem> items)
{
var total = 0.0;
for (var i = 0; i < items.Count; i++) total += Math.Max(0, items[i].Value);
return total;
}
/// <summary>Rank fade 1 → 0.35 for items in the shared colour; items with their own brush stay opaque.</summary>
private static double OpacityOf(int index, IReadOnlyList<ChartItem> items) =>
items[index].BrushKey is not null || items.Count < 2 ? 1 : 1 - 0.65 * index / (items.Count - 1);
private string Share(double share) => ShareFormatter?.Invoke(share) ?? share.ToString("P0", Loc.Culture);
/// <summary>Flows legend entries into lines of the given width; draws them when <paramref name="dc"/> is set. Returns the line count.</summary>
private int LayoutLegend(IReadOnlyList<ChartItem> items, double width, DrawingContext? dc)
{
var total = Total(items);
var muted = GetBrush("Brush.TextMuted");
var text = GetBrush("Brush.Text");
double x = 0;
var line = 0;
var top = BarHeight + LegendGap;
for (var i = 0; i < items.Count; i++)
{
var label = CreateText(items[i].Label, LabelSize, muted);
var value = CreateText(items[i].ValueText ?? Share(total > 0 ? Math.Max(0, items[i].Value) / total : 0), LabelSize, text);
var entryWidth = 8 + 6 + label.Width + 4 + value.Width;
if (x > 0 && double.IsFinite(width) && x + entryWidth > width)
{
x = 0;
line++;
}
if (dc is not null)
{
var y = top + line * LegendLine;
var cy = y + label.Height / 2;
dc.PushOpacity(OpacityOf(i, items));
dc.DrawRoundedRectangle(GetBrush(items[i].BrushKey ?? BrushKey), null, new Rect(x, cy - 4, 8, 8), 2, 2);
dc.Pop();
dc.DrawText(label, new Point(x + 14, y));
dc.DrawText(value, new Point(x + 14 + label.Width + 4, y));
_entries.Add(new Rect(x, y, entryWidth, LegendLine));
}
x += entryWidth + EntryGap;
}
return line + 1;
}
private int HitTest(Point p)
{
for (var i = 0; i < _segments.Count; i++)
if (p.Y >= 0 && p.Y <= BarHeight && p.X >= _segments[i].Left && p.X <= _segments[i].Right + SegmentGap) return i;
for (var i = 0; i < _entries.Count; i++)
if (_entries[i].Contains(p)) return i;
return -1;
}
private string ReadoutText(int index)
{
var items = Items!;
var item = items[index];
if (item.ToolTip is not null) return item.ToolTip;
var total = Total(items);
var share = Share(total > 0 ? Math.Max(0, item.Value) / total : 0);
return item.Label + " · " + (item.ValueText is null ? share : item.ValueText + " · " + share);
}
}