The personal finance app for everyone (by everyone)
Ruby
Move dashboard reordering onto the shared sortable-list controller (#4334)
GFR8874f37362f2
diff --git a/app/javascript/controllers/dashboard_masonry_controller.js b/app/javascript/controllers/dashboard_masonry_controller.jsindex 99c2343b19..9e1c8cc79f 100644--- a/app/javascript/controllers/dashboard_masonry_controller.js+++ b/app/javascript/controllers/dashboard_masonry_controller.js@@ -6,7 +6,7 @@ import { Controller } from "@hotwired/stimulus";// single-column mode it clears the spans and normal block flow takes over.//// The DOM stays a single flat list of <section data-section-key> children, so-// the dashboard-sortable controller (drag / keyboard reorder) is unaffected —+// the sortable-list controller (drag / keyboard reorder) is unaffected —// reordering just moves a node and the CSS re-packs.export default class extends Controller {connect() {diff --git a/app/javascript/controllers/dashboard_sortable_controller.js b/app/javascript/controllers/dashboard_sortable_controller.jsdeleted file mode 100644index 64fb845e47..0000000000--- a/app/javascript/controllers/dashboard_sortable_controller.js+++ /dev/null@@ -1,375 +0,0 @@-import { Controller } from "@hotwired/stimulus";--export default class extends Controller {- static targets = ["section", "handle"];-- // Hold delay to require deliberate press-and-hold before activating drag mode- static values = {- holdDelay: { type: Number, default: 800 },- };-- connect() {- this.draggedElement = null;- this.placeholder = null;- this.touchStartY = 0;- this.currentTouchX = 0;- this.currentTouchY = 0;- this.isTouching = false;- this.keyboardGrabbedElement = null;- this.holdTimer = null;- this.holdActivated = false;- }-- // ===== Mouse Drag Events =====- dragStart(event) {- // 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.- if (this.isTouching || this.pendingSection) {- event.preventDefault();- return;- }-- this.draggedElement = event.currentTarget;- this.draggedElement.classList.add("opacity-50");- this.draggedElement.setAttribute("aria-grabbed", "true");- event.dataTransfer.effectAllowed = "move";- }-- dragEnd(event) {- event.currentTarget.classList.remove("opacity-50");- event.currentTarget.setAttribute("aria-grabbed", "false");- this.clearPlaceholders();- }-- dragOver(event) {- event.preventDefault();- event.dataTransfer.dropEffect = "move";-- const afterElement = this.getDragAfterElement(event.clientX, event.clientY);- const container = this.element;-- this.clearPlaceholders();-- if (afterElement == null) {- this.showPlaceholder(container.lastElementChild, "after");- } else {- this.showPlaceholder(afterElement, "before");- }- }-- drop(event) {- event.preventDefault();- event.stopPropagation();-- const afterElement = this.getDragAfterElement(event.clientX, event.clientY);- const container = this.element;-- if (afterElement == null) {- container.appendChild(this.draggedElement);- } else {- container.insertBefore(this.draggedElement, afterElement);- }-- this.clearPlaceholders();- this.saveOrder();- }-- // ===== Touch Events =====- // Touch events are bound to the drag handle only, with a short hold delay- // to prevent accidental touches.-- touchStart(event) {- // Find the parent section element from the handle- const section = event.currentTarget.closest(- "[data-dashboard-sortable-target='section']",- );- if (!section) return;-- // Respect strict draggable="false" which might be set by other controllers (e.g. expand-controller)- if (section.getAttribute("draggable") === "false") return;-- this.pendingSection = section;- this.touchStartX = event.touches[0].clientX;- this.touchStartY = event.touches[0].clientY;- this.currentTouchX = this.touchStartX;- this.currentTouchY = this.touchStartY;- this.holdActivated = false;-- // Prevent text selection while waiting for hold to activate- section.style.userSelect = "none";- section.style.webkitUserSelect = "none";-- // Start hold timer- this.holdTimer = setTimeout(() => {- this.activateDrag();- }, this.holdDelayValue);- }-- activateDrag() {- if (!this.pendingSection) return;-- this.holdActivated = true;- this.isTouching = true;- this.draggedElement = this.pendingSection;- this.draggedElement.classList.add("opacity-50", "scale-[1.02]");- this.draggedElement.setAttribute("aria-grabbed", "true");-- // Haptic feedback if available- if (navigator.vibrate) {- navigator.vibrate(30);- }- }-- touchMove(event) {- const touchX = event.touches[0].clientX;- const touchY = event.touches[0].clientY;-- // If hold hasn't activated yet, cancel if user moves too far (scrolling or swiping)- // Uses Euclidean distance to catch diagonal gestures too- if (!this.holdActivated) {- const dx = touchX - this.touchStartX;- const dy = touchY - this.touchStartY;- if (dx * dx + dy * dy > 100) { // 10px radius- this.cancelHold();- }- return;- }-- if (!this.isTouching || !this.draggedElement) return;-- event.preventDefault();- this.currentTouchX = touchX;- this.currentTouchY = touchY;-- const afterElement = this.getDragAfterElement(this.currentTouchX, this.currentTouchY);- this.clearPlaceholders();-- if (afterElement == null) {- this.showPlaceholder(this.element.lastElementChild, "after");- } else {- this.showPlaceholder(afterElement, "before");- }- }-- touchEnd() {- this.cancelHold();-- if (!this.holdActivated || !this.isTouching || !this.draggedElement) {- this.resetTouchState();- return;- }-- const afterElement = this.getDragAfterElement(this.currentTouchX, this.currentTouchY);- const container = this.element;-- if (afterElement == null) {- container.appendChild(this.draggedElement);- } else {- container.insertBefore(this.draggedElement, afterElement);- }-- this.draggedElement.classList.remove("opacity-50", "scale-[1.02]");- this.draggedElement.setAttribute("aria-grabbed", "false");- this.clearPlaceholders();- this.saveOrder();-- this.resetTouchState();- }-- cancelHold() {- if (this.holdTimer) {- clearTimeout(this.holdTimer);- this.holdTimer = null;- }- }-- resetTouchState() {- // Restore text selection- if (this.pendingSection) {- this.pendingSection.style.userSelect = "";- this.pendingSection.style.webkitUserSelect = "";- }- if (this.draggedElement) {- this.draggedElement.style.userSelect = "";- this.draggedElement.style.webkitUserSelect = "";- }-- this.isTouching = false;- this.draggedElement = null;- this.pendingSection = null;- this.holdActivated = false;- }-- // ===== Keyboard Navigation =====- handleKeyDown(event) {- const currentSection = event.currentTarget;- // Keys pressed on a control inside the card (a header button, a widget's- // own inputs) belong to that control, not to the reorder grab.- if (event.target !== currentSection) return;-- switch (event.key) {- case "ArrowUp":- event.preventDefault();- if (this.keyboardGrabbedElement === currentSection) {- this.moveUp(currentSection);- }- break;- case "ArrowDown":- event.preventDefault();- if (this.keyboardGrabbedElement === currentSection) {- this.moveDown(currentSection);- }- break;- case "Enter":- case " ":- event.preventDefault();- this.toggleGrabMode(currentSection);- break;- case "Escape":- if (this.keyboardGrabbedElement) {- event.preventDefault();- this.releaseKeyboardGrab();- }- break;- }- }-- toggleGrabMode(section) {- if (this.keyboardGrabbedElement === section) {- this.releaseKeyboardGrab();- } else {- this.grabWithKeyboard(section);- }- }-- grabWithKeyboard(section) {- // Release any previously grabbed element- if (this.keyboardGrabbedElement) {- this.releaseKeyboardGrab();- }-- this.keyboardGrabbedElement = section;- section.setAttribute("aria-grabbed", "true");- section.classList.add("ring-2", "ring-primary", "ring-offset-2");- }-- releaseKeyboardGrab() {- if (this.keyboardGrabbedElement) {- this.keyboardGrabbedElement.setAttribute("aria-grabbed", "false");- this.keyboardGrabbedElement.classList.remove(- "ring-2",- "ring-primary",- "ring-offset-2",- );- this.keyboardGrabbedElement = null;- this.saveOrder();- }- }-- moveUp(section) {- const previousSibling = section.previousElementSibling;- if (previousSibling?.hasAttribute("data-section-key")) {- this.element.insertBefore(section, previousSibling);- section.focus();- }- }-- moveDown(section) {- const nextSibling = section.nextElementSibling;- if (nextSibling?.hasAttribute("data-section-key")) {- this.element.insertBefore(nextSibling, section);- section.focus();- }- }-- getDragAfterElement(pointerX, pointerY) {- const draggableElements = this.sectionTargets.filter(- (section) => section !== this.draggedElement,- );-- if (draggableElements.length === 0) return null;-- let closest = null;- let minDistance = Number.POSITIVE_INFINITY;-- draggableElements.forEach((child) => {- const rect = child.getBoundingClientRect();- const centerX = rect.left + rect.width / 2;- const centerY = rect.top + rect.height / 2;-- const dx = pointerX - centerX;- const dy = pointerY - centerY;- const distance = Math.sqrt(dx * dx + dy * dy);-- if (distance < minDistance) {- minDistance = distance;- closest = child;- }- });-- return closest;- }-- showPlaceholder(element, position) {- if (!element) return;-- if (position === "before") {- element.classList.add("border-t-4", "border-primary");- } else {- element.classList.add("border-b-4", "border-primary");- }- }-- clearPlaceholders() {- this.sectionTargets.forEach((section) => {- section.classList.remove(- "border-t-4",- "border-b-4",- "border-primary",- "border-t-2",- "border-b-2",- );- });- }-- async saveOrder() {- const order = this.sectionTargets.map(- (section) => section.dataset.sectionKey,- );-- // Safely obtain CSRF token- const csrfToken = document.querySelector('meta[name="csrf-token"]');- if (!csrfToken) {- console.error(- "[Dashboard Sortable] CSRF token not found. Cannot save section order.",- );- return;- }-- try {- const response = await fetch("/dashboard/preferences", {- method: "PATCH",- headers: {- "Content-Type": "application/json",- "X-CSRF-Token": csrfToken.content,- },- body: JSON.stringify({ preferences: { section_order: order } }),- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- console.error(- "[Dashboard Sortable] Failed to save section order:",- response.status,- errorData,- );- }- } catch (error) {- console.error(- "[Dashboard Sortable] Network error saving section order:",- error,- );- }- }-}diff --git a/app/javascript/controllers/dashboard_widget_size_controller.js b/app/javascript/controllers/dashboard_widget_size_controller.jsindex 57c87cf5d8..07ead00187 100644--- a/app/javascript/controllers/dashboard_widget_size_controller.js+++ b/app/javascript/controllers/dashboard_widget_size_controller.js@@ -21,7 +21,7 @@ export default class extends Controller {}// Keep Enter/Space/arrow keydowns inside the menu from bubbling to the- // section-level dashboard-sortable handler, which would otherwise hijack them+ // section-level sortable-list handler, which would otherwise hijack them// to toggle keyboard reorder mode.stopKeydown(event) {event.stopPropagation();diff --git a/app/javascript/controllers/sankey_preview_controller.js b/app/javascript/controllers/sankey_preview_controller.jsindex f4111e3946..3bf985bac7 100644--- a/app/javascript/controllers/sankey_preview_controller.js+++ b/app/javascript/controllers/sankey_preview_controller.js@@ -125,9 +125,7 @@ export default class extends Controller {expand() {if (this.state !== "content" || this.expandedDialogTarget.open) return;- this.section = this.element.closest(- "[data-dashboard-sortable-target='section']",- );+ this.section = this.element.closest("[data-sortable-list-target='item']");this.originalDraggable = this.section?.getAttribute("draggable");this.section?.setAttribute("draggable", "false");this.expandedDialogTarget.showModal();diff --git a/app/javascript/controllers/sortable_list_controller.js b/app/javascript/controllers/sortable_list_controller.jsindex fd0afd38ca..3d3c77268c 100644--- a/app/javascript/controllers/sortable_list_controller.js+++ b/app/javascript/controllers/sortable_list_controller.js@@ -6,7 +6,7 @@ import { Controller } from "@hotwired/stimulus";// the ids are sent as JSON to urlValue, nested under paramValue// ("a.b" sends { a: { b: [...] } }).export default class extends Controller {- static targets = ["item", "handle"];+ static targets = ["item"];// Hold delay to require deliberate press-and-hold before activating drag mode.// Lists whose whole item reacts to touch (not just a small grip) should raise@@ -15,6 +15,13 @@ export default class extends Controller {url: String,param: String,holdDelay: { type: Number, default: 150 },+ // 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+ // on its upper half, after it on its lower half.+ dropTarget: { type: String, default: "below" },+ // Leave keys pressed on a control inside an item to that control.+ ownKeysOnly: { type: Boolean, default: false },};connect() {@@ -22,6 +29,7 @@ export default class extends Controller {this.placeholder = null;this.touchStartX = 0;this.touchStartY = 0;+ this.currentTouchX = 0;this.currentTouchY = 0;this.isTouching = false;this.keyboardGrabbedElement = null;@@ -29,6 +37,10 @@ export default class extends Controller {this.holdActivated = false;}+ disconnect() {+ this.cancelHold();+ }+// ===== Mouse Drag Events =====dragStart(event) {// If a touch interaction is in progress, cancel native drag —@@ -49,37 +61,27 @@ export default class extends Controller {event.currentTarget.classList.remove("opacity-50");event.currentTarget.setAttribute("aria-grabbed", "false");this.clearPlaceholders();+ this.draggedElement = null;}+ // 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) {+ if (!this.draggedElement) return;+event.preventDefault();event.dataTransfer.dropEffect = "move";- const afterElement = this.getDragAfterElement(event.clientY);- const container = this.element;-- this.clearPlaceholders();-- if (afterElement == null) {- this.showPlaceholder(container.lastElementChild, "after");- } else {- this.showPlaceholder(afterElement, "before");- }+ this.showDropPosition(event.clientX, event.clientY);}drop(event) {+ if (!this.draggedElement) return;+event.preventDefault();event.stopPropagation();- const afterElement = this.getDragAfterElement(event.clientY);- const container = this.element;-- if (afterElement == null) {- container.appendChild(this.draggedElement);- } else {- container.insertBefore(this.draggedElement, afterElement);- }-+ this.moveDraggedTo(event.clientX, event.clientY);this.clearPlaceholders();this.saveOrder();}@@ -95,9 +97,14 @@ export default class extends Controller {);if (!section) return;+ // Another controller may switch dragging off for a while, e.g. the+ // dashboard Sankey while its expanded view is open.+ if (section.getAttribute("draggable") === "false") return;+this.pendingSection = section;this.touchStartX = event.touches[0].clientX;this.touchStartY = event.touches[0].clientY;+ this.currentTouchX = this.touchStartX;this.currentTouchY = this.touchStartY;this.holdActivated = false;@@ -135,7 +142,8 @@ export default class extends Controller {if (!this.holdActivated) {const dx = touchX - this.touchStartX;const dy = touchY - this.touchStartY;- if (dx * dx + dy * dy > 100) { // 10px radius+ // 10px radius+ if (dx * dx + dy * dy > 100) {this.cancelHold();}return;@@ -144,16 +152,10 @@ export default class extends Controller {if (!this.isTouching || !this.draggedElement) return;event.preventDefault();+ this.currentTouchX = touchX;this.currentTouchY = touchY;- const afterElement = this.getDragAfterElement(this.currentTouchY);- this.clearPlaceholders();-- if (afterElement == null) {- this.showPlaceholder(this.element.lastElementChild, "after");- } else {- this.showPlaceholder(afterElement, "before");- }+ this.showDropPosition(this.currentTouchX, this.currentTouchY);}touchEnd() {@@ -164,14 +166,7 @@ export default class extends Controller {return;}- const afterElement = this.getDragAfterElement(this.currentTouchY);- const container = this.element;-- if (afterElement == null) {- container.appendChild(this.draggedElement);- } else {- container.insertBefore(this.draggedElement, afterElement);- }+ this.moveDraggedTo(this.currentTouchX, this.currentTouchY);this.draggedElement.classList.remove("opacity-50", "scale-[1.02]");this.draggedElement.setAttribute("aria-grabbed", "false");@@ -234,6 +229,9 @@ export default class extends Controller {"[data-sortable-list-target='item']",);if (!currentSection) return;+ // Keys pressed on a control inside the item (a header button, a widget's+ // own inputs) belong to that control, not to the reorder grab.+ if (this.ownKeysOnlyValue && event.target !== event.currentTarget) return;this.keyboardFocusElement = event.currentTarget;switch (event.key) {@@ -317,15 +315,53 @@ export default class extends Controller {}}- getDragAfterElement(y) {- const draggableElements = [- ...this.itemTargets.filter((section) => section !== this.draggedElement),- ];+ // ===== Drop Position =====+ // Measures the items before touching any classes, so a drag event does+ // not force an extra layout pass.+ showDropPosition(pointerX, pointerY) {+ const { element, position } = this.dropSlot(pointerX, pointerY);+ this.clearPlaceholders();+ this.showPlaceholder(element, position);+ }++ moveDraggedTo(pointerX, pointerY) {+ const { element, position } = this.dropSlot(pointerX, pointerY);++ if (position === "after") {+ element.after(this.draggedElement);+ } else {+ element.before(this.draggedElement);+ }+ }++ // The item the dragged one lands next to, and on which side.+ dropSlot(pointerX, pointerY) {+ const draggableElements = this.itemTargets.filter(+ (section) => section !== this.draggedElement,+ );++ if (this.dropTargetValue === "nearest") {+ const nearest = this.nearestItem(draggableElements, pointerX, pointerY);+ if (nearest) {+ // The lower half of the closest card drops after it, so a card can+ // also move past the last one.+ const box = nearest.getBoundingClientRect();+ const after = pointerY > box.top + box.height / 2;+ return { element: nearest, position: after ? "after" : "before" };+ }+ } else {+ const below = this.firstItemBelow(draggableElements, pointerY);+ if (below) return { element: below, position: "before" };+ }++ return { element: this.element.lastElementChild, position: "after" };+ }- return draggableElements.reduce(+ firstItemBelow(items, pointerY) {+ return items.reduce((closest, child) => {const box = child.getBoundingClientRect();- const offset = y - box.top - box.height / 2;+ const offset = pointerY - box.top - box.height / 2;if (offset < 0 && offset > closest.offset) {return { offset: offset, element: child };@@ -336,6 +372,25 @@ export default class extends Controller {).element;}+ nearestItem(items, pointerX, pointerY) {+ let closest = null;+ let minDistance = Number.POSITIVE_INFINITY;++ items.forEach((child) => {+ const rect = child.getBoundingClientRect();+ const dx = pointerX - (rect.left + rect.width / 2);+ const dy = pointerY - (rect.top + rect.height / 2);+ const distance = Math.sqrt(dx * dx + dy * dy);++ if (distance < minDistance) {+ minDistance = distance;+ closest = child;+ }+ });++ return closest;+ }+showPlaceholder(element, position) {if (!element) return;diff --git a/app/views/pages/dashboard.html.erb b/app/views/pages/dashboard.html.erbindex 4b61927498..e678e06470 100644--- a/app/views/pages/dashboard.html.erb+++ b/app/views/pages/dashboard.html.erb@@ -112,13 +112,14 @@<% end %><% two_column = Current.user.dashboard_two_column? %>- <div class="grid grid-cols-1 <%= "2xl:grid-cols-2 2xl:items-start 2xl:gap-y-0 2xl:[grid-auto-flow:row_dense] 2xl:[grid-auto-rows:1px]" if two_column %> gap-6 pb-6 lg:pb-12" data-controller="dashboard-sortable dashboard-masonry" data-action="dragover->dashboard-sortable#dragOver drop->dashboard-sortable#drop" role="list" aria-label="<%= t("pages.dashboard.sections_aria_label") %>">+ <div class="grid grid-cols-1 <%= "2xl:grid-cols-2 2xl:items-start 2xl:gap-y-0 2xl:[grid-auto-flow:row_dense] 2xl:[grid-auto-rows:1px]" if two_column %> gap-6 pb-6 lg:pb-12" data-controller="sortable-list dashboard-masonry" data-sortable-list-url-value="<%= dashboard_preferences_path %>" data-sortable-list-param-value="preferences.section_order" data-sortable-list-hold-delay-value="800" data-sortable-list-drop-target-value="nearest" data-sortable-list-own-keys-only-value="true" data-action="dragover->sortable-list#dragOver drop->sortable-list#drop" role="list" aria-label="<%= t("pages.dashboard.sections_aria_label") %>"><% if accessible_accounts.any? %><% @dashboard_sections.each do |section| %><section- class="bg-container rounded-xl shadow-border-xs transition-all group focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-900 focus-visible:ring-offset-2<%= " 2xl:col-span-2" if two_column && section[:layout][:col_span] == "full" %>"+ class="bg-container rounded-xl shadow-border-xs transition-all group focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-900 focus-visible:ring-offset-2 [-webkit-touch-callout:none]<%= " 2xl:col-span-2" if two_column && section[:layout][:col_span] == "full" %>"style="<%= "--dash-widget-h: #{section[:layout][:height_px]}px;" if section[:layout][:grow] %>"- data-dashboard-sortable-target="section"+ data-sortable-list-target="item"+ data-sortable-list-id="<%= section[:key] %>"data-section-key="<%= section[:key] %>"<%= "autofocus" if @just_shown_section == section[:key] %>data-controller="dashboard-section<%= " cashflow-expand" if section[:key] == "cashflow_sankey" %>"@@ -130,13 +131,14 @@aria-grabbed="false"aria-label="<%= t(section[:title]) %> section. Press Enter or Space to grab for reordering, then use arrow keys to move."data-action="- dragstart->dashboard-sortable#dragStart- dragend->dashboard-sortable#dragEnd- touchstart->dashboard-sortable#touchStart- touchmove->dashboard-sortable#touchMove- touchend->dashboard-sortable#touchEnd- touchcancel->dashboard-sortable#touchEnd- keydown->dashboard-sortable#handleKeyDown">+ dragstart->sortable-list#dragStart+ dragend->sortable-list#dragEnd+ touchstart->sortable-list#touchStart+ touchmove->sortable-list#touchMove+ touchend->sortable-list#touchEnd+ touchcancel->sortable-list#touchCancel+ contextmenu->sortable-list#suppressContextMenu+ keydown->sortable-list#handleKeyDown"><div class="px-4 py-2 flex items-center justify-between"><div class="flex items-center gap-2"><buttondiff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rbindex 19fc5cceef..7f91799172 100644--- a/test/application_system_test_case.rb+++ b/test/application_system_test_case.rb@@ -115,6 +115,38 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase.performend+ # Lets a dashboard or reports test wait for the section order PATCH: once+ # it answers, <html> carries data-order-saved with the response status.+ # data-order-requests counts the PATCHes as soon as they are sent.+ # Waits for the sortable-list controller to connect first, so keys sent+ # next are handled.+ def record_saved_section_order+ page.document.synchronize do+ connected = page.evaluate_script(<<~JS)+ (() => {+ const list = document.querySelector("[data-controller~='sortable-list']");+ return !!list && !!window.Stimulus.getControllerForElementAndIdentifier(list, "sortable-list");+ })()+ JS+ raise Capybara::ExpectationNotMet, "sortable-list is not connected" unless connected+ end++ page.execute_script(<<~JS)+ const originalFetch = window.fetch;+ window.fetch = (url, init) => {+ if (typeof init?.body !== "string" || !init.body.includes("section_order")) {+ return originalFetch(url, init);+ }+ const { dataset } = document.documentElement;+ dataset.orderRequests = Number(dataset.orderRequests || 0) + 1;+ return originalFetch(url, init).then((response) => {+ dataset.orderSaved = response.status;+ return response;+ });+ };+ JS+ end+def login_as(user)sign_in(user)enddiff --git a/test/system/dashboard_chart_drag_select_test.rb b/test/system/dashboard_chart_drag_select_test.rbindex cdf94a6697..9d24c64c2e 100644--- a/test/system/dashboard_chart_drag_select_test.rb+++ b/test/system/dashboard_chart_drag_select_test.rb@@ -11,7 +11,7 @@ class DashboardChartDragSelectTest < ApplicationSystemTestCaseoriginal_order = page.all("[data-section-key]").map { |el| el["data-section-key"] }# The net worth chart sits inside a `<section draggable="true">` used by- # dashboard-sortable for card reordering. Without an explicit+ # sortable-list for card reordering. Without an explicit# `draggable="false"` on the chart container, this same gesture would be# hijacked by the native HTML5 drag-and-drop instead of the chart's brush.drag_across find("#netWorthChart .drag-select-brush .overlay", visible: :all)diff --git a/test/system/dashboard_customize_test.rb b/test/system/dashboard_customize_test.rbindex 21d049eed0..224d9c705a 100644--- a/test/system/dashboard_customize_test.rb+++ b/test/system/dashboard_customize_test.rb@@ -22,4 +22,65 @@ class DashboardCustomizeTest < ApplicationSystemTestCaseclick_on I18n.t("pages.dashboard.customize.done")assert_no_button I18n.t("pages.dashboard.customize.hide", title: net_worth)end++ test "a widget moved with the keyboard keeps its new place" do+ sign_in @user+ first, second = all("section[data-section-key]").first(2).map { |section| section["data-section-key"] }+ record_saved_section_order++ find("section[data-section-key='#{first}']").send_keys(:enter)+ page.send_keys(:arrow_down)+ page.send_keys(:enter)++ assert_selector "html[data-order-saved='200']"+ saved_order = @user.reload.dashboard_section_order+ assert_operator saved_order.index(second), :<, saved_order.index(first)+ end++ test "a widget dropped on the lower half of the last widget moves to the end" do+ sign_in @user+ keys = all("section[data-section-key]").map { |section| section["data-section-key"] }+ record_saved_section_order++ page.execute_script(<<~JS, keys.first, keys.last)+ const [draggedKey, targetKey] = arguments;+ const dragged = document.querySelector(`section[data-section-key='${draggedKey}']`);+ const target = document.querySelector(`section[data-section-key='${targetKey}']`);+ const box = target.getBoundingClientRect();+ const point = { clientX: box.left + box.width / 2, clientY: box.bottom - 5 };+ const dataTransfer = new DataTransfer();+ dragged.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer }));+ target.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer, ...point }));+ target.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer, ...point }));+ dragged.dispatchEvent(new DragEvent("dragend", { bubbles: true, dataTransfer }));+ JS++ assert_selector "html[data-order-saved='200']"+ assert_equal keys.drop(1) + [ keys.first ], @user.reload.dashboard_section_order.select { |key| keys.include?(key) }+ end++ test "a drop that did not start on a widget changes nothing" do+ sign_in @user+ keys = all("section[data-section-key]").map { |section| section["data-section-key"] }+ record_saved_section_order++ # One finished widget drag, then a file or text dragged in from outside.+ page.execute_script(<<~JS, keys.first, keys.last)+ const [draggedKey, targetKey] = arguments;+ const dragged = document.querySelector(`section[data-section-key='${draggedKey}']`);+ const target = document.querySelector(`section[data-section-key='${targetKey}']`);+ const box = target.getBoundingClientRect();+ const point = { clientX: box.left + box.width / 2, clientY: box.top + 5 };+ const drag = (element, type, init = {}) =>+ element.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: new DataTransfer(), ...init }));+ drag(dragged, "dragstart");+ drag(dragged, "dragend");+ drag(target, "dragover", point);+ drag(target, "drop", point);+ JS++ assert_equal keys, all("section[data-section-key]").map { |section| section["data-section-key"] }+ assert_no_text "null"+ assert_nil page.evaluate_script("document.documentElement.dataset.orderRequests")+ endenddiff --git a/test/system/reports_test.rb b/test/system/reports_test.rbindex 8d880c9f7a..f448a710d5 100644--- a/test/system/reports_test.rb+++ b/test/system/reports_test.rb@@ -50,6 +50,19 @@ class ReportsTest < ApplicationSystemTestCaseassert_equal %w[ArrowLeft], clicked_hotkeysend+ test "a section moved with the keyboard keeps its new place" do+ first, second = all("section[data-section-key]").first(2).map { |section| section["data-section-key"] }+ record_saved_section_order++ find("section[data-section-key='#{first}']").send_keys(:enter)+ page.send_keys(:arrow_down)+ page.send_keys(:enter)++ assert_selector "html[data-order-saved='200']"+ saved_order = users(:family_admin).reload.reports_section_order+ assert_operator saved_order.index(second), :<, saved_order.index(first)+ end+privatedef clicked_hotkeyspage.evaluate_script("window.clickedHotkeys")