Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Keep the cash flow Sankey readable once a family has subcategories (#4642)

Yong Cong Sin5226e08b240e
diff --git a/app/javascript/controllers/preview_sankey_chart_controller.js b/app/javascript/controllers/preview_sankey_chart_controller.js
index 9df2971d7b..283ec7cda3 100644
--- a/app/javascript/controllers/preview_sankey_chart_controller.js
+++ b/app/javascript/controllers/preview_sankey_chart_controller.js
@@ -1,8 +1,9 @@
import { Controller } from "@hotwired/stimulus";
import * as d3 from "d3";
-import { sankey } from "d3-sankey";
+import { sankey, sankeyCenter } from "d3-sankey";
import { formatCashFlowCurrency } from "utils/cash_flow_chart_data";
import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";
+import { sankeyLabelOnRight } from "utils/sankey_align";
import { hiddenSankeyLabels } from "utils/sankey_labels";
import { sankeyNodeHasChildren, zoomSankeyData } from "utils/sankey_zoom";
import {
@@ -308,6 +309,10 @@ export default class extends Controller {
#generateSankeyData(nodes, links, width, height, nodePadding) {
const margin = this.constructor.EXTENT_MARGIN;
const sankeyGenerator = sankey()
+ // Centre alignment: a sink sits at its depth, a source one column
+ // before the nearest node it feeds. The default pushes every sink to
+ // the last column, which is the subcategories' once a family has any.
+ .nodeAlign(sankeyCenter)
.nodeWidth(this.nodeWidthValue)
.nodePadding(nodePadding)
.extent([
@@ -406,7 +411,12 @@ 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(svg, nodeGroups, width, nodes);
+ const hiddenLabels = this.#addNodeLabels(
+ svg,
+ nodeGroups,
+ sankeyLabelOnRight(nodes, width),
+ nodes,
+ );
return { nodeGroups, hiddenLabels };
}
@@ -463,11 +473,11 @@ export default class extends Controller {
L ${x0},${y1} Z`;
}
- #addNodeLabels(svg, nodeGroups, width, nodes) {
+ #addNodeLabels(svg, nodeGroups, labelOnRight, nodes) {
const controller = this;
const hiddenLabels = this.#calculateHiddenLabels(
nodes,
- this.#measureLabels(svg, nodes, width),
+ this.#measureLabels(svg, nodes, labelOnRight),
);
nodeGroups
@@ -485,21 +495,22 @@ export default class extends Controller {
)
.style("transition", "opacity 0.2s ease")
.each(function (d) {
- controller.#writeLabel(d3.select(this), d, width);
+ controller.#writeLabel(d3.select(this), d, labelOnRight);
});
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;
+ // Name above amount, beside the bar on the side the label rule picks.
+ #writeLabel(textEl, d, labelOnRight) {
+ const right = labelOnRight(d);
+ const x = right ? 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");
+ .attr("text-anchor", right ? "start" : "end");
textEl.selectAll("tspan").remove();
textEl.append("tspan").text(d.name);
@@ -515,7 +526,7 @@ export default class extends Controller {
// 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) {
+ #measureLabels(svg, nodes, labelOnRight) {
const probe = svg
.append("text")
.attr("class", "text-xs font-medium select-none")
@@ -523,7 +534,7 @@ export default class extends Controller {
const boxes = new Map();
nodes.forEach((d) => {
- this.#writeLabel(probe, d, width);
+ this.#writeLabel(probe, d, labelOnRight);
const { x, y, width: boxWidth, height } = probe.node().getBBox();
boxes.set(d.index, { x, y, width: boxWidth, height });
});
diff --git a/app/javascript/controllers/sankey_chart_controller.js b/app/javascript/controllers/sankey_chart_controller.js
index a5e6adb877..41220216de 100644
--- a/app/javascript/controllers/sankey_chart_controller.js
+++ b/app/javascript/controllers/sankey_chart_controller.js
@@ -1,8 +1,10 @@
import { Controller } from "@hotwired/stimulus";
import * as d3 from "d3";
-import { sankey } from "d3-sankey";
+import { sankey, sankeyCenter } from "d3-sankey";
import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";
+import { sankeyLabelOnRight } from "utils/sankey_align";
import { hiddenSankeyLabels } from "utils/sankey_labels";
+import { withoutSankeySubcategories } from "utils/sankey_subcategories";
import { sankeyNodeHasChildren, zoomSankeyData } from "utils/sankey_zoom";
import {
buildCategoryTransactionsUrl,
@@ -26,6 +28,9 @@ export default class extends Controller {
static HOVER_OPACITY = 0.4;
static HOVER_FILTER = "saturate(1.3) brightness(1.1)";
static EXTENT_MARGIN = 16;
+ // Below this chart width the subcategory column is dropped: five columns
+ // on a phone leave about 60px between bars, too little for most labels.
+ static SUBCATEGORY_MIN_WIDTH = 640;
static MIN_NODE_PADDING = 4;
static MAX_PADDING_RATIO = 0.4;
static CORNER_RADIUS = 8;
@@ -103,7 +108,8 @@ export default class extends Controller {
}
#draw({ animate = false } = {}) {
- const { nodes = [], links = [] } = this.#visibleData();
+ const width = this.#chartWidth();
+ const { nodes = [], links = [] } = this.#visibleData(width);
if (!nodes.length || !links.length) return;
// Hide tooltip and reset any hover states before redrawing
@@ -124,19 +130,18 @@ export default class extends Controller {
.remove();
this.drawTimeout = setTimeout(() => {
- this.#render(nodes, links, true);
+ this.#render(nodes, links, width, true);
}, this.constructor.ZOOM_TRANSITION_MS / 2);
} else {
chart.selectAll("svg").remove();
- this.#render(nodes, links, false);
+ this.#render(nodes, links, width, false);
}
}
- #render(nodes, links, animate) {
+ #render(nodes, links, width, animate) {
const chartElement = this.#chartElement();
const chart = d3.select(chartElement);
- const width = chartElement.clientWidth || 600;
const height = chartElement.clientHeight || 400;
const svg = chart
@@ -177,10 +182,32 @@ export default class extends Controller {
return this.hasChartTarget ? this.chartTarget : this.element;
}
- #visibleData() {
- if (!this.zoomRootId) return this.dataValue || {};
+ // The data at the current zoom, before the narrow-chart filter. Drill-down
+ // is decided here, so a category whose children are all subcategories
+ // still opens on a phone; the zoomed-in view has no Cash Flow node for
+ // the filter to work from, so it keeps them.
+ #drillableData() {
+ return this.zoomRootId
+ ? zoomSankeyData(this.dataValue, this.zoomRootId)
+ : this.dataValue || {};
+ }
+
+ // Decided on every draw from the width the chart is laid out at, so
+ // rotating a phone redraws with or without the subcategory column as the
+ // width allows.
+ #visibleData(width) {
+ const data = this.#drillableData();
+
+ return width < this.constructor.SUBCATEGORY_MIN_WIDTH
+ ? withoutSankeySubcategories(data)
+ : data;
+ }
- return zoomSankeyData(this.dataValue, this.zoomRootId);
+ // A container with no size yet (the expand dialog before it opens) gets
+ // the same fallback for the filter and the layout; the ResizeObserver
+ // redraws once it has one.
+ #chartWidth() {
+ return this.#chartElement().clientWidth || 600;
}
#syncZoomControls() {
@@ -190,7 +217,7 @@ export default class extends Controller {
}
#zoomIn(node) {
- if (!node.id || !sankeyNodeHasChildren(this.#visibleData(), node.id))
+ if (!node.id || !sankeyNodeHasChildren(this.#drillableData(), node.id))
return;
this.zoomRootId = node.id;
@@ -231,6 +258,10 @@ export default class extends Controller {
#generateSankeyData(nodes, links, width, height, nodePadding) {
const margin = this.constructor.EXTENT_MARGIN;
const sankeyGenerator = sankey()
+ // Centre alignment: a sink sits at its depth, a source one column
+ // before the nearest node it feeds. The default pushes every sink to
+ // the last column, which is the subcategories' once a family has any.
+ .nodeAlign(sankeyCenter)
.nodeWidth(this.nodeWidthValue)
.nodePadding(nodePadding)
.extent([
@@ -319,7 +350,12 @@ 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(svg, nodeGroups, width, nodes);
+ const hiddenLabels = this.#addNodeLabels(
+ svg,
+ nodeGroups,
+ sankeyLabelOnRight(nodes, width),
+ nodes,
+ );
return { nodeGroups, hiddenLabels };
}
@@ -376,11 +412,11 @@ export default class extends Controller {
L ${x0},${y1} Z`;
}
- #addNodeLabels(svg, nodeGroups, width, nodes) {
+ #addNodeLabels(svg, nodeGroups, labelOnRight, nodes) {
const controller = this;
const hiddenLabels = this.#calculateHiddenLabels(
nodes,
- this.#measureLabels(svg, nodes, width),
+ this.#measureLabels(svg, nodes, labelOnRight),
);
nodeGroups
@@ -398,21 +434,22 @@ export default class extends Controller {
)
.style("transition", "opacity 0.2s ease")
.each(function (d) {
- controller.#writeLabel(d3.select(this), d, width);
+ controller.#writeLabel(d3.select(this), d, labelOnRight);
});
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;
+ // Name above amount, beside the bar on the side the label rule picks.
+ #writeLabel(textEl, d, labelOnRight) {
+ const right = labelOnRight(d);
+ const x = right ? 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");
+ .attr("text-anchor", right ? "start" : "end");
textEl.selectAll("tspan").remove();
textEl.append("tspan").text(d.name);
@@ -428,7 +465,7 @@ export default class extends Controller {
// 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) {
+ #measureLabels(svg, nodes, labelOnRight) {
const probe = svg
.append("text")
.attr("class", "text-xs font-medium select-none")
@@ -436,7 +473,7 @@ export default class extends Controller {
const boxes = new Map();
nodes.forEach((d) => {
- this.#writeLabel(probe, d, width);
+ this.#writeLabel(probe, d, labelOnRight);
const { x, y, width: boxWidth, height } = probe.node().getBBox();
boxes.set(d.index, { x, y, width: boxWidth, height });
});
@@ -519,7 +556,7 @@ export default class extends Controller {
nodeGroups
.selectAll("path")
.style("cursor", (d) =>
- sankeyNodeHasChildren(this.#visibleData(), d.id)
+ sankeyNodeHasChildren(this.#drillableData(), d.id)
? "pointer"
: "default",
)
@@ -549,7 +586,7 @@ export default class extends Controller {
.selectAll("text")
.style("cursor", (d) =>
isNavigableCategoryNode(d.id) ||
- sankeyNodeHasChildren(this.#visibleData(), d.id)
+ sankeyNodeHasChildren(this.#drillableData(), d.id)
? "pointer"
: "default",
)
diff --git a/app/javascript/utils/sankey_align.mjs b/app/javascript/utils/sankey_align.mjs
new file mode 100644
index 0000000000..05b5c0c45a
--- /dev/null
+++ b/app/javascript/utils/sankey_align.mjs
@@ -0,0 +1,19 @@
+// Label side for the cash flow Sankey charts. (Column assignment is
+// d3-sankey's sankeyCenter: a sink at its depth, a source one column before
+// the nearest node it feeds, so a category without subcategories stays in
+// the category column and the surplus and invested outflows end beside Cash
+// Flow instead of flush right across the categories.)
+//
+// Labels face the middle of the chart so neither edge cuts them off. The
+// surplus and invested outflows are the exception: beside Cash Flow, a
+// label facing the middle shares the gap with the Cash Flow label and
+// loses to it under the overlap rule, so theirs goes on the right, where
+// nothing flows out of them, unless that is the chart's edge.
+const OUTFLOW_IDS = new Set(["surplus_node", "invested_node"]);
+
+export function sankeyLabelOnRight(nodes, width) {
+ const lastColumn = Math.max(...nodes.map((node) => node.layer));
+ return (node) =>
+ (OUTFLOW_IDS.has(node.id) && node.layer < lastColumn) ||
+ node.x0 < width / 2;
+}
diff --git a/app/javascript/utils/sankey_subcategories.mjs b/app/javascript/utils/sankey_subcategories.mjs
new file mode 100644
index 0000000000..fc189cd9b9
--- /dev/null
+++ b/app/javascript/utils/sankey_subcategories.mjs
@@ -0,0 +1,53 @@
+import { sankeyLinkIndex } from "utils/sankey_zoom";
+
+// Node ids carry the hierarchy the server built (PagesController
+// #build_cashflow_sankey_data): "<side>_<category id>" for a category and
+// "<side>_sub_<category id>" for a subcategory under it. A subcategory whose
+// net direction runs against its parent is linked straight to Cash Flow
+// instead; it is a column of its own and is kept.
+const CASH_FLOW_NODE_ID = "cash_flow_node";
+
+// The chart without its subcategory column. A category's value already
+// includes its subcategories, so dropping them changes no total; it frees a
+// column, which on a narrow chart is the difference between labels that fit
+// and labels that are hidden.
+export function withoutSankeySubcategories(data) {
+ const nodes = data?.nodes || [];
+ const links = data?.links || [];
+ const cashFlowIndex = nodes.findIndex((node) => node.id === CASH_FLOW_NODE_ID);
+ if (cashFlowIndex < 0) return data;
+
+ const linkedToCashFlow = new Set();
+ links.forEach((link) => {
+ const source = sankeyLinkIndex(link.source);
+ const target = sankeyLinkIndex(link.target);
+ if (source === cashFlowIndex) linkedToCashFlow.add(target);
+ if (target === cashFlowIndex) linkedToCashFlow.add(source);
+ });
+
+ const kept = nodes
+ .map((_, index) => index)
+ .filter(
+ (index) =>
+ !String(nodes[index].id).includes("_sub_") || linkedToCashFlow.has(index),
+ );
+ if (kept.length === nodes.length) return data;
+
+ const reindexed = new Map(kept.map((index, newIndex) => [index, newIndex]));
+
+ return {
+ ...data,
+ nodes: kept.map((index) => ({ ...nodes[index] })),
+ links: links
+ .filter(
+ (link) =>
+ reindexed.has(sankeyLinkIndex(link.source)) &&
+ reindexed.has(sankeyLinkIndex(link.target)),
+ )
+ .map((link) => ({
+ ...link,
+ source: reindexed.get(sankeyLinkIndex(link.source)),
+ target: reindexed.get(sankeyLinkIndex(link.target)),
+ })),
+ };
+}
diff --git a/app/javascript/utils/sankey_zoom.mjs b/app/javascript/utils/sankey_zoom.mjs
index 15e27b9ae5..7348b253e1 100644
--- a/app/javascript/utils/sankey_zoom.mjs
+++ b/app/javascript/utils/sankey_zoom.mjs
@@ -44,8 +44,8 @@ export function zoomSankeyData(data, rootNodeId) {
function buildGraph(data) {
const nodes = data?.nodes || [];
const links = (data?.links || []).map((link) => {
- const sourceIndex = linkIndex(link.source);
- const targetIndex = linkIndex(link.target);
+ const sourceIndex = sankeyLinkIndex(link.source);
+ const targetIndex = sankeyLinkIndex(link.target);
return {
original: link,
@@ -77,7 +77,7 @@ function nodeId(node, index) {
return node?.id ?? index;
}
-function linkIndex(endpoint) {
+export function sankeyLinkIndex(endpoint) {
return typeof endpoint === "object" ? endpoint.index : endpoint;
}
diff --git a/config/importmap.rb b/config/importmap.rb
index 8392c63d2e..e527776be1 100644
--- a/config/importmap.rb
+++ b/config/importmap.rb
@@ -62,3 +62,5 @@ 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"
+pin "utils/sankey_align", to: "utils/sankey_align.mjs"
+pin "utils/sankey_subcategories", to: "utils/sankey_subcategories.mjs"
diff --git a/test/config/importmap_test.rb b/test/config/importmap_test.rb
new file mode 100644
index 0000000000..e22bd0fe9f
--- /dev/null
+++ b/test/config/importmap_test.rb
@@ -0,0 +1,15 @@
+require "test_helper"
+
+class ImportmapTest < ActiveSupport::TestCase
+ # `pin_all_from` only picks up .js files, so every .mjs helper needs its own
+ # pin. One left out fails silently: the browser cannot resolve the bare
+ # specifier and every controller importing it stops loading.
+ test "every .mjs helper under utils is pinned" do
+ imports = JSON.parse(Rails.application.importmap.to_json(resolver: ActionController::Base.helpers)).fetch("imports")
+
+ Rails.root.glob("app/javascript/utils/*.mjs").each do |path|
+ specifier = "utils/#{path.basename(".mjs")}"
+ assert imports.key?(specifier), "#{path.relative_path_from(Rails.root)} is not pinned; add `pin \"#{specifier}\", to: \"#{specifier}.mjs\"` to config/importmap.rb"
+ end
+ end
+end
diff --git a/test/javascript/sankey_align_test.mjs b/test/javascript/sankey_align_test.mjs
new file mode 100644
index 0000000000..47912af2a9
--- /dev/null
+++ b/test/javascript/sankey_align_test.mjs
@@ -0,0 +1,34 @@
+import { describe, it } from "node:test"
+import assert from "node:assert/strict"
+import { sankeyLabelOnRight } from "../../app/javascript/utils/sankey_align.mjs"
+
+describe("sankeyLabelOnRight", () => {
+ const WIDTH = 1000
+ const nodes = [
+ { id: "income_work", layer: 1, x0: 200 },
+ { id: "cash_flow_node", layer: 2, x0: 492 },
+ { id: "expense_food", layer: 3, x0: 744 },
+ { id: "surplus_node", layer: 3, x0: 744 },
+ { id: "expense_sub_uk_tax", layer: 4, x0: 969 },
+ ]
+ const onRight = sankeyLabelOnRight(nodes, WIDTH)
+
+ it("faces labels towards the middle of the chart", () => {
+ assert.equal(onRight(nodes[0]), true)
+ assert.equal(onRight(nodes[1]), true)
+ assert.equal(onRight(nodes[2]), false)
+ assert.equal(onRight(nodes[4]), false)
+ })
+
+ it("puts the surplus label on its right, away from the Cash Flow label", () => {
+ assert.equal(onRight(nodes[3]), true)
+ })
+
+ it("keeps a surplus in the last column facing the middle", () => {
+ const threeColumns = [
+ { id: "cash_flow_node", layer: 1, x0: 492 },
+ { id: "surplus_node", layer: 2, x0: 969 },
+ ]
+ assert.equal(sankeyLabelOnRight(threeColumns, WIDTH)(threeColumns[1]), false)
+ })
+})
diff --git a/test/javascript/sankey_subcategories_test.mjs b/test/javascript/sankey_subcategories_test.mjs
new file mode 100644
index 0000000000..785bdfcbaa
--- /dev/null
+++ b/test/javascript/sankey_subcategories_test.mjs
@@ -0,0 +1,83 @@
+import { readFile } from "node:fs/promises"
+import { describe, it } from "node:test"
+import assert from "node:assert/strict"
+
+// The helper resolves "utils/sankey_zoom" through the importmap, which Node
+// has no equivalent of, so the specifier is rewritten to a file URL and the
+// module is imported as written.
+const SOURCE_URL = new URL("../../app/javascript/utils/sankey_subcategories.mjs", import.meta.url)
+const SANKEY_ZOOM_URL = new URL("../../app/javascript/utils/sankey_zoom.mjs", import.meta.url)
+
+const source = (await readFile(SOURCE_URL, "utf8")).replace(
+ '"utils/sankey_zoom"',
+ JSON.stringify(SANKEY_ZOOM_URL.href),
+)
+
+const { withoutSankeySubcategories } = await import(
+ `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`
+)
+
+// Cash Flow -> Taxes -> UK Tax, Cash Flow -> Food, Salary -> Income -> Cash Flow,
+// plus a subcategory that nets against its parent and so links to Cash Flow directly.
+const data = {
+ currency_symbol: "£",
+ nodes: [
+ { id: "cash_flow_node", name: "Cash Flow", value: 100 },
+ { id: "income_1", name: "Income", value: 100 },
+ { id: "income_sub_2", name: "Salary", value: 100 },
+ { id: "expense_3", name: "Taxes", value: 60 },
+ { id: "expense_sub_4", name: "UK Tax", value: 60 },
+ { id: "expense_5", name: "Food", value: 30 },
+ { id: "expense_sub_6", name: "Refunds", value: 10 },
+ ],
+ links: [
+ { source: 1, target: 0, value: 100 },
+ { source: 2, target: 1, value: 100 },
+ { source: 0, target: 3, value: 60 },
+ { source: 3, target: 4, value: 60 },
+ { source: 0, target: 5, value: 30 },
+ { source: 0, target: 6, value: 10 },
+ ],
+}
+
+describe("withoutSankeySubcategories", () => {
+ it("drops subcategories under a parent and reindexes the remaining links", () => {
+ const result = withoutSankeySubcategories(data)
+
+ assert.deepEqual(result.nodes.map((n) => n.name), ["Cash Flow", "Income", "Taxes", "Food", "Refunds"])
+ assert.deepEqual(
+ result.links.map((l) => [result.nodes[l.source].name, result.nodes[l.target].name, l.value]),
+ [["Income", "Cash Flow", 100], ["Cash Flow", "Taxes", 60], ["Cash Flow", "Food", 30], ["Cash Flow", "Refunds", 10]],
+ )
+ assert.equal(result.currency_symbol, "£")
+ })
+
+ it("keeps a subcategory that flows straight to Cash Flow", () => {
+ const result = withoutSankeySubcategories(data)
+
+ assert.ok(result.nodes.some((n) => n.id === "expense_sub_6"))
+ })
+
+ it("accepts links whose endpoints are node objects, as d3 rewrites them", () => {
+ const linked = {
+ ...data,
+ links: data.links.map((l) => ({ ...l, source: { index: l.source }, target: { index: l.target } })),
+ }
+
+ assert.equal(withoutSankeySubcategories(linked).nodes.length, 5)
+ })
+
+ it("returns the data untouched when there is nothing to collapse", () => {
+ const flat = { nodes: data.nodes.slice(0, 2), links: data.links.slice(0, 1) }
+
+ assert.equal(withoutSankeySubcategories(flat), flat)
+ assert.equal(withoutSankeySubcategories({ nodes: [{ id: "x_sub_1" }], links: [] }).nodes.length, 1)
+ })
+
+ it("does not mutate its input", () => {
+ const before = JSON.stringify(data)
+ withoutSankeySubcategories(data)
+
+ assert.equal(JSON.stringify(data), before)
+ })
+})
diff --git a/test/system/cash_flow_test.rb b/test/system/cash_flow_test.rb
index 3632cf450b..bb8f038e9d 100644
--- a/test/system/cash_flow_test.rb
+++ b/test/system/cash_flow_test.rb
@@ -58,6 +58,30 @@ class CashFlowTest < ApplicationSystemTestCase
assert_equal Date.current.iso8601, query.dig("q", "end_date")
end
+ test "a category without subcategories stays in the category column" do
+ rent = @user.family.categories.create!(name: "Sankey Rent", color: "#654321")
+ create_transaction(account: @account, category: rent, amount: 80, date: @month)
+ # Wide enough for the dashboard chart to keep its subcategory column.
+ page.current_window.resize_to(1920, 1400)
+ sign_in @user
+ assert_selector "#cashflow-preview svg .sankey-link"
+ assert_selector "#cashflow-sankey-chart svg .sankey-link"
+
+ # By datum: the label rule can hide a bar's label at this width. The
+ # first chart of each is the inline one, not the dialog's copy.
+ columns = page.evaluate_script(<<~JS)
+ ["#cashflow-preview [data-controller='preview-sankey-chart']", "#cashflow-sankey-chart [data-controller='sankey-chart']"].map((chart) => {
+ const bars = Array.from(document.querySelector(chart).querySelectorAll("svg g > path:not(.sankey-link)"));
+ const x = (name) => bars.find((bar) => bar.__data__?.name === name)?.__data__.x0;
+ return [x("Sankey Rent"), x("Sankey Shopping"), x("Sankey Groceries")];
+ })
+ JS
+ columns.each do |rent_x, category_x, subcategory_x|
+ assert_equal category_x, rent_x
+ assert_operator rent_x, :<, subcategory_x
+ end
+ end
+
test "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.