Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Keep a sidebar group's total in line at a narrow sidebar width (#4909)

Yong Cong Sin3dbc78b57a90
diff --git a/app/components/DS/disclosure.html.erb b/app/components/DS/disclosure.html.erb
index 5b10224f14..e8d248d3af 100644
--- a/app/components/DS/disclosure.html.erb
+++ b/app/components/DS/disclosure.html.erb
@@ -1,5 +1,5 @@
<%= tag.details class: details_classes, open: open, **details_opts do %>
- <%= tag.summary class: summary_classes, aria: summary_aria_attrs do %>
+ <%= tag.summary class: summary_classes, aria: summary_aria_attrs, data: summary_data do %>
<% if summary_content? %>
<% if variant.in?(%i[default bare]) %>
<%# `:default` summary is already `flex justify-between`, so
diff --git a/app/components/DS/disclosure.rb b/app/components/DS/disclosure.rb
index e31c71b3f5..604b50c933 100644
--- a/app/components/DS/disclosure.rb
+++ b/app/components/DS/disclosure.rb
@@ -3,7 +3,7 @@ class DS::Disclosure < DesignSystemComponent
VARIANTS = %i[default card card_inset inline bare].freeze
- attr_reader :title, :align, :open, :variant, :summary_class_override, :summary_aria_label, :body_class, :opts
+ attr_reader :title, :align, :open, :variant, :summary_class_override, :summary_aria_label, :summary_data, :body_class, :opts
# `:default` — bg-surface summary, no chrome on the `<details>`. Use
# for inline expanders that sit inside a parent card (the summary
@@ -37,13 +37,14 @@ class DS::Disclosure < DesignSystemComponent
# `body_class:` styles the wrapper around the disclosure body (ignored for
# `:bare`, which renders no wrapper). Defaults to `mt-2` (the standard gap
# below the summary). Pass `nil`/`""` to drop it on non-bare variants.
- def initialize(title: nil, align: "right", open: false, variant: :default, summary_class: nil, summary_aria_label: nil, body_class: "mt-2", **opts)
+ def initialize(title: nil, align: "right", open: false, variant: :default, summary_class: nil, summary_aria_label: nil, summary_data: {}, body_class: "mt-2", **opts)
@title = title
@align = align.to_sym
@open = open
@variant = variant&.to_sym
@summary_class_override = summary_class
@summary_aria_label = summary_aria_label
+ @summary_data = summary_data
@body_class = body_class
@opts = opts
diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb
index ed77623187..c2bc40ccc0 100644
--- a/app/helpers/accounts_helper.rb
+++ b/app/helpers/accounts_helper.rb
@@ -97,7 +97,7 @@ module AccountsHelper
.pick(Arel.sql("count(*)"), Arel.sql("max(account_providers.updated_at)"))
[
- family.build_cache_key("account_sidebar_tabs_v9", invalidate_on_data_updates: true),
+ family.build_cache_key("account_sidebar_tabs_v10", invalidate_on_data_updates: true),
Current.user&.id,
shares_version,
providers_version,
diff --git a/app/javascript/controllers/sidebar_name_marquee_controller.js b/app/javascript/controllers/sidebar_name_marquee_controller.js
new file mode 100644
index 0000000000..c347800ca4
--- /dev/null
+++ b/app/javascript/controllers/sidebar_name_marquee_controller.js
@@ -0,0 +1,87 @@
+import { Controller } from "@hotwired/stimulus";
+
+// A group name cut short in a narrow sidebar slides once to show its end and
+// back when its group is tapped (a touch or a pen) or gets keyboard focus;
+// on hover its title shows the full name. One pass, well under five seconds,
+// then it rests. With reduced motion the layout shows the full name instead
+// (the total moves below it), so nothing moves; a tap where the main pointer
+// is fine (a touchscreen laptop) has no such layout, so the tap shows it.
+// Sits on the group's <summary>, which declares the focus and pointerup
+// actions.
+export default class extends Controller {
+ static targets = ["name", "text"];
+
+ connect() {
+ // A page Turbo cached mid-slide (or mid-reveal) keeps those styles and
+ // marks; start at rest.
+ this.#rest();
+ this.element.removeAttribute("data-name-revealed");
+ }
+
+ disconnect() {
+ this.animation?.cancel();
+ }
+
+ focus() {
+ if (this.element.matches(":focus-visible")) this.#play();
+ }
+
+ // A mouse has hover, so the title shows the full name; any other pointer
+ // (a finger, a pen that doesn't hover) gets the slide or the full name.
+ tap(event) {
+ if (event.pointerType === "mouse") return;
+ if (this.#reducedMotion()) {
+ if (this.#isCut()) this.element.setAttribute("data-name-revealed", "");
+ } else {
+ this.#play();
+ }
+ }
+
+ #reducedMotion() {
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ }
+
+ #isCut() {
+ return this.nameTarget.scrollWidth - this.nameTarget.clientWidth > 1;
+ }
+
+ #play() {
+ if (this.#reducedMotion()) return;
+ if (this.animation?.playState === "running") return;
+
+ const distance = this.nameTarget.scrollWidth - this.nameTarget.clientWidth;
+ if (distance <= 1) return;
+
+ // About 40px a second, within 0.6-1.6s each way, with a short pause
+ // before setting off and a longer one at the end of the name.
+ const travel = Math.min(Math.max(distance * 25, 600), 1600);
+ const startPause = 400;
+ const endPause = 1000;
+ const duration = startPause + travel + endPause + travel;
+ const at = (ms) => ms / duration;
+ const shown = `translateX(-${distance}px)`;
+
+ // At rest the name is inline, so the ellipsis shows where it is cut; it
+ // only becomes a box (which can move, and which no ellipsis can cut)
+ // while it slides, without an ellipsis riding over it.
+ this.nameTarget.style.textOverflow = "clip";
+ this.textTarget.style.display = "inline-block";
+ this.animation = this.textTarget.animate(
+ [
+ { transform: "translateX(0)", offset: 0 },
+ { transform: "translateX(0)", offset: at(startPause) },
+ { transform: shown, offset: at(startPause + travel) },
+ { transform: shown, offset: at(startPause + travel + endPause) },
+ { transform: "translateX(0)", offset: 1 },
+ ],
+ { duration, easing: "ease-in-out" },
+ );
+ this.animation.addEventListener("finish", this.#rest);
+ this.animation.addEventListener("cancel", this.#rest);
+ }
+
+ #rest = () => {
+ this.nameTarget.style.textOverflow = "";
+ this.textTarget.style.display = "";
+ };
+}
diff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erb
index ab74b50704..02addb92f4 100644
--- a/app/views/accounts/_account_sidebar_tabs.html.erb
+++ b/app/views/accounts/_account_sidebar_tabs.html.erb
@@ -4,7 +4,7 @@
ERB dependency tracker mis-parses as a bogus "Ds/D" template dependency
and then logs "Couldn't find template for digesting: Ds/D" on every cache
miss. The cache key is already manually versioned via
- account_sidebar_tabs_cache_key ("account_sidebar_tabs_v9",
+ account_sidebar_tabs_cache_key ("account_sidebar_tabs_v10",
invalidate_on_data_updates: true), so we opt out of automatic template
digesting. Bump that version suffix when changing this template or its
sidebar dependencies. %>
diff --git a/app/views/accounts/_accountable_group.html.erb b/app/views/accounts/_accountable_group.html.erb
index f1712a97f7..9285e2b49d 100644
--- a/app/views/accounts/_accountable_group.html.erb
+++ b/app/views/accounts/_accountable_group.html.erb
@@ -3,28 +3,45 @@
<% copy = account_group.dom_id(tab: all_tab ? :all : nil, mobile: mobile) %>
<div id="<%= copy %>" data-group-key="<%= account_group.key %>">
<% is_open = open.nil? ? (account_group.accounts.any? { |account| page_active?(account_path(account)) } || Current.user.always_expanded_account_group?(account_group.key)) : open %>
- <%= render DS::Disclosure.new(align: :left, open: is_open) do |disclosure| %>
+ <%# The summary owns the name's slide: it is what a tap or keyboard focus
+ lands on (sidebar_name_marquee_controller). %>
+ <%= render DS::Disclosure.new(align: :left, open: is_open,
+ summary_data: { controller: "sidebar-name-marquee",
+ action: "focus->sidebar-name-marquee#focus pointerup->sidebar-name-marquee#tap" }) do |disclosure| %>
<% disclosure.with_summary_content do %>
- <div class="flex items-center gap-3">
- <%= icon "chevron-right", class: "group-open:transform group-open:rotate-90" %>
- <%= tag.span class: class_names("text-sm text-primary font-medium", "animate-pulse" => account_group.syncing?) do %>
- <%= account_group.name %>
- <% end %>
- </div>
+ <%# The name gives way (truncating) to the total, so a long group name
+ can't push the total out of line at a narrow sidebar width; the
+ title shows the full name on hover. With no hover (a touch screen)
+ or with keyboard focus, a cut name slides once to show its end
+ (sidebar_name_marquee_controller). With reduced motion the name
+ keeps its full width there instead, and a total that no longer
+ fits moves to the line below, still on the right; a tap on a
+ screen whose main pointer is fine does the same (the controller
+ marks the summary data-name-revealed). %>
+ <div class="flex items-center w-full min-w-0 gap-x-2 pointer-coarse:motion-reduce:flex-wrap [summary:focus-visible_&]:motion-reduce:flex-wrap in-data-name-revealed:flex-wrap">
+ <div class="flex items-center gap-3 min-w-0 pointer-coarse:motion-reduce:shrink-0 pointer-coarse:motion-reduce:max-w-full [summary:focus-visible_&]:motion-reduce:shrink-0 [summary:focus-visible_&]:motion-reduce:max-w-full in-data-name-revealed:shrink-0 in-data-name-revealed:max-w-full">
+ <%= icon "chevron-right", class: "shrink-0 group-open:transform group-open:rotate-90" %>
+ <%= tag.span class: class_names("text-sm text-primary font-medium truncate pointer-coarse:motion-reduce:whitespace-normal [summary:focus-visible_&]:motion-reduce:whitespace-normal in-data-name-revealed:whitespace-normal", "animate-pulse" => account_group.syncing?),
+ title: account_group.name,
+ data: { sidebar_name_marquee_target: "name" } do %>
+ <%= tag.span account_group.name, data: { sidebar_name_marquee_target: "text" } %>
+ <% end %>
+ </div>
- <div class="ml-auto text-right grow">
- <%= tag.p format_money(account_group.total_money), class: "text-sm font-medium text-primary privacy-sensitive" %>
- <% group_version = sidebar_sparkline_versions(Current.family)[account_group.accountable_type] %>
- <%= tag.div id: sidebar_sparkline_wrapper_id(copy, "total", group_version), data: kept_element_data do %>
- <%= turbo_frame_tag "#{account_group.key}_sparkline",
- src: accountable_sparkline_path(account_group.key, v: group_version),
- loading: "lazy",
- data: sparkline_frame_data do %>
- <div class="flex items-center w-8 h-4 ml-auto">
- <div class="w-6 h-px bg-loader"></div>
- </div>
+ <div class="ml-auto text-right shrink-0">
+ <%= tag.p format_money(account_group.total_money), class: "text-sm font-medium text-primary whitespace-nowrap privacy-sensitive" %>
+ <% group_version = sidebar_sparkline_versions(Current.family)[account_group.accountable_type] %>
+ <%= tag.div id: sidebar_sparkline_wrapper_id(copy, "total", group_version), data: kept_element_data do %>
+ <%= turbo_frame_tag "#{account_group.key}_sparkline",
+ src: accountable_sparkline_path(account_group.key, v: group_version),
+ loading: "lazy",
+ data: sparkline_frame_data do %>
+ <div class="flex items-center w-8 h-4 ml-auto">
+ <div class="w-6 h-px bg-loader"></div>
+ </div>
+ <% end %>
<% end %>
- <% end %>
+ </div>
</div>
<% end %>
diff --git a/test/components/DS/disclosure_test.rb b/test/components/DS/disclosure_test.rb
index 583c7f9d26..84d9ca9463 100644
--- a/test/components/DS/disclosure_test.rb
+++ b/test/components/DS/disclosure_test.rb
@@ -25,6 +25,13 @@ class DS::DisclosureTest < ViewComponent::TestCase
assert_selector "details > div", text: "body text"
end
+ test "summary_data puts data attributes on the summary, not the details" do
+ render_inline(DS::Disclosure.new(title: "More", summary_data: { controller: "probe", action: "pointerup->probe#tap" })) { "body text" }
+
+ assert_selector "details > summary[data-controller='probe'][data-action='pointerup->probe#tap']"
+ assert_no_selector "details[data-controller]"
+ end
+
test "forwards data attributes and a summary_class override" do
render_inline(DS::Disclosure.new(
summary_class: "custom-summary",
diff --git a/test/system/sidebar_narrow_test.rb b/test/system/sidebar_narrow_test.rb
new file mode 100644
index 0000000000..79d10dab18
--- /dev/null
+++ b/test/system/sidebar_narrow_test.rb
@@ -0,0 +1,281 @@
+require "application_system_test_case"
+
+# At the sidebar's narrowest width a group's name must give way to its total:
+# a longer name ("Investments", "Other Liabilities") used to push the amount
+# out of line with the other groups' amounts or onto a second line.
+class SidebarNarrowTest < ApplicationSystemTestCase
+ setup { sign_in users(:family_admin) }
+
+ test "at the narrowest sidebar every group's total stays on one line and lines up" do
+ page.driver.browser.manage.window.resize_to(1400, 1000)
+ visit root_path
+ page.execute_script(%(localStorage.setItem("sure.sidebarWidth.left", "240")))
+ visit root_path
+ assert_left_sidebar_width 240
+
+ totals = page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary p.privacy-sensitive"))
+ .filter((p) => p.offsetParent)
+ .map((p) => { const r = p.getBoundingClientRect(); return { right: Math.round(r.right), lines: Math.round(r.height / parseFloat(getComputedStyle(p).lineHeight)) } })
+ JS
+
+ assert_operator totals.size, :>=, 3
+ assert_equal [ 1 ], totals.map { |total| total["lines"] }.uniq, "a group total wrapped"
+ assert_equal 1, totals.map { |total| total["right"] }.uniq.size, "the group totals don't line up: #{totals.inspect}"
+
+ names = page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary span.font-medium"))
+ .filter((span) => span.offsetParent)
+ .map((span) => ({ name: span.textContent.trim(), title: span.title, ellipsis: getComputedStyle(span).textOverflow === "ellipsis", cut: span.scrollWidth > span.clientWidth }))
+ JS
+
+ assert_equal totals.size, names.size, "every visible group's name should be checked"
+ assert names.all? { |name| name["ellipsis"] && name["title"] == name["name"] }, "group names must truncate with their full name as the title: #{names.inspect}"
+ assert names.any? { |name| name["cut"] }, "expected a long group name (e.g. Investments) to be cut at this width: #{names.inspect}"
+ ensure
+ page.execute_script(%(localStorage.removeItem("sure.sidebarWidth.left")))
+ end
+
+ # The full name is in the title, which only a hover shows. A cut name
+ # slides once to show its end when its group is tapped or gets keyboard
+ # focus; with reduced motion the full name shows instead, with the total
+ # moved below it.
+ test "a cut group name slides once to show its end when its group is tapped" do
+ skip "needs Chrome DevTools touch input" unless page.driver.browser.respond_to?(:execute_cdp)
+ narrow_sidebar(touch: true)
+ cut = visible_group_names.find { |name| name["cut"] }
+ assert cut, "expected a long group name to be cut at this width"
+ assert_equal "inline", marquee(cut["name"])["display"], "a cut name must show its ellipsis before it slides"
+
+ tap_group(cut["name"])
+ page.document.synchronize { raise Capybara::ExpectationNotMet, "no slide started" unless marquee(cut["name"])["running"] }
+ sleep 1.2
+ moving = marquee(cut["name"])
+ assert_operator moving["shift"], :<, 0, "the name did not slide: #{moving.inspect}"
+ assert_equal "clip", moving["textOverflow"], "the ellipsis rides over the moving name"
+
+ page.document.synchronize(6) { raise Capybara::ExpectationNotMet, "still sliding" if marquee(cut["name"])["running"] }
+ rested = marquee(cut["name"])
+ assert_equal 0, rested["shift"], "the name did not come back"
+ assert_equal "", rested["textOverflow"], "the ellipsis did not come back"
+ assert_equal "inline", rested["display"], "at rest the name must be inline, or its ellipsis can't show"
+ assert visible_group_names.none? { |name| name["totalBelow"] }, "a total moved below its name"
+ ensure
+ reset_emulation
+ end
+
+ # Turbo caches a copy of the page when leaving it, so a name that was
+ # sliding at that moment comes back with its sliding styles.
+ test "a name cached mid-slide is back at rest, with its ellipsis, when the page is restored" do
+ narrow_sidebar
+ cut = visible_group_names.find { |name| name["cut"] }
+ assert cut, "expected a long group name to be cut at this width"
+
+ # The styles a slide puts on the name, as the cached copy keeps them.
+ page.execute_script(<<~JS, cut["name"])
+ const span = Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary span.font-medium"))
+ .find((s) => s.offsetParent && s.textContent.trim() === arguments[0]);
+ span.style.textOverflow = "clip";
+ span.querySelector("[data-sidebar-name-marquee-target='text']").style.display = "inline-block";
+ JS
+ assert_equal "clip", marquee(cut["name"])["textOverflow"]
+
+ page.execute_script(%(Turbo.visit("#{transactions_path}")))
+ assert_current_path transactions_path
+ page.go_back
+ assert_current_path root_path
+
+ page.document.synchronize do
+ rested = marquee(cut["name"])
+ raise Capybara::ExpectationNotMet, "the restored name kept its sliding styles: #{rested.inspect}" unless rested["textOverflow"] == "" && rested["display"] == "inline"
+ end
+ restored = page.evaluate_script(<<~JS, cut["name"])
+ (() => {
+ const span = Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary span.font-medium"))
+ .find((s) => s.offsetParent && s.textContent.trim() === arguments[0]);
+ return { ellipsis: getComputedStyle(span).textOverflow === "ellipsis", cut: span.scrollWidth > span.clientWidth };
+ })()
+ JS
+ assert restored["cut"], "expected the restored name to still be cut"
+ assert restored["ellipsis"], "the restored name lost its ellipsis"
+ ensure
+ reset_emulation
+ end
+
+ test "a name that fits, or a mouse click, does not slide" do
+ skip "needs Chrome DevTools touch input" unless page.driver.browser.respond_to?(:execute_cdp)
+ narrow_sidebar(touch: true)
+ fits = visible_group_names.find { |name| !name["cut"] }
+ tap_group(fits["name"])
+ sleep 0.3
+ assert_not marquee(fits["name"])["running"], "a name that fits slid"
+
+ reset_emulation
+ narrow_sidebar
+ cut = visible_group_names.find { |name| name["cut"] }
+ group_summary(cut["name"]).click
+ sleep 0.3
+ assert_not marquee(cut["name"])["running"], "a mouse click made the name slide"
+ ensure
+ reset_emulation
+ end
+
+ test "a cut group name slides while its group has keyboard focus" do
+ narrow_sidebar
+ cut = visible_group_names.find { |name| name["cut"] }
+ assert cut, "expected a long group name to be cut at this width"
+ page.execute_script(<<~JS, cut["name"])
+ Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary"))
+ .find((s) => s.offsetParent && s.querySelector("span.font-medium").textContent.trim() === arguments[0])
+ .focus({ focusVisible: true });
+ JS
+
+ page.document.synchronize { raise Capybara::ExpectationNotMet, "no slide on keyboard focus" unless marquee(cut["name"])["running"] }
+ ensure
+ page.execute_script(%(localStorage.removeItem("sure.sidebarWidth.left"))) rescue nil
+ end
+
+ test "with reduced motion on a touch screen a long group name shows in full and its total moves below it" do
+ skip "needs Chrome DevTools touch emulation" unless page.driver.browser.respond_to?(:execute_cdp)
+ page.driver.browser.execute_cdp("Emulation.setEmulatedMedia", features: [ { name: "prefers-reduced-motion", value: "reduce" } ])
+ narrow_sidebar(touch: true)
+
+ names = visible_group_names
+ assert names.none? { |name| name["cut"] }, "a group name is still cut: #{names.inspect}"
+ assert names.any? { |name| name["totalBelow"] }, "no long group name moved its total below it: #{names.inspect}"
+ assert_equal [ 1 ], names.map { |name| name["totalLines"] }.uniq, "a group total wrapped"
+ assert_equal 1, names.map { |name| name["totalRight"] }.uniq.size, "the group totals don't line up on the right: #{names.inspect}"
+
+ tap_group(names.find { |name| name["totalBelow"] }["name"])
+ sleep 0.3
+ assert names.none? { |name| marquee(name["name"])["running"] }, "a name slid with reduced motion"
+ ensure
+ reset_emulation
+ end
+
+ # A pen that doesn't hover can't show the title either, so its tap slides
+ # the name like a finger's; a mouse has hover and doesn't.
+ test "a pen tap on a cut name slides it" do
+ narrow_sidebar
+ cut = visible_group_names.find { |name| name["cut"] }
+ assert cut, "expected a long group name to be cut at this width"
+
+ pointer_up(cut["name"], "pen")
+ page.document.synchronize { raise Capybara::ExpectationNotMet, "a pen tap did not slide the name" unless marquee(cut["name"])["running"] }
+ ensure
+ reset_emulation
+ end
+
+ # A touchscreen laptop's main pointer is fine, so the touch-screen layout
+ # above doesn't apply there; with reduced motion a tap on a cut name shows
+ # it in full instead of sliding it.
+ test "with reduced motion a tap on a cut name where the main pointer is fine shows it in full" do
+ skip "needs Chrome DevTools media emulation" unless page.driver.browser.respond_to?(:execute_cdp)
+ narrow_sidebar
+ page.driver.browser.execute_cdp("Emulation.setEmulatedMedia", features: [ { name: "prefers-reduced-motion", value: "reduce" } ])
+ assert_not page.evaluate_script(%(matchMedia("(pointer: coarse)").matches)), "the touch-screen layout must not apply here"
+ cut = visible_group_names.find { |name| name["cut"] }
+ assert cut, "expected a long group name to be cut at this width"
+
+ pointer_up(cut["name"], "mouse")
+ sleep 0.2
+ assert visible_group_names.find { |name| name["name"] == cut["name"] }["cut"], "a mouse click showed the name in full"
+
+ pointer_up(cut["name"], "touch")
+ page.document.synchronize do
+ shown = visible_group_names.find { |name| name["name"] == cut["name"] }
+ raise Capybara::ExpectationNotMet, "the tapped name is still cut: #{shown.inspect}" if shown["cut"]
+ end
+ shown = visible_group_names.find { |name| name["name"] == cut["name"] }
+ assert shown["totalBelow"], "the total should move below the full name: #{shown.inspect}"
+ assert_equal 1, shown["totalLines"], "the total wrapped"
+ assert_not marquee(cut["name"])["running"], "a name slid with reduced motion"
+ ensure
+ reset_emulation
+ end
+
+ private
+ # A pointerup of the given type on the group's summary, as a tap or a
+ # click ends there (the summary listens for it).
+ def pointer_up(name, type)
+ page.execute_script(<<~JS, name, type)
+ const span = Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary span.font-medium"))
+ .find((s) => s.offsetParent && s.textContent.trim() === arguments[0]);
+ span.closest("summary").dispatchEvent(new PointerEvent("pointerup", { pointerType: arguments[1], bubbles: true }));
+ JS
+ end
+
+ def narrow_sidebar(touch: false)
+ page.driver.browser.manage.window.resize_to(1400, 1000)
+ page.driver.browser.execute_cdp("Emulation.setTouchEmulationEnabled", enabled: true, maxTouchPoints: 1) if touch
+ visit root_path
+ page.execute_script(%(localStorage.setItem("sure.sidebarWidth.left", "240")))
+ visit root_path
+ assert_left_sidebar_width 240
+ assert page.evaluate_script(%(matchMedia("(pointer: coarse)").matches)), "the touch emulation did not make the pointer coarse" if touch
+ end
+
+ def reset_emulation
+ if page.driver.browser.respond_to?(:execute_cdp)
+ page.driver.browser.execute_cdp("Emulation.setTouchEmulationEnabled", enabled: false) rescue nil
+ page.driver.browser.execute_cdp("Emulation.setEmulatedMedia", features: []) rescue nil
+ end
+ page.execute_script(%(localStorage.removeItem("sure.sidebarWidth.left"))) rescue nil
+ end
+
+ def group_summary(name)
+ all("#sidebar-scroll [data-group-key] summary").find { |summary| summary.visible? && summary.find("span.font-medium").text.strip == name }
+ end
+
+ # A real tap (Chrome DevTools touch input) on the group's name.
+ def tap_group(name)
+ point = page.evaluate_script(<<~JS, name)
+ (() => {
+ const span = Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary span.font-medium"))
+ .find((s) => s.offsetParent && s.textContent.trim() === arguments[0]);
+ const r = span.getBoundingClientRect();
+ return [r.left + 10, r.top + r.height / 2];
+ })()
+ JS
+ page.driver.browser.execute_cdp("Input.dispatchTouchEvent", type: "touchStart", touchPoints: [ { x: point[0], y: point[1] } ])
+ page.driver.browser.execute_cdp("Input.dispatchTouchEvent", type: "touchEnd", touchPoints: [])
+ end
+
+ def marquee(name)
+ page.evaluate_script(<<~JS, name)
+ (() => {
+ const span = Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary span.font-medium"))
+ .find((s) => s.offsetParent && s.textContent.trim() === arguments[0]);
+ const text = span.querySelector("[data-sidebar-name-marquee-target='text']");
+ return { running: text.getAnimations().some((a) => a.playState === "running"),
+ shift: Math.round(new DOMMatrix(getComputedStyle(text).transform).m41), textOverflow: span.style.textOverflow,
+ display: getComputedStyle(text).display };
+ })()
+ JS
+ end
+
+ def visible_group_names
+ page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll("#sidebar-scroll [data-group-key] summary"))
+ .filter((summary) => summary.offsetParent)
+ .map((summary) => {
+ const span = summary.querySelector("span.font-medium");
+ const total = summary.querySelector("p.privacy-sensitive");
+ const name = span.getBoundingClientRect(), amount = total.getBoundingClientRect();
+ return { name: span.textContent.trim(), cut: span.scrollWidth > span.clientWidth,
+ totalBelow: amount.top >= name.bottom - 2,
+ totalLines: Math.round(amount.height / parseFloat(getComputedStyle(total).lineHeight)),
+ totalRight: Math.round(amount.right) };
+ })
+ JS
+ end
+
+ # The stored width is applied once the sidebar-resize controller connects,
+ # and the sidebar then animates to it, so wait until it has settled there.
+ def assert_left_sidebar_width(expected)
+ page.document.synchronize do
+ width = page.evaluate_script(%(Math.round(document.querySelector('[data-sidebar-resize-target="leftSidebar"]').getBoundingClientRect().width)))
+ raise Capybara::ExpectationNotMet, "the left sidebar is #{width}px wide, not #{expected}px" unless width == expected
+ end
+ end
+end