diff --git a/CLAUDE.md b/CLAUDE.md index e74169b..ce7cbe0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,7 +68,7 @@ Pages live in `Schaad.Accounting.UI/Components/Pages/`. Each page typically has - `Microsoft.FluentUI.AspNetCore.Components` — UI components (FluentDataGrid, FluentDialog, etc.) - `Plotly.Blazor` — charts on the older chart pages -- Chart.js 4 — charts on the Analyse page; vendored in `wwwroot/lib/chartjs` (no CDN), wrapped by `wwwroot/js/charts.js` and `StackedBarChart.razor` +- Chart.js 4 + `chartjs-chart-treemap` — charts on the Analyse page; vendored in `wwwroot/lib/` (no CDN), wrapped by `wwwroot/js/charts.js` and `ChartJsChart.razor` - `FreeSpire.PDF` — PDF parsing for bank statement imports - `Schaad.Finance.dll` / `Schaad.Finance.Api.dll` — proprietary DLLs for MT940/CAMT053 parsing and FX rate lookups (FixerIo API key in `appsettings.Development.json`) diff --git a/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs b/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs index 3ed8cd3..786f19a 100644 --- a/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs +++ b/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs @@ -60,6 +60,30 @@ namespace Schaad.Accounting.Datasets.Analytics public decimal? ChangePercent => Previous == 0 ? null : (Current - Previous) / Math.Abs(Previous) * 100; } + /// + /// Monthly values of the queried node in one year (index 0 = January). Months after the last + /// month with data are null. + /// + public record YearProfile(int Year, IReadOnlyList Months, decimal Total); + + /// + /// A category's value in one year. For the running year only the months with data count, and + /// the change compares the same months of the previous year. + /// + public record YearCell(int Year, decimal Value, decimal? ChangePercent); + + /// + /// One row of the category × year table, in the same order as . + /// + public record CategoryYears(AnalyticsNode Node, string Name, bool CanDrillDown, IReadOnlyList Cells, decimal Total); + + /// + /// A treemap tile: a child of the queried node and, one level deeper, one of its children. + /// is null when the child has no deeper level (booking-text groups). + /// Only positive amounts are included; an area can't show a refund. + /// + public record CompositionItem(AnalyticsNode Parent, string ParentName, AnalyticsNode? Child, string? ChildName, decimal Value); + public record AnalyticsResult( IReadOnlyList Breadcrumb, IReadOnlyList Periods, @@ -67,5 +91,8 @@ namespace Schaad.Accounting.Datasets.Analytics decimal Total, int Months, decimal AveragePerMonth, - YearComparison? Comparison); + YearComparison? Comparison, + IReadOnlyList YearProfiles, + IReadOnlyList CategoryYears, + IReadOnlyList Composition); } diff --git a/Schaad.Accounting.Services/ExpenseAnalysis.cs b/Schaad.Accounting.Services/ExpenseAnalysis.cs index dbbd1eb..fe30121 100644 --- a/Schaad.Accounting.Services/ExpenseAnalysis.cs +++ b/Schaad.Accounting.Services/ExpenseAnalysis.cs @@ -128,7 +128,83 @@ namespace Schaad.Accounting.Services total, months, months == 0 ? 0 : total / months, - GetComparison(nodeFacts, end)); + GetComparison(nodeFacts, end), + GetYearProfiles(nodeFacts, start, end), + GetCategoryYears(nodeFacts, query.Node, categories, start, end), + GetComposition(inRange, query.Node, categories)); + } + + private static List GetYearProfiles(List nodeFacts, DateOnly start, DateOnly end) + { + var profiles = new List(); + for (var year = start.Year; year <= end.Year; year++) + { + var lastMonth = year == end.Year ? end.Month : 12; + var months = new decimal?[12]; + for (var month = 1; month <= lastMonth; month++) + { + months[month - 1] = 0; + } + foreach (var fact in nodeFacts.Where(f => f.Month.Year == year && f.Month.Month <= lastMonth)) + { + months[fact.Month.Month - 1] += fact.Amount; + } + profiles.Add(new YearProfile(year, months, months.Sum() ?? 0)); + } + return profiles; + } + + private List GetCategoryYears(List nodeFacts, AnalyticsNode node, List categories, DateOnly start, DateOnly end) + { + // Not limited to the range: the first year's change needs the year before. + var factsByChild = nodeFacts.GroupBy(f => ChildOf(f, node)).ToDictionary(g => g.Key, g => g.ToList()); + + return categories.Select(category => + { + var childFacts = factsByChild.GetValueOrDefault(category.Node) ?? new List(); + var cells = new List(); + for (var year = start.Year; year <= end.Year; year++) + { + var lastMonth = year == end.Year ? end.Month : 12; + var value = SumYear(childFacts, year, lastMonth); + decimal? change = null; + if (Years.Contains(year - 1)) + { + var previous = SumYear(childFacts, year - 1, lastMonth); + change = previous == 0 ? null : (value - previous) / Math.Abs(previous) * 100; + } + cells.Add(new YearCell(year, value, change)); + } + return new CategoryYears(category.Node, category.Name, category.CanDrillDown, cells, category.Total); + }).ToList(); + } + + private static decimal SumYear(List facts, int year, int lastMonth) + => facts.Where(f => f.Month.Year == year && f.Month.Month <= lastMonth).Sum(f => f.Amount); + + private List GetComposition(List inRange, AnalyticsNode node, List categories) + { + var items = new List(); + foreach (var category in categories.Where(c => c.Total > 0)) + { + if (category.Node.Level == AnalyticsLevel.Text) + { + items.Add(new CompositionItem(category.Node, category.Name, null, null, category.Total)); + continue; + } + + var children = inRange + .Where(f => ChildOf(f, node) == category.Node) + .GroupBy(f => ChildOf(f, category.Node)) + .Select(g => (Node: g.Key, Value: g.Sum(f => f.Amount))) + .Where(c => c.Value > 0) + .OrderByDescending(c => c.Value); + foreach (var child in children) + { + items.Add(new CompositionItem(category.Node, category.Name, child.Node, NameOf(child.Node), child.Value)); + } + } + return items; } private YearComparison? GetComparison(List nodeFacts, DateOnly end) diff --git a/Schaad.Accounting.Tests/ExpenseAnalysisTestShould.cs b/Schaad.Accounting.Tests/ExpenseAnalysisTestShould.cs index 7911e4f..1a2a751 100644 --- a/Schaad.Accounting.Tests/ExpenseAnalysisTestShould.cs +++ b/Schaad.Accounting.Tests/ExpenseAnalysisTestShould.cs @@ -252,4 +252,99 @@ public class ExpenseAnalysisTestShould result.Categories.ShouldBeEmpty(); result.Periods.Count.ShouldBe(12); } + + [Fact] + public void LeaveMonthsWithoutDataEmptyWhenBuildingYearProfiles() + { + var sut = new ExpenseAnalysis( + [ + Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-12-10", Bank, Food, 50)), + Year(2026, Booking("2026-02-10", Bank, Food, 70)) + ]); + + var profiles = sut.Query(Query(2025, 2026)).YearProfiles; + + profiles.Select(p => p.Year).ShouldBe([2025, 2026]); + profiles[0].Months.Count.ShouldBe(12); + profiles[0].Months[0].ShouldBe(100); + profiles[0].Months[1].ShouldBe(0); + profiles[0].Total.ShouldBe(150); + profiles[1].Months[0].ShouldBe(0); + profiles[1].Months[1].ShouldBe(70); + profiles[1].Months[2].ShouldBeNull(); + } + + [Fact] + public void CompareSameMonthsWithPreviousYearWhenBuildingCategoryYears() + { + var sut = new ExpenseAnalysis( + [ + Year(2024, Booking("2024-01-10", Bank, Food, 100), Booking("2024-06-10", Bank, Rent, 400)), + Year(2025, Booking("2025-01-10", Bank, Food, 150), Booking("2025-06-10", Bank, Rent, 500), Booking("2025-11-10", Bank, Rent, 999)), + Year(2026, Booking("2026-01-10", Bank, Food, 120), Booking("2026-02-10", Bank, Rent, 300)) + ]); + + // Range starts in 2025, so 2025's change still compares with 2024. + var rows = sut.Query(Query(2025, 2026)).CategoryYears; + + var food = rows.Single(r => r.Name == "Verpflegung"); + food.Cells.Select(c => (c.Year, c.Value)).ShouldBe([(2025, 150m), (2026, 120m)]); + food.Cells[0].ChangePercent.ShouldBe(50); + food.Cells[1].ChangePercent.ShouldBe(-20); // Jan–Feb 2026 vs. Jan–Feb 2025 + var rent = rows.Single(r => r.Name == "Wohnen"); + rent.Cells[1].Value.ShouldBe(300); + rent.Cells[1].ChangePercent.ShouldBeNull(); // nothing in Jan–Feb 2025 + rows.Select(r => r.Node).ShouldBe(sut.Query(Query(2025, 2026)).Categories.Select(c => c.Node)); + } + + [Fact] + public void ReturnNoChangeWhenYearBeforeHasNoData() + { + var sut = new ExpenseAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100))]); + + sut.Query(Query(2025, 2025)).CategoryYears.Single().Cells.Single().ChangePercent.ShouldBeNull(); + } + + [Fact] + public void NestAccountsInSubClassesWhenBuildingComposition() + { + var sut = new ExpenseAnalysis([Year(2025, + Booking("2025-01-10", Bank, Food, 100), + Booking("2025-01-11", Bank, Restaurant, 40), + Booking("2025-01-12", Bank, Rent, 1000))]); + + var items = sut.Query(Query(2025, 2025)).Composition; + + items.Select(i => (i.ParentName, i.ChildName, i.Value)).ShouldBe( + [ + ("Wohnen", "Miete", 1000m), + ("Verpflegung", "Lebensmittel", 100m), + ("Verpflegung", "Restaurant", 40m) + ]); + items[1].Child.ShouldBe(new AnalyticsNode(40, 4000)); + } + + [Fact] + public void UseSingleLevelWhenBuildingCompositionForAccount() + { + var sut = new ExpenseAnalysis([Year(2025, + Booking("2025-01-10", Bank, Food, 100, "Migros"), + Booking("2025-01-11", Bank, Food, 30, "Coop"))]); + + var items = sut.Query(Query(2025, 2025, new AnalyticsNode(40, 4000))).Composition; + + items.Select(i => (i.ParentName, i.Child, i.Value)).ShouldBe([("Migros", (AnalyticsNode?)null, 100m), ("Coop", null, 30m)]); + } + + [Fact] + public void LeaveOutNegativeAmountsWhenBuildingComposition() + { + var sut = new ExpenseAnalysis([Year(2025, + Booking("2025-01-10", Bank, Food, 100), + Booking("2025-01-11", Restaurant, Bank, 40))]); + + var items = sut.Query(Query(2025, 2025, new AnalyticsNode(SubClass: 40))).Composition; + + items.Single().ParentName.ShouldBe("Lebensmittel"); + } } diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor index 3e6aca7..66fa996 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor @@ -75,7 +75,7 @@ @if (result.Comparison is { } comparison) {
@ComparisonLabel(comparison)
-
@ChangeLabel(comparison)
+
@ChangeLabel(comparison)
@Chf(comparison.Current) statt @Chf(comparison.Previous)
} else @@ -106,9 +106,9 @@
@CurrentName im Verlauf
@if (result.Categories.Count > 0) { - - @if (node.Level != AnalyticsLevel.Text) + + @if (CanDrillDown) {
Klick auf einen Balken oder einen Eintrag rechts zeigt die Details.
} @@ -149,4 +149,100 @@ + + @if (result.Categories.Count > 0) + { +
+ +
Zusammensetzung @RangeLabel
+ @if (result.Composition.Count > 0) + { + +
Fläche entspricht dem Betrag; Rückerstattungen (negative Beträge) sind nicht enthalten.@(CanDrillDown ? " Klick auf eine Fläche zeigt die Details." : "")
+ } + else + { +
Keine positiven Beträge im gewählten Zeitraum.
+ } +
+ + +
+
Jahresvergleich
+
+ Monatlich + Kumuliert +
+
+ +
+
+ + +
Jahre im Vergleich
+
+ + + + + @foreach (var profile in result.YearProfiles) + { + + } + + + + + @foreach (var row in result.CategoryYears) + { + + + @foreach (var cell in row.Cells) + { + @if (cell.Value == 0) + { + + } + else + { + + } + } + + + } + + + + + @foreach (var profile in result.YearProfiles) + { + + } + + + +
@ChildLevelName@YearHeader(profile.Year)Total
+ @if (row.CanDrillDown) + { + @row.Name + } + else + { + @row.Name + } + – + @Whole(cell.Value) +
@ChangeText(cell.ChangePercent)
+
@Whole(row.Total)
Total@Whole(profile.Total)@Whole(result.Total)
+
+
Beträge in CHF; Farbe = Ø pro Monat, damit ein laufendes Jahr vergleichbar bleibt; Prozent = Veränderung zum Vorjahr.@(lastYearMonths < 12 ? " " + PartialYearNote : "")
+
+ } diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs index 88df4f2..6a200f2 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs @@ -16,7 +16,13 @@ namespace Schaad.Accounting.UI.Components.Pages.Analytics; public partial class Analytics : ComponentBase { private static readonly CultureInfo Swiss = new("de-CH"); + private static readonly CultureInfo SwissNumbers = CreateSwissNumbers(); private static readonly AnalyticsPeriod[] Periods = [AnalyticsPeriod.Month, AnalyticsPeriod.Quarter, AnalyticsPeriod.Year]; + private static readonly string[] MonthNames = ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"]; + + // Year-comparison lines: the latest year in the accent colour, the one before in orange, + // older ones in fading grey. + private static readonly string[] OlderYearColors = ["#898781", "#a9a8a3", "#c4c3be", "#d6d5d0"]; [Inject] private IAnalyticsService analyticsService { get; set; } = null!; @@ -53,12 +59,22 @@ public partial class Analytics : ComponentBase private int toYear; private AnalyticsPeriod period; - private IReadOnlyList chartLabels = []; - private IReadOnlyList chartSeries = []; - // Category behind each chart series; null for the folded "Andere" series. + private object barData = new(); + // Category behind each bar series; null for the folded "Andere" series. private List seriesCategories = []; private int coloredCount; + private object treemapData = new(); + // Treemap click key ("p3" or "p3|c7") → drill-down target. + private Dictionary treemapNodes = []; + + private object lineData = new(); + private bool cumulative = true; + + // Heat shading of the year table: a cell's monthly average relative to the largest one. + private decimal maxMonthlyAverage; + private int lastYearMonths = 12; + protected override async Task OnInitializedAsync() { mandator = settingsService.GetMandator(); @@ -86,23 +102,24 @@ public partial class Analytics : ComponentBase : AnalyticsNode.All; result = analysis.Query(new AnalyticsQuery(fromYear, toYear, period, node)); - BuildChart(result); + BuildBarChart(result); + BuildTreemap(result); + BuildLineChart(result); + BuildYearTable(result); } - private void BuildChart(AnalyticsResult data) + private void BuildBarChart(AnalyticsResult data) { - chartLabels = data.Periods.Select(PeriodLabel).ToList(); - // Same folding as the other charts: past MaxCategories, the tail becomes "Andere". var categories = data.Categories; coloredCount = categories.Count > ChartTheme.MaxCategories ? ChartTheme.MaxCategories - 1 : categories.Count; - var series = new List(); + var series = new List(); seriesCategories = []; for (var i = 0; i < coloredCount; i++) { var category = categories[i]; - series.Add(new ChartSeries(category.Name, ChartTheme.ColorAt(i), category.Values, category.CanDrillDown)); + series.Add(new { name = category.Name, color = ChartTheme.ColorAt(i), values = category.Values, clickable = category.CanDrillDown }); seriesCategories.Add(category); } if (coloredCount < categories.Count) @@ -115,34 +132,130 @@ public partial class Analytics : ComponentBase other[p] += category.Values[p]; } } - series.Add(new ChartSeries(ChartTheme.OtherLabel, ChartTheme.OtherColor, other, Clickable: false)); + series.Add(new { name = ChartTheme.OtherLabel, color = ChartTheme.OtherColor, values = other, clickable = false }); seriesCategories.Add(null); } - chartSeries = series; + barData = new { labels = data.Periods.Select(PeriodLabel).ToList(), series }; } - private void OnSeriesClick(int seriesIndex) + private void BuildTreemap(AnalyticsResult data) { - if (seriesCategories.ElementAtOrDefault(seriesIndex) is { CanDrillDown: true } category) + // Parent ids follow the category order, so a parent has the same colour as in the bar + // chart and the list. + var parents = data.Categories + .Select((category, i) => (category.Node, Id: $"p{i}", Color: ColorFor(i))) + .ToDictionary(x => x.Node); + var names = new Dictionary(); + var colors = new Dictionary(); + var items = new List(); + treemapNodes = []; + + foreach (var item in data.Composition) + { + var parent = parents[item.Parent]; + names[parent.Id] = item.ParentName; + colors[parent.Id] = parent.Color; + if (item.Parent.Level != AnalyticsLevel.Text) + { + treemapNodes[parent.Id] = item.Parent; + } + + string? childId = null; + if (item.Child is { } child) + { + childId = $"c{items.Count}"; + names[childId] = item.ChildName!; + treemapNodes[$"{parent.Id}|{childId}"] = child; + } + items.Add(new { p = parent.Id, c = childId, value = item.Value }); + } + treemapData = new { items, names, colors, clickable = treemapNodes.Keys.ToList() }; + } + + private void BuildLineChart(AnalyticsResult data) + { + var profiles = data.YearProfiles; + var series = profiles.Select((profile, i) => + { + var age = profiles.Count - 1 - i; + var color = age switch + { + 0 => ChartTheme.Categorical[0], + 1 => ChartTheme.Categorical[1], + _ => OlderYearColors[Math.Min(age - 2, OlderYearColors.Length - 1)] + }; + var values = cumulative ? RunningTotal(profile.Months) : profile.Months; + return new { name = profile.Year.ToString(), color, values, width = age == 0 ? 3 : 2 }; + }).ToList(); + lineData = new { labels = MonthNames, series }; + } + + private static IReadOnlyList RunningTotal(IReadOnlyList months) + { + var sum = 0m; + return months.Select(m => m is { } value ? sum += value : (decimal?)null).ToList(); + } + + private void SetCumulative(bool value) + { + cumulative = value; + BuildLineChart(result!); + } + + private void BuildYearTable(AnalyticsResult data) + { + lastYearMonths = data.YearProfiles[^1].Months.Count(m => m is not null); + maxMonthlyAverage = data.CategoryYears + .SelectMany(row => row.Cells) + .Select(cell => cell.Value / MonthsOf(cell.Year)) + .DefaultIfEmpty(0) + .Max(); + } + + private int MonthsOf(int year) => year == toYear ? Math.Max(lastYearMonths, 1) : 12; + + private void OnBarClick(string key) + { + if (int.TryParse(key, out var index) && seriesCategories.ElementAtOrDefault(index) is { CanDrillDown: true } category) { navigation.NavigateTo(NodeUrl(category.Node)); } } + private void OnTreemapClick(string key) + { + if (treemapNodes.TryGetValue(key, out var target)) + { + navigation.NavigateTo(NodeUrl(target)); + } + } + + // FluentSelect reports its selection again whenever it re-renders. The new year only reaches + // OnParametersSet once the navigation completes, so it is taken over right away; otherwise + // every re-render starts another navigation to the same URL, cancelling the previous one, + // and the page never updates. private void OnFromChanged(int year) { - if (year != fromYear) + if (year == fromYear) { - navigation.NavigateTo(Url(node, year, year > toYear ? year : To, Period)); + return; } + var url = Url(node, year, year > toYear ? year : To, Period); + fromYear = year; + toYear = Math.Max(toYear, year); + navigation.NavigateTo(url); } private void OnToChanged(int year) { - if (year != toYear) + if (year == toYear) { - navigation.NavigateTo(Url(node, year < fromYear ? year : From, year, Period)); + return; } + var url = Url(node, year < fromYear ? year : From, year, Period); + toYear = year; + fromYear = Math.Min(fromYear, year); + navigation.NavigateTo(url); } private void ShowAllYears() => navigation.NavigateTo(Url(node, null, null, Period)); @@ -179,6 +292,8 @@ public partial class Analytics : ComponentBase _ => "Jahr" }; + private bool CanDrillDown => result!.Categories.Any(c => c.CanDrillDown); + private string RangeLabel => fromYear == toYear ? fromYear.ToString() : $"{fromYear}–{toYear}"; private string CurrentName => result!.Breadcrumb[^1].Name; @@ -194,10 +309,31 @@ public partial class Analytics : ComponentBase private static string Chf(decimal value) => ChartFormatting.Chf(value); + private static string Whole(decimal value) => value.ToString("#,0", SwissNumbers); + private static string Percent(decimal share) => (share * 100).ToString("0.0", Swiss) + " %"; private static string ShareWidth(decimal share) => Math.Clamp(share * 100, 0, 100).ToString("0.##", CultureInfo.InvariantCulture) + "%"; + private string YearHeader(int year) => year == toYear && lastYearMonths < 12 ? $"{year}*" : year.ToString(); + + private string PartialYearNote + => $"* {toYear}: Januar–{Swiss.DateTimeFormat.GetMonthName(lastYearMonths)}; Veränderung gegenüber denselben Monaten im Vorjahr."; + + private string HeatColor(YearCell cell) + { + if (maxMonthlyAverage <= 0 || cell.Value <= 0) + { + return "transparent"; + } + var intensity = Math.Min(cell.Value / MonthsOf(cell.Year) / maxMonthlyAverage, 1); + // Capped so dark text stays readable on the strongest cells. + return $"rgba(42, 120, 214, {(0.06m + intensity * 0.5m).ToString("0.###", CultureInfo.InvariantCulture)})"; + } + + private static string ChangeText(decimal? change) + => change is { } c ? (c > 0 ? "+" : "") + c.ToString("0", Swiss) + " %" : ""; + private static string ComparisonLabel(YearComparison comparison) => comparison.Months == 12 ? $"{comparison.Year} vs. {comparison.Year - 1}" @@ -207,6 +343,12 @@ public partial class Analytics : ComponentBase => comparison.ChangePercent is { } change ? (change > 0 ? "+" : "") + change.ToString("0.0", Swiss) + " %" : "–"; // For expenses, more is worse. - private static string ChangeClass(YearComparison comparison) - => comparison.ChangePercent switch { > 0 => "up", < 0 => "down", _ => "" }; + private static string ChangeClass(decimal? change) => change switch { > 0 => "up", < 0 => "down", _ => "" }; + + private static CultureInfo CreateSwissNumbers() + { + var culture = new CultureInfo("de-CH"); + culture.NumberFormat.NumberGroupSeparator = "'"; + return culture; + } } diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css index 65b9ab1..fd42d3e 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css @@ -161,3 +161,113 @@ color: #52514e; font-size: 12px; } + +.pair { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + gap: 12px; +} + +@media (max-width: 1100px) { + .pair { + grid-template-columns: minmax(0, 1fr); + } +} + +.card-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 12px; +} + +.card-header .card-title { + margin-bottom: 0; +} + +.segmented.small { + margin-left: 0; +} + +::deep .table-card { + padding: 16px; + min-width: 0; +} + +.table-scroll { + overflow-x: auto; +} + +.years { + width: 100%; + border-collapse: separate; + border-spacing: 2px; + font-variant-numeric: tabular-nums; +} + +.years th, +.years td { + padding: 6px 8px; + text-align: right; + white-space: nowrap; + border-radius: 3px; +} + +.years thead th { + color: #52514e; + font-weight: 600; + font-size: 12px; +} + +.years .name { + text-align: left; + font-weight: normal; + max-width: 280px; + overflow: hidden; + text-overflow: ellipsis; +} + +.years thead .name { + font-weight: 600; +} + +.years .name a { + color: inherit; + text-decoration: none; +} + +.years .name a:hover, +.years .name a:focus-visible { + text-decoration: underline; +} + +.years .total { + font-weight: 600; + border-left: 1px solid #e1e0d9; +} + +.years tfoot th, +.years tfoot td { + font-weight: 600; + border-top: 1px solid #e1e0d9; +} + +.years .zero { + color: #c4c3be; +} + +.change { + font-size: 11px; + color: #52514e; + min-height: 14px; +} + +.change.up { + color: #c50f1f; +} + +.change.down { + color: #107c10; +} diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor b/Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor new file mode 100644 index 0000000..f466d21 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor @@ -0,0 +1,6 @@ +@* Chart.js chart (wwwroot/js/charts.js). Created once; a new Data object is pushed as an in-place + update so the chart animates instead of being rebuilt. *@ + +
+ +
diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor.cs b/Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor.cs similarity index 61% rename from Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor.cs rename to Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor.cs index 2e2de83..1502129 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor.cs +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor.cs @@ -3,30 +3,29 @@ using Microsoft.JSInterop; namespace Schaad.Accounting.UI.Components.Pages.Analytics; -public record ChartSeries(string Name, string Color, IReadOnlyList Values, bool Clickable); - -public partial class StackedBarChart : ComponentBase, IAsyncDisposable +public partial class ChartJsChart : ComponentBase, IAsyncDisposable { private ElementReference canvas; private IJSObjectReference? module; private IJSObjectReference? chart; private Task? creating; - private DotNetObjectReference? selfReference; - private IReadOnlyList? renderedLabels; - private IReadOnlyList? renderedSeries; + private DotNetObjectReference? selfReference; + private object? renderedData; [Inject] private IJSRuntime js { get; set; } = null!; + /// "stackedBar", "line" or "treemap"; see charts.js for the data each one takes. [Parameter, EditorRequired] - public IReadOnlyList Labels { get; set; } = []; + public string Kind { get; set; } = ""; + /// Serialized to JSON for charts.js. Pass a new object to update the chart. [Parameter, EditorRequired] - public IReadOnlyList Series { get; set; } = []; + public object Data { get; set; } = null!; - /// Called with the index into when a clickable segment is clicked. + /// Called with the clicked element's key (see charts.js) when a clickable element is clicked. [Parameter] - public EventCallback OnSeriesClick { get; set; } + public EventCallback OnClick { get; set; } [Parameter] public string Height { get; set; } = "420px"; @@ -36,18 +35,11 @@ public partial class StackedBarChart : ComponentBase, IAsyncDisposable protected override async Task OnAfterRenderAsync(bool firstRender) { - if (ReferenceEquals(Labels, renderedLabels) && ReferenceEquals(Series, renderedSeries)) + if (ReferenceEquals(Data, renderedData)) { return; } - renderedLabels = Labels; - renderedSeries = Series; - - var data = new - { - labels = Labels, - series = Series.Select(s => new { name = s.Name, color = s.Color, values = s.Values, clickable = s.Clickable }) - }; + var data = renderedData = Data; if (creating is null) { @@ -65,11 +57,11 @@ public partial class StackedBarChart : ComponentBase, IAsyncDisposable { module = await js.InvokeAsync("import", "./js/charts.js"); selfReference = DotNetObjectReference.Create(this); - chart = await module.InvokeAsync("createStackedBar", canvas, data, selfReference); + chart = await module.InvokeAsync("createChart", canvas, Kind, data, selfReference); } [JSInvokable] - public Task OnSeriesClicked(int seriesIndex) => OnSeriesClick.InvokeAsync(seriesIndex); + public Task OnChartClicked(string key) => OnClick.InvokeAsync(key); public async ValueTask DisposeAsync() { diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor.css b/Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor.css similarity index 100% rename from Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor.css rename to Schaad.Accounting.UI/Components/Pages/Analytics/ChartJsChart.razor.css diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor b/Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor deleted file mode 100644 index 906ef49..0000000 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/StackedBarChart.razor +++ /dev/null @@ -1,6 +0,0 @@ -@* Chart.js stacked bar chart (wwwroot/js/charts.js). Created once; later parameter changes are - pushed as an in-place update so the chart animates instead of being rebuilt. *@ - -
- -
diff --git a/Schaad.Accounting.UI/wwwroot/js/charts.js b/Schaad.Accounting.UI/wwwroot/js/charts.js index 5909657..c3dfd8d 100644 --- a/Schaad.Accounting.UI/wwwroot/js/charts.js +++ b/Schaad.Accounting.UI/wwwroot/js/charts.js @@ -1,20 +1,28 @@ -// Thin Chart.js wrapper for Blazor (see StackedBarChart.razor). Chart.js is loaded on first use -// from wwwroot/lib/chartjs, so pages without charts don't pay for it. +// Thin Chart.js wrapper for Blazor (see ChartJsChart.razor). Chart.js and the treemap plugin are +// loaded on first use from wwwroot/lib, so pages without charts don't pay for them. -let chartJsLoading; +const scripts = new Map(); -function loadChartJs() { - if (window.Chart) { - return Promise.resolve(); +function loadScript(src) { + if (!scripts.has(src)) { + scripts.set(src, new Promise((resolve, reject) => { + const script = document.createElement('script'); + script.src = src; + script.onload = resolve; + script.onerror = () => reject(new Error(`${src} could not be loaded`)); + document.head.appendChild(script); + })); } - chartJsLoading ??= new Promise((resolve, reject) => { - const script = document.createElement('script'); - script.src = 'lib/chartjs/chart.umd.min.js'; - script.onload = resolve; - script.onerror = () => reject(new Error('Chart.js could not be loaded')); - document.head.appendChild(script); - }); - return chartJsLoading; + return scripts.get(src); +} + +async function loadChartJs(kind) { + await loadScript('lib/chartjs/chart.umd.min.js'); + if (kind === 'treemap') { + // Registers itself with the global Chart. + await loadScript('lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js'); + } + window.Chart.defaults.font.family = theme.font; } // Same look as ChartTheme.cs. @@ -32,54 +40,69 @@ const axisAmount = new Intl.NumberFormat('de-CH', { maximumFractionDigits: 0 }); const formatChf = value => amount.format(value).replace(/’/g, "'"); const formatAxis = value => axisAmount.format(value).replace(/’/g, "'"); -function toDatasets(series) { - return series.map(s => ({ - label: s.name, - data: s.values, - backgroundColor: s.color, - hoverBackgroundColor: s.color, - borderColor: theme.surface, - borderWidth: { top: 1 }, - borderRadius: 3, - stack: 'total', - clickable: s.clickable - })); +// Treemap tile helpers: level 0 tiles are parents (their group value is the parent id); level 1 +// tiles keep the original tree items, which carry the parent id. +const parentOf = raw => raw.l === 0 ? raw.g : raw._data.children[0].p; +const isParentGroup = (raw, items) => raw.l === 0 && items.some(i => i.c); + +function withAlpha(hex, alpha) { + const n = parseInt(hex.slice(1), 16); + return `rgba(${n >> 16}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`; } -/** - * Creates a stacked bar chart on the canvas and returns a handle with update/destroy. - * data: { labels: string[], series: { name, color, values: number[], clickable }[] } - * Clicking a bar segment of a clickable series calls dotNetRef.OnSeriesClicked(seriesIndex). - */ -export async function createStackedBar(canvas, data, dotNetRef) { - await loadChartJs(); - window.Chart.defaults.font.family = theme.font; +const tooltip = { + backgroundColor: '#ffffff', + borderColor: theme.grid, + borderWidth: 1, + titleColor: theme.ink, + bodyColor: theme.ink, + footerColor: theme.ink, + titleFont: { weight: 'bold' }, + footerFont: { weight: 'bold' }, + padding: 10, + usePointStyle: true +}; - const chart = new window.Chart(canvas, { +const legend = { + position: 'bottom', + labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { size: 12 } } +}; + +const amountAxis = { + grid: { color: theme.grid }, + border: { display: false }, + title: { display: true, text: 'CHF', color: theme.muted }, + ticks: { color: theme.muted, callback: value => formatAxis(value) } +}; + +const categoryAxis = { grid: { display: false }, ticks: { color: theme.muted } }; + +// Each kind turns the data sent from Blazor into Chart.js data, and builds its options once. +// Options read the current data through state(), so update() only has to swap the data. +const kinds = { + // data: { labels, series: [{ name, color, values, clickable }] }; click key = series index + stackedBar: { type: 'bar', - data: { labels: data.labels, datasets: toDatasets(data.series) }, - options: { - responsive: true, - maintainAspectRatio: false, - animation: { duration: 250 }, + data: data => ({ + labels: data.labels, + datasets: data.series.map(s => ({ + label: s.name, + data: s.values, + backgroundColor: s.color, + hoverBackgroundColor: s.color, + borderColor: theme.surface, + borderWidth: { top: 1 }, + borderRadius: 3, + stack: 'total', + clickable: s.clickable + })) + }), + options: () => ({ interaction: { mode: 'index', intersect: false }, plugins: { - legend: { - position: 'bottom', - labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { family: theme.font, size: 12 } } - }, + legend, tooltip: { - backgroundColor: '#ffffff', - borderColor: theme.grid, - borderWidth: 1, - titleColor: theme.ink, - bodyColor: theme.ink, - footerColor: theme.ink, - titleFont: { family: theme.font, weight: 'bold' }, - bodyFont: { family: theme.font }, - footerFont: { family: theme.font, weight: 'bold' }, - padding: 10, - usePointStyle: true, + ...tooltip, filter: item => item.parsed.y !== 0, itemSort: (a, b) => b.parsed.y - a.parsed.y, callbacks: { @@ -88,33 +111,148 @@ export async function createStackedBar(canvas, data, dotNetRef) { } } }, - scales: { - x: { stacked: true, grid: { display: false }, ticks: { color: theme.muted, font: { family: theme.font } } }, - y: { - stacked: true, - grid: { color: theme.grid }, - border: { display: false }, - title: { display: true, text: 'CHF', color: theme.muted, font: { family: theme.font } }, - ticks: { color: theme.muted, font: { family: theme.font }, callback: value => formatAxis(value) } + scales: { x: { ...categoryAxis, stacked: true }, y: { ...amountAxis, stacked: true } } + }), + hit: (chart, event) => { + const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0]; + return hit && chart.data.datasets[hit.datasetIndex].clickable ? String(hit.datasetIndex) : null; + } + }, + + // data: { labels, series: [{ name, color, values (null = no data), width }] }; not clickable + line: { + type: 'line', + data: data => ({ + labels: data.labels, + datasets: data.series.map(s => ({ + label: s.name, + data: s.values, + borderColor: s.color, + backgroundColor: s.color, + borderWidth: s.width, + pointRadius: s.width > 2 ? 3 : 2, + pointHoverRadius: 5, + tension: 0.25, + spanGaps: false + })) + }), + options: () => ({ + interaction: { mode: 'index', intersect: false }, + plugins: { + legend: { ...legend, labels: { ...legend.labels, pointStyle: 'line' } }, + tooltip: { + ...tooltip, + filter: item => item.parsed.y !== null, + itemSort: (a, b) => b.parsed.y - a.parsed.y, + callbacks: { label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF` } } }, + scales: { x: categoryAxis, y: amountAxis } + }), + hit: () => null + }, + + // data: { items: [{ p, c, value }], names: { id: name }, colors: { p: color }, clickable: [key] } + // p = parent id, c = child id (null for a single level); click key = "p" or "p|c" + treemap: { + type: 'treemap', + data: data => ({ + datasets: [{ + tree: data.items, + key: 'value', + groups: data.items.some(i => i.c) ? ['p', 'c'] : ['p'], + spacing: 1, + borderWidth: 0, + borderRadius: 3, + backgroundColor: ctx => { + if (ctx.type !== 'data') { + return 'transparent'; + } + const color = data.colors[parentOf(ctx.raw)] ?? '#898781'; + return withAlpha(color, isParentGroup(ctx.raw, data.items) ? 0.25 : 0.9); + }, + captions: { + display: true, + color: theme.ink, + font: { weight: 'bold', size: 12 }, + formatter: ctx => `${data.names[ctx.raw.g]} ${formatAxis(ctx.raw.v)}` + }, + labels: { + display: true, + color: '#ffffff', + font: [{ size: 12, weight: 'bold' }, { size: 11 }], + overflow: 'hidden', + formatter: ctx => [data.names[ctx.raw.g], `${formatAxis(ctx.raw.v)} CHF`] + } + }] + }), + options: state => ({ + plugins: { + legend: { display: false }, + tooltip: { + ...tooltip, + displayColors: false, + callbacks: { + title: items => { + const raw = items[0].raw; + const names = state().names; + return raw.l === 0 ? names[raw.g] : `${names[parentOf(raw)]} › ${names[raw.g]}`; + }, + label: item => `${formatChf(item.raw.v)} CHF` + } + } + } + }), + hit: (chart, event) => { + // Deepest tile under the pointer: an account inside a subclass wins over the subclass. + const hits = chart.getElementsAtEventForMode(event, 'point', { intersect: true }, false); + const data = chart.data.datasets[0].data; + const raw = hits.map(h => data[h.index]).sort((a, b) => b.l - a.l)[0]; + if (!raw) { + return null; + } + const key = raw.l === 0 ? raw.g : `${parentOf(raw)}|${raw.g}`; + return chart.$clickable?.includes(key) ? key : null; + } + } +}; + +/** + * Creates a chart of the given kind on the canvas and returns a handle with update/destroy. + * Clicking a clickable element calls dotNetRef.OnChartClicked(key); see the kinds above for keys. + */ +export async function createChart(canvas, kind, data, dotNetRef) { + await loadChartJs(kind); + const spec = kinds[kind]; + let current = data; + + const chart = new window.Chart(canvas, { + type: spec.type, + data: spec.data(current), + options: { + responsive: true, + maintainAspectRatio: false, + animation: { duration: 250 }, + ...spec.options(() => current), onHover: (event, _, chart) => { - const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0]; - event.native.target.style.cursor = hit && chart.data.datasets[hit.datasetIndex].clickable ? 'pointer' : 'default'; + event.native.target.style.cursor = spec.hit(chart, event) !== null ? 'pointer' : 'default'; }, onClick: (event, _, chart) => { - const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0]; - if (hit && chart.data.datasets[hit.datasetIndex].clickable) { - dotNetRef.invokeMethodAsync('OnSeriesClicked', hit.datasetIndex); + const key = spec.hit(chart, event); + if (key !== null) { + dotNetRef.invokeMethodAsync('OnChartClicked', key); } } } }); + chart.$clickable = current.clickable; + return { update(newData) { - chart.data.labels = newData.labels; - chart.data.datasets = toDatasets(newData.series); + current = newData; + chart.$clickable = current.clickable; + chart.data = spec.data(current); chart.update(); }, destroy() { diff --git a/Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/LICENSE b/Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/LICENSE new file mode 100644 index 0000000..c32131d --- /dev/null +++ b/Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-2021 Jukka Kurkela + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js b/Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js new file mode 100644 index 0000000..c54db71 --- /dev/null +++ b/Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js @@ -0,0 +1,8 @@ +/*! + * chartjs-chart-treemap v0.0.0-development + * https://chartjs-chart-treemap.pages.dev/ + * (c) 2026 Jukka Kurkela + * Released under the MIT license + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("chart.js"),require("chart.js/helpers")):"function"==typeof define&&define.amd?define(["exports","chart.js","chart.js/helpers"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["chartjs-chart-treemap"]={},t.Chart,t.Chart.helpers)}(this,function(t,e,n){"use strict";function i(t,e,n,i){const r=2*i,o=e.getPixelForValue(t.x),s=n.getPixelForValue(t.y),a=e.getPixelForValue(t.x+t.w)-o,h=n.getPixelForValue(t.y+t.h)-s;return{height:h-r,hidden:r>a||r>h,width:a-r,x:o+i,y:s+i}}function r(t,e){let n,i;if(!t||!e)return!0;if(t===e)return!1;if(t.length!==e.length)return!0;for(n=0,i=t.length;nt.rtl?t.x+t.iw-e:t.x+t._ix;function l(t,e,n,i){const r={_data:e._data,a:e._normalized,h:n.h,s:i,v:e.value,vs:e.values,w:n.w,x:h(t,n.w),y:t.y+t._iy};return e.group&&(r.g=e.group,r.l=e.level,r.gs=e.groupSum),r}class u{get area(){return this.w*this.h}get iw(){return this.w-this._ix}get ih(){return this.h-this._iy}get dir(){const t=this.ih;return t<=this.iw&&t>0?"y":"x"}get side(){return"x"===this.dir?this.iw:this.ih}map(t){const{dir:e,side:n}=this,i="x"===e?"_ix":"_iy",r=t.nsum,o=t.get(),s=n*n,h=r*r,u=[];let c=0,d=0;for(const e of o){const n=a(e,s,h,i);d+=n.d1,c=Math.max(c,n.d2),u.push(l(this,e,n,t.sum)),this[i]+=n.d1}return this["x"===e?"_iy":"_ix"]+=c,this[i]-=d,u}constructor(t){t=t||{h:1,w:1},this.rtl=!!t.rtl,this.unsorted=!!t.unsorted,this.x=t.x||t.left||0,this.y=t.y||t.top||0,this._ix=0,this._iy=0,this.w=t.w||t.width||t.right-t.left,this.h=t.h||t.height||t.bottom-t.top}}const c=Math.min,d=Math.max;function f(t,e){const n=+e[t.key],i=n*t.ratio;return e._normalized=i,{max:d(t.max,n),min:c(t.min,n),nmax:d(t.nmax,i),nmin:c(t.nmin,i),nsum:t.nsum+i,sum:t.sum+n}}function p(t,e,n){t._arr.push(e),function(t,e){Object.assign(t,e)}(t,n)}class g{get length(){return this._arr.length}reset(){this._arr=[],this._hist=[],this.sum=0,this.nsum=0,this.min=1/0,this.max=-1/0,this.nmin=1/0,this.nmax=-1/0}push(t){p(this,t,f(this,t))}pushIf(t,e,...n){const i=f(this,t);if(!e((r=this,{max:r.max,min:r.min,nmax:r.nmax,nmin:r.nmin,nsum:r.nsum,sum:r.sum}),i,n))return t;var r;p(this,t,i)}get(){return this._arr}constructor(t,e){this._arr=[],this._hist=[],this.sum=0,this.nsum=0,this.min=1/0,this.max=-1/0,this.nmin=1/0,this.nmax=-1/0,this.key=t,this.ratio=e,this.reset()}}const m=(t,e)=>e>t||t.length>e.length&&t.startsWith(e),x=t=>String(t),y=t=>null!=t&&""!==t;function b(t,e,i,r=[],o=0,s=[]){const a=o-1;if(t[0]in i&&o>0){const n=r.reduce((t,e,n)=>(n!==a&&(t[x(n)]=e),t),{});n[e]=r[a],t.forEach(t=>{n[t]=i[t]}),s.push(n)}else for(const a of Object.keys(i)){const h=i[a];n.isObject(h)&&(r.push(a),b(t,e,h,r,o+1,s))}return r.splice(a,1),s}function v(t,e,n){const i=b(t,e,n);if(!i.length)return i;const r=i.reduce((t,e)=>{const n=Object.keys(e).length-2;return Math.max(t,n)},0);return i.forEach(t=>{for(let e=0;e{r[t]=0}),e[n]=[]}function k(t,e,n,i,r,o,s=[],a=s,h=s.length-1){const l=n[0],u=n.slice(1),c=Object.create(null),d=Object.create(null),f=[],p=a.length?a:[e],g=a.length?h:0;let m,x;for(m=0,x=t.length;m{a[t]+=e[t]}),c[s].path=_(p.slice(0,n.groupIndex+1),e,s),d[s].push(e)}return Object.keys(c).forEach(t=>{const n={children:d[t]};n[l]=+c[t].value,u.forEach(e=>{n[e]=+c[t][e]}),n[e]=c[t].label,n.group=c[t].group,n.groupIndex=c[t].groupIndex,n.label=t,n.path=c[t].path,r&&(n[r]=o),f.push(n)}),f}function T(t,e){let i,r=t.length;if(!r)return e;const o=n.isObject(t[0]);for(e=o?e:"v",i=0,r=t.length;i+n[e]-+t[e]):t.sort((t,e)=>+e-+t)}function R(t,e){let n,i,r;for(n=0,i=0,r=t.length;im?+p[t][m]:+p[t],y=t=>i&&p[t][i];for(d=0;d(e[n]=+t[n],e),{})}f=h.pushIf(f,E,l),f&&(s.push(a.map(h)),l=a.side,h.reset(),h.push(f))}return h.length&&s.push(a.map(h)),w(s)}const P=new Map;function S(t,e,i){if(!i||!1===i.display)return!1;if("headerBoxes"===t)return!0;const{w:r,h:o}=e,s=n.toFont(i.font||{}).lineHeight,a=Math.max(Math.min(2*n.valueOrDefault(i.padding,3),Math.min(r,o)),0);return r-a>s&&o-a>s}function D(t,e,n,i){if("headerBoxes"!==t)return n.lineHeight+2*i;const r=n.lineHeight+2*i;return e.h<2*r?e.h/3:r}function I(t,e,i,r,o){const{captions:s,labels:a,displayMode:h}=i;t.save(),t.beginPath(),t.rect(e.x,e.y,e.w,e.h),t.clip();const l=r&&(!n.defined(r.l)||r.isLeaf);l&&a.display?function(t,e,i,r,o){const s=i.labels,a=B(s.formatter,A(o,r));if(!a)return;const h=n.isArray(a)?a:[a];let l=function(t,e){const{font:i,hoverFont:r}=e,o=(t.active?r:i)||i;return Array.isArray(o)?o.map(t=>n.toFont(t)):[n.toFont(o)]}(e,s),u=F(t,h,l);const c=function(t,e,n,i){const{overflow:r,padding:o}=n,{width:s,height:a}=i;if("hidden"===r)return!(s+2*o>e.w||a+2*o>e.h);if("fit"===r){const t=Math.min(e.w/(s+2*o),e.h/(a+2*o));if(t<1)return t}return!0}(0,e,s,u);if(!c)return;n.isNumber(c)&&(u={height:u.height*c,width:u.width*c},l=function(t,e){return t.map(t=>{const{lineHeight:i,...r}=t;return n.toFont({...r,size:Math.floor(t.size*e)})})}(l,c));const{color:d,hoverColor:f,align:p}=s,g=(e.active?f:d)||d,m=n.isArray(g)?g:[g],x=function(t,e,n){const{align:i,position:r,padding:o}=e,s=z(t,i,o);let a;a="top"===r?t.y+o:"bottom"===r?t.y+t.h-o-n.height:t.y+(t.h-n.height)/2+o;return{x:s,y:a}}(e,s,u);t.textAlign=p,t.textBaseline="middle";let y=0;h.forEach((e,n)=>{const i=m[Math.min(n,m.length-1)],r=l[Math.min(n,l.length-1)],o=r.lineHeight;t.font=r.string,t.fillStyle=i,t.fillText(e,x.x,x.y+o/2+y),y+=o})}(t,e,i,r,o):!l&&S(h,e,s)&&function(t,e,i,r,o){const{captions:s,spacing:a,rtl:h,displayMode:l}=i,{color:u,hoverColor:c,font:d,hoverFont:f,padding:p,align:g}=s,m=(e.active?c:u)||u,x=g||(h?"right":"left"),y=(e.active?f:d)||d,b=n.toFont(y),v=[b];if(b.lineHeight>e.h)return;let w=function(t,e,n){return B(t.formatter,A(e,n))||n.g||""}(s,o,r);if(!w)return;const _=F(t,[w],v);_.width+2*p>e.w&&(w=function(t,e,n,i){const r="...",o=F(t,[r],i).width;if(o>=n)return"";let s,a=1,h=e.length;for(;a<=h;){const r=Math.floor((a+h)/2);s=F(t,[e.slice(0,r)],i).width,s+o>n?h=r-1:a=r+1}const l=e.slice(0,Math.max(0,a-1));return l?l+r:""}(t,w,e.w-2*p,v));const M=b.lineHeight/2,C=z(e,x,p);t.fillStyle=m,t.font=b.string,t.textAlign=x,t.textBaseline="middle";const k="headerBoxes"===l?e.y+e.h/2:e.y+p+a+M;t.fillText(w,C,k)}(t,e,i,r,o),t.restore()}function A(t,e){const n=t.$context||{active:!!t.active,raw:e,type:"data"};return n.active=!!t.active,n.raw=e,n}function B(t,e){return"function"==typeof t?t(e):t}function F(t,e,n){const i=n.reduce((t,e)=>t+=e.string,""),r=e.join()+i+(t._measureText?"-spriting":"");let o=P.get(r);if(!o){t.save();const i=e.length;let s=0,a=0;for(let r=0;re<=r),a,r),b=L(y,f,i,m,r,g),v=b.slice();return r{const i=function(t,n){const i="headerBoxes"===e.displayMode?{b:0,l:0,r:0,t:0}:s(e.borderWidth,t.w/2,t.h/2),r={...n,h:t.h-2*l-i.t-i.b,w:t.w-2*l-i.l-i.r,x:t.x+l+i.l,y:t.y+l+i.t};if(S(e.displayMode,r,u)){const t=D(e.displayMode,r,c,d);r.y+=t,r.h-=t}return r}(n,f),r=[],o=n._data.groupIndex+1;o{t.isLeaf=!0}),v}(t,0,r):L(t,r,i);return f.map(t=>{if("headerBoxes"!==e.displayMode||t.isLeaf)return t;if(!S(e.displayMode,t,u))return;const n=D(e.displayMode,t,c,d);return{...t,h:n}}).filter(Boolean)}function V(){const t=e.registry.plugins.get("tooltip");t&&!t.positioners.treemap&&(t.positioners.treemap=t=>{if(!t.length)return!1;return t.at(-1).element.tooltipPosition()})}class $ extends e.DatasetController{initialize(){V(),this.enableOptionSharing=!0,super.initialize()}getMinMax(t){return{max:"x"===t.axis?t.right-t.left:t.bottom-t.top,min:0}}configure(){super.configure();const{xScale:t,yScale:e}=this.getMeta();if(!t||!e)return;const n=t.right-t.left,i=e.bottom-e.top,r={h:i,rtl:!!this.options.rtl,unsorted:!!this.options.unsorted,w:n,x:0,y:0};var o,s;o=this._rect,s=r,o&&s&&o.x===s.x&&o.y===s.y&&o.w===s.w&&o.h===s.h&&o.rtl===s.rtl&&o.unsorted===s.unsorted||(this._rect=r,this._rectChanged=!0),this._rectChanged&&(t.max=n,t.configure(),e.max=i,e.configure())}update(t){const e=this.getDataset(),{data:n}=this.getMeta(),i=e.groups||[],o=[e.key||""].concat(e.sumKeys||[]);e.tree=e.tree||e.data||[];const s=e.tree,a=e.treeVersion;"reset"===t&&this.configure(),(this._rectChanged||r(this._keys||[],o)||r(this._groups||[],i)||this._prevTree!==s||this._prevTreeVersion!==a)&&(this._groups=i.slice(),this._keys=o.slice(),this._prevTree=s,this._prevTreeVersion=a,this._rectChanged=!1,e.data=H(s,e,this._keys,this._rect),this._dataCheck(),this._resyncElements()),this.updateElements(n,0,n.length,t)}updateElements(t,e,n,r){const o="reset"===r,s=this.getDataset(),a=this.resolveDataElementOptions(e,r);this._rect.options=a;const h=this.getSharedOptions(a),l=this.includeOptions(r,h||{}),{xScale:u,yScale:c}=this.getMeta();for(let a=e;a=s.left&&e<=s.right)&&(o||n>=s.top&&n<=s.bottom)}function N(t,e){t.rect(e.x,e.y,e.w,e.h)}$.id="treemap",$.version="0.0.0-development",$.defaults={animations:{numbers:{properties:["x","y","width","height"],type:"number"}},dataElementType:"treemap"},$.descriptors={_indexable:!1,_scriptable:!0,captions:{_fallback:!0,_scriptable:t=>"formatter"!==t},labels:{_fallback:!0,_scriptable:t=>"formatter"!==t}},$.overrides={hover:{},interaction:{includeInvisible:!0,intersect:!0,mode:"point"},plugins:{tooltip:{callbacks:{label(t){const e=t.dataset,n=e.data[t.dataIndex],i=n.g||n._data.label||e.label;return(i?`${i}: `:"")+n.v},title(t){if(t.length){return t[0].dataset.key||""}return""}},intersect:!0,position:"treemap"}},scales:{x:{alignToPixels:!0,bounds:"data",display:!1,type:"linear"},y:{alignToPixels:!0,bounds:"data",display:!1,reverse:!0,type:"linear"}}},$.beforeRegister=()=>{j("chart.js","3.8",e.Chart.version)},$.afterRegister=()=>{V()},$.afterUnregister=()=>{const t=e.registry.plugins.get("tooltip");t&&delete t.positioners.treemap};class G extends e.Element{draw(t,e){if(!e)return;const i=this.options,{inner:r,outer:o}=q(this),s=(a=o.radius).topLeft||a.topRight||a.bottomLeft||a.bottomRight?n.addRoundedRectPath:N;var a;t.save(),o.w===r.w&&o.h===r.h||(t.beginPath(),s(t,o),t.clip(),s(t,r),t.fillStyle=i.borderColor,t.fill("evenodd")),t.beginPath(),s(t,r),t.fillStyle=i.backgroundColor,t.fill(),function(t,e,n,i){const r=n.dividers,o=i._data?.children;if(!r.display||!Array.isArray(o)||!o.length)return;const{x:s,y:a,w:h,h:l}=e,{lineColor:u,lineCapStyle:c,lineDash:d,lineDashOffset:f,lineWidth:p}=r;if(t.save(),t.strokeStyle=u,t.lineCap=c,t.setLineDash(d),t.lineDashOffset=f,t.lineWidth=p,t.beginPath(),h>l){const e=h/2;t.moveTo(s+e,a),t.lineTo(s+e,a+l)}else{const e=l/2;t.moveTo(s,a+e),t.lineTo(s+h,a+e)}t.stroke(),t.restore()}(t,r,i,e),I(t,r,i,e,this),t.restore()}inRange(t,e,n){return K(this,t,e,n)}inXRange(t,e){return K(this,t,null,e)}inYRange(t,e){return K(this,null,t,e)}getCenterPoint(t){const{x:e,y:n,width:i,height:r}=this.getProps(["x","y","width","height"],t);return{x:e+i/2,y:n+r/2}}tooltipPosition(){return this.getCenterPoint()}constructor(t){super(),this.width=void 0,this.height=void 0,t&&Object.assign(this,t)}}G.id="treemap",G.defaults={borderRadius:0,borderWidth:0,captions:{align:void 0,color:"black",display:!0,font:{},formatter:t=>{const e=t.raw._data?.label;return t.raw.g||("string"==typeof e?e:"")},padding:3},displayMode:"containerBoxes",dividers:{display:!1,lineCapStyle:"butt",lineColor:"black",lineDash:[],lineDashOffset:0,lineWidth:1},label:void 0,labels:{align:"center",color:"black",display:!1,font:{},formatter(t){const e=t.raw._data?.label;return t.raw.g?[t.raw.g,`${t.raw.v}`]:"string"==typeof e?[e,`${t.raw.v}`]:`${t.raw.v}`},overflow:"cut",padding:3,position:"middle"},rtl:!1,spacing:.5,unsorted:!1},G.descriptors={_indexable:!1,_scriptable:!0,captions:{_fallback:!0,_scriptable:t=>"formatter"!==t},labels:{_fallback:!0,_scriptable:t=>"formatter"!==t}},G.defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"},e.Chart.register($,G),t.TreemapController=$,t.TreemapElement=G,t.flatten=w,t.getGroupKey=x,t.group=k,t.index=T,t.normalizeTreeToArray=v,t.requireVersion=j,t.sort=O,t.sum=R}); +//# sourceMappingURL=chartjs-chart-treemap.min.js.map