The personal finance app for everyone (by everyone)
Ruby
Let a finger scrub and select on a chart (#4942)
Yong Cong Sin3cd5c8c9fe89
diff --git a/app/javascript/controllers/time_series_chart_controller.js b/app/javascript/controllers/time_series_chart_controller.jsindex 917a9186dd..420e030fef 100644--- a/app/javascript/controllers/time_series_chart_controller.js+++ b/app/javascript/controllers/time_series_chart_controller.js@@ -28,6 +28,16 @@ export default class extends Controller {// point) that is enough to straddle two data points and navigate somewhere// the user never aimed at, so treat anything this small as a click._dragSelectMinPx = 4;+ // Touch (see _bindTouchHandlers): how long a finger rests before a slide+ // selects a range instead of moving the tooltip, how far it may drift while+ // resting, and the touch in progress.+ _longPressMs = 450;+ _touchSlopPx = 10;+ _touch = null;+ // performance.now() counts from the page load: 0 would make its first+ // second look like a touch had just happened and ignore the mouse.+ _lastTouchAt = Number.NEGATIVE_INFINITY;+ _touchTooltipShown = false;// y-axis domain tuning. Both are relative to the data, so the scale is// resolution-independent: a chart looks the same on a phone and a 4K// display — only pixel density changes.@@ -38,6 +48,7 @@ export default class extends Controller {connect() {this._install();document.addEventListener("turbo:load", this._reinstall);+ document.addEventListener("pointerdown", this._onDocumentPointerDown, true);this._settledResize = new SettledResize(this.element, this._reinstall);this._settledResize.start();}@@ -45,6 +56,11 @@ export default class extends Controller {disconnect() {this._teardown();document.removeEventListener("turbo:load", this._reinstall);+ document.removeEventListener(+ "pointerdown",+ this._onDocumentPointerDown,+ true,+ );this._settledResize?.stop();}@@ -60,6 +76,9 @@ export default class extends Controller {this._normalDataPoints = [];this._d3DragSelectBrush = null;this._d3DragSelectGroup = null;+ clearTimeout(this._touch?.timer);+ this._touch = null;+ this._touchTooltipShown = false;this._d3Container.selectAll("*").remove();}@@ -109,6 +128,17 @@ export default class extends Controller {this._drawDashedLineEmptyState();this._drawCenteredCircleEmptyState();++ // A hold on an interactive chart never picks up its card, also while it+ // has too few points to draw (see _bindTouchHandlers). Sparklines, which+ // have no tooltip and no selection, leave touches to their container.+ if (this.useTooltipValue || this.selectableValue) {+ this._d3Svg+ .node()+ .addEventListener("touchstart", this._keepTouchInChart, {+ passive: true,+ });+ }}_drawDashedLineEmptyState() {@@ -348,6 +378,7 @@ export default class extends Controller {.attr("pointer-events", "all");this._bindTooltipHandlers(rect);+ this._bindTouchHandlers(rect, { selectable: false });}_drawDragSelectOverlay() {@@ -363,6 +394,11 @@ export default class extends Controller {// charts. Drag-select is a mouse-only affordance for now, so opt out of// touch handling and leave scrolling/panning untouched on mobile..touchable(false)+ // A tap is followed by emulated mouse events; one of those must not+ // start a mouse drag after a touch gesture (handled below) ended.+ .filter(+ (event) => !event.ctrlKey && !event.button && !this._recentTouch(),+ ).on("start brush", (event) => this._handleDragSelectMove(event)).on("end", (event) => this._handleDragSelectEnd(event));@@ -383,6 +419,9 @@ export default class extends Controller {if (this.useTooltipValue) {this._bindTooltipHandlers(brushGroup.select(".overlay"));}+ this._bindTouchHandlers(brushGroup.select(".overlay"), {+ selectable: true,+ });this._d3DragSelectBrush = brush;this._d3DragSelectGroup = brushGroup;@@ -411,10 +450,16 @@ export default class extends Controller {const [x0, x1] = event.selection;- if (x1 - x0 < this._dragSelectMinPx) {+ if (!this._selectPixelRange(x0, x1)) {this._d3DragSelectGroup?.call(this._d3DragSelectBrush.move, null);- return;}+ }++ // Opens the dates between two pixels (x0 <= x1), from a mouse drag or a+ // touch selection. False when the range is too small to be one: the caller+ // clears its selection instead.+ _selectPixelRange(x0, x1) {+ if (x1 - x0 < this._dragSelectMinPx) return false;// Snap to the actual plotted data points (same as the tooltip shown// during the drag) rather than the raw continuous pixel-to-time value —@@ -428,12 +473,220 @@ export default class extends Controller {// and still collapse to a single date. That range renders one value, which// sends _draw() down the empty-state path — and the empty state has no// brush left to drag back out of.- if (startDatum === endDatum) {- this._d3DragSelectGroup?.call(this._d3DragSelectBrush.move, null);+ if (startDatum === endDatum) return false;++ this._navigateToDateRange(startDatum.date, endDatum.date);+ return true;+ }++ // Touch. A finger sliding along the chart moves the tooltip with it+ // (scrubbing), and on a selectable chart a finger that rests for a moment+ // and then slides selects a range, as a mouse drag does. The overlay claims+ // only horizontal movement (touch-action: pan-y pinch-zoom), so a vertical+ // swipe still scrolls the page and a pinch still zooms: the browser takes+ // that gesture over and cancels the pointer. Without this a tap only showed+ // the tooltip where it landed.+ _bindTouchHandlers(selection, { selectable }) {+ const node = selection.node();+ // On the <svg>: browsers ignore touch-action on the shapes inside one.+ // Pinch zoom stays the browser's, as everywhere else on the page.+ const svg = this._d3Svg.node();+ svg.style.touchAction = "pan-y pinch-zoom";+ svg.style.webkitUserSelect = "none";+ svg.style.userSelect = "none";+ svg.style.webkitTouchCallout = "none";++ selection+ .on("pointerdown.touch", (event) => this._touchStart(event, selectable))+ .on("pointermove.touch", (event) => this._touchMove(event))+ .on("pointerup.touch", (event) => this._touchEnd(event))+ .on("pointercancel.touch", (event) => this._touchCancel(event))+ // A long press otherwise opens the browser's context menu.+ .on("contextmenu.touch", (event) => {+ if (this._touch || this._recentTouch()) event.preventDefault();+ });+ // Once a selection has started, the finger may drift up or down while it+ // slides; only a cancelable touchmove can keep that from scrolling.+ node.addEventListener("touchmove", this._preventScrollWhileSelecting, {+ passive: false,+ });+ // A card holding the chart may be reordered by holding it (the dashboard,+ // after 800 ms): on the chart a hold selects a range instead, as a mouse+ // drag on it does (the chart is draggable="false" there).+ // On the whole <svg>, so its margins and axis labels count too.+ svg.addEventListener("touchstart", this._keepTouchInChart, {+ passive: true,+ });+ }++ _touchStart(event, selectable) {+ // Only a gesture's first finger: a second one is a pinch, which+ // _onDocumentPointerDown handles wherever it lands. A new first finger+ // means any earlier touch has ended, even one whose end this chart missed+ // (redrawn while the finger was down), so it starts afresh.+ if (event.pointerType !== "touch" || !event.isPrimary) return;+ if (this._touch) this._abortTouch();++ this._lastTouchAt = performance.now();+ const x = this._touchX(event);+ this._touch = {+ id: event.pointerId,+ startClientX: event.clientX,+ startClientY: event.clientY,+ x,+ anchorX: x,+ selecting: false,+ timer: selectable+ ? setTimeout(() => this._startTouchSelection(), this._longPressMs)+ : null,+ };+ this._scrubTo(event);+ }++ _touchMove(event) {+ const touch = this._touch;+ if (!touch || event.pointerId !== touch.id) return;++ this._lastTouchAt = performance.now();+ if (+ touch.timer &&+ Math.hypot(+ event.clientX - touch.startClientX,+ event.clientY - touch.startClientY,+ ) > this._touchSlopPx+ ) {+ clearTimeout(touch.timer);+ touch.timer = null;+ }++ touch.x = this._touchX(event);+ if (touch.selecting) this._drawTouchSelection(touch.anchorX, touch.x);+ this._scrubTo(event);+ }++ // A tap or a slide leaves the tooltip on the last point (touching anywhere+ // else hides it); a selection opens its range.+ _touchEnd(event) {+ const touch = this._touch;+ if (!touch || event.pointerId !== touch.id) return;++ this._lastTouchAt = performance.now();+ clearTimeout(touch.timer);+ this._touch = null;++ if (touch.selecting) {+ this._removeTouchSelection();+ // A long press lifted without sliding, or with no more than a finger's+ // drift (on a dense period a few pixels reach the next day), selects+ // nothing and keeps the tooltip, as a tap does.+ const slid = Math.abs(touch.x - touch.anchorX) >= this._touchSlopPx;+ const opened =+ slid &&+ this._selectPixelRange(+ Math.min(touch.anchorX, touch.x),+ Math.max(touch.anchorX, touch.x),+ );+ if (opened) this._hideTooltip();+ }+ }++ // The browser took the gesture over: a vertical swipe scrolls the page, so+ // the tooltip goes. A selection the browser ends (some end a long press+ // this way rather than with pointerup) opens nothing and keeps the tooltip.+ _touchCancel(event) {+ const touch = this._touch;+ if (!touch || event.pointerId !== touch.id) return;++ clearTimeout(touch.timer);+ this._touch = null;+ this._removeTouchSelection();+ if (!touch.selecting) this._hideTooltip();+ }++ _abortTouch() {+ clearTimeout(this._touch?.timer);+ this._touch = null;+ this._removeTouchSelection();+ this._hideTooltip();+ }++ _startTouchSelection() {+ const touch = this._touch;+ if (!touch) return;++ touch.timer = null;+ touch.selecting = true;+ touch.anchorX = touch.x;+ navigator.vibrate?.(10);+ this._drawTouchSelection(touch.anchorX, touch.x);+ }++ _keepTouchInChart = (event) => {+ event.stopPropagation();+ };++ // One finger only: a second one makes it a pinch, which stays the browser's.+ _preventScrollWhileSelecting = (event) => {+ if (+ this._touch?.selecting &&+ event.cancelable &&+ event.touches.length === 1+ )+ event.preventDefault();+ };++ // On the document (capture), so a touch counts wherever it lands. A second+ // finger starts a pinch: the long press or the selection is dropped rather+ // than let lifting the first finger open a range, also when it lands on the+ // chart's margin or off the chart. A touch elsewhere hides the tooltip.+ _onDocumentPointerDown = (event) => {+ if (event.pointerType !== "touch") return;+ if (!event.isPrimary) {+ if (this._touch) this._abortTouch();return;}+ if (this._touchTooltipShown && !this.element.contains(event.target)) {+ this._hideTooltip();+ }+ };- this._navigateToDateRange(startDatum.date, endDatum.date);+ // Emulated mouse events follow a tap; they must not act as a mouse would.+ _recentTouch() {+ return performance.now() - this._lastTouchAt < 1000;+ }++ _touchX(event) {+ const [xPos] = d3.pointer(event, this._d3Group.node());+ return Math.max(0, Math.min(xPos, this._d3ContainerWidth));+ }++ _scrubTo(event) {+ const datum = this._nearestDataPointForPixel(this._touchX(event));+ this._renderTooltipAt(datum, event.pageX, event.pageY, { touch: true });+ this._touchTooltipShown = true;+ }++ _drawTouchSelection(x0, x1) {+ let rect = this._d3Group.select(".touch-selection");+ if (rect.empty()) {+ rect = this._d3Group+ .append("rect")+ .attr("class", "touch-selection")+ .attr("y", 0)+ .attr("height", this._d3ContainerHeight)+ .attr("fill", this._trendColor)+ .attr("fill-opacity", 0.12)+ .attr("stroke", this._trendColor)+ .attr("stroke-opacity", 0.5)+ .attr("pointer-events", "none");+ }+ rect+ .attr("x", Math.min(x0, x1))+ .attr("width", Math.max(1, Math.abs(x1 - x0)));+ }++ _removeTouchSelection() {+ this._d3Group.selectAll(".touch-selection").remove();}_navigateToDateRange(startDate, endDate) {@@ -468,12 +721,14 @@ export default class extends Controller {_bindTooltipHandlers(selection) {selection.on("mousemove", (event) => {+ if (this._recentTouch()) return;const [xPos] = d3.pointer(event);const datum = this._nearestDataPointForPixel(xPos);this._renderTooltipAt(datum, event.pageX, event.pageY);}).on("mouseout", (event) => {+ if (this._recentTouch()) return;const hoveringOnGuideline =event.toElement?.classList.contains("guideline");@@ -483,7 +738,7 @@ export default class extends Controller {});}- _renderTooltipAt(datum, pageX, pageY) {+ _renderTooltipAt(datum, pageX, pageY, { touch = false } = {}) {const estimatedTooltipWidth = 250;const pageWidth = document.body.clientWidth;const tooltipX = pageX + 10;@@ -507,7 +762,10 @@ export default class extends Controller {.attr("x2", this._d3XScale(datum.date)).attr("y2", this._d3ContainerHeight).attr("stroke", "currentColor")- .attr("stroke-dasharray", "4, 4");+ .attr("stroke-dasharray", "4, 4")+ // A touch on the line (the tooltip stays after a tap) must reach the+ // overlay underneath, as with the point circles.+ .attr("pointer-events", "none");// Big circlethis._d3Group@@ -539,9 +797,38 @@ export default class extends Controller {.style("z-index", 999).style("left", `${adjustedX}px`).style("top", `${pageY - 10}px`);++ if (touch) this._placeTooltipAboveFinger(pageX, pageY);+ }++ // Beside the pointer, a finger would cover the tooltip: above it instead,+ // centred and kept on the page, or below when there is no room above. One+ // too tall for either side (a breakdown with many rows on a small screen)+ // is kept on the screen, over the finger if it must.+ _placeTooltipAboveFinger(pageX, pageY) {+ const node = this._d3Tooltip?.node();+ if (!node) return;++ const gap = 28;+ const width = node.offsetWidth;+ const height = node.offsetHeight;+ const minX = window.scrollX + 8;+ const maxX = window.scrollX + document.body.clientWidth - width - 8;+ const left = Math.max(minX, Math.min(pageX - width / 2, maxX));+ const minY = window.scrollY + 8;+ const maxY = window.scrollY + window.innerHeight - height - 8;+ const above = pageY - height - gap;+ const below = pageY + gap;+ let top;+ if (above >= minY) top = above;+ else if (below <= maxY) top = below;+ else top = Math.max(minY, maxY);++ this._d3Tooltip.style("left", `${left}px`).style("top", `${top}px`);}_hideTooltip() {+ this._touchTooltipShown = false;this._d3Group.selectAll(".guideline").remove();this._d3Group.selectAll(".data-point-circle").remove();this._d3Tooltip?.style("opacity", 0);diff --git a/test/system/chart_touch_test.rb b/test/system/chart_touch_test.rbnew file mode 100644index 0000000000..640426599c--- /dev/null+++ b/test/system/chart_touch_test.rb@@ -0,0 +1,409 @@+require "application_system_test_case"++# On a touchscreen a chart has no hover and no mouse drag: a finger sliding+# along it moves the tooltip (scrubbing), and a long press followed by a slide+# selects a date range. Vertical swipes must still scroll the page. The+# gestures are real touch input (Chrome DevTools Input.dispatchTouchEvent), so+# the browser applies touch-action and fires pointer and emulated mouse events+# as it does on a phone.+class ChartTouchTest < ApplicationSystemTestCase+ CHART = "#netWorthChart".freeze++ setup do+ # Each test gets a browser of its own. Touch input comes through Chrome+ # DevTools, and an earlier test in the same browser (its WebDriver mouse+ # actions, a touch left unfinished) can keep any touch from reaching the+ # page.+ restart_browser+ # Real touch input comes through Chrome DevTools, which other drivers lack.+ skip "needs Chrome DevTools touch input" unless page.driver.browser.respond_to?(:execute_cdp)+ sign_in users(:family_admin)+ assert_selector "#{CHART} .drag-select-brush .overlay", visible: :all+ # Touch input lands on whatever is at the point, so the chart must be on screen.+ page.execute_script(%(document.querySelector("#{CHART}").scrollIntoView({ block: "center" })))+ end++ # And none is left to the test after it (after the failure screenshot).+ def after_teardown+ super+ ensure+ Capybara.current_session.driver.quit+ end++ test "a finger sliding along the chart moves the tooltip with it, and it stays until a touch elsewhere" do+ from = chart_point(0.2)+ nudged = [ from[0] + 30, from[1] ]+ to = chart_point(0.8)++ # Moving off the first point straight away: a finger resting longer+ # than the long press starts a selection instead (the next test).+ touch("touchStart", from)+ touch("touchMove", nudged)+ first_date = tooltip_date+ assert tooltip_visible?, "a touch shows the tooltip"++ slide(nudged, to)+ # The browser may deliver the last move with the next frame.+ page.document.synchronize(5) do+ off_by = (to[0] - chart_box["left"] - guideline_x).abs+ raise Capybara::ExpectationNotMet, "the guideline is #{off_by.round}px from the finger" if off_by > point_spacing+ end+ assert_not_equal first_date, tooltip_date, "the tooltip did not follow the finger"++ touch("touchEnd")+ assert tooltip_visible?, "lifting the finger keeps the tooltip on the last point"+ assert_equal "/", URI.parse(page.current_url).path++ header = page.evaluate_script(%(document.querySelector("#{CHART}").getBoundingClientRect().top)) - 40+ touch("touchStart", [ 20, header ])+ touch("touchEnd")+ assert_not tooltip_visible?, "a touch elsewhere hides the tooltip"+ end++ test "a tooltip too tall for either side of the finger is kept on the screen" do+ page.execute_script(%(document.querySelector("#{CHART} > .chart-tooltip").style.minHeight = `${Math.round(window.innerHeight * 0.75)}px`))+ from = chart_point(0.5)++ touch("touchStart", from)+ touch("touchMove", [ from[0] + 30, from[1] ])+ assert tooltip_visible?, "a touch shows the tooltip"++ box = page.evaluate_script(<<~JS)+ (() => {+ const r = document.querySelector("#{CHART} > .chart-tooltip").getBoundingClientRect()+ return { top: r.top, bottom: r.bottom, height: r.height, screen: window.innerHeight }+ })()+ JS+ assert box["height"] + 28 > from[1] - 8 && from[1] + 28 + box["height"] > box["screen"] - 8,+ "the tooltip fits on one side of the finger, so this tests nothing: #{box.inspect}"+ assert_operator box["bottom"], :<=, box["screen"], "the tooltip runs off the bottom of the screen: #{box.inspect}"+ assert_operator box["top"], :>=, 0, "the tooltip runs off the top of the screen: #{box.inspect}"+ touch("touchEnd")+ end++ test "a long press then a slide selects a date range" do+ from = chart_point(0.3)+ to = chart_point(0.7)++ touch("touchStart", from)+ sleep 0.7+ assert_selector "#{CHART} .touch-selection", visible: :all+ slide(from, to)+ selection_width = page.evaluate_script(%(Number(document.querySelector("#{CHART} .touch-selection").getAttribute("width"))))+ assert_in_delta to[0] - from[0], selection_width, 2+ touch("touchEnd")++ assert_current_path(%r{/\?.*start_date=.*end_date=})+ params = Rack::Utils.parse_query(URI.parse(page.current_url).query)+ assert_operator Date.parse(params["start_date"]), :<, Date.parse(params["end_date"])+ end++ test "a long press lifted without sliding selects nothing and keeps the tooltip" do+ point = chart_point(0.4)++ touch("touchStart", point)+ sleep 0.7+ touch("touchEnd")++ assert tooltip_visible?, "the tooltip went away"+ assert_no_selector "#{CHART} .touch-selection", visible: :all+ assert_nil URI.parse(page.current_url).query+ end++ # Dashboard cards are reordered by holding them (800 ms); a hold on the+ # chart selects a range and must not lift its card.+ test "holding a finger on the chart does not pick up its dashboard card" do+ point = chart_point(0.4)++ touch("touchStart", point)+ sleep 1.2+ assert_selector "#{CHART} .touch-selection", visible: :all+ grabbed = page.evaluate_script(%(document.querySelector("#{CHART}").closest("[data-sortable-list-target='item']").getAttribute("aria-grabbed")))+ touch("touchEnd")++ assert_equal "false", grabbed, "the hold picked up the dashboard card"+ end++ test "holding a finger on the chart's margin does not pick up its dashboard card" do+ # Above the plotting area, in the <svg>'s own top margin.+ svg = page.evaluate_script(%((() => { const r = document.querySelector("#{CHART} svg").getBoundingClientRect(); return [r.left + r.width / 2, r.top + 4] })()))+ assert_equal "svg", page.evaluate_script(%(document.elementFromPoint(#{svg[0]}, #{svg[1]}).tagName)), "the point is not on the chart's margin"++ touch("touchStart", svg)+ sleep 1.2+ grabbed = page.evaluate_script(%(document.querySelector("#{CHART}").closest("[data-sortable-list-target='item']").getAttribute("aria-grabbed")))+ touch("touchEnd")++ assert_equal "false", grabbed, "a hold on the chart's margin picked up the dashboard card"+ end++ # On the first day of a period the chart has a single point and draws its+ # empty state; a hold on it still leaves the card where it is.+ test "holding a finger on a chart with a single point does not pick up its dashboard card" do+ travel_to Date.current.beginning_of_month+ visit root_path(period: "current_month")+ assert_no_selector "#{CHART} .drag-select-brush", visible: :all+ assert_selector "#{CHART} svg circle", visible: :all+ page.execute_script(%(document.querySelector("#{CHART}").scrollIntoView({ block: "center" })))+ svg = page.evaluate_script(%((() => { const r = document.querySelector("#{CHART} svg").getBoundingClientRect(); return [r.left + r.width / 3, r.top + r.height / 2] })()))++ touch("touchStart", svg)+ sleep 1.2+ grabbed = page.evaluate_script(%(document.querySelector("#{CHART}").closest("[data-sortable-list-target='item']").getAttribute("aria-grabbed")))+ touch("touchEnd")++ assert_equal "false", grabbed, "a hold on a single-point chart picked up the dashboard card"+ end++ # During a selection a one-finger drift up or down must not scroll the page,+ # but a second finger makes it a pinch, which zooms as anywhere else.+ # A browser may end the gesture itself (pointercancel) after the long press;+ # the selection goes, the tooltip stays, nothing opens, and a new touch works.+ test "a long press the browser cancels leaves the tooltip and lets the next touch start" do+ point = chart_point(0.4)++ touch("touchStart", point)+ # Waits for the selection, then cancels at once (an idle finger held+ # much longer may be cancelled by the browser itself).+ assert_selector "#{CHART} .touch-selection", visible: :all+ touch("touchMove", [ point[0] + 40, point[1] ])+ page.driver.browser.execute_cdp("Input.dispatchTouchEvent", type: "touchCancel", touchPoints: [])++ assert_no_selector "#{CHART} .touch-selection", visible: :all+ assert tooltip_visible?, "the tooltip went away"+ assert_nil URI.parse(page.current_url).query++ from = chart_point(0.2)+ touch("touchStart", from)+ touch("touchMove", [ from[0] + 30, from[1] ])+ first_date = tooltip_date+ slide([ from[0] + 30, from[1] ], chart_point(0.7))+ touch("touchEnd")+ assert_not_equal first_date, tooltip_date, "a touch after the cancelled one did not scrub"+ end++ # On a dense period (365 days over a few hundred pixels) a finger's drift+ # while lifting reaches another day; it must not open a range.+ test "a finger drifting a few pixels after a long press opens nothing" do+ visit root_path(period: "last_365_days")+ assert_selector "#{CHART} .drag-select-brush .overlay", visible: :all+ page.execute_script(%(document.querySelector("#{CHART}").scrollIntoView({ block: "center" })))+ assert_operator point_spacing, :<, 7, "the period is not dense enough for a 7px drift to reach another day"+ point = chart_point(0.4)++ touch("touchStart", point)+ assert_selector "#{CHART} .touch-selection", visible: :all+ touch("touchMove", [ point[0] + 7, point[1] ])+ touch("touchEnd")++ assert tooltip_visible?, "the tooltip went away"+ assert_no_match(/start_date/, page.current_url, "a drift after the long press opened a range")+ end++ # A second finger starts a pinch: lifting the first must not open a range,+ # whether the long press had already started a selection or not.+ test "a second finger cancels a long press and a selection" do+ point = chart_point(0.3)+ two = ->(a) { page.driver.browser.execute_cdp("Input.dispatchTouchEvent", type: "touchStart", touchPoints: [ { x: a[0], y: a[1] }, { x: a[0] + 120, y: a[1] + 10 } ]) }++ touch("touchStart", point)+ two.call(point)+ sleep 0.7+ assert_no_selector "#{CHART} .touch-selection", visible: :all+ touch("touchEnd")+ assert_nil URI.parse(page.current_url).query++ touch("touchStart", point)+ assert_selector "#{CHART} .touch-selection", visible: :all+ slide(point, chart_point(0.6))+ two.call(chart_point(0.6))+ assert_no_selector "#{CHART} .touch-selection", visible: :all+ touch("touchEnd")+ assert_nil URI.parse(page.current_url).query, "lifting after a second finger opened a range"+ end++ # A second finger has its own target: on the chart's margin it never reaches+ # the plotting overlay, and must still cancel the selection.+ test "a second finger on the chart's margin cancels a selection" do+ point = chart_point(0.3)+ margin = page.evaluate_script(%((() => { const r = document.querySelector("#{CHART} svg").getBoundingClientRect(); return [r.left + r.width / 2, r.top + 4] })()))+ assert_equal "svg", page.evaluate_script(%(document.elementFromPoint(#{margin[0]}, #{margin[1]}).tagName)), "the point is not on the chart's margin"++ touch("touchStart", point)+ assert_selector "#{CHART} .touch-selection", visible: :all+ slide(point, chart_point(0.6))+ # Real two-finger input makes Chrome cancel the first pointer itself; a+ # browser that waits for the fingers to move does not. The second+ # finger's pointerdown alone, on the margin, has to end the selection.+ page.execute_script(<<~JS, margin[0], margin[1])+ const [x, y] = arguments;+ document.elementFromPoint(x, y).dispatchEvent(new PointerEvent("pointerdown",+ { bubbles: true, cancelable: true, pointerType: "touch", pointerId: 99, isPrimary: false, clientX: x, clientY: y }));+ JS+ touch("touchEnd")++ assert_no_selector "#{CHART} .touch-selection", visible: :all+ sleep 1 # a range opens through Turbo.visit, after the lift+ assert_nil URI.parse(page.current_url).query, "lifting after a second finger on the margin opened a range"+ end++ # The tooltip stays after a tap, with its guideline; a touch landing on that+ # line must still reach the chart.+ test "a touch on the tooltip's guideline still scrubs" do+ point = chart_point(0.5)+ touch("touchStart", point)+ touch("touchEnd")+ assert tooltip_visible?+ first_date = tooltip_date+ # On the first painted dash of the dashed line.+ line = page.evaluate_script(%((() => { const r = document.querySelector("#{CHART} .guideline").getBoundingClientRect(); return [r.left + r.width / 2, r.top + 2] })()))++ touch("touchStart", line)+ slide(line, [ line[0] + 120, line[1] ], steps: 6)+ touch("touchEnd")++ assert_not_equal first_date, tooltip_date, "a touch on the guideline did not scrub"+ end++ test "a selection keeps one finger from scrolling but leaves a pinch to the browser" do+ page.execute_script(<<~JS)+ window.__moves = []+ document.addEventListener("touchmove", (event) => window.__moves.push([event.touches.length, event.defaultPrevented]))+ JS+ point = chart_point(0.4)++ touch("touchStart", point)+ sleep 0.7+ touch("touchMove", [ point[0] + 15, point[1] + 5 ])+ # A second finger lands (touchStart with both), then both move.+ page.driver.browser.execute_cdp("Input.dispatchTouchEvent", type: "touchStart",+ touchPoints: [ { x: point[0] + 15, y: point[1] + 5 }, { x: point[0] + 60, y: point[1] + 30 } ])+ page.driver.browser.execute_cdp("Input.dispatchTouchEvent", type: "touchMove",+ touchPoints: [ { x: point[0] + 10, y: point[1] }, { x: point[0] + 80, y: point[1] + 50 } ])+ touch("touchEnd")++ moves = page.evaluate_script("window.__moves")+ assert_includes moves, [ 1, true ], "a one-finger move during a selection was not kept from scrolling: #{moves.inspect}"+ assert_includes moves, [ 2, false ], "a two-finger move during a selection was cancelled: #{moves.inspect}"+ end++ test "a slide without the long press only moves the tooltip and selects nothing" do+ from = chart_point(0.3)+ middle = chart_point(0.5)+ to = chart_point(0.7)++ # Resting past the long press in the middle of a slide: a finger that+ # already moved is scrubbing, so going on must not select.+ touch("touchStart", from)+ slide(from, middle)+ sleep 0.7+ assert_no_selector "#{CHART} .touch-selection", visible: :all+ slide(middle, to)+ touch("touchEnd")++ assert_no_selector "#{CHART} .touch-selection", visible: :all+ assert_equal "/", URI.parse(page.current_url).path+ assert_nil URI.parse(page.current_url).query+ end++ test "a vertical swipe on the chart scrolls the page and hides the tooltip" do+ page.driver.browser.manage.window.resize_to(1400, 700)+ page.execute_script(%(document.querySelector("#{CHART}").scrollIntoView({ block: "center" })))+ before = scroll_offsets+ start = chart_point(0.5)++ touch("touchStart", start)+ slide(start, [ start[0], start[1] - 250 ], steps: 12)+ touch("touchEnd")++ assert_equal "pan-y pinch-zoom", page.evaluate_script(%(getComputedStyle(document.querySelector("#{CHART} svg")).touchAction)),+ "the chart takes horizontal slides and leaves vertical scrolling and pinch zoom to the browser"+ assert_not_equal before, scroll_offsets, "the page did not scroll"+ assert_not tooltip_visible?, "the tooltip stayed after the page scrolled"+ assert_no_selector "#{CHART} .touch-selection", visible: :all+ assert_equal "/", URI.parse(page.current_url).path+ end++ # Emulated mouse events are ignored for a moment after a touch, timed with+ # performance.now(), which counts from the page load. Held at 500 ms, the+ # page stays in its first second: with no touch yet, the mouse must work.+ test "the mouse works before any touch, even in the page's first second" do+ clock = page.driver.browser.execute_cdp("Page.addScriptToEvaluateOnNewDocument", source: "performance.now = () => 500")+ visit root_path+ assert_selector "#{CHART} .drag-select-brush .overlay", visible: :all+ page.execute_script(%(document.querySelector("#{CHART}").scrollIntoView({ block: "center" })))++ # A mouse move dispatched in the page rather than a WebDriver action,+ # which would leave input state behind for the touch tests.+ page.execute_script(<<~JS)+ const overlay = document.querySelector("#{CHART} .drag-select-brush .overlay");+ const r = overlay.getBoundingClientRect();+ overlay.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 }));+ JS++ assert tooltip_visible?, "hovering showed no tooltip"+ ensure+ # Registered for every later page in this browser, not only this visit.+ page.driver.browser.execute_cdp("Page.removeScriptToEvaluateOnNewDocument", identifier: clock["identifier"]) if clock+ end++ private+ # Quits the session's browser; the next use of `page` starts a new one.+ def restart_browser+ Capybara.current_session.driver.quit+ reset_viewport+ end++ def touch(type, point = nil)+ points = point ? [ { x: point[0], y: point[1] } ] : []+ page.driver.browser.execute_cdp("Input.dispatchTouchEvent", type: type, touchPoints: points)+ end++ def slide(from, to, steps: 10)+ (1..steps).each do |step|+ x = from[0] + (to[0] - from[0]) * step / steps.to_f+ y = from[1] + (to[1] - from[1]) * step / steps.to_f+ touch("touchMove", [ x, y ])+ end+ end++ def chart_box+ page.evaluate_script(<<~JS)+ (() => {+ const r = document.querySelector("#{CHART} .drag-select-brush .overlay").getBoundingClientRect()+ return { left: r.left, top: r.top, width: r.width, height: r.height }+ })()+ JS+ end++ # A point at a fraction of the chart's width, halfway down, in viewport pixels.+ def chart_point(fraction)+ box = chart_box+ [ box["left"] + box["width"] * fraction, box["top"] + box["height"] / 2 ]+ end++ def point_spacing+ count = page.evaluate_script(%(JSON.parse(document.querySelector("#{CHART}").dataset.timeSeriesChartDataValue).values.length))+ chart_box["width"] / [ count - 1, 1 ].max+ end++ def guideline_x+ page.evaluate_script(%(Number(document.querySelector("#{CHART} .guideline").getAttribute("x1"))))+ end++ def tooltip_date+ page.evaluate_script(%(document.querySelector("#{CHART} > .chart-tooltip .text-secondary")?.textContent.trim()))+ end++ def tooltip_visible?+ # Shown and hidden through its inline opacity (the class starts it hidden).+ page.evaluate_script(%(document.querySelector("#{CHART} > .chart-tooltip").style.opacity)) == "1"+ end++ # Every scrollable box's offset, since the page scrolls inside the layout.+ def scroll_offsets+ page.evaluate_script(<<~JS)+ [document.scrollingElement.scrollTop, ...Array.from(document.querySelectorAll("*")).filter((el) => el.scrollHeight > el.clientHeight && /auto|scroll/.test(getComputedStyle(el).overflowY)).map((el) => el.scrollTop)]+ JS+ end+end