Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Keep an account page's scroll position when the account is edited from it (#4918)

Yong Cong Sinb1612bed16ad
diff --git a/app/controllers/concerns/accountable_resource.rb b/app/controllers/concerns/accountable_resource.rb
index 3db1f8940f..ac9d1b5f61 100644
--- a/app/controllers/concerns/accountable_resource.rb
+++ b/app/controllers/concerns/accountable_resource.rb
@@ -144,11 +144,27 @@ module AccountableResource
# them. Compared by hand: lock_saved_attributes! saves again, which clears
# saved_change_to_cost_basis_method?.
@account.sync_later if @account.cost_basis_method != previous_cost_basis_method
-
- redirect_back_or_to account_path(@account), notice: t("accounts.update.success", type: accountable_type.name.underscore.humanize)
+ @account_updated = true
+
+ notice = t("accounts.update.success", type: accountable_type.name.underscore.humanize)
+ respond_to do |format|
+ format.html { redirect_back_or_to account_path(@account), notice: notice }
+ # The form submitted through Turbo from the modal: return to the page it
+ # was opened on with a "replace" visit, which Turbo turns into a
+ # morphing refresh of the same page, keeping its scroll position.
+ format.turbo_stream do
+ flash[:notice] = notice
+ render turbo_stream: turbo_stream.action(:redirect, url_from(request.referer) || account_path(@account))
+ end
+ end
end
private
+ # Whether `update` saved the account, for controllers that save more after it.
+ def account_updated?
+ @account_updated.present?
+ end
+
def logo_choice
params.dig(:account, :logo_choice).presence
end
diff --git a/app/controllers/credit_cards_controller.rb b/app/controllers/credit_cards_controller.rb
index 81b57feb3d..9f41c88a83 100644
--- a/app/controllers/credit_cards_controller.rb
+++ b/app/controllers/credit_cards_controller.rb
@@ -17,9 +17,9 @@ class CreditCardsController < ApplicationController
# compare the limit before and after instead.
@available_credit_before = @account.accountable&.available_credit
super
- # Only apply provider settings once the account update succeeded (redirect);
- # a failed update renders :edit and must not persist the flag.
- if response.redirect?
+ # Only apply provider settings once the account update succeeded; a failed
+ # update renders :edit and must not persist the flag.
+ if account_updated?
update_enable_banking_settings
update_lunchflow_settings
update_simplefin_settings
diff --git a/app/controllers/investments_controller.rb b/app/controllers/investments_controller.rb
index 32740822ee..99458d787d 100644
--- a/app/controllers/investments_controller.rb
+++ b/app/controllers/investments_controller.rb
@@ -5,9 +5,9 @@ class InvestmentsController < ApplicationController
def update
super
- # Only if the account itself saved (we redirected). A failed update renders
- # :edit and shouldn't save the portfolio's settings either.
- update_sharesight_settings if response.redirect?
+ # Only if the account itself saved. A failed update renders :edit and
+ # shouldn't save the portfolio's settings either.
+ update_sharesight_settings if account_updated?
end
private
diff --git a/app/views/accounts/_form.html.erb b/app/views/accounts/_form.html.erb
index 5bbb710a4c..27e6b9b483 100644
--- a/app/views/accounts/_form.html.erb
+++ b/app/views/accounts/_form.html.erb
@@ -1,12 +1,15 @@
-<%# locals: (account:, url:, logo: true) %>
+<%# locals: (account:, url:, logo: true, turbo: account.persisted?) %>
<%# `logo: false` hides the icon block for forms whose controller does not
- save it (properties). %>
+ save it (properties). With `turbo`, the form submits through Turbo inside
+ the modal: an edit saved from an account's page returns to that page as a
+ morphing refresh (its scroll position kept), and errors re-render in the
+ modal. New accounts and the property wizard post the page as before. %>
<% if @error_message.present? %>
<%= render DS::Alert.new(message: @error_message, variant: :error) %>
<% end %>
-<%= styled_form_with model: account, url: url, scope: :account, data: { turbo: false }, class: "flex flex-col gap-4 justify-between grow text-primary" do |form| %>
+<%= styled_form_with model: account, url: url, scope: :account, data: (turbo ? {} : { turbo: false }), class: "flex flex-col gap-4 justify-between grow text-primary" do |form| %>
<div class="grow space-y-2">
<%= form.hidden_field :accountable_type %>
<%= form.hidden_field :return_to, value: params[:return_to] %>
diff --git a/app/views/properties/_form.html.erb b/app/views/properties/_form.html.erb
index 196ebe48de..6d33d538d5 100644
--- a/app/views/properties/_form.html.erb
+++ b/app/views/properties/_form.html.erb
@@ -1,6 +1,6 @@
<%# locals: (account:, url:) %>
-<%= render "accounts/form", account: account, url: url, logo: false do |form| %>
+<%= render "accounts/form", account: account, url: url, logo: false, turbo: false do |form| %>
<%= form.select :subtype,
Property.subtype_options_for_select,
{ label: true, prompt: t("properties.form.subtype_prompt"), include_blank: t("properties.form.none") } %>
diff --git a/test/controllers/credit_cards_controller_test.rb b/test/controllers/credit_cards_controller_test.rb
index 5d2793063b..2207a1f794 100644
--- a/test/controllers/credit_cards_controller_test.rb
+++ b/test/controllers/credit_cards_controller_test.rb
@@ -162,6 +162,17 @@ class CreditCardsControllerTest < ActionDispatch::IntegrationTest
assert enable_banking_account.reload.treat_balance_as_available_credit?
end
+ test "an edit saved through Turbo still applies the provider settings" do
+ enable_banking_account = create_linked_enable_banking_account
+
+ patch credit_card_path(@account),
+ params: { account: { name: @account.name, accountable_type: "CreditCard", enable_banking: { treat_balance_as_available_credit: "1" } } },
+ headers: { "Accept" => "text/vnd.turbo-stream.html" }, as: :turbo_stream
+
+ assert_match %(action="redirect"), response.body
+ assert enable_banking_account.reload.treat_balance_as_available_credit?
+ end
+
test "clears enable banking balance interpretation flag when toggled off" do
enable_banking_account = create_linked_enable_banking_account
enable_banking_account.update!(treat_balance_as_available_credit: true)
diff --git a/test/controllers/depositories_controller_test.rb b/test/controllers/depositories_controller_test.rb
index 40f8e91009..0923c63d3d 100644
--- a/test/controllers/depositories_controller_test.rb
+++ b/test/controllers/depositories_controller_test.rb
@@ -72,6 +72,45 @@ class DepositoriesControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to account_path(created) # not the external URL
end
+ test "an edit saved through Turbo returns to the page it was opened on with a refresh" do
+ patch depository_path(@account),
+ params: { account: { name: "Renamed", accountable_type: "Depository" } },
+ headers: { "Accept" => "text/vnd.turbo-stream.html", "Referer" => account_url(@account, tab: "activity") },
+ as: :turbo_stream
+
+ assert_response :success
+ assert_equal "Renamed", @account.reload.name
+ assert_match %(<turbo-stream action="redirect" target="#{account_url(@account, tab: "activity")}">), response.body
+ assert_equal I18n.t("accounts.update.success", type: "Depository"), flash[:notice]
+ end
+
+ test "an edit saved through Turbo ignores a referer from another host" do
+ patch depository_path(@account),
+ params: { account: { name: "Renamed", accountable_type: "Depository" } },
+ headers: { "Accept" => "text/vnd.turbo-stream.html", "Referer" => "https://evil.example/phish" },
+ as: :turbo_stream
+
+ assert_match %(target="#{account_path(@account)}"), response.body
+ end
+
+ test "an edit that fails through Turbo re-renders the form" do
+ patch depository_path(@account),
+ params: { account: { name: "", accountable_type: "Depository" } },
+ headers: { "Accept" => "text/vnd.turbo-stream.html, text/html" }
+
+ assert_response :unprocessable_entity
+ assert_select "form[action='#{depository_path(@account)}']:not([data-turbo='false'])"
+ assert_not_equal "", @account.reload.name
+ end
+
+ test "the edit form submits through Turbo; the new-account form posts the page" do
+ get edit_depository_path(@account)
+ assert_select "form[action='#{depository_path(@account)}']:not([data-turbo='false'])"
+
+ get new_depository_path
+ assert_select "form[data-turbo='false']"
+ end
+
test "update persists enable_category_matcher through the shared update action" do
linked_account = accounts(:connected)
assert linked_account.enable_category_matcher?
diff --git a/test/system/account_edit_scroll_test.rb b/test/system/account_edit_scroll_test.rb
new file mode 100644
index 0000000000..68b91c5e06
--- /dev/null
+++ b/test/system/account_edit_scroll_test.rb
@@ -0,0 +1,49 @@
+require "application_system_test_case"
+
+# Editing an account from its page used to post the whole page and reload it,
+# landing back at the top. Through Turbo, the save returns to the same page as
+# a morphing refresh that keeps where the page was scrolled to.
+class AccountEditScrollTest < ApplicationSystemTestCase
+ include EntriesTestHelper
+
+ setup do
+ @account = accounts(:depository)
+ 30.times { |i| create_transaction(account: @account, name: "Entry #{i}", date: (i + 1).days.ago.to_date, amount: 10 + i) }
+ sign_in users(:family_admin)
+ end
+
+ test "renaming an account from its page keeps the page where it was scrolled to" do
+ page.driver.browser.manage.window.resize_to(1400, 900)
+ visit account_path(@account)
+ page.execute_script(%(window.notReloaded = true; document.getElementById("main").scrollTop = 600))
+ assert_equal 600, main_scroll
+
+ find("a[href='#{edit_account_path(@account)}']", visible: :all).execute_script("this.click()")
+ within("dialog[open]") do
+ find("input[name='account[name]']").set("Renamed account")
+ click_on I18n.t("helpers.submit.update", model: "Account")
+ end
+
+ assert_selector "h2", text: "Renamed account"
+ assert page.evaluate_script("window.notReloaded === true"), "the page was reloaded instead of refreshed"
+ assert_in_delta 600, main_scroll, 5
+ end
+
+ test "an edit that fails shows its error in the modal" do
+ visit account_path(@account)
+ find("a[href='#{edit_account_path(@account)}']", visible: :all).execute_script("this.click()")
+ within("dialog[open]") do
+ find("input[name='account[name]']").set("")
+ page.execute_script(%(document.querySelector("dialog[open] input[name='account[name]']").removeAttribute("required")))
+ click_on I18n.t("helpers.submit.update", model: "Account")
+ end
+
+ assert_selector "dialog[open] input[name='account[name]']"
+ assert_selector "dialog[open]", text: /can.t be blank/i
+ end
+
+ private
+ def main_scroll
+ page.evaluate_script(%(Math.round(document.getElementById("main").scrollTop)))
+ end
+end