The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat(sdk,embed-js): Auto-scroll to the auto-opened dropdown for Join Step on touch devices (#71965)
Timofey Kachalov5ea5206719b5
diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinColumnButton/JoinColumnButton.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinColumnButton/JoinColumnButton.tsxindex b052028ace6..a5743eefcd6 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinColumnButton/JoinColumnButton.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinColumnButton/JoinColumnButton.tsx@@ -1,5 +1,7 @@+import { useMergedRef } from "@mantine/hooks";import cx from "classnames";-import { type Ref, forwardRef, useMemo } from "react";+import { type Ref, forwardRef, useMemo, useRef } from "react";+import { useMount } from "react-use";import { t } from "ttag";import { useLocale } from "metabase/common/hooks";@@ -7,6 +9,7 @@ import { useTranslateContent } from "metabase/i18n/hooks";import type { ContentTranslationFunction } from "metabase/i18n/types";import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";import { Text } from "metabase/ui";+import { isTouchDevice } from "metabase/utils/browser";import * as Lib from "metabase-lib";import S from "./JoinColumnButton.module.css";@@ -48,6 +51,21 @@ export const JoinColumnButton = forwardRef(function JoinColumnTarget(const isLiteral =expression != null && Lib.isJoinConditionLHSorRHSLiteral(expression);+ const buttonRef = useRef<HTMLButtonElement>(null);+ const mergedRef = useMergedRef(buttonRef, ref);++ useMount(() => {+ // On touch devices we scroll to the auto-opened dropdown,+ // as the anchor button of the opened dropdown may be horizontally out of the screen.+ if (isOpened && buttonRef.current && isTouchDevice()) {+ buttonRef.current.scrollIntoView({+ behavior: "smooth",+ inline: "start",+ block: "nearest",+ });+ }+ });+return (<buttonclassName={cx(S.joinCellItem, {@@ -56,7 +74,7 @@ export const JoinColumnButton = forwardRef(function JoinColumnTarget([S.noColumnStyle]: isEmpty,[S.isOpen]: isOpened,})}- ref={ref}+ ref={mergedRef}disabled={isReadOnly}onClick={onClick}aria-label={isLhsPicker ? t`Left column` : t`Right column`}diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinColumnButton/JoinColumnButton.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinColumnButton/JoinColumnButton.unit.spec.tsxnew file mode 100644index 00000000000..d0bbde0766e--- /dev/null+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinColumnButton/JoinColumnButton.unit.spec.tsx@@ -0,0 +1,99 @@+import { renderWithProviders } from "__support__/ui";+import { isTouchDevice } from "metabase/utils/browser";+import * as Lib from "metabase-lib";+import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";+import { ORDERS_ID } from "metabase-types/api/mocks/presets";++import { JoinColumnButton } from "./JoinColumnButton";++jest.mock("metabase/utils/browser", () => ({+ ...jest.requireActual("metabase/utils/browser"),+ isTouchDevice: jest.fn(() => false),+}));++const scrollIntoViewMock = jest.fn();++const query = Lib.createTestQuery(SAMPLE_PROVIDER, {+ stages: [+ {+ source: { type: "table", id: ORDERS_ID },+ },+ ],+});++function setup({+ isOpened = false,+ isLhsPicker = true,+ isReadOnly = false,+ touch = false,+}: {+ isOpened?: boolean;+ isLhsPicker?: boolean;+ isReadOnly?: boolean;+ touch?: boolean;+} = {}) {+ (isTouchDevice as jest.Mock).mockReturnValue(touch);++ return renderWithProviders(+ <JoinColumnButton+ query={query}+ stageIndex={0}+ tableName={undefined}+ lhsExpression={undefined}+ rhsExpression={undefined}+ isLhsPicker={isLhsPicker}+ isOpened={isOpened}+ isReadOnly={isReadOnly}+ onClick={jest.fn()}+ />,+ );+}++describe("JoinColumnButton scroll on auto-open", () => {+ beforeEach(() => {+ scrollIntoViewMock.mockClear();+ HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("scrolls into view on auto-open on touch devices", () => {+ setup({ isOpened: true, touch: true });++ expect(scrollIntoViewMock).toHaveBeenCalledWith({+ behavior: "smooth",+ inline: "start",+ block: "nearest",+ });+ });++ it("does not scroll when mounted as closed then opened later", () => {+ const { rerender } = setup({ isOpened: false, touch: true });++ scrollIntoViewMock.mockClear();++ rerender(+ <JoinColumnButton+ query={query}+ stageIndex={0}+ tableName={undefined}+ lhsExpression={undefined}+ rhsExpression={undefined}+ isLhsPicker+ isOpened+ isReadOnly={false}+ onClick={jest.fn()}+ />,+ );++ expect(scrollIntoViewMock).not.toHaveBeenCalled();+ });++ it("does not scroll on desktop", () => {+ setup({ isOpened: true, touch: false });++ expect(scrollIntoViewMock).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/metabase/utils/browser.ts b/frontend/src/metabase/utils/browser.tsindex 12cc44b6211..ba85287e968 100644--- a/frontend/src/metabase/utils/browser.ts+++ b/frontend/src/metabase/utils/browser.ts@@ -58,11 +58,13 @@ export const isTouchDevice = () => {window.matchMedia("(pointer: coarse)").matches;const hasHoverSupport = window.matchMedia("(hover: hover)").matches;- if (hasCoarsePointerSupport && !hasHoverSupport) {- return true;- }+ // true for phones/tablets (coarse pointer, no hover)+ // false for desktops (fine pointer, has hover)+ // false for laptops with touchscreens (coarse pointer, but also has hover)+ return hasCoarsePointerSupport && !hasHoverSupport;}+ // Fallback for environments without matchMedia (e.g. older browsers)return typeof navigator !== "undefined" && navigator.maxTouchPoints > 0;};diff --git a/frontend/src/metabase/utils/browser.unit.spec.ts b/frontend/src/metabase/utils/browser.unit.spec.tsindex d6b97c07e87..7feab9f65b4 100644--- a/frontend/src/metabase/utils/browser.unit.spec.ts+++ b/frontend/src/metabase/utils/browser.unit.spec.ts@@ -1,78 +1,130 @@-import { parseHashOptions, stringifyHashOptions } from "metabase/utils/browser";+import { createMockMediaQueryList } from "__support__/ui";+import {+ isTouchDevice,+ parseHashOptions,+ stringifyHashOptions,+} from "metabase/utils/browser";-describe("browser", () => {- describe("parseHashOptions", () => {- it("should parse with prepended '#'", () => {- expect(parseHashOptions("#foo=bar")).toEqual({ foo: "bar" });- });-- it("should parse without prepended '#'", () => {- expect(parseHashOptions("foo=bar")).toEqual({ foo: "bar" });- });-- it("should parse strings", () => {- expect(parseHashOptions("#foo=bar")).toEqual({ foo: "bar" });- });-- it("should parse numbers", () => {- expect(parseHashOptions("#foo=123")).toEqual({ foo: 123 });- });-- it("should parse negative numbers", () => {- expect(parseHashOptions("#foo=-123")).toEqual({ foo: -123 });- });-- it("should parse base key as true", () => {- expect(parseHashOptions("#foo")).toEqual({ foo: true });- });-- it("should parse true", () => {- expect(parseHashOptions("#foo=true")).toEqual({ foo: true });- });-- it("should parse false", () => {- expect(parseHashOptions("#foo=false")).toEqual({ foo: false });- });+const originalMatchMedia = window.matchMedia;- it("should parse all the things", () => {- expect(- parseHashOptions("#foo1=bar&foo2=123&foo3&foo4=true&foo5=false"),- ).toEqual({- foo1: "bar",- foo2: 123,- foo3: true,- foo4: true,- foo5: false,+function setup({+ coarsePointer = false,+ hover = false,+ maxTouchPoints = 0,+ matchMediaAvailable = true,+}: {+ coarsePointer?: boolean;+ hover?: boolean;+ maxTouchPoints?: number;+ matchMediaAvailable?: boolean;+} = {}) {+ if (matchMediaAvailable) {+ window.matchMedia = (query: string) =>+ createMockMediaQueryList({+ matches:+ (query === "(pointer: coarse)" && coarsePointer) ||+ (query === "(hover: hover)" && hover),});- });- });-- describe("stringifyHashOptions", () => {- it("should stringify strings", () => {- expect(stringifyHashOptions({ foo: "bar" })).toEqual("foo=bar");- });+ } else {+ (window as any).matchMedia = undefined;+ }- it("should stringify numbers", () => {- expect(stringifyHashOptions({ foo: 123 })).toEqual("foo=123");- });+ Object.defineProperty(navigator, "maxTouchPoints", {+ value: maxTouchPoints,+ configurable: true,+ });+}- it("should stringify base key as true", () => {- expect(stringifyHashOptions({ foo: true })).toEqual("foo");+describe("browser", () => {+ describe("isTouchDevice", () => {+ afterEach(() => {+ window.matchMedia = originalMatchMedia;+ Object.defineProperty(navigator, "maxTouchPoints", {+ value: 0,+ configurable: true,+ });});- it("should stringify false", () => {- expect(stringifyHashOptions({ foo: false })).toEqual("foo=false");+ it.each([+ {+ name: "touch-only device (coarse pointer, no hover)",+ opts: { coarsePointer: true },+ expected: true,+ },+ {+ name: "desktop (fine pointer, has hover)",+ opts: { hover: true },+ expected: false,+ },+ {+ name: "2-in-1 laptop in laptop mode (fine pointer + touch screen)",+ opts: { hover: true, maxTouchPoints: 10 },+ expected: false,+ },+ {+ name: "2-in-1 laptop in tablet mode (coarse pointer, no hover)",+ opts: { coarsePointer: true, maxTouchPoints: 10 },+ expected: true,+ },+ {+ name: "no coarse pointer and no hover",+ opts: {},+ expected: false,+ },+ {+ name: "matchMedia unavailable with touch points",+ opts: { matchMediaAvailable: false, maxTouchPoints: 5 },+ expected: true,+ },+ {+ name: "matchMedia unavailable without touch points",+ opts: { matchMediaAvailable: false },+ expected: false,+ },+ ])("returns $expected for $name", ({ opts, expected }) => {+ setup(opts);+ expect(isTouchDevice()).toBe(expected);});+ });- it("should stringify all the things", () => {- expect(- stringifyHashOptions({+ describe("parseHashOptions", () => {+ it.each([+ { input: "#foo=bar", expected: { foo: "bar" }, name: "with '#'" },+ { input: "foo=bar", expected: { foo: "bar" }, name: "without '#'" },+ { input: "#foo=123", expected: { foo: 123 }, name: "numbers" },+ { input: "#foo=-123", expected: { foo: -123 }, name: "negative numbers" },+ { input: "#foo", expected: { foo: true }, name: "bare key as true" },+ { input: "#foo=true", expected: { foo: true }, name: "true" },+ { input: "#foo=false", expected: { foo: false }, name: "false" },+ {+ input: "#foo1=bar&foo2=123&foo3&foo4=true&foo5=false",+ expected: {foo1: "bar",foo2: 123,foo3: true,- foo4: false,- }),- ).toEqual("foo1=bar&foo2=123&foo3&foo4=false");+ foo4: true,+ foo5: false,+ },+ name: "mixed values",+ },+ ])("should parse $name", ({ input, expected }) => {+ expect(parseHashOptions(input)).toEqual(expected);+ });+ });++ describe("stringifyHashOptions", () => {+ it.each([+ { input: { foo: "bar" }, expected: "foo=bar", name: "strings" },+ { input: { foo: 123 }, expected: "foo=123", name: "numbers" },+ { input: { foo: true }, expected: "foo", name: "true as bare key" },+ { input: { foo: false }, expected: "foo=false", name: "false" },+ {+ input: { foo1: "bar", foo2: 123, foo3: true, foo4: false },+ expected: "foo1=bar&foo2=123&foo3&foo4=false",+ name: "mixed values",+ },+ ])("should stringify $name", ({ input, expected }) => {+ expect(stringifyHashOptions(input)).toEqual(expected);});});});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.tsindex a1c430324e4..c363062a74b 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.unit.spec.ts+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-brush.unit.spec.ts@@ -2,7 +2,7 @@ import { act, renderHook } from "@testing-library/react";import type { EChartsType } from "echarts/core";import type { MutableRefObject, RefObject } from "react";-import { isTouchDevice } from "metabase/utils/browser";+import { createMockMediaQueryList } from "__support__/ui";import {createZrenderMousedownEvent,@@ -78,11 +78,23 @@ const firePointer = ();};+const mockMatchMedia = (results: Record<string, boolean>) => {+ window.matchMedia = (query: string) =>+ createMockMediaQueryList({+ matches: results[query] ?? false,+ media: query,+ });+};+const simulateTouch = () => {Object.defineProperty(navigator, "maxTouchPoints", {value: 5,configurable: true,});+ mockMatchMedia({+ "(pointer: coarse)": true,+ "(hover: hover)": false,+ });};const simulateDesktop = () => {@@ -90,6 +102,10 @@ const simulateDesktop = () => {value: 0,configurable: true,});+ mockMatchMedia({+ "(pointer: coarse)": false,+ "(hover: hover)": true,+ });};const expectBrushEnabled = (dispatchAction: jest.Mock) => {@@ -177,57 +193,6 @@ describe("use-brush", () => {});});- 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();