Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix Back for drawers, modals, the period picker and URL rewrites (#3886)

Guillem Arias Fausted12543f5dc7c
diff --git a/app/components/DS/dialog.rb b/app/components/DS/dialog.rb
index 60a5226715..ca7b4f21cf 100644
--- a/app/components/DS/dialog.rb
+++ b/app/components/DS/dialog.rb
@@ -141,6 +141,13 @@ class DS::Dialog < DesignSystemComponent
data[:DS__dialog_disable_click_outside_value] = disable_click_outside
data[:action] = [ "click->DS--dialog#clickOutside", data[:action] ].compact.join(" ")
data[:hotkey] = "esc:DS--dialog#close"
+ # Fetched into a frame over the page, the dialog is left out of Turbo's
+ # cached copy of that page, or Back brings it back: stray if it was still
+ # open, opened again if it was closed. Visited directly, it is the page and
+ # stays. Turbo also caches the live page right after any frame visit with
+ # data-turbo-action renders, and that removes these dialogs, so don't open
+ # one that way or make such a visit while one is open.
+ data[:turbo_temporary] = true if helpers.turbo_frame_request_id == frame.to_s
merged_opts[:data] = data
merged_opts
diff --git a/app/components/DS/dialog_controller.js b/app/components/DS/dialog_controller.js
index 918e707a5b..d16aa71425 100644
--- a/app/components/DS/dialog_controller.js
+++ b/app/components/DS/dialog_controller.js
@@ -32,7 +32,11 @@ export default class extends Controller {
this.element.addEventListener("keydown", this._onKeydown);
this.element.addEventListener("close", this._onClose);
- if (this.element.open) return;
+ if (this.element.matches(":modal")) return;
+ // Back restores a dialog cached open as a plain open one: no backdrop, no
+ // focus trap. Put it back as it was rendered, closed and with no close
+ // event for listeners to act on, and let auto-open show it as a modal.
+ if (this.element.open) this.element.removeAttribute("open");
if (this.autoOpenValue) {
this._priorFocus = this.#returnFocusTarget();
this.element.showModal();
@@ -65,6 +69,8 @@ export default class extends Controller {
close() {
this.element.close();
+ // Now as well as on the close event: a reload-on-close visit can cache
+ // the page before that event fires.
this.#clearParentModalFrame();
if (this.reloadOnCloseValue) {
@@ -115,6 +121,8 @@ export default class extends Controller {
if (prior && typeof prior.focus === "function" && document.body.contains(prior)) {
prior.focus();
}
+ // Escape closes the dialog natively, without close().
+ this.#clearParentModalFrame();
}
#focusables() {
diff --git a/app/components/DS/menu_controller.js b/app/components/DS/menu_controller.js
index 5615c6e5b8..f0822f871f 100644
--- a/app/components/DS/menu_controller.js
+++ b/app/components/DS/menu_controller.js
@@ -27,6 +27,9 @@ export default class extends Controller {
this.boundUpdate = this.update.bind(this);
this.addEventListeners();
this.startAutoUpdate();
+ // Every menu renders closed, so one that connects open is a copy Turbo
+ // cached while it was open, brought back by Back.
+ this.close();
}
// Derived from the content element's own class rather than tracked as
diff --git a/app/components/DS/tabs_controller.js b/app/components/DS/tabs_controller.js
index 1fe66c396b..a8f3d90478 100644
--- a/app/components/DS/tabs_controller.js
+++ b/app/components/DS/tabs_controller.js
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus";
+import replaceUrl from "utils/replace_url";
// Connects to data-controller="tabs--components"
export default class extends Controller {
@@ -37,12 +38,9 @@ export default class extends Controller {
if (this.urlParamKeyValue) {
const url = new URL(window.location.href);
url.searchParams.set(this.urlParamKeyValue, selectedTabId);
- // Keep Turbo's entry in the state: without it, Turbo ignores the
- // popstate when Back returns here and the other page stays on screen.
- window.history.replaceState(window.history.state, "", url);
+ replaceUrl(url);
}
- // Update URL with the selected tab
if (this.sessionKeyValue) {
this.#updateSessionPreference(selectedTabId);
}
diff --git a/app/javascript/application.js b/app/javascript/application.js
index 353017fa9e..9362e27719 100644
--- a/app/javascript/application.js
+++ b/app/javascript/application.js
@@ -45,6 +45,25 @@ HwComboboxController.prototype._filterAsync = async function(inputType) {
}
};
+// Fix Back after a frame visit with data-turbo-action (the period picker).
+// Turbo promotes it to a page visit that renders nothing, because turbo_rails'
+// frame layout has none of the page's data-turbo-track assets, so Turbo never
+// records the new URL as rendered. Back to the old URL is then a same-page
+// no-op, and navigating away caches this page under the old URL. Record it on
+// turbo:load, after the promoted visit has cached the previous page under the
+// old URL, and only when a frame on the page now shows that URL: Turbo 8.0.13
+// also promotes a frame that loads after the page it was on has gone. Drop
+// this once hotwired/turbo#1569 ships.
+document.addEventListener("turbo:load", ({ detail: { url } }) => {
+ const frames = document.querySelectorAll("turbo-frame[src]");
+ const frameShowsUrl = [...frames].some(
+ (frame) => new URL(frame.src, document.baseURI).href === url,
+ );
+ if (frameShowsUrl) {
+ Turbo.session.view.lastRenderedLocation = Turbo.session.history.location;
+ }
+});
+
Turbo.StreamActions.redirect = function () {
// Use "replace" to avoid adding form submission to browser history
Turbo.visit(this.target, { action: "replace" });
diff --git a/app/javascript/controllers/auto_open_controller.js b/app/javascript/controllers/auto_open_controller.js
index de59f108eb..8ccb346ccb 100644
--- a/app/javascript/controllers/auto_open_controller.js
+++ b/app/javascript/controllers/auto_open_controller.js
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus";
+import replaceUrl from "utils/replace_url";
// Connects to data-controller="auto-open"
// Auto-opens a <details> element based on URL param
@@ -18,7 +19,7 @@ export default class extends Controller {
const newUrl = params.toString()
? `${window.location.pathname}?${params.toString()}${window.location.hash}`
: `${window.location.pathname}${window.location.hash}`;
- window.history.replaceState({}, "", newUrl);
+ replaceUrl(newUrl);
// Scroll into view after opening
requestAnimationFrame(() => {
diff --git a/app/javascript/controllers/budget_filter_controller.js b/app/javascript/controllers/budget_filter_controller.js
index 0d73e4f43d..5a9eebc7b5 100644
--- a/app/javascript/controllers/budget_filter_controller.js
+++ b/app/javascript/controllers/budget_filter_controller.js
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus";
+import replaceUrl from "utils/replace_url";
export default class extends Controller {
static targets = ["onTrack", "overBudget", "tab"];
@@ -55,6 +56,6 @@ export default class extends Controller {
url.searchParams.set("filter", this.filterValue);
}
- window.history.replaceState({}, "", url);
+ replaceUrl(url);
}
}
diff --git a/app/javascript/controllers/goals_filter_controller.js b/app/javascript/controllers/goals_filter_controller.js
index ed98040b9d..454f82a724 100644
--- a/app/javascript/controllers/goals_filter_controller.js
+++ b/app/javascript/controllers/goals_filter_controller.js
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus";
+import replaceUrl from "utils/replace_url";
// Free-text + status-chip filter for the goals index grid.
// Mirrors the providers-filter pattern. Each card has data-goal-name
@@ -67,10 +68,10 @@ export default class extends Controller {
this.#scheduleUrlSync();
}
- // Debounced wrapper. Firing replaceState on every keystroke is wasteful
+ // Debounced wrapper. Firing replaceUrl on every keystroke is wasteful
// and produced visible jank on slow CPUs; deferring 200 ms collapses a
// typing burst into a single URL update without losing back-button
- // fidelity (replaceState doesn't create history entries anyway).
+ // fidelity (replaceUrl doesn't create history entries anyway).
#scheduleUrlSync() {
clearTimeout(this._urlSyncTimer);
this._urlSyncTimer = setTimeout(() => this.#syncUrl(), 200);
@@ -103,7 +104,7 @@ export default class extends Controller {
}
const qs = params.toString();
const url = qs ? `${window.location.pathname}?${qs}` : window.location.pathname;
- window.history.replaceState(window.history.state, "", url);
+ replaceUrl(url);
}
updateEmptyState(visible, query, active) {
diff --git a/app/javascript/controllers/lazy_load_controller.js b/app/javascript/controllers/lazy_load_controller.js
index 93bea5c30b..246602d652 100644
--- a/app/javascript/controllers/lazy_load_controller.js
+++ b/app/javascript/controllers/lazy_load_controller.js
@@ -3,27 +3,12 @@ import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="lazy-load"
// Used with <details> elements to lazy-load content when expanded
// Use data-action="toggle->lazy-load#toggled" on the <details> element
-// Optional: data-lazy-load-auto-open-param-value="paramName" to auto-open when ?paramName=1 is in URL
export default class extends Controller {
static targets = ["content", "loading", "frame"];
- static values = { url: String, loaded: Boolean, autoOpenParam: String };
+ static values = { url: String, loaded: Boolean };
connect() {
- // Check if we should auto-open based on URL param
- if (this.hasAutoOpenParamValue && this.autoOpenParamValue) {
- const params = new URLSearchParams(window.location.search);
- if (params.get(this.autoOpenParamValue) === "1") {
- this.element.open = true;
- // Clean up the URL param after opening
- params.delete(this.autoOpenParamValue);
- const newUrl = params.toString()
- ? `${window.location.pathname}?${params.toString()}${window.location.hash}`
- : `${window.location.pathname}${window.location.hash}`;
- window.history.replaceState({}, "", newUrl);
- }
- }
-
- // If already open on connect (browser restored state), load immediately
+ // If already open on connect (rendered open, or browser restored state), load immediately
if (this.element.open && !this.loadedValue) {
this.load();
}
diff --git a/app/javascript/utils/replace_url.js b/app/javascript/utils/replace_url.js
new file mode 100644
index 0000000000..371b6818f1
--- /dev/null
+++ b/app/javascript/utils/replace_url.js
@@ -0,0 +1,15 @@
+// Rewrites the current history entry's URL the way a Turbo "replace" visit
+// does, minus the request. A raw history.replaceState hides the new URL from
+// Turbo. With other state, Turbo ignores Back to the entry. With Turbo's state
+// kept, Turbo still caches the page under the old URL, so Back to the new one
+// refetches the page instead of restoring it.
+//
+// Uses Turbo 8.0.13 internals, like the turbo:load listener in application.js.
+// test/system/replace_url_back_test.rb fails if an upgrade moves them.
+export default function replaceUrl(url) {
+ const location = new URL(url, window.location.href);
+ const { session } = Turbo;
+
+ session.history.replace(location, session.history.restorationIdentifier);
+ session.view.lastRenderedLocation = location;
+}
diff --git a/app/views/accounts/new/_method_selector.html.erb b/app/views/accounts/new/_method_selector.html.erb
index a267c562c9..55dd6912c5 100644
--- a/app/views/accounts/new/_method_selector.html.erb
+++ b/app/views/accounts/new/_method_selector.html.erb
@@ -30,7 +30,6 @@
class: "group text-primary flex items-center gap-4 w-full text-center focus:outline-hidden focus:bg-surface-hover border border-transparent focus:border focus:border-primary px-2 hover:bg-surface-hover rounded-lg p-2",
data: is_lunchflow ? {
turbo_frame: "modal",
- turbo_action: "advance",
lunchflow_preload_target: "link"
} : { turbo_frame: "modal", turbo_prefetch: "false" } do %>
<span class="flex w-8 h-8 shrink-0 grow-0 items-center justify-center rounded-lg bg-alpha-black-50 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.02)]">
diff --git a/app/views/bills/drawer.html.erb b/app/views/bills/drawer.html.erb
index 0dcabdfd12..1a0a9b97a2 100644
--- a/app/views/bills/drawer.html.erb
+++ b/app/views/bills/drawer.html.erb
@@ -1,11 +1,7 @@
<%# Opened from a row, over the list, the way a transaction or a budget
category opens. The list stays where it was, so closing this lands back
- on the same row.
-
- Temporary, so Turbo leaves it out of the cached page: "View full bill"
- navigates away with the drawer still open, and Back would otherwise bring
- it back as a stray non-modal dialog. %>
-<%= render DS::Dialog.new(variant: :drawer, data: { turbo_temporary: true }) do |dialog| %>
+ on the same row. %>
+<%= render DS::Dialog.new(variant: :drawer) do |dialog| %>
<% dialog.with_header(title: @series.display_name) do %>
<% if @series.category %>
<%= render "categories/badge", category: @series.category %>
diff --git a/app/views/indexa_capital_items/_indexa_capital_item.html.erb b/app/views/indexa_capital_items/_indexa_capital_item.html.erb
index b2f0d05c52..bd2ae5cba5 100644
--- a/app/views/indexa_capital_items/_indexa_capital_item.html.erb
+++ b/app/views/indexa_capital_items/_indexa_capital_item.html.erb
@@ -79,7 +79,7 @@
variant: "link",
text: t(".update_credentials"),
icon: "cable",
- href: settings_providers_path(manage: "1")
+ href: settings_providers_path
) %>
<% menu.with_item(
variant: "button",
diff --git a/app/views/recurring_occurrences/show.html.erb b/app/views/recurring_occurrences/show.html.erb
index 5e160461cd..b1688f9fe5 100644
--- a/app/views/recurring_occurrences/show.html.erb
+++ b/app/views/recurring_occurrences/show.html.erb
@@ -13,15 +13,9 @@
app -- a centred card on a phone, a right-hand drawer from lg up. The close
button is ours rather than dialog.close_button, because that one carries
`hidden lg:flex` under `responsive`, which leaves a phone with no visible
- way out.
+ way out. %>
- Temporary in the drawer, so Turbo leaves it out of the cached page: "View
- full bill" navigates away with it open, and Back would otherwise restore
- it as a stray non-modal dialog. Not on a direct visit, where the dialog is
- the page and Back has to bring it back. nil there, not false: Turbo drops
- any element carrying the attribute, "false" included. %>
-
-<%= render DS::Dialog.new(frame: "drawer", responsive: true, data: { turbo_temporary: (true if turbo_frame_request?) }) do |dialog| %>
+<%= render DS::Dialog.new(frame: "drawer", responsive: true) do |dialog| %>
<% dialog.with_header(custom_header: true) do %>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
diff --git a/app/views/settings/providers/_snaptrade_panel.html.erb b/app/views/settings/providers/_snaptrade_panel.html.erb
index 3d975f249d..8190de2d03 100644
--- a/app/views/settings/providers/_snaptrade_panel.html.erb
+++ b/app/views/settings/providers/_snaptrade_panel.html.erb
@@ -1,4 +1,4 @@
-<div class="space-y-4">
+<div id="snaptrade-providers-panel" class="space-y-4">
<%= render DS::Alert.new(message: t("providers.snaptrade.free_tier_warning"), variant: :warning) %>
<% error_msg = local_assigns[:error_message] || @error_message %>
@@ -75,13 +75,15 @@
<% if snaptrade_item&.persisted? && snaptrade_item.oauth_configured? %>
<div class="border-t border-primary pt-4 mt-4">
+ <%# "Manage Connections" in the item menu links here with ?manage=1. %>
+ <%# The row's auto-open reads and drops it, so open from the server. %>
<%= render DS::Disclosure.new(
variant: :inline,
+ open: params[:manage] == "1",
data: {
controller: "lazy-load",
action: "toggle->lazy-load#toggled",
- lazy_load_url_value: connections_snaptrade_item_path(snaptrade_item),
- lazy_load_auto_open_param_value: "manage"
+ lazy_load_url_value: connections_snaptrade_item_path(snaptrade_item)
}
) do |disclosure| %>
<% disclosure.with_summary_content do %>
diff --git a/test/components/DS/dialog_test.rb b/test/components/DS/dialog_test.rb
new file mode 100644
index 0000000000..e6fac26642
--- /dev/null
+++ b/test/components/DS/dialog_test.rb
@@ -0,0 +1,35 @@
+require "test_helper"
+
+class DS::DialogTest < ViewComponent::TestCase
+ # Turbo caches a page as it was left, and Back restores that copy. A drawer or
+ # modal fetched into the page came back with it: stray and non-modal if it was
+ # still open, opened again if it had been closed.
+ test "a drawer fetched into its frame is left out of Turbo's page cache" do
+ vc_test_request.headers["Turbo-Frame"] = "drawer"
+ render_inline(DS::Dialog.new(frame: "drawer", responsive: true))
+
+ assert_selector "turbo-frame#drawer > dialog[data-turbo-temporary]"
+ end
+
+ test "a drawer fetched into a frame of its own is left out of Turbo's page cache" do
+ vc_test_request.headers["Turbo-Frame"] = "bulk_transaction_edit_drawer"
+ render_inline(DS::Dialog.new(variant: "drawer", frame: "bulk_transaction_edit_drawer"))
+
+ assert_selector "turbo-frame#bulk_transaction_edit_drawer > dialog[data-turbo-temporary]"
+ end
+
+ # Visited directly, the drawer is the page, and Back has to bring it back.
+ test "a drawer rendered as the page stays in the cache" do
+ render_inline(DS::Dialog.new(frame: "drawer", responsive: true))
+
+ assert_selector "turbo-frame#drawer > dialog"
+ assert_no_selector "dialog[data-turbo-temporary]"
+ end
+
+ test "a modal fetched into the modal frame is left out of Turbo's page cache" do
+ vc_test_request.headers["Turbo-Frame"] = "modal"
+ render_inline(DS::Dialog.new)
+
+ assert_selector "turbo-frame#modal > dialog[data-turbo-temporary]"
+ end
+end
diff --git a/test/system/dialog_back_test.rb b/test/system/dialog_back_test.rb
new file mode 100644
index 0000000000..66f49603cc
--- /dev/null
+++ b/test/system/dialog_back_test.rb
@@ -0,0 +1,120 @@
+require "application_system_test_case"
+
+# Turbo caches a page as it was left, and Back restores that copy. A drawer or
+# modal fetched into the page came back with it: stray and non-modal if it was
+# still open, opened again if it had been closed.
+class DialogBackTest < ApplicationSystemTestCase
+ setup do
+ sign_in users(:family_admin)
+ @transfer = transfers(:one)
+ # The fixture's kinds predate the transfer kinds, and without them its row
+ # opens the transaction drawer instead of the transfer's.
+ @transfer.outflow_transaction.update!(kind: "cc_payment")
+ @transfer.inflow_transaction.update!(kind: "funds_movement")
+ @row_link = "a[data-turbo-frame='drawer'][href='#{transfer_path(@transfer)}']"
+ @account = accounts(:depository)
+ end
+
+ test "going back from an account the transfer drawer linked to shows the list without the drawer" do
+ visit transactions_url
+ open_transfer_drawer
+ within("dialog[open]") { click_on @account.name }
+ assert_selector "main h2", text: @account.name
+
+ page.go_back
+ assert_selector "main h1", text: I18n.t("transactions.index.title")
+ assert_no_selector "dialog[open]"
+ end
+
+ test "a drawer closed before leaving the list stays closed on Back" do
+ visit transactions_url
+ open_transfer_drawer
+ page.send_keys(:escape)
+ assert_no_selector "dialog[open]"
+
+ leave_the_list_and_come_back
+ assert_no_selector "dialog[open]"
+ end
+
+ # The modal frame is emptied as its dialog closes, however it closes. Escape
+ # closes it natively, without the controller's close.
+ test "a modal closed with Escape before leaving the list stays closed on Back" do
+ visit transactions_url
+ click_on I18n.t("transactions.index.new_transaction")
+ assert_selector "turbo-frame#modal dialog[open]"
+ page.send_keys(:escape)
+ assert_no_selector "dialog[open]"
+
+ leave_the_list_and_come_back
+ assert_no_selector "dialog[open]"
+ end
+
+ # The user menu's Settings opens the list with a return_to, and a provider's
+ # Cancel goes to the bare list. Back undid the Cancel: the modal came back as
+ # if it had never been cancelled.
+ test "going back after cancelling a provider's link modal shows the list without it" do
+ visit accounts_url(return_to: root_path)
+ within("##{dom_id(@account)}") { find("[data-DS--menu-target='button']").click }
+ click_on I18n.t("accounts.account.link_provider")
+ click_on I18n.t("wise_items.provider_connection.name", name: wise_items(:one).name)
+
+ # Both lists look the same, so the one being left is marked.
+ execute_script("document.body.dataset.left = ''")
+ within("dialog:modal", text: I18n.t("wise_items.select_existing_account.title", account_name: @account.name)) do
+ click_on I18n.t("wise_items.select_existing_account.cancel")
+ end
+ assert_no_selector "body[data-left]"
+
+ page.go_back
+ assert_selector "body[data-left]"
+ assert_no_selector "dialog[open]"
+ end
+
+ # Turbo drops temporary elements as it caches a page, and a frame visit with
+ # data-turbo-action caches the live page right after the frame renders. Lunch
+ # Flow's link opened the modal frame that way, so its modal went as it opened.
+ test "Lunch Flow's link opens its modal and the modal stays open" do
+ # Without an API key the link opens the setup modal, and nothing calls Lunch
+ # Flow.
+ lunchflow_items(:one).update!(api_key: nil)
+ visit accounts_url
+ click_on I18n.t("accounts.index.new_account")
+ # Each click waits for the modal frame to finish loading. A link clicked
+ # before that loses any data-turbo-action, so this test would pass with the
+ # attribute back on Lunch Flow's link. People don't click that fast.
+ assert_selector "turbo-frame#modal[complete]", visible: :all
+ click_link Depository.singular_display_name
+ assert_selector "turbo-frame#modal[complete]", visible: :all
+ click_link I18n.t("accounts.new.method_selector.link_with_provider", provider: "Lunch Flow")
+
+ title = I18n.t("lunchflow_items.setup_required.title")
+ assert_selector "dialog:modal", text: title
+ assert_not has_no_selector?("dialog:modal", text: title, wait: 1), "The modal went as it opened"
+ end
+
+ # Visited directly, the drawer is the page, so Back has to bring it back.
+ test "going back to a drawer visited directly restores it as a modal" do
+ visit transfer_url(@transfer)
+ within("dialog[open]") { click_on @account.name }
+ assert_selector "main h2", text: @account.name
+
+ page.go_back
+ within("dialog:modal") { assert_link @account.name }
+ end
+
+ private
+ # The row's name is cut to nothing beside its badges, so this clicks the
+ # link the way the row's own click handler does.
+ def open_transfer_drawer
+ execute_script("arguments[0].click()", find(@row_link, visible: :all))
+ within("dialog[open]") { assert_link @account.name }
+ end
+
+ def leave_the_list_and_come_back
+ find("a[href='#{reports_path}']", match: :first).click
+ assert_selector "h1", text: I18n.t("reports.index.title")
+
+ page.go_back
+ assert_selector "main h1", text: I18n.t("transactions.index.title")
+ end
+end
diff --git a/test/system/period_picker_back_test.rb b/test/system/period_picker_back_test.rb
new file mode 100644
index 0000000000..338ca0463c
--- /dev/null
+++ b/test/system/period_picker_back_test.rb
@@ -0,0 +1,94 @@
+require "application_system_test_case"
+
+class PeriodPickerBackTest < ApplicationSystemTestCase
+ setup do
+ sign_in users(:family_admin)
+ end
+
+ test "Back after a pick shows the previous period" do
+ account = accounts(:depository)
+ visit account_path(account)
+ assert_selector "main h2", text: account.name
+
+ pick_period "90D"
+ page.go_back
+
+ assert_selector "#{period_button("30D")}[aria-expanded='false']"
+ assert_current_path account_path(account)
+ end
+
+ test "Back after a tab switch and a pick shows the tab and the previous period" do
+ account = accounts(:investment)
+ visit account_path(account)
+ find("[role='tab']", text: "Holdings").click
+ assert_current_path account_path(account, tab: "holdings")
+
+ pick_period "90D"
+ page.go_back
+
+ assert_selector "#{period_button("30D")}[aria-expanded='false']"
+ assert_selector "[role='tab'][aria-selected='true']", text: "Holdings"
+ assert_current_path account_path(account, tab: "holdings")
+ end
+
+ test "Back from a page opened after a pick shows the pick, then the previous period" do
+ pick_period "90D"
+ click_link "Transactions"
+ assert_selector "main h1", text: "Transactions"
+
+ page.go_back
+ assert_selector period_button("90D")
+
+ page.go_back
+ assert_selector "#{period_button("30D")}[aria-expanded='false']"
+ assert_current_path root_path
+ end
+
+ test "Back after leaving before a pick loads stays on the page left for" do
+ execute_script(<<~JS)
+ document.addEventListener("turbo:before-fetch-request", function hold(event) {
+ if (event.target.id !== "dashboard_sections") return;
+ document.removeEventListener("turbo:before-fetch-request", hold);
+ event.preventDefault();
+ window.releasePick = event.detail.resume;
+ });
+ JS
+ find(any_period_button).click
+ click_link "90D"
+ click_link "Transactions"
+ assert_selector "main h1", text: "Transactions"
+
+ # Turbo 8.0.13 still renders the frame the page left behind, then pushes
+ # its URL and promotes it to a visit.
+ wait_for_turbo_load { execute_script("window.releasePick()") }
+ page.go_back
+
+ assert_not has_selector?(any_period_button, wait: 1)
+ assert_current_path transactions_path
+ end
+
+ private
+ def period_button(label)
+ "button[aria-label='#{I18n.t("UI.period_picker.aria_label", period: label)}']"
+ end
+
+ def any_period_button
+ "button[aria-label^='#{I18n.t("UI.period_picker.aria_label", period: "")}']"
+ end
+
+ def pick_period(label)
+ find(any_period_button).click
+ wait_for_turbo_load { click_link label }
+ assert_selector period_button(label)
+ end
+
+ # A pick renders its frame, then Turbo promotes it to a page visit that
+ # pushes the new URL. Leaving before that visit's turbo:load cancels it,
+ # which no person clicks fast enough to do.
+ def wait_for_turbo_load
+ execute_script("document.addEventListener('turbo:load', () => document.documentElement.dataset.turboLoaded = '', { once: true })")
+ yield
+ assert_selector "html[data-turbo-loaded]", visible: :all
+ execute_script("delete document.documentElement.dataset.turboLoaded")
+ end
+end
diff --git a/test/system/replace_url_back_test.rb b/test/system/replace_url_back_test.rb
new file mode 100644
index 0000000000..f678cab6b0
--- /dev/null
+++ b/test/system/replace_url_back_test.rb
@@ -0,0 +1,39 @@
+require "application_system_test_case"
+
+class ReplaceUrlBackTest < ApplicationSystemTestCase
+ setup do
+ sign_in users(:family_admin)
+ end
+
+ test "Back after a tab switch restores the account page as it was left" do
+ account = accounts(:investment)
+ visit account_path(account)
+ find("[role='tab']", text: "Holdings").click
+ assert_current_path account_path(account, tab: "holdings")
+
+ # Only the copy Turbo caches on leaving carries this mark. A refetch drops it.
+ execute_script("document.body.dataset.left = ''")
+ click_link "Transactions"
+ assert_selector "main h1", text: "Transactions"
+
+ page.go_back
+
+ assert_selector "body[data-left]"
+ assert_selector "[role='tab'][aria-selected='true']", text: "Holdings"
+ assert_current_path account_path(account, tab: "holdings")
+ end
+
+ test "Back to a page that dropped its auto-open param shows that page" do
+ visit settings_providers_path(manage: 1)
+ assert_selector "details[open]", text: "SnapTrade"
+ assert_current_path settings_providers_path
+
+ click_link "Preferences"
+ assert_selector "h1", text: "Preferences"
+
+ page.go_back
+
+ assert_selector "h1", text: "Bank sync"
+ assert_current_path settings_providers_path
+ end
+end
diff --git a/test/system/settings/providers_test.rb b/test/system/settings/providers_test.rb
index 196aae181f..4a64307700 100644
--- a/test/system/settings/providers_test.rb
+++ b/test/system/settings/providers_test.rb
@@ -317,6 +317,21 @@ class Settings::ProvidersTest < ApplicationSystemTestCase
assert_includes details[:class], "border-warning/25"
end
+ test "Manage Connections in the SnapTrade menu opens the connections list" do
+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)
+ Provider::Snaptrade.any_instance.stubs(:list_connections)
+ .returns([ { "id" => "auth_456", "brokerage" => { "name" => "Fidelity Investments" } } ])
+
+ visit accounts_path
+ within "##{dom_id(snaptrade_items(:configured_item))}" do
+ find("button[aria-haspopup='menu']", match: :first).click
+ click_link "Manage Connections"
+ end
+
+ assert_selector "details[open] #snaptrade-providers-panel details[open]", text: "Fidelity Investments"
+ assert_current_path settings_providers_path
+ end
+
private
# Card grid rendered after the `#available` group heading (following sibling div.grid)