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
Fix dashcard #scrollTo auto-scroll (#78522)
Romeo Van Snick14a65406f14a
diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.jsindex f95c325e82a..f4f244cc868 100644--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js@@ -1098,7 +1098,7 @@ describe("scenarios > dashboard", () => {);cy.log("should not be visible (below the fold)");- cy.visit(`/dashboard/${dashboard.id}}`);+ cy.visit(`/dashboard/${dashboard.id}`);cy.findByText(TARGET_TEXT).should("not.be.visible");cy.log("should scroll into view w/ scrollTo hash param");diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsxindex ea9fa156603..c90610fbccc 100644--- a/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsx+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCard.tsx@@ -47,6 +47,7 @@ import S from "./DashCard.module.css";import { DashCardActionsPanel } from "./DashCardActionsPanel/DashCardActionsPanel";import { DashCardVisualization } from "./DashCardVisualization";import type { DashCardOnChangeCardAndRunHandler } from "./types";+import { useAutoScrollIntoView } from "./use-auto-scroll-into-view";function preventDragging(event: React.SyntheticEvent) {event.stopPropagation();@@ -135,11 +136,12 @@ function DashCardInner({cardRootRef?.current?.scrollIntoView({ block: "nearest" });markNewCardSeen(dashcard.id);}+ });- if (autoScroll) {- cardRootRef?.current?.scrollIntoView({ block: "nearest" });- reportAutoScrolledToDashcard?.();- }+ useAutoScrollIntoView({+ ref: cardRootRef,+ enabled: Boolean(autoScroll),+ onScrolled: () => reportAutoScrolledToDashcard?.(),});useUpdateEffect(() => {diff --git a/frontend/src/metabase/dashboard/components/DashCard/use-auto-scroll-into-view.ts b/frontend/src/metabase/dashboard/components/DashCard/use-auto-scroll-into-view.tsnew file mode 100644index 00000000000..dd10f08dcde--- /dev/null+++ b/frontend/src/metabase/dashboard/components/DashCard/use-auto-scroll-into-view.ts@@ -0,0 +1,59 @@+import { type RefObject, useEffect, useRef } from "react";++/**+ * Long enough to cover the grid's post-measure re-layout, short enough not to+ * fight a user who starts scrolling.+ */+const CORRECTION_FRAME_COUNT = 20;++/**+ * Scrolls the target into view, then keeps it there for a moment.+ *+ * Runs whenever the card becomes the target, not only when it mounts: a+ * `#scrollTo` hash added to the dashboard you are already on is a plain hash+ * change, and the dashcards around it stay mounted.+ *+ * The repeat matters on a cold load. The dashboard grid measures its container+ * and re-lays out its cards over the following frames, which moves every+ * dashcard out from under a scroll that already happened.+ *+ * `onScrolled` fires with the first scroll rather than the last, so clearing+ * the `scrollTo` hash never waits on the layout. Clearing it is what makes this+ * card stop being the target, so the repeats deliberately outlive `enabled` and+ * are only cancelled on unmount.+ */+export function useAutoScrollIntoView({+ ref,+ enabled,+ onScrolled,+}: {+ ref: RefObject<HTMLElement>;+ enabled: boolean;+ onScrolled: () => void;+}) {+ const onScrolledRef = useRef(onScrolled);+ onScrolledRef.current = onScrolled;++ const frameRef = useRef<number>();++ useEffect(() => () => cancelAnimationFrame(frameRef.current ?? 0), []);++ useEffect(() => {+ if (!enabled) {+ return;+ }++ let frameCount = 0;++ const scrollIntoView = () => {+ ref.current?.scrollIntoView({ block: "nearest" });++ if (++frameCount < CORRECTION_FRAME_COUNT) {+ frameRef.current = requestAnimationFrame(scrollIntoView);+ }+ };++ scrollIntoView();+ onScrolledRef.current();+ }, [enabled, ref]);+}diff --git a/frontend/src/metabase/dashboard/components/DashCard/use-auto-scroll-into-view.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashCard/use-auto-scroll-into-view.unit.spec.tsxnew file mode 100644index 00000000000..186c8765110--- /dev/null+++ b/frontend/src/metabase/dashboard/components/DashCard/use-auto-scroll-into-view.unit.spec.tsx@@ -0,0 +1,84 @@+import { act, renderHook } from "@testing-library/react";++import { useAutoScrollIntoView } from "./use-auto-scroll-into-view";++function setup({ enabled = true }: { enabled?: boolean } = {}) {+ const frames: FrameRequestCallback[] = [];+ jest+ .spyOn(window, "requestAnimationFrame")+ .mockImplementation((callback) => frames.push(callback));+ jest+ .spyOn(window, "cancelAnimationFrame")+ .mockImplementation(() => undefined);++ const scrollIntoView = jest.fn();+ // A stub rather than a real element: jsdom has no layout.+ const ref = { current: { scrollIntoView } as unknown as HTMLElement };++ const onScrolled = jest.fn();+ const { rerender } = renderHook(+ (props: { enabled: boolean }) =>+ useAutoScrollIntoView({ ref, onScrolled, ...props }),+ { initialProps: { enabled } },+ );++ const runFrames = (count: number) =>+ act(() => {+ for (let index = 0; index < count; index++) {+ const frame = frames.shift();+ if (!frame) {+ return;+ }+ frame(0);+ }+ });++ const setEnabled = (nextEnabled: boolean) =>+ rerender({ enabled: nextEnabled });++ return { scrollIntoView, onScrolled, runFrames, setEnabled };+}++describe("useAutoScrollIntoView", () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("does nothing when it is not the target dashcard", () => {+ const { scrollIntoView, onScrolled, runFrames } = setup({ enabled: false });++ runFrames(5);++ expect(scrollIntoView).not.toHaveBeenCalled();+ expect(onScrolled).not.toHaveBeenCalled();+ });++ it("scrolls and reports right away, without waiting for a frame", () => {+ const { scrollIntoView, onScrolled } = setup();++ expect(scrollIntoView).toHaveBeenCalledTimes(1);+ expect(onScrolled).toHaveBeenCalledTimes(1);+ });++ it("scrolls when an already mounted card becomes the target", () => {+ const { scrollIntoView, onScrolled, setEnabled } = setup({+ enabled: false,+ });++ setEnabled(true);++ expect(scrollIntoView).toHaveBeenCalledTimes(1);+ expect(onScrolled).toHaveBeenCalledTimes(1);+ });++ it("keeps correcting the scroll while the grid lays itself out, then stops", () => {+ const { scrollIntoView, setEnabled, runFrames } = setup();++ // Reporting the scroll clears the hash, which is what turns `enabled` off.+ setEnabled(false);++ runFrames(30);++ expect(scrollIntoView).toHaveBeenCalledTimes(20);+ });+});diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.autoscroll.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.autoscroll.unit.spec.tsxnew file mode 100644index 00000000000..405670f09fe--- /dev/null+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.autoscroll.unit.spec.tsx@@ -0,0 +1,129 @@+import {+ setupActionsEndpoints,+ setupBookmarksEndpoints,+ setupCardsEndpoints,+ setupCollectionsEndpoints,+ setupDashboardEndpoints,+ setupDashboardQueryMetadataEndpoint,+ setupDatabasesEndpoints,+ setupSearchEndpoints,+} from "__support__/server-mocks";+import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";+import { mockSettings } from "__support__/settings";+import { createMockEntitiesState } from "__support__/store";+import {+ act,+ renderWithProviders,+ waitFor,+ waitForLoaderToBeRemoved,+} from "__support__/ui";+import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";+import { createMockDashboardState } from "metabase/redux/store/mocks";+import { Route } from "metabase/router";+import { checkNotNull } from "metabase/utils/types";+import {+ createMockDashboard,+ createMockDashboardQueryMetadata,+ createMockDatabase,+ createMockTextDashboardCard,+} from "metabase-types/api/mocks";++const TARGET_TEXT = "Scroll to me plz.";+const DASHBOARD_ID = 1;+const TARGET_DASHCARD_ID = 42;++async function setup({ hash = "" }: { hash?: string } = {}) {+ const dashboard = createMockDashboard({+ id: DASHBOARD_ID,+ dashcards: [+ createMockTextDashboardCard({+ id: 1,+ dashboard_id: DASHBOARD_ID,+ row: 0,+ text: "I'm just padding",+ }),+ createMockTextDashboardCard({+ id: TARGET_DASHCARD_ID,+ dashboard_id: DASHBOARD_ID,+ row: 10,+ text: TARGET_TEXT,+ }),+ ],+ });++ const database = createMockDatabase();+ setupNotificationChannelsEndpoints({});+ setupDatabasesEndpoints([database]);+ setupDashboardEndpoints(dashboard);+ setupDashboardQueryMetadataEndpoint(+ dashboard,+ createMockDashboardQueryMetadata({ databases: [database] }),+ );+ setupCollectionsEndpoints({ collections: [] });+ setupSearchEndpoints([]);+ setupCardsEndpoints([]);+ setupBookmarksEndpoints([]);+ setupActionsEndpoints([]);++ const scrollIntoView = jest.spyOn(HTMLElement.prototype, "scrollIntoView");++ const { history } = renderWithProviders(+ <Route path="/dashboard/:slug" element={<DashboardApp />} />,+ {+ initialRoute: `/dashboard/${dashboard.id}${hash}`,+ withRouter: true,+ storeInitialState: {+ dashboard: createMockDashboardState(),+ entities: createMockEntitiesState({ databases: [database] }),+ settings: mockSettings({ "site-url": "http://localhost:3000" }),+ },+ },+ );++ await waitForLoaderToBeRemoved();++ const getTargetDashcard = () =>+ checkNotNull(+ document.querySelector(`[data-dashcard-key="${TARGET_DASHCARD_ID}"]`),+ );++ const wasTargetScrolledIntoView = () =>+ scrollIntoView.mock.contexts.some(+ (context) => context === getTargetDashcard(),+ );++ return { history: checkNotNull(history), wasTargetScrolledIntoView };+}++describe("DashboardApp auto-scroll", () => {+ it("scrolls to the dashcard named by the scrollTo hash param and clears the hash", async () => {+ const { history, wasTargetScrolledIntoView } = await setup({+ hash: `#scrollTo=${TARGET_DASHCARD_ID}`,+ });++ await waitFor(() => expect(history.getCurrentLocation().hash).toBe(""));++ expect(wasTargetScrolledIntoView()).toBe(true);+ });++ it("scrolls when the scrollTo hash param is added to the dashboard already on screen", async () => {+ const { history, wasTargetScrolledIntoView } = await setup();++ expect(wasTargetScrolledIntoView()).toBe(false);++ act(() => {+ history.push(`/dashboard/${DASHBOARD_ID}#scrollTo=${TARGET_DASHCARD_ID}`);+ });++ await waitFor(() => expect(history.getCurrentLocation().hash).toBe(""));++ expect(wasTargetScrolledIntoView()).toBe(true);+ });++ it("does not scroll when there is no scrollTo hash param", async () => {+ const { history, wasTargetScrolledIntoView } = await setup();++ expect(wasTargetScrolledIntoView()).toBe(false);+ expect(history.getCurrentLocation().hash).toBe("");+ });+});