Skip to content

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

Prefetch queries from Exploration toolbar navigation (#79615)

Kevin Kelleher0fc5582ae250
diff --git a/e2e/test/scenarios/explorations/explorations.cy.spec.ts b/e2e/test/scenarios/explorations/explorations.cy.spec.ts
index 24dbf75d640..d943c48b03d 100644
--- a/e2e/test/scenarios/explorations/explorations.cy.spec.ts
+++ b/e2e/test/scenarios/explorations/explorations.cy.spec.ts
@@ -727,7 +727,7 @@ describe("scenarios > explorations > sidebar triage", () => {
);
});
- it("hides pages from the toolbar and group menus, reveals them via Show hidden items, and keeps Initial investigation when everything is hidden", () => {
+ it("hides pages from the toolbar and group menus and reveals them via Show hidden items", () => {
createTwoPageExploration("Sidebar hide fixture").then(
({ explorationId, metricName, pageNames }) => {
cy.intercept("PUT", "/api/exploration/pages/hidden").as(
@@ -751,7 +751,6 @@ describe("scenarios > explorations > sidebar triage", () => {
)!;
cy.log("Triage arrows step between pages");
- cy.findByRole("button", { name: "Previous" }).should("be.disabled");
cy.findByRole("button", { name: "Next" }).click();
selectedRows().should("contain.text", secondPageName);
cy.findByRole("button", { name: "Previous" }).click();
diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsx
index bfc5027c417..b1a53d86eba 100644
--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsx
+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsx
@@ -1,8 +1,7 @@
import cx from "classnames";
-import { useCallback, useEffect, useMemo } from "react";
+import { useEffect, useMemo } from "react";
import { t } from "ttag";
-import { explorationApi } from "metabase/api/exploration";
import { Tree, useTree } from "metabase/common/components/tree";
import type { ITreeNodeItem } from "metabase/common/components/tree/types";
import { getInitialExpandedIds } from "metabase/common/components/tree/utils";
@@ -54,7 +53,6 @@ interface ExplorationSidebarProps {
getSelectedSidebarTabUrl: (tab: ExplorationSidebarTab) => string;
tree: ITreeNodeItem<ExplorationTreeNodeDataType>[];
selectedPageId: ExplorationPageNodeId | null;
- setSelectedPageId: (pageId: ExplorationPageNodeId) => void;
getSelectedPageUrl: (pageId: ExplorationPageNodeId) => string;
shouldScrollSelectionRef: React.MutableRefObject<boolean>;
isOpen: boolean;
@@ -64,6 +62,9 @@ interface ExplorationSidebarProps {
sortOrder: ExplorationSortOrder;
onChangeSortOrder: (sortOrder: ExplorationSortOrder) => void;
contentMode: ExplorationSidebarContentMode;
+ onPreviousPage: () => void;
+ onNextPage: () => void;
+ onPrefetchPage: (pageId: ExplorationPageNodeId) => void;
}
export function ExplorationSidebar({
@@ -73,7 +74,6 @@ export function ExplorationSidebar({
getSelectedSidebarTabUrl,
tree,
selectedPageId,
- setSelectedPageId,
getSelectedPageUrl,
shouldScrollSelectionRef,
isOpen,
@@ -83,6 +83,9 @@ export function ExplorationSidebar({
sortOrder,
onChangeSortOrder,
contentMode,
+ onPreviousPage,
+ onNextPage,
+ onPrefetchPage,
}: ExplorationSidebarProps) {
const navigate = useNavigate();
const treeController = useTree({
@@ -93,25 +96,6 @@ export function ExplorationSidebar({
const flatItems = useMemo(() => flattenTree(tree), [tree]);
- const prefetchQueryResult = explorationApi.usePrefetch(
- "getExplorationQueryResult",
- );
-
- const handlePrefetch = useCallback(
- (item: ITreeNodeItem<ExplorationTreeNodeDataType>) => {
- if (item.data?.type !== "page") {
- return;
- }
- const queries = item.data.queries;
- for (const query of queries) {
- if (query.status === "done") {
- prefetchQueryResult(query.id);
- }
- }
- },
- [prefetchQueryResult],
- );
-
// `collapse` is stable, but treeController is not
// so we need to be careful to prevent this effect from running on every render
// eslint complains when passing `treeController.collapse` to `useEffect` deps
@@ -143,29 +127,25 @@ export function ExplorationSidebar({
}
const direction = event.key === "ArrowRight" ? 1 : -1;
const nextItem = getAdjacentById(flatItems, selectedPageId, direction);
- if (nextItem != null && nextItem.id !== selectedPageId) {
- if (nextItem.data?.type !== "page") {
- return;
- }
- setSelectedPageId(nextItem.data.page_id);
- trackExplorationVisualizationChanged(exploration.id, "keyboard");
- event.preventDefault();
- shouldScrollSelectionRef.current = true;
- setExpandedIds(
- (prev) =>
- new Set([...prev, ...getInitialExpandedIds(nextItem.id, tree)]),
- );
- // prefetch the following item
- // if the user uses a keyboard shortcut once, they're likely to use it again
- const followingItem = getAdjacentById(
- flatItems,
- nextItem.id,
- direction,
- );
- if (followingItem != null) {
- handlePrefetch(followingItem);
- }
+ if (
+ nextItem == null ||
+ nextItem.id === selectedPageId ||
+ nextItem.data?.type !== "page"
+ ) {
+ return;
+ }
+ if (direction === 1) {
+ onNextPage();
+ } else {
+ onPreviousPage();
}
+ trackExplorationVisualizationChanged(exploration.id, "keyboard");
+ event.preventDefault();
+ shouldScrollSelectionRef.current = true;
+ setExpandedIds(
+ (prev) =>
+ new Set([...prev, ...getInitialExpandedIds(nextItem.id, tree)]),
+ );
// if we moved into a different folder, collapse the previous folder
const currentItem = flatItems.find((item) => item.id === selectedPageId);
if (
@@ -181,9 +161,9 @@ export function ExplorationSidebar({
flatItems,
tree,
selectedPageId,
- setSelectedPageId,
+ onPreviousPage,
+ onNextPage,
setExpandedIds,
- handlePrefetch,
collapse,
exploration.id,
shouldScrollSelectionRef,
@@ -193,7 +173,7 @@ export function ExplorationSidebar({
() => ({
explorationId: exploration.id,
canWrite: exploration.can_write,
- handlePrefetch,
+ onPrefetchPage,
shouldScrollSelectionRef,
getSelectedPageUrl,
readPageIds,
@@ -201,7 +181,7 @@ export function ExplorationSidebar({
[
exploration.id,
exploration.can_write,
- handlePrefetch,
+ onPrefetchPage,
shouldScrollSelectionRef,
getSelectedPageUrl,
readPageIds,
diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsx
index 5d05a6d8d01..23341707dd2 100644
--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsx
+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsx
@@ -46,14 +46,14 @@ describe("ExplorationSidebar", () => {
describe("keyboard navigation", () => {
it("moves selection to the next page with ArrowRight", () => {
- const { setSelectedPageId } = setup({
+ const { onNextPage } = setup({
queries: [doneQuery, errorQuery],
selectedQueryId: 2,
});
fireEvent.keyDown(document.body, { key: "ArrowRight" });
- expect(setSelectedPageId).toHaveBeenCalledWith("3");
+ expect(onNextPage).toHaveBeenCalledTimes(1);
expect(trackExplorationVisualizationChanged).toHaveBeenCalledWith(
expect.any(Number),
"keyboard",
@@ -61,14 +61,14 @@ describe("ExplorationSidebar", () => {
});
it("moves selection to the previous page with ArrowLeft", () => {
- const { setSelectedPageId } = setup({
+ const { onPreviousPage } = setup({
queries: [doneQuery, errorQuery],
selectedQueryId: 3,
});
fireEvent.keyDown(document.body, { key: "ArrowLeft" });
- expect(setSelectedPageId).toHaveBeenCalledWith("2");
+ expect(onPreviousPage).toHaveBeenCalledTimes(1);
});
});
@@ -158,7 +158,6 @@ describe("ExplorationSidebar", () => {
getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}
tree={tree}
selectedPageId="2"
- setSelectedPageId={jest.fn()}
getSelectedPageUrl={(pageId) => `${path}/page/${pageId}`}
shouldScrollSelectionRef={{ current: false }}
isOpen
@@ -168,6 +167,9 @@ describe("ExplorationSidebar", () => {
sortOrder={DEFAULT_SORT_ORDER}
onChangeSortOrder={jest.fn()}
contentMode="tree"
+ onPreviousPage={jest.fn()}
+ onNextPage={jest.fn()}
+ onPrefetchPage={jest.fn()}
/>
</>
);
@@ -219,7 +221,7 @@ describe("ExplorationSidebar", () => {
});
it("toggles show-hidden from the menu without changing selection", async () => {
- const { onToggleShowHidden, setSelectedPageId } = setup({
+ const { onToggleShowHidden, onNextPage, onPreviousPage } = setup({
queries: [doneQuery],
});
await userEvent.click(filterButton());
@@ -228,7 +230,8 @@ describe("ExplorationSidebar", () => {
);
expect(onToggleShowHidden).toHaveBeenCalledTimes(1);
// toggling the filter must not navigate/select anything
- expect(setSelectedPageId).not.toHaveBeenCalled();
+ expect(onNextPage).not.toHaveBeenCalled();
+ expect(onPreviousPage).not.toHaveBeenCalled();
});
it("changes sort order from the menu", async () => {
@@ -517,7 +520,6 @@ describe("ExplorationSidebar", () => {
getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}
tree={tree}
selectedPageId={String(REVENUE_PAGE_ID)}
- setSelectedPageId={jest.fn()}
getSelectedPageUrl={() => path}
shouldScrollSelectionRef={shouldScrollSelectionRef}
isOpen
@@ -527,6 +529,9 @@ describe("ExplorationSidebar", () => {
sortOrder={DEFAULT_SORT_ORDER}
onChangeSortOrder={jest.fn()}
contentMode="tree"
+ onPreviousPage={jest.fn()}
+ onNextPage={jest.fn()}
+ onPrefetchPage={jest.fn()}
/>
);
@@ -624,7 +629,6 @@ describe("ExplorationSidebar", () => {
getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}
tree={tree}
selectedPageId={selectedId}
- setSelectedPageId={jest.fn()}
getSelectedPageUrl={() => path}
shouldScrollSelectionRef={shouldScrollSelectionRef}
isOpen
@@ -634,6 +638,9 @@ describe("ExplorationSidebar", () => {
sortOrder={DEFAULT_SORT_ORDER}
onChangeSortOrder={jest.fn()}
contentMode="tree"
+ onNextPage={jest.fn()}
+ onPreviousPage={jest.fn()}
+ onPrefetchPage={jest.fn()}
/>
);
// Drive updates through in-component state so the sidebar stays mounted
@@ -987,7 +994,7 @@ describe("ExplorationSidebar", () => {
describe("arrow-key navigation", () => {
it("Right moves selection from one page to the next within the same heading and keeps that heading expanded", () => {
- const { setSelectedPageId } = setup({
+ const { onNextPage } = setup({
queries: [...planQueries, ...regionQueries],
blocks,
selectedPageId: planLeafAllId,
@@ -995,7 +1002,7 @@ describe("ExplorationSidebar", () => {
fireEvent.keyDown(document.body, { key: "ArrowRight" });
- expect(setSelectedPageId).toHaveBeenLastCalledWith(planLeafUsId);
+ expect(onNextPage).toHaveBeenCalledTimes(1);
// Region heading stayed closed; we never left the plan heading.
const regionHeading = screen.getByRole("group", {
name: /Revenue by region/,
@@ -1004,7 +1011,7 @@ describe("ExplorationSidebar", () => {
});
it("Right past the last page in a heading selects the first page of the next heading and collapses the source heading", () => {
- const { setSelectedPageId } = setup({
+ const { onNextPage } = setup({
queries: [...planQueries, ...regionQueries],
blocks,
// Selection sits on the LAST page of the plan heading.
@@ -1013,13 +1020,13 @@ describe("ExplorationSidebar", () => {
fireEvent.keyDown(document.body, { key: "ArrowRight" });
- expect(setSelectedPageId).toHaveBeenLastCalledWith(regionLeafAllId);
+ expect(onNextPage).toHaveBeenCalledTimes(1);
// The keyboard handler imperatively collapses the source
// heading via `treeController.collapse`. Auto-expanding the
// target heading happens via `getInitialExpandedIds` on the
// next render — that's a parent-side effect we don't model
- // here (the `setSelectedPageId` is a mock so the controlled
+ // here (onNextPage is a mock so the controlled
// `selectedPageId` prop never updates).
const planHeading = screen.getByRole("group", {
name: /Revenue by plan/,
@@ -1028,7 +1035,7 @@ describe("ExplorationSidebar", () => {
});
it("Left past the first page in a heading selects the last page of the previous heading and collapses the source heading", () => {
- const { setSelectedPageId } = setup({
+ const { onPreviousPage } = setup({
queries: [...planQueries, ...regionQueries],
blocks,
selectedPageId: regionLeafAllId,
@@ -1036,7 +1043,7 @@ describe("ExplorationSidebar", () => {
fireEvent.keyDown(document.body, { key: "ArrowLeft" });
- expect(setSelectedPageId).toHaveBeenLastCalledWith(planLeafUsId);
+ expect(onPreviousPage).toHaveBeenCalledTimes(1);
const regionHeading = screen.getByRole("group", {
name: /Revenue by region/,
@@ -1051,7 +1058,7 @@ describe("ExplorationSidebar", () => {
];
const PAGE_BLOCK_ID = 60;
const PAGE_LEAF_ID = 600;
- const { setSelectedPageId } = setup({
+ const { onNextPage } = setup({
queries: [...planQueries, ...pageQueriesNav],
blocks: [
blocks[0], // plan block + its two single-query pages
@@ -1076,9 +1083,7 @@ describe("ExplorationSidebar", () => {
fireEvent.keyDown(document.body, { key: "ArrowRight" });
- expect(setSelectedPageId).toHaveBeenLastCalledWith(
- String(PAGE_LEAF_ID),
- );
+ expect(onNextPage).toHaveBeenCalledTimes(1);
const planHeading = screen.getByRole("group", {
name: /Revenue by plan/,
});
@@ -1151,7 +1156,6 @@ describe("ExplorationSidebar", () => {
getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}
tree={tree}
selectedPageId={String(PAGE_ID)}
- setSelectedPageId={jest.fn()}
getSelectedPageUrl={() => path}
shouldScrollSelectionRef={shouldScrollSelectionRef}
isOpen
@@ -1161,6 +1165,9 @@ describe("ExplorationSidebar", () => {
sortOrder={DEFAULT_SORT_ORDER}
onChangeSortOrder={jest.fn()}
contentMode="tree"
+ onPreviousPage={jest.fn()}
+ onNextPage={jest.fn()}
+ onPrefetchPage={jest.fn()}
/>
</>
);
diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsx
index 5d9cc7853e1..79d03a9f55e 100644
--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsx
+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsx
@@ -69,7 +69,7 @@ const HEADING_ICON: Record<
export interface ExplorationTreeContextValue {
explorationId: ExplorationId;
canWrite: boolean;
- handlePrefetch: (item: ITreeNodeItem<ExplorationTreeNode>) => void;
+ onPrefetchPage: (pageId: ExplorationPageNodeId) => void;
shouldScrollSelectionRef: React.MutableRefObject<boolean>;
getSelectedPageUrl: (pageId: ExplorationPageNodeId) => string;
readPageIds: ReadonlySet<string>;
@@ -357,7 +357,7 @@ function ExplorationTreeItem({
isSelected,
depth,
explorationId,
- handlePrefetch,
+ onPrefetchPage,
shouldScrollSelectionRef,
getSelectedPageUrl,
readPageIds,
@@ -407,7 +407,7 @@ function ExplorationTreeItem({
[S.treeRowSelected]: isSelected,
[S.treeRowNested]: depth > 0,
})}
- onMouseEnter={() => handlePrefetch(item)}
+ onMouseEnter={() => onPrefetchPage(pageId)}
onClick={handleClick}
// custom css var used for tree styles
style={{ "--tree-depth": depth } as React.CSSProperties}
diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsx
index 5864a37276c..e2eaa3d49b3 100644
--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsx
+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsx
@@ -807,7 +807,6 @@ describe("ExplorationTreeNode", () => {
getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}
tree={getTree()}
selectedPageId={String(PAGE_ID)}
- setSelectedPageId={jest.fn()}
getSelectedPageUrl={() => path}
shouldScrollSelectionRef={shouldScrollSelectionRef}
isOpen
@@ -817,6 +816,9 @@ describe("ExplorationTreeNode", () => {
sortOrder={DEFAULT_SORT_ORDER}
onChangeSortOrder={jest.fn()}
contentMode="tree"
+ onPreviousPage={jest.fn()}
+ onNextPage={jest.fn()}
+ onPrefetchPage={jest.fn()}
/>
}
/>,
diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsx
index c2222fccc20..596dbf308cd 100644
--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsx
+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsx
@@ -92,7 +92,9 @@ export function setup({
readPageIds = new Set<string>(),
tab = "all",
}: SetupOpts) {
- const setSelectedPageId = jest.fn();
+ const onPreviousPage = jest.fn();
+ const onNextPage = jest.fn();
+ const onPrefetchPage = jest.fn();
const onToggleShowHidden = jest.fn();
const onChangeSortOrder = jest.fn();
@@ -156,7 +158,6 @@ export function setup({
getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}
tree={displayTree}
selectedPageId={resolvedPageId}
- setSelectedPageId={setSelectedPageId}
getSelectedPageUrl={getSelectedPageUrl}
shouldScrollSelectionRef={{ current: true }}
isOpen
@@ -166,6 +167,9 @@ export function setup({
sortOrder={sortOrder}
onChangeSortOrder={onChangeSortOrder}
contentMode={contentMode}
+ onPreviousPage={onPreviousPage}
+ onNextPage={onNextPage}
+ onPrefetchPage={onPrefetchPage}
/>
);
@@ -174,7 +178,9 @@ export function setup({
initialRoute: explorationPath,
});
return {
- setSelectedPageId,
+ onPreviousPage,
+ onNextPage,
+ onPrefetchPage,
onToggleShowHidden,
onChangeSortOrder,
getSelectedPageUrl,
diff --git a/frontend/src/metabase/explorations/pages/ExplorationPage.tsx b/frontend/src/metabase/explorations/pages/ExplorationPage.tsx
index feafedf4436..46bd3dbc107 100644
--- a/frontend/src/metabase/explorations/pages/ExplorationPage.tsx
+++ b/frontend/src/metabase/explorations/pages/ExplorationPage.tsx
@@ -7,6 +7,7 @@ import {
useListCommentsQuery,
useListTimelinesQuery,
} from "metabase/api";
+import { explorationApi } from "metabase/api/exploration";
import { getListCommentsQuery } from "metabase/comments/utils";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useToast } from "metabase/common/hooks";
@@ -57,6 +58,8 @@ import {
type ExplorationSidebarTab,
isExplorationSidebarTab,
} from "../types";
+import { getAdjacentById } from "../utils";
+
const QUERY_POLL_INTERVAL_MS = 2000;
const TIMELINE_QUERY_PARAM = "timeline";
@@ -310,31 +313,109 @@ function ExplorationPageForId() {
return pickInitialSidebarPage(tree);
}, [params.pageId, tree]);
- const orderedPageIds = useMemo(
+ const pageIdToPageAndQueries: Map<
+ ExplorationPageNodeId,
+ {
+ page: ExplorationPageNode;
+ thread: ExplorationThread;
+ queries: ExplorationQuery[];
+ block: ExplorationBlockNode;
+ }
+ > = useMemo(() => {
+ const map = new Map<
+ ExplorationPageNodeId,
+ {
+ page: ExplorationPageNode;
+ thread: ExplorationThread;
+ queries: ExplorationQuery[];
+ block: ExplorationBlockNode;
+ }
+ >();
+ for (const thread of exploration?.threads ?? []) {
+ const queriesById = new Map((thread.queries ?? []).map((q) => [q.id, q]));
+ for (const block of thread.blocks ?? []) {
+ for (const page of block.pages) {
+ const queries = page.query_ids
+ .map((id) => queriesById.get(id))
+ .filter((q): q is ExplorationQuery => q !== undefined);
+ map.set(String(page.id), { page, thread, queries, block });
+ }
+ }
+ }
+ return map;
+ }, [exploration]);
+
+ const prefetchQueryResult = explorationApi.usePrefetch(
+ "getExplorationQueryResult",
+ );
+
+ const prefetchPage = useCallback(
+ (pageId: ExplorationPageNodeId) => {
+ const entry = pageIdToPageAndQueries.get(pageId);
+ if (!entry) {
+ return;
+ }
+ for (const query of entry.queries) {
+ if (query.status === "done") {
+ prefetchQueryResult(query.id);
+ }
+ }
+ },
+ [pageIdToPageAndQueries, prefetchQueryResult],
+ );
+
+ const orderedPages = useMemo(
() =>
flattenTree(tree).flatMap((item) =>
- item.data?.type === "page" ? [item.data.page_id] : [],
+ item.data?.type === "page" ? [{ id: item.data.page_id }] : [],
),
[tree],
);
- const currentPageIndex =
- selectedPageId != null ? orderedPageIds.indexOf(selectedPageId) : -1;
+ const previousPage = getAdjacentById(orderedPages, selectedPageId, -1);
+ const nextPage = getAdjacentById(orderedPages, selectedPageId, 1);
+ // Undefined when there's nowhere else to go (empty or single-page list).
const previousPageId =
- currentPageIndex > 0 ? orderedPageIds[currentPageIndex - 1] : undefined;
+ previousPage != null && previousPage.id !== selectedPageId
+ ? previousPage.id
+ : undefined;
const nextPageId =
- currentPageIndex !== -1 && currentPageIndex < orderedPageIds.length - 1
- ? orderedPageIds[currentPageIndex + 1]
+ nextPage != null && nextPage.id !== selectedPageId
+ ? nextPage.id
: undefined;
- const goToPreviousPage = useCallback(() => {
- if (previousPageId != null) {
- setSelectedPageId(previousPageId, { scrollIntoView: true });
- }
- }, [previousPageId, setSelectedPageId]);
- const goToNextPage = useCallback(() => {
- if (nextPageId != null) {
- setSelectedPageId(nextPageId, { scrollIntoView: true });
- }
- }, [nextPageId, setSelectedPageId]);
+
+ // Navigate and prefetch the page after the destination in the same
+ // direction — once a user pages once they're likely to page again.
+ // Both directions wrap around the ordered page list.
+ const goToAdjacentPage = useCallback(
+ (direction: 1 | -1) => {
+ const destination = getAdjacentById(
+ orderedPages,
+ selectedPageId,
+ direction,
+ );
+ if (destination == null || destination.id === selectedPageId) {
+ return;
+ }
+ setSelectedPageId(destination.id, { scrollIntoView: true });
+ const following = getAdjacentById(
+ orderedPages,
+ destination.id,
+ direction,
+ );
+ if (following != null) {
+ prefetchPage(following.id);
+ }
+ },
+ [orderedPages, selectedPageId, setSelectedPageId, prefetchPage],
+ );
+ const goToPreviousPage = useCallback(
+ () => goToAdjacentPage(-1),
+ [goToAdjacentPage],
+ );
+ const goToNextPage = useCallback(
+ () => goToAdjacentPage(1),
+ [goToAdjacentPage],
+ );
useEffect(() => {
if (selectedPageId != null && !readPageIds.has(selectedPageId)) {
@@ -386,38 +467,6 @@ function ExplorationPageForId() {
}
}, [exploration, sendToast, setSelectedPageId]);
- const pageIdToPageAndQueries: Map<
- ExplorationPageNodeId,
- {
- page: ExplorationPageNode;
- thread: ExplorationThread;
- queries: ExplorationQuery[];
- block: ExplorationBlockNode;
- }
- > = useMemo(() => {
- const map = new Map<
- ExplorationPageNodeId,
- {
- page: ExplorationPageNode;
- thread: ExplorationThread;
- queries: ExplorationQuery[];
- block: ExplorationBlockNode;
- }
- >();
- for (const thread of exploration?.threads ?? []) {
- const queriesById = new Map((thread.queries ?? []).map((q) => [q.id, q]));
- for (const block of thread.blocks ?? []) {
- for (const page of block.pages) {
- const queries = page.query_ids
- .map((id) => queriesById.get(id))
- .filter((q): q is ExplorationQuery => q !== undefined);
- map.set(String(page.id), { page, thread, queries, block });
- }
- }
- }
- return map;
- }, [exploration]);
-
const selectedPage = useMemo(() => {
return selectedPageId != null
? pageIdToPageAndQueries.get(selectedPageId)
@@ -506,7 +555,6 @@ function ExplorationPageForId() {
getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}
tree={tree}
selectedPageId={selectedPageId}
- setSelectedPageId={setSelectedPageId}
getSelectedPageUrl={getSelectedPageUrl}
shouldScrollSelectionRef={shouldScrollSelectionRef}
isOpen={isSidebarOpen}
@@ -516,6 +564,9 @@ function ExplorationPageForId() {
sortOrder={sortOrder}
onChangeSortOrder={handleChangeSortOrder}
contentMode={sidebarContentMode}
+ onPreviousPage={goToPreviousPage}
+ onNextPage={goToNextPage}
+ onPrefetchPage={prefetchPage}
/>
{selectedPage && (
<ExplorationGroupVisualization
diff --git a/frontend/src/metabase/explorations/pages/ExplorationPage.unit.spec.tsx b/frontend/src/metabase/explorations/pages/ExplorationPage.unit.spec.tsx
index 2537927c22a..70b04413bb5 100644
--- a/frontend/src/metabase/explorations/pages/ExplorationPage.unit.spec.tsx
+++ b/frontend/src/metabase/explorations/pages/ExplorationPage.unit.spec.tsx
@@ -1,4 +1,5 @@
import { act } from "@testing-library/react";
+import fetchMock from "fetch-mock";
import { useReducer } from "react";
import {
@@ -61,8 +62,21 @@ jest.mock("../components/ExplorationVisualization", () => ({
ExplorationChartAreaSkeleton: () => null,
}));
+type CapturedSidebarNavProps = {
+ onPreviousPage: () => void;
+ onNextPage: () => void;
+};
+
+let latestSidebarNavProps: CapturedSidebarNavProps | null = null;
+
jest.mock("../components/ExplorationSidebar", () => ({
- ExplorationSidebar: () => <div data-testid="sidebar" />,
+ ExplorationSidebar: (props: CapturedSidebarNavProps) => {
+ latestSidebarNavProps = {
+ onPreviousPage: props.onPreviousPage,
+ onNextPage: props.onNextPage,
+ };
+ return <div data-testid="sidebar" />;
+ },
ExplorationTitle: () => <div data-testid="exploration-title" />,
}));
@@ -116,9 +130,142 @@ function rerenderExplorationPage() {
fireEvent.click(screen.getByTestId(RERENDER_BUTTON_TESTID));
}
+function makeMultiPageExploration(): Exploration {
+ return makeExploration([
+ makeThread(
+ 1,
+ "Initial thread",
+ [
+ createPage({
+ id: 100,
+ name: "Page A",
+ position: 0,
+ query_ids: [1],
+ }),
+ createPage({
+ id: 200,
+ name: "Page B",
+ position: 1,
+ query_ids: [2],
+ }),
+ createPage({
+ id: 300,
+ name: "Page C",
+ position: 2,
+ query_ids: [3],
+ }),
+ ],
+ [
+ createQuery({ id: 1, name: "Query A", status: "done" }),
+ createQuery({ id: 2, name: "Query B", status: "done" }),
+ createQuery({ id: 3, name: "Query C", status: "done" }),
+ ],
+ ),
+ ]);
+}
+
+describe("ExplorationPage page navigation", () => {
+ beforeEach(() => {
+ latestSidebarNavProps = null;
+ explorationData = makeMultiPageExploration();
+ // goToAdjacentPage prefetches the following page's query results
+ fetchMock.get("express:/api/exploration/query/:id", {
+ data: { rows: [], cols: [] },
+ });
+ });
+
+ it("onNextPage navigates to the next page id in sidebar order", async () => {
+ const { router } = renderExplorationPage(
+ `${Urls.exploration(explorationData.id)}/page/100`,
+ );
+ if (!router) {
+ throw new Error("expected router");
+ }
+ expect(latestSidebarNavProps).not.toBeNull();
+
+ await act(async () => {
+ latestSidebarNavProps?.onNextPage();
+ });
+
+ await waitFor(() => {
+ expect(router.location.pathname).toContain("/page/200");
+ });
+ });
+
+ it("onNextPage prefetches the page after the destination", async () => {
+ renderExplorationPage(`${Urls.exploration(explorationData.id)}/page/100`);
+
+ await act(async () => {
+ latestSidebarNavProps?.onNextPage();
+ });
+
+ // A → B; prefetch the page after B (C / query 3), not B itself.
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called("path:/api/exploration/query/3"),
+ ).toBe(true);
+ });
+ expect(fetchMock.callHistory.called("path:/api/exploration/query/2")).toBe(
+ false,
+ );
+ });
+
+ it("onPreviousPage navigates to the previous page id in sidebar order", async () => {
+ const { router } = renderExplorationPage(
+ `${Urls.exploration(explorationData.id)}/page/200`,
+ );
+ if (!router) {
+ throw new Error("expected router");
+ }
+
+ await act(async () => {
+ latestSidebarNavProps?.onPreviousPage();
+ });
+
+ await waitFor(() => {
+ expect(router.location.pathname).toContain("/page/100");
+ });
+ });
+
+ it("onNextPage wraps from the last page to the first", async () => {
+ const { router } = renderExplorationPage(
+ `${Urls.exploration(explorationData.id)}/page/300`,
+ );
+ if (!router) {
+ throw new Error("expected router");
+ }
+
+ await act(async () => {
+ latestSidebarNavProps?.onNextPage();
+ });
+
+ await waitFor(() => {
+ expect(router.location.pathname).toContain("/page/100");
+ });
+ });
+
+ it("onPreviousPage wraps from the first page to the last", async () => {
+ const { router } = renderExplorationPage(
+ `${Urls.exploration(explorationData.id)}/page/100`,
+ );
+ if (!router) {
+ throw new Error("expected router");
+ }
+
+ await act(async () => {
+ latestSidebarNavProps?.onPreviousPage();
+ });
+
+ await waitFor(() => {
+ expect(router.location.pathname).toContain("/page/300");
+ });
+ });
+});
+
describe("ExplorationPage thread-ready toasts", () => {
beforeEach(() => {
sendToastMock.mockClear();
+ latestSidebarNavProps = null;
explorationData = makeExploration([
makeThread(
1,