Skip to content

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

Pause toast auto-dismiss while hovered or focused (#82957)

Will Fry44f2da8e70f3
diff --git a/frontend/src/metabase/common/components/UndoListing.module.css b/frontend/src/metabase/common/components/UndoListing.module.css
index 8bae1c19ba3..2aa9443df8a 100644
--- a/frontend/src/metabase/common/components/UndoListing.module.css
+++ b/frontend/src/metabase/common/components/UndoListing.module.css
@@ -27,7 +27,7 @@
transform-origin: left;
}
-.toast:hover .progress {
+.toast[data-paused] .progress {
animation-play-state: paused;
}
diff --git a/frontend/src/metabase/common/components/UndoListing.tsx b/frontend/src/metabase/common/components/UndoListing.tsx
index a647bffa874..cd35f282b4a 100644
--- a/frontend/src/metabase/common/components/UndoListing.tsx
+++ b/frontend/src/metabase/common/components/UndoListing.tsx
@@ -1,5 +1,6 @@
import {
type CSSProperties,
+ type FocusEvent,
Fragment,
type ReactNode,
useEffect,
@@ -71,16 +72,45 @@ function UndoToast({
style: CSSProperties;
}) {
const dispatch = useDispatch();
+ const interaction = useRef({ isHovered: false, isFocused: false });
+ const hasTimer = Boolean(undo.timeout);
- const handleMouseEnter = () => {
- if (undo.showProgress) {
+ const updateInteraction = (
+ change: Partial<{ isHovered: boolean; isFocused: boolean }>,
+ ) => {
+ const wasInteracting =
+ interaction.current.isHovered || interaction.current.isFocused;
+ interaction.current = { ...interaction.current, ...change };
+ const isInteracting =
+ interaction.current.isHovered || interaction.current.isFocused;
+
+ if (!hasTimer || wasInteracting === isInteracting) {
+ return;
+ }
+ dispatch(isInteracting ? pauseUndo(undo) : resumeUndo(undo.id));
+ };
+
+ // handle the case where a hovered toast with no timer changes
+ // to one with a timer - pause it.
+ useEffect(() => {
+ const { isHovered, isFocused } = interaction.current;
+ if ((isHovered || isFocused) && hasTimer && undo.pausedAt == null) {
dispatch(pauseUndo(undo));
}
+ }, [undo, hasTimer, dispatch]);
+
+ const handleBlur = (event: FocusEvent<HTMLDivElement>) => {
+ const isFocusStillInside =
+ event.relatedTarget instanceof Node &&
+ event.currentTarget.contains(event.relatedTarget);
+ if (!isFocusStillInside) {
+ updateInteraction({ isFocused: false });
+ }
};
- const handleMouseLeave = () => {
- if (undo.showProgress) {
- dispatch(resumeUndo(undo));
+ const handleFocus = (event: FocusEvent<HTMLDivElement>) => {
+ if (event.target.matches(":focus-visible")) {
+ updateInteraction({ isFocused: true });
}
};
@@ -94,8 +124,11 @@ function UndoToast({
color={undo.toastColor}
role="status"
className={S.toast}
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
+ data-paused={undo.pausedAt != null || undefined}
+ onMouseEnter={() => updateInteraction({ isHovered: true })}
+ onMouseLeave={() => updateInteraction({ isHovered: false })}
+ onFocus={handleFocus}
+ onBlur={handleBlur}
bg={dark ? "background_page-primary-inverse" : "background_page-primary"}
c={dark ? "text-secondary-inverse" : "text-primary"}
withBorder={!noBorder}
diff --git a/frontend/src/metabase/common/components/UndoListing.unit.spec.tsx b/frontend/src/metabase/common/components/UndoListing.unit.spec.tsx
index 03894ca3251..305417ad342 100644
--- a/frontend/src/metabase/common/components/UndoListing.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/UndoListing.unit.spec.tsx
@@ -1,36 +1,31 @@
+import type { Store } from "@reduxjs/toolkit";
import userEvent from "@testing-library/user-event";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { State } from "metabase/redux/store";
import type { Undo } from "metabase/redux/store/undo";
+import { addUndo, dismissUndo } from "metabase/redux/undo";
import { UndoListing } from "./UndoListing";
-type UndoOverride = Partial<Omit<Undo, "id" | "_domId">>;
-
-function makeUndo(override: UndoOverride = {}, id = 0): Undo {
- return {
- icon: null,
- message:
- "Auto-connect this filter to all questions containing “Product.Title”, in the current tab?",
- timeout: 12000,
- timeoutId: null,
- canDismiss: true,
- id,
- _domId: id,
- ...override,
- };
-}
+type UndoOverride = Partial<Omit<Undo, "_domId">>;
async function setup(undo: Undo) {
- renderWithProviders(<UndoListing />, {
+ jest.useFakeTimers();
+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
+ const { store } = renderWithProviders(<UndoListing />, {
storeInitialState: {
undo: [undo],
},
});
await screen.findByRole("status");
+
+ return { user, store };
}
+afterEach(() => jest.useRealTimers());
+
describe("UndoListing", () => {
it("renders list of Undo toasts", async () => {
await setup(makeUndo());
@@ -73,9 +68,9 @@ describe("UndoListing", () => {
it("performs the undo action and dismisses the toast when clicked", async () => {
const action = jest.fn();
- await setup(makeUndo({ actions: [action] }));
+ const { user } = await setup(makeUndo({ actions: [action] }));
- await userEvent.click(screen.getByRole("button", { name: "Undo" }));
+ await user.click(screen.getByRole("button", { name: "Undo" }));
await waitFor(() => {
expect(action).toHaveBeenCalled();
@@ -85,17 +80,170 @@ describe("UndoListing", () => {
it("performs and dismisses the toast when the extra action is clicked", async () => {
const action = jest.fn();
- await setup(
+ const { user } = await setup(
makeUndo({
extraAction: { label: "See all", action },
}),
);
- await userEvent.click(screen.getByRole("button", { name: "See all" }));
+ await user.click(screen.getByRole("button", { name: "See all" }));
await waitFor(() => {
expect(action).toHaveBeenCalled();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
});
});
+
+ describe("auto-dismiss", () => {
+ const TIMEOUT = 5000;
+
+ // a dismissed toast stays mounted until its exit transition finishes,
+ // so settle it before asserting either way
+ async function expectDismissed() {
+ await tick(1000);
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ }
+
+ async function expectStillOpen() {
+ await tick(1000);
+ expect(screen.getByRole("status")).toBeInTheDocument();
+ }
+
+ async function setupTimed(undo: Partial<Undo> = {}) {
+ jest.useFakeTimers();
+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
+ const { store } = renderWithProviders(<UndoListing />);
+
+ await act(async () => {
+ store.dispatch(addUndo({ message: "Saved", ...undo }));
+ });
+ // let the toast's enter transition start
+ await tick(10);
+ expect(screen.getByRole("status")).toBeInTheDocument();
+
+ return { user };
+ }
+
+ it("dismisses the toast after the default timeout", async () => {
+ await setupTimed();
+
+ await tick(TIMEOUT);
+
+ await expectDismissed();
+ });
+
+ it.each([{ showProgress: false }, { showProgress: true }])(
+ "keeps the toast open while hovered (%o)",
+ async (undo) => {
+ const { user } = await setupTimed(undo);
+
+ await user.hover(screen.getByRole("status"));
+ await tick(TIMEOUT * 2);
+ await expectStillOpen();
+
+ await user.unhover(screen.getByRole("status"));
+ await tick(TIMEOUT);
+ await expectDismissed();
+ },
+ );
+
+ it("keeps the toast open while it has keyboard focus", async () => {
+ const { user } = await setupTimed({ actions: [jest.fn()] });
+
+ await user.tab();
+ expect(screen.getByRole("button", { name: "Undo" })).toHaveFocus();
+ await tick(TIMEOUT * 2);
+ await expectStillOpen();
+
+ await user.tab();
+ await tick(TIMEOUT);
+ await expectDismissed();
+ });
+
+ it("stays paused when the pointer leaves while it still has focus", async () => {
+ const { user } = await setupTimed({ actions: [jest.fn()] });
+
+ await user.hover(screen.getByRole("status"));
+ await user.tab();
+ await user.unhover(screen.getByRole("status"));
+ await tick(TIMEOUT * 2);
+
+ await expectStillOpen();
+ });
+
+ it("toast replaced under same id while hovered stays open", async () => {
+ const { user, store } = await setup(
+ makeUndo({ id: "paste", timeout: null, message: "Saving" }),
+ );
+ await user.hover(screen.getByRole("status"));
+
+ await act(async () => {
+ store.dispatch(addUndo({ id: "paste", message: "Saved" }));
+ });
+ await tick(7000);
+ expect(undosInStore(store)).toEqual(["paste:Saved"]);
+ });
+
+ it("unhovering a replaced toast does not dismiss it immediately", async () => {
+ const { user, store } = await setup(
+ makeUndo({ id: "paste", timeout: null, message: "Saving" }),
+ );
+
+ await user.hover(screen.getByRole("status"));
+ await act(async () => {
+ store.dispatch(addUndo({ id: "paste", message: "Saved" }));
+ });
+ await tick(1000);
+ await user.unhover(screen.getByRole("status"));
+ await tick(100);
+ expect(undosInStore(store)).toEqual(["paste:Saved"]);
+ });
+
+ it("unhovering an exiting toast does not dismiss a later toast with the same id", async () => {
+ const { user, store } = await setup(
+ makeUndo({ id: "paste", message: "Saved", startedAt: Date.now() }),
+ );
+
+ await user.hover(screen.getByRole("status"));
+ await tick(1000);
+ await act(async () => {
+ store.dispatch(dismissUndo({ undoId: "paste" }));
+ });
+ await tick(10);
+ await user.unhover(screen.getByRole("status"));
+ await tick(1000);
+ await act(async () => {
+ store.dispatch(
+ addUndo({ id: "paste", timeout: null, message: "Saving again" }),
+ );
+ });
+ await tick(15000);
+ expect(undosInStore(store)).toEqual(["paste:Saving again"]);
+ });
+ });
});
+
+function makeUndo(override: UndoOverride = {}): Undo {
+ const id = override.id ?? 0;
+ return {
+ icon: null,
+ message:
+ "Auto-connect this filter to all questions containing “Product.Title”, in the current tab?",
+ timeout: 12000,
+ timeoutId: null,
+ canDismiss: true,
+ id,
+ _domId: id,
+ ...override,
+ };
+}
+
+function tick(ms: number) {
+ return act(async () => {
+ jest.advanceTimersByTime(ms);
+ });
+}
+
+function undosInStore(store: Store<State>) {
+ return store.getState().undo.map((undo) => `${undo.id}:${undo.message}`);
+}
diff --git a/frontend/src/metabase/redux/undo.ts b/frontend/src/metabase/redux/undo.ts
index 10e93e16a8e..15e455a49b6 100644
--- a/frontend/src/metabase/redux/undo.ts
+++ b/frontend/src/metabase/redux/undo.ts
@@ -39,6 +39,7 @@ export const addUndo = createThunkAction(ADD_UNDO, (undo: Partial<Undo>) => {
ref: createRef(),
icon,
canDismiss,
+ timeout,
timeoutId,
startedAt: Date.now(),
};
@@ -53,21 +54,34 @@ export const pauseUndo = createAction(PAUSE_UNDO, (undo: Undo) => {
});
const RESUME_UNDO = "metabase/questions/RESUME_UNDO";
-export const resumeUndo = createThunkAction(RESUME_UNDO, (undo) => {
- const restTime = undo.timeout - (undo.pausedAt - undo.startedAt);
+export const resumeUndo = createThunkAction(
+ RESUME_UNDO,
+ (undoId: Undo["id"]) => {
+ return (dispatch, getState) => {
+ // The undo may already be gone, e.g. a toast still animating out after
+ // being dismissed, in which case there's nothing to resume.
+ const current = getUndo(getState(), undoId);
+ if (
+ !current?.timeout ||
+ current.pausedAt == null ||
+ current.startedAt == null
+ ) {
+ return undoId;
+ }
- return (dispatch) => {
- return {
- ...undo,
- pausedAt: null,
- timeoutId: setTimeout(
- () => dispatch(dismissUndo({ undoId: undo.id })),
- restTime,
- ),
- timeout: restTime,
+ const restTime = current.timeout - (current.pausedAt - current.startedAt);
+ return {
+ ...current,
+ pausedAt: null,
+ timeoutId: setTimeout(
+ () => dispatch(dismissUndo({ undoId: current.id })),
+ restTime,
+ ),
+ timeout: restTime,
+ };
};
- };
-});
+ },
+);
function getUndo(state: State, undoId: Undo["id"]) {
return _.findWhere(state.undo, { id: undoId });
@@ -201,7 +215,7 @@ export function undoReducer(
}
return state.map((undo) => {
- if (undo.id === payload.id) {
+ if (undo.id === payload.id && undo.pausedAt == null) {
return {
...undo,
pausedAt: Date.now(),
diff --git a/frontend/src/metabase/redux/undo.unit.spec.ts b/frontend/src/metabase/redux/undo.unit.spec.ts
index 3f695cf4ad5..c5e29fa0a77 100644
--- a/frontend/src/metabase/redux/undo.unit.spec.ts
+++ b/frontend/src/metabase/redux/undo.unit.spec.ts
@@ -117,7 +117,7 @@ describe("metabase/redux/undo", () => {
expect(store.getState().undo.length).toBe(1);
// resume undo (e.g. when mouse left toast)
- store.dispatch(resumeUndo(store.getState().undo[0]));
+ store.dispatch(resumeUndo(store.getState().undo[0].id));
await act(async () => {
jest.advanceTimersByTime(timeShiftResumed1);