Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(accounts): add expand/collapse all and default-expanded groups to sidebar and dashboard (#3551)

ampersandru44bbfb2faccc
diff --git a/app/components/DS/expand_toggle.html.erb b/app/components/DS/expand_toggle.html.erb
new file mode 100644
index 0000000000..1851258821
--- /dev/null
+++ b/app/components/DS/expand_toggle.html.erb
@@ -0,0 +1,4 @@
+<%= tag.button **merged_opts do %>
+ <span data-icon="expand" aria-hidden="true"><%= helpers.icon("chevrons-up-down", size: "sm") %></span>
+ <span data-icon="collapse" aria-hidden="true" style="display:none"><%= helpers.icon("chevrons-down-up", size: "sm") %></span>
+<% end %>
diff --git a/app/components/DS/expand_toggle.rb b/app/components/DS/expand_toggle.rb
new file mode 100644
index 0000000000..068829a774
--- /dev/null
+++ b/app/components/DS/expand_toggle.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+# An icon-only "Expand all / Collapse all" toggle for a group of <details>
+# elements. The button shows a single Lucide icon that swaps between
+# `chevrons-up-down` (expand) and `chevrons-down-up` (collapse) to reflect the
+# current state; the accessible name (aria-label) and aria-expanded state are
+# driven by client-side JS (the inline scripts in the account sidebar and the
+# dashboard balance sheet). This component renders the static shell: the
+# <button>, the data attributes those scripts key off, the two icons (with the
+# collapse icon hidden by default), and the initial aria-label.
+#
+# The icon swap is done in JS by toggling each icon's `style.display` (not via
+# a Tailwind `group-aria-expanded:` variant) on purpose: the running Docker
+# image ships a precompiled Tailwind bundle, so a newly introduced variant
+# class would not be present in that CSS and the icons would not swap on a
+# bind-mounted deploy. Inline `style.display` works regardless of the compiled
+# bundle.
+#
+# The two labels are localized at the call site and passed in; they are stored
+# in data-expand-label / data-collapse-label so the scripts can update the
+# aria-label without re-rendering. The component stays locale-agnostic (this is
+# what removes the "localization-bound" text the maintainer asked to drop).
+#
+# `data:` carries the presence marker the scripts select on
+# (e.g. `account_sidebar_expand_all:` / `balance_sheet_expand_all:`). It is
+# passed as `true` so Rails renders a bare `data-...` attribute; a `nil`
+# value would be dropped by the tag helper and break the selector.
+class DS::ExpandToggle < DesignSystemComponent
+ # Shared icon-only outline style. The button is a compact square: centered
+ # icon, 8px padding (32px total with the 16px icon), the same border and
+ # background as the previous labelled button. The sidebar call site appends
+ # `shrink-0` so the button does not compress next to the flex-1 "New" link.
+ DEFAULT_CLASSES = "inline-flex items-center justify-center rounded-lg border border-primary bg-container p-2 text-primary hover:bg-surface-inset transition-colors"
+
+ attr_reader :expand_label, :collapse_label, :data, :extra_classes
+
+ def initialize(expand_label:, collapse_label:, data:, class_name: nil)
+ @expand_label = expand_label
+ @collapse_label = collapse_label
+ @data = data
+ @extra_classes = class_name
+ end
+
+ def merged_opts
+ {
+ type: "button",
+ class: class_names(DEFAULT_CLASSES, extra_classes),
+ data: data.merge(expand_label: expand_label, collapse_label: collapse_label),
+ aria: { expanded: false, label: expand_label }
+ }
+ end
+end
diff --git a/app/controllers/settings/appearances_controller.rb b/app/controllers/settings/appearances_controller.rb
index c9a0ccbc92..1feaf96a8f 100644
--- a/app/controllers/settings/appearances_controller.rb
+++ b/app/controllers/settings/appearances_controller.rb
@@ -1,10 +1,14 @@
class Settings::AppearancesController < ApplicationController
layout "settings"
+ # Renders the user's appearance settings page (the form for #update).
def show
@user = Current.user
end
+ # Updates the submitted Appearance preferences under a pessimistic
+ # user-row lock. Account-group selections are filtered to known accountable
+ # keys; preferences omitted from the form are preserved as-is.
def update
@user = Current.user
@user.transaction do
@@ -13,6 +17,20 @@ class Settings::AppearancesController < ApplicationController
updated_prefs["show_split_grouped"] = params.dig(:user, :show_split_grouped) == "1" if params.dig(:user, :show_split_grouped)
updated_prefs["dashboard_two_column"] = params.dig(:user, :dashboard_two_column) == "1" if params.dig(:user, :dashboard_two_column)
updated_prefs["disable_modal_click_outside"] = params.dig(:user, :disable_modal_click_outside) == "1" if params.dig(:user, :disable_modal_click_outside)
+ # "Always expand" account groups on the dashboard balance sheet. The form
+ # posts one checkbox per accountable type; unchecked boxes are hidden
+ # fields that submit an empty string, so when the checkboxes are in the
+ # form the param is always present (an array, possibly empty). We only
+ # write it when present so a form that omits the checkboxes (e.g. a
+ # two-column-only form) never wipes the stored selection.
+ if (account_groups = params.dig(:user, :account_groups))
+ # Unchecked boxes arrive as empty strings (one per hidden field); keep
+ # only the actually-selected keys, and validate against known types so
+ # arbitrary strings can't be injected into the JSONB column.
+ valid_keys = Accountable::TYPES.map(&:underscore)
+ selected = (account_groups.is_a?(Array) ? account_groups : [ account_groups ])
+ updated_prefs["always_expanded_account_groups"] = selected.select { |k| valid_keys.include?(k) }
+ end
@user.update!(preferences: updated_prefs)
end
redirect_to settings_appearance_path
diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb
index d35ed07eda..ffb8480d3b 100644
--- a/app/helpers/accounts_helper.rb
+++ b/app/helpers/accounts_helper.rb
@@ -36,13 +36,18 @@ module AccountsHelper
end
[
- family.build_cache_key("account_sidebar_tabs_v2", invalidate_on_data_updates: true),
+ family.build_cache_key("account_sidebar_tabs_v3", invalidate_on_data_updates: true),
Current.user&.id,
shares_version,
active_tab,
mobile,
I18n.locale,
- sidebar_active_account_id
+ sidebar_active_account_id,
+ # Fold the per-user "start expanded by default" preference into the key
+ # so toggling it in Settings busts the 12h fragment cache immediately
+ # (this partial renders with skip_digest: true, so the template digest
+ # would not otherwise reflect the change).
+ Current.user&.always_expanded_account_groups&.sort
]
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 0a89d20692..31ea5c4762 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -645,10 +645,25 @@ class User < ApplicationRecord
preferences&.dig("show_split_grouped") != false
end
+ # Returns whether the user has enabled the two-column dashboard layout.
def dashboard_two_column?
preferences&.dig("dashboard_two_column") == true
end
+ # Returns the accountable keys (e.g. "depository", "credit_card") that should
+ # start expanded in the sidebar and dashboard balance sheet, or an empty
+ # array when unset. Stored in the preferences JSONB column.
+ def always_expanded_account_groups
+ preferences&.dig("always_expanded_account_groups") || []
+ end
+
+ # Returns whether the given key (coerced to a string) is selected to start
+ # expanded in the sidebar and dashboard balance sheet.
+ def always_expanded_account_group?(account_group_key)
+ always_expanded_account_groups.include?(account_group_key.to_s)
+ end
+
+ # Returns whether clicking outside a modal is prevented from closing it.
def disable_modal_click_outside?
preferences&.dig("disable_modal_click_outside") == true
end
diff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erb
index 5469f0c8d0..3213402613 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_v2",
+ account_sidebar_tabs_cache_key ("account_sidebar_tabs_v3",
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. %>
@@ -28,15 +28,23 @@
<% tabs.with_panel(tab_id: "asset") do %>
<div class="space-y-2">
- <%= render DS::Link.new(
- text: t("accounts.sidebar.new_asset"),
- variant: "ghost",
- href: new_account_path(step: "method_select", classification: "asset"),
- icon: "plus",
- frame: :modal,
- full_width: true,
- class: "justify-start"
- ) %>
+ <div class="flex items-center gap-2">
+ <%= render DS::Link.new(
+ text: t("accounts.sidebar.new_asset"),
+ variant: "ghost",
+ href: new_account_path(step: "method_select", classification: "asset"),
+ icon: "plus",
+ frame: :modal,
+ class: "flex-1 justify-start"
+ ) %>
+
+ <%= render DS::ExpandToggle.new(
+ expand_label: t("accounts.sidebar.expand_all"),
+ collapse_label: t("accounts.sidebar.collapse_all"),
+ data: { account_sidebar_expand_all: true },
+ class_name: "shrink-0"
+ ) %>
+ </div>
<div>
<% family.balance_sheet.assets.account_groups.each do |group| %>
@@ -48,15 +56,23 @@
<% tabs.with_panel(tab_id: "liability") do %>
<div class="space-y-2">
- <%= render DS::Link.new(
- text: t("accounts.sidebar.new_debt"),
- variant: "ghost",
- href: new_account_path(step: "method_select", classification: "liability"),
- icon: "plus",
- frame: :modal,
- full_width: true,
- class: "justify-start"
+ <div class="flex items-center gap-2">
+ <%= render DS::Link.new(
+ text: t("accounts.sidebar.new_debt"),
+ variant: "ghost",
+ href: new_account_path(step: "method_select", classification: "liability"),
+ icon: "plus",
+ frame: :modal,
+ class: "flex-1 justify-start"
+ ) %>
+
+ <%= render DS::ExpandToggle.new(
+ expand_label: t("accounts.sidebar.expand_all"),
+ collapse_label: t("accounts.sidebar.collapse_all"),
+ data: { account_sidebar_expand_all: true },
+ class_name: "shrink-0"
) %>
+ </div>
<div>
<% family.balance_sheet.liabilities.account_groups.each do |group| %>
@@ -68,15 +84,23 @@
<% tabs.with_panel(tab_id: "all") do %>
<div class="space-y-2">
- <%= render DS::Link.new(
- text: t("accounts.sidebar.new_account"),
- variant: "ghost",
- full_width: true,
- href: new_account_path(step: "method_select"),
- icon: "plus",
- frame: :modal,
- class: "justify-start"
+ <div class="flex items-center gap-2">
+ <%= render DS::Link.new(
+ text: t("accounts.sidebar.new_account"),
+ variant: "ghost",
+ href: new_account_path(step: "method_select"),
+ icon: "plus",
+ frame: :modal,
+ class: "flex-1 justify-start"
+ ) %>
+
+ <%= render DS::ExpandToggle.new(
+ expand_label: t("accounts.sidebar.expand_all"),
+ collapse_label: t("accounts.sidebar.collapse_all"),
+ data: { account_sidebar_expand_all: true },
+ class_name: "shrink-0"
) %>
+ </div>
<div>
<% family.balance_sheet.account_groups.each do |group| %>
@@ -87,4 +111,68 @@
<% end %>
<% end %>
</div>
+<%= javascript_tag nonce: true do %>
+ // Expand/Collapse all for the account sidebar. Event-delegated on document
+ // so it works for both the desktop and mobile sidebar instances and survives
+ // Turbo re-renders. Wrapped in javascript_tag for CSP nonce compliance
+ // (matches the dashboard balance sheet).
+ (function () {
+ function setLabel(btn, expanded) {
+ btn.setAttribute("aria-expanded", expanded ? "true" : "false");
+ btn.setAttribute("aria-label", expanded ? btn.dataset.collapseLabel : btn.dataset.expandLabel);
+ // Swap the visible icon via inline display (not a Tailwind
+ // group-aria-expanded: variant, which is absent from the precompiled
+ // bundle shipped in the Docker image).
+ var expandIcon = btn.querySelector('[data-icon="expand"]');
+ var collapseIcon = btn.querySelector('[data-icon="collapse"]');
+ if (expandIcon) expandIcon.style.display = expanded ? "none" : "";
+ if (collapseIcon) collapseIcon.style.display = expanded ? "" : "none";
+ }
+
+ // A mixed open/closed panel shows "Expand all" (a click expands the closed
+ // ones); only an all-open panel shows "Collapse all".
+ function syncPanel(panel) {
+ var btn = panel.querySelector("[data-account-sidebar-expand-all]");
+ if (!btn) return;
+ var details = Array.prototype.slice.call(panel.querySelectorAll("details"));
+ // Hide the control when the panel has no groups (e.g. assets but no
+ // debts) so it never renders as a dead button. Matches the dashboard.
+ btn.style.display = details.length ? "" : "none";
+ if (!details.length) return;
+ setLabel(btn, details.every(function (d) { return d.open; }));
+ }
+
+ // One-time event binding (document delegation survives Turbo re-renders
+ // and covers both the desktop and mobile sidebar instances).
+ if (!window.__sidebarExpandAllBound) {
+ window.__sidebarExpandAllBound = true;
+
+ document.addEventListener("click", function (e) {
+ var btn = e.target.closest("[data-account-sidebar-expand-all]");
+ if (!btn) return;
+ var panel = btn.closest("[role=tabpanel]");
+ if (!panel) return;
+ var details = Array.prototype.slice.call(panel.querySelectorAll("details"));
+ if (!details.length) return;
+ var anyClosed = details.some(function (d) { return !d.open; });
+ details.forEach(function (d) { d.open = anyClosed; });
+ setLabel(btn, anyClosed);
+ });
+
+ // Keep the label in sync when a group is opened/closed manually.
+ // `toggle` does not bubble, so listen in the capture phase.
+ document.addEventListener("toggle", function (e) {
+ var panel = e.target.closest("[role=tabpanel]");
+ if (panel) syncPanel(panel);
+ }, true);
+ }
+
+ // Per-render label sync (idempotent): runs on every render, including after
+ // Turbo navigations, so a freshly rendered sidebar reflects its groups'
+ // current open/closed state.
+ Array.prototype.slice.call(document.querySelectorAll("[role=tabpanel]")).forEach(function (panel) {
+ syncPanel(panel);
+ });
+ })();
+<% end %>
<% end %>
diff --git a/app/views/accounts/_accountable_group.html.erb b/app/views/accounts/_accountable_group.html.erb
index 28727dc85c..efcc44f0f4 100644
--- a/app/views/accounts/_accountable_group.html.erb
+++ b/app/views/accounts/_accountable_group.html.erb
@@ -1,7 +1,7 @@
<%# locals: (account_group:, mobile: false, all_tab: false, open: nil, **args) %>
-<div id="<%= account_group.dom_id(tab: all_tab ? :all : nil, mobile: mobile) %>">
- <% is_open = open.nil? ? account_group.accounts.any? { |account| page_active?(account_path(account)) } : open %>
+<div id="<%= account_group.dom_id(tab: all_tab ? :all : nil, mobile: mobile) %>" 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 %>
<div class="flex items-center gap-3">
@@ -28,6 +28,7 @@
"block flex items-center gap-2 px-3 py-2 rounded-lg",
page_active?(account_path(account)) ? "bg-container" : "hover:bg-surface-hover"
),
+ data: page_active?(account_path(account)) ? { active_account: true } : {},
title: account.name do %>
<%= render "accounts/logo", account: account, size: "sm", color: account_group.color %>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 378346387c..0c429e4441 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -112,7 +112,7 @@ end %>
inert: !Current.user.show_sidebar?,
data: { app_layout_target: "leftSidebar", sidebar_resize_target: "leftSidebar" } do %>
<%= render "layouts/shared/sidebar_resize_handle", side: "left" %>
- <div class="px-4 h-full flex flex-col overflow-y-auto">
+ <div id="sidebar-scroll" data-controller="preserve-scroll" class="px-4 h-full flex flex-col overflow-y-auto">
<% if content_for?(:sidebar) %>
<%= yield :sidebar %>
<% else %>
@@ -256,5 +256,154 @@ end %>
<%= render "layouts/shared/release_highlight", tag: tag %>
<% end %>
<% end %>
+<%# Preserve the account sidebar's group open/closed state across Turbo Drive navigations so the sidebar height stays stable and the scroll position is not clamped to the top. See the inline script below for details. %>
+<%= javascript_tag nonce: true do %>
+ // Preserves the account sidebar's group open/closed state across Turbo Drive
+ // navigations so the sidebar height stays stable and the scroll position
+ // (restored by the `preserve-scroll` controller) is not clamped to the top.
+ //
+ // Each account group is a <details> whose open state is decided server-side:
+ // a group is open when it holds the active account or is in the user's
+ // "always expanded" preference. Navigating between accounts re-renders a
+ // different set of open groups, which changes the sidebar's scrollHeight.
+ // If the new sidebar is shorter than the saved offset, the browser clamps
+ // the restored scrollTop to the new maximum and the user sees the sidebar
+ // jump back up. This script records the open/closed state of every group
+ // before the navigation and re-applies it after the render (so a group the
+ // user collapsed stays collapsed, even one the server would re-open from the
+ // "always expanded" preference), keeps the group holding the active account
+ // open, forces a synchronous layout pass, and re-applies the saved scrollTop
+ // so the offset is valid again.
+ //
+ // groupKeyOf() derives a tab-independent group key from either markup shape:
+ // (a) the NEW sidebar partial / balance sheet, which carry
+ // data-group-key on the <details> or its wrapper, or
+ // (b) the OLD sidebar partial, whose wrapper id is <tab>_<group>
+ // (all_/asset_/liability_, plus the mobile_ variant) with no
+ // data-group-key. A key is only accepted if it is a known account
+ // category, so unrelated <details> widgets are never treated as
+ // account groups. This makes the fix tolerant of a mixed deployment
+ // where the sidebar partial and the balance sheet differ.
+ //
+ // State lives on a window global so it survives Turbo Drive visits (the
+ // window is not replaced, only the body). The listeners are bound once;
+ // the trailing restore() also covers a full (non-Turbo) page load, where
+ // the global is fresh and the call is a no-op.
+ (function () {
+ var state = window.__sidebarScrollPreserve ||
+ (window.__sidebarScrollPreserve = { groupStates: null, scrollTop: null });
+
+ var PREFIX_RE = /^(mobile_)?(all|asset|liability)_/;
+ // Accepted group keys, derived from Accountable::TYPES at render time
+ // so the set stays in sync with the source of truth: adding a new
+ // accountable type cannot silently recreate the "open group not
+ // re-opened after navigation" gap. `to_json` escapes <>& as unicode
+ // (safe inside a <script> tag); `raw` keeps ERB from double-escaping.
+ var GROUP_KEYS = new Set(<%= raw(Accountable::TYPES.map(&:underscore).to_json) %>);
+
+ function container() { return document.getElementById("sidebar-scroll"); }
+
+ function validKey(value) {
+ return value && GROUP_KEYS.has(value) ? value : null;
+ }
+
+ // Derive a tab-independent group key from a <details>, or null if it is
+ // not an account group.
+ function groupKeyOf(details) {
+ var root = container();
+ if (!root || !root.contains(details)) return null;
+ // 1. data-group-key on the <details> or its nearest wrapper.
+ for (var node = details; node && node !== root; node = node.parentElement) {
+ if (node.hasAttribute("data-group-key")) {
+ return validKey(node.getAttribute("data-group-key"));
+ }
+ }
+ // 2. Wrapper id with the tab prefix stripped (old partial).
+ for (var w = details.parentElement; w && w !== root; w = w.parentElement) {
+ if (w.id && PREFIX_RE.test(w.id)) {
+ return validKey(w.id.replace(PREFIX_RE, ""));
+ }
+ }
+ return null;
+ }
+
+ function groupDetails() {
+ var root = container();
+ if (!root) return [];
+ return Array.prototype.slice.call(root.querySelectorAll("details"));
+ }
+
+ // Prototype-free map of group key -> open/closed for every account group,
+ // or null when there are no account groups at all. Storing the explicit
+ // boolean (not just the open keys) lets restore() keep a group the user
+ // collapsed closed, including groups the server re-opens from the
+ // "always expanded" preference.
+ function groupStates() {
+ var states = null;
+ groupDetails().forEach(function (d) {
+ var k = groupKeyOf(d);
+ if (k) {
+ if (!states) states = Object.create(null);
+ states[k] = d.open;
+ }
+ });
+ return states;
+ }
+
+ // Key of the group holding the active account, or null. The active account
+ // link is marked data-active-account in the sidebar partial; every copy of
+ // the account (per tab panel, desktop + mobile) shares the same group key,
+ // so the first match resolves to the right group.
+ function activeGroupKey() {
+ var root = container();
+ if (!root) return null;
+ var active = root.querySelector("[data-active-account]");
+ if (!active) return null;
+ var d = active.closest("details");
+ return d ? groupKeyOf(d) : null;
+ }
+
+ function capture() {
+ var el = container();
+ if (!el) return;
+ state.groupStates = groupStates();
+ // Always save the scroll offset, even when every group is collapsed:
+ // the sidebar can still be scrolled (headers, "New" buttons, the bottom
+ // of a long list), so coupling the save to "any group open" would drop
+ // the offset in that case.
+ state.scrollTop = el.scrollTop;
+ }
+
+ function restore() {
+ var el = container();
+ if (!el || !state.groupStates) return;
+ var activeKey = activeGroupKey();
+ // Re-apply the user's pre-navigation open/closed state to every group we
+ // captured. A group the user collapsed stays closed even if the server
+ // re-opens it (active account or "always expanded" preference); the group
+ // holding the active account is forced open so it is never hidden.
+ // Groups not in state.groupStates (new since capture) are left as the
+ // server rendered them.
+ groupDetails().forEach(function (d) {
+ var k = groupKeyOf(d);
+ if (!k || !Object.prototype.hasOwnProperty.call(state.groupStates, k)) return;
+ d.open = (k === activeKey) ? true : state.groupStates[k];
+ });
+ // Force a synchronous layout pass so scrollHeight reflects the re-opened
+ // groups before we write scrollTop; otherwise the browser clamps the
+ // restored offset to the (still-short) container.
+ void el.offsetHeight;
+ if (typeof state.scrollTop === "number") el.scrollTop = state.scrollTop;
+ }
+
+ if (!window.__sidebarScrollPreserveBound) {
+ window.__sidebarScrollPreserveBound = true;
+ window.addEventListener("turbo:before-cache", capture);
+ window.addEventListener("turbo:render", restore);
+ }
+ restore();
+ })();
+
+<% end %>
</div>
<% end %>
diff --git a/app/views/pages/dashboard.html.erb b/app/views/pages/dashboard.html.erb
index 50fbdca2b1..997d5eb4aa 100644
--- a/app/views/pages/dashboard.html.erb
+++ b/app/views/pages/dashboard.html.erb
@@ -78,6 +78,22 @@
</h2>
</div>
<div class="flex items-center gap-1">
+ <%# Expand/Collapse-all for the balance sheet, as the leftmost
+ icon in the header's hover cluster. Wired by the inline script
+ in _balance_sheet.html.erb (which finds it via this section). %>
+ <% if section[:key] == "balance_sheet" && @balance_sheet.classification_groups.any? { |cg| cg.account_groups.any? } %>
+ <button
+ type="button"
+ class="flex items-center justify-center w-6 h-6 rounded-md text-secondary hover:text-primary hover:bg-container-inset-hover transition-colors opacity-0 group-hover:opacity-100"
+ data-balance-sheet-expand-all="true"
+ data-expand-label="<%= t("pages.dashboard.balance_sheet.expand_all") %>"
+ data-collapse-label="<%= t("pages.dashboard.balance_sheet.collapse_all") %>"
+ aria-expanded="false"
+ aria-label="<%= t("pages.dashboard.balance_sheet.expand_all") %>">
+ <span data-icon="expand" aria-hidden="true"><%= icon("chevrons-up-down", size: "sm", class: "!w-3.5 !h-3.5") %></span>
+ <span data-icon="collapse" aria-hidden="true" style="display:none"><%= icon("chevrons-down-up", size: "sm", class: "!w-3.5 !h-3.5") %></span>
+ </button>
+ <% end %>
<% if section[:key] == "cashflow_sankey" && section[:locals][:sankey_data][:links].present? %>
<button
type="button"
diff --git a/app/views/pages/dashboard/_balance_sheet.html.erb b/app/views/pages/dashboard/_balance_sheet.html.erb
index 5d2d476f44..ce165c1bb9 100644
--- a/app/views/pages/dashboard/_balance_sheet.html.erb
+++ b/app/views/pages/dashboard/_balance_sheet.html.erb
@@ -1,6 +1,8 @@
<%# locals: (balance_sheet:, **args) %>
-<div class="space-y-6" id="balance-sheet">
+<div class="space-y-6" id="balance-sheet"
+ data-always-expanded="<%= Current.user.always_expanded_account_groups.to_json %>">
+
<% balance_sheet.classification_groups.each do |classification_group| %>
<div class="space-y-4 px-4">
<div class="flex items-center gap-2">
@@ -53,7 +55,8 @@
<details class="group open:bg-container
<%= idx == 0 ? "rounded-t-lg" : "" %>
<%= idx == classification_group.account_groups.size - 1 ? "rounded-b-lg" : "" %>
- ">
+ " data-group-key="<%= account_group.key %>"
+ <%= "open" if Current.user.always_expanded_account_group?(account_group.key) %>>
<summary class="cursor-pointer p-4 group-open:bg-container rounded-lg flex items-center justify-between">
<div class="w-40 shrink-0 flex items-center gap-1">
<%= icon("chevron-right", class: "group-open:rotate-90") %>
@@ -135,3 +138,74 @@
display: none;
}
</style>
+
+<%#
+ "Expand all / Collapse all" for the balance-sheet account groups.
+
+ This is an inline <script> (not a Stimulus controller) on purpose: Sure ships
+ its JS via importmap, and the .importmap.json manifest is baked into the
+ Docker image at build time. A newly bind-mounted *_controller.js would not be
+ in that manifest, so the browser would 404 it and the button would be dead on
+ the running image. An inline script is served with the HTML and re-runs
+ automatically when the surrounding Turbo frame re-renders (e.g. on a period
+ change). Wrapped in javascript_tag for CSP nonce compliance.
+%>
+<% if balance_sheet.classification_groups.any? { |cg| cg.account_groups.any? } %>
+<%= javascript_tag nonce: true do %>
+ (function () {
+ var section = document.querySelector('section[data-section-key="balance_sheet"]');
+ var root = document.getElementById("balance-sheet");
+ var button = section && section.querySelector("[data-balance-sheet-expand-all]");
+ if (!button) return;
+
+ var details = Array.prototype.slice.call(root.querySelectorAll("details"));
+ if (details.length === 0) { button.style.display = "none"; return; }
+
+ // Enforce "always expanded" preference client-side. The root div carries
+ // the current preference list (server-rendered); each <details> carries
+ // its own data-group-key. This works on full page loads, Turbo frame
+ // swaps, and bfcache restores alike.
+ var alwaysExpanded = [];
+ try { alwaysExpanded = JSON.parse(root.getAttribute("data-always-expanded") || "[]"); } catch (e) {}
+ if (alwaysExpanded.length > 0) {
+ details.forEach(function (d) {
+ var key = d.getAttribute("data-group-key");
+ if (key && alwaysExpanded.indexOf(key) !== -1) d.open = true;
+ });
+ }
+
+ var expandLabel = button.getAttribute("data-expand-label") || "Expand all";
+ var collapseLabel = button.getAttribute("data-collapse-label") || "Collapse all";
+
+ function allOpen() {
+ return details.every(function (d) { return d.open; });
+ }
+
+ function syncButton() {
+ var open = allOpen();
+ button.setAttribute("aria-expanded", open ? "true" : "false");
+ button.setAttribute("aria-label", open ? collapseLabel : expandLabel);
+ // Swap the visible icon via inline display (not a Tailwind
+ // group-aria-expanded: variant, which is absent from the precompiled
+ // bundle shipped in the Docker image).
+ var expandIcon = button.querySelector('[data-icon="expand"]');
+ var collapseIcon = button.querySelector('[data-icon="collapse"]');
+ if (expandIcon) expandIcon.style.display = open ? "none" : "";
+ if (collapseIcon) collapseIcon.style.display = open ? "" : "none";
+ }
+
+ button.addEventListener("click", function () {
+ var open = allOpen();
+ details.forEach(function (d) { d.open = !open; });
+ syncButton();
+ });
+
+ // Keep the button in sync if an individual group is toggled by hand.
+ details.forEach(function (d) {
+ d.addEventListener("toggle", syncButton);
+ });
+
+ syncButton();
+ })();
+<% end %>
+<% end %>
diff --git a/app/views/settings/appearances/show.html.erb b/app/views/settings/appearances/show.html.erb
index 230c5e92ac..ac09a58dc5 100644
--- a/app/views/settings/appearances/show.html.erb
+++ b/app/views/settings/appearances/show.html.erb
@@ -31,7 +31,7 @@
<%= settings_section title: t(".dashboard_title"), subtitle: t(".dashboard_subtitle") do %>
<div>
<%= form_with url: settings_appearance_path, method: :patch,
- class: "p-3",
+ class: "p-3 space-y-4",
data: { controller: "auto-submit-form" } do |f| %>
<div class="flex cursor-pointer items-center gap-4 justify-between">
<div class="text-sm space-y-1">
@@ -45,6 +45,29 @@
data: { auto_submit_form_target: "auto" }
) %>
</div>
+
+ <div class="border-t border-primary pt-4">
+ <div class="text-sm space-y-1 mb-3">
+ <p class="text-primary font-medium"><%= t(".dashboard_account_groups_title") %></p>
+ <p class="text-secondary"><%= t(".dashboard_account_groups_description") %></p>
+ </div>
+ <div class="grid gap-2 sm:grid-cols-2">
+ <% selected = @user.always_expanded_account_groups %>
+ <% Accountable::TYPES.each do |type| %>
+ <% key = type.underscore %>
+ <% checked = selected.include?(key) %>
+ <label class="flex cursor-pointer items-center gap-2.5 rounded-lg px-3 py-2 hover:bg-surface-inset transition-colors"
+ for="user_account_groups_<%= key %>">
+ <%= hidden_field_tag "user[account_groups][]", "", id: nil %>
+ <%= check_box_tag "user[account_groups][]", key, checked,
+ id: "user_account_groups_#{key}",
+ class: "checkbox checkbox--light mt-0.5",
+ data: { auto_submit_form_target: "auto" } %>
+ <span class="text-sm text-primary"><%= Accountable.from_type(type).display_name %></span>
+ </label>
+ <% end %>
+ </div>
+ </div>
<% end %>
</div>
<% end %>
diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.yml
index 02a68aea9e..e76606734c 100644
--- a/config/locales/views/accounts/en.yml
+++ b/config/locales/views/accounts/en.yml
@@ -144,6 +144,8 @@ en:
new_debt: New debt
new_account: New account
new_account_group: "New %{account_group}"
+ expand_all: Expand all
+ collapse_all: Collapse all
types:
depository: Cash
investment: Investment
diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.yml
index 3d60596ba6..d1b705bc1d 100644
--- a/config/locales/views/pages/en.yml
+++ b/config/locales/views/pages/en.yml
@@ -71,6 +71,8 @@ en:
name: "Name"
weight: "Weight"
value: "Value"
+ expand_all: "Expand all"
+ collapse_all: "Collapse all"
classifications:
asset: "Assets"
liability: "Liabilities"
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 293828084a..5a206e3a73 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -180,6 +180,8 @@ en:
dashboard_subtitle: Customize how the dashboard is displayed
dashboard_two_column_title: Two-column layout
dashboard_two_column_description: Display dashboard widgets in two columns on large screens, with per-widget width and height controls in each widget's header. When off, widgets stack in a single column.
+ dashboard_account_groups_title: Start expanded by default
+ dashboard_account_groups_description: These account sections will start expanded on the dashboard and in the account sidebar. You can still collapse them manually at any time.
split_grouped_title: Group split transactions
split_grouped_description: Show split transactions grouped under their parent in the transaction list. When off, split children appear as individual rows.
preferences:
diff --git a/test/components/DS/expand_toggle_test.rb b/test/components/DS/expand_toggle_test.rb
new file mode 100644
index 0000000000..083eb073f7
--- /dev/null
+++ b/test/components/DS/expand_toggle_test.rb
@@ -0,0 +1,51 @@
+require "test_helper"
+
+class DS::ExpandToggleTest < ViewComponent::TestCase
+ test "renders the presence-marker attribute and icon-only shell the sidebar JS keys off" do
+ render_inline(DS::ExpandToggle.new(
+ expand_label: "Expand all",
+ collapse_label: "Collapse all",
+ data: { account_sidebar_expand_all: true },
+ class_name: "shrink-0"
+ ))
+
+ # `true` (not nil) is required: the tag helper drops nil-valued data keys,
+ # which would omit the attribute and break the [data-...] selector.
+ assert_selector "button[data-account-sidebar-expand-all]"
+ assert_selector "button[data-account-sidebar-expand-all][type='button']"
+ assert_selector "button[data-expand-label='Expand all']"
+ assert_selector "button[data-collapse-label='Collapse all']"
+ assert_selector "button[aria-expanded='false']"
+ # Icon-only: the accessible name lives on the button (not a text node), and
+ # both state icons are present (the collapse icon is hidden by default and
+ # revealed by JS once the groups are all open).
+ assert_selector "button[aria-label='Expand all']"
+ assert_selector "button [data-icon='expand']"
+ assert_selector "button [data-icon='collapse']", visible: :all
+ end
+
+ test "renders the balance-sheet marker without a shrink class" do
+ render_inline(DS::ExpandToggle.new(
+ expand_label: "Expand all",
+ collapse_label: "Collapse all",
+ data: { balance_sheet_expand_all: true }
+ ))
+
+ assert_selector "button[data-balance-sheet-expand-all]"
+ assert_selector "button[data-balance-sheet-expand-all][aria-expanded='false']"
+ assert_selector "button[aria-label='Expand all']"
+ assert_selector "button [data-icon='expand']"
+ assert_selector "button [data-icon='collapse']", visible: :all
+ end
+
+ test "keeps the shared icon-only outline style and the caller's extra class" do
+ render_inline(DS::ExpandToggle.new(
+ expand_label: "Expand all",
+ collapse_label: "Collapse all",
+ data: { account_sidebar_expand_all: true },
+ class_name: "shrink-0"
+ ))
+
+ assert_selector "button.shrink-0.border.border-primary.bg-container.text-primary"
+ end
+end
diff --git a/test/integration/sidebar_scroll_preserve_keys_test.rb b/test/integration/sidebar_scroll_preserve_keys_test.rb
new file mode 100644
index 0000000000..fb62fce661
--- /dev/null
+++ b/test/integration/sidebar_scroll_preserve_keys_test.rb
@@ -0,0 +1,56 @@
+require "test_helper"
+
+# Regression for Jimata review 5200022044 on PR #3551.
+#
+# The sidebar scroll-preserve inline script re-opens the account groups a user
+# had open before a Turbo navigation, so the restored sidebar has enough height
+# to hold the saved scrollTop. It validates each derived group key against an
+# accepted-key set. That set was originally a hardcoded 6-key regex
+# (credit_card|depository|investment|loan|property|vehicle) that silently
+# dropped three of the nine Accountable::TYPES — crypto, other_asset, and
+# other_liability — so an open group of one of those types was never re-opened
+# and the restored scrollTop could be clamped.
+#
+# The fix derives the accepted set from Accountable::TYPES.map(&:underscore) at
+# render time. This test guards that: the rendered set must equal the full set
+# of accountable types (order-independent), and must include each of the three
+# previously-omitted keys. It is a fast, browser-free integration test, so it
+# cannot flake the way a headless Turbo-navigation system test would.
+class SidebarScrollPreserveKeysTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in users(:family_admin)
+ end
+
+ # Pull the `new Set([...])` argument out of the rendered inline script.
+ # Anchored on the unique GROUP_KEYS variable so we never match an unrelated
+ # `new Set([...])` from another inlined script earlier in the page.
+ def group_keys_from(body)
+ match = body.match(/GROUP_KEYS = new Set\((\[[^\]]*\])\)/)
+ assert match, "expected the sidebar scroll-preserve script's GROUP_KEYS Set in the layout"
+ JSON.parse(match[1])
+ end
+
+ test "accepted group keys are derived from Accountable::TYPES (all nine)" do
+ get root_path
+ assert_response :ok
+
+ expected = Accountable::TYPES.map(&:underscore)
+ rendered = group_keys_from(response.body)
+
+ assert_equal expected.to_set, rendered.to_set,
+ "GROUP_KEYS must equal Accountable::TYPES.map(&:underscore)"
+ end
+
+ test "the three previously-omitted group keys are accepted" do
+ get root_path
+ assert_response :ok
+
+ rendered = group_keys_from(response.body)
+
+ # The exact keys the old 6-key GROUP_RE dropped.
+ [ "crypto", "other_asset", "other_liability" ].each do |key|
+ assert_includes rendered, key,
+ "GROUP_KEYS must include #{key.inspect} (dropped by the old 6-key regex)"
+ end
+ end
+end