Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(accounts): manual drag-and-drop account order (#4341)

GFRafa392d06eb2
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index ca3af101c5..c601e9eefa 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -209,6 +209,15 @@ class AccountsController < ApplicationController
end
end
+ # Saves the drag-and-drop order of one account group for the current user.
+ def reorder
+ if Current.user.update_manual_account_order(params[:group], params[:account_ids])
+ head :ok
+ else
+ head :unprocessable_entity
+ end
+ end
+
def toggle_active
if @account.active?
@account.disable!
diff --git a/app/controllers/settings/appearances_controller.rb b/app/controllers/settings/appearances_controller.rb
index 1feaf96a8f..e208c76acf 100644
--- a/app/controllers/settings/appearances_controller.rb
+++ b/app/controllers/settings/appearances_controller.rb
@@ -11,9 +11,7 @@ class Settings::AppearancesController < ApplicationController
# keys; preferences omitted from the form are preserved as-is.
def update
@user = Current.user
- @user.transaction do
- @user.lock!
- updated_prefs = (@user.preferences || {}).deep_dup
+ @user.with_locked_preferences do |updated_prefs|
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)
@@ -31,7 +29,9 @@ class Settings::AppearancesController < ApplicationController
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)
+ # Account order is a column, not a preference; unknown keys are ignored.
+ account_order = params.dig(:user, :default_account_order)
+ @user.default_account_order = account_order if AccountOrder::ORDERS.key?(account_order.to_s)
end
redirect_to settings_appearance_path
end
diff --git a/app/controllers/settings/preferences_controller.rb b/app/controllers/settings/preferences_controller.rb
index 48e9cdc71c..4b846780c4 100644
--- a/app/controllers/settings/preferences_controller.rb
+++ b/app/controllers/settings/preferences_controller.rb
@@ -15,14 +15,11 @@ class Settings::PreferencesController < ApplicationController
@user = Current.user
user_params = params.permit(user: [ :preview_features_enabled ]).fetch(:user, {})
- @user.transaction do
- @user.lock!
- updated_prefs = (@user.preferences || {}).deep_dup
+ @user.with_locked_preferences do |updated_prefs|
if user_params.key?(:preview_features_enabled)
updated_prefs["preview_features_enabled"] =
ActiveModel::Type::Boolean.new.cast(user_params[:preview_features_enabled])
end
- @user.update!(preferences: updated_prefs)
end
redirect_to settings_preferences_path
end
diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb
index 616c79a757..79ee336b00 100644
--- a/app/helpers/accounts_helper.rb
+++ b/app/helpers/accounts_helper.rb
@@ -56,7 +56,7 @@ module AccountsHelper
end
[
- family.build_cache_key("account_sidebar_tabs_v4", invalidate_on_data_updates: true),
+ family.build_cache_key("account_sidebar_tabs_v5", invalidate_on_data_updates: true),
Current.user&.id,
shares_version,
active_tab,
@@ -67,7 +67,12 @@ module AccountsHelper
# 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
+ Current.user&.always_expanded_account_groups&.sort,
+ # Changing the account order, or dragging an account in the manual
+ # order, must re-render the sidebar right away rather than after the
+ # 12h expiry.
+ Current.user&.default_account_order,
+ Current.user&.account_order&.manual? ? Digest::SHA256.hexdigest(Current.user.manual_account_order.to_json) : nil
]
end
end
diff --git a/app/javascript/controllers/account_sort_mode_controller.js b/app/javascript/controllers/account_sort_mode_controller.js
new file mode 100644
index 0000000000..5459745660
--- /dev/null
+++ b/app/javascript/controllers/account_sort_mode_controller.js
@@ -0,0 +1,106 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Sort mode of the account sidebar, used with the manual account order.
+// The drag handles stay hidden until the user turns sort mode on, so the
+// list looks the same as with the other orders the rest of the time.
+// Visibility is set inline (not with Tailwind classes) because the Docker
+// image ships a precompiled CSS bundle, like the expand-all toggle.
+export default class extends Controller {
+ static targets = ["toggle", "bar", "handle"];
+
+ // Also resets markup restored from Turbo's page cache in sort mode.
+ connect() {
+ this.sorting = false;
+ this.render();
+ }
+
+ toggle() {
+ this.sorting ? this.stop() : this.start();
+ }
+
+ start() {
+ this.sorting = true;
+ this.render();
+ // Handles inside collapsed groups would stay out of sight. They close
+ // again when sort mode ends.
+ this.openedGroups = new Set();
+ this.handleTargets.forEach((handle) => {
+ const group = handle.closest("details");
+ if (group && !group.open) {
+ group.open = true;
+ this.openedGroups.add(group);
+ }
+ });
+ }
+
+ stop() {
+ const active = document.activeElement;
+ const focusWillHide =
+ this.handleTargets.includes(active) ||
+ this.barTargets.some((bar) => bar.contains(active));
+
+ // A row picked up with the keyboard is dropped and saved where it is.
+ window.dispatchEvent(new CustomEvent("account-sort-mode:stop"));
+
+ this.sorting = false;
+ this.render();
+ this.openedGroups?.forEach((group) => {
+ group.open = false;
+ });
+ this.openedGroups = null;
+ if (focusWillHide) this.focusAfterStop();
+ }
+
+ // Handles rendered later (e.g. another tab's list) follow the current mode.
+ handleTargetConnected(handle) {
+ this.renderHandle(handle);
+ }
+
+ // Also runs after a Turbo morph refresh, which restores the server markup.
+ render() {
+ const display = this.sorting ? "" : "none";
+ this.handleTargets.forEach((handle) => this.renderHandle(handle));
+ this.barTargets.forEach((bar) => {
+ bar.style.display = display;
+ });
+ this.toggleTargets.forEach((toggle) => {
+ toggle.setAttribute("aria-pressed", this.sorting ? "true" : "false");
+ });
+ }
+
+ // Rows can only be dragged in sort mode, so outside it a press on an
+ // account link or a text selection behaves as usual. In sort mode the link
+ // inside a row is not draggable on its own, so dragging it moves the row.
+ renderHandle(handle) {
+ handle.style.display = this.sorting ? "" : "none";
+ const item = handle.closest("[data-sortable-list-target='item']");
+ if (!item) return;
+
+ item.draggable = this.sorting;
+ item.querySelectorAll("a").forEach((link) => {
+ if (this.sorting) {
+ link.setAttribute("draggable", "false");
+ } else {
+ link.removeAttribute("draggable");
+ }
+ });
+ }
+
+ // Keeps keyboard users in the sidebar when the focused handle or bar hides:
+ // on the visible sort toggle, or on the sidebar itself when the active tab
+ // has none, instead of letting focus fall back to the page body.
+ focusAfterStop() {
+ const toggle = this.toggleTargets.find(
+ (toggle) => toggle.offsetParent !== null,
+ );
+ if (toggle) {
+ toggle.focus();
+ return;
+ }
+
+ if (!this.element.hasAttribute("tabindex")) {
+ this.element.setAttribute("tabindex", "-1");
+ }
+ this.element.focus();
+ }
+}
diff --git a/app/javascript/controllers/sortable_list_controller.js b/app/javascript/controllers/sortable_list_controller.js
index 3d3c77268c..e24dfbd6f5 100644
--- a/app/javascript/controllers/sortable_list_controller.js
+++ b/app/javascript/controllers/sortable_list_controller.js
@@ -15,6 +15,13 @@ export default class extends Controller {
url: String,
param: String,
holdDelay: { type: Number, default: 150 },
+ // Milliseconds after which an unanswered save counts as failed, so a
+ // stalled request cannot hold back every later save. 0 waits forever.
+ saveTimeout: { type: Number, default: 0 },
+ // The same list rendered more than once on a page (e.g. once per tab)
+ // follows a move right away: other sortable lists with the same url and
+ // param are reordered too.
+ mirrorLists: { type: Boolean, default: false },
// Where a dragged item lands: "below" inserts it before the first item
// whose vertical centre is below the pointer (a single column),
// "nearest" next to the item whose centre is closest (a grid): before it
@@ -43,6 +50,10 @@ export default class extends Controller {
// ===== Mouse Drag Events =====
dragStart(event) {
+ // A drag starting inside a row that is not draggable itself (an image,
+ // selected text) is not a reorder.
+ if (!event.currentTarget.draggable) return;
+
// If a touch interaction is in progress, cancel native drag —
// use touch events with hold delay instead.
// This avoids blocking mouse/trackpad drag on touch-capable laptops.
@@ -55,6 +66,12 @@ export default class extends Controller {
this.draggedElement.classList.add("opacity-50");
this.draggedElement.setAttribute("aria-grabbed", "true");
event.dataTransfer.effectAllowed = "move";
+ // Firefox only starts a drag that carries data. A custom type keeps text
+ // fields from accepting the row as a drop.
+ event.dataTransfer.setData(
+ "application/x-sortable-list-id",
+ this.draggedElement.dataset.sortableListId ?? "",
+ );
}
dragEnd(event) {
@@ -67,6 +84,7 @@ export default class extends Controller {
// Only a drag that started on one of the items is a reorder; a file or
// text dragged in from outside is left to the browser.
dragOver(event) {
+ // A drag from another list on the page is not ours to drop.
if (!this.draggedElement) return;
event.preventDefault();
@@ -295,10 +313,22 @@ export default class extends Controller {
"ring-offset-2",
);
this.keyboardGrabbedElement = null;
- this.saveOrder();
+ return this.saveOrder();
}
}
+ // Bound to turbo:before-visit. A visit (e.g. following a link inside the
+ // list) replaces the page before a row still held with the keyboard is
+ // released, which would drop the move. The row is dropped where it is and
+ // the visit waits until the order is saved, so the next page shows it.
+ saveBeforeVisit(event) {
+ if (!this.keyboardGrabbedElement) return;
+
+ event.preventDefault();
+ const { url } = event.detail;
+ this.releaseKeyboardGrab().then(() => Turbo.visit(url));
+ }
+
moveUp(section) {
const previousSibling = section.previousElementSibling;
if (previousSibling && this.itemTargets.includes(previousSibling)) {
@@ -421,12 +451,45 @@ export default class extends Controller {
// Saves run one at a time. A change made while a save is in flight is sent
// once it finishes, with the latest order only, so an older request can
- // never land after a newer one and restore an earlier order.
+ // never land after a newer one and restore an earlier order. Resolves once
+ // the queue has sent everything.
saveOrder() {
- this.pendingOrder = this.itemTargets.map(
- (item) => item.dataset.sortableListId,
+ const order = this.itemTargets.map((item) => item.dataset.sortableListId);
+ const queue = this.mirrorListsValue ? this.mirrorOrder(order) : this;
+ queue.pendingOrder = order;
+ if (!queue.saving) queue.savesFinished = queue.flushSaves();
+ return queue.savesFinished;
+ }
+
+ // Applies the order to the other copies of this list and returns the
+ // controller whose queue saves for all copies, so their saves also run one
+ // at a time.
+ mirrorOrder(order) {
+ const lists = [
+ ...document.querySelectorAll(`[data-controller~='${this.identifier}']`),
+ ].filter(
+ (list) =>
+ list.dataset.sortableListUrlValue === this.urlValue &&
+ list.dataset.sortableListParamValue === this.paramValue,
+ );
+
+ lists.forEach((list) => {
+ if (list === this.element) return;
+
+ order.forEach((id) => {
+ const item = list.querySelector(
+ `[data-sortable-list-id='${CSS.escape(id)}']`,
+ );
+ if (item) list.appendChild(item);
+ });
+ });
+
+ return (
+ this.application.getControllerForElementAndIdentifier(
+ lists[0],
+ this.identifier,
+ ) ?? this
);
- if (!this.saving) this.flushSaves();
}
async flushSaves() {
@@ -453,6 +516,10 @@ export default class extends Controller {
method: "PATCH",
headers,
body: JSON.stringify(this.buildBody(order)),
+ signal:
+ this.saveTimeoutValue > 0 && AbortSignal.timeout
+ ? AbortSignal.timeout(this.saveTimeoutValue)
+ : undefined,
});
if (!response.ok) {
diff --git a/app/javascript/controllers/sync_toast_controller.js b/app/javascript/controllers/sync_toast_controller.js
index f7af867774..eb3d6a9259 100644
--- a/app/javascript/controllers/sync_toast_controller.js
+++ b/app/javascript/controllers/sync_toast_controller.js
@@ -111,6 +111,11 @@ export default class extends Controller {
}
#userIsInteracting() {
+ // A grabbed list item (sortable-list) is only saved when it is released;
+ // a morph would drop the move. Focus may have left it, so look it up in
+ // the whole document.
+ if (document.querySelector("[aria-grabbed='true']")) return true;
+
const el = document.activeElement;
if (!el || el === document.body || el === document.documentElement)
return false;
diff --git a/app/models/account_order.rb b/app/models/account_order.rb
index bd7367c0b9..58cc8a1b34 100644
--- a/app/models/account_order.rb
+++ b/app/models/account_order.rb
@@ -22,6 +22,13 @@ class AccountOrder
label: "Balance (High to Low)",
label_short: "Balance ↓",
sql_order: "balance DESC"
+ },
+ # Per-user drag-and-drop order, stored in users.preferences. SQL callers
+ # fall back to alphabetical; BalanceSheet applies the stored order.
+ "manual" => {
+ label: "Manual (drag to reorder)",
+ label_short: "Manual",
+ sql_order: "name ASC"
}
}.freeze
@@ -44,6 +51,10 @@ class AccountOrder
ORDERS.dig(key, :sql_order)
end
+ def manual?
+ key == "manual"
+ end
+
class << self
def all
ORDERS.keys.map { |key| new(key) }
diff --git a/app/models/balance_sheet.rb b/app/models/balance_sheet.rb
index 6dd2db3ac4..a43710a8d7 100644
--- a/app/models/balance_sheet.rb
+++ b/app/models/balance_sheet.rb
@@ -76,8 +76,22 @@ class BalanceSheet
accounts.sort_by(&:balance)
when "balance_desc"
accounts.sort_by(&:balance).reverse
+ when "manual"
+ sort_manually(accounts)
else
accounts
end
end
+
+ # Accounts the user has dragged into place come first, in their saved
+ # position within their group; accounts added since then follow
+ # alphabetically.
+ def sort_manually(accounts)
+ positions = user.manual_account_order.values.flat_map { |ids| ids.each_with_index.to_a }.to_h
+
+ accounts.sort_by do |account|
+ position = positions[account.id]
+ [ position ? 0 : 1, position || 0, account.name.to_s.downcase, account.id.to_s ]
+ end
+ end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 0bfb8b77e1..936c9f9914 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -592,6 +592,44 @@ class User < ApplicationRecord
AccountOrder.find(default_account_order) || AccountOrder.default
end
+ MANUAL_ACCOUNT_ORDER_LIMIT = 500
+
+ # Drag-and-drop order of accounts per account group, keyed by accountable
+ # key (e.g. "depository") with account ids in display order.
+ def manual_account_order
+ order = preferences&.dig("manual_account_order")
+ order.is_a?(Hash) ? order : {}
+ end
+
+ # Stores the order of one account group. Ids the user cannot access are
+ # dropped so the stored preference never references foreign accounts.
+ def update_manual_account_order(group_key, account_ids)
+ group_key = group_key.to_s
+ return false unless Accountable::TYPES.map(&:underscore).include?(group_key)
+ return false unless account_ids.is_a?(Array)
+
+ requested_ids = account_ids.map(&:to_s).uniq.first(MANUAL_ACCOUNT_ORDER_LIMIT)
+ accessible_ids = accessible_accounts.where(id: requested_ids, accountable_type: group_key.camelize).pluck(:id).to_set
+ ordered_ids = requested_ids.select { |id| accessible_ids.include?(id) }
+
+ with_locked_preferences do |prefs|
+ prefs["manual_account_order"] = manual_account_order.merge(group_key => ordered_ids)
+ end
+ end
+
+ # Locked read-modify-write of the preferences JSONB: yields a copy of the
+ # current preferences (re-read under a row lock) to change in place, then
+ # saves it, so concurrent updates of other keys are not lost. Attributes set
+ # on the user inside the block are saved with it.
+ def with_locked_preferences
+ transaction do
+ lock!
+ updated_prefs = (preferences || {}).deep_dup
+ yield updated_prefs
+ update!(preferences: updated_prefs)
+ end
+ end
+
def default_account_for_transactions
return nil unless default_account_id.present?
@@ -658,12 +696,10 @@ class User < ApplicationRecord
# Adds or removes one key rather than taking the whole list, so a stale tab
# hiding one widget can't bring back another hidden elsewhere.
def update_dashboard_section_hidden(section_key, hidden)
- transaction do
- lock!
-
+ with_locked_preferences do |prefs|
keys = dashboard_hidden_sections - [ section_key ]
keys << section_key if hidden
- update!(preferences: (preferences || {}).merge("hidden_sections" => keys))
+ prefs["hidden_sections"] = keys
end
end
@@ -688,12 +724,8 @@ class User < ApplicationRecord
# laid_out_order is the order the dashboard laid its widgets out in, which
# also places widgets the saved order doesn't list yet.
def update_dashboard_preferences(prefs, laid_out_order: nil)
- # Use pessimistic locking to ensure atomic read-modify-write
- # This prevents race conditions when multiple sections are collapsed quickly
- transaction do
- lock! # Acquire row-level lock (SELECT FOR UPDATE)
-
- updated_prefs = (preferences || {}).deep_dup
+ # Locked so sections collapsed in quick succession don't overwrite each other.
+ with_locked_preferences do |updated_prefs|
if prefs["section_order"]
prefs = prefs.merge("section_order" => keep_hidden_sections_in_order(prefs["section_order"], laid_out_order || dashboard_section_order))
end
@@ -707,8 +739,6 @@ class User < ApplicationRecord
updated_prefs[key] = value
end
end
-
- update!(preferences: updated_prefs)
end
end
@@ -722,11 +752,7 @@ class User < ApplicationRecord
end
def update_reports_preferences(prefs)
- # Use pessimistic locking to ensure atomic read-modify-write
- transaction do
- lock!
-
- updated_prefs = (preferences || {}).deep_dup
+ with_locked_preferences do |updated_prefs|
prefs.each do |key, value|
if value.is_a?(Hash)
updated_prefs[key] ||= {}
@@ -735,8 +761,6 @@ class User < ApplicationRecord
updated_prefs[key] = value
end
end
-
- update!(preferences: updated_prefs)
end
end
diff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erb
index dd4664bf06..c29233fcfc 100644
--- a/app/views/accounts/_account_sidebar_tabs.html.erb
+++ b/app/views/accounts/_account_sidebar_tabs.html.erb
@@ -4,12 +4,17 @@
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_v4",
+ account_sidebar_tabs_cache_key ("account_sidebar_tabs_v5",
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. %>
<% cache account_sidebar_tabs_cache_key(family: family, active_tab: active_tab, mobile: mobile), expires_in: 12.hours, skip_digest: true do %>
-<div id="account-sidebar-tabs">
+<% sortable = Current.user&.account_order&.manual? %>
+<%= tag.div id: "account-sidebar-tabs",
+ data: sortable ? {
+ controller: "account-sort-mode",
+ action: "turbo:morph@window->account-sort-mode#render"
+ } : {} do %>
<% if family.missing_data_provider? %>
<div class="mb-3">
<%= render DS::Alert.new(title: t("accounts.sidebar.missing_data"), variant: :warning) do %>
@@ -38,6 +43,8 @@
class: "flex-1 justify-start"
) %>
+ <%= render "accounts/sort_mode_toggle", sortable: sortable && family.balance_sheet.assets.account_groups.any? %>
+
<%= render DS::ExpandToggle.new(
expand_label: t("accounts.sidebar.expand_all"),
collapse_label: t("accounts.sidebar.collapse_all"),
@@ -46,9 +53,11 @@
) %>
</div>
+ <%= render "accounts/sort_mode_bar", sortable: sortable && family.balance_sheet.assets.account_groups.any? %>
+
<div>
<% family.balance_sheet.assets.account_groups.each do |group| %>
- <%= render "accounts/accountable_group", account_group: group, mobile: mobile %>
+ <%= render "accounts/accountable_group", account_group: group, mobile: mobile, sortable: sortable %>
<% end %>
</div>
</div>
@@ -66,6 +75,8 @@
class: "flex-1 justify-start"
) %>
+ <%= render "accounts/sort_mode_toggle", sortable: sortable && family.balance_sheet.liabilities.account_groups.any? %>
+
<%= render DS::ExpandToggle.new(
expand_label: t("accounts.sidebar.expand_all"),
collapse_label: t("accounts.sidebar.collapse_all"),
@@ -74,9 +85,11 @@
) %>
</div>
+ <%= render "accounts/sort_mode_bar", sortable: sortable && family.balance_sheet.liabilities.account_groups.any? %>
+
<div>
<% family.balance_sheet.liabilities.account_groups.each do |group| %>
- <%= render "accounts/accountable_group", account_group: group, mobile: mobile %>
+ <%= render "accounts/accountable_group", account_group: group, mobile: mobile, sortable: sortable %>
<% end %>
</div>
</div>
@@ -94,6 +107,8 @@
class: "flex-1 justify-start"
) %>
+ <%= render "accounts/sort_mode_toggle", sortable: sortable && family.balance_sheet.account_groups.any? %>
+
<%= render DS::ExpandToggle.new(
expand_label: t("accounts.sidebar.expand_all"),
collapse_label: t("accounts.sidebar.collapse_all"),
@@ -102,15 +117,17 @@
) %>
</div>
+ <%= render "accounts/sort_mode_bar", sortable: sortable && family.balance_sheet.account_groups.any? %>
+
<div>
<% family.balance_sheet.account_groups.each do |group| %>
- <%= render "accounts/accountable_group", account_group: group, mobile: mobile, all_tab: true %>
+ <%= render "accounts/accountable_group", account_group: group, mobile: mobile, all_tab: true, sortable: sortable %>
<% end %>
</div>
</div>
<% end %>
<% end %>
-</div>
+<% end %>
<script nonce="<%= content_security_policy_nonce %>">
// Expand/Collapse all for the account sidebar. Event-delegated on document
// so it works for both the desktop and mobile sidebar instances and survives
diff --git a/app/views/accounts/_accountable_group.html.erb b/app/views/accounts/_accountable_group.html.erb
index ce44bc98b8..61d9b7b09c 100644
--- a/app/views/accounts/_accountable_group.html.erb
+++ b/app/views/accounts/_accountable_group.html.erb
@@ -1,4 +1,4 @@
-<%# locals: (account_group:, mobile: false, all_tab: false, open: nil, **args) %>
+<%# 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 %>">
<% is_open = open.nil? ? (account_group.accounts.any? { |account| page_active?(account_path(account)) } || Current.user.always_expanded_account_group?(account_group.key)) : open %>
@@ -24,11 +24,43 @@
</div>
<% end %>
- <div class="space-y-1">
+ <%= tag.div class: "space-y-1",
+ data: sortable ? {
+ controller: "sortable-list",
+ sortable_list_url_value: reorder_accounts_path(group: account_group.key),
+ sortable_list_param_value: "account_ids",
+ sortable_list_hold_delay_value: 400,
+ sortable_list_save_timeout_value: 10_000,
+ sortable_list_mirror_lists_value: true,
+ action: "dragover->sortable-list#dragOver drop->sortable-list#drop account-sort-mode:stop@window->sortable-list#releaseKeyboardGrab turbo:before-visit@window->sortable-list#saveBeforeVisit"
+ } : {} do %>
<% account_group.accounts.each do |account| %>
+ <%# Rows become draggable only in sort mode (account-sort-mode). %>
+ <%= tag.div class: "flex items-center gap-1 rounded-lg",
+ data: sortable ? {
+ sortable_list_target: "item",
+ sortable_list_id: account.id,
+ action: "dragstart->sortable-list#dragStart dragend->sortable-list#dragEnd"
+ } : {} do %>
+ <% if sortable %>
+ <%# Hidden until the sidebar is in sort mode (account-sort-mode). %>
+ <%= render DS::Button.new(
+ variant: :icon,
+ icon: "grip-vertical",
+ size: :sm,
+ style: "display:none",
+ class: "shrink-0 cursor-grab active:cursor-grabbing touch-none [-webkit-touch-callout:none]",
+ aria_label: t("accounts.sidebar.reorder_account", account: account.name),
+ title: t("accounts.sidebar.reorder_hint"),
+ data: {
+ account_sort_mode_target: "handle",
+ action: "touchstart->sortable-list#touchStart touchmove->sortable-list#touchMove touchend->sortable-list#touchEnd touchcancel->sortable-list#touchCancel contextmenu->sortable-list#suppressContextMenu keydown->sortable-list#handleKeyDown"
+ }
+ ) %>
+ <% end %>
<%= link_to account_path(account),
class: class_names(
- "block flex items-center gap-2 px-3 py-2 rounded-lg",
+ "block flex items-center gap-2 px-3 py-2 rounded-lg min-w-0 grow",
page_active?(account_path(account)) ? "bg-container" : "hover:bg-surface-hover"
),
data: page_active?(account_path(account)) ? { active_account: true } : {},
@@ -57,8 +89,9 @@
<% end %>
</div>
<% end %>
+ <% end %>
<% end %>
- </div>
+ <% end %>
<div class="my-2">
<%= render DS::Link.new(
diff --git a/app/views/accounts/_sort_mode_bar.html.erb b/app/views/accounts/_sort_mode_bar.html.erb
new file mode 100644
index 0000000000..636b8fd0d4
--- /dev/null
+++ b/app/views/accounts/_sort_mode_bar.html.erb
@@ -0,0 +1,16 @@
+<%# locals: (sortable:) %>
+
+<% if sortable %>
+ <%= tag.div class: "flex items-center gap-2 rounded-lg bg-container px-3 py-2",
+ style: "display:none",
+ data: { account_sort_mode_target: "bar" } do %>
+ <p class="grow text-xs text-secondary"><%= t("accounts.sidebar.sort_mode.hint") %></p>
+ <%= render DS::Button.new(
+ variant: :outline,
+ size: :sm,
+ text: t("accounts.sidebar.sort_mode.done"),
+ class: "shrink-0",
+ data: { action: "account-sort-mode#stop" }
+ ) %>
+ <% end %>
+<% end %>
diff --git a/app/views/accounts/_sort_mode_toggle.html.erb b/app/views/accounts/_sort_mode_toggle.html.erb
new file mode 100644
index 0000000000..961f566147
--- /dev/null
+++ b/app/views/accounts/_sort_mode_toggle.html.erb
@@ -0,0 +1,18 @@
+<%# locals: (sortable:) %>
+
+<%# Shown only with the manual account order. Switches the sidebar into sort
+ mode, the only time the drag handles are visible. %>
+<% if sortable %>
+ <%= render DS::Button.new(
+ variant: :outline,
+ size: :md,
+ icon: "arrow-up-down",
+ class: "shrink-0 aria-pressed:bg-surface-inset",
+ title: t("accounts.sidebar.sort_mode.start"),
+ aria: { label: t("accounts.sidebar.sort_mode.start"), pressed: "false" },
+ data: {
+ account_sort_mode_target: "toggle",
+ action: "account-sort-mode#toggle"
+ }
+ ) %>
+<% end %>
diff --git a/app/views/settings/appearances/show.html.erb b/app/views/settings/appearances/show.html.erb
index ac09a58dc5..94140313fd 100644
--- a/app/views/settings/appearances/show.html.erb
+++ b/app/views/settings/appearances/show.html.erb
@@ -30,6 +30,14 @@
<%= settings_section title: t(".dashboard_title"), subtitle: t(".dashboard_subtitle") do %>
<div>
+ <%= styled_form_with model: @user, url: settings_appearance_path, method: :patch,
+ class: "p-3",
+ data: { controller: "auto-submit-form" } do |form| %>
+ <%= form.select :default_account_order,
+ AccountOrder.all.map { |order| [ order.label, order.key ] },
+ { label: t("settings.preferences.show.default_account_order"), help_text: t("settings.preferences.show.default_account_order_hint") },
+ { data: { auto_submit_form_target: "auto" } } %>
+ <% end %>
<%= form_with url: settings_appearance_path, method: :patch,
class: "p-3 space-y-4",
data: { controller: "auto-submit-form" } do |f| %>
diff --git a/app/views/settings/preferences/show.html.erb b/app/views/settings/preferences/show.html.erb
index fd997dd44f..03372def8c 100644
--- a/app/views/settings/preferences/show.html.erb
+++ b/app/views/settings/preferences/show.html.erb
@@ -16,10 +16,6 @@
Family::DATE_FORMATS,
{ label: t(".date_format") },
{ data: { auto_submit_form_target: "auto" } } %>
- <%= form.select :default_account_order,
- AccountOrder.all.map { |order| [ order.label, order.key ] },
- { label: t(".default_account_order") },
- { data: { auto_submit_form_target: "auto" } } %>
<%= family_form.collection_select :country,
country_options,
:last,
diff --git a/config/locales/models/account/de.yml b/config/locales/models/account/de.yml
index 9bba647839..74fa10bb03 100644
--- a/config/locales/models/account/de.yml
+++ b/config/locales/models/account/de.yml
@@ -26,6 +26,9 @@ de:
balance_desc:
label: Saldo (absteigend)
label_short: Saldo ↓
+ manual:
+ label: Manuell (per Ziehen sortieren)
+ label_short: Manuell
name_asc:
label: Name (A–Z)
label_short: Name ↑
diff --git a/config/locales/models/account/en.yml b/config/locales/models/account/en.yml
index df47d3302b..e7ca999cb3 100644
--- a/config/locales/models/account/en.yml
+++ b/config/locales/models/account/en.yml
@@ -7,6 +7,9 @@ en:
balance_desc:
label: Balance (High to Low)
label_short: Balance ↓
+ manual:
+ label: Manual (drag to reorder)
+ label_short: Manual
name_asc:
label: Name (A-Z)
label_short: Name ↑
diff --git a/config/locales/views/accounts/de.yml b/config/locales/views/accounts/de.yml
index df2ea96325..878f5214c2 100644
--- a/config/locales/views/accounts/de.yml
+++ b/config/locales/views/accounts/de.yml
@@ -135,6 +135,12 @@ de:
new_debt: Neue Verbindlichkeit
new_account: Neues Konto
new_account_group: "Neue %{account_group}"
+ reorder_account: "%{account} verschieben"
+ reorder_hint: Zum Umsortieren ziehen. Mit der Tastatur Enter drücken, dann die Pfeiltasten.
+ sort_mode:
+ start: Konten sortieren
+ hint: Konten am Griff an ihre Stelle ziehen.
+ done: Fertig
types:
depository: Bankkonto
investment: Investment
diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.yml
index 5db8310a9e..7448bf64c1 100644
--- a/config/locales/views/accounts/en.yml
+++ b/config/locales/views/accounts/en.yml
@@ -151,6 +151,12 @@ en:
new_account_group: "New %{account_group}"
expand_all: Expand all
collapse_all: Collapse all
+ reorder_account: "Move %{account}"
+ reorder_hint: Drag to reorder. With the keyboard, press Enter, then the arrow keys.
+ sort_mode:
+ start: Sort accounts
+ hint: Drag accounts by their handle to reorder them.
+ done: Done
types:
depository: Cash
investment: Investment
diff --git a/config/locales/views/settings/de.yml b/config/locales/views/settings/de.yml
index 32201cd347..ba8917fef0 100644
--- a/config/locales/views/settings/de.yml
+++ b/config/locales/views/settings/de.yml
@@ -49,6 +49,7 @@ de:
general_title: Allgemein
default_period: Standardzeitraum
default_account_order: Standardreihenfolge der Konten
+ default_account_order_hint: Bei „Manuell“ ziehst du die Konten in der Seitenleiste in die gewünschte Reihenfolge.
language: Sprache
language_auto: Browsersprache
page_title: Einstellungen
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index ea9a12735b..6920d94c32 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -197,6 +197,7 @@ en:
general_title: General
default_period: Default Period
default_account_order: Default Account Order
+ default_account_order_hint: With Manual, drag accounts in the sidebar to set their order.
language: Language
language_auto: Browser language
page_title: Preferences
diff --git a/config/routes.rb b/config/routes.rb
index 69ca172238..09f126aa8d 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -677,6 +677,7 @@ Rails.application.routes.draw do
collection do
post :sync_all
+ patch :reorder
end
resource :sharing, only: [ :show, :update ], controller: "account_sharings"
diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rb
index 01456273fd..5668ea3976 100644
--- a/test/controllers/accounts_controller_test.rb
+++ b/test/controllers/accounts_controller_test.rb
@@ -1244,6 +1244,40 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 0
end
+ test "reorder saves the manual order of one account group" do
+ # Same shape as the sidebar's sortable-list: group in the URL, ids in the body.
+ patch reorder_accounts_url(group: "depository"), params: { account_ids: [ accounts(:connected).id, @account.id ] }, as: :json
+
+ assert_response :success
+ assert_equal [ accounts(:connected).id, @account.id ], @user.reload.manual_account_order["depository"]
+ end
+
+ test "reorder drops accounts from another family" do
+ foreign = families(:empty).accounts.create!(name: "Foreign", currency: "USD", balance: 0, accountable: Depository.new, owner: users(:empty))
+
+ patch reorder_accounts_url, params: { group: "depository", account_ids: [ foreign.id, @account.id ] }, as: :json
+
+ assert_response :success
+ assert_equal [ @account.id ], @user.reload.manual_account_order["depository"]
+ end
+
+ test "reorder rejects an unknown group" do
+ patch reorder_accounts_url, params: { group: "not_a_type", account_ids: [ @account.id ] }, as: :json
+
+ assert_response :unprocessable_entity
+ assert_nil @user.reload.manual_account_order["not_a_type"]
+ end
+
+ test "sidebar shows drag handles only with the manual account order" do
+ get account_url(@account)
+ assert_select "[data-controller~='sortable-list']", count: 0
+
+ @user.update!(default_account_order: "manual")
+ get account_url(@account)
+ assert_select "[data-controller~='sortable-list'][data-sortable-list-url-value=?]", reorder_accounts_path(group: "depository")
+ assert_select "[data-sortable-list-target='item'][data-sortable-list-id=?]", @account.id
+ end
+
private
# #3630. Links a shared and an unshared account to +item+ through two fresh
# provider rows built by the block, and returns them in that order. Shares
diff --git a/test/controllers/settings/appearances_account_order_test.rb b/test/controllers/settings/appearances_account_order_test.rb
new file mode 100644
index 0000000000..298d73b034
--- /dev/null
+++ b/test/controllers/settings/appearances_account_order_test.rb
@@ -0,0 +1,31 @@
+require "test_helper"
+
+class Settings::AppearancesAccountOrderTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in @user = users(:family_admin)
+ end
+
+ test "appearance page offers the account order" do
+ get settings_appearance_url
+
+ assert_response :success
+ assert_select "select[name='user[default_account_order]'] option[value='manual']"
+ end
+
+ test "updates the account order and keeps other preferences" do
+ @user.update!(preferences: { "always_expanded_account_groups" => [ "depository" ] })
+
+ patch settings_appearance_url, params: { user: { default_account_order: "manual" } }
+
+ assert_redirected_to settings_appearance_url
+ assert_equal "manual", @user.reload.default_account_order
+ assert_equal [ "depository" ], @user.always_expanded_account_groups
+ end
+
+ test "ignores an unknown account order" do
+ patch settings_appearance_url, params: { user: { default_account_order: "bogus" } }
+
+ assert_redirected_to settings_appearance_url
+ assert_equal "name_asc", @user.reload.default_account_order
+ end
+end
diff --git a/test/helpers/accounts_helper_test.rb b/test/helpers/accounts_helper_test.rb
new file mode 100644
index 0000000000..20fdd28f53
--- /dev/null
+++ b/test/helpers/accounts_helper_test.rb
@@ -0,0 +1,33 @@
+require "test_helper"
+
+class AccountsHelperTest < ActionView::TestCase
+ setup do
+ @user = users(:family_admin)
+ Current.session = @user.sessions.create!
+ end
+
+ teardown { Current.session = nil }
+
+ test "sidebar cache key changes with the account order" do
+ @user.update!(default_account_order: "name_asc")
+ name_key = sidebar_key
+
+ @user.update!(default_account_order: "balance_desc")
+
+ assert_not_equal name_key, sidebar_key
+ end
+
+ test "sidebar cache key changes when the manual order changes" do
+ @user.update!(default_account_order: "manual")
+ before = sidebar_key
+
+ @user.update_manual_account_order("depository", [ accounts(:connected).id, accounts(:depository).id ])
+
+ assert_not_equal before, sidebar_key
+ end
+
+ private
+ def sidebar_key
+ account_sidebar_tabs_cache_key(family: @user.family, active_tab: "all", mobile: false)
+ end
+end
diff --git a/test/models/balance_sheet_test.rb b/test/models/balance_sheet_test.rb
index 0351c5308f..7f188e19c1 100644
--- a/test/models/balance_sheet_test.rb
+++ b/test/models/balance_sheet_test.rb
@@ -205,6 +205,24 @@ class BalanceSheetTest < ActiveSupport::TestCase
assert_equal 3000 + 5000, liability_groups.find { |ag| ag.name == OtherLiability.display_name }.total
end
+ test "sorts accounts in the user's manual order, new accounts last alphabetically" do
+ user = users(:empty)
+ user.update!(default_account_order: "manual")
+ checking = create_account(name: "Checking", balance: 0, accountable: Depository.new, owner: user)
+ savings = create_account(name: "Savings", balance: 0, accountable: Depository.new, owner: user)
+ create_account(name: "Brokerage", balance: 0, accountable: Depository.new, owner: user)
+ create_account(name: "Another", balance: 0, accountable: Depository.new, owner: user)
+ card = create_account(name: "Card", balance: 0, accountable: CreditCard.new, owner: user)
+
+ user.update_manual_account_order("depository", [ savings.id, checking.id ])
+ user.update_manual_account_order("credit_card", [ card.id ])
+
+ balance_sheet = BalanceSheet.new(@family, user: user)
+
+ assert_equal %w[Savings Checking Another Brokerage], balance_sheet.assets.account_groups.first.accounts.map(&:name)
+ assert_equal %w[Card], balance_sheet.liabilities.account_groups.first.accounts.map(&:name)
+ end
+
private
def create_account(attributes = {})
account = @family.accounts.create! name: "Test", currency: "USD", **attributes
diff --git a/test/models/user_test.rb b/test/models/user_test.rb
index 20a4d84e5e..286ad764ff 100644
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -1369,4 +1369,39 @@ class UserTest < ActiveSupport::TestCase
assert token.reload.revoked_at.present?
assert grant.reload.revoked_at.present?
end
+
+ test "update_manual_account_order keeps other groups and only accessible accounts" do
+ @user.update_manual_account_order("credit_card", [ accounts(:credit_card).id ])
+ foreign = families(:empty).accounts.create!(name: "Foreign", currency: "USD", balance: 0, accountable: Depository.new, owner: users(:empty))
+
+ assert @user.update_manual_account_order("depository", [ accounts(:connected).id, foreign.id, accounts(:depository).id, "not-a-uuid" ])
+
+ order = @user.reload.manual_account_order
+ assert_equal [ accounts(:connected).id, accounts(:depository).id ], order["depository"]
+ assert_equal [ accounts(:credit_card).id ], order["credit_card"]
+ end
+
+ test "update_manual_account_order drops family accounts not shared with the user" do
+ unshared = families(:dylan_family).accounts.create!(name: "Unshared", currency: "USD", balance: 0, accountable: Depository.new, owner: users(:family_member))
+
+ assert @user.update_manual_account_order("depository", [ unshared.id, accounts(:depository).id ])
+
+ assert_equal [ accounts(:depository).id ], @user.reload.manual_account_order["depository"]
+ end
+
+ test "update_manual_account_order drops accounts from another group" do
+ @user.update_manual_account_order("depository", [ accounts(:credit_card).id, accounts(:depository).id ])
+
+ assert_equal [ accounts(:depository).id ], @user.reload.manual_account_order["depository"]
+ end
+
+ test "update_manual_account_order rejects account ids that are not a list" do
+ assert_not @user.update_manual_account_order("depository", { "0" => accounts(:depository).id })
+ assert_equal({}, @user.reload.manual_account_order)
+ end
+
+ test "update_manual_account_order rejects unknown groups" do
+ assert_not @user.update_manual_account_order("transactions", [ accounts(:depository).id ])
+ assert_equal({}, @user.reload.manual_account_order)
+ end
end
diff --git a/test/system/account_manual_order_test.rb b/test/system/account_manual_order_test.rb
new file mode 100644
index 0000000000..90895cf909
--- /dev/null
+++ b/test/system/account_manual_order_test.rb
@@ -0,0 +1,249 @@
+require "application_system_test_case"
+
+class AccountManualOrderTest < ApplicationSystemTestCase
+ setup do
+ @user = users(:family_admin)
+ @user.update!(default_account_order: "manual")
+ sign_in @user
+ end
+
+ test "moving an account with the keyboard saves the new order" do
+ checking = accounts(:depository)
+ plaid = accounts(:connected)
+
+ visit account_path(checking)
+ open_groups_before = open_group_count
+
+ within_testid("account-sidebar-tabs") do
+ assert_equal [ checking.id, plaid.id ], visible_depository_ids.first(2)
+ assert_no_selector "[data-sortable-list-target='item'] button", visible: true
+
+ find("button[aria-label='#{I18n.t("accounts.sidebar.sort_mode.start")}']", visible: true).click
+
+ handle = find("[data-sortable-list-target='item'][data-sortable-list-id='#{plaid.id}'] button")
+ handle.send_keys(:enter)
+ handle.send_keys(:up)
+ handle.send_keys(:enter)
+
+ assert_equal [ plaid.id, checking.id ], visible_depository_ids.first(2)
+ end
+
+ assert_eventually { @user.reload.manual_account_order["depository"]&.first(2) == [ plaid.id, checking.id ] }
+
+ within_testid("account-sidebar-tabs") do
+ click_button I18n.t("accounts.sidebar.sort_mode.done")
+ assert_no_selector "[data-sortable-list-target='item'] button", visible: true
+ end
+ # Groups opened for sort mode close again.
+ assert_equal open_groups_before, open_group_count
+
+ visit account_path(checking)
+ within_testid("account-sidebar-tabs") do
+ assert_equal [ plaid.id, checking.id ], visible_depository_ids.first(2)
+ end
+ end
+
+ test "leaving sort mode saves a row still held with the keyboard" do
+ checking = accounts(:depository)
+ plaid = accounts(:connected)
+
+ visit account_path(checking)
+
+ within_testid("account-sidebar-tabs") do
+ find("button[aria-label='#{I18n.t("accounts.sidebar.sort_mode.start")}']", visible: true).click
+
+ handle = find("[data-sortable-list-target='item'][data-sortable-list-id='#{plaid.id}'] button")
+ handle.send_keys(:enter)
+ handle.send_keys(:up)
+
+ click_button I18n.t("accounts.sidebar.sort_mode.done")
+ end
+
+ assert_eventually { @user.reload.manual_account_order["depository"]&.first(2) == [ plaid.id, checking.id ] }
+ end
+
+ test "following an account link saves a row still held with the keyboard" do
+ checking = accounts(:depository)
+ plaid = accounts(:connected)
+
+ visit account_path(checking)
+
+ within_testid("account-sidebar-tabs") do
+ find("button[aria-label='#{I18n.t("accounts.sidebar.sort_mode.start")}']", visible: true).click
+
+ handle = find("[data-sortable-list-target='item'][data-sortable-list-id='#{plaid.id}'] button")
+ handle.send_keys(:enter)
+ handle.send_keys(:up)
+
+ find("[data-sortable-list-target='item'][data-sortable-list-id='#{plaid.id}'] a[href='#{account_path(plaid)}']").click
+ end
+
+ assert_current_path account_path(plaid)
+ assert_eventually { @user.reload.manual_account_order["depository"]&.first(2) == [ plaid.id, checking.id ] }
+ within_testid("account-sidebar-tabs") do
+ assert_equal [ plaid.id, checking.id ], visible_depository_ids.first(2)
+ end
+ end
+
+ test "leaving sort mode keeps focus in the sidebar when no sort toggle is visible" do
+ visit account_path(accounts(:depository))
+
+ within_testid("account-sidebar-tabs") do
+ find("button[aria-label='#{I18n.t("accounts.sidebar.sort_mode.start")}']", visible: true).click
+ end
+
+ # Like a tab that renders no sort toggle: nothing visible to return to.
+ page.execute_script(<<~JS)
+ document.querySelectorAll("[data-account-sort-mode-target='toggle']").forEach((toggle) => {
+ toggle.style.display = "none";
+ });
+ JS
+
+ within_testid("account-sidebar-tabs") do
+ click_button I18n.t("accounts.sidebar.sort_mode.done")
+ end
+
+ assert evaluate_script(<<~JS), "focus fell back to the page body"
+ document.activeElement.closest("[data-controller~='account-sort-mode']") !== null
+ JS
+ end
+
+ test "a stalled save times out and reloads the saved order" do
+ checking = accounts(:depository)
+ plaid = accounts(:connected)
+
+ visit account_path(checking)
+
+ # Order saves never answer, like a dropped mobile connection; they only
+ # end when the caller aborts them. Page loads still go through.
+ page.execute_script(<<~JS)
+ window.realFetch = window.fetch;
+ window.fetch = (url, options = {}) => {
+ if (!String(url).includes("/accounts/reorder")) return window.realFetch(url, options);
+ return new Promise((resolve, reject) => {
+ options.signal?.addEventListener("abort", () => reject(options.signal.reason));
+ });
+ };
+ document.querySelectorAll("[data-controller~='sortable-list']").forEach((list) => {
+ list.setAttribute("data-sortable-list-save-timeout-value", "1500");
+ });
+ JS
+
+ within_testid("account-sidebar-tabs") do
+ find("button[aria-label='#{I18n.t("accounts.sidebar.sort_mode.start")}']", visible: true).click
+
+ handle = find("[data-sortable-list-target='item'][data-sortable-list-id='#{plaid.id}'] button")
+ handle.send_keys(:enter)
+ handle.send_keys(:up)
+ handle.send_keys(:enter)
+
+ assert_equal [ plaid.id, checking.id ], visible_depository_ids.first(2)
+ end
+
+ # The failed save reloads the page, which shows the order actually saved.
+ # The reload renders the whole page, which can take several seconds on CI.
+ assert_eventually(timeout: 15) do
+ within_testid("account-sidebar-tabs") { visible_depository_ids.first(2) == [ checking.id, plaid.id ] }
+ end
+
+ assert_nil @user.reload.manual_account_order["depository"]
+ end
+
+ test "a move is mirrored in the other sidebar tabs" do
+ checking = accounts(:depository)
+ plaid = accounts(:connected)
+
+ visit account_path(checking)
+
+ within_testid("account-sidebar-tabs") do
+ find("button[aria-label='#{I18n.t("accounts.sidebar.sort_mode.start")}']", visible: true).click
+
+ handle = find("[data-sortable-list-target='item'][data-sortable-list-id='#{plaid.id}'] button")
+ handle.send_keys(:enter)
+ handle.send_keys(:up)
+ handle.send_keys(:enter)
+ end
+
+ lists = all("[data-sortable-list-url-value='#{reorder_accounts_path(group: "depository")}']", visible: :all)
+ assert_operator lists.size, :>, 1
+ lists.each do |list|
+ ids = list.all("[data-sortable-list-target='item']", visible: :all).map { |item| item["data-sortable-list-id"] }
+ assert_equal [ plaid.id, checking.id ], ids.first(2)
+ end
+ end
+
+ test "a sync refresh waits while a row is held, even after focus left it" do
+ checking = accounts(:depository)
+ plaid = accounts(:connected)
+
+ visit account_path(checking)
+
+ within_testid("account-sidebar-tabs") do
+ find("button[aria-label='#{I18n.t("accounts.sidebar.sort_mode.start")}']", visible: true).click
+
+ handle = find("[data-sortable-list-target='item'][data-sortable-list-id='#{plaid.id}'] button")
+ handle.send_keys(:enter)
+ handle.send_keys(:up)
+ end
+
+ # The toast a finished sync broadcasts; it would morph-refresh the page.
+ # Focus has moved on, as after a touch drag or a click elsewhere.
+ page.execute_script(<<~JS)
+ document.activeElement.blur();
+ const toast = document.createElement("div");
+ toast.dataset.controller = "sync-toast";
+ toast.dataset.syncToastAutoRefreshDelayValue = "100";
+ document.body.appendChild(toast);
+ JS
+ sleep 1
+
+ within_testid("account-sidebar-tabs") do
+ assert_equal [ plaid.id, checking.id ], visible_depository_ids.first(2)
+ click_button I18n.t("accounts.sidebar.sort_mode.done")
+ end
+
+ assert_eventually { @user.reload.manual_account_order["depository"]&.first(2) == [ plaid.id, checking.id ] }
+ end
+
+ test "a drag outside sort mode does not move a row" do
+ checking = accounts(:depository)
+ plaid = accounts(:connected)
+
+ visit account_path(checking)
+
+ # Like dragging an account logo or selected text: the drag starts inside
+ # a row that is not draggable and is dropped at the top of the list.
+ page.execute_script(<<~JS, plaid.id)
+ const row = document.querySelector(`[data-sortable-list-target='item'][data-sortable-list-id='${arguments[0]}']`);
+ const list = row.closest("[data-controller~='sortable-list']");
+ const dataTransfer = new DataTransfer();
+ row.querySelector("a").dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer }));
+ list.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer, clientY: 0 }));
+ list.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer, clientY: 0 }));
+ JS
+
+ within_testid("account-sidebar-tabs") do
+ assert_equal [ checking.id, plaid.id ], visible_depository_ids.first(2)
+ end
+ assert_nil @user.reload.manual_account_order["depository"]
+ end
+
+ private
+ def open_group_count
+ evaluate_script("document.querySelectorAll(\"[data-testid='account-sidebar-tabs'] details[open]\").length")
+ end
+
+ def visible_depository_ids
+ list = all("[data-sortable-list-url-value='#{reorder_accounts_path(group: "depository")}']", visible: true).first
+ list.all("[data-sortable-list-target='item']").map { |item| item["data-sortable-list-id"] }
+ end
+
+ def assert_eventually(timeout: 5)
+ deadline = Time.current + timeout
+ until yield
+ flunk "condition not met within #{timeout}s" if Time.current > deadline
+ sleep 0.1
+ end
+ pass
+ end
+end