Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Keep pinches, text drags and self-drops from reordering (#4756)

GFR7367a14b31a4
diff --git a/app/javascript/controllers/account_sort_mode_controller.js b/app/javascript/controllers/account_sort_mode_controller.js
index 5459745660..aef73b49a6 100644
--- a/app/javascript/controllers/account_sort_mode_controller.js
+++ b/app/javascript/controllers/account_sort_mode_controller.js
@@ -70,18 +70,19 @@ export default class extends Controller {
// 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.
+ // and the logo inside a row are not draggable on their own, so dragging
+ // them 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) => {
+ item.querySelectorAll("a, img").forEach((element) => {
if (this.sorting) {
- link.setAttribute("draggable", "false");
+ element.setAttribute("draggable", "false");
} else {
- link.removeAttribute("draggable");
+ element.removeAttribute("draggable");
}
});
}
diff --git a/app/javascript/controllers/sortable_list_controller.js b/app/javascript/controllers/sortable_list_controller.js
index 3e76bc802c..b07fb444da 100644
--- a/app/javascript/controllers/sortable_list_controller.js
+++ b/app/javascript/controllers/sortable_list_controller.js
@@ -11,6 +11,19 @@ import { Controller } from "@hotwired/stimulus";
// controller events from inside a nested controller of the same name, and
// the outer list needs the dragover and drop events over the inner one to
// move a whole group. Each list handles only drags of its own items.
+// A second finger anywhere on the page means a pinch zoom, not a reorder,
+// also when it lands outside the items. One document listener serves every
+// connected list.
+const connectedLists = new Set();
+
+function cancelOnSecondFinger(event) {
+ if (event.touches.length < 2) return;
+
+ for (const list of connectedLists) {
+ if (list.pendingSection || list.isTouching) list.touchCancel();
+ }
+}
+
export default class extends Controller {
static targets = ["item"];
@@ -48,9 +61,36 @@ export default class extends Controller {
this.keyboardGrabbedElement = null;
this.holdTimer = null;
this.holdActivated = false;
+ // What the server has; a save that cannot reach it puts this back.
+ this.savedOrder = this.currentOrder();
+
+ if (connectedLists.size === 0) {
+ document.addEventListener("touchstart", cancelOnSecondFinger, {
+ capture: true,
+ passive: true,
+ });
+ }
+ connectedLists.add(this);
+
+ // A morph (a page refresh, a broadcast) can reorder the items without
+ // reconnecting this controller; the new order is what the server has.
+ this.refreshSavedOrder = () => {
+ const queue = this.queueController();
+ if (queue.saving || queue.pendingOrder || this.isMoving()) return;
+ this.savedOrder = this.currentOrder();
+ queue.savedOrder = this.savedOrder;
+ };
+ document.addEventListener("turbo:morph", this.refreshSavedOrder);
}
disconnect() {
+ connectedLists.delete(this);
+ if (connectedLists.size === 0) {
+ document.removeEventListener("touchstart", cancelOnSecondFinger, {
+ capture: true,
+ });
+ }
+ document.removeEventListener("turbo:morph", this.refreshSavedOrder);
this.cancelHold();
}
@@ -71,6 +111,10 @@ export default class extends Controller {
return;
}
+ // Selected text, a link or an image inside the item drags as usual;
+ // only a drag of the item itself reorders.
+ if (event.target !== event.currentTarget) return;
+
this.draggedElement = event.currentTarget;
this.draggedElement.classList.add("opacity-50");
this.draggedElement.setAttribute("aria-grabbed", "true");
@@ -88,6 +132,7 @@ export default class extends Controller {
event.currentTarget.setAttribute("aria-grabbed", "false");
this.clearPlaceholders();
this.draggedElement = null;
+ this.finishDeferredRollback();
}
// Only a drag that started on one of the items is a reorder; a file or
@@ -108,9 +153,9 @@ export default class extends Controller {
event.preventDefault();
event.stopPropagation();
- this.moveDraggedTo(event.clientX, event.clientY);
+ const moved = this.moveDraggedTo(event.clientX, event.clientY);
this.clearPlaceholders();
- this.saveOrder();
+ if (moved) this.saveOrder();
}
// ===== Touch Events =====
@@ -118,6 +163,9 @@ export default class extends Controller {
// (finger moves before the hold delay elapses) cancels it.
touchStart(event) {
+ // The second finger of a pinch; the document listener cancelled the hold.
+ if (event.touches.length > 1) return;
+
// Find the parent item element from the handle
const section = event.currentTarget.closest(this.itemSelector);
if (!section) return;
@@ -188,17 +236,19 @@ export default class extends Controller {
if (!this.holdActivated || !this.isTouching || !this.draggedElement) {
this.resetTouchState();
+ this.finishDeferredRollback();
return;
}
- this.moveDraggedTo(this.currentTouchX, this.currentTouchY);
+ const moved = this.moveDraggedTo(this.currentTouchX, this.currentTouchY);
this.draggedElement.classList.remove("opacity-50", "scale-[1.02]");
this.draggedElement.setAttribute("aria-grabbed", "false");
this.clearPlaceholders();
- this.saveOrder();
+ if (moved) this.saveOrder();
this.resetTouchState();
+ this.finishDeferredRollback();
}
touchCancel() {
@@ -211,6 +261,7 @@ export default class extends Controller {
this.clearPlaceholders();
this.resetTouchState();
+ this.finishDeferredRollback();
}
// Belt-and-suspenders alongside the `[-webkit-touch-callout:none]` class:
@@ -367,23 +418,39 @@ export default class extends Controller {
// 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);
+ const slot = this.dropSlot(pointerX, pointerY);
this.clearPlaceholders();
- this.showPlaceholder(element, position);
+ if (slot) this.showPlaceholder(slot.element, slot.position);
}
+ // Returns whether the order changed, so a drop back into the same place
+ // saves nothing.
moveDraggedTo(pointerX, pointerY) {
- const { element, position } = this.dropSlot(pointerX, pointerY);
+ const slot = this.dropSlot(pointerX, pointerY);
+ if (!slot) return false;
- if (position === "after") {
- element.after(this.draggedElement);
+ const before = JSON.stringify(this.currentOrder());
+ if (slot.position === "after") {
+ slot.element.after(this.draggedElement);
} else {
- element.before(this.draggedElement);
+ slot.element.before(this.draggedElement);
}
+ return JSON.stringify(this.currentOrder()) !== before;
}
- // The item the dragged one lands next to, and on which side.
+ // The item the dragged one lands next to, and on which side. None while
+ // the pointer is over the dragged item itself: it stays where it is.
dropSlot(pointerX, pointerY) {
+ const own = this.draggedElement.getBoundingClientRect();
+ if (
+ pointerX >= own.left &&
+ pointerX <= own.right &&
+ pointerY >= own.top &&
+ pointerY <= own.bottom
+ ) {
+ return null;
+ }
+
const draggableElements = this.itemTargets.filter(
(section) => section !== this.draggedElement,
);
@@ -472,7 +539,7 @@ export default class extends Controller {
// never land after a newer one and restore an earlier order. Resolves once
// the queue has sent everything.
saveOrder() {
- const order = this.itemTargets.map((item) => item.dataset.sortableListId);
+ const order = this.currentOrder();
const queue = this.mirrorListsValue ? this.mirrorOrder(order) : this;
queue.pendingOrder = order;
if (!queue.saving) queue.savesFinished = queue.flushSaves();
@@ -483,13 +550,7 @@ export default class extends Controller {
// 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,
- );
+ const lists = this.mirroredLists();
lists.forEach((list) => {
if (list === this.element) return;
@@ -502,14 +563,48 @@ export default class extends Controller {
});
});
+ return this.queueController();
+ }
+
+ // The controller whose queue saves for this list and all its copies.
+ queueController() {
+ if (!this.mirrorListsValue) return this;
+
return (
this.application.getControllerForElementAndIdentifier(
- lists[0],
+ this.mirroredLists()[0],
this.identifier,
) ?? this
);
}
+ mirroredListControllers() {
+ if (!this.mirrorListsValue) return [this];
+
+ return this.mirroredLists()
+ .map((list) =>
+ this.application.getControllerForElementAndIdentifier(
+ list,
+ this.identifier,
+ ),
+ )
+ .filter(Boolean);
+ }
+
+ mirroredLists() {
+ return [
+ ...document.querySelectorAll(`[data-controller~='${this.identifier}']`),
+ ].filter(
+ (list) =>
+ list.dataset.sortableListUrlValue === this.urlValue &&
+ list.dataset.sortableListParamValue === this.paramValue,
+ );
+ }
+
+ currentOrder() {
+ return this.itemTargets.map((item) => item.dataset.sortableListId);
+ }
+
async flushSaves() {
this.saving = true;
while (this.pendingOrder) {
@@ -540,7 +635,10 @@ export default class extends Controller {
: undefined,
});
- if (!response.ok) {
+ if (response.ok) {
+ this.savedOrder = order;
+ this.rollbackPending = false;
+ } else {
const errorData = await response.json().catch(() => ({}));
console.error(
"[Sortable List] Failed to save order:",
@@ -554,10 +652,99 @@ export default class extends Controller {
}
} catch (error) {
console.error("[Sortable List] Network error saving order:", error);
- // A newer order still gets sent; otherwise show what is actually saved.
- if (!this.pendingOrder) {
+ // A newer order still gets sent.
+ if (this.pendingOrder) return;
+
+ // A timed-out request may still have been saved, so show what the
+ // server has.
+ if (error?.name === "TimeoutError") {
Turbo.visit(window.location.href, { action: "replace" });
+ return;
+ }
+
+ // No response: the order may or may not have been saved, and
+ // reloading would fail too while offline. Put back the last order the
+ // server confirmed and say the save could not be confirmed. A move the
+ // user has not released yet stays; its release sends the order again,
+ // and a gesture that ends without a move puts the order back then.
+ const lists = this.mirroredListControllers();
+ if (lists.some((list) => list.isMoving())) {
+ this.rollbackPending = true;
+ } else {
+ this.rollBack(lists);
}
+ this.showSaveFailed();
}
}
+
+ rollBack(lists = this.mirroredListControllers()) {
+ this.rollbackPending = false;
+ lists.forEach((list) => {
+ list.restoreOrder(this.savedOrder);
+ });
+ }
+
+ // Called when a gesture ends. A save that failed while it was going on put
+ // nothing back; if the gesture saved no new order, do that now.
+ finishDeferredRollback() {
+ const queue = this.queueController();
+ if (!queue.rollbackPending || queue.saving || queue.pendingOrder) return;
+ if (queue.mirroredListControllers().some((list) => list.isMoving())) return;
+
+ queue.rollBack();
+ }
+
+ isMoving() {
+ return Boolean(
+ this.draggedElement ||
+ this.keyboardGrabbedElement ||
+ this.isTouching ||
+ this.pendingSection,
+ );
+ }
+
+ // Puts the items back in the given order. Items the order does not know
+ // keep their order behind the known ones. Only items out of place move, so
+ // the controllers inside the others do not reconnect.
+ restoreOrder(order) {
+ const rank = (item) => {
+ const index = order.indexOf(item.dataset.sortableListId);
+ return index === -1 ? order.length : index;
+ };
+ const sorted = [...this.itemTargets].sort((a, b) => rank(a) - rank(b));
+ const focused = document.activeElement;
+
+ sorted.forEach((item, index) => {
+ const current = this.itemTargets[index];
+ if (current !== item) current.before(item);
+ });
+
+ // Moving the focused item drops its focus; give it back.
+ if (focused !== document.activeElement && focused?.isConnected) {
+ focused.focus();
+ }
+ }
+
+ // The alert is rendered by the server into a template in the
+ // notification tray, so its text is translated. The list moving back is
+ // announced too, since the toast itself is not a live region.
+ showSaveFailed() {
+ const template = document.getElementById("sortable-list-save-failed");
+ const tray = document.getElementById("notification-tray");
+ if (!template || !tray) return;
+
+ // One alert, however often the save fails.
+ tray.querySelector("[data-sortable-list-save-failed]")?.remove();
+ const alert = template.content.firstElementChild.cloneNode(true);
+ alert.dataset.sortableListSaveFailed = "";
+ tray.append(alert);
+
+ // Cleared first, so the same message is read out again the next time.
+ const announcer = document.getElementById("aria-announcer");
+ if (!announcer) return;
+ announcer.textContent = "";
+ requestAnimationFrame(() => {
+ announcer.textContent = template.dataset.message;
+ });
+ }
}
diff --git a/app/views/layouts/shared/_notification_tray.html.erb b/app/views/layouts/shared/_notification_tray.html.erb
index c19e58a2dd..e1e3c1d86c 100644
--- a/app/views/layouts/shared/_notification_tray.html.erb
+++ b/app/views/layouts/shared/_notification_tray.html.erb
@@ -26,3 +26,10 @@
<template id="desktop-download-failed" data-message="<%= t(".download_failed") %>">
<%= render "shared/notifications/alert", message: t(".download_failed") %>
</template>
+
+<%# sortable_list_controller.js clones this when a new order cannot reach
+ the server and the list goes back to the saved one, and reads the message
+ for #aria-announcer. %>
+<template id="sortable-list-save-failed" data-message="<%= t(".order_save_failed") %>">
+ <%= render "shared/notifications/alert", message: t(".order_save_failed") %>
+</template>
diff --git a/config/locales/views/layout/de.yml b/config/locales/views/layout/de.yml
index 964ec9ae77..2670bc8619 100644
--- a/config/locales/views/layout/de.yml
+++ b/config/locales/views/layout/de.yml
@@ -29,6 +29,8 @@ de:
are_you_sure: Bist du sicher?
cannot_be_undone: Das lässt sich nicht rückgängig machen.
confirm: Bestätigen
+ notification_tray:
+ order_save_failed: Ob die neue Reihenfolge gespeichert wurde, ließ sich nicht bestätigen. Prüfe deine Verbindung und lade die Seite neu, um die gespeicherte Reihenfolge zu sehen.
trial:
open_demo: Offene Demo
data_deleted_in_days: Daten werden in %{days} Tagen gelöscht
diff --git a/config/locales/views/layout/en.yml b/config/locales/views/layout/en.yml
index 4cada73e4b..ba0ee6639b 100644
--- a/config/locales/views/layout/en.yml
+++ b/config/locales/views/layout/en.yml
@@ -36,6 +36,7 @@ en:
download_complete: Download complete
download_failed: Download failed. Please try again.
download_location: The file is in your Downloads folder.
+ order_save_failed: "Couldn't confirm that the new order was saved. Check your connection and reload the page to see the saved order."
trial:
open_demo: Open demo
data_deleted_in_days: Data deleted in %{days} days
diff --git a/test/system/sortable_list_test.rb b/test/system/sortable_list_test.rb
new file mode 100644
index 0000000000..3e1130f746
--- /dev/null
+++ b/test/system/sortable_list_test.rb
@@ -0,0 +1,177 @@
+require "application_system_test_case"
+
+# Gestures the shared sortable-list controller must not take for a reorder,
+# and what it shows when a new order cannot be saved. Driven on the
+# dashboard, whose cards react to drag and touch over their whole area.
+class SortableListTest < ApplicationSystemTestCase
+ setup do
+ @user = users(:family_admin)
+ end
+
+ test "a pinch zoom on a card does not move it" do
+ sign_in @user
+ keys = section_keys
+ 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}']`).getBoundingClientRect();
+ const start = dragged.getBoundingClientRect();
+ const touch = (identifier, element, clientX, clientY) => new Touch({ identifier, target: element, clientX, clientY });
+ const fire = (element, type, touches) =>
+ element.dispatchEvent(new TouchEvent(type, { bubbles: true, cancelable: true, touches, changedTouches: touches }));
+ const first = touch(1, dragged, start.left + 20, start.top + 20);
+
+ // One finger held on the card past the hold delay, so the drag is on;
+ // then the second finger of the pinch lands outside the card.
+ fire(dragged, "touchstart", [first]);
+ setTimeout(() => {
+ const second = touch(2, document.body, 5, 5);
+ fire(document.body, "touchstart", [first, second]);
+ document.documentElement.dataset.dragAfterPinch = dragged.classList.contains("opacity-50");
+ fire(dragged, "touchmove", [touch(1, dragged, target.left + 20, target.bottom - 5), second]);
+ fire(dragged, "touchend", []);
+ document.documentElement.dataset.pinchDone = "true";
+ }, 1000);
+ JS
+
+ assert_selector "html[data-pinch-done='true']"
+ assert_selector "html[data-drag-after-pinch='false']"
+ assert_equal keys, section_keys
+ assert_no_selector "section[data-section-key].opacity-50"
+ assert_nil page.evaluate_script("document.documentElement.dataset.orderRequests")
+ end
+
+ test "dragging selected text inside a card does not move the card" do
+ sign_in @user
+ keys = section_keys
+ record_saved_section_order
+
+ page.execute_script(<<~JS, keys.first, keys.last)
+ const [draggedKey, targetKey] = arguments;
+ const card = document.querySelector(`section[data-section-key='${draggedKey}']`);
+ const target = document.querySelector(`section[data-section-key='${targetKey}']`);
+ // The browser starts a text drag on the text node under the pointer.
+ const walker = document.createTreeWalker(card, NodeFilter.SHOW_TEXT, {
+ acceptNode: (node) => (node.textContent.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP),
+ });
+ const text = walker.nextNode();
+ const box = target.getBoundingClientRect();
+ const point = { clientX: box.left + box.width / 2, clientY: box.bottom - 5 };
+ const dataTransfer = new DataTransfer();
+ text.dispatchEvent(new DragEvent("dragstart", { bubbles: true, cancelable: true, dataTransfer }));
+ target.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer, ...point }));
+ target.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer, ...point }));
+ text.dispatchEvent(new DragEvent("dragend", { bubbles: true, dataTransfer }));
+ JS
+
+ assert_equal keys, section_keys
+ assert_nil page.evaluate_script("document.documentElement.dataset.orderRequests")
+ end
+
+ test "a card dropped on its own place in the two-column grid stays there" do
+ @user.update!(preferences: (@user.preferences || {}).merge("dashboard_two_column" => true))
+ page.current_window.resize_to(1800, 1400)
+ sign_in @user
+ keys = section_keys
+ record_saved_section_order
+
+ dropped = page.evaluate_script(<<~JS)
+ (() => {
+ // A half-width card, so its nearest neighbour sits in the other column.
+ const card = [...document.querySelectorAll("section[data-section-key]")]
+ .find((section) => section.getBoundingClientRect().width < window.innerWidth / 2);
+ if (!card) return null;
+
+ const box = card.getBoundingClientRect();
+ const point = { clientX: box.left + box.width / 2, clientY: box.top + box.height / 2 };
+ const dataTransfer = new DataTransfer();
+ card.dispatchEvent(new DragEvent("dragstart", { bubbles: true, cancelable: true, dataTransfer }));
+ card.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer, ...point }));
+ card.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer, ...point }));
+ card.dispatchEvent(new DragEvent("dragend", { bubbles: true, dataTransfer }));
+ return card.dataset.sectionKey;
+ })()
+ JS
+
+ assert dropped, "expected a half-width card in the two-column grid"
+ assert_equal keys, section_keys
+ assert_nil page.evaluate_script("document.documentElement.dataset.orderRequests")
+ end
+
+ test "an order that cannot be saved goes back and says so without reloading" do
+ sign_in @user
+ keys = section_keys
+ page.execute_script(<<~JS)
+ document.body.insertAdjacentHTML("beforeend", "<div id='still-this-page'></div>");
+ const originalFetch = window.fetch;
+ window.fetch = (url, init) =>
+ init?.method === "PATCH" ? Promise.reject(new TypeError("Failed to fetch")) : originalFetch(url, init);
+ JS
+
+ find("section[data-section-key='#{keys.first}']").send_keys(:enter)
+ page.send_keys(:arrow_down)
+ page.send_keys(:enter)
+
+ message = I18n.t("layouts.shared.notification_tray.order_save_failed")
+ assert_text message
+ assert_selector "#aria-announcer", text: message, visible: :all
+ assert_equal keys, section_keys
+ assert_selector "#still-this-page", visible: :all
+ assert_equal keys.first, page.evaluate_script("document.activeElement.dataset.sectionKey")
+ end
+
+ test "a save that fails during a drag puts the order back when the drag ends without a move" do
+ sign_in @user
+ keys = section_keys
+ page.execute_script(<<~JS, keys.first, keys.second)
+ const [firstKey, secondKey] = arguments;
+ const list = document.querySelector(`section[data-section-key='${firstKey}']`).closest("[data-controller~='sortable-list']");
+ const controller = window.Stimulus.getControllerForElementAndIdentifier(list, "sortable-list");
+ window.fetch = () => Promise.reject(new TypeError("Failed to fetch"));
+
+ // A drag is still going on when the save of an earlier move fails.
+ const first = list.querySelector(`[data-section-key='${firstKey}']`);
+ list.querySelector(`[data-section-key='${secondKey}']`).after(first);
+ controller.draggedElement = first;
+ controller.saveOrder().then(() => {
+ document.documentElement.dataset.orderWhileDragging = controller.currentOrder().join(",");
+ controller.dragEnd({ currentTarget: first });
+ document.documentElement.dataset.dragEnded = "true";
+ });
+ JS
+
+ assert_selector "html[data-drag-ended='true']"
+ moved = [ keys.second, keys.first, *keys.drop(2) ]
+ assert_equal moved.join(","), page.evaluate_script("document.documentElement.dataset.orderWhileDragging")
+ assert_equal keys, section_keys
+ end
+
+ test "a failed save goes back to the order a morph brought in" do
+ sign_in @user
+ keys = section_keys
+ page.execute_script(<<~JS, keys.first, keys.second, keys.third)
+ const [firstKey, secondKey, thirdKey] = arguments;
+ const list = document.querySelector(`section[data-section-key='${firstKey}']`).closest("[data-controller~='sortable-list']");
+ const controller = window.Stimulus.getControllerForElementAndIdentifier(list, "sortable-list");
+ const item = (key) => list.querySelector(`[data-section-key='${key}']`);
+
+ // A refresh morph swaps the first two cards; the controller stays.
+ item(secondKey).after(item(firstKey));
+ document.dispatchEvent(new Event("turbo:morph"));
+
+ window.fetch = () => Promise.reject(new TypeError("Failed to fetch"));
+ item(thirdKey).after(item(secondKey));
+ controller.saveOrder().then(() => { document.documentElement.dataset.saveDone = "true"; });
+ JS
+
+ assert_selector "html[data-save-done='true']"
+ assert_equal [ keys.second, keys.first, *keys.drop(2) ], section_keys
+ end
+
+ private
+ def section_keys
+ all("section[data-section-key]").map { |section| section["data-section-key"] }
+ end
+end