Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(dashboard): sort the preview cash-flow Sankey by amount (#3798)

scragnogd24db478516d
diff --git a/app/javascript/controllers/preview_sankey_chart_controller.js b/app/javascript/controllers/preview_sankey_chart_controller.js
index a67fb6b3d6..3c7bc75eb8 100644
--- a/app/javascript/controllers/preview_sankey_chart_controller.js
+++ b/app/javascript/controllers/preview_sankey_chart_controller.js
@@ -14,7 +14,7 @@ let nextChartId = 0;
// Preview-only renderer. Keep the legacy Sankey unchanged during comparison.
export default class extends Controller {
- static targets = ["chart", "zoomOutButton"];
+ static targets = ["chart", "zoomOutButton", "sortSegment"];
static values = {
data: Object,
@@ -42,6 +42,9 @@ export default class extends Controller {
"var(--color-gray-500)": "#737373",
};
static MIN_LABEL_SPACING = 28; // Minimum vertical space needed for labels (2 lines)
+ static SORT_ORDERS = ["auto", "ascending", "descending"];
+ static SORT_STORAGE_KEY = "cashflowSankeySortOrder";
+ static SORT_EVENT = "cashflow-sankey:sort-changed";
connect() {
this.gradientPrefix ||= `preview-sankey-${++nextChartId}`;
@@ -50,8 +53,14 @@ export default class extends Controller {
this.resizeObserver = new ResizeObserver(() => this.#draw());
this.resizeObserver.observe(this.#chartElement());
this.tooltip = null;
+ this.sortOrder = this.#storedSortOrder();
+ // The dashboard renders this chart twice (inline and in the expand dialog):
+ // keep every instance on the page in step when one changes the order.
+ this.onSortChanged = (event) => this.#applySortOrder(event.detail.order);
+ window.addEventListener(this.constructor.SORT_EVENT, this.onSortChanged);
this.#createTooltip();
this.#syncZoomControls();
+ this.#syncSortControls();
this.#draw();
}
@@ -65,6 +74,7 @@ export default class extends Controller {
disconnect() {
this.connected = false;
+ window.removeEventListener(this.constructor.SORT_EVENT, this.onSortChanged);
this.resizeObserver?.disconnect();
clearTimeout(this.drawTimeout);
this.tooltip?.remove();
@@ -78,6 +88,32 @@ export default class extends Controller {
d3.select(this.#chartElement()).selectAll("svg").interrupt().remove();
}
+ // Top-to-bottom order of the nodes in each column. "auto" is d3-sankey's
+ // default layout (minimises crossings); the others order by amount.
+ setSort(event) {
+ const order = event.currentTarget.dataset.sortOrder;
+ if (!this.constructor.SORT_ORDERS.includes(order)) return;
+ if (order === this.sortOrder) return;
+
+ try {
+ localStorage.setItem(this.constructor.SORT_STORAGE_KEY, order);
+ } catch {
+ // Ignore storage errors (e.g. private browsing); the choice still applies now.
+ }
+ window.dispatchEvent(
+ new CustomEvent(this.constructor.SORT_EVENT, { detail: { order } }),
+ );
+ }
+
+ #applySortOrder(order) {
+ if (!this.constructor.SORT_ORDERS.includes(order)) return;
+ if (order === this.sortOrder) return;
+
+ this.sortOrder = order;
+ this.#syncSortControls();
+ this.#draw({ animate: true });
+ }
+
zoomOut() {
if (!this.zoomRootId) return;
@@ -135,6 +171,8 @@ export default class extends Controller {
.append("svg")
.attr("width", width)
.attr("height", height)
+ // Marks which order this drawing uses (a redraw fades the old one out).
+ .attr("data-sort-order", this.sortOrder)
.style("opacity", animate ? 0 : 1);
const effectivePadding = this.#calculateNodePadding(nodes.length, height);
@@ -175,6 +213,23 @@ export default class extends Controller {
return zoomSankeyData(this.dataValue, this.zoomRootId);
}
+ #storedSortOrder() {
+ try {
+ const stored = localStorage.getItem(this.constructor.SORT_STORAGE_KEY);
+ return this.constructor.SORT_ORDERS.includes(stored) ? stored : "auto";
+ } catch {
+ return "auto";
+ }
+ }
+
+ #syncSortControls() {
+ this.sortSegmentTargets.forEach((segment) => {
+ const active = segment.dataset.sortOrder === this.sortOrder;
+ segment.classList.toggle("segmented-control__segment--active", active);
+ segment.setAttribute("aria-pressed", active ? "true" : "false");
+ });
+ }
+
#syncZoomControls() {
this.zoomOutButtonTargets.forEach((button) => {
button.hidden = !this.zoomRootId;
@@ -237,6 +292,12 @@ export default class extends Controller {
[width - margin, height - margin],
]);
+ if (this.sortOrder === "ascending") {
+ sankeyGenerator.nodeSort((a, b) => a.value - b.value);
+ } else if (this.sortOrder === "descending") {
+ sankeyGenerator.nodeSort((a, b) => b.value - a.value);
+ }
+
return sankeyGenerator({
nodes: nodes.map((d) => ({
...d,
diff --git a/app/views/pages/dashboard/_cashflow_preview_chart.html.erb b/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
index 3a2e85676f..7f55f43712 100644
--- a/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
+++ b/app/views/pages/dashboard/_cashflow_preview_chart.html.erb
@@ -7,7 +7,7 @@
data-preview-sankey-chart-start-date-value="<%= period.start_date&.iso8601 %>"
data-preview-sankey-chart-end-date-value="<%= period.end_date&.iso8601 %>"
class="w-full min-w-0 h-full privacy-sensitive flex flex-col gap-2">
- <div class="flex justify-start px-4">
+ <div class="flex items-center justify-between gap-2 px-4">
<%= render DS::Button.new(
variant: :icon,
icon: "arrow-left",
@@ -20,6 +20,17 @@
action: "preview-sankey-chart#zoomOut"
}
) %>
+ <%# Remembered per browser; "auto" keeps d3-sankey's crossing-minimising layout. %>
+ <%= render DS::SegmentedControl.new(aria_label: t("pages.dashboard.cashflow_preview.sort_label"), class: "ml-auto") do |sc| %>
+ <% { "auto" => "sort_auto", "ascending" => "sort_ascending", "descending" => "sort_descending" }.each do |order, key| %>
+ <% sc.with_segment(
+ t("pages.dashboard.cashflow_preview.#{key}"),
+ active: order == "auto",
+ class: "text-xs",
+ data: { preview_sankey_chart_target: "sortSegment", sort_order: order, action: "preview-sankey-chart#setSort" }
+ ) %>
+ <% end %>
+ <% end %>
</div>
<div data-preview-sankey-chart-target="chart" class="min-h-0 flex-1"></div>
</div>
diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.yml
index 95f083ed42..d42874228a 100644
--- a/config/locales/views/pages/en.yml
+++ b/config/locales/views/pages/en.yml
@@ -104,6 +104,10 @@ en:
feedback_thanks: "Thanks for helping improve the chart!"
feedback_privacy: "Your response is sent to PostHog. Describe the issue without account numbers, balances, or other private financial details."
feedback_submit: "Send feedback"
+ sort_label: "Sort flows"
+ sort_auto: "Auto"
+ sort_ascending: "Smallest first"
+ sort_descending: "Largest first"
cashflow_sankey:
loading: "Loading cash flow…"
load_error: "Cash flow could not be loaded. Please try again."
diff --git a/test/system/cash_flow_sort_test.rb b/test/system/cash_flow_sort_test.rb
new file mode 100644
index 0000000000..bd8ff7faff
--- /dev/null
+++ b/test/system/cash_flow_sort_test.rb
@@ -0,0 +1,65 @@
+require "application_system_test_case"
+
+class CashFlowSortTest < ApplicationSystemTestCase
+ include EntriesTestHelper
+
+ setup do
+ sign_in @user = users(:family_admin)
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ @month = Date.current.beginning_of_month
+ account = @user.family.accounts.first
+ { "Sort Small" => 30, "Sort Large" => 3000, "Sort Medium" => 300 }.each do |name, amount|
+ category = @user.family.categories.create!(name: name, color: "#123456")
+ create_transaction(account: account, name: "#{name} spend", amount: amount, category: category, date: @month)
+ end
+ page.current_window.resize_to(1400, 1000)
+ end
+
+ test "sorting the preview Sankey orders each column by amount and is remembered" do
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ chart = find("#cashflow-preview [data-controller='preview-sankey-chart']", match: :first)
+ assert chart.has_css?("svg .sankey-link")
+
+ chart.click_button "Smallest first"
+ assert_column_order(:ascending)
+
+ chart.click_button "Largest first"
+ assert_column_order(:descending)
+
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ chart = find("#cashflow-preview [data-controller='preview-sankey-chart']", match: :first)
+ assert chart.has_css?("svg .sankey-link")
+ assert chart.has_css?("button[data-sort-order='descending'][aria-pressed='true']")
+ assert_column_order(:descending)
+ end
+
+ private
+ # Reads the rendered layout (d3 binds each node's datum to its <g>) and
+ # checks every column with 2+ nodes is ordered top-to-bottom by value.
+ def assert_column_order(direction)
+ # A redraw fades the old drawing out and appends a new one, stamped with
+ # its sort order, so wait for that one and read it.
+ svg = "#cashflow-preview [data-preview-sankey-chart-target='chart'] svg[data-sort-order='#{direction}']"
+ assert page.has_css?("#{svg} .sankey-link", wait: 5)
+ columns = page.evaluate_script(<<~JS)
+ (() => {
+ const svg = document.querySelector(#{svg.to_json});
+ const byLayer = {};
+ svg.querySelectorAll("g > g").forEach((g) => {
+ const d = g.__data__;
+ if (!d || d.layer === undefined || d.value === undefined) return;
+ (byLayer[d.layer] ||= []).push({ y: d.y0, value: d.value });
+ });
+ return Object.values(byLayer)
+ .filter((col) => col.length > 1)
+ .map((col) => col.sort((a, b) => a.y - b.y).map((n) => n.value));
+ })()
+ JS
+
+ assert columns.any?, "expected at least one column with several nodes"
+ columns.each do |values|
+ expected = direction == :ascending ? values.sort : values.sort.reverse
+ assert_equal expected, values, "column not #{direction}: #{values.inspect}"
+ end
+ end
+end