The personal finance app for everyone (by everyone)
Ruby
Stop the account sidebar shifting when its list scrolls or the page loads (#4823)
Yong Cong Sin330451da76af
diff --git a/app/javascript/controllers/sidebar_resize_controller.js b/app/javascript/controllers/sidebar_resize_controller.jsindex 4490ce25d2..9e340943ac 100644--- a/app/javascript/controllers/sidebar_resize_controller.js+++ b/app/javascript/controllers/sidebar_resize_controller.js@@ -11,7 +11,7 @@ import {// Drives the draggable dividers on the left (accounts) and right (assistant)// sidebars. The chosen width is stored as a CSS variable on the root layout-// element (consumed via `max-width: var(--left-sidebar-width)`) and persisted+// element and on <html> (consumed via `max-width: var(--left-sidebar-width)`) and persisted// per-device in localStorage. Width changes compose with the show/hide toggle// owned by app_layout_controller — collapsing wins via `w-0`, reopening// restores the last width.@@ -240,8 +240,14 @@ export default class extends Controller {}}+ // Also on <html>, where the head script puts the stored widths before the+ // first paint: a Turbo visit swaps in a new layout element without this+ // inline width, so until this controller connects the sidebar takes the+ // <html> one. Kept in step, a resize since the page loaded can't make the+ // new page start at the old width and slide to this one.#setWidth(side, width) {this.element.style.setProperty(`--${side}-sidebar-width`, `${width}px`);+ document.documentElement.style.setProperty(`--${side}-sidebar-width`, `${width}px`);}#currentWidth(side) {diff --git a/app/javascript/utils/sidebar_resize.js b/app/javascript/utils/sidebar_resize.jsindex 39d59a8186..2402cfc2bc 100644--- a/app/javascript/utils/sidebar_resize.js+++ b/app/javascript/utils/sidebar_resize.js@@ -2,7 +2,9 @@//// Kept free of any DOM access so the clamping logic can be unit-tested in// isolation. Must be kept in sync with-// test/javascript/utils/sidebar_resize_test.mjs.+// test/javascript/utils/sidebar_resize_test.mjs, and with the inline script in+// app/views/layouts/shared/_head.html.erb, which repeats these bounds to apply+// the stored widths before the first paint.// Width of the always-visible icon navbar to the left of the sidebars.export const SIDEBAR_NAVBAR_WIDTH = 84;diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erbindex 2a18a1b1e9..9f9820f5b5 100644--- a/app/views/layouts/application.html.erb+++ b/app/views/layouts/application.html.erb@@ -111,14 +111,16 @@ end %><%# DESKTOP - Left sidebar %><%= tag.div class: class_names(- "hidden lg:block relative py-4 shrink-0 transition-all duration-300 border-divider",+ "hidden lg:block relative py-4 shrink-0 transition-[width] duration-300 border-divider",Current.user.show_sidebar? ? [expanded_sidebar_class, "border-r"] : [collapsed_sidebar_class, "border-r-0"],),style: "max-width: var(--left-sidebar-width, 320px)",inert: !Current.user.show_sidebar?,data: { app_layout_target: "leftSidebar", sidebar_resize_target: "leftSidebar" } do %><%= render "layouts/shared/sidebar_resize_handle", side: "left" %>- <div id="sidebar-scroll" data-controller="preserve-scroll" class="px-4 h-full flex flex-col overflow-y-auto">+ <%# The scrollbar's space is kept even while the list fits, so opening or+ closing account groups doesn't narrow and widen the sidebar. %>+ <div id="sidebar-scroll" data-controller="preserve-scroll" class="px-4 h-full flex flex-col overflow-y-auto [scrollbar-gutter:stable]"><% if content_for?(:sidebar) %><%= yield :sidebar %><% else %>@@ -197,7 +199,7 @@ end %><% if assistant_enabled %><%# DESKTOP - Right sidebar %><%= tag.div class: class_names(- "hidden lg:block relative h-full shrink-0 transition-all duration-300 border-divider",+ "hidden lg:block relative h-full shrink-0 transition-[width] duration-300 border-divider",Current.user.show_ai_sidebar? ? [expanded_sidebar_class, "border-l"] : [collapsed_sidebar_class, "border-l-0"],),style: "max-width: var(--right-sidebar-width, 400px)",diff --git a/app/views/layouts/shared/_head.html.erb b/app/views/layouts/shared/_head.html.erbindex 2314f0a13b..8e906f72fd 100644--- a/app/views/layouts/shared/_head.html.erb+++ b/app/views/layouts/shared/_head.html.erb@@ -8,13 +8,62 @@<%= combobox_style_tag %>+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover">++ <%# Applies the sidebar widths the user dragged to before the first paint;+ sidebar_resize_controller only runs once the page's JavaScript has+ loaded, so the sidebars drew at their default width and then jumped.+ It computes what the controller settles on when it connects: the bounds+ of utils/sidebar_resize.js, each sidebar clamped against the other one's+ width when that one is open (the left first, then the right, repeated+ until neither moves). It sits after the viewport tag, so innerWidth is+ the device's, not a default layout width. Without storage (blocked,+ private mode) each side takes its default, as the controller does.+ A Turbo visit that leaves this script unchanged doesn't run it again,+ while the window may have been resized on a page without the sidebars+ (settings), so it also runs before each Turbo render. %>+ <script nonce="<%= content_security_policy_nonce %>">+ (function () {+ var apply = function () {+ <%# The layout renders the right sidebar only while the assistant is enabled. %>+ var open = { left: <%= Current.user&.show_sidebar? ? "true" : "false" %>, right: <%= Current.user&.show_ai_sidebar? && Current.family&.assistant_enabled? ? "true" : "false" %> };+ var defaults = { left: 320, right: 400 }, absMax = { left: 480, right: 560 };+ var room = window.innerWidth - 84 - 400;+ var requested = {};+ ["left", "right"].forEach(function (side) {+ var stored = NaN;+ try {+ stored = parseInt(localStorage.getItem("sure.sidebarWidth." + side), 10);+ } catch (e) {}+ requested[side] = isFinite(stored) ? stored : defaults[side];+ });+ var clamp = function (side, otherWidth) {+ var max = Math.max(240, Math.min(absMax[side], room - otherWidth));+ return Math.round(Math.min(Math.max(requested[side], 240), max));+ };+ var width = { left: clamp("left", 0), right: clamp("right", 0) };+ for (var i = 0; i < 3; i++) {+ width.left = clamp("left", open.right ? width.right : 0);+ width.right = clamp("right", open.left ? width.left : 0);+ }+ ["left", "right"].forEach(function (side) {+ document.documentElement.style.setProperty("--" + side + "-sidebar-width", width[side] + "px");+ });+ };+ apply();+ <%# One listener at a time: a changed script (new preferences) replaces it. %>+ if (document.addEventListener) {+ document.removeEventListener("turbo:before-render", window.sureSidebarWidthsBeforeRender);+ window.sureSidebarWidthsBeforeRender = apply;+ document.addEventListener("turbo:before-render", apply);+ }+ })();+ </script><%= javascript_importmap_tags %><%= render "layouts/dark_mode_check" %><%= render "layouts/privacy_mode_check" %><%= turbo_refreshes_with method: :morph, scroll: :preserve %>- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover">-<meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex db18b03a07..c28e98111c 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -31,6 +31,14 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_includes response.body, I18n.t("accounts.reconciliation_indicator.needs_attention")end+ # Opening the account groups makes the list scroll; reserving the scrollbar's+ # space keeps the sidebar from shifting sideways when it appears.+ test "the sidebar keeps room for its scrollbar" do+ get root_url++ assert_select "#sidebar-scroll[class*='[scrollbar-gutter:stable]']"+ end+test "show points an unmatched transaction with a counterpart to the transfer matcher" dooutflow = create_transaction(account: @account, name: "Hint outflow", amount: 500, date: Date.current)create_transaction(account: accounts(:credit_card), name: "Hint inflow", amount: -500, date: Date.current)diff --git a/test/system/sidebar_widths_test.rb b/test/system/sidebar_widths_test.rbnew file mode 100644index 0000000000..cfdaaaa8de--- /dev/null+++ b/test/system/sidebar_widths_test.rb@@ -0,0 +1,130 @@+require "application_system_test_case"++# The head script applies the stored sidebar widths before the first paint,+# and sidebar_resize_controller applies them again once it connects; wherever+# the two disagree, the sidebars visibly jump after the page appears.+class SidebarWidthsTest < ApplicationSystemTestCase+ setup do+ sign_in users(:family_admin)+ end++ test "without the assistant the left sidebar keeps the room of the right one the layout leaves out" do+ users(:family_admin).family.update!(assistant_type: "mcp_only")+ page.driver.browser.manage.window.resize_to(1280, 900)+ visit root_path+ page.execute_script(%(localStorage.setItem("sure.sidebarWidth.left", "480"); localStorage.setItem("sure.sidebarWidth.right", "560")))++ visit root_path++ assert_nil page.evaluate_script(%(document.querySelector("[data-app-layout-target='rightSidebar']"))), "the layout leaves the right sidebar out"+ assert_equal kept_widths.first, before_paint_widths.first+ assert_equal "480px", before_paint_widths.first, "the stored width fits once no room is kept for the right sidebar"+ ensure+ page.execute_script(%(localStorage.removeItem("sure.sidebarWidth.left"); localStorage.removeItem("sure.sidebarWidth.right")))+ end++ test "the widths applied before the first paint are the ones the resize controller keeps" do+ page.driver.browser.manage.window.resize_to(1280, 900)+ visit root_path+ # Wider together than the viewport allows with both sidebars open.+ page.execute_script(%(localStorage.setItem("sure.sidebarWidth.left", "480"); localStorage.setItem("sure.sidebarWidth.right", "560")))++ visit root_path++ assert page.evaluate_script(%(["leftSidebar", "rightSidebar"].every((target) => document.querySelector("[data-app-layout-target='" + target + "']").offsetWidth > 0))), "both sidebars open"+ before_paint = before_paint_widths+ kept = kept_widths++ assert_equal kept, before_paint+ assert_operator before_paint.sum(&:to_i), :<, 560 + 480, "the pair was not clamped together"+ ensure+ page.execute_script(%(localStorage.removeItem("sure.sidebarWidth.left"); localStorage.removeItem("sure.sidebarWidth.right")))+ end++ # A visit that leaves the head script unchanged doesn't run it again; a+ # window resized on a page without the sidebars (settings, where no resize+ # controller follows the window) must not bring the old window's widths back.+ test "a visit after a window resize on a page without the sidebars starts at widths that fit the window" do+ page.driver.browser.manage.window.resize_to(1600, 1000)+ visit root_path+ page.execute_script(%(localStorage.setItem("sure.sidebarWidth.left", "480"); localStorage.setItem("sure.sidebarWidth.right", "560")))+ visit settings_profile_path+ assert_no_selector "[data-controller~='sidebar-resize']", visible: :all+ page.driver.browser.manage.window.resize_to(1280, 900)++ page.execute_script(<<~JS)+ document.addEventListener("turbo:before-render", () => {+ const style = getComputedStyle(document.documentElement)+ window.widthsAtRender = ["left", "right"].map((side) => style.getPropertyValue("--" + side + "-sidebar-width").trim())+ }, { once: true })+ Turbo.visit("/")+ JS++ kept = kept_widths+ assert_not_equal %w[480px 560px], kept, "the narrower window clamps the pair"+ assert_equal kept, page.evaluate_script("window.widthsAtRender"), "the page rendered at the old window's widths"+ ensure+ page.execute_script(%(localStorage.removeItem("sure.sidebarWidth.left"); localStorage.removeItem("sure.sidebarWidth.right")))+ end++ test "a visit after a resize keeps the sidebar at its new width instead of sliding back to it" do+ page.driver.browser.manage.window.resize_to(1500, 1000)+ visit root_path+ find("[data-action*='sidebar-resize#keyLeft']").send_keys(:arrow_left, :arrow_left, :arrow_left)+ resized = page.evaluate_script(%(Math.round(document.querySelector("[data-app-layout-target='leftSidebar']").getBoundingClientRect().width)))+ assert_equal 320 - 3 * 16, resized+ assert_equal "#{resized}px", page.evaluate_script(%(getComputedStyle(document.documentElement).getPropertyValue("--left-sidebar-width").trim())),+ "a page swapped in by a visit reads the width from <html> until the resize controller connects"+ assert_equal "width", page.evaluate_script(%(getComputedStyle(document.querySelector("[data-app-layout-target='leftSidebar']")).transitionProperty)),+ "only opening and closing animate; a width set by a resize or a visit applies at once"+ find("#sidebar-scroll details", match: :first).find("summary").click++ # Every frame from the click until 600 ms after the destination rendered,+ # however long the visit takes; <html> (which a visit keeps) is marked+ # when sampling is done, so the test waits for that rather than sleeping.+ page.execute_script(<<~JS)+ window.sidebarWidths = []+ let renderedAt = null+ document.addEventListener("turbo:render", () => { renderedAt = performance.now() }, { once: true })+ const sample = (now) => {+ const width = Math.round(document.querySelector("[data-app-layout-target='leftSidebar']").getBoundingClientRect().width)+ window.sidebarWidths.push({ width: width, afterRender: renderedAt !== null })+ if (renderedAt === null || now - renderedAt < 600) requestAnimationFrame(sample)+ else document.documentElement.dataset.sidebarSampled = "true"+ }+ requestAnimationFrame(sample)+ JS+ find("#sidebar-scroll details[open] a[href^='/accounts/']", match: :first).click+ assert_selector "#sidebar-scroll a[data-active-account]"+ assert_selector "html[data-sidebar-sampled]", visible: :all, wait: 10++ samples = page.evaluate_script("window.sidebarWidths")+ assert samples.any? { |sample| sample["afterRender"] }, "no frame of the destination page was sampled"+ assert_equal [ resized ], samples.map { |sample| sample["width"] }.uniq, "the sidebar changed width across the visit"+ ensure+ page.execute_script(%(localStorage.removeItem("sure.sidebarWidth.left"); localStorage.removeItem("sure.sidebarWidth.right")))+ end++ private+ # The widths the inline head script sets before the first paint. Reading+ # them off <html> afterwards would see what sidebar_resize_controller+ # wrote there once it connected, so the page's own script is run again+ # against a stand-in document: same viewport, same stored widths.+ def before_paint_widths+ page.evaluate_script(<<~JS)+ (() => {+ const script = Array.from(document.head.querySelectorAll("script")).find((s) => s.textContent.includes("sure.sidebarWidth."))+ const set = {}+ new Function("document", script.textContent)({ documentElement: { style: { setProperty: (name, value) => { set[name] = value } } } })+ return ["left", "right"].map((side) => set["--" + side + "-sidebar-width"])+ })()+ JS+ end++ # What sidebar_resize_controller applied once it connected; it writes both+ # widths on connect, so wait for them rather than reading too early.+ def kept_widths+ assert_selector "[data-controller~='sidebar-resize'][style*='--left-sidebar-width'][style*='--right-sidebar-width']", visible: :all+ page.evaluate_script(%(["left", "right"].map((side) => document.querySelector("[data-controller~='sidebar-resize']").style.getPropertyValue("--" + side + "-sidebar-width"))))+ end+end