The personal finance app for everyone (by everyone)
Ruby
Let activity rows off screen skip layout while a sidebar animates (#4931)
Yong Cong Sin2afc356fb29c
diff --git a/app/javascript/controllers/activity_label_quick_edit_controller.js b/app/javascript/controllers/activity_label_quick_edit_controller.jsindex ee10fdf2cf..802ba08b35 100644--- a/app/javascript/controllers/activity_label_quick_edit_controller.js+++ b/app/javascript/controllers/activity_label_quick_edit_controller.js@@ -26,6 +26,7 @@ export default class extends Controller {if (this.hasDropdownTarget) {this.dropdownTarget.classList.toggle("hidden")+ this.#syncExpanded()}}@@ -38,9 +39,19 @@ export default class extends Controller {close() {if (this.hasDropdownTarget) {this.dropdownTarget.classList.add("hidden")+ this.#syncExpanded()}}+ // The badge says whether its dropdown is open, for assistive technology,+ // and so a row with it open is not contained (and the dropdown clipped)+ // while a sidebar is dragged.+ #syncExpanded() {+ if (!this.hasBadgeTarget) return+ const open = !this.dropdownTarget.classList.contains("hidden")+ this.badgeTarget.setAttribute("aria-expanded", open.toString())+ }+async select(event) {event.preventDefault()event.stopPropagation()diff --git a/app/javascript/controllers/app_layout_controller.js b/app/javascript/controllers/app_layout_controller.jsindex f31c7b9233..cc9c897682 100644--- a/app/javascript/controllers/app_layout_controller.js+++ b/app/javascript/controllers/app_layout_controller.js@@ -1,4 +1,5 @@import { Controller } from "@hotwired/stimulus";+import { markLayoutAnimating } from "utils/layout_animating";// Connects to data-controller="dialog"export default class extends Controller {@@ -45,6 +46,8 @@ export default class extends Controller {const expandedClasses = side === "left" ? [...this.expandedSidebarClasses, "border-r"] : [...this.expandedSidebarClasses, "border-l"];const collapsedClasses = side === "left" ? [...this.collapsedSidebarClasses, "border-r-0"] : [...this.collapsedSidebarClasses, "border-l-0"];+ markLayoutAnimating(el);+if (isCurrentlyOpen) {el.classList.remove(...expandedClasses);el.classList.add(...collapsedClasses);diff --git a/app/javascript/controllers/sidebar_resize_controller.js b/app/javascript/controllers/sidebar_resize_controller.jsindex 0ea840a676..4490ce25d2 100644--- a/app/javascript/controllers/sidebar_resize_controller.js+++ b/app/javascript/controllers/sidebar_resize_controller.js@@ -4,6 +4,10 @@ import {SIDEBAR_DEFAULTS,clampSidebarWidth,} from "utils/sidebar_resize";+import {+ holdLayoutAnimating,+ markLayoutAnimating,+} from "utils/layout_animating";// Drives the draggable dividers on the left (accounts) and right (assistant)// sidebars. The chosen width is stored as a CSS variable on the root layout@@ -26,14 +30,18 @@ export default class extends Controller {#drag = null;#onMove = null;#onUp = null;+ #handle = null;connect() {this.#applyStoredWidth("left");this.#applyStoredWidth("right");}+ // Ends a drag in progress as a pointerup would: Stimulus reuses this+ // controller if the element connects again, and a #drag left set would+ // ignore every later pointerdown (and keep the drag's cursor).disconnect() {- this.#teardownListeners();+ this.#endResize();}startLeft(event) {@@ -64,24 +72,65 @@ export default class extends Controller {#startResize(event, side) {const sidebar = this.#sidebar(side);- if (!sidebar) return;+ // One drag at a time: a second one would orphan the first's hold on+ // utils/layout_animating and leave the page marked.+ if (!sidebar || this.#drag) return;event.preventDefault();- this.#drag = { side, sidebar };+ // The pointer that started the drag: only its events move or end it, so+ // another pointer (a second finger the browser cancels to scroll) can't+ // end a mouse or stylus drag still held.+ // A click on the divider (no movement) changes nothing: its position,+ // read against the sidebars' current sizes, could clamp the width.+ this.#drag = {+ side,+ sidebar,+ pointerId: event.pointerId,+ startX: event.clientX,+ moved: false,+ release: holdLayoutAnimating(),+ };// Suppress the open/close transition so the panel tracks the pointer 1:1.sidebar.style.transition = "none";document.body.style.userSelect = "none";document.body.style.cursor = "col-resize";- this.#onMove = (moveEvent) => this.#resize(moveEvent);- this.#onUp = () => this.#endResize();+ this.#onMove = (moveEvent) => {+ if (this.#isDragPointer(moveEvent)) this.#resize(moveEvent);+ };+ this.#onUp = (upEvent) => {+ if (upEvent.type !== "blur" && !this.#isDragPointer(upEvent)) return;+ // Where the pointer was released is the drag's final width.+ if (upEvent.type === "pointerup") this.#resize(upEvent);+ this.#endResize();+ };window.addEventListener("pointermove", this.#onMove);- window.addEventListener("pointerup", this.#onUp, { once: true });+ window.addEventListener("pointerup", this.#onUp);+ // The browser can take a touch over (scrolling) and cancel the pointer.+ window.addEventListener("pointercancel", this.#onUp);+ // A button released outside the window, or the window losing focus+ // mid-drag, isn't guaranteed to reach the listeners above: capture the+ // pointer, and end the drag when that capture or the focus is lost.+ this.#handle = event.currentTarget;+ try {+ this.#handle?.setPointerCapture?.(event.pointerId);+ } catch (_e) {+ // Not an active pointer (a synthetic event): the window listeners remain.+ }+ this.#handle?.addEventListener("lostpointercapture", this.#onUp);+ window.addEventListener("blur", this.#onUp);+ }++ #isDragPointer(event) {+ const id = this.#drag?.pointerId;+ return id === undefined || event.pointerId === id;}#resize(event) {if (!this.#drag) return;+ if (!this.#drag.moved && event.clientX === this.#drag.startX) return;+ this.#drag.moved = true;const { side, sidebar } = this.#drag;const rect = sidebar.getBoundingClientRect();@@ -95,13 +144,18 @@ export default class extends Controller {#endResize() {if (!this.#drag) return;- const { side, sidebar } = this.#drag;+ const { side, sidebar, release } = this.#drag;+ release();+ // Lay out the final width while transitions are still off, as a stored+ // width is applied: restored first, a width written by the last move but+ // not yet laid out would animate (max-width) after the drag ended.+ sidebar.getBoundingClientRect();sidebar.style.transition = "";document.body.style.userSelect = "";document.body.style.cursor = "";this.#teardownListeners();- this.#persist(side, this.#currentWidth(side));+ if (this.#drag.moved) this.#persist(side, this.#currentWidth(side));this.#drag = null;}@@ -126,8 +180,13 @@ export default class extends Controller {this.#commitWidth(side, next);}+ // From the keyboard or a double-click: the sidebar animates to the new+ // width (its open/close transition), so the page is marked as for a toggle.#commitWidth(side, rawWidth) {const width = this.#clamp(side, rawWidth);+ const sidebar = this.#sidebar(side);+ if (sidebar && width !== this.#currentWidth(side))+ markLayoutAnimating(sidebar);this.#setWidth(side, width);this.#persist(side, width);}@@ -143,7 +202,18 @@ export default class extends Controller {// Storage blocked (private mode / locked down) — fall back to default.}const requested = Number.isFinite(stored) ? stored : SIDEBAR_DEFAULTS[side];- this.#setWidth(side, this.#clamp(side, requested));+ const width = this.#clamp(side, requested);+ // #clamp reads the other sidebar's size, laying the page out at the+ // width it has now, so a different stored width would animate the+ // sidebar (its max-width) on every page load, laying out the activity+ // rows each frame. A restored width applies at once instead.+ const sidebar = this.#sidebar(side);+ if (sidebar) sidebar.style.transition = "none";+ this.#setWidth(side, width);+ if (sidebar) {+ sidebar.getBoundingClientRect();+ sidebar.style.transition = "";+ }}#clamp(side, rawWidth) {@@ -191,8 +261,14 @@ export default class extends Controller {#teardownListeners() {if (this.#onMove) window.removeEventListener("pointermove", this.#onMove);- if (this.#onUp) window.removeEventListener("pointerup", this.#onUp);+ if (this.#onUp) {+ window.removeEventListener("pointerup", this.#onUp);+ window.removeEventListener("pointercancel", this.#onUp);+ window.removeEventListener("blur", this.#onUp);+ this.#handle?.removeEventListener("lostpointercapture", this.#onUp);+ }this.#onMove = null;this.#onUp = null;+ this.#handle = null;}}diff --git a/app/javascript/utils/layout_animating.js b/app/javascript/utils/layout_animating.jsnew file mode 100644index 0000000000..1260a4da5e--- /dev/null+++ b/app/javascript/utils/layout_animating.js@@ -0,0 +1,96 @@+// Marks the page while a sidebar is animating or being dragged, as+// `<html data-layout-animating>`. Each frame of a sidebar's width change lays+// out everything beside it again, and a long list (an account's activity) takes+// most of a frame to lay out; while the mark is set, CSS lets rows that are off+// screen skip that (content-visibility: auto, on the activity row partials). It is not left+// on: that containment would clip the rows' fixed-position menus. A row with a+// menu or picker open (a trigger with aria-expanded="true") is left out of it+// meanwhile, since those stay open through a drag.+let holds = 0;++function apply() {+ if (holds > 0) {+ document.documentElement.dataset.layoutAnimating = "";+ } else {+ delete document.documentElement.dataset.layoutAnimating;+ }+}++// Marks the page until the caller releases it (a drag).+export function holdLayoutAnimating() {+ holds += 1;+ apply();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ holds -= 1;+ apply();+ };+}++// Marks the page until `element`'s width and max-width transitions have+// ended (or `fallbackMs` passes, for a transition that never runs or ends). A+// toggle animates the width; a resize committed from the keyboard or a+// double-click animates the max-width that caps it, and the two can overlap.+// A toggle while the sidebar is still moving reverses its transition: the old+// one is cancelled and a new one runs. The element keeps one mark, renewed by+// each toggle or resize, counting the transitions that started and released+// two frames after the last of them ends or is cancelled, unless another+// starts meanwhile: one transition's end can come just before the next one's+// start (a resize from the keyboard as a toggle finishes, or a reversed+// toggle).+const marks = new WeakMap();+const LAYOUT_PROPERTIES = ["width", "max-width"];++export function markLayoutAnimating(element, { fallbackMs = 600 } = {}) {+ let mark = marks.get(element);+ if (!mark) {+ const release = holdLayoutAnimating();+ const ours = (event) =>+ event.target === element &&+ LAYOUT_PROPERTIES.includes(event.propertyName);+ mark = {+ timer: null,+ running: 0,+ finish: () => {+ element.removeEventListener("transitionrun", mark.onRun);+ element.removeEventListener("transitionend", mark.onEnd);+ element.removeEventListener("transitioncancel", mark.onCancel);+ clearTimeout(mark.timer);+ marks.delete(element);+ release();+ },+ // With no transition left running, the mark ends once a transition+ // starting in the same or the next frame has had time to register.+ settle: () => {+ if (mark.running > 0) return;+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ if (marks.get(element) === mark && mark.running === 0)+ mark.finish();+ }),+ );+ },+ onRun: (event) => {+ if (ours(event)) mark.running += 1;+ },+ onEnd: (event) => {+ if (!ours(event)) return;+ mark.running = Math.max(0, mark.running - 1);+ mark.settle();+ },+ onCancel: (event) => {+ if (!ours(event)) return;+ mark.running = Math.max(0, mark.running - 1);+ mark.settle();+ },+ };+ element.addEventListener("transitionrun", mark.onRun);+ element.addEventListener("transitionend", mark.onEnd);+ element.addEventListener("transitioncancel", mark.onCancel);+ marks.set(element, mark);+ }+ clearTimeout(mark.timer);+ mark.timer = setTimeout(() => mark.finish(), fallbackMs);+}diff --git a/app/views/investment_activity/_quick_edit_badge.html.erb b/app/views/investment_activity/_quick_edit_badge.html.erbindex 355b1a316d..35bc8291b6 100644--- a/app/views/investment_activity/_quick_edit_badge.html.erb+++ b/app/views/investment_activity/_quick_edit_badge.html.erb@@ -59,6 +59,7 @@class: "inline-flex items-center gap-1 text-xs font-medium rounded-full px-2.5 py-1 #{income_trade ? "cursor-pointer" : "cursor-pointer hover:opacity-80"} transition-opacity",style: (has_label ? "background-color: color-mix(in oklab, #{color} 15%, transparent); border: 1px solid color-mix(in oklab, #{color} 25%, transparent); color: #{color};" : "background-color: var(--color-surface-inset); border: 1px solid var(--color-border-secondary); color: var(--color-text-secondary);"),data: (income_trade ? {} : { action: "click->activity-label-quick-edit#toggle", activity_label_quick_edit_target: "badge" }),+ aria: (income_trade ? {} : { expanded: "false" }),title: (has_label ? t("transactions.transaction.activity_type_tooltip") : t("transactions.show.activity_type"))) do %><% if has_label %><%= t("transactions.activity_labels.#{label.parameterize(separator: "_")}", default: label) %>diff --git a/app/views/trades/_trade.html.erb b/app/views/trades/_trade.html.erbindex c907c5ee34..b1f6f296e5 100644--- a/app/views/trades/_trade.html.erb+++ b/app/views/trades/_trade.html.erb@@ -5,7 +5,7 @@<%= turbo_frame_tag dom_id(entry) do %><%= turbo_frame_tag dom_id(trade) do %>- <div class="group grid grid-cols-12 items-center <%= entry.excluded ? "text-secondary bg-surface-inset" : "text-primary" %> text-sm font-medium p-4"+ <div class="group grid grid-cols-12 items-center [html[data-layout-animating]_&:not(:has([aria-expanded=true])):not(:has([role=tooltip]:not(.hidden)))]:[content-visibility:auto] [contain-intrinsic-size:auto_--spacing(18)] <%= entry.excluded ? "text-secondary bg-surface-inset" : "text-primary" %> text-sm font-medium p-4"data-controller="clickable-row"data-action="click->clickable-row#open"><div class="col-span-8 flex items-center gap-4">diff --git a/app/views/transactions/_split_parent_row.html.erb b/app/views/transactions/_split_parent_row.html.erbindex b35f8178f9..56a7d7d960 100644--- a/app/views/transactions/_split_parent_row.html.erb+++ b/app/views/transactions/_split_parent_row.html.erb@@ -1,7 +1,7 @@<%# locals: (entry:) %><% transaction = entry.entryable %>-<div class="group flex lg:grid lg:grid-cols-12 items-center text-sm font-medium p-3 lg:p-4 opacity-50 text-secondary"+<div class="group flex lg:grid lg:grid-cols-12 items-center text-sm font-medium p-3 lg:p-4 opacity-50 text-secondary [html[data-layout-animating]_&:not(:has([aria-expanded=true])):not(:has([role=tooltip]:not(.hidden)))]:[content-visibility:auto] [contain-intrinsic-size:auto_--spacing(18)]"data-controller="clickable-row"data-action="click->clickable-row#open"><div class="pr-4 lg:pr-10 flex items-center gap-3 lg:gap-4 col-span-8 min-w-0">diff --git a/app/views/transactions/_transaction.html.erb b/app/views/transactions/_transaction.html.erbindex 48ec9352e9..59f8f48b14 100644--- a/app/views/transactions/_transaction.html.erb+++ b/app/views/transactions/_transaction.html.erb@@ -15,7 +15,7 @@end %><%= turbo_frame_tag dom_id(entry) do %><%= turbo_frame_tag dom_id(transaction) do %>- <div class="group group/transaction flex lg:grid lg:grid-cols-12 items-center text-primary text-sm font-medium p-3 lg:p-4 <%= "pl-8 lg:pl-12" if in_split_group %>"+ <div class="group group/transaction flex lg:grid lg:grid-cols-12 items-center text-primary text-sm font-medium p-3 lg:p-4 [html[data-layout-animating]_&:not(:has([aria-expanded=true])):not(:has([role=tooltip]:not(.hidden)))]:[content-visibility:auto] [contain-intrinsic-size:auto_--spacing(18)] <%= "pl-8 lg:pl-12" if in_split_group %>"data-controller="clickable-row"data-action="click->clickable-row#open">diff --git a/app/views/valuations/_valuation.html.erb b/app/views/valuations/_valuation.html.erbindex a7c5f7cc0d..8f99b1f78a 100644--- a/app/views/valuations/_valuation.html.erb+++ b/app/views/valuations/_valuation.html.erb@@ -7,7 +7,7 @@<%= turbo_frame_tag dom_id(entry) do %><%= turbo_frame_tag dom_id(valuation) do %>- <div class="p-3 lg:p-4 grid grid-cols-12 items-center text-primary text-sm font-medium">+ <div class="p-3 lg:p-4 grid grid-cols-12 items-center text-primary text-sm font-medium [html[data-layout-animating]_&:not(:has([aria-expanded=true])):not(:has([role=tooltip]:not(.hidden)))]:[content-visibility:auto] [contain-intrinsic-size:auto_--spacing(18)]"><div class="col-span-8 flex items-center gap-3 lg:gap-4"><%= check_box_tag dom_id(entry, "selection"),class: "checkbox checkbox--light hidden lg:block",diff --git a/test/system/sidebar_animation_rows_test.rb b/test/system/sidebar_animation_rows_test.rbnew file mode 100644index 0000000000..df320c58c8--- /dev/null+++ b/test/system/sidebar_animation_rows_test.rb@@ -0,0 +1,699 @@+require "application_system_test_case"++# Each frame of a sidebar's width animation lays out everything beside it+# again, and a long activity list took most of a frame to lay out, so the+# animation stuttered on account pages. While a sidebar animates (or is+# dragged) the page is marked, and rows off screen skip layout. The mark comes+# off afterwards: left on, the containment would clip the rows' menus.+class SidebarAnimationRowsTest < ApplicationSystemTestCase+ include EntriesTestHelper++ setup do+ sign_in users(:family_admin)+ end++ test "activity rows skip layout only while a sidebar animates" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ row = "#main [data-controller~='clickable-row']"+ assert_selector row, minimum: 1++ # The toggle saves the preference first; the test layout has no csrf meta tag.+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))+ assert_equal "visible", page.evaluate_script(%(getComputedStyle(document.querySelector(#{row.to_json})).contentVisibility))++ page.execute_script(<<~JS)+ window.__frames = [];+ const sample = () => {+ window.__frames.push([document.documentElement.hasAttribute("data-layout-animating"), getComputedStyle(document.querySelector(#{row.to_json})).contentVisibility]);+ if (window.__frames.length < 90) requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ JS+ find("[data-action='app-layout#toggleLeftSidebar']").click+ sleep 1.5++ frames = page.evaluate_script("window.__frames")+ marked = frames.select(&:first)+ assert marked.any?, "the page was never marked while the sidebar animated"+ assert marked.all? { |_, visibility| visibility == "auto" }, "rows did not skip layout while the page was marked: #{marked.uniq.inspect}"+ assert_not page.evaluate_script(%(document.documentElement.hasAttribute("data-layout-animating"))), "the mark was left on after the animation"+ assert_equal "visible", page.evaluate_script(%(getComputedStyle(document.querySelector(#{row.to_json})).contentVisibility)), "rows still skip layout after the animation"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A drag holds the mark until the pointer is released. A pointer the browser+ # cancels (taking a touch over to scroll), or a second pointerdown during the+ # drag, must not leave it on: rows would keep skipping layout and clip menus.+ test "a cancelled or doubled sidebar drag does not leave the page marked" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ handle = "[data-action~='pointerdown->sidebar-resize#startLeft']"+ assert_selector handle, visible: :all++ marks = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector(#{handle.to_json});+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ const down = () => handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300 }));+ down();+ const duringDrag = marked();+ down();+ window.dispatchEvent(new PointerEvent("pointercancel", { bubbles: true }));+ const afterCancel = marked();+ down();+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true }));+ return { duringDrag, afterCancel, afterUp: marked() };+ })()+ JS++ assert marks["duringDrag"], "a drag did not mark the page"+ assert_not marks["afterCancel"], "a cancelled drag (after a second pointerdown) left the page marked"+ assert_not marks["afterUp"], "a released drag left the page marked"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # The fallback size stays on between animations: taken off, the browser+ # would forget each row's remembered size (contain-intrinsic-size: auto) and+ # every toggle would start the rows off screen at the fallback again.+ test "activity rows keep their remembered size between animations" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ row = "#main [data-controller~='clickable-row']"+ assert_selector row, minimum: 1++ style = page.evaluate_script(%((() => { const s = getComputedStyle(document.querySelector(#{row.to_json})); return [s.contentVisibility, s.containIntrinsicSize] })()))+ assert_equal [ "visible", "auto 72px" ], style+ end++ # A width committed from the divider's keyboard controls or a double-click+ # animates the sidebar too (its max-width), and lays out the rows each frame+ # like a toggle.+ test "a resize from the keyboard or a double-click marks the page until it stops" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ handle = "[data-action~='keydown->sidebar-resize#keyLeft']"+ assert_selector handle, visible: :all++ marks = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const handle = document.querySelector(#{handle.to_json});+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ handle.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));+ const afterKey = marked();+ setTimeout(() => {+ const keySettled = marked();+ handle.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ const afterReset = marked();+ setTimeout(() => done({ afterKey, keySettled, afterReset, resetSettled: marked() }), 1200);+ }, 1200);+ JS++ assert marks["afterKey"], "a keyboard resize did not mark the page"+ assert_not marks["keySettled"], "the mark was left on after the keyboard resize"+ assert marks["afterReset"], "a double-click reset did not mark the page"+ assert_not marks["resetSettled"], "the mark was left on after the reset"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A drag whose button is released outside the window, or whose window loses+ # focus, may never see its pointerup; losing the pointer capture or the focus+ # ends it, so the mark comes off and the next drag can start.+ test "a drag that loses the window's focus or its pointer capture ends" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ handle = "[data-action~='pointerdown->sidebar-resize#startLeft']"+ assert_selector handle, visible: :all++ marks = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector(#{handle.to_json});+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ const down = () => handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300 }));+ down();+ const duringDrag = marked();+ window.dispatchEvent(new Event("blur"));+ const afterBlur = marked();+ return { duringDrag, afterBlur };+ })()+ JS++ assert marks["duringDrag"], "a drag did not mark the page"+ assert_not marks["afterBlur"], "the window losing focus left the drag (and the mark) on"++ # A real mouse drag: the handle captures the pointer, and losing that+ # capture (as when the button is released outside the window) ends it.+ mouse = page.driver.browser.action+ # The drag's own pointer id (Chromium gives the mouse 1, Firefox can give 0).+ page.execute_script(%(document.querySelector(#{handle.to_json}).addEventListener("pointerdown", (event) => { window.dragPointerId = event.pointerId }, { once: true })))+ mouse.move_to(find(handle, visible: :all).native).click_and_hold.perform+ pointer_id = Integer(page.evaluate_script("window.dragPointerId"))+ captured = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector(#{handle.to_json});+ return { captured: handle.hasPointerCapture(#{pointer_id}), marked: document.documentElement.hasAttribute("data-layout-animating") };+ })()+ JS+ assert captured["captured"], "a drag did not capture its pointer"+ assert captured["marked"], "a second drag could not start after the interrupted one"++ page.execute_script(%(document.querySelector(#{handle.to_json}).releasePointerCapture(#{pointer_id})))+ # The capture change is processed with the next pointer event.+ mouse.move_by(4, 0).perform+ assert_selector "html:not([data-layout-animating])", visible: :all+ width = page.evaluate_script(%(document.querySelector("[data-app-layout-target='leftSidebar']").getBoundingClientRect().width))+ mouse.move_by(-60, 0).perform+ assert_equal width, page.evaluate_script(%(document.querySelector("[data-app-layout-target='leftSidebar']").getBoundingClientRect().width)), "the drag kept resizing after losing its pointer capture"+ mouse.release.perform+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A split transaction's parent row (created here: no fixture has one).+ test "split parent rows skip layout only while a sidebar animates" do+ entry = create_transaction(amount: 100, name: "Split for the sidebar test", account: accounts(:depository))+ entry.split!([ { name: "Part one", amount: 60, category_id: nil }, { name: "Part two", amount: 40, category_id: nil } ])+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ row = "#main .split-group > div:first-child"+ assert_selector row, minimum: 1+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))++ page.execute_script(<<~JS)+ window.__frames = [];+ const sample = () => {+ window.__frames.push([document.documentElement.hasAttribute("data-layout-animating"), getComputedStyle(document.querySelector(#{row.to_json})).contentVisibility]);+ if (window.__frames.length < 90) requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ JS+ find("[data-action='app-layout#toggleLeftSidebar']").click+ sleep 1.5++ marked = page.evaluate_script("window.__frames").select(&:first)+ assert marked.any?, "the page was never marked while the sidebar animated"+ assert marked.all? { |_, visibility| visibility == "auto" }, "split parent rows did not skip layout while the page was marked: #{marked.uniq.inspect}"+ assert_equal [ "visible", "auto 72px" ], page.evaluate_script(%((() => { const s = getComputedStyle(document.querySelector(#{row.to_json})); return [s.contentVisibility, s.containIntrinsicSize] })()))+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A drag started while a toggle is still animating turns the sidebar's+ # transition off, cancelling it with nothing replacing it: the toggle's+ # mark must come off with it, not linger until its fallback.+ test "a drag that interrupts a toggle leaves no mark once it ends" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))+ handle = "[data-action~='pointerdown->sidebar-resize#startLeft']"+ assert_selector handle, visible: :all++ marks = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ const sidebar = document.querySelector("[data-app-layout-target='leftSidebar']");+ let cancelled = false;+ sidebar.addEventListener("transitioncancel", (event) => { if (event.target === sidebar && event.propertyName === "width") cancelled = true; });+ document.querySelector("[data-action='app-layout#toggleLeftSidebar']").click();+ setTimeout(() => {+ const handle = document.querySelector(#{handle.to_json});+ handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300 }));+ // The drag lasts a few frames, so its transition: none takes effect.+ requestAnimationFrame(() => requestAnimationFrame(() => {+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true }));+ // Well inside the toggle's 600 ms fallback.+ setTimeout(() => done({ cancelled, afterDrag: marked() }), 200);+ }));+ }, 80);+ JS++ assert marks["cancelled"], "the drag did not cancel the toggle's transition: #{marks.inspect}"+ assert_not marks["afterDrag"], "the toggle's mark stayed on after the drag cancelled its transition"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # Trades are investment accounts' activity rows.+ test "trade rows skip layout only while a sidebar animates" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:investment))+ row = "#main turbo-frame[id^='trade_'] > div"+ assert_selector row, minimum: 1+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))++ page.execute_script(<<~JS)+ window.__frames = [];+ const sample = () => {+ window.__frames.push([document.documentElement.hasAttribute("data-layout-animating"), getComputedStyle(document.querySelector(#{row.to_json})).contentVisibility]);+ if (window.__frames.length < 90) requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ JS+ find("[data-action='app-layout#toggleLeftSidebar']").click+ sleep 1.5++ marked = page.evaluate_script("window.__frames").select(&:first)+ assert marked.any?, "the page was never marked while the sidebar animated"+ assert marked.all? { |_, visibility| visibility == "auto" }, "trade rows did not skip layout while the page was marked: #{marked.uniq.inspect}"+ assert_equal [ "visible", "auto 72px" ], page.evaluate_script(%((() => { const s = getComputedStyle(document.querySelector(#{row.to_json})); return [s.contentVisibility, s.containIntrinsicSize] })()))+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A stored width differing from the default must not animate the sidebar+ # each time the page loads (a Turbo visit swaps in a new sidebar), which+ # would lay out every row on each frame with nothing marked.+ test "a stored sidebar width applies on a visit without animating" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ page.execute_script(%(localStorage.setItem("sure.sidebarWidth.left", "400")))++ page.execute_script(<<~JS)+ window.__runs = [];+ document.addEventListener("transitionrun", (event) => {+ if (event.target.matches?.("[data-app-layout-target='leftSidebar']") && ["width", "max-width"].includes(event.propertyName)) window.__runs.push(event.propertyName);+ }, true);+ document.documentElement.dataset.visitDone = "";+ delete document.documentElement.dataset.visitDone;+ document.addEventListener("turbo:load", () => setTimeout(() => { document.documentElement.dataset.visitDone = "true" }, 700), { once: true });+ Turbo.visit(window.location.href);+ JS+ assert_selector "html[data-visit-done]", visible: :all, wait: 10++ assert_equal "400px", page.evaluate_script(%(getComputedStyle(document.querySelector("[data-app-layout-target='leftSidebar']")).maxWidth))+ assert_equal [], page.evaluate_script("window.__runs"), "the stored width animated the sidebar on the visit"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # Valuations are activity rows too (they have no clickable-row controller).+ test "valuation rows skip layout only while a sidebar animates" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ row = "#main turbo-frame[id^='valuation_'] > div"+ assert_selector row, minimum: 1+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))++ page.execute_script(<<~JS)+ window.__frames = [];+ const sample = () => {+ window.__frames.push([document.documentElement.hasAttribute("data-layout-animating"), getComputedStyle(document.querySelector(#{row.to_json})).contentVisibility]);+ if (window.__frames.length < 90) requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ JS+ find("[data-action='app-layout#toggleLeftSidebar']").click+ sleep 1.5++ marked = page.evaluate_script("window.__frames").select(&:first)+ assert marked.any?, "the page was never marked while the sidebar animated"+ assert marked.all? { |_, visibility| visibility == "auto" }, "valuation rows did not skip layout while the page was marked: #{marked.uniq.inspect}"+ assert_equal [ "visible", "auto 72px" ], page.evaluate_script(%((() => { const s = getComputedStyle(document.querySelector(#{row.to_json})); return [s.contentVisibility, s.containIntrinsicSize] })()))+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A keyboard resize (a max-width transition) and a toggle (a width+ # transition) can run at once; the first to end must not take the mark off+ # while the other is still moving the sidebar.+ test "overlapping width and max-width transitions keep the page marked until both end" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))+ handle = "[data-action~='keydown->sidebar-resize#keyLeft']"+ assert_selector handle, visible: :all++ marks = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const handle = document.querySelector(#{handle.to_json});+ const sidebar = document.querySelector("[data-app-layout-target='leftSidebar']");+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ const ended = {};+ // Both properties animate here whatever the layout's own transition+ // classes say, so the overlap happens even where only width animates.+ sidebar.style.transitionProperty = "width, max-width";+ handle.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));+ // Added after the keydown created the mark, so it runs after the mark's+ // own transitionend listener and sees what that left.+ sidebar.addEventListener("transitionend", (event) => {+ if (event.target === sidebar && ["width", "max-width"].includes(event.propertyName) && !(event.propertyName in ended)) ended[event.propertyName] = marked();+ });+ setTimeout(() => {+ document.querySelector("[data-action='app-layout#toggleLeftSidebar']").click();+ setTimeout(() => done({ ended, after: marked() }), 1500);+ }, 80);+ JS++ assert_equal [ "max-width", "width" ], marks["ended"].keys.sort, "both transitions should have run: #{marks.inspect}"+ assert marks["ended"]["max-width"], "the mark came off when the max-width transition ended, with the width one still running"+ assert_not marks["after"], "the mark was left on after both transitions ended"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A resize from the keyboard just as a toggle finishes: the toggle's width+ # transition can end just before the resize's max-width transition starts.+ # The mark stays on for the new transition rather than coming off between+ # the two.+ test "a transition starting just after another ends keeps the page marked" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))+ handle = "[data-action~='keydown->sidebar-resize#keyLeft']"+ assert_selector handle, visible: :all++ marks = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const handle = document.querySelector(#{handle.to_json});+ const sidebar = document.querySelector("[data-app-layout-target='leftSidebar']");+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ const frame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));+ const transition = (type, propertyName) => sidebar.dispatchEvent(new TransitionEvent(type, { propertyName }));+ // The events are replayed in that order; the sidebar's own transitions+ // are off so that none of its real ones interleave.+ sidebar.style.transition = "none";+ handle.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));+ transition("transitionrun", "width");+ (async () => {+ await frame();+ transition("transitionend", "width");+ const betweenEndAndRun = marked();+ await frame();+ transition("transitionrun", "max-width");+ await frame();+ await frame();+ await frame();+ const duringNext = marked();+ transition("transitionend", "max-width");+ await frame();+ await frame();+ await frame();+ done({ betweenEndAndRun, duringNext, after: marked() });+ })();+ JS++ assert marks["betweenEndAndRun"], "the mark came off as soon as the first transition ended"+ assert marks["duringNext"], "the mark came off before the next transition, which started a frame later, ended"+ assert_not marks["after"], "the mark was left on after the last transition ended"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # Stimulus reuses the controller when its element connects again, so a drag+ # in progress at disconnect must end, not stay set and block the next one.+ test "a drag in progress when the controller disconnects ends" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ handle = "[data-action~='pointerdown->sidebar-resize#startLeft']"+ assert_selector handle, visible: :all++ page.execute_script(<<~JS)+ document.querySelector(#{handle.to_json}).dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300 }));+ window.__layout = document.querySelector("[data-controller~='sidebar-resize']");+ window.__layout.dataset.controller = window.__layout.dataset.controller.replace("sidebar-resize", "").trim();+ JS+ assert_selector "html:not([data-layout-animating])", visible: :all+ page.execute_script(%(window.__layout.dataset.controller += " sidebar-resize"))+ assert_selector "[data-controller~='sidebar-resize']", visible: :all++ state = page.evaluate_script(<<~JS)+ (() => {+ const before = { cursor: document.body.style.cursor, userSelect: document.body.style.userSelect };+ document.querySelector(#{handle.to_json}).dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300 }));+ const secondDrag = document.documentElement.hasAttribute("data-layout-animating");+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true }));+ return { ...before, secondDrag };+ })()+ JS++ assert_equal "", state["cursor"], "the drag's cursor stayed on after the disconnect"+ assert_equal "", state["userSelect"], "text selection stayed off after the disconnect"+ assert state["secondDrag"], "a new drag could not start after the controller connected again"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # Toggling the same sidebar again while it moves reverses its transition: the+ # old one is cancelled and a new one runs, which must keep the mark until it+ # ends.+ test "a sidebar toggled again mid-animation keeps the page marked until it stops" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))++ marks = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const toggle = document.querySelector("[data-action='app-layout#toggleLeftSidebar']");+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ toggle.click();+ setTimeout(() => {+ toggle.click();+ setTimeout(() => {+ const duringReversal = marked();+ setTimeout(() => done({ duringReversal, after: marked() }), 1200);+ // Well inside the reversed transition, which runs only as long as the+ // first had already run (about 100ms of its 300ms).+ }, 40);+ }, 100);+ JS++ assert marks["duringReversal"], "the reversed animation ran without the mark"+ assert_not marks["after"], "the mark was left on after the reversed animation"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # Paint containment clips a row's fixed-position menus to the row. A tag+ # picker or menu stays open until a click outside it, so one opened before a+ # drag starts stays open through it: its row is not contained.+ test "a row with an open tag picker is not contained while a sidebar is dragged" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ row = "#main [data-controller~='clickable-row']"+ picker = "[data-DS--popover-target='button']"+ assert_selector "#{row} #{picker}", minimum: 1+ page.execute_script(%(document.querySelector(#{row.to_json}).scrollIntoView({ block: "center" })))+ first(:css, "#{row} #{picker}").click+ assert_selector "#{row} #{picker}[aria-expanded='true']"++ styles = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector("[data-action~='pointerdown->sidebar-resize#startLeft']");+ handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300, pointerId: 1 }));+ const rows = Array.from(document.querySelectorAll(#{row.to_json}));+ const open = rows.find((r) => r.querySelector("#{picker}[aria-expanded='true']"));+ const other = rows.find((r) => r !== open);+ const result = {+ marked: document.documentElement.hasAttribute("data-layout-animating"),+ open: getComputedStyle(open).contentVisibility,+ other: other && getComputedStyle(other).contentVisibility,+ };+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: 300, pointerId: 1 }));+ return result;+ })()+ JS++ assert styles["marked"], "the drag did not mark the page"+ assert_equal "visible", styles["open"], "the row with an open tag picker was contained (clipping the picker) during the drag"+ assert_equal "auto", styles["other"], "the other rows stopped skipping layout during the drag"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # The investment activity-label quick-edit opens its own dropdown (not a+ # DS menu), which also stays open until a click outside it: its badge says+ # so (aria-expanded), and its row is not contained either.+ test "a trade row with an open activity-label dropdown is not contained while a sidebar is dragged" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:investment))+ row = "#main turbo-frame[id^='trade_'] > div"+ badge = "button[data-activity-label-quick-edit-target='badge']"+ assert_selector "#{row} #{badge}", minimum: 1+ page.execute_script(%(document.querySelector(#{row.to_json}).scrollIntoView({ block: "center" })))+ first(:css, "#{row} #{badge}").click+ assert_selector "#{row} [data-activity-label-quick-edit-target='dropdown']:not(.hidden)"+ assert_selector "#{row} #{badge}[aria-expanded='true']"++ styles = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector("[data-action~='pointerdown->sidebar-resize#startLeft']");+ handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300, pointerId: 1 }));+ const rows = Array.from(document.querySelectorAll(#{row.to_json}));+ const open = rows.find((r) => r.querySelector("[data-activity-label-quick-edit-target='dropdown']:not(.hidden)"));+ const other = rows.find((r) => r !== open);+ const result = {+ marked: document.documentElement.hasAttribute("data-layout-animating"),+ open: getComputedStyle(open).contentVisibility,+ other: other && getComputedStyle(other).contentVisibility,+ };+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: 300, pointerId: 1 }));+ return result;+ })()+ JS++ assert styles["marked"], "the drag did not mark the page"+ assert_equal "visible", styles["open"], "the row with an open activity-label dropdown was contained (clipping it) during the drag"+ assert_equal "auto", styles["other"], "the other rows stopped skipping layout during the drag" if styles["other"]++ # Closing it (a click outside) says so too.+ find("#main h1, #main h2", match: :first).click+ assert_selector "#{row} #{badge}[aria-expanded='false']", minimum: 1+ assert_no_selector "#{row} #{badge}[aria-expanded='true']"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # Only the pointer that started a drag moves or ends it: a second finger the+ # browser cancels (to scroll) must not end a mouse or stylus drag still held.+ test "another pointer's events neither move nor end a drag" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ handle = "[data-action~='pointerdown->sidebar-resize#startLeft']"+ assert_selector handle, visible: :all++ result = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector(#{handle.to_json});+ const sidebar = document.querySelector("[data-app-layout-target='leftSidebar']");+ const marked = () => document.documentElement.hasAttribute("data-layout-animating");+ const width = () => getComputedStyle(document.querySelector("[data-controller~='sidebar-resize']")).getPropertyValue("--left-sidebar-width");+ const left = sidebar.getBoundingClientRect().left;+ handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: left + 300, pointerId: 1 }));+ const before = width();+ window.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, clientX: left + 260, pointerId: 2 }));+ const afterOtherMove = width();+ window.dispatchEvent(new PointerEvent("pointercancel", { bubbles: true, pointerId: 2 }));+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: left + 260, pointerId: 2 }));+ const afterOtherEnd = marked();+ window.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, clientX: left + 280, pointerId: 1 }));+ const afterOwnMove = width();+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: left + 280, pointerId: 1 }));+ return { before, afterOtherMove, afterOtherEnd, afterOwnMove, afterOwnEnd: marked() };+ })()+ JS++ assert_equal result["before"], result["afterOtherMove"], "another pointer's move resized the sidebar: #{result.inspect}"+ assert result["afterOtherEnd"], "another pointer's cancel or release ended the drag: #{result.inspect}"+ assert_not_equal result["before"], result["afterOwnMove"], "the drag's own pointer stopped resizing after another pointer ended: #{result.inspect}"+ assert_not result["afterOwnEnd"], "the drag's own pointer release did not end it: #{result.inspect}"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A release can arrive before the last move's width is laid out. Restoring+ # the sidebar's transitions then animated that last change (max-width) after+ # the drag, laying the rows out on every frame of it.+ test "a drag's last width is laid out before the sidebar's transitions return" do+ page.driver.browser.manage.window.resize_to(1400, 1000)+ visit account_path(accounts(:depository))+ handle = "[data-action~='pointerdown->sidebar-resize#startLeft']"+ assert_selector handle, visible: :all++ runs = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const handle = document.querySelector(#{handle.to_json});+ const sidebar = document.querySelector("[data-app-layout-target='leftSidebar']");+ const runs = [];+ sidebar.addEventListener("transitionrun", (event) => { if (event.target === sidebar) runs.push(event.propertyName); });+ const left = sidebar.getBoundingClientRect().left;+ // In one task: no layout between the last move and the release.+ handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: left + 300, pointerId: 1 }));+ window.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, clientX: left + 240, pointerId: 1 }));+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: left + 240, pointerId: 1 }));+ setTimeout(() => done(runs), 500);+ JS++ assert_empty runs, "the sidebar animated after the drag ended: #{runs.inspect}"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A pending transfer's tooltip shows and hides itself (no aria-expanded),+ # and can stay open as a drag starts: the divider keeps the focus. Its row+ # is not contained either, or the containment would clip the tooltip.+ test "a row with an open tooltip is not contained while a sidebar is dragged" do+ users(:family_admin).update!(show_ai_sidebar: false)+ page.driver.browser.manage.window.resize_to(1400, 1000)+ outflow = create_transaction(name: "Payment to credit card", amount: 100)+ inflow = create_transaction(name: "Payment received", amount: -100, account: accounts(:credit_card))+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable)+ visit transactions_path+ match = "##{dom_id(outflow.entryable, :transfer_match)}"+ row = "#main [data-controller~='clickable-row']"+ assert_selector match+ find("#{match} [data-testid='transfer-match-pill']", visible: true).hover+ assert_selector "#{match} [role='tooltip']", visible: true++ styles = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector("[data-action~='pointerdown->sidebar-resize#startLeft']");+ handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: 300, pointerId: 1 }));+ const rows = Array.from(document.querySelectorAll(#{row.to_json}));+ const open = rows.find((r) => r.querySelector("[role='tooltip']:not(.hidden)"));+ const other = rows.find((r) => r !== open);+ const result = {+ marked: document.documentElement.hasAttribute("data-layout-animating"),+ open: open && getComputedStyle(open).contentVisibility,+ other: other && getComputedStyle(other).contentVisibility,+ };+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: 300, pointerId: 1 }));+ return result;+ })()+ JS++ assert styles["marked"], "the drag did not mark the page"+ assert_equal "visible", styles["open"], "the row with an open tooltip was contained (clipping the tooltip) during the drag"+ assert_equal "auto", styles["other"], "the other rows stopped skipping layout during the drag"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A click on a divider (no movement) changes nothing. Its position, read+ # against the sidebars' current sizes, could otherwise clamp the width and+ # save it: a left sidebar widened while the right one was closed shrank on+ # a click once the right one was open.+ test "a click on a divider leaves the sidebar's width as it was" do+ users(:family_admin).update!(show_ai_sidebar: false)+ page.driver.browser.manage.window.resize_to(1100, 900)+ visit account_path(accounts(:depository))+ page.execute_script(%(localStorage.setItem("sure.sidebarWidth.left", "480"); localStorage.setItem("sure.sidebarWidth.right", "240")))+ visit account_path(accounts(:depository))+ root = "[data-controller~='sidebar-resize']"+ assert_equal "480px", page.evaluate_script(%(document.querySelector(#{root.to_json}).style.getPropertyValue("--left-sidebar-width")))++ # The toggle saves the preference first; the test layout has no csrf meta tag.+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))+ find("[data-action='app-layout#toggleRightSidebar']").click+ page.document.synchronize(5) do+ width = page.evaluate_script(%(Math.round(document.querySelector("[data-app-layout-target='rightSidebar']").getBoundingClientRect().width)))+ raise Capybara::ExpectationNotMet, "the right sidebar is not open yet: #{width}" unless width == 240+ end++ result = page.evaluate_script(<<~JS)+ (() => {+ const handle = document.querySelector("[data-action~='pointerdown->sidebar-resize#startLeft']");+ const sidebar = document.querySelector("[data-app-layout-target='leftSidebar']");+ const x = sidebar.getBoundingClientRect().right;+ const rendered = () => Math.round(sidebar.getBoundingClientRect().width);+ const before = rendered();+ handle.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, clientX: x, pointerId: 1 }));+ window.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: x, pointerId: 1 }));+ return {+ before,+ after: rendered(),+ variable: document.querySelector(#{root.to_json}).style.getPropertyValue("--left-sidebar-width"),+ stored: localStorage.getItem("sure.sidebarWidth.left"),+ };+ })()+ JS++ assert_equal "480px", result["variable"], "a click changed the sidebar's width: #{result.inspect}"+ assert_equal "480", result["stored"], "a click saved a different width: #{result.inspect}"+ assert_equal result["before"], result["after"], "a click changed the sidebar's rendered width: #{result.inspect}"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end+end