Skip to content

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

Stop dashboard cards from splaying out on load (#83620)

Maz Ameli77eea9b8788a
diff --git a/frontend/src/metabase/common/hooks/use-has-painted-since-mount.ts b/frontend/src/metabase/common/hooks/use-has-painted-since-mount.ts
new file mode 100644
index 00000000000..ac5f103408d
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-has-painted-since-mount.ts
@@ -0,0 +1,20 @@
+import { useEffect, useState } from "react";
+
+/**
+ * Returns `false` until the browser has painted at least one frame after the
+ * component mounted, then `true`.
+ */
+export function useHasPaintedSinceMount(): boolean {
+ const [hasPainted, setHasPainted] = useState(false);
+
+ useEffect(() => {
+ // The first frame callback runs before that frame is painted, so wait for
+ // the second one.
+ let frameId = requestAnimationFrame(() => {
+ frameId = requestAnimationFrame(() => setHasPainted(true));
+ });
+ return () => cancelAnimationFrame(frameId);
+ }, []);
+
+ return hasPainted;
+}
diff --git a/frontend/src/metabase/common/hooks/use-has-painted-since-mount.unit.spec.ts b/frontend/src/metabase/common/hooks/use-has-painted-since-mount.unit.spec.ts
new file mode 100644
index 00000000000..e75afb786eb
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-has-painted-since-mount.unit.spec.ts
@@ -0,0 +1,63 @@
+import { act, renderHook } from "@testing-library/react";
+
+import { useHasPaintedSinceMount } from "./use-has-painted-since-mount";
+
+describe("useHasPaintedSinceMount", () => {
+ let frameCallbacks: Map<number, FrameRequestCallback>;
+ let nextFrameId: number;
+
+ const runFrame = () => {
+ const callbacks = [...frameCallbacks.values()];
+ frameCallbacks.clear();
+ act(() => callbacks.forEach((callback) => callback(performance.now())));
+ };
+
+ beforeEach(() => {
+ frameCallbacks = new Map();
+ nextFrameId = 1;
+ jest
+ .spyOn(window, "requestAnimationFrame")
+ .mockImplementation((callback) => {
+ const frameId = nextFrameId++;
+ frameCallbacks.set(frameId, callback);
+ return frameId;
+ });
+ jest
+ .spyOn(window, "cancelAnimationFrame")
+ .mockImplementation((frameId) => frameCallbacks.delete(frameId));
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("is false on mount", () => {
+ const { result } = renderHook(() => useHasPaintedSinceMount());
+ expect(result.current).toBe(false);
+ });
+
+ it("stays false after only one frame, because that frame has not been painted yet", () => {
+ const { result } = renderHook(() => useHasPaintedSinceMount());
+ runFrame();
+ expect(result.current).toBe(false);
+ });
+
+ it("becomes true on the second frame", () => {
+ const { result } = renderHook(() => useHasPaintedSinceMount());
+ runFrame();
+ runFrame();
+ expect(result.current).toBe(true);
+ });
+
+ it.each([
+ ["before the first frame", 0],
+ ["between the two frames", 1],
+ ])("cancels the pending frame when unmounted %s", (_label, framesRun) => {
+ const { unmount } = renderHook(() => useHasPaintedSinceMount());
+ for (let i = 0; i < framesRun; i++) {
+ runFrame();
+ }
+ unmount();
+ expect(frameCallbacks.size).toBe(0);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/DashboardGrid.module.css b/frontend/src/metabase/dashboard/components/DashboardGrid.module.css
index 37fbf7634fa..909d0953f81 100644
--- a/frontend/src/metabase/dashboard/components/DashboardGrid.module.css
+++ b/frontend/src/metabase/dashboard/components/DashboardGrid.module.css
@@ -23,10 +23,6 @@
z-index: 2;
}
- &.isAnimationDisabled {
- transition: none;
- }
-
@media (prefers-reduced-motion) {
/* short duration (instead of none) to still trigger transition events */
transition-duration: 10ms !important;
diff --git a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx b/frontend/src/metabase/dashboard/components/DashboardGrid.tsx
index 33e1529478e..64ff9b89a83 100644
--- a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardGrid.tsx
@@ -88,7 +88,6 @@ interface DashboardGridInnerState {
};
replaceCardModalDashCard: BaseDashboardCard | null;
isDragging: boolean;
- isAnimationPaused: boolean;
dashcardCountByCardId: Record<CardId, number>;
_lastProps?: LastProps;
@@ -169,8 +168,6 @@ class DashboardGridInner extends Component<
> {
static contextType = ContentViewportContext;
- _pauseAnimationTimer: ReturnType<typeof setTimeout> | null = null;
-
constructor(props: DashboardGridInnerProps, context: unknown) {
super(props, context);
@@ -196,7 +193,6 @@ class DashboardGridInner extends Component<
),
replaceCardModalDashCard: null,
isDragging: false,
- isAnimationPaused: true,
_lastProps: {
dashboard: props.dashboard,
isEditing: props.isEditing,
@@ -205,21 +201,6 @@ class DashboardGridInner extends Component<
};
}
- componentDidMount() {
- // In order to skip the initial cards animation we must let the grid layout calculate
- // the initial card positions. The timer is necessary to enable animation only
- // after the grid layout has been calculated and applied to the DOM.
- this._pauseAnimationTimer = setTimeout(() => {
- this.setState({ isAnimationPaused: false });
- }, 0);
- }
-
- componentWillUnmount() {
- if (this._pauseAnimationTimer !== null) {
- clearTimeout(this._pauseAnimationTimer);
- }
- }
-
componentDidUpdate(prevProps: DashboardGridInnerProps) {
if (prevProps.dashboard.dashcards !== this.props.dashboard.dashcards) {
this.setState({
@@ -615,7 +596,6 @@ class DashboardGridInner extends Component<
S.DashboardCardContainer,
{
[DashboardS.BrandColorResizeHandle]: shouldChangeResizeHandle,
- [S.isAnimationDisabled]: this.state.isAnimationPaused,
},
)}
>
diff --git a/frontend/src/metabase/dashboard/components/grid/GridLayout.module.css b/frontend/src/metabase/dashboard/components/grid/GridLayout.module.css
new file mode 100644
index 00000000000..fdd2d3107a6
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/grid/GridLayout.module.css
@@ -0,0 +1,8 @@
+/*
+ * A state override: transitions must stay off whatever react-grid-layout's
+ * stylesheet, or the dashcards' reduced-motion rule, would otherwise set.
+ */
+.withoutTransitions,
+.withoutTransitions :global(.react-grid-item) {
+ transition: none !important;
+}
diff --git a/frontend/src/metabase/dashboard/components/grid/GridLayout.tsx b/frontend/src/metabase/dashboard/components/grid/GridLayout.tsx
index a7ebc07f24f..d130e7ec030 100644
--- a/frontend/src/metabase/dashboard/components/grid/GridLayout.tsx
+++ b/frontend/src/metabase/dashboard/components/grid/GridLayout.tsx
@@ -1,12 +1,15 @@
+import cx from "classnames";
import { useCallback, useMemo, useState } from "react";
import {
type ItemCallback,
Responsive as ReactGridLayout,
} from "react-grid-layout";
+import { useHasPaintedSinceMount } from "metabase/common/hooks/use-has-painted-since-mount";
import { useMantineTheme } from "metabase/ui";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";
+import S from "./GridLayout.module.css";
import { generateGridBackground } from "./utils";
// We need to omit onLayoutChange and margin from the props of ReactGridLayout
@@ -79,10 +82,18 @@ export function GridLayout<T extends { id: number | null }>(
rowHeight,
isEditing,
onLayoutChange,
+ className,
...otherProps
} = props;
const theme = useMantineTheme();
+ // Cards only animate while editing, where the motion shows where a dragged
+ // or resized card lands. Even then, wait for a paint after mount:
+ // react-grid-layout swaps top/left positioning for CSS transforms right after
+ // mounting, and animating that swap slides every card in from the top-left.
+ const hasPaintedSinceMount = useHasPaintedSinceMount();
+ const areTransitionsEnabled = isEditing && hasPaintedSinceMount;
+
const [currentBreakpoint, setCurrentBreakpoint] = useState(
// Unjustified type cast. FIXME
(ReactGridLayout as any).utils.getBreakpointFromWidth(
@@ -233,6 +244,9 @@ export function GridLayout<T extends { id: number | null }>(
isDraggable={isEditing && !isMobile}
isResizable={isEditing && !isMobile}
{...otherProps}
+ className={cx(className, {
+ [S.withoutTransitions]: !areTransitionsEnabled,
+ })}
autoSize={false}
onLayoutChange={onLayoutChangeWrapped}
onBreakpointChange={onBreakpointChange}
diff --git a/frontend/src/metabase/dashboard/components/grid/GridLayout.unit.spec.tsx b/frontend/src/metabase/dashboard/components/grid/GridLayout.unit.spec.tsx
index ece567bbaa8..3e7a5efeaa6 100644
--- a/frontend/src/metabase/dashboard/components/grid/GridLayout.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/grid/GridLayout.unit.spec.tsx
@@ -1,4 +1,4 @@
-import { screen } from "@testing-library/react";
+import { act, screen } from "@testing-library/react";
import type { ComponentProps } from "react";
import { renderWithProviders } from "__support__/ui";
@@ -6,6 +6,10 @@ import { ThemeProvider } from "metabase/ui";
import { GridLayout } from "./GridLayout";
+jest.mock("./GridLayout.module.css", () => ({
+ withoutTransitions: "withoutTransitions",
+}));
+
// Sample items for testing
const testItems = [
{ id: 1, name: "Item 1" },
@@ -50,6 +54,21 @@ const defaultProps = {
rowHeight: 100,
} as ComponentProps<typeof GridLayout>;
+function setup(props: Partial<ComponentProps<typeof GridLayout>> = {}) {
+ renderWithProviders(
+ <ThemeProvider>
+ <GridLayout {...defaultProps} {...props} />
+ </ThemeProvider>,
+ );
+
+ // eslint-disable-next-line testing-library/no-node-access -- react-grid-layout doesn't forward test ids to its root
+ const grid = screen.getByTestId("item-1").parentElement;
+ return { grid };
+}
+
+// Enough for the two animation frames GridLayout waits for after mounting
+const waitForPaint = () => act(() => jest.advanceTimersByTime(100));
+
describe("GridLayout", () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -80,4 +99,28 @@ describe("GridLayout", () => {
expect(screen.getByTestId("item-1")).toBeInTheDocument();
expect(screen.getByTestId("item-2")).toBeInTheDocument();
});
+
+ describe("card transitions", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ test("are disabled outside of edit mode", () => {
+ const { grid } = setup({ isEditing: false });
+ waitForPaint();
+ expect(grid).toHaveClass("withoutTransitions");
+ });
+
+ test("are disabled in edit mode until the grid has painted after mounting", () => {
+ const { grid } = setup({ isEditing: true });
+ expect(grid).toHaveClass("withoutTransitions");
+
+ waitForPaint();
+ expect(grid).not.toHaveClass("withoutTransitions");
+ });
+ });
});