The personal finance app for everyone (by everyone)
Ruby
Prefer prominent labels in the new Sankey chart (#3614)
Juan José Mata00edeea18535
diff --git a/app/javascript/controllers/preview_sankey_chart_controller.js b/app/javascript/controllers/preview_sankey_chart_controller.jsindex dd83b14653..a67fb6b3d6 100644--- a/app/javascript/controllers/preview_sankey_chart_controller.js+++ b/app/javascript/controllers/preview_sankey_chart_controller.js@@ -3,6 +3,7 @@ import * as d3 from "d3";import { sankey } from "d3-sankey";import { formatCashFlowCurrency } from "utils/cash_flow_chart_data";import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";+import { hiddenSankeyLabels } from "utils/sankey_labels";import { sankeyNodeHasChildren, zoomSankeyData } from "utils/sankey_zoom";import {buildCategoryTransactionsUrl,@@ -415,44 +416,11 @@ export default class extends Controller {// Calculate which labels should be hidden to prevent overlap#calculateHiddenLabels(nodes) {- const hiddenLabels = new Set();const height = this.#chartElement().clientHeight || 400;- const isLargeGraph = height > 600;- const minSpacing = isLargeGraph- ? this.constructor.MIN_LABEL_SPACING * 0.7- : this.constructor.MIN_LABEL_SPACING;-- // Group nodes by column (using depth which d3-sankey assigns)- const columns = new Map();- nodes.forEach((node) => {- const depth = node.depth;- if (!columns.has(depth)) columns.set(depth, []);- columns.get(depth).push(node);- });-- // For each column, check for overlapping labels- columns.forEach((columnNodes) => {- // Sort by vertical position- columnNodes.sort((a, b) => (a.y0 + a.y1) / 2 - (b.y0 + b.y1) / 2);-- let lastVisibleY = Number.NEGATIVE_INFINITY;-- columnNodes.forEach((node) => {- const nodeY = (node.y0 + node.y1) / 2;- const nodeHeight = node.y1 - node.y0;-- if (isLargeGraph && nodeHeight > minSpacing * 1.5) {- lastVisibleY = nodeY;- } else if (nodeY - lastVisibleY < minSpacing) {- // Too close to previous visible label, hide this one- hiddenLabels.add(node.index);- } else {- lastVisibleY = nodeY;- }- });+ return hiddenSankeyLabels(nodes, {+ height,+ minSpacing: this.constructor.MIN_LABEL_SPACING,});-- return hiddenLabels;}#attachHoverEvents(linkPaths, nodeGroups, sankeyData, hiddenLabels) {diff --git a/app/javascript/utils/sankey_labels.mjs b/app/javascript/utils/sankey_labels.mjsnew file mode 100644index 0000000000..21bff1c191--- /dev/null+++ b/app/javascript/utils/sankey_labels.mjs@@ -0,0 +1,50 @@+// Label-collision rule for the new preview Sankey chart.+// Nodes compete for labels only within their own+// visual column: d3-sankey's justify alignment can place same-depth nodes+// in different columns (sinks flush right), so columns are keyed by x0,+// not depth. Within a column, labels are considered in descending+// node-value order and kept only when they clear the minimum spacing from+// every label already kept. A small node can no longer hide a large+// category's label merely by sitting above it: the prominent node is+// labeled first, and the small neighbor is the one that yields.+export function hiddenSankeyLabels(nodes, { height, minSpacing }) {+ const hiddenLabels = new Set();+ const isLargeGraph = height > 600;+ const spacing = isLargeGraph ? minSpacing * 0.7 : minSpacing;++ // Group nodes by visual column (x position assigned by d3-sankey)+ const columns = new Map();+ nodes.forEach((node) => {+ const column = Math.round(node.x0);+ if (!columns.has(column)) columns.set(column, []);+ columns.get(column).push(node);+ });++ columns.forEach((columnNodes) => {+ // Most significant nodes claim their labels first; ties fall back to+ // vertical position so the rule stays deterministic.+ const byProminence = [...columnNodes].sort((a, b) => {+ if (b.value !== a.value) return b.value - a.value;+ return (a.y0 + a.y1) / 2 - (b.y0 + b.y1) / 2;+ });++ const keptYs = [];++ byProminence.forEach((node) => {+ const nodeY = (node.y0 + node.y1) / 2;+ const nodeHeight = node.y1 - node.y0;++ // Tall bars in large graphs always earn their label.+ if (+ (isLargeGraph && nodeHeight > spacing * 1.5) ||+ keptYs.every((keptY) => Math.abs(nodeY - keptY) >= spacing)+ ) {+ keptYs.push(nodeY);+ } else {+ hiddenLabels.add(node.index);+ }+ });+ });++ return hiddenLabels;+}diff --git a/config/importmap.rb b/config/importmap.rbindex 57c755e9ab..5463caf589 100644--- a/config/importmap.rb+++ b/config/importmap.rb@@ -62,3 +62,5 @@ pin "utils/cash_flow_chart_data", to: "utils/cash_flow_chart_data.mjs"pin "utils/sankey_preview_analytics", to: "utils/sankey_preview_analytics.mjs"pin "utils/sankey_comparison", to: "utils/sankey_comparison.mjs"++pin "utils/sankey_labels", to: "utils/sankey_labels.mjs"diff --git a/test/javascript/utils/sankey_labels_test.mjs b/test/javascript/utils/sankey_labels_test.mjsnew file mode 100644index 0000000000..a3ea21d17d--- /dev/null+++ b/test/javascript/utils/sankey_labels_test.mjs@@ -0,0 +1,103 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { hiddenSankeyLabels } from "../../../app/javascript/utils/sankey_labels.mjs";++const SPACING = 28;++// One column (same depth) of vertically stacked nodes, top to bottom.+const column = (entries) =>+ entries.map(([value, y0, y1], i) => ({+ index: i,+ x0: 100,+ value,+ y0,+ y1,+ }));++test("a small node above a large node no longer hides the large label", () => {+ // Demo-scale regression: Fees ($1.15) sat above Household ($160) and won+ // the label under the old top-down rule.+ const nodes = column([+ [1.15, 18, 20],+ [160.0, 10, 60],+ [928.21, 90, 240],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });+ assert.equal(hidden.has(1), false, "large node keeps its label");+ assert.equal(hidden.has(0), true, "small neighbor yields");+ assert.equal(hidden.has(2), false);+});++test("spacing still hides the less prominent of two crowded large nodes", () => {+ const nodes = column([+ [500.0, 0, 20],+ [400.0, 22, 40],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });+ assert.equal(hidden.has(0), false, "larger value keeps the label");+ assert.equal(hidden.has(1), true);+});++test("nodes spaced far enough apart all stay labeled", () => {+ const nodes = column([+ [5.99, 0, 4],+ [20.24, 40, 46],+ [1.15, 80, 82],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });+ assert.equal(hidden.size, 0);+});++test("columns are independent of each other", () => {+ const nodes = [+ { index: 0, x0: 0, value: 10, y0: 0, y1: 10 },+ { index: 1, x0: 100, value: 10, y0: 0, y1: 10 },+ { index: 2, x0: 100, value: 20, y0: 12, y1: 22 },+ ];+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });+ assert.equal(hidden.has(0), false);+ assert.equal(hidden.has(1), true, "smaller node in the shared column yields");+ assert.equal(hidden.has(2), false, "larger node in the shared column wins");+});++test("equal values fall back to vertical order deterministically", () => {+ const nodes = column([+ [50, 0, 10],+ [50, 12, 22],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });+ assert.equal(hidden.has(0), false, "top-most of equal values stays");+ assert.equal(hidden.has(1), true);+});++test("large graphs keep tall-bar labels and use tighter spacing", () => {+ const nodes = column([+ [300.0, 8, 38], // 18px from the higher-value node; needs the tall-bar override+ [500.0, 0, 10], // highest value claims its label first+ [200.0, 43, 53], // 25px from the tall bar; needs the reduced 19.6px spacing+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 800, minSpacing: SPACING });+ assert.equal(hidden.has(0), false, "tall bar always labeled");+ assert.equal(hidden.has(1), false, "highest-value node keeps its label");+ assert.equal(hidden.has(2), false, "tighter spacing in large graphs");+});++test("hidden set uses node.index, not array position", () => {+ const nodes = [+ { index: 7, x0: 100, value: 1, y0: 28, y1: 30 },+ { index: 3, x0: 100, value: 100, y0: 6, y1: 60 },+ ];+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });+ assert.deepEqual([...hidden], [7]);+});++test("same-depth nodes in different visual columns do not compete", () => {+ // d3-sankey justify alignment flushes sinks to the last column; a parent+ // one column left at the same y must not lose its label to the sink.+ const nodes = [+ { index: 0, x0: 100, value: 476.85, y0: 16, y1: 35.5 }, // parent, middle column+ { index: 1, x0: 300, value: 524.99, y0: 16, y1: 37.4 }, // sink, right column+ ];+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });+ assert.equal(hidden.size, 0);+});