Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

feat(sdk,embed-js): Improve mobile range selection experience for visualizations (#71374)

Timofey Kachalova3340c17a6bf
diff --git a/e2e/support/helpers/e2e-mobile-device-helpers.ts b/e2e/support/helpers/e2e-mobile-device-helpers.ts
index 2eceb8e42b3..43c22900960 100644
--- a/e2e/support/helpers/e2e-mobile-device-helpers.ts
+++ b/e2e/support/helpers/e2e-mobile-device-helpers.ts
@@ -78,3 +78,47 @@ export function quickSwipe(
button: 0,
});
}
+
+export function longPressAndDrag(
+ selector: string,
+ startX: number,
+ startY: number,
+ endX: number,
+ holdMs = LONG_PRESS_MS,
+) {
+ cy.findByTestId(selector).trigger("pointerdown", startX, startY, {
+ force: true,
+ isPrimary: true,
+ button: 0,
+ });
+
+ cy.wait(holdMs);
+
+ cy.findByTestId(selector)
+ .trigger("mousemove", endX, startY)
+ .trigger("mouseup", endX, startY);
+}
+
+export function quickSwipe(
+ selector: string,
+ startX: number,
+ startY: number,
+ endX: number,
+) {
+ cy.findByTestId(selector)
+ .trigger("pointerdown", startX, startY, {
+ force: true,
+ isPrimary: true,
+ button: 0,
+ })
+ .trigger("pointermove", endX, startY, {
+ force: true,
+ isPrimary: true,
+ button: 0,
+ })
+ .trigger("pointerup", endX, startY, {
+ force: true,
+ isPrimary: true,
+ button: 0,
+ });
+}
diff --git a/e2e/test-component/scenarios/embedding-sdk/touch-brush.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/touch-brush.cy.spec.tsx
new file mode 100644
index 00000000000..ca191cfd12a
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/touch-brush.cy.spec.tsx
@@ -0,0 +1,130 @@
+const { H } = cy;
+
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { createQuestion } from "e2e/support/helpers";
+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
+import {
+ disableTouchEmulation,
+ enableTouchEmulation,
+ longPressAndDrag,
+ quickSwipe,
+} from "e2e/support/helpers/e2e-mobile-device-helpers";
+import { echartsContainer } from "e2e/support/helpers/e2e-visual-tests-helpers";
+import { mountInteractiveQuestion } from "e2e/support/helpers/embedding-sdk-component-testing";
+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+
+const { ORDERS_ID, ORDERS } = SAMPLE_DATABASE;
+
+function waitForChart() {
+ getSdkRoot().within(() => {
+ echartsContainer().should("be.visible");
+ // Wait for ECharts to finish rendering data points.
+ echartsContainer().find("path").should("have.length.greaterThan", 0);
+ });
+}
+
+describe("scenarios > embedding-sdk > touch-brush", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ createQuestion({
+ name: "Line chart for brush test",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", ORDERS.PRODUCT_ID, null]],
+ },
+ display: "line",
+ }).then(({ body: question }) => {
+ cy.wrap(question.id).as("questionId");
+ });
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ describe("touch device", () => {
+ beforeEach(() => {
+ cy.viewport("iphone-x");
+ enableTouchEmulation();
+ });
+
+ afterEach(() => {
+ disableTouchEmulation();
+ });
+
+ it("should activate brush on long press + horizontal drag", () => {
+ mountInteractiveQuestion();
+ waitForChart();
+
+ longPressAndDrag("chart-container", 100, 150, 250);
+
+ getSdkRoot().within(() => {
+ // We check a title of a new question that appears after a range selection
+ cy.findByText("Count by Product ID").should("be.visible");
+ });
+ });
+
+ it("should NOT trigger brush on quick horizontal swipe", () => {
+ mountInteractiveQuestion();
+ waitForChart();
+
+ quickSwipe("chart-container", 100, 150, 250);
+
+ cy.wait(1000);
+ getSdkRoot().within(() => {
+ cy.findByText("Count by Product ID").should("not.exist");
+ });
+ });
+ });
+
+ describe("desktop (non-touch)", () => {
+ it("should trigger brush on regular mouse drag", () => {
+ mountInteractiveQuestion();
+ waitForChart();
+
+ cy.findByTestId("query-visualization-root")
+ .trigger("mousedown", 150, 150)
+ .trigger("mousemove", 300, 150)
+ .trigger("mouseup", 300, 150);
+
+ getSdkRoot().within(() => {
+ cy.findByText("Count by Product ID").should("be.visible");
+ });
+ });
+ });
+
+ describe("tap on data point", () => {
+ describe("touch device", () => {
+ beforeEach(() => {
+ cy.viewport("iphone-x");
+ enableTouchEmulation();
+ });
+
+ afterEach(() => {
+ disableTouchEmulation();
+ });
+
+ it("should open drill popover on regular tap (not long press)", () => {
+ mountInteractiveQuestion();
+ waitForChart();
+
+ H.cartesianChartCircle().first().click({ force: true });
+
+ H.popover().should("be.visible");
+ });
+ });
+
+ describe("desktop (non-touch)", () => {
+ it("should open drill popover on click", () => {
+ mountInteractiveQuestion();
+ waitForChart();
+
+ H.cartesianChartCircle().first().click({ force: true });
+
+ H.popover().should("be.visible");
+ });
+ });
+ });
+});
diff --git a/frontend/src/metabase/lib/browser.ts b/frontend/src/metabase/lib/browser.ts
index 2872728e88d..83cf58b5813 100644
--- a/frontend/src/metabase/lib/browser.ts
+++ b/frontend/src/metabase/lib/browser.ts
@@ -48,5 +48,22 @@ export function isMac() {
return Boolean(platform.match(/^Mac/));
}
+export const isTouchDevice = () => {
+ if (typeof window === "undefined") {
+ return false;
+ }
+
+ if (typeof window.matchMedia === "function") {
+ const hasCoarsePointer = window.matchMedia("(pointer: coarse)").matches;
+ const cannotHover = window.matchMedia("(hover: none)").matches;
+
+ if (hasCoarsePointer && cannotHover) {
+ return true;
+ }
+ }
+
+ return typeof navigator !== "undefined" && navigator.maxTouchPoints > 0;
+};
+
export const METAKEY = isMac() ? "⌘" : "Ctrl";
export const ALTKEY = isMac() ? "⌥" : "Alt";
diff --git a/frontend/src/metabase/visualizations/components/EChartsRenderer/EChartsRenderer.styled.tsx b/frontend/src/metabase/visualizations/components/EChartsRenderer/EChartsRenderer.styled.tsx
index 754d25e58f0..694e117a9b0 100644
--- a/frontend/src/metabase/visualizations/components/EChartsRenderer/EChartsRenderer.styled.tsx
+++ b/frontend/src/metabase/visualizations/components/EChartsRenderer/EChartsRenderer.styled.tsx
@@ -6,7 +6,19 @@ export const EChartsRendererRoot = styled.div`
align-items: center;
justify-content: center;
/* HACK: zrender adds user-select: none to the root svg element which prevents users from selecting text on charts */
- & svg {
- user-select: auto !important;
+ @media (hover: hover) {
+ & svg {
+ user-select: auto !important;
+ }
+ }
+
+ /* zrender sets touch-action: none on the SVG which blocks all native
+ scrolling on touch devices. We override with auto so the browser handles
+ scroll in all directions. Brush selection is gated behind a long-press
+ that calls preventDefault on touchmove to reclaim the gesture (see useBrush). */
+ @media (hover: none) {
+ & svg {
+ touch-action: auto !important;
+ }
}
`;
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.ts
new file mode 100644
index 00000000000..41b3bfe8cf6
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.ts
@@ -0,0 +1,276 @@
+import type { EChartsType } from "echarts/core";
+import {
+ type MutableRefObject,
+ type RefObject,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+
+import { isTouchDevice } from "metabase/lib/browser";
+
+const LONG_PRESS_DURATION_MS = 500;
+const TOUCH_MOVE_THRESHOLD_PX = 10;
+
+type Point = { x: number; y: number };
+
+export const hasMovedBeyondThreshold = (
+ start: Point,
+ current: Point,
+ threshold = TOUCH_MOVE_THRESHOLD_PX,
+) => {
+ const dx = current.x - start.x;
+ const dy = current.y - start.y;
+
+ return dx * dx + dy * dy > threshold * threshold;
+};
+
+export const createZrenderMousedownEvent = (
+ point: Point,
+ containerRect: DOMRect,
+) => ({
+ offsetX: point.x - containerRect.left,
+ offsetY: point.y - containerRect.top,
+ target: null,
+ event: {
+ preventDefault: () => {},
+ },
+});
+
+const addPointerListeners = (
+ el: HTMLElement,
+ listeners: Record<string, (e: PointerEvent) => void>,
+) => {
+ for (const [event, handler] of Object.entries(listeners)) {
+ el.addEventListener(event, handler as EventListener);
+ }
+
+ return () => {
+ for (const [event, handler] of Object.entries(listeners)) {
+ el.removeEventListener(event, handler as EventListener);
+ }
+ };
+};
+
+/**
+ * Manages brush (range selection) for cartesian charts.
+ *
+ * Delegates to `useDesktopBrush` or `useTouchBrush` depending on device.
+ */
+export const useBrush = (
+ chartRef: MutableRefObject<EChartsType | undefined>,
+ containerRef: RefObject<HTMLDivElement>,
+ canBrushChart: boolean,
+ isBrushable: boolean,
+ // ECharts option object — used as a signal dep to re-enable brush after
+ // chart model changes (ECharts resets the cursor state on re-render).
+ option?: unknown,
+) => {
+ const isTouch = useRef(isTouchDevice()).current;
+
+ const enableBrush = useCallback(() => {
+ chartRef.current?.dispatchAction({
+ type: "takeGlobalCursor",
+ key: "brush",
+ brushOption: { brushType: "lineX", brushMode: "single" },
+ });
+ }, [chartRef]);
+
+ const disableBrush = useCallback(() => {
+ chartRef.current?.dispatchAction({ type: "takeGlobalCursor" });
+ }, [chartRef]);
+
+ useDesktopBrush({ isTouch, isBrushable, enableBrush, disableBrush, option });
+ useTouchBrush({
+ chartRef,
+ containerRef,
+ isTouch,
+ canBrushChart,
+ enableBrush,
+ disableBrush,
+ });
+};
+
+/** Desktop: brush is always on while `isBrushable` is true. */
+function useDesktopBrush({
+ isTouch,
+ isBrushable,
+ enableBrush,
+ disableBrush,
+ option,
+}: {
+ isTouch: boolean;
+ isBrushable: boolean;
+ enableBrush: () => void;
+ disableBrush: () => void;
+ option?: unknown;
+}) {
+ useEffect(() => {
+ if (isTouch) {
+ return;
+ }
+
+ const timeout = setTimeout(() => {
+ if (isBrushable) {
+ enableBrush();
+ } else {
+ disableBrush();
+ }
+ }, 0);
+
+ return () => clearTimeout(timeout);
+ }, [isBrushable, isTouch, enableBrush, disableBrush, option]);
+}
+
+/**
+ * Touch: long press activates brush for a single gesture.
+ * The user continues dragging horizontally to select a range, and brush
+ * is deactivated on pointer up.
+ */
+function useTouchBrush({
+ chartRef,
+ containerRef,
+ isTouch,
+ canBrushChart,
+ enableBrush,
+ disableBrush,
+}: {
+ chartRef: MutableRefObject<EChartsType | undefined>;
+ containerRef: RefObject<HTMLDivElement>;
+ isTouch: boolean;
+ canBrushChart: boolean;
+ enableBrush: () => void;
+ disableBrush: () => void;
+}) {
+ const timerRef = useRef<ReturnType<typeof setTimeout>>();
+ const startRef = useRef<Point | null>(null);
+ const activeRef = useRef(false);
+
+ // Track container element via state so the effect re-runs once when the
+ // ref becomes available (ExplicitSize hasn't measured on first render).
+ const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally no deps: syncs ref → state on every render
+ useEffect(() => {
+ const container = containerRef.current;
+
+ if (container && container !== containerEl) {
+ setContainerEl(container);
+ }
+ });
+
+ useEffect(() => {
+ if (!containerEl || !canBrushChart || !isTouch) {
+ return;
+ }
+
+ disableBrush();
+
+ // Prevent selection highlight, callout, and tap highlight on long-press.
+ // Applied as inline styles so only brushable charts on touch are affected.
+ // Save originals to restore on cleanup.
+ const svg = containerEl.querySelector("svg");
+
+ // Removes highlight on tap on android
+ containerEl.style.setProperty("-webkit-tap-highlight-color", "transparent");
+
+ // Removes text selection on long tap
+ svg?.style.setProperty("user-select", "none");
+ svg?.style.setProperty("-webkit-user-select", "none");
+ svg?.style.setProperty("-webkit-touch-callout", "none");
+
+ const cancel = () => {
+ clearTimeout(timerRef.current);
+
+ timerRef.current = undefined;
+ startRef.current = null;
+ };
+
+ const onPointerDown = (event: PointerEvent) => {
+ if (activeRef.current) {
+ return;
+ }
+
+ startRef.current = { x: event.clientX, y: event.clientY };
+
+ timerRef.current = setTimeout(() => {
+ activeRef.current = true;
+ enableBrush();
+
+ // Trigger mousedown directly on zrender's internal event bus.
+ // BrushController missed the real pointerdown (brush wasn't enabled
+ // yet), so we feed it the start position to anchor the selection.
+ const zrender = chartRef.current?.getZr();
+
+ if (zrender && startRef.current) {
+ zrender.trigger(
+ "mousedown",
+ createZrenderMousedownEvent(
+ startRef.current,
+ containerEl.getBoundingClientRect(),
+ ),
+ );
+ }
+ }, LONG_PRESS_DURATION_MS);
+ };
+
+ const onPointerMove = (event: PointerEvent) => {
+ if (!startRef.current || activeRef.current) {
+ return;
+ }
+
+ if (hasMovedBeyondThreshold(startRef.current, event)) {
+ cancel();
+ }
+ };
+
+ const onPointerEnd = () => {
+ cancel();
+
+ if (activeRef.current) {
+ activeRef.current = false;
+
+ // ECharts processes pointerup synchronously through its DOM handler
+ // chain (zrender pointerup → mouseup → brush end). All of this runs
+ // in the current microtask before any setTimeout(0) callback fires,
+ // so deferring by one macrotask is enough to guarantee brushEnd has
+ // already completed.
+ setTimeout(disableBrush, 0);
+ }
+ };
+
+ // Prevent browser scroll ONLY when brush is active (after long-press).
+ // Must be non-passive to allow preventDefault(). Before the long-press
+ // fires, touchmove is not prevented and the browser scrolls normally.
+ const onTouchMove = (e: TouchEvent) => {
+ if (activeRef.current) {
+ e.preventDefault();
+ }
+ };
+ containerEl.addEventListener("touchmove", onTouchMove, { passive: false });
+
+ const removeListeners = addPointerListeners(containerEl, {
+ pointerdown: onPointerDown,
+ pointermove: onPointerMove,
+ pointerup: onPointerEnd,
+ pointercancel: onPointerEnd,
+ });
+
+ return () => {
+ cancel();
+ removeListeners();
+
+ containerEl.style.setProperty("-webkit-tap-highlight-color", "none");
+ svg?.style.setProperty("user-select", "none");
+ svg?.style.setProperty("-webkit-user-select", "none");
+ svg?.style.setProperty("-webkit-touch-callout", "none");
+ };
+ }, [
+ containerEl,
+ chartRef,
+ canBrushChart,
+ isTouch,
+ enableBrush,
+ disableBrush,
+ ]);
+}
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.unit.spec.ts
new file mode 100644
index 00000000000..44116bded70
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.unit.spec.ts
@@ -0,0 +1,338 @@
+import { act, renderHook } from "@testing-library/react";
+import type { EChartsType } from "echarts/core";
+import type { MutableRefObject, RefObject } from "react";
+
+import { isTouchDevice } from "metabase/lib/browser";
+
+import {
+ createZrenderMousedownEvent,
+ hasMovedBeyondThreshold,
+ useBrush,
+} from "./use-brush";
+
+class PointerEventPolyfill extends MouseEvent {
+ readonly pointerType: string;
+
+ constructor(type: string, init: PointerEventInit = {}) {
+ super(type, init);
+
+ this.pointerType = init.pointerType ?? "";
+ }
+}
+
+if (typeof globalThis.PointerEvent === "undefined") {
+ (globalThis as any).PointerEvent = PointerEventPolyfill;
+}
+
+const createMockChartRef = () => {
+ const dispatchAction = jest.fn();
+ const trigger = jest.fn();
+ const getZrender = jest.fn(() => ({ trigger }));
+ const chartRef = {
+ current: { dispatchAction, getZr: getZrender } as unknown as EChartsType,
+ } as MutableRefObject<EChartsType | undefined>;
+
+ return { chartRef, dispatchAction, trigger };
+};
+
+const createMockContainerRef = () => {
+ const element = document.createElement("div");
+
+ element.getBoundingClientRect = jest.fn(
+ () => ({ left: 10, top: 20, width: 400, height: 300 }) as DOMRect,
+ );
+
+ const containerRef = { current: element } as RefObject<HTMLDivElement>;
+
+ return { containerRef, el: element };
+};
+
+const firePointer = (
+ element: HTMLElement,
+ type: string,
+ { clientX = 0, clientY = 0 }: { clientX?: number; clientY?: number } = {},
+) => {
+ element.dispatchEvent(
+ new PointerEvent(type, {
+ clientX,
+ clientY,
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+};
+
+const simulateTouch = () => {
+ Object.defineProperty(navigator, "maxTouchPoints", {
+ value: 5,
+ configurable: true,
+ });
+};
+
+const simulateDesktop = () => {
+ Object.defineProperty(navigator, "maxTouchPoints", {
+ value: 0,
+ configurable: true,
+ });
+};
+
+const expectBrushEnabled = (dispatchAction: jest.Mock) => {
+ expect(dispatchAction).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "takeGlobalCursor", key: "brush" }),
+ );
+};
+
+const expectBrushDisabled = (dispatchAction: jest.Mock) => {
+ expect(dispatchAction).toHaveBeenCalledWith({ type: "takeGlobalCursor" });
+};
+
+const expectBrushNotEnabled = (dispatchAction: jest.Mock) => {
+ expect(dispatchAction).not.toHaveBeenCalledWith(
+ expect.objectContaining({ key: "brush" }),
+ );
+};
+
+/**
+ * Renders useBrush in touch mode, flushes the initial setup,
+ * and clears dispatchAction so tests only see subsequent calls.
+ */
+const setupTouchBrush = (canBrushChart = true, isBrushable = true) => {
+ const { chartRef, dispatchAction, trigger } = createMockChartRef();
+ const { containerRef, el } = createMockContainerRef();
+
+ renderHook(() =>
+ useBrush(chartRef, containerRef, canBrushChart, isBrushable),
+ );
+ act(() => jest.runAllTimers());
+ dispatchAction.mockClear();
+
+ return { el, dispatchAction, trigger };
+};
+
+describe("use-brush", () => {
+ describe("hasMovedBeyondThreshold", () => {
+ it.each([
+ { start: { x: 0, y: 0 }, current: { x: 5, y: 5 }, expected: false },
+ { start: { x: 0, y: 0 }, current: { x: 10, y: 10 }, expected: true },
+ { start: { x: 100, y: 100 }, current: { x: 85, y: 85 }, expected: true },
+ { start: { x: 0, y: 0 }, current: { x: 0, y: 0 }, expected: false },
+ ])(
+ "($start → $current) = $expected (default threshold)",
+ ({ start, current, expected }) => {
+ expect(hasMovedBeyondThreshold(start, current)).toBe(expected);
+ },
+ );
+
+ it.each([
+ {
+ start: { x: 0, y: 0 },
+ current: { x: 3, y: 3 },
+ threshold: 100,
+ expected: false,
+ },
+ {
+ start: { x: 0, y: 0 },
+ current: { x: 80, y: 80 },
+ threshold: 100,
+ expected: true,
+ },
+ ])(
+ "($start → $current, threshold=$threshold) = $expected",
+ ({ start, current, threshold, expected }) => {
+ expect(hasMovedBeyondThreshold(start, current, threshold)).toBe(
+ expected,
+ );
+ },
+ );
+ });
+
+ describe("createZrenderMousedownEvent", () => {
+ it("calculates correct offsets from client coords and rect", () => {
+ const rect = { left: 50, top: 100 } as DOMRect;
+ const { offsetX, offsetY, target, event } = createZrenderMousedownEvent(
+ { x: 150, y: 250 },
+ rect,
+ );
+
+ expect(offsetX).toBe(100);
+ expect(offsetY).toBe(150);
+ expect(target).toBeNull();
+ expect(event.preventDefault).toBeInstanceOf(Function);
+ });
+ });
+
+ describe("isTouchDevice", () => {
+ const originalMatchMedia = window.matchMedia;
+
+ afterEach(() => {
+ window.matchMedia = originalMatchMedia;
+ });
+
+ it("returns false when no touch support", () => {
+ simulateDesktop();
+ expect(isTouchDevice()).toBe(false);
+ });
+
+ it("returns true when coarse pointer and no hover", () => {
+ simulateDesktop();
+ window.matchMedia = jest.fn((query: string) => ({
+ matches: query === "(pointer: coarse)" || query === "(hover: none)",
+ media: query,
+ onchange: null,
+ addListener: jest.fn(),
+ removeListener: jest.fn(),
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ dispatchEvent: jest.fn(),
+ }));
+ expect(isTouchDevice()).toBe(true);
+ });
+
+ it("returns false when fine pointer even with hover none", () => {
+ simulateDesktop();
+ window.matchMedia = jest.fn((query: string) => ({
+ matches: query === "(hover: none)",
+ media: query,
+ onchange: null,
+ addListener: jest.fn(),
+ removeListener: jest.fn(),
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ dispatchEvent: jest.fn(),
+ }));
+ expect(isTouchDevice()).toBe(false);
+ });
+
+ it("returns true when maxTouchPoints > 0", () => {
+ Object.defineProperty(navigator, "maxTouchPoints", {
+ value: 1,
+ configurable: true,
+ });
+ expect(isTouchDevice()).toBe(true);
+ });
+ });
+
+ describe("useBrush", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ describe("desktop (non-touch)", () => {
+ beforeEach(simulateDesktop);
+
+ it("enables brush when isBrushable is true", () => {
+ const { chartRef, dispatchAction } = createMockChartRef();
+ const { containerRef } = createMockContainerRef();
+
+ renderHook(() => useBrush(chartRef, containerRef, true, true));
+ act(() => jest.runAllTimers());
+
+ expectBrushEnabled(dispatchAction);
+ });
+
+ it("disables brush when isBrushable is false", () => {
+ const { chartRef, dispatchAction } = createMockChartRef();
+ const { containerRef } = createMockContainerRef();
+
+ renderHook(() => useBrush(chartRef, containerRef, true, false));
+ act(() => jest.runAllTimers());
+
+ expectBrushDisabled(dispatchAction);
+ });
+ });
+
+ describe("touch", () => {
+ beforeEach(simulateTouch);
+
+ it("disables brush by default", () => {
+ const { chartRef, dispatchAction } = createMockChartRef();
+ const { containerRef } = createMockContainerRef();
+
+ renderHook(() => useBrush(chartRef, containerRef, true, true));
+ act(() => jest.runAllTimers());
+
+ expectBrushDisabled(dispatchAction);
+ });
+
+ it("enables brush after long press", () => {
+ const { el, dispatchAction } = setupTouchBrush();
+
+ firePointer(el, "pointerdown", { clientX: 100, clientY: 100 });
+ act(() => jest.advanceTimersByTime(500));
+
+ expectBrushEnabled(dispatchAction);
+ });
+
+ it("cancels long press on movement", () => {
+ const { el, dispatchAction } = setupTouchBrush();
+
+ firePointer(el, "pointerdown", { clientX: 100, clientY: 100 });
+ firePointer(el, "pointermove", { clientX: 150, clientY: 100 });
+ act(() => jest.advanceTimersByTime(500));
+
+ expectBrushNotEnabled(dispatchAction);
+ });
+
+ it("cancels long press on pointer up before timeout", () => {
+ const { el, dispatchAction } = setupTouchBrush();
+
+ firePointer(el, "pointerdown", { clientX: 100, clientY: 100 });
+ act(() => jest.advanceTimersByTime(200));
+ firePointer(el, "pointerup");
+ act(() => jest.advanceTimersByTime(300));
+
+ expectBrushNotEnabled(dispatchAction);
+ });
+
+ it("disables brush when finger is lifted after long press", () => {
+ const { el, dispatchAction } = setupTouchBrush();
+
+ firePointer(el, "pointerdown", { clientX: 100, clientY: 100 });
+ act(() => jest.advanceTimersByTime(500));
+ dispatchAction.mockClear();
+
+ firePointer(el, "pointerup");
+ act(() => jest.runAllTimers());
+
+ expectBrushDisabled(dispatchAction);
+ });
+
+ it("does not activate when chart does not support brush", () => {
+ const { el, dispatchAction } = setupTouchBrush(false, false);
+
+ firePointer(el, "pointerdown", { clientX: 100, clientY: 100 });
+ act(() => jest.advanceTimersByTime(500));
+
+ expect(dispatchAction).not.toHaveBeenCalled();
+ });
+
+ it("allows scroll (touchmove) before long press", () => {
+ const { el } = setupTouchBrush();
+
+ firePointer(el, "pointerdown", { clientX: 100, clientY: 100 });
+ act(() => jest.advanceTimersByTime(200));
+
+ const touchmove = new Event("touchmove", { cancelable: true });
+ el.dispatchEvent(touchmove);
+
+ expect(touchmove.defaultPrevented).toBe(false);
+ });
+
+ it("prevents scroll (touchmove) after long press", () => {
+ const { el } = setupTouchBrush();
+
+ firePointer(el, "pointerdown", { clientX: 100, clientY: 100 });
+ act(() => jest.advanceTimersByTime(500));
+
+ const touchmove = new Event("touchmove", { cancelable: true });
+ el.dispatchEvent(touchmove);
+
+ expect(touchmove.defaultPrevented).toBe(true);
+ });
+ });
+ });
+});
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-chart-events.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-chart-events.ts
index 15efe31f55f..4065c0e0783 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-chart-events.ts
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-chart-events.ts
@@ -43,6 +43,7 @@ import {
import { getVisualizerSeriesCardIndex } from "metabase/visualizer/utils";
import type { CardId } from "metabase-types/api";
+import { useBrush } from "./use-brush";
import { useTooltipMouseLeave } from "./use-tooltip-mouse-leave";
import { getHoveredEChartsSeriesDataKeyAndIndex } from "./utils";
@@ -356,42 +357,15 @@ export const useChartEvents = (
useClickedStateTooltipSync(chartRef.current, clicked);
- // In order to keep brushing always enabled we have to re-enable it on every model change
- useEffect(
- function toggleBrushing() {
- const shouldEnableBrushing =
- canBrush(rawSeries, settings, onChangeCardAndRun, onBrush) &&
- !hovered &&
- !clicked;
-
- setTimeout(() => {
- if (shouldEnableBrushing) {
- chartRef.current?.dispatchAction({
- type: "takeGlobalCursor",
- key: "brush",
- brushOption: {
- brushType: "lineX",
- brushMode: "single",
- },
- });
- } else {
- chartRef.current?.dispatchAction({
- type: "takeGlobalCursor",
- });
- }
- }, 0);
- },
- [
- chartRef,
- hovered,
- onChangeCardAndRun,
- onBrush,
- option,
- rawSeries,
- settings,
- clicked,
- ],
+ const canBrushChart = canBrush(
+ rawSeries,
+ settings,
+ onChangeCardAndRun,
+ onBrush,
);
+ const isBrushable = canBrushChart && !hovered && !clicked;
+
+ useBrush(chartRef, containerRef, canBrushChart, isBrushable, option);
const onSelectSeries = useCallback(
(event: React.MouseEvent, seriesIndex: number) => {