The personal finance app for everyone (by everyone)
Ruby
Keep Sankey labels off the next column's bars on narrow screens (#4345)
Guillem Arias Fauste9bed45e903a0
diff --git a/app/javascript/controllers/preview_sankey_chart_controller.js b/app/javascript/controllers/preview_sankey_chart_controller.jsindex 3c7bc75eb8..6a2abf4cb4 100644--- a/app/javascript/controllers/preview_sankey_chart_controller.js+++ b/app/javascript/controllers/preview_sankey_chart_controller.js@@ -62,6 +62,14 @@ export default class extends Controller {this.#syncZoomControls();this.#syncSortControls();this.#draw();++ // Labels are measured to keep them off neighbouring bars; measure again+ // once the page font has replaced the fallback.+ if (document.fonts?.status === "loading") {+ document.fonts.ready.then(() => {+ if (this.connected) this.#draw();+ });+ }}dataValueChanged() {@@ -383,7 +391,7 @@ export default class extends Controller {.attr("fill", (d) => d.color || this.constructor.DEFAULT_COLOR).attr("stroke", (d) => (d.color ? "none" : "var(--color-gray-500)"));- const hiddenLabels = this.#addNodeLabels(nodeGroups, width, nodes);+ const hiddenLabels = this.#addNodeLabels(svg, nodeGroups, width, nodes);return { nodeGroups, hiddenLabels };}@@ -440,47 +448,82 @@ export default class extends Controller {L ${x0},${y1} Z`;}- #addNodeLabels(nodeGroups, width, nodes) {+ #addNodeLabels(svg, nodeGroups, width, nodes) {const controller = this;- const hiddenLabels = this.#calculateHiddenLabels(nodes);+ const hiddenLabels = this.#calculateHiddenLabels(+ nodes,+ this.#measureLabels(svg, nodes, width),+ );nodeGroups.append("text")- .attr("x", (d) => (d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6))- .attr("y", (d) => (d.y1 + d.y0) / 2)- .attr("dy", "-0.2em")- .attr("text-anchor", (d) => (d.x0 < width / 2 ? "start" : "end")).attr("class","text-xs font-medium text-primary fill-current select-none",).style("cursor", "default").style("opacity", (d) => (hiddenLabels.has(d.index) ? 0 : 1))+ // A hidden label can sit over another node's bar; it must not take+ // that bar's hovers and clicks, even while hover reveals it.+ .style("pointer-events", (d) =>+ hiddenLabels.has(d.index) ? "none" : null,+ ).style("transition", "opacity 0.2s ease").each(function (d) {- const textEl = d3.select(this);- textEl.selectAll("tspan").remove();-- textEl.append("tspan").text(d.name);-- textEl- .append("tspan")- .attr("x", textEl.attr("x"))- .attr("dy", "1.2em")- .attr("class", "font-mono text-secondary")- .style("font-size", "0.65rem")- .text(controller.#formatCurrency(d.value));+ controller.#writeLabel(d3.select(this), d, width);});return hiddenLabels;}+ // Name above amount, beside the bar on the side facing the chart's middle.+ #writeLabel(textEl, d, width) {+ const x = d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6;++ textEl+ .attr("x", x)+ .attr("y", (d.y1 + d.y0) / 2)+ .attr("dy", "-0.2em")+ .attr("text-anchor", d.x0 < width / 2 ? "start" : "end");++ textEl.selectAll("tspan").remove();+ textEl.append("tspan").text(d.name);+ textEl+ .append("tspan")+ .attr("x", x)+ .attr("dy", "1.2em")+ .attr("class", "font-mono text-secondary")+ .style("font-size", "0.65rem")+ .text(this.#formatCurrency(d.value));+ }++ // Where each label lands at this width, measured with an invisible probe+ // before the real labels are drawn, so the overlap rule can see a label+ // that reaches into the next column.+ #measureLabels(svg, nodes, width) {+ const probe = svg+ .append("text")+ .attr("class", "text-xs font-medium select-none")+ .style("visibility", "hidden");++ const boxes = new Map();+ nodes.forEach((d) => {+ this.#writeLabel(probe, d, width);+ const { x, y, width: boxWidth, height } = probe.node().getBBox();+ boxes.set(d.index, { x, y, width: boxWidth, height });+ });++ probe.remove();+ return boxes;+ }+// Calculate which labels should be hidden to prevent overlap- #calculateHiddenLabels(nodes) {+ #calculateHiddenLabels(nodes, labelBoxes) {const height = this.#chartElement().clientHeight || 400;return hiddenSankeyLabels(nodes, {height,minSpacing: this.constructor.MIN_LABEL_SPACING,+ labelBoxes,});}diff --git a/app/javascript/controllers/sankey_chart_controller.js b/app/javascript/controllers/sankey_chart_controller.jsindex 5a25528218..d32992cd22 100644--- a/app/javascript/controllers/sankey_chart_controller.js+++ b/app/javascript/controllers/sankey_chart_controller.js@@ -2,6 +2,7 @@ import { Controller } from "@hotwired/stimulus";import * as d3 from "d3";import { sankey } from "d3-sankey";import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";+import { hiddenSankeyLabels } from "utils/sankey_labels";import { sankeyNodeHasChildren, zoomSankeyData } from "utils/sankey_zoom";import {buildCategoryTransactionsUrl,@@ -47,6 +48,14 @@ export default class extends Controller {this.#createTooltip();this.#syncZoomControls();this.#draw();++ // Labels are measured to keep them off neighbouring bars; measure again+ // once the page font has replaced the fallback.+ if (document.fonts?.status === "loading") {+ document.fonts.ready.then(() => {+ if (this.connected) this.#draw();+ });+ }}dataValueChanged() {@@ -290,7 +299,7 @@ export default class extends Controller {.attr("fill", (d) => d.color || this.constructor.DEFAULT_COLOR).attr("stroke", (d) => (d.color ? "none" : "var(--color-gray-500)"));- const hiddenLabels = this.#addNodeLabels(nodeGroups, width, nodes);+ const hiddenLabels = this.#addNodeLabels(svg, nodeGroups, width, nodes);return { nodeGroups, hiddenLabels };}@@ -347,81 +356,83 @@ export default class extends Controller {L ${x0},${y1} Z`;}- #addNodeLabels(nodeGroups, width, nodes) {+ #addNodeLabels(svg, nodeGroups, width, nodes) {const controller = this;- const hiddenLabels = this.#calculateHiddenLabels(nodes);+ const hiddenLabels = this.#calculateHiddenLabels(+ nodes,+ this.#measureLabels(svg, nodes, width),+ );nodeGroups.append("text")- .attr("x", (d) => (d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6))- .attr("y", (d) => (d.y1 + d.y0) / 2)- .attr("dy", "-0.2em")- .attr("text-anchor", (d) => (d.x0 < width / 2 ? "start" : "end")).attr("class","text-xs font-medium text-primary fill-current select-none",).style("cursor", "default").style("opacity", (d) => (hiddenLabels.has(d.index) ? 0 : 1))+ // A hidden label can sit over another node's bar; it must not take+ // that bar's hovers and clicks, even while hover reveals it.+ .style("pointer-events", (d) =>+ hiddenLabels.has(d.index) ? "none" : null,+ ).style("transition", "opacity 0.2s ease").each(function (d) {- const textEl = d3.select(this);- textEl.selectAll("tspan").remove();-- textEl.append("tspan").text(d.name);-- textEl- .append("tspan")- .attr("x", textEl.attr("x"))- .attr("dy", "1.2em")- .attr("class", "font-mono text-secondary")- .style("font-size", "0.65rem")- .text(controller.#formatCurrency(d.value));+ controller.#writeLabel(d3.select(this), d, width);});return hiddenLabels;}- // 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);- });+ // Name above amount, beside the bar on the side facing the chart's middle.+ #writeLabel(textEl, d, width) {+ const x = d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6;- // 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;- }- });+ textEl+ .attr("x", x)+ .attr("y", (d.y1 + d.y0) / 2)+ .attr("dy", "-0.2em")+ .attr("text-anchor", d.x0 < width / 2 ? "start" : "end");++ textEl.selectAll("tspan").remove();+ textEl.append("tspan").text(d.name);+ textEl+ .append("tspan")+ .attr("x", x)+ .attr("dy", "1.2em")+ .attr("class", "font-mono text-secondary")+ .style("font-size", "0.65rem")+ .text(this.#formatCurrency(d.value));+ }++ // Where each label lands at this width, measured with an invisible probe+ // before the real labels are drawn, so the overlap rule can see a label+ // that reaches into the next column.+ #measureLabels(svg, nodes, width) {+ const probe = svg+ .append("text")+ .attr("class", "text-xs font-medium select-none")+ .style("visibility", "hidden");++ const boxes = new Map();+ nodes.forEach((d) => {+ this.#writeLabel(probe, d, width);+ const { x, y, width: boxWidth, height } = probe.node().getBBox();+ boxes.set(d.index, { x, y, width: boxWidth, height });});- return hiddenLabels;+ probe.remove();+ return boxes;+ }++ // Calculate which labels should be hidden to prevent overlap+ #calculateHiddenLabels(nodes, labelBoxes) {+ const height = this.#chartElement().clientHeight || 400;+ return hiddenSankeyLabels(nodes, {+ height,+ minSpacing: this.constructor.MIN_LABEL_SPACING,+ labelBoxes,+ });}#attachHoverEvents(linkPaths, nodeGroups, sankeyData, hiddenLabels) {diff --git a/app/javascript/utils/sankey_labels.mjs b/app/javascript/utils/sankey_labels.mjsindex 21bff1c191..da96e71d6c 100644--- a/app/javascript/utils/sankey_labels.mjs+++ b/app/javascript/utils/sankey_labels.mjs@@ -1,4 +1,4 @@-// Label-collision rule for the new preview Sankey chart.+// Label-collision rule shared by the dashboard's Sankey charts.// 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,@@ -7,44 +7,76 @@// 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 }) {+//+// On a narrow chart a label can also run across the gap into the next+// column. When the caller passes each label's measured box (keyed by+// node.index), a label yields if it would cover another node's bar, or a+// more prominent label from another column.+export function hiddenSankeyLabels(nodes, { height, minSpacing, labelBoxes }) {const hiddenLabels = new Set();const isLargeGraph = height > 600;const spacing = isLargeGraph ? minSpacing * 0.7 : minSpacing;+ const bars = labelBoxes ? nodes.map(barBox) : [];+ const keptYsByColumn = new Map();+ const keptBoxes = [];- // Group nodes by visual column (x position assigned by d3-sankey)- const columns = new Map();- nodes.forEach((node) => {+ // One pass in prominence order, so a label rejected for crossing into+ // another column never blocks a smaller neighbour that would fit.+ [...nodes].sort(byProminence).forEach((node) => {+ // Columns are the visual x position assigned by d3-sankeyconst column = Math.round(node.x0);- if (!columns.has(column)) columns.set(column, []);- columns.get(column).push(node);- });+ const nodeY = (node.y0 + node.y1) / 2;+ const keptYs = keptYsByColumn.get(column) || [];++ // Tall bars in large graphs always earn their label.+ const spaced =+ (isLargeGraph && node.y1 - node.y0 > spacing * 1.5) ||+ keptYs.every((keptY) => Math.abs(nodeY - keptY) >= spacing);++ const box = labelBoxes?.get(node.index);+ const clear =+ !box ||+ !(+ bars.some((bar) => bar.node !== node && overlaps(box, bar)) ||+ // Same-column spacing is the rule above's job.+ keptBoxes.some((kept) => kept.column !== column && overlaps(box, kept.box))+ );- 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);- }- });+ if (spaced && clear) {+ keptYsByColumn.set(column, [...keptYs, nodeY]);+ if (box) keptBoxes.push({ column, box });+ } else {+ hiddenLabels.add(node.index);+ }});return hiddenLabels;}++// Most significant nodes claim their labels first; ties fall back to+// vertical position so the rule stays deterministic.+function byProminence(a, b) {+ if (b.value !== a.value) return b.value - a.value;+ return (a.y0 + a.y1) / 2 - (b.y0 + b.y1) / 2;+}++const CLEARANCE = 2;++function overlaps(a, b) {+ return (+ a.x < b.x + b.width + CLEARANCE &&+ b.x < a.x + a.width + CLEARANCE &&+ a.y < b.y + b.height + CLEARANCE &&+ b.y < a.y + a.height + CLEARANCE+ );+}++function barBox(node) {+ return {+ node,+ x: node.x0,+ y: node.y0,+ width: node.x1 - node.x0,+ height: node.y1 - node.y0,+ };+}diff --git a/test/javascript/utils/sankey_labels_test.mjs b/test/javascript/utils/sankey_labels_test.mjsindex a3ea21d17d..168a3a52c7 100644--- a/test/javascript/utils/sankey_labels_test.mjs+++ b/test/javascript/utils/sankey_labels_test.mjs@@ -101,3 +101,75 @@ test("same-depth nodes in different visual columns do not compete", () => {const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING });assert.equal(hidden.size, 0);});++// On a phone the columns sit ~100px apart, so "Investment Income" beside the+// first column ran across the gap into the Cash Flow bar.+test("a label that would run into another column's bar yields", () => {+ const nodes = [+ { index: 0, x0: 0, x1: 15, value: 1042, y0: 250, y1: 254 },+ { index: 1, x0: 120, x1: 135, value: 61957, y0: 60, y1: 300 },+ ];+ const labelBoxes = new Map([+ [0, { x: 21, y: 240, width: 108, height: 26 }],+ [1, { x: 141, y: 168, width: 70, height: 26 }],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING, labelBoxes });+ assert.equal(hidden.has(0), true, "label crossing the next bar yields");+ assert.equal(hidden.has(1), false);+});++test("a label that stops short of the next column keeps showing", () => {+ const nodes = [+ { index: 0, x0: 0, x1: 15, value: 9855, y0: 230, y1: 246 },+ { index: 1, x0: 120, x1: 135, value: 61957, y0: 60, y1: 300 },+ ];+ const labelBoxes = new Map([+ [0, { x: 21, y: 226, width: 60, height: 26 }],+ [1, { x: 141, y: 168, width: 70, height: 26 }],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING, labelBoxes });+ assert.equal(hidden.size, 0);+});++test("of two labels from different columns that would collide, the smaller yields", () => {+ const nodes = [+ { index: 0, x0: 120, x1: 135, value: 3230, y0: 100, y1: 110 }, // label runs right+ { index: 1, x0: 300, x1: 315, value: 21967, y0: 100, y1: 140 }, // label runs left+ ];+ const labelBoxes = new Map([+ [0, { x: 141, y: 92, width: 90, height: 26 }],+ [1, { x: 200, y: 108, width: 94, height: 26 }],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING, labelBoxes });+ assert.equal(hidden.has(1), false, "more prominent label keeps its place");+ assert.equal(hidden.has(0), true);+});++test("label boxes in the same column are left to the spacing rule", () => {+ const nodes = column([+ [500, 0, 20],+ [400, 30, 50],+ ]).map((node) => ({ ...node, x1: 115 }));+ const labelBoxes = new Map([+ [0, { x: 121, y: -3, width: 80, height: 26 }],+ [1, { x: 121, y: 26, width: 80, height: 26 }],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING, labelBoxes });+ assert.equal(hidden.size, 0);+});++test("a label rejected for crossing a bar doesn't keep its smaller neighbour hidden", () => {+ const nodes = [+ { index: 0, x0: 300, x1: 315, value: 1000, y0: 100, y1: 140 },+ { index: 1, x0: 300, x1: 315, value: 200, y0: 145, y1: 150 },+ { index: 2, x0: 200, x1: 215, value: 1500, y0: 100, y1: 160 },+ ];+ const labelBoxes = new Map([+ [0, { x: 190, y: 106, width: 104, height: 26 }],+ [1, { x: 240, y: 134, width: 54, height: 26 }],+ ]);+ const hidden = hiddenSankeyLabels(nodes, { height: 400, minSpacing: SPACING, labelBoxes });+ assert.equal(hidden.has(0), true, "crosses the bar to its left");+ assert.equal(hidden.has(1), false, "takes the place it was crowded out of");+ assert.equal(hidden.has(2), false);+});diff --git a/test/system/cash_flow_test.rb b/test/system/cash_flow_test.rbindex 51cb7dbe73..ae4b5821ad 100644--- a/test/system/cash_flow_test.rb+++ b/test/system/cash_flow_test.rb@@ -20,6 +20,13 @@ class CashFlowTest < ApplicationSystemTestCasechart = find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)assert_selector "#cashflow-preview svg .sankey-link"assert page.evaluate_script("performance.getEntriesByType('resource').some(e => e.name.includes('/dashboard/cash_flow?'))")+ # A label hidden to avoid a collision can sit over another node; it must+ # not catch that node's clicks.+ assert page.evaluate_script(<<~JS)+ Array.from(document.querySelectorAll("#cashflow-preview svg text"))+ .filter(text => text.style.opacity === "0")+ .every(text => getComputedStyle(text).pointerEvents === "none")+ JSwithin "#cashflow-preview" doclick_button "Expand", enable_aria_label: trueend@@ -39,8 +46,7 @@ class CashFlowTest < ApplicationSystemTestCase})JSpage.execute_script("document.querySelector('#cashflow-preview-expanded-dialog').close()")- parent = chart.find("svg text", text: "Sankey Shopping", match: :first)- parent.find(:xpath, "..").find("path").click+ chart.find("g[role='button'][aria-label^='Sankey Shopping,']").find("path").clickassert_selector "[data-preview-sankey-chart-target='zoomOutButton']:not([hidden])"find("[data-preview-sankey-chart-target='zoomOutButton']", match: :first).clickchart.find("svg text", text: "Sankey Groceries", match: :first).find(:xpath, "..").find("path").click@@ -52,6 +58,9 @@ class CashFlowTest < ApplicationSystemTestCaseendtest "bars labels Enter and Space share zoom and transaction actions" do+ # With the assistant panel open the chart is ~500px wide, and Sankey+ # Shopping's label would cover Cash Flow's, so it yields; give it room.+ @user.update!(show_ai_sidebar: false)sign_in @user[ :bar, :label, :enter, :space ].each do |activation|visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)@@ -241,7 +250,7 @@ class CashFlowTest < ApplicationSystemTestCasesign_in @userassert_selector "#cashflow-preview svg .sankey-link"install_posthog_fake- find("#cashflow-preview svg text", text: "Sankey Shopping", match: :first).hover+ find("#cashflow-preview g[aria-label^='Sankey Shopping,'] path", match: :first).hoverassert_selector ".chart-tooltip.ph-no-capture", text: "Sankey Shopping"within "#cashflow-preview" doclick_button "Something looks wrong"