The personal finance app for everyone (by everyone)
Ruby
Redraw the cash flow Sankey charts after a Turbo morph refresh (#4697)
Yong Cong Sin8c3d4728bf06
diff --git a/app/javascript/controllers/preview_sankey_chart_controller.js b/app/javascript/controllers/preview_sankey_chart_controller.jsindex 6a2abf4cb4..9df2971d7b 100644--- a/app/javascript/controllers/preview_sankey_chart_controller.js+++ b/app/javascript/controllers/preview_sankey_chart_controller.js@@ -58,6 +58,20 @@ export default class extends Controller {// 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);+ // A Turbo morph refresh (the sync toast's auto-refresh, or a broadcast+ // refresh stream) keeps this element and its controller but puts the+ // server markup back inside, so the sort controls show the default while+ // the order is kept here, and the tooltip appended outside this element+ // is dropped. The graph is fetched again by the cash-flow controller,+ // and the data value callback resets the zoom.+ this.onMorph = () => {+ if (!this.connected) return;++ this.tooltip?.remove();+ this.#createTooltip();+ this.#syncSortControls();+ };+ document.addEventListener("turbo:morph", this.onMorph);this.#createTooltip();this.#syncZoomControls();this.#syncSortControls();@@ -83,6 +97,7 @@ export default class extends Controller {disconnect() {this.connected = false;window.removeEventListener(this.constructor.SORT_EVENT, this.onSortChanged);+ document.removeEventListener("turbo:morph", this.onMorph);this.resizeObserver?.disconnect();clearTimeout(this.drawTimeout);this.tooltip?.remove();diff --git a/app/javascript/controllers/sankey_chart_controller.js b/app/javascript/controllers/sankey_chart_controller.jsindex d32992cd22..a5e6adb877 100644--- a/app/javascript/controllers/sankey_chart_controller.js+++ b/app/javascript/controllers/sankey_chart_controller.js@@ -49,6 +49,13 @@ export default class extends Controller {this.#syncZoomControls();this.#draw();+ // A Turbo morph refresh (the sync toast's auto-refresh) keeps this+ // element and its controller but puts the server markup back around+ // them. Nothing else notices: the size has not changed and the data is+ // unchanged unless the sync brought something new.+ this.onMorph = () => this.#restoreAfterMorph();+ document.addEventListener("turbo:morph", this.onMorph);+// Labels are measured to keep them off neighbouring bars; measure again// once the page font has replaced the fallback.if (document.fonts?.status === "loading") {@@ -68,12 +75,25 @@ export default class extends Controller {disconnect() {this.connected = false;+ document.removeEventListener("turbo:morph", this.onMorph);this.resizeObserver?.disconnect();clearTimeout(this.drawTimeout);this.tooltip?.remove();this.tooltip = null;}+ // The morph dropped the drawing and the tooltip appended outside this+ // element, and put the server's hidden zoom-out button back while the+ // zoom is kept here.+ #restoreAfterMorph() {+ if (!this.connected) return;++ this.tooltip?.remove();+ this.#createTooltip();+ this.#syncZoomControls();+ if (!this.#chartElement().querySelector("svg")) this.#draw();+ }+zoomOut() {if (!this.zoomRootId) return;diff --git a/app/javascript/controllers/sankey_preview_controller.js b/app/javascript/controllers/sankey_preview_controller.jsindex 3bf985bac7..a6d82100ba 100644--- a/app/javascript/controllers/sankey_preview_controller.js+++ b/app/javascript/controllers/sankey_preview_controller.js@@ -75,6 +75,13 @@ export default class extends Controller {this.survey = null;}+ // clear() runs before Turbo caches the page for a visit. A morph refresh+ // keeps this controller, so it is told here that the page is live again+ // and the graph fetched after the morph counts as displayed.+ resume() {+ this.active = true;+ }+update({ detail }) {if (detail.state === "loading") {this.displays.clear();diff --git a/app/views/pages/dashboard/_cashflow_preview.html.erb b/app/views/pages/dashboard/_cashflow_preview.html.erbindex 08f248ab40..41581363ee 100644--- a/app/views/pages/dashboard/_cashflow_preview.html.erb+++ b/app/views/pages/dashboard/_cashflow_preview.html.erb@@ -11,7 +11,7 @@data-sankey-preview-feedback-key-value="<%= feedback[:api_key] %>"data-sankey-preview-feedback-host-value="<%= feedback[:host] %>"data-sankey-preview-survey-id-value="<%= feedback[:survey_id] %>"- data-action="cash-flow:state->sankey-preview#update posthog:ready@document->sankey-preview#trackDisplay visibilitychange@document->sankey-preview#trackDisplay turbo:before-cache@document->sankey-preview#clear keydown->sankey-preview#stopKeydown">+ data-action="cash-flow:state->sankey-preview#update posthog:ready@document->sankey-preview#trackDisplay visibilitychange@document->sankey-preview#trackDisplay turbo:before-cache@document->sankey-preview#clear turbo:morph@document->sankey-preview#resume keydown->sankey-preview#stopKeydown"><header class="px-4 flex flex-wrap items-center justify-between gap-2"><div class="flex flex-wrap items-center gap-2"><h3 class="font-medium text-primary"><%= t("pages.dashboard.cashflow_preview.title") %></h3>@@ -20,8 +20,10 @@<%= render DS::Button.new(icon: "maximize-2", text: nil, variant: :ghost, disabled: true, aria: { label: t("global.expand") },data: { action: "sankey-preview#expand", sankey_preview_target: "expandButton" }) %></header>+ <%# A morph refresh (the sync toast's) puts the server markup back inside, loading state and all,+ with the controllers still connected, so the graph is fetched again and tracking resumes. %><div data-controller="cash-flow" data-sankey-preview-target="display" class="ph-no-capture"- data-action="turbo:before-cache@document->cash-flow#clear"+ data-action="turbo:before-cache@document->cash-flow#clear turbo:morph@document->cash-flow#load"data-cash-flow-url-value="<%= dashboard_cash_flow_path(start_date: period.start_date.iso8601, end_date: period.end_date.iso8601) %>"data-cash-flow-group-by-value="<%= Current.user.cashflow_sankey_group_by %>"><%# Outside the loading/content states, so the grouping can be switched back from an empty graph. %>diff --git a/test/system/cash_flow_test.rb b/test/system/cash_flow_test.rbindex 1b445d4768..3632cf450b 100644--- a/test/system/cash_flow_test.rb+++ b/test/system/cash_flow_test.rb@@ -163,6 +163,80 @@ class CashFlowTest < ApplicationSystemTestCaseassert_no_selector "[data-preview-sankey-chart-target='chart'] svg"end+ test "both charts come back with their controls after a morph refresh" do+ sign_in @user+ assert_selector "#cashflow-preview svg .sankey-link"+ assert_selector "#cashflow-sankey-chart svg .sankey-link"+ within "#cashflow-preview" do+ click_button "Largest first"+ end+ assert_selector "#cashflow-preview button[data-sort-order='descending'][aria-pressed='true']"+ assert_selector "#cashflow-preview svg[data-sort-order='descending'] .sankey-link"+ # By datum rather than label: the label rule can hide a bar's label at+ # this width, and the legacy chart has no accessible node names.+ page.execute_script(<<~JS)+ Array.from(document.querySelectorAll("#cashflow-sankey-chart svg g > path"))+ .find((bar) => bar.__data__?.name === "Sankey Shopping")+ .dispatchEvent(new MouseEvent("click", { bubbles: true }));+ JS+ assert_selector "#cashflow-sankey-chart [data-sankey-chart-target='zoomOutButton']:not([hidden])"+ # The zoomed view keeps the category and its subcategory: one flow.+ assert_selector "#cashflow-sankey-chart svg .sankey-link", count: 1++ # The sync toast refreshes the page this way once a background sync+ # finishes. The morph keeps the chart elements and their controllers but+ # puts the server markup back around them: no drawing, the controls in+ # their default state, and the tooltips gone from the body. Both redraws+ # above have settled, so only the morph can replace the marked drawings.+ page.execute_script(<<~JS)+ window.sankeyMorphs = 0;+ document.addEventListener("turbo:morph", () => { window.sankeyMorphs += 1; });+ document.querySelectorAll("#cashflow-sankey-chart svg, #cashflow-preview svg")+ .forEach((svg) => svg.setAttribute("data-stale", ""));+ Turbo.visit(window.location.href, { action: "replace" });+ JS+ assert_selector "body" do+ page.evaluate_script("window.sankeyMorphs") == 1+ end+ assert_no_selector "#cashflow-sankey-chart svg[data-stale], #cashflow-preview svg[data-stale]"+ assert_selector "#cashflow-sankey-chart svg:not([data-stale]) .sankey-link"+ assert_selector "#cashflow-preview svg:not([data-stale]) .sankey-link"+ assert_selector "#cashflow-sankey-chart [data-sankey-chart-target='zoomOutButton']:not([hidden])"+ assert_selector "#cashflow-preview button[data-sort-order='descending'][aria-pressed='true']"++ find("#cashflow-sankey-chart svg text", text: "Sankey Groceries", match: :first).hover+ assert_selector ".chart-tooltip:not(.ph-no-capture)", text: "Sankey Groceries"++ # Tracking stopped when the page was cached for the visit and must be+ # live again: the graph fetched after the morph counts as a display.+ install_posthog_fake+ find("#cashflow-preview").scroll_to(:center)+ assert_event_count "sankey_preview_displayed", 1+ end++ test "the preview tooltip comes back after a broadcast refresh" do+ sign_in @user+ assert_selector "#cashflow-preview svg .sankey-link"++ # A family broadcast_refresh (e.g. at the end of a SimpleFIN sync) arrives+ # as a refresh stream: Turbo morphs the page without caching it first, so+ # turbo:before-cache never clears the chart, and the morph drops the+ # tooltip it appended to the body.+ page.execute_script(<<~JS)+ window.sankeyMorphs = 0;+ document.addEventListener("turbo:morph", () => { window.sankeyMorphs += 1; });+ document.querySelectorAll("#cashflow-preview svg").forEach((svg) => svg.setAttribute("data-stale", ""));+ Turbo.session.refresh(window.location.href);+ JS+ assert_selector "body" do+ page.evaluate_script("window.sankeyMorphs") == 1+ end+ assert_selector "#cashflow-preview svg:not([data-stale]) .sankey-link"++ find("#cashflow-preview g[aria-label^='Sankey Shopping,'] path", match: :first).hover+ assert_selector ".chart-tooltip.ph-no-capture", text: "Sankey Shopping"+ end+test "preview displays are counted once and feedback uses PostHog survey question IDs" dosign_in @userassert_selector "#cashflow-preview svg .sankey-link"