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
Split the query builder into its own chunk (#79342)
Romeo Van Snick258b1708da68
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/common/TableBreadcrumbs.tsx b/enterprise/frontend/src/metabase-enterprise/table-editing/common/TableBreadcrumbs.tsxindex e41633cc27f..cc78ad8b00e 100644--- a/enterprise/frontend/src/metabase-enterprise/table-editing/common/TableBreadcrumbs.tsx+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/common/TableBreadcrumbs.tsx@@ -1,7 +1,7 @@import { useMemo } from "react";import { t } from "ttag";-import { HeadBreadcrumbs } from "metabase/query_builder/components/view/ViewHeader/components";+import { HeadBreadcrumbs } from "metabase/query_builder/components/view/ViewHeader/components/HeaderBreadcrumbs/HeaderBreadcrumbs";import type { DataSourcePart } from "metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/utils";import { ViewHeading } from "metabase/query_builder/components/view/ViewSection";import * as Urls from "metabase/urls";diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataHeader.tsx b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataHeader.tsxindex 27fac1b1c22..24e02ae1b46 100644--- a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataHeader.tsx+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/EditTableDataHeader.tsx@@ -1,7 +1,7 @@import { useDisclosure } from "@mantine/hooks";import { t } from "ttag";-import { QuestionFiltersHeader } from "metabase/query_builder/components/view/ViewHeader/components";+import { QuestionFiltersHeader } from "metabase/query_builder/components/view/ViewHeader/components/QuestionFiltersHeader";import { Box, Button, Icon, Stack } from "metabase/ui";import type Question from "metabase-lib/v1/Question";diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.jsindex 68c4d4aa675..6246eb54ee4 100644--- a/frontend/src/metabase/app.js+++ b/frontend/src/metabase/app.js@@ -30,6 +30,7 @@ import { createRoot } from "react-dom/client";import { initializePlugins } from "ee-plugins";import { AppThemeProvider } from "metabase/AppThemeProvider";import { createSnowplowTracker } from "metabase/analytics";+import { DelayedLoadingSpinner } from "metabase/common/components/DelayedLoading/DelayedLoading";import { ModifiedBackend } from "metabase/common/components/dnd/ModifiedBackend";import { registerDashboardVisualizations } from "metabase/dashboard/visualizations/register";import { initializeInteractiveEmbedding } from "metabase/embedding/interactive-embedding";@@ -103,6 +104,7 @@ function _init(reducers, getRoutes, callback) {<RouterProviderroutes={routes}onLocationChange={mirrorLocation}+ hydrateFallback={<DelayedLoadingSpinner />}/></MetabotProvider></AppThemeProvider>diff --git a/frontend/src/metabase/app/nav/AppBar.tsx b/frontend/src/metabase/app/nav/AppBar.tsxindex 970467deb49..8bad3654e17 100644--- a/frontend/src/metabase/app/nav/AppBar.tsx+++ b/frontend/src/metabase/app/nav/AppBar.tsx@@ -20,11 +20,10 @@ import { getMetabotVisible } from "metabase/metabot/state";import { AppBar as AppBarView } from "metabase/nav/components/AppBar";import { CollectionBreadcrumbs } from "metabase/nav/containers/CollectionBreadcrumbs";import { isQuestionPath } from "metabase/nav/containers/MainNavbar/getSelectedItems";-import { zoomInRow } from "metabase/query_builder/actions";import {getOriginalQuestion,getQuestion,-} from "metabase/query_builder/selectors";+} from "metabase/query_builder/selectors/question";import { useDispatch, useSelector } from "metabase/redux";import { closeNavbar, toggleNavbar } from "metabase/redux/app";import { useLocation, useNavigate, useParams } from "metabase/router";@@ -109,9 +108,14 @@ export function AppBarContainer() {// Unjustified type cast. FIXMEconst locationState = location.state as { cardId?: number } | undefined;- const onSearchItemSelect = (result: SearchResult) => {+ const onSearchItemSelect = async (result: SearchResult) => {const selection = getSearchResultSelection(result, locationState?.cardId);if (selection.type === "zoom") {+ // Reached through an import so the app bar, which every page mounts, does+ // not put the query builder's actions in the initial bundle. Only a search+ // selection on an object-detail page gets here, and the query builder it+ // zooms within is already loaded by then.+ const { zoomInRow } = await import("metabase/query_builder/actions");dispatch(zoomInRow({ objectId: selection.objectId }));} else {navigate(selection.url);diff --git a/frontend/src/metabase/app/selectors.ts b/frontend/src/metabase/app/selectors.tsindex baf6c5b15fa..27d276cd298 100644--- a/frontend/src/metabase/app/selectors.ts+++ b/frontend/src/metabase/app/selectors.ts@@ -11,7 +11,7 @@ import { getCurrentExploration } from "metabase/explorations/selectors";import {getIsSavedQuestionChanged,getQuestion,-} from "metabase/query_builder/selectors";+} from "metabase/query_builder/selectors/question";import type { State } from "metabase/redux/store";import { type RouterProps, getDetailViewState } from "metabase/selectors/app";import { getUser } from "metabase/selectors/user";diff --git a/frontend/src/metabase/common/components/Link/BaseLink.prefetch.unit.spec.tsx b/frontend/src/metabase/common/components/Link/BaseLink.prefetch.unit.spec.tsxnew file mode 100644index 00000000000..2ebe4e7d6a6--- /dev/null+++ b/frontend/src/metabase/common/components/Link/BaseLink.prefetch.unit.spec.tsx@@ -0,0 +1,67 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";+import { Route, registerPagePrefetch } from "metabase/router";++import { Link } from "./Link";++let nextId = 0;+const uniquePath = () => `/prefetch-link-spec-${nextId++}`;++function setup(path: string, onMouseEnter?: () => void) {+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ renderWithProviders(+ <Route+ path="/"+ element={+ <>+ <Link to={path} onMouseEnter={onMouseEnter}>+ split page+ </Link>+ <Link to={uniquePath()}>ordinary page</Link>+ </>+ }+ />,+ { withRouter: true, initialRoute: "/" },+ );++ return { load };+}++describe("BaseLink prefetching", () => {+ it("loads the target's chunk when the link is hovered", async () => {+ const { load } = setup(uniquePath());++ await userEvent.hover(screen.getByText("split page"));++ expect(load).toHaveBeenCalledTimes(1);+ });++ it("loads it on keyboard focus too", () => {+ const { load } = setup(uniquePath());++ screen.getByText("split page").focus();++ expect(load).toHaveBeenCalledTimes(1);+ });++ it("leaves a link with nothing to prefetch alone", async () => {+ const { load } = setup(uniquePath());++ await userEvent.hover(screen.getByText("ordinary page"));++ expect(load).not.toHaveBeenCalled();+ });++ it("still calls the call site's own hover handler", async () => {+ const onMouseEnter = jest.fn();+ const { load } = setup(uniquePath(), onMouseEnter);++ await userEvent.hover(screen.getByText("split page"));++ expect(onMouseEnter).toHaveBeenCalledTimes(1);+ expect(load).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/metabase/common/components/Link/BaseLink.tsx b/frontend/src/metabase/common/components/Link/BaseLink.tsxindex 8d6c7327e51..0b33690febb 100644--- a/frontend/src/metabase/common/components/Link/BaseLink.tsx+++ b/frontend/src/metabase/common/components/Link/BaseLink.tsx@@ -11,6 +11,7 @@ import {type NavLinkRenderProps,Link as RouterLink,type To,+ prefetchPage,useInRouterContext,} from "metabase/router";@@ -92,7 +93,10 @@ export interface BaseLinkProps extends Omit<* that need it subscribe to the current route.*/export const BaseLink = forwardRef<HTMLAnchorElement, BaseLinkProps>(- function BaseLink({ to, innerRef, className, style, end, ...rest }, ref) {+ function BaseLink(+ { to, innerRef, className, style, end, onMouseEnter, onFocus, ...rest },+ ref,+ ) {const linkRef = ref ?? innerRef;const inRouter = useInRouterContext();@@ -112,6 +116,8 @@ export const BaseLink = forwardRef<HTMLAnchorElement, BaseLinkProps>(<a{...rest}href={href}+ onMouseEnter={onMouseEnter}+ onFocus={onFocus}className={resolveClassName(className, INACTIVE)}style={resolveStyle(style, INACTIVE)}ref={linkRef}@@ -121,10 +127,26 @@ export const BaseLink = forwardRef<HTMLAnchorElement, BaseLinkProps>(const target = anchorTarget(to);+ // Reaching for a link is the earliest reliable sign that the user is about+ // to follow it, so a target in its own chunk starts loading here instead of+ // when its route renders. `prefetchPage` does nothing for a target that+ // registered no loader, which is almost all of them.+ const prefetchProps = {+ onMouseEnter: (event: React.MouseEvent<HTMLAnchorElement>) => {+ onMouseEnter?.(event);+ prefetchPage(hrefFor(target));+ },+ onFocus: (event: React.FocusEvent<HTMLAnchorElement>) => {+ onFocus?.(event);+ prefetchPage(hrefFor(target));+ },+ };+if (typeof className === "function" || typeof style === "function") {return (<NavLink{...rest}+ {...prefetchProps}to={target}end={end}// Normalize both to callbacks: given a plain string `NavLink` appends@@ -139,6 +161,7 @@ export const BaseLink = forwardRef<HTMLAnchorElement, BaseLinkProps>(return (<RouterLink{...rest}+ {...prefetchProps}to={target}className={className}style={style}diff --git a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.ts b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.tsindex 9dac0f75922..435b4e6fcc7 100644--- a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.ts+++ b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.ts@@ -50,6 +50,11 @@ export const useListKeyboardNavigation = <break;case "Enter":if (cursorIndex != null && !isNaN(cursorIndex)) {+ // Selecting an item consumes the key. Without this the same Enter+ // also reaches whatever the list is rendered over, and the search+ // bar takes it as "show all results" and navigates to /search,+ // replacing the navigation this selection just started.+ event.preventDefault();onEnter(list[cursorIndex]);}break;diff --git a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.ts b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.tsindex 71b4e34b6a3..587d946d038 100644--- a/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.ts+++ b/frontend/src/metabase/common/hooks/use-list-keyboard-navigation/use-list-keyboard-navigation.unit.spec.ts@@ -40,6 +40,27 @@ describe("useListKeyboardNavigation", () => {expect(list.some(getRef)).toBeFalsy();});+ // The search bar renders this list over an input that treats Enter as "show+ // all results" and navigates. Consuming the key keeps that from replacing the+ // navigation the selection just started.+ it("consumes Enter when an item is selected", () => {+ renderHook(() =>+ useListKeyboardNavigation<unknown>({ list, onEnter: jest.fn() }),+ );++ fireKey("ArrowDown");++ expect(fireEvent.keyDown(window, { key: "Enter" })).toBe(false);+ });++ it("leaves Enter alone when no item is selected", () => {+ renderHook(() =>+ useListKeyboardNavigation<unknown>({ list, onEnter: jest.fn() }),+ );++ expect(fireEvent.keyDown(window, { key: "Enter" })).toBe(true);+ });+it("does nothing on key down if no list items", () => {const onEnterMock = jest.fn();const { result } = renderHook(() =>diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.tsindex b582af07f35..5e5960767bc 100644--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts@@ -9,6 +9,7 @@ import {type Location,queryToSearch,subscribeLocation,+ useIsNavigating,useIsNavigationHeld,useNavigate,} from "metabase/router";@@ -32,6 +33,7 @@ export function useDashboardUrlQuery(location: Location) {const parameters = useSelector(getValuePopulatedParameters);const siteUrl = useSetting("site-url");const isNavigationHeld = useIsNavigationHeld();+ const isNavigating = useIsNavigating();const dispatch = useDispatch();const navigate = useNavigate();@@ -78,6 +80,17 @@ export function useDashboardUrlQuery(location: Location) {return;}+ /**+ * The router is on its way somewhere else and has not committed it yet,+ * which a `route.lazy` destination makes possible. Syncing now would replace+ * that pending navigation and strand the user on the dashboard. Note the+ * skip the same way, so the sync still happens if we stay put.+ */+ if (isNavigating) {+ hasDeferredSyncRef.current = true;+ return;+ }+const pathname = location.pathname.replace(siteUrl, "");const isDashboardUrl = pathname.startsWith("/dashboard/");if (isDashboardUrl) {@@ -124,6 +137,7 @@ export function useDashboardUrlQuery(location: Location) {siteUrl,navigate,isNavigationHeld,+ isNavigating,]);useEffect(() => {diff --git a/frontend/src/metabase/query_builder/actions/core/core.ts b/frontend/src/metabase/query_builder/actions/core/core.tsindex 6416b2d26fb..ea3c2edfde1 100644--- a/frontend/src/metabase/query_builder/actions/core/core.ts+++ b/frontend/src/metabase/query_builder/actions/core/core.ts@@ -17,8 +17,11 @@ import { createThunkAction } from "metabase/redux";import { openUrl } from "metabase/redux/app";import { createQuestionCard, updateQuestionCard } from "metabase/redux/cards";import {+ API_CREATE_QUESTION,API_UPDATE_QUESTION,+ RELOAD_CARD,REVERT_CARD_TO_REVISION,+ SET_CARD_AND_RUN,SOFT_RELOAD_CARD,clearQueryResult,onCloseSidebars,@@ -71,7 +74,6 @@ export const softReloadCard = createThunkAction(SOFT_RELOAD_CARD, () => {};});-export const RELOAD_CARD = "metabase/qb/RELOAD_CARD";export const reloadCard = createThunkAction(RELOAD_CARD, () => {return async (dispatch, getState) => {const outdatedQuestion = getQuestion(getState());@@ -103,7 +105,6 @@ export const reloadCard = createThunkAction(RELOAD_CARD, () => {* - clicking in the entity details view* - `navigateToNewCardInsideQB` is being called (see below)*/-export const SET_CARD_AND_RUN = "metabase/qb/SET_CARD_AND_RUN";export const setCardAndRun = (nextCard: Card,{ shouldUpdateUrl = true } = {},@@ -217,7 +218,6 @@ export const setDatasetQuery =type OnCreateOptions = { dashboardTabId?: DashboardTabId | undefined };-export const API_CREATE_QUESTION = "metabase/qb/API_CREATE_QUESTION";export const apiCreateQuestion = (question: Question,options?: OnCreateOptions,diff --git a/frontend/src/metabase/query_builder/actions/core/native.ts b/frontend/src/metabase/query_builder/actions/core/native.tsindex e896261e785..fe4f814d96e 100644--- a/frontend/src/metabase/query_builder/actions/core/native.ts+++ b/frontend/src/metabase/query_builder/actions/core/native.ts@@ -1,5 +1,5 @@-export const SET_IS_SHOWING_TEMPLATE_TAGS_EDITOR =- "metabase/qb/SET_IS_SHOWING_TEMPLATE_TAGS_EDITOR";+import { SET_IS_SHOWING_TEMPLATE_TAGS_EDITOR } from "metabase/redux/query-builder";+export const setIsShowingTemplateTagsEditor = (isShowingTemplateTagsEditor: boolean,) => ({diff --git a/frontend/src/metabase/query_builder/actions/core/updateQuestion.ts b/frontend/src/metabase/query_builder/actions/core/updateQuestion.tsindex 84dbff8f75d..70b4f9f1872 100644--- a/frontend/src/metabase/query_builder/actions/core/updateQuestion.ts+++ b/frontend/src/metabase/query_builder/actions/core/updateQuestion.ts@@ -3,6 +3,7 @@ import _ from "underscore";import { loadMetadataForCard } from "metabase/questions/actions";import { createThunkAction } from "metabase/redux";import {+ UPDATE_QUESTION,onCloseQuestionInfo,setUIControls,} from "metabase/redux/query-builder";@@ -77,7 +78,6 @@ export type UpdateQuestionOpts = {/*** Replaces the currently active question with the given Question object.*/-export const UPDATE_QUESTION = "metabase/qb/UPDATE_QUESTION";export const updateQuestion = (newQuestion: Question,{diff --git a/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.tsindex 963575009d6..e95db6f9ce2 100644--- a/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.ts+++ b/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.ts@@ -1,6 +1,7 @@import { createMockEntitiesState } from "__support__/store";import * as questionActions from "metabase/questions/actions";import * as sharedQB from "metabase/redux/query-builder";+import { UPDATE_QUESTION } from "metabase/redux/query-builder";import type { QueryBuilderMode } from "metabase/redux/store";import {createMockQueryBuilderState,@@ -56,7 +57,7 @@ import * as ui from "../ui";import * as url from "../url";import * as native from "./native";-import { UPDATE_QUESTION, updateQuestion } from "./updateQuestion";+import { updateQuestion } from "./updateQuestion";registerVisualizations();diff --git a/frontend/src/metabase/query_builder/actions/models.ts b/frontend/src/metabase/query_builder/actions/models.tsindex ad373a17218..26481dbec3b 100644--- a/frontend/src/metabase/query_builder/actions/models.ts+++ b/frontend/src/metabase/query_builder/actions/models.ts@@ -1,6 +1,7 @@import { createAction } from "redux-actions";import { t } from "ttag";+import { SET_METADATA_DIFF } from "metabase/redux/query-builder";import type {DatasetEditorTab,Dispatch,@@ -76,7 +77,6 @@ export const turnModelIntoQuestion =);};-export const SET_METADATA_DIFF = "metabase/qb/SET_METADATA_DIFF";export const setMetadataDiff = createAction(SET_METADATA_DIFF);export const onModelPersistenceChange =diff --git a/frontend/src/metabase/query_builder/actions/native.ts b/frontend/src/metabase/query_builder/actions/native.tsindex 84d185ae89a..f07a3a6916a 100644--- a/frontend/src/metabase/query_builder/actions/native.ts+++ b/frontend/src/metabase/query_builder/actions/native.ts@@ -3,6 +3,16 @@ import { createAction } from "redux-actions";import { cardApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { createThunkAction } from "metabase/redux";+import {+ OPEN_DATA_REFERENCE_AT_QUESTION,+ SET_DATA_REFERENCE_STACK,+ SET_MODAL_SNIPPET,+ SET_NATIVE_EDITOR_SELECTED_RANGE,+ SET_SNIPPET_COLLECTION_ID,+ TOGGLE_DATA_REFERENCE,+ TOGGLE_SNIPPET_SIDEBAR,+ TOGGLE_TEMPLATE_TAGS_EDITOR,+} from "metabase/redux/query-builder";import type { Dispatch, GetState } from "metabase/redux/store";import { settingsApi } from "metabase/settings";import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";@@ -24,10 +34,8 @@ import {import { updateQuestion } from "./core/updateQuestion";-export const TOGGLE_DATA_REFERENCE = "metabase/qb/TOGGLE_DATA_REFERENCE";export const toggleDataReference = createAction(TOGGLE_DATA_REFERENCE);-export const SET_DATA_REFERENCE_STACK = "metabase/qb/SET_DATA_REFERENCE_STACK";export const setDataReferenceStack = createAction(SET_DATA_REFERENCE_STACK);export const POP_DATA_REFERENCE_STACK = "metabase/qb/POP_DATA_REFERENCE_STACK";@@ -49,8 +57,6 @@ export const pushDataReferenceStack = createThunkAction(},);-export const OPEN_DATA_REFERENCE_AT_QUESTION =- "metabase/qb/OPEN_DATA_REFERENCE_AT_QUESTION";export const openDataReferenceAtQuestion = createThunkAction(OPEN_DATA_REFERENCE_AT_QUESTION,(id: CardId) => async (dispatch: Dispatch) => {@@ -72,13 +78,10 @@ export const openDataReferenceAtQuestion = createThunkAction(},);-export const TOGGLE_TEMPLATE_TAGS_EDITOR =- "metabase/qb/TOGGLE_TEMPLATE_TAGS_EDITOR";export const toggleTemplateTagsEditor = createAction(TOGGLE_TEMPLATE_TAGS_EDITOR,);-export const TOGGLE_SNIPPET_SIDEBAR = "metabase/qb/TOGGLE_SNIPPET_SIDEBAR";export const toggleSnippetSidebar = createAction(TOGGLE_SNIPPET_SIDEBAR);export const SET_IS_SHOWING_SNIPPET_SIDEBAR =@@ -90,17 +93,12 @@ export const setIsShowingSnippetSidebar = (isShowingSnippetSidebar,});-export const SET_NATIVE_EDITOR_SELECTED_RANGE =- "metabase/qb/SET_NATIVE_EDITOR_SELECTED_RANGE";export const setNativeEditorSelectedRange = createAction(SET_NATIVE_EDITOR_SELECTED_RANGE,);-export const SET_MODAL_SNIPPET = "metabase/qb/SET_MODAL_SNIPPET";export const setModalSnippet = createAction(SET_MODAL_SNIPPET);-export const SET_SNIPPET_COLLECTION_ID =- "metabase/qb/SET_SNIPPET_COLLECTION_ID";export const setSnippetCollectionId = createAction(SET_SNIPPET_COLLECTION_ID);export const openSnippetModalWithSelectedText =diff --git a/frontend/src/metabase/query_builder/actions/object-detail.ts b/frontend/src/metabase/query_builder/actions/object-detail.tsindex 1fbc792cebf..84c5e4a4067 100644--- a/frontend/src/metabase/query_builder/actions/object-detail.ts+++ b/frontend/src/metabase/query_builder/actions/object-detail.ts@@ -3,7 +3,11 @@ import _ from "underscore";import { datasetApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { createThunkAction } from "metabase/redux";-import { RESET_ROW_ZOOM } from "metabase/redux/query-builder";+import {+ CLEAR_OBJECT_DETAIL_FK_REFERENCES,+ LOAD_OBJECT_DETAIL_FK_REFERENCES,+ RESET_ROW_ZOOM,+} from "metabase/redux/query-builder";import type { Dispatch, GetState } from "metabase/redux/store";import { getMetadata } from "metabase/selectors/metadata";import type { ObjectId } from "metabase/visualizations/components/ObjectDetail/types";@@ -102,8 +106,6 @@ interface FKInfo {value: string | number | null;}-export const LOAD_OBJECT_DETAIL_FK_REFERENCES =- "metabase/qb/LOAD_OBJECT_DETAIL_FK_REFERENCES";export const loadObjectDetailFKReferences = createThunkAction(LOAD_OBJECT_DETAIL_FK_REFERENCES,({ objectId }) => {@@ -204,9 +206,6 @@ export const loadObjectDetailFKReferences = createThunkAction(},);-export const CLEAR_OBJECT_DETAIL_FK_REFERENCES =- "metabase/qb/CLEAR_OBJECT_DETAIL_FK_REFERENCES";-export const viewNextObjectDetail = () => {return (dispatch: Dispatch, getState: GetState) => {if (getCanZoomNextRow(getState())) {diff --git a/frontend/src/metabase/query_builder/actions/state.ts b/frontend/src/metabase/query_builder/actions/state.tsindex 0f4898b0151..2c50f629f81 100644--- a/frontend/src/metabase/query_builder/actions/state.ts+++ b/frontend/src/metabase/query_builder/actions/state.ts@@ -1,4 +1,5 @@import { createAction } from "redux-actions";-export const SET_CURRENT_STATE = "metabase/qb/SET_CURRENT_STATE";+import { SET_CURRENT_STATE } from "metabase/redux/query-builder";+export const setCurrentState = createAction(SET_CURRENT_STATE);diff --git a/frontend/src/metabase/query_builder/actions/timelines.ts b/frontend/src/metabase/query_builder/actions/timelines.tsindex cf10a662836..fdb7c4eb9b7 100644--- a/frontend/src/metabase/query_builder/actions/timelines.ts+++ b/frontend/src/metabase/query_builder/actions/timelines.ts@@ -1,20 +1,19 @@import { createAction } from "redux-actions";+import {+ DESELECT_TIMELINE_EVENTS,+ HIDE_TIMELINE_EVENTS,+ SELECT_TIMELINE_EVENTS,+ SHOW_TIMELINE_EVENTS,+} from "metabase/redux/query-builder";import type { Dispatch, GetState } from "metabase/redux/store";import type { CollectionId, Timeline } from "metabase-types/api";import { getFetchedTimelines } from "../selectors";-export const SELECT_TIMELINE_EVENTS = "metabase/qb/SELECT_TIMELINE_EVENTS";export const selectTimelineEvents = createAction(SELECT_TIMELINE_EVENTS);--export const DESELECT_TIMELINE_EVENTS = "metabase/qb/DESELECT_TIMELINE_EVENTS";export const deselectTimelineEvents = createAction(DESELECT_TIMELINE_EVENTS);--export const HIDE_TIMELINE_EVENTS = "metabase/qb/HIDE_TIMELINE_EVENTS";export const hideTimelineEvents = createAction(HIDE_TIMELINE_EVENTS);--export const SHOW_TIMELINE_EVENTS = "metabase/qb/SHOW_TIMELINE_EVENTS";export const showTimelineEvents = createAction(SHOW_TIMELINE_EVENTS);export const showTimelinesForCollection =diff --git a/frontend/src/metabase/query_builder/actions/url.unit.spec.ts b/frontend/src/metabase/query_builder/actions/url.unit.spec.tsindex 81106d7e09e..2f80b1dff0d 100644--- a/frontend/src/metabase/query_builder/actions/url.unit.spec.ts+++ b/frontend/src/metabase/query_builder/actions/url.unit.spec.ts@@ -6,6 +6,7 @@// other side: how `navigate` drives the router.import { createMockEntitiesState } from "__support__/store";+import { SET_CURRENT_STATE } from "metabase/redux/query-builder";import {createMockQueryBuilderState,createMockQueryBuilderUIControlsState,@@ -26,7 +27,6 @@ import {import { getTableUrlForPristineQuestion } from "../utils";-import { SET_CURRENT_STATE } from "./state";import { updateUrl } from "./url";registerVisualizations();diff --git a/frontend/src/metabase/query_builder/reducers.ts b/frontend/src/metabase/query_builder/reducers.tsindex 9e2ffe967af..ccd4700654d 100644--- a/frontend/src/metabase/query_builder/reducers.ts+++ b/frontend/src/metabase/query_builder/reducers.ts@@ -11,9 +11,11 @@ import {} from "metabase/api";import { EDIT_QUESTION, NAVIGATE_TO_NEW_CARD } from "metabase/redux/dashboard";import {+ API_CREATE_QUESTION,API_UPDATE_QUESTION,CANCEL_QUERY,CANCEL_QUESTION_CHANGES,+ CLEAR_OBJECT_DETAIL_FK_REFERENCES,CLEAR_QUERY_RESULT,CLOSE_AI_QUESTION_ANALYSIS_SIDEBAR,CLOSE_CHART_SETTINGS,@@ -24,28 +26,47 @@ import {CLOSE_QUESTION_SETTINGS,CLOSE_SIDEBARS,CLOSE_TIMELINES,+ DESELECT_TIMELINE_EVENTS,EDIT_SUMMARY,+ HIDE_TIMELINE_EVENTS,INITIALIZE_QB,+ LOAD_OBJECT_DETAIL_FK_REFERENCES,ON_CLOSE_SUMMARY,OPEN_AI_QUESTION_ANALYSIS_SIDEBAR,OPEN_CHART_SETTINGS,OPEN_CHART_TYPE,+ OPEN_DATA_REFERENCE_AT_QUESTION,OPEN_QUESTION_INFO,OPEN_QUESTION_SETTINGS,OPEN_TIMELINES,QUERY_COMPLETED,QUERY_ERRORED,+ RELOAD_CARD,RESET_QB,RESET_ROW_ZOOM,RESET_UI_CONTROLS,RUN_QUERY,+ SELECT_TIMELINE_EVENTS,+ SET_CARD_AND_RUN,+ SET_CURRENT_STATE,+ SET_DATA_REFERENCE_STACK,SET_DOCUMENT_TITLE,SET_DOCUMENT_TITLE_TIMEOUT_ID,+ SET_IS_SHOWING_TEMPLATE_TAGS_EDITOR,+ SET_METADATA_DIFF,+ SET_MODAL_SNIPPET,+ SET_NATIVE_EDITOR_SELECTED_RANGE,SET_PARAMETER_VALUE,SET_SHOW_LOADING_COMPLETE_FAVICON,+ SET_SNIPPET_COLLECTION_ID,SET_UI_CONTROLS,SHOW_CHART_SETTINGS,+ SHOW_TIMELINE_EVENTS,SOFT_RELOAD_CARD,+ TOGGLE_DATA_REFERENCE,+ TOGGLE_SNIPPET_SIDEBAR,+ TOGGLE_TEMPLATE_TAGS_EDITOR,+ UPDATE_QUESTION,ZOOM_IN_ROW,} from "metabase/redux/query-builder";import type {@@ -68,29 +89,6 @@ import type {TimelineEvent,} from "metabase-types/api";-import {- API_CREATE_QUESTION,- CLEAR_OBJECT_DETAIL_FK_REFERENCES,- DESELECT_TIMELINE_EVENTS,- HIDE_TIMELINE_EVENTS,- LOAD_OBJECT_DETAIL_FK_REFERENCES,- OPEN_DATA_REFERENCE_AT_QUESTION,- RELOAD_CARD,- SELECT_TIMELINE_EVENTS,- SET_CARD_AND_RUN,- SET_CURRENT_STATE,- SET_DATA_REFERENCE_STACK,- SET_IS_SHOWING_TEMPLATE_TAGS_EDITOR,- SET_METADATA_DIFF,- SET_MODAL_SNIPPET,- SET_NATIVE_EDITOR_SELECTED_RANGE,- SET_SNIPPET_COLLECTION_ID,- SHOW_TIMELINE_EVENTS,- TOGGLE_DATA_REFERENCE,- TOGGLE_SNIPPET_SIDEBAR,- TOGGLE_TEMPLATE_TAGS_EDITOR,- UPDATE_QUESTION,-} from "./actions";import {CLOSED_NATIVE_EDITOR_SIDEBARS,DEFAULT_LOADING_CONTROLS,diff --git a/frontend/src/metabase/query_builder/selectors.ts b/frontend/src/metabase/query_builder/selectors.tsindex 53533609a7c..86c739ceaf3 100644--- a/frontend/src/metabase/query_builder/selectors.ts+++ b/frontend/src/metabase/query_builder/selectors.ts@@ -12,7 +12,6 @@ import { getEmbedOptions } from "metabase/embedding/interactive-embedding";import {isQuestionDirty,isQuestionRunnable,- isSavedQuestionChanged,} from "metabase/querying/common/utils/question";import type { State } from "metabase/redux/store";import { getMetadata } from "metabase/selectors/metadata";@@ -59,10 +58,30 @@ import { isAbsoluteDateTimeUnit } from "metabase-types/guards/date-time";import { getQuestionWithDefaultVisualizationSettings } from "./actions/core/utils";import { cleanIndexFlags } from "./model-indexes/actions";+import {+ getCard,+ getOriginalCard,+ getOriginalQuestion,+ getParameterValues,+ getQueryBuilderMode,+ getQuestion,+ getQuestionWithoutComposing,+ getUiControls,+} from "./selectors/question";import { getWritableColumnProperties } from "./utils";-// This selector can be called from public questions / dashboards, which do not have state.qb-export const getUiControls = (state: State) => state.qb?.uiControls;+export {+ getCard,+ getIsSavedQuestionChanged,+ getOriginalCard,+ getOriginalQuestion,+ getParameterValues,+ getQueryBuilderMode,+ getQuestion,+ getQuestionWithoutComposing,+ getUiControls,+} from "./selectors/question";+export const getQueryStatus = (state: State) => state.qb.queryStatus;export const getLoadingControls = (state: State) => state.qb.loadingControls;@@ -103,12 +122,8 @@ export const getIsRunning = (state: State) => getUiControls(state).isRunning;export const getIsLoadingComplete = (state: State) =>getQueryStatus(state) === "complete";-export const getCard = (state: State) => state.qb.card;-export const getOriginalCard = (state: State) => state.qb.originalCard;export const getLastRunCard = (state: State) => state.qb.lastRunCard;-export const getParameterValues = (state: State) => state.qb.parameterValues;-export const getMetadataDiff = (state: State) => state.qb.metadataDiff;export const getVisibleTimelineEventIds = (state: State) =>@@ -127,11 +142,6 @@ export const getIsBookmarked = (bookmark.type === "card" && bookmark.item_id === state.qb.card?.id,);-export const getQueryBuilderMode = createSelector(- [getUiControls],- (uiControls) => uiControls.queryBuilderMode,-);-export const getQueryStartTime = (state: State) => state.qb.queryStartTime;export const getDatabaseId = createSelector(@@ -163,12 +173,6 @@ export const getDatasetEditorTab = createSelector((uiControls) => uiControls.datasetEditorTab,);-export const getOriginalQuestion = createSelector(- [getMetadata, getOriginalCard],- (metadata, card) =>- (metadata && card && new Question(card, metadata)) ?? undefined,-);-export const getOriginalQuestionWithParameterValues = createSelector([getMetadata, getOriginalCard, getParameterValues],(metadata, card, parameterValues) =>@@ -181,40 +185,6 @@ export const getLastRunQuestion = createSelector(card && metadata && new Question(card, metadata, parameterValues),);-export const getQuestionWithoutComposing = createSelector(- [getCard, getMetadata, getParameterValues],- (card, metadata, parameterValues) => {- if (!card || !metadata) {- return;- }- return new Question(card, metadata, parameterValues);- },-);--export const getQuestion = createSelector(- [getQuestionWithoutComposing, getQueryBuilderMode],- (question, queryBuilderMode) => {- if (!question) {- return;- }-- const isModel = question.type() === "model";- const isMetric = question.type() === "metric";- if ((isModel || isMetric) && queryBuilderMode === "dataset") {- return isModel ? question.lockDisplay() : question;- }-- // When opening a model or a metric, we construct a question- // with a clean, ad-hoc, query.- // This has to be skipped for users without data permissions.- // See https://github.com/metabase/metabase/issues/20042- const composedQuestion =- isModel || isMetric ? question.composeQuestion() : question;- const { isEditable } = Lib.queryDisplayInfo(composedQuestion.query());- return isEditable ? composedQuestion : question;- },-);-/*** Returns whether the current question is a native query*/@@ -625,11 +595,6 @@ export const getIsDirty = createSelector(isQuestionDirty,);-export const getIsSavedQuestionChanged = createSelector(- [getQuestion, getOriginalQuestion],- isSavedQuestionChanged,-);-export const getIsRunnable = createSelector([getQuestion, getIsDirty],isQuestionRunnable,diff --git a/frontend/src/metabase/query_builder/selectors/question.ts b/frontend/src/metabase/query_builder/selectors/question.tsnew file mode 100644index 00000000000..b91562f13e4--- /dev/null+++ b/frontend/src/metabase/query_builder/selectors/question.ts@@ -0,0 +1,74 @@+import { createSelector } from "@reduxjs/toolkit";++import { isSavedQuestionChanged } from "metabase/querying/common/utils/question";+import type { State } from "metabase/redux/store";+import { getMetadata } from "metabase/selectors/metadata";+import * as Lib from "metabase-lib";+import Question from "metabase-lib/v1/Question";++/**+ * The question on screen, and the slice reads it is built from.+ *+ * Separate from `query_builder/selectors` because the app shell reads these on+ * every page, and that module reaches the visualization and querying stacks. Its+ * dependencies here are only metabase-lib and the metadata selector, so an+ * always-mounted component can import it without pulling the query builder into+ * the initial bundle. `query_builder/selectors` re-exports all of it.+ */++// This selector can be called from public questions / dashboards, which do not have state.qb+export const getUiControls = (state: State) => state.qb?.uiControls;++export const getCard = (state: State) => state.qb.card;+export const getOriginalCard = (state: State) => state.qb.originalCard;+export const getParameterValues = (state: State) => state.qb.parameterValues;++export const getQueryBuilderMode = createSelector(+ [getUiControls],+ (uiControls) => uiControls.queryBuilderMode,+);++export const getOriginalQuestion = createSelector(+ [getMetadata, getOriginalCard],+ (metadata, card) =>+ (metadata && card && new Question(card, metadata)) ?? undefined,+);++export const getQuestionWithoutComposing = createSelector(+ [getCard, getMetadata, getParameterValues],+ (card, metadata, parameterValues) => {+ if (!card || !metadata) {+ return;+ }+ return new Question(card, metadata, parameterValues);+ },+);++export const getQuestion = createSelector(+ [getQuestionWithoutComposing, getQueryBuilderMode],+ (question, queryBuilderMode) => {+ if (!question) {+ return;+ }++ const isModel = question.type() === "model";+ const isMetric = question.type() === "metric";+ if ((isModel || isMetric) && queryBuilderMode === "dataset") {+ return isModel ? question.lockDisplay() : question;+ }++ // When opening a model or a metric, we construct a question+ // with a clean, ad-hoc, query.+ // This has to be skipped for users without data permissions.+ // See https://github.com/metabase/metabase/issues/20042+ const composedQuestion =+ isModel || isMetric ? question.composeQuestion() : question;+ const { isEditable } = Lib.queryDisplayInfo(composedQuestion.query());+ return isEditable ? composedQuestion : question;+ },+);++export const getIsSavedQuestionChanged = createSelector(+ [getQuestion, getOriginalQuestion],+ isSavedQuestionChanged,+);diff --git a/frontend/src/metabase/redux/query-builder.ts b/frontend/src/metabase/redux/query-builder.tsindex a4f7933dde0..c2883304e4d 100644--- a/frontend/src/metabase/redux/query-builder.ts+++ b/frontend/src/metabase/redux/query-builder.ts@@ -1,3 +1,12 @@+/**+ * The query builder's action types, and the action creators light enough to sit+ * next to them.+ *+ * The types live here rather than beside their thunks so that+ * `query_builder/reducers.ts` can name them without importing+ * `query_builder/actions`. The store imports that reducer on every page, and+ * anything it reaches is in the initial bundle.+ */import { createAction } from "redux-actions";import { userApi } from "metabase/api";@@ -144,6 +153,35 @@ export const INITIALIZE_QB = "metabase/qb/INITIALIZE_QB";export const ZOOM_IN_ROW = "metabase/qb/ZOOM_IN_ROW";export const RESET_ROW_ZOOM = "metabase/qb/RESET_ROW_ZOOM";+export const API_CREATE_QUESTION = "metabase/qb/API_CREATE_QUESTION";+export const CLEAR_OBJECT_DETAIL_FK_REFERENCES =+ "metabase/qb/CLEAR_OBJECT_DETAIL_FK_REFERENCES";+export const DESELECT_TIMELINE_EVENTS = "metabase/qb/DESELECT_TIMELINE_EVENTS";+export const HIDE_TIMELINE_EVENTS = "metabase/qb/HIDE_TIMELINE_EVENTS";+export const LOAD_OBJECT_DETAIL_FK_REFERENCES =+ "metabase/qb/LOAD_OBJECT_DETAIL_FK_REFERENCES";+export const OPEN_DATA_REFERENCE_AT_QUESTION =+ "metabase/qb/OPEN_DATA_REFERENCE_AT_QUESTION";+export const RELOAD_CARD = "metabase/qb/RELOAD_CARD";+export const SELECT_TIMELINE_EVENTS = "metabase/qb/SELECT_TIMELINE_EVENTS";+export const SET_CARD_AND_RUN = "metabase/qb/SET_CARD_AND_RUN";+export const SET_CURRENT_STATE = "metabase/qb/SET_CURRENT_STATE";+export const SET_DATA_REFERENCE_STACK = "metabase/qb/SET_DATA_REFERENCE_STACK";+export const SET_IS_SHOWING_TEMPLATE_TAGS_EDITOR =+ "metabase/qb/SET_IS_SHOWING_TEMPLATE_TAGS_EDITOR";+export const SET_METADATA_DIFF = "metabase/qb/SET_METADATA_DIFF";+export const SET_MODAL_SNIPPET = "metabase/qb/SET_MODAL_SNIPPET";+export const SET_NATIVE_EDITOR_SELECTED_RANGE =+ "metabase/qb/SET_NATIVE_EDITOR_SELECTED_RANGE";+export const SET_SNIPPET_COLLECTION_ID =+ "metabase/qb/SET_SNIPPET_COLLECTION_ID";+export const SHOW_TIMELINE_EVENTS = "metabase/qb/SHOW_TIMELINE_EVENTS";+export const TOGGLE_DATA_REFERENCE = "metabase/qb/TOGGLE_DATA_REFERENCE";+export const TOGGLE_SNIPPET_SIDEBAR = "metabase/qb/TOGGLE_SNIPPET_SIDEBAR";+export const TOGGLE_TEMPLATE_TAGS_EDITOR =+ "metabase/qb/TOGGLE_TEMPLATE_TAGS_EDITOR";+export const UPDATE_QUESTION = "metabase/qb/UPDATE_QUESTION";+export const CLOSE_QB_NEWB_MODAL = "metabase/qb/CLOSE_QB_NEWB_MODAL";export const closeQbNewbModal = createThunkAction(CLOSE_QB_NEWB_MODAL, () => {return async (dispatch, getState) => {diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsxindex 6b06c8c206f..116e1baacae 100644--- a/frontend/src/metabase/router/RouterProvider.tsx+++ b/frontend/src/metabase/router/RouterProvider.tsx@@ -1,4 +1,4 @@-import { useLayoutEffect, useState } from "react";+import { type ReactNode, useLayoutEffect, useState } from "react";import {type DataRouter,RouterProvider as ReactRouterProvider,@@ -53,9 +53,8 @@ function useLocationMirror(/*** Hosts the app as a data router. The whole route tree goes in as real data- * routes, so there is no descendant `<Routes>` left. No route has a loader,- * `lazy`, or middleware yet: adding those per subtree is what DEV-2291 does from- * here.+ * routes, so there is no descendant `<Routes>` left. Code-split subtrees carry a+ * `route.lazy`; no route has a loader or middleware.** `useTransitions={false}` keeps navigation committing synchronously.* react-router otherwise marks its own location update as a transition, which in@@ -73,12 +72,14 @@ function useLocationMirror(export function RouterProvider({routes,onLocationChange,+ hydrateFallback,}: {routes: RouteObject[];onLocationChange?: LocationMirror;+ hydrateFallback?: ReactNode;}): JSX.Element {const [router] = useState(() =>- createAppRouter(routes, getBasename() || undefined),+ createAppRouter(routes, getBasename() || undefined, hydrateFallback),);useLocationMirror(router, onLocationChange);@@ -97,15 +98,22 @@ export function RouterProviderMemory({basename,routerHolder,onLocationChange,+ hydrateFallback,}: {routes: RouteObject[];initialRoute: string;basename?: string;routerHolder?: MemoryTestRouterHolder;onLocationChange?: LocationMirror;+ hydrateFallback?: ReactNode;}): JSX.Element {const [router] = useState(() => {- const created = createMemoryAppRouter(routes, initialRoute, basename);+ const created = createMemoryAppRouter(+ routes,+ initialRoute,+ basename,+ hydrateFallback,+ );if (routerHolder) {routerHolder.current = created;}diff --git a/frontend/src/metabase/router/create-router.tsx b/frontend/src/metabase/router/create-router.tsxindex c9412f89c48..0c5b4ee6d90 100644--- a/frontend/src/metabase/router/create-router.tsx+++ b/frontend/src/metabase/router/create-router.tsx@@ -1,3 +1,4 @@+import type { ReactNode } from "react";import {type DataRouter,type RouteObject,@@ -22,31 +23,50 @@ export type MemoryTestRouterHolder = { current: MemoryTestRouter | null };* The layout route contributes no path, so it changes no matching. It exists so* relative redux navigation resolves from the root (see `AppShell`) and as the* seat for anything the app shell needs above the route tree.+ *+ * `hydrateFallback` is what the router shows before it initializes. That window+ * is empty unless the first URL matches a `lazy` route, in which case the whole+ * tree, chrome included, waits on the chunk. Without a fallback the page is+ * blank for that time. The router cannot build one itself, so the app passes it+ * in.*/-function withAppShell(routes: RouteObject[]): RouteObject[] {+function withAppShell(+ routes: RouteObject[],+ hydrateFallback?: ReactNode,+): RouteObject[] {// Every router this module builds gets an `AppShell`, and every `AppShell`// registers a `navigate`. That is what lets the navigator hold a navigation// made before the registration, knowing one is coming.setRouterExpected(true);- return [{ element: <AppShell />, children: routes }];+ return [+ {+ element: <AppShell />,+ hydrateFallbackElement: hydrateFallback,+ children: routes,+ },+ ];}export function createAppRouter(routes: RouteObject[],basename?: string,+ hydrateFallback?: ReactNode,): DataRouter {- return createBrowserRouter(withAppShell(routes), { basename });+ return createBrowserRouter(withAppShell(routes, hydrateFallback), {+ basename,+ });}export function createMemoryAppRouter(routes: RouteObject[],initialRoute: string,basename?: string,+ hydrateFallback?: ReactNode,): DataRouter {const entry = initialRoute.startsWith("/")? initialRoute: `/${initialRoute}`;- return createMemoryRouter(withAppShell(routes), {+ return createMemoryRouter(withAppShell(routes, hydrateFallback), {basename,initialEntries: [entry],});diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.tsindex 7024158434c..41903b07649 100644--- a/frontend/src/metabase/router/index.ts+++ b/frontend/src/metabase/router/index.ts@@ -13,11 +13,13 @@ export {useSearchParams,} from "react-router";export * from "./use-navigate";+export * from "./prefetch";export * from "./redirect";export * from "./to-route-objects";export * from "./location-change";export * from "./RouterProvider";export * from "./types";+export * from "./use-is-navigating";export * from "./use-maybe-location";export * from "./use-route-leave-blocker";export {diff --git a/frontend/src/metabase/router/lazy-route.unit.spec.tsx b/frontend/src/metabase/router/lazy-route.unit.spec.tsxnew file mode 100644index 00000000000..192141ae680--- /dev/null+++ b/frontend/src/metabase/router/lazy-route.unit.spec.tsx@@ -0,0 +1,131 @@+import { render, renderRoutes, screen } from "__support__/ui";+import { type RouteObject, RouterProviderMemory } from "metabase/router";++function Home() {+ return <span data-testid="home">home</span>;+}++function Split() {+ return <span data-testid="split">split</span>;+}++function makeRoutes(): RouteObject[] {+ return [+ { path: "/", element: <Home /> },+ { path: "/split", lazy: async () => ({ Component: Split }) },+ ];+}++/**+ * Navigation is synchronous while no route is `lazy`: react-router commits the+ * location without awaiting anything. A `lazy` route breaks that for its own+ * first visit, which is the behavior every code-split subtree buys into. These+ * pin how far the change reaches.+ */+describe("a lazy route", () => {+ it("defers the location until the module resolves", async () => {+ const { router } = renderRoutes(makeRoutes(), { initialRoute: "/" });++ const seen: string[] = [];+ const unsubscribe = router?.onLocationChange(({ pathname }) =>+ seen.push(pathname),+ );++ router?.navigate("/split");++ expect(router?.location.pathname).toBe("/");+ expect(seen).toEqual([]);++ expect(await screen.findByTestId("split")).toBeInTheDocument();+ expect(router?.location.pathname).toBe("/split");+ expect(seen).toEqual(["/split"]);++ unsubscribe?.();+ });++ it("keeps the previous page mounted while the module loads", async () => {+ const { router } = renderRoutes(makeRoutes(), { initialRoute: "/" });++ router?.navigate("/split");++ expect(screen.getByTestId("home")).toBeInTheDocument();+ expect(await screen.findByTestId("split")).toBeInTheDocument();+ });++ // The router does not initialize until the first URL's match resolves, so a+ // deep link into a split subtree has no tree to render at all, chrome+ // included. The app passes a fallback for exactly that window.+ it("shows the hydrate fallback on a deep link, then the page", async () => {+ render(+ <RouterProviderMemory+ routes={makeRoutes()}+ initialRoute="/split"+ hydrateFallback={<span data-testid="hydrating">loading</span>}+ />,+ );++ expect(screen.getByTestId("hydrating")).toBeInTheDocument();+ expect(await screen.findByTestId("split")).toBeInTheDocument();+ expect(screen.queryByTestId("hydrating")).not.toBeInTheDocument();+ });++ // The sharp edge of deferring the location. A second navigation arriving+ // before the module resolves does not queue behind the first, it replaces it,+ // and the destination the user asked for is dropped with no trace. Anything+ // that navigates on a timer or from an effect has to sit this window out:+ // `useDashboardUrlQuery` skips its URL sync on `useIsNavigating` for exactly+ // this reason.+ it("drops a pending navigation if another one lands first", async () => {+ const { router } = renderRoutes(makeRoutes(), { initialRoute: "/" });++ router?.navigate("/split");+ router?.navigate("/");++ await new Promise((resolve) => setTimeout(resolve, 50));++ expect(router?.location.pathname).toBe("/");+ expect(screen.getByTestId("home")).toBeInTheDocument();+ expect(screen.queryByTestId("split")).not.toBeInTheDocument();+ });++ // What prefetching on hover buys, and what it does not. The module is already+ // in hand, so the gap is a tick rather than a round trip, but the router still+ // awaits `lazy` and still commits the location late.+ it("defers the location even when the module is already loaded", async () => {+ const load = jest.fn().mockResolvedValue({ Component: Split });+ const { router } = renderRoutes(+ [+ { path: "/", element: <Home /> },+ {+ path: "/split",+ lazy: load,+ },+ ],+ { initialRoute: "/" },+ );++ await load();++ router?.navigate("/split");+ expect(router?.location.pathname).toBe("/");++ expect(await screen.findByTestId("split")).toBeInTheDocument();+ expect(router?.location.pathname).toBe("/split");+ });++ // react-router resolves `lazy` onto the route object itself, so the cost is+ // paid once per chunk rather than on every navigation into the subtree.+ it("is synchronous again on the second visit", async () => {+ const { router } = renderRoutes(makeRoutes(), { initialRoute: "/" });++ router?.navigate("/split");+ expect(await screen.findByTestId("split")).toBeInTheDocument();++ router?.navigate("/");+ expect(await screen.findByTestId("home")).toBeInTheDocument();++ router?.navigate("/split");++ expect(router?.location.pathname).toBe("/split");+ });+});diff --git a/frontend/src/metabase/router/prefetch.ts b/frontend/src/metabase/router/prefetch.tsnew file mode 100644index 00000000000..2662bb9daae--- /dev/null+++ b/frontend/src/metabase/router/prefetch.ts@@ -0,0 +1,47 @@+type LoadPage = () => Promise<unknown>;++type Registration = {+ pathPrefix: string;+ load: LoadPage;+ isStarted: boolean;+};++const registrations: Registration[] = [];++/**+ * Ask for a code-split page to be fetched before the user navigates to it.+ *+ * A page in its own chunk is only requested once its route renders, so the user+ * waits for the network right after they click. A link to it under the pointer+ * is a good signal that the click is coming, and acting on it buys most of that+ * time back.+ *+ * `pathPrefix` matches the start of a link's target, so one registration covers+ * a page and everything below it. Two pages may register the same prefix, which+ * is what a route that renders one page or another depending on the license+ * needs.+ */+export function registerPagePrefetch(pathPrefix: string, load: LoadPage): void {+ registrations.push({ pathPrefix, load, isStarted: false });+}++/**+ * Start fetching whatever `path` needs, if anything registered for it.+ *+ * Safe to call on every hover: each page is only asked for once, and the bundler+ * hands the same module promise to the render that follows. A failed fetch is+ * forgotten rather than reported, so the navigation asks again and can show the+ * error where the user is looking.+ */+export function prefetchPage(path: string): void {+ for (const registration of registrations) {+ if (registration.isStarted || !path.startsWith(registration.pathPrefix)) {+ continue;+ }++ registration.isStarted = true;+ registration.load().catch(() => {+ registration.isStarted = false;+ });+ }+}diff --git a/frontend/src/metabase/router/prefetch.unit.spec.ts b/frontend/src/metabase/router/prefetch.unit.spec.tsnew file mode 100644index 00000000000..c9f1340b7e2--- /dev/null+++ b/frontend/src/metabase/router/prefetch.unit.spec.ts@@ -0,0 +1,84 @@+import { prefetchPage, registerPagePrefetch } from "./prefetch";++// The registry is module state that no test can clear, so every test registers+// its own path. That is closer to how the app uses it anyway: registration+// happens once, when a routes module is first imported.+let nextId = 0;+const uniquePath = () => `/prefetch-spec-${nextId++}`;++describe("prefetchPage", () => {+ it("loads a page whose prefix matches", () => {+ const path = uniquePath();+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ prefetchPage(path);++ expect(load).toHaveBeenCalledTimes(1);+ });++ it("matches anything below the registered prefix", () => {+ const path = uniquePath();+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ prefetchPage(`${path}/42`);++ expect(load).toHaveBeenCalledTimes(1);+ });++ it("leaves an unrelated path alone", () => {+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(uniquePath(), load);++ prefetchPage(uniquePath());++ expect(load).not.toHaveBeenCalled();+ });++ it("asks for a page once however often it is hovered", () => {+ const path = uniquePath();+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ prefetchPage(path);+ prefetchPage(path);+ prefetchPage(`${path}/42`);++ expect(load).toHaveBeenCalledTimes(1);+ });++ // A route that renders one page or another depending on the license registers+ // both against the same path.+ it("loads every page registered for the same prefix", () => {+ const path = uniquePath();+ const first = jest.fn().mockResolvedValue(undefined);+ const second = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, first);+ registerPagePrefetch(path, second);++ prefetchPage(path);++ expect(first).toHaveBeenCalledTimes(1);+ expect(second).toHaveBeenCalledTimes(1);+ });++ // Nothing renders a prefetch failure, so the next hover has to be able to try+ // again. Otherwise one dropped request leaves the page unfetchable ahead of+ // time for the rest of the session.+ it("retries after a failed load", async () => {+ const path = uniquePath();+ const load = jest+ .fn()+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ prefetchPage(path);+ await Promise.resolve();++ prefetchPage(path);++ expect(load).toHaveBeenCalledTimes(2);+ });+});diff --git a/frontend/src/metabase/router/use-is-navigating.ts b/frontend/src/metabase/router/use-is-navigating.tsnew file mode 100644index 00000000000..e5a56ab4ecd--- /dev/null+++ b/frontend/src/metabase/router/use-is-navigating.ts@@ -0,0 +1,29 @@+import { useContext } from "react";+import { UNSAFE_NavigationContext, useNavigation } from "react-router";++/**+ * Whether the router is part-way through a navigation it has not committed yet.+ *+ * A `route.lazy` route resolves its module before committing the location, which+ * opens a window where the old page is still mounted at the old URL while the+ * router is already on its way somewhere else. Anything that navigates in that+ * window replaces the pending navigation rather than queueing behind it, and the+ * destination the user asked for is lost.+ *+ * Effects that keep a URL in sync with state have to sit that window out. See+ * `useDashboardUrlQuery`, which already does the same for a navigation held by a+ * leave prompt.+ *+ * Returns `false` outside a router, where nothing can be pending. Much of the app+ * is shared with the SDK, which mounts none (see `useMaybeLocation`).+ */+export function useIsNavigating(): boolean {+ const hasRouter = useContext(UNSAFE_NavigationContext) != null;++ // react-router's hook throws when there is no router, so it can only be called+ // on the branch that has one. Safe despite the rule: a router appearing above a+ // mounted component would change the tree shape and remount it, so `hasRouter`+ // cannot flip between renders of the same mount.+ // eslint-disable-next-line react-hooks/rules-of-hooks+ return hasRouter ? useNavigation().state !== "idle" : false;+}diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsxindex 4f35553e464..580cef25414 100644--- a/frontend/src/metabase/routes.tsx+++ b/frontend/src/metabase/routes.tsx@@ -51,9 +51,7 @@ import {PLUGIN_TABLE_EDITING,PLUGIN_TENANTS,} from "metabase/plugins";-import { MetabotQueryBuilder } from "metabase/query_builder/components/MetabotQueryBuilder";import { QuestionHashRedirect } from "metabase/query_builder/components/QuestionHashRedirect";-import { QueryBuilder } from "metabase/query_builder/containers/QueryBuilder";import type { State } from "metabase/redux/store";import DatabaseDetailContainer from "metabase/reference/databases/DatabaseDetailContainer";import DatabaseListContainer from "metabase/reference/databases/DatabaseListContainer";@@ -80,6 +78,7 @@ import {Navigate,type RouteObject,redirect,+ registerPagePrefetch,toRouteObjects,useParams,} from "metabase/router";@@ -113,6 +112,40 @@ export function LegacyBrowseRedirect() {return <Navigate to={`/browse/databases/${dbIdAndSlug}`} replace />;}+/**+ * The query builder, in its own chunk. Every route that renders it names the+ * same `import()`, so they share one chunk that is fetched the first time one of+ * them is visited.+ *+ * A `lazy` route makes that first navigation asynchronous: the router resolves+ * the module before it commits the location. It resolves the route in place, so+ * every later navigation to the query builder is synchronous again.+ */+const queryBuilder = () =>+ import("metabase/query_builder/containers/QueryBuilder").then(+ ({ QueryBuilder }) => ({ Component: QueryBuilder }),+ );++const metabotQueryBuilder = () =>+ import("metabase/query_builder/components/MetabotQueryBuilder").then(+ ({ MetabotQueryBuilder }) => ({ Component: MetabotQueryBuilder }),+ );++/**+ * Hovering a link into the query builder starts the fetch, so the chunk is+ * usually in hand by the time the click lands. The router still awaits `lazy`+ * and still commits the location a tick late, so this removes the round trip+ * rather than the asynchrony. See `lazy-route.unit.spec.tsx`.+ *+ * The paths are prefixes, so `/table/` also covers the table detail page, which+ * is not the query builder. The chunk is fetched once either way, and someone+ * looking at a table row is a fair bet to open a question next.+ */+registerPagePrefetch("/question", queryBuilder);+registerPagePrefetch("/model", queryBuilder);+registerPagePrefetch("/table/", queryBuilder);+registerPagePrefetch("/question/ask", metabotQueryBuilder);+export const getRoutes = (store: AppStore): RouteObject[] => [{element: <App />,@@ -301,14 +334,14 @@ export const getRoutes = (store: AppStore): RouteObject[] => [],}),},- { index: true, element: <QueryBuilder /> },- { path: "notebook", element: <QueryBuilder /> },- { path: "ask", element: <MetabotQueryBuilder /> },+ { index: true, lazy: queryBuilder },+ { path: "notebook", lazy: queryBuilder },+ { path: "ask", lazy: metabotQueryBuilder },...toRouteObjects(getExplorationsRoutes()),- { path: ":slug", element: <QueryBuilder /> },- { path: ":slug/notebook", element: <QueryBuilder /> },- { path: ":slug/metabot", element: <QueryBuilder /> },- { path: ":slug/:objectId", element: <QueryBuilder /> },+ { path: ":slug", lazy: queryBuilder },+ { path: ":slug/notebook", lazy: queryBuilder },+ { path: ":slug/metabot", lazy: queryBuilder },+ { path: ":slug/:objectId", lazy: queryBuilder },],},@@ -318,17 +351,17 @@ export const getRoutes = (store: AppStore): RouteObject[] => [{path: "/model",children: [- { index: true, element: <QueryBuilder /> },+ { index: true, lazy: queryBuilder },{ path: "new", element: <NewModelOptions /> },- { path: ":slug", element: <QueryBuilder /> },- { path: ":slug/notebook", element: <QueryBuilder /> },- { path: ":slug/query", element: <QueryBuilder /> },- { path: ":slug/columns", element: <QueryBuilder /> },- { path: ":slug/metadata", element: <QueryBuilder /> },- { path: ":slug/metabot", element: <QueryBuilder /> },- { path: ":slug/:objectId", element: <QueryBuilder /> },- { path: "query", element: <QueryBuilder /> },- { path: "metabot", element: <QueryBuilder /> },+ { path: ":slug", lazy: queryBuilder },+ { path: ":slug/notebook", lazy: queryBuilder },+ { path: ":slug/query", lazy: queryBuilder },+ { path: ":slug/columns", lazy: queryBuilder },+ { path: ":slug/metadata", lazy: queryBuilder },+ { path: ":slug/metabot", lazy: queryBuilder },+ { path: ":slug/:objectId", lazy: queryBuilder },+ { path: "query", lazy: queryBuilder },+ { path: "metabot", lazy: queryBuilder },],},@@ -371,7 +404,7 @@ export const getRoutes = (store: AppStore): RouteObject[] => [{path: "table",children: [- { path: ":slug", element: <QueryBuilder /> },+ { path: ":slug", lazy: queryBuilder },{path: ":tableId/detail/:rowId",element: <TableDetailPage />,