Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Keep drawn sidebar sparklines and account logos across Turbo visits (#4827)

Yong Cong Sin8c52feda738f
diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb
index 4adf614e9f..ed77623187 100644
--- a/app/helpers/accounts_helper.rb
+++ b/app/helpers/accounts_helper.rb
@@ -37,6 +37,33 @@ module AccountsHelper
match && match[1]
end
+ # The id of the permanent wrapper around a sidebar sparkline frame. On a
+ # Turbo visit, an element marked data-turbo-permanent is carried over to the
+ # new page when that page has one with the same id, so the chart already
+ # drawn stays instead of being fetched and drawn again. The id names the copy
+ # of the sidebar it sits in (each tab panel, and the mobile one), since ids
+ # must be unique, and the series version, so a chart whose data changed is
+ # replaced by a fresh frame.
+ def sidebar_sparkline_wrapper_id(copy, subject, version)
+ "sparkline_keep_#{copy}_#{subject}_#{Digest::MD5.hexdigest(version.to_s)[0, 12]}"
+ end
+
+ # The id of the permanent wrapper around a sidebar account logo, for the
+ # same reason as the sparklines': a new <img> shows the initials beneath it
+ # until the image loads, so every visit flashed them. It changes with what
+ # the logo shows (the image, and the name and colour of the initials), not
+ # with its URL, which changes at the daily rollover where stored URLs
+ # expire (Account#logo_identity).
+ def sidebar_logo_wrapper_id(copy, account, color)
+ "logo_keep_#{copy}_#{account.id}_#{Digest::MD5.hexdigest([ account.logo_identity, account.name, color ].join("|"))[0, 12]}"
+ end
+
+ # See kept_element_controller.js: a morph refresh never removes a permanent
+ # element, so one the refreshed page no longer has removes itself.
+ def kept_element_data
+ { turbo_permanent: true, controller: "kept-element", action: "turbo:before-render@document->kept-element#dropIfGone" }
+ end
+
# Cache key for `accounts/_account_sidebar_tabs.html.erb`.
# Kept here (not in the ERB) so the partial stays render-only.
#
@@ -70,7 +97,7 @@ module AccountsHelper
.pick(Arel.sql("count(*)"), Arel.sql("max(account_providers.updated_at)"))
[
- family.build_cache_key("account_sidebar_tabs_v8", invalidate_on_data_updates: true),
+ family.build_cache_key("account_sidebar_tabs_v9", invalidate_on_data_updates: true),
Current.user&.id,
shares_version,
providers_version,
diff --git a/app/javascript/controllers/kept_element_controller.js b/app/javascript/controllers/kept_element_controller.js
new file mode 100644
index 0000000000..588d402478
--- /dev/null
+++ b/app/javascript/controllers/kept_element_controller.js
@@ -0,0 +1,28 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Connects to data-controller="kept-element", on a permanent sidebar element
+// (a sparkline frame's wrapper, an account logo's).
+//
+// On a visit, Turbo carries a permanent element into the new page only when
+// that page has one with the same id, and drops it otherwise. A morph refresh
+// (what the sync toast triggers) never removes a permanent element, so one
+// whose id the refreshed page no longer has — its content changed — would
+// stay beside the new one, stacking a copy per refresh. The element removes
+// itself before such a morph.
+//
+// One that has dropped its permanence (a sparkline that timed out, a logo
+// that failed) removes itself too, even when the refreshed page has the same
+// id: the morph would make it permanent again and keep what it shows, such as
+// a frame back on its placeholder that never loads again, where the refreshed
+// page's own copy fetches afresh.
+export default class extends Controller {
+ dropIfGone(event) {
+ const { renderMethod, newBody } = event.detail;
+ if (renderMethod !== "morph" || !newBody) return;
+
+ const failed = !this.element.hasAttribute("data-turbo-permanent");
+ if (failed || !newBody.querySelector(`#${CSS.escape(this.element.id)}`)) {
+ this.element.remove();
+ }
+ }
+}
diff --git a/app/javascript/controllers/turbo_frame_timeout_controller.js b/app/javascript/controllers/turbo_frame_timeout_controller.js
index ba2587c234..3df3995417 100644
--- a/app/javascript/controllers/turbo_frame_timeout_controller.js
+++ b/app/javascript/controllers/turbo_frame_timeout_controller.js
@@ -47,6 +47,10 @@ export default class extends Controller {
}
handleTimeout() {
+ // A sidebar sparkline sits in a wrapper Turbo carries across visits; the
+ // badge must not be carried with it, so the next page fetches it again.
+ this.element.closest("[data-turbo-permanent]")?.removeAttribute("data-turbo-permanent")
+
// Replace loading content with error state
this.element.innerHTML = `
<div class="flex items-center justify-end gap-1">
diff --git a/app/models/account/logoable.rb b/app/models/account/logoable.rb
index b6e73e40b1..9cd08abd9b 100644
--- a/app/models/account/logoable.rb
+++ b/app/models/account/logoable.rb
@@ -37,14 +37,46 @@ module Account::Logoable
end
end
+ # Names what #logo_url shows with a value that stays the same from one
+ # render to the next. A stored logo's URL carries an expiry when
+ # config.active_storage.urls_expire_in is set (as in production); that
+ # expiry is rounded to the end of the day, so the URL stays the same through
+ # the day and changes at the daily rollover, while its blob doesn't. The same image uploaded
+ # again is a new blob, and the old one is purged, so the blob's id names it
+ # rather than its checksum.
+ #
+ # Where stored URLs expire, the day is part of it too: a logo kept across
+ # visits keeps the URL it was rendered with, so one that hasn't loaded yet
+ # (in a closed group) must not be kept past its URL's expiry.
+ def logo_identity
+ if logo_brandfetch? && brandfetch_logo_url
+ brandfetch_logo_url
+ elsif logo.attached? && logo.blob.persisted?
+ [ "blob:#{logo.blob.id}", (Time.current.to_date if ActiveStorage.urls_expire_in) ].compact.join(":")
+ else
+ fallback_logo_url
+ end
+ end
+
# What shows without a stored logo, and so what removing it brings back.
def fallback_logo_url
brandfetch_logo_url || provider&.logo_url.presence
end
# A rejected upload re-rendered in the form is attached but unsaved and has no URL yet.
+ #
+ # With config.active_storage.urls_expire_in set, a blob URL carries its
+ # expiry, to the millisecond by default, so each render made a new URL and
+ # the browser fetched the logo again on every page, showing the initials
+ # until it arrived. The expiry is rounded to the end of that day instead:
+ # the URL stays the same all day, so the browser's cache serves it, and it
+ # still expires no sooner than configured (at most a day later). It changes
+ # on the same day boundary as #logo_identity.
def stored_logo_url
- Rails.application.routes.url_helpers.rails_blob_path(logo, only_path: true) if logo.attached? && logo.blob.persisted?
+ return unless logo.attached? && logo.blob.persisted?
+
+ expiry = ActiveStorage.urls_expire_in && { expires_in: nil, expires_at: (Time.current + ActiveStorage.urls_expire_in).end_of_day }
+ Rails.application.routes.url_helpers.rails_blob_path(logo, only_path: true, **expiry.to_h)
end
def brandfetch_logo_url
diff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erb
index a811b33c6b..ab74b50704 100644
--- a/app/views/accounts/_account_sidebar_tabs.html.erb
+++ b/app/views/accounts/_account_sidebar_tabs.html.erb
@@ -4,7 +4,7 @@
ERB dependency tracker mis-parses as a bogus "Ds/D" template dependency
and then logs "Couldn't find template for digesting: Ds/D" on every cache
miss. The cache key is already manually versioned via
- account_sidebar_tabs_cache_key ("account_sidebar_tabs_v8",
+ account_sidebar_tabs_cache_key ("account_sidebar_tabs_v9",
invalidate_on_data_updates: true), so we opt out of automatic template
digesting. Bump that version suffix when changing this template or its
sidebar dependencies. %>
diff --git a/app/views/accounts/_accountable_group.html.erb b/app/views/accounts/_accountable_group.html.erb
index 28668cf01a..f1712a97f7 100644
--- a/app/views/accounts/_accountable_group.html.erb
+++ b/app/views/accounts/_accountable_group.html.erb
@@ -1,6 +1,7 @@
<%# locals: (account_group:, mobile: false, all_tab: false, open: nil, sortable: false, **args) %>
-<div id="<%= account_group.dom_id(tab: all_tab ? :all : nil, mobile: mobile) %>" data-group-key="<%= account_group.key %>">
+<% copy = account_group.dom_id(tab: all_tab ? :all : nil, mobile: mobile) %>
+<div id="<%= copy %>" data-group-key="<%= account_group.key %>">
<% is_open = open.nil? ? (account_group.accounts.any? { |account| page_active?(account_path(account)) } || Current.user.always_expanded_account_group?(account_group.key)) : open %>
<%= render DS::Disclosure.new(align: :left, open: is_open) do |disclosure| %>
<% disclosure.with_summary_content do %>
@@ -13,13 +14,16 @@
<div class="ml-auto text-right grow">
<%= tag.p format_money(account_group.total_money), class: "text-sm font-medium text-primary privacy-sensitive" %>
- <%= turbo_frame_tag "#{account_group.key}_sparkline",
- src: accountable_sparkline_path(account_group.key, v: sidebar_sparkline_versions(Current.family)[account_group.accountable_type]),
- loading: "lazy",
- data: sparkline_frame_data do %>
- <div class="flex items-center w-8 h-4 ml-auto">
- <div class="w-6 h-px bg-loader"></div>
- </div>
+ <% group_version = sidebar_sparkline_versions(Current.family)[account_group.accountable_type] %>
+ <%= tag.div id: sidebar_sparkline_wrapper_id(copy, "total", group_version), data: kept_element_data do %>
+ <%= turbo_frame_tag "#{account_group.key}_sparkline",
+ src: accountable_sparkline_path(account_group.key, v: group_version),
+ loading: "lazy",
+ data: sparkline_frame_data do %>
+ <div class="flex items-center w-8 h-4 ml-auto">
+ <div class="w-6 h-px bg-loader"></div>
+ </div>
+ <% end %>
<% end %>
</div>
<% end %>
@@ -65,7 +69,9 @@
),
data: page_active?(account_path(account)) ? { active_account: true } : {},
title: account.name do %>
- <%= render "accounts/logo", account: account, size: "sm", color: account_group.color %>
+ <%= tag.span id: sidebar_logo_wrapper_id(copy, account, account_group.color), class: "shrink-0", data: kept_element_data do %>
+ <%= render "accounts/logo", account: account, size: "sm", color: account_group.color %>
+ <% end %>
<div class="min-w-0 grow">
<div class="flex items-center gap-2 mb-0.5">
@@ -79,13 +85,16 @@
<div class="ml-auto text-right grow h-10">
<%= tag.p format_money(account.balance_money), class: "text-sm font-medium text-primary whitespace-nowrap privacy-sensitive" %>
- <%= turbo_frame_tag dom_id(account, :sparkline),
- src: sparkline_account_path(account, v: sidebar_sparkline_versions(Current.family)[account.id]),
- loading: "lazy",
- data: sparkline_frame_data do %>
- <div class="flex items-center w-8 h-4 ml-auto">
- <div class="w-6 h-px bg-loader"></div>
- </div>
+ <% account_version = sidebar_sparkline_versions(Current.family)[account.id] %>
+ <%= tag.div id: sidebar_sparkline_wrapper_id(copy, account.id, account_version), data: kept_element_data do %>
+ <%= turbo_frame_tag dom_id(account, :sparkline),
+ src: sparkline_account_path(account, v: account_version),
+ loading: "lazy",
+ data: sparkline_frame_data do %>
+ <div class="flex items-center w-8 h-4 ml-auto">
+ <div class="w-6 h-px bg-loader"></div>
+ </div>
+ <% end %>
<% end %>
</div>
<% end %>
diff --git a/app/views/accounts/_logo.html.erb b/app/views/accounts/_logo.html.erb
index 86ab70fae6..4fed309861 100644
--- a/app/views/accounts/_logo.html.erb
+++ b/app/views/accounts/_logo.html.erb
@@ -15,6 +15,16 @@
rounded: true
} %>
+<%# A sidebar logo sits in a wrapper Turbo carries across visits; a failed
+ image must not be carried as its initials, so it drops the permanence
+ and the next page tries the image again. %>
+<%# Before that, a same-origin image retries once at a fresh URL: iOS Safari
+ can fail an image it only revalidated (its cached redirect, then 304 Not
+ Modified, with the cached copy already dropped), and a new URL makes it
+ fetch the image again rather than give up on a logo that is there.
+ window.URL: in an inline handler a bare URL is document.URL, a string. %>
+<% retry_once = "if (!this.dataset.retried && new window.URL(this.src).origin === location.origin) { this.dataset.retried = '1'; const url = new window.URL(this.src); url.searchParams.set('retry', Date.now()); this.src = url; return; }" %>
+<% on_error = "#{retry_once} this.closest('[data-turbo-permanent]')?.removeAttribute('data-turbo-permanent'); #{ProviderLogo::REMOVE_ON_ERROR}" %>
<div class="relative shrink-0">
<% if url.present? %>
<%# The ProviderLogo recipe: the initials sit under the image, and a logo the
@@ -26,7 +36,7 @@
class: "absolute inset-0 w-full h-full rounded-full object-contain bg-container",
alt: "",
loading: "lazy",
- onerror: ProviderLogo::REMOVE_ON_ERROR %>
+ onerror: on_error %>
<% end %>
<% else %>
<%= render DS::FilledIcon.new(**initials) %>
diff --git a/config/initializers/active_storage_disk_caching.rb b/config/initializers/active_storage_disk_caching.rb
new file mode 100644
index 0000000000..d0dc025bca
--- /dev/null
+++ b/config/initializers/active_storage_disk_caching.rb
@@ -0,0 +1,41 @@
+# A disk service URL is only valid for ActiveStorage.service_urls_expire_in and
+# always names the same file, so the browser can keep what it serves for that
+# long without asking again. Without a freshness lifetime, browsers revalidate
+# each use: iOS Safari does so when it restores a page from its back/forward
+# cache (`pageshow`), and when it has already dropped the image it fails the
+# 304 Not Modified it gets back, so stored logos vanish (their initials show).
+#
+# Only account logos are kept this way. A cached response is served without
+# reaching the server, so the authorization in active_storage_authorization.rb
+# would not run again for it; files whose access is checked (statements,
+# attachments, exports) keep Rails' revalidate-every-time policy.
+Rails.application.config.to_prepare do
+ module ActiveStorageDiskCaching
+ extend ActiveSupport::Concern
+
+ CACHEABLE_ATTACHMENTS = [ %w[Account logo] ].freeze
+
+ included do
+ after_action :cache_served_file, only: :show
+ end
+
+ private
+ def cache_served_file
+ return unless response.status.in?([ 200, 206, 304 ])
+ return unless cacheable_file?
+
+ expires_in ActiveStorage.service_urls_expire_in, public: false, immutable: true
+ end
+
+ # Every attachment of the blob (or of the blob a variant derives from) is
+ # one the browser may keep: a file shared with anything else is not.
+ def cacheable_file?
+ attachments = respond_to?(:authorized_attachments, true) ? authorized_attachments : nil
+ attachments.present? && attachments.all? { |attachment| CACHEABLE_ATTACHMENTS.include?([ attachment.record_type, attachment.name ]) }
+ end
+ end
+
+ if defined?(ActiveStorage::DiskController) && !ActiveStorage::DiskController.include?(ActiveStorageDiskCaching)
+ ActiveStorage::DiskController.include ActiveStorageDiskCaching
+ end
+end
diff --git a/test/helpers/accounts_helper_test.rb b/test/helpers/accounts_helper_test.rb
index c00e4f5007..237e0713d5 100644
--- a/test/helpers/accounts_helper_test.rb
+++ b/test/helpers/accounts_helper_test.rb
@@ -11,6 +11,54 @@ class AccountsHelperTest < ActionView::TestCase
teardown { Current.session = nil }
+ test "a sidebar logo's wrapper id stays the same through the day, as its stored logo's URL does" do
+ account = accounts(:depository)
+ account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png", content_type: "image/png")
+ ActiveStorage.stubs(:urls_expire_in).returns(7.days)
+
+ first_url = first_id = nil
+ travel_to Time.zone.local(2026, 11, 10, 9) do
+ first_url, first_id = account.logo_url, sidebar_logo_wrapper_id("asset_depository", account, "#000")
+
+ travel 8.hours
+ assert_equal first_url, Account.find(account.id).logo_url
+ assert_equal first_id, sidebar_logo_wrapper_id("asset_depository", Account.find(account.id), "#000")
+ end
+
+ account.logo.attach(io: file_fixture("profile_image.png").open, filename: "other.png", content_type: "image/png")
+ assert_not_equal first_id, sidebar_logo_wrapper_id("asset_depository", account.reload, "#000"), "another image is another logo"
+ end
+
+ # A kept logo keeps the URL it was rendered with. One that hasn't loaded yet
+ # (in a closed group) must not be kept past that URL's expiry.
+ test "a sidebar logo's wrapper id changes from one day to the next where stored logo URLs expire" do
+ account = accounts(:depository)
+ account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png", content_type: "image/png")
+ ActiveStorage.stubs(:urls_expire_in).returns(7.days)
+
+ travel_to Time.zone.local(2026, 11, 10, 9) do
+ morning = sidebar_logo_wrapper_id("asset_depository", Account.find(account.id), "#000")
+
+ travel 8.hours
+ assert_equal morning, sidebar_logo_wrapper_id("asset_depository", Account.find(account.id), "#000")
+
+ travel 1.day
+ assert_not_equal morning, sidebar_logo_wrapper_id("asset_depository", Account.find(account.id), "#000")
+ end
+ end
+
+ # The same image uploaded again is a new blob, and the old one is purged: a
+ # kept wrapper would point at the purged blob.
+ test "a sidebar logo's wrapper id changes when the same image is uploaded again" do
+ account = accounts(:depository)
+ account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png", content_type: "image/png")
+ first_id = sidebar_logo_wrapper_id("asset_depository", account.reload, "#000")
+
+ account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png", content_type: "image/png")
+
+ assert_not_equal first_id, sidebar_logo_wrapper_id("asset_depository", account.reload, "#000")
+ end
+
test "sidebar cache key changes with the Brandfetch client id" do
Setting.stubs(:brand_fetch_client_id).returns(nil)
without_key = account_sidebar_tabs_cache_key(family: @family, active_tab: "all", mobile: false)
diff --git a/test/integration/active_storage_authorization_test.rb b/test/integration/active_storage_authorization_test.rb
index b316596d06..8b3dd36d75 100644
--- a/test/integration/active_storage_authorization_test.rb
+++ b/test/integration/active_storage_authorization_test.rb
@@ -52,6 +52,34 @@ class ActiveStorageAuthorizationTest < ActionDispatch::IntegrationTest
assert_redirected_to new_session_url
end
+ test "a disk service url lets the browser keep an account logo for as long as the url is valid" do
+ sign_in @user_a
+ account = @user_a.family.accounts.first
+ account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png", content_type: "image/png")
+
+ get rails_blob_path(account.logo)
+ get response.location
+
+ assert_response :success
+ cache_control = response.headers["Cache-Control"]
+ assert_includes cache_control, "max-age=#{ActiveStorage.service_urls_expire_in.to_i}"
+ assert_includes cache_control, "private"
+ assert_includes cache_control, "immutable"
+ end
+
+ # A cached response would be served without the authorization checks.
+ test "a disk service url for a protected file still has the browser ask every time" do
+ sign_in @user_a
+
+ get rails_blob_path(@statement_a.original_file)
+ get response.location
+
+ assert_response :success
+ cache_control = response.headers["Cache-Control"]
+ assert_not_includes cache_control, "immutable"
+ assert_includes cache_control, "must-revalidate"
+ end
+
test "disk service urls enforce statement blob authorization" do
sign_in @user_a
diff --git a/test/models/account/logoable_test.rb b/test/models/account/logoable_test.rb
new file mode 100644
index 0000000000..a4c119743a
--- /dev/null
+++ b/test/models/account/logoable_test.rb
@@ -0,0 +1,41 @@
+require "test_helper"
+
+class Account::LogoableTest < ActiveSupport::TestCase
+ setup do
+ @account = accounts(:depository)
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png", content_type: "image/png")
+ ActiveStorage.stubs(:urls_expire_in).returns(7.days)
+ end
+
+ test "a stored logo's URL stays the same through the day, so the browser can cache it" do
+ travel_to Time.zone.local(2026, 11, 10, 9) do
+ morning = Account.find(@account.id).stored_logo_url
+
+ travel 8.hours
+ assert_equal morning, Account.find(@account.id).stored_logo_url
+
+ travel 1.day
+ assert_not_equal morning, Account.find(@account.id).stored_logo_url, "a new day gives a new expiry"
+ end
+ end
+
+ test "a new logo gets a new URL the same day, so the browser doesn't keep showing the old one" do
+ before = Account.find(@account.id).stored_logo_url
+
+ @account.logo.attach(io: file_fixture("profile_image.png").open, filename: "logo.png", content_type: "image/png")
+
+ assert_not_equal before, Account.find(@account.id).stored_logo_url
+ end
+
+ test "a stored logo's URL still finds its logo and expires no sooner than configured" do
+ travel_to Time.zone.local(2026, 11, 10, 9) do
+ signed_id = Account.find(@account.id).stored_logo_url.split("/")[-2]
+
+ travel 7.days - 1.minute
+ assert_equal @account.logo.blob, ActiveStorage::Blob.find_signed(signed_id)
+
+ travel 2.days
+ assert_nil ActiveStorage::Blob.find_signed(signed_id), "it expires a day later at most"
+ end
+ end
+end
diff --git a/test/system/sidebar_sparklines_test.rb b/test/system/sidebar_sparklines_test.rb
index 8963b99477..7274207d93 100644
--- a/test/system/sidebar_sparklines_test.rb
+++ b/test/system/sidebar_sparklines_test.rb
@@ -209,6 +209,200 @@ class SidebarSparklinesTest < ApplicationSystemTestCase
end
end
+ # A Turbo visit replaces the page body, sidebar included. The sparklines sit
+ # in permanent wrappers so the next page takes over the charts already drawn
+ # rather than starting every frame from its placeholder and fetching it again.
+ test "a visit keeps the sparklines already drawn instead of fetching them again" do
+ visit root_path
+ expand_first_group
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME}[complete] svg path", minimum: 1
+ kept = mark_drawn_sparklines
+ record_sparkline_requests
+
+ visit_first_open_account
+
+ assert_equal kept, page.evaluate_script("document.querySelectorAll(#{"#{SPARKLINE_FRAME}[data-kept]".to_json}).length"), "the drawn sparklines were replaced"
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME}[data-kept][complete] svg path", minimum: 1
+ assert_empty page.evaluate_script("window.sparklineRequests").select { |id| id.start_with?("sparkline_account_") }
+ end
+
+ test "a visit keeps the account logos instead of drawing them again" do
+ visit root_path
+ expand_first_group
+ kept = page.evaluate_script(<<~JS)
+ (() => {
+ const logos = document.querySelectorAll("#sidebar-scroll details[open] [id^='logo_keep_']")
+ logos.forEach((logo) => { logo.dataset.kept = "1" })
+ return logos.length
+ })()
+ JS
+ assert_operator kept, :>, 0
+
+ visit_first_open_account
+
+ assert_equal kept, page.evaluate_script("document.querySelectorAll(\"[id^='logo_keep_'][data-kept]\").length"), "the logos were drawn again"
+ end
+
+ test "a logo that failed to load is not carried to the next page" do
+ account = accounts(:depository)
+ account.logo.attach(io: StringIO.new("not an image"), filename: "broken.png", content_type: "image/png")
+
+ visit root_path
+ expand_first_group
+
+ wrapper = "[id^='logo_keep_'][id*='#{account.id}']"
+ assert_selector wrapper, minimum: 1
+ assert_no_selector "#{wrapper} img", wait: 10
+ assert page.evaluate_script(%(Array.from(document.querySelectorAll(#{wrapper.to_json})).filter((el) => el.offsetParent).every((el) => !el.hasAttribute("data-turbo-permanent")))),
+ "a wrapper whose logo failed is still permanent"
+ end
+
+ # iOS Safari can fail a stored logo it only revalidated (a 304 for an image
+ # whose data it already dropped). One failure must not cost the logo: the
+ # image is fetched again once, at a fresh URL, before the initials show.
+ test "a logo that fails once is fetched again at a fresh URL and shown" do
+ account = accounts(:depository)
+ account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png", content_type: "image/png")
+
+ visit root_path
+ expand_first_group
+
+ image = "[id^='logo_keep_'][id*='#{account.id}'] img"
+ assert_selector image, minimum: 1
+ page.execute_script(<<~JS)
+ const img = Array.from(document.querySelectorAll(#{image.to_json})).find((el) => el.offsetParent);
+ img.dataset.probe = "1";
+ img.dispatchEvent(new Event("error"));
+ JS
+
+ assert_selector "img[data-probe][src*='retry=']", visible: :all, wait: 5
+ page.document.synchronize(5) do
+ loaded = page.evaluate_script(%((() => { const img = document.querySelector("img[data-probe]"); return !!img && img.complete && img.naturalWidth > 0 })()))
+ raise Capybara::ExpectationNotMet, "the retried logo did not load" unless loaded
+ end
+ assert page.evaluate_script(%(document.querySelector("img[data-probe]").closest("[id^='logo_keep_']").hasAttribute("data-turbo-permanent"))),
+ "a logo that recovered stopped being kept"
+ end
+
+ test "a visit fetches a sparkline again once its series has changed" do
+ visit root_path
+ expand_first_group
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME}[complete] svg path", minimum: 1
+ mark_drawn_sparklines
+
+ FreshSparklineVersions.salt = SecureRandom.hex(4)
+ visit_first_open_account
+
+ assert_no_selector "#{SPARKLINE_FRAME}[data-kept]", visible: :all
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME}[complete] svg path", minimum: 1
+ end
+
+ # A finished sync refreshes the page with a morph rather than a visit. Turbo
+ # never removes a permanent element during a morph, so a wrapper whose id
+ # the refreshed page no longer has would stay beside the new one.
+ test "a refresh after the series changed replaces each sparkline instead of adding one" do
+ visit root_path
+ expand_first_group
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME}[complete] svg path", minimum: 1
+ wrappers = sparkline_wrapper_count
+
+ 2.times do
+ FreshSparklineVersions.salt = SecureRandom.hex(4)
+ morph_refresh
+ # The group totals sit in the summaries, on screen whatever the morph
+ # does to the groups' open state.
+ assert_selector "#{GROUP_SPARKLINE_FRAME}[complete] svg path", minimum: 1
+ assert_equal wrappers, sparkline_wrapper_count, "a refresh left the old sparklines beside the new ones"
+ end
+ end
+
+ test "a refresh with unchanged series keeps the sparklines drawn" do
+ visit root_path
+ expand_first_group
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME}[complete] svg path", minimum: 1
+ kept = mark_drawn_sparklines
+
+ morph_refresh
+
+ assert_equal kept, page.evaluate_script("document.querySelectorAll(#{"#{SPARKLINE_FRAME}[data-kept]".to_json}).length")
+ end
+
+ test "a sparkline that timed out is not carried to the next page" do
+ with_short_sparkline_timeout do
+ visit root_path
+
+ with_stalled_sparkline_responses do
+ expand_first_group
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME} p", text: BADGE_TEXT, minimum: 1
+
+ # While the responses are still held: once released they render over
+ # the badges, and no badge left would make this pass on nothing.
+ timed_out = page.evaluate_script(<<~JS)
+ (() => {
+ const frames = Array.from(document.querySelectorAll("#{ACCOUNT_SPARKLINE_FRAME}"))
+ .filter((frame) => frame.textContent.includes("#{BADGE_TEXT}"))
+ return { count: frames.length, permanent: frames.filter((frame) => frame.closest("[data-turbo-permanent]")).length }
+ })()
+ JS
+ assert_operator timed_out["count"], :>, 0
+ assert_equal 0, timed_out["permanent"], "a wrapper around a timed-out sparkline is still permanent"
+ end
+ end
+ end
+
+ # A request that failed outright never answers, so nothing renders over the
+ # badge. The refresh a finished sync triggers would otherwise make its
+ # wrapper permanent again and put the frame back on its placeholder for good.
+ test "a refresh with unchanged series fetches a sparkline that timed out again" do
+ with_short_sparkline_timeout do
+ visit root_path
+
+ with_broken_sparkline_responses(:server_error) do
+ expand_first_group
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME} p", text: BADGE_TEXT, minimum: 1, wait: SETTLE_WAIT_SECONDS
+ wait_for_fetched_frames
+ end
+ timed_out = page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll("#{ACCOUNT_SPARKLINE_FRAME}"))
+ .filter((frame) => frame.offsetParent && frame.textContent.includes("#{BADGE_TEXT}")).map((frame) => frame.id)
+ JS
+ assert_not_empty timed_out
+
+ morph_refresh
+ expand_first_group unless page.evaluate_script(%(document.querySelector("#sidebar-scroll details").open))
+
+ page.document.synchronize(SETTLE_WAIT_SECONDS) do
+ stuck = page.evaluate_script(<<~JS)
+ #{timed_out.to_json}.filter((id) => !Array.from(document.querySelectorAll(`[id="${id}"]`)).some((frame) => frame.offsetParent && frame.querySelector("svg path") && !frame.textContent.includes("#{BADGE_TEXT}")))
+ JS
+ raise Capybara::ExpectationNotMet, "sparklines that timed out stayed undrawn after the refresh: #{stuck.inspect}" if stuck.any?
+ end
+ end
+ end
+
+ # In this sidebar the morph above replaces the timed-out frames, so that case
+ # passes either way; a frame the morph kept instead would stay on its
+ # placeholder, so the wrapper doesn't rely on being replaced.
+ test "a wrapper that dropped its permanence removes itself before a morph, even when the refreshed page has its id" do
+ visit root_path
+ expand_first_group
+ assert_selector "#{ACCOUNT_SPARKLINE_FRAME}[complete] svg path", minimum: 1
+
+ result = page.evaluate_script(<<~JS)
+ (() => {
+ const wrappers = Array.from(document.querySelectorAll("[id^='sparkline_keep_']")).filter((el) => el.offsetParent)
+ const [failed, kept] = wrappers
+ failed.removeAttribute("data-turbo-permanent")
+ const newBody = document.body.cloneNode(true)
+ document.dispatchEvent(new CustomEvent("turbo:before-render", { detail: { renderMethod: "morph", newBody } }))
+ return { failed: failed.isConnected, kept: kept.isConnected }
+ })()
+ JS
+
+ assert_not result["failed"], "a wrapper that lost its permanence stayed for the morph"
+ assert result["kept"], "a wrapper still permanent and still on the refreshed page was removed"
+ end
+
# Only a response that renders the frame ends the wait; one without it is as
# much a failed sparkline as a request that never returns. Each response has
# to arrive inside the window, otherwise the badge would be there before it
@@ -274,6 +468,44 @@ class SidebarSparklinesTest < ApplicationSystemTestCase
assert response_times.all? { |time| time < ms }, "Sparkline responses took #{response_times.map(&:round)} ms"
end
+ # Tags every drawn sparkline frame, so a frame on the next page can be told
+ # apart as the same element (carried over) or a new one.
+ def mark_drawn_sparklines
+ page.evaluate_script(<<~JS)
+ (() => {
+ const frames = document.querySelectorAll("#{SPARKLINE_FRAME}[complete]")
+ frames.forEach((frame) => { frame.dataset.kept = "1" })
+ return frames.length
+ })()
+ JS
+ end
+
+ def record_sparkline_requests
+ page.execute_script(<<~JS)
+ window.sparklineRequests = []
+ document.addEventListener("turbo:before-fetch-request", (event) => {
+ if (event.target.id.includes("sparkline")) window.sparklineRequests.push(event.target.id)
+ })
+ JS
+ end
+
+ def sparkline_wrapper_count
+ page.evaluate_script("document.querySelectorAll('[id^=sparkline_keep_]').length")
+ end
+
+ # What the sync toast does once a sync has finished: refresh the page in
+ # place, which the layout's turbo_refreshes_with turns into a morph.
+ def morph_refresh
+ page.execute_script(%(window.__morphed = false; document.addEventListener("turbo:morph", () => { window.__morphed = true }, { once: true }); Turbo.visit(location.href, { action: "replace" })))
+ Timeout.timeout(15) { sleep 0.05 until page.evaluate_script("window.__morphed") }
+ end
+
+ # A Turbo visit, unlike `visit`, which loads the page afresh.
+ def visit_first_open_account
+ find("#sidebar-scroll details[open] a[href^='/accounts/']", match: :first).click
+ assert_selector "#sidebar-scroll a[data-active-account]"
+ end
+
def expand_first_group
find("#sidebar-scroll details", match: :first).find("summary").click
end
diff --git a/test/views/accounts/logo_view_test.rb b/test/views/accounts/logo_view_test.rb
index 562845d323..02647f4dcb 100644
--- a/test/views/accounts/logo_view_test.rb
+++ b/test/views/accounts/logo_view_test.rb
@@ -10,7 +10,11 @@ class AccountsLogoViewTest < ActionView::TestCase
assert_select "span.relative" do
assert_select "div", text: @account.name.first
- assert_select "img[src='https://example.com/logo.png'][onerror=?]", ProviderLogo::REMOVE_ON_ERROR
+ assert_select "img[src='https://example.com/logo.png']" do |images|
+ on_error = images.first["onerror"]
+ assert on_error.end_with?(ProviderLogo::REMOVE_ON_ERROR), "the image removes itself"
+ assert_includes on_error, "removeAttribute('data-turbo-permanent')", "a kept sidebar wrapper stops being kept"
+ end
end
end