Add breakdown chart support

This also cleans up the bar chart code slightly and fixes
some minor bugs that were detected in related code.

Closes #244
This commit is contained in:
Patrik Svensson
2021-01-31 22:46:15 +01:00
committed by Patrik Svensson
parent 58400fe74e
commit b64e016e8c
32 changed files with 911 additions and 41 deletions

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Rendering;
namespace Spectre.Console
{
internal sealed class BreakdownBar : Renderable
{
private readonly List<IBreakdownChartItem> _data;
public int? Width { get; set; }
public BreakdownBar(List<IBreakdownChartItem> data)
{
_data = data ?? throw new ArgumentNullException(nameof(data));
}
protected override Measurement Measure(RenderContext context, int maxWidth)
{
var width = Math.Min(Width ?? maxWidth, maxWidth);
return new Measurement(width, width);
}
protected override IEnumerable<Segment> Render(RenderContext context, int maxWidth)
{
var width = Math.Min(Width ?? maxWidth, maxWidth);
// Chart
var maxValue = _data.Sum(i => i.Value);
var items = _data.ToArray();
var bars = Ratio.Distribute(width, items.Select(i => Math.Max(0, (int)(width * (i.Value / maxValue)))).ToArray());
for (var index = 0; index < items.Length; index++)
{
yield return new Segment(new string('█', bars[index]), new Style(items[index].Color));
}
yield return Segment.LineBreak;
}
}
}