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
Load CodeMirror editors lazily so they leave the initial bundle (#79809)
Romeo Van Snick16906d4383aa
diff --git a/e2e/support/helpers/e2e-codemirror-helpers.ts b/e2e/support/helpers/e2e-codemirror-helpers.tsindex 1166b350f1d..c7c96f9531d 100644--- a/e2e/support/helpers/e2e-codemirror-helpers.ts+++ b/e2e/support/helpers/e2e-codemirror-helpers.ts@@ -45,6 +45,11 @@ export function codeMirrorHelpers<T extends object>(testId: string, extra: T) {) {if (focus) {helpers.focus();+ } else {+ // The editor can be a lazily loaded chunk, so it may still be mounting.+ // Wait for it to hold focus before typing, or the first keystroke goes+ // nowhere. Do not click it: that would move the caret.+ helpers.get().get(".cm-editor").should("have.class", "cm-focused");}if (allowFastSet) {@@ -148,21 +153,19 @@ export function codeMirrorHelpers<T extends object>(testId: string, extra: T) {return helpers.get().get("[role='textbox']");},value() {- // Get the multiline text content of the editor- return helpers- .textbox()- .get(".cm-line")- .then((lines) => {- const text: string[] = [];- lines.each((_, line) => {- const placeholder = line.querySelector(".cm-placeholder");- if (placeholder) {- return;- }- text.push(line.textContent ?? "");- });- return text.join("\n");- });+ // The editor mounts with an empty document and fills it in when the first+ // format finishes. It can also mount late, because its chunk loads on+ // demand. Wait for two identical reads before reporting the value, or a+ // read that lands in either window reports an empty editor.+ let previous: string | null = null;+ cy.get(`[data-testid=${testId}] .cm-content`).should(($content) => {+ const current = textOf($content);+ const isStable = previous !== null && current === previous;+ previous = current;+ expect(isStable, "the editor text is stable").to.be.true;+ });++ return helpers.get().then(textOf);},completions() {return cy.get(".cm-tooltip-autocomplete").should("be.visible");@@ -233,3 +236,18 @@ export function codeMirrorValue() {return value;});}++/**+ * The text of every line in a CodeMirror editor, skipping the placeholder line+ * that stands in for an empty document.+ */+function textOf($content: JQuery<HTMLElement>) {+ const text: string[] = [];+ $content.find(".cm-line").each((_, line) => {+ if (line.querySelector(".cm-placeholder")) {+ return;+ }+ text.push(line.textContent ?? "");+ });+ return text.join("\n");+}diff --git a/e2e/test/scenarios/actions/model-actions.cy.spec.js b/e2e/test/scenarios/actions/model-actions.cy.spec.jsindex ecab205a9d8..6748c2ee1e0 100644--- a/e2e/test/scenarios/actions/model-actions.cy.spec.js+++ b/e2e/test/scenarios/actions/model-actions.cy.spec.js@@ -846,7 +846,9 @@ function assertQueryEditorDisabled() {H.NativeEditor.get().should("not.be.focused");H.NativeEditor.get().should("have.attr", "contenteditable", "false");- H.NativeEditor.type("QWERTY", { focus: false });+ // Type straight into the page: the editor helper waits for focus, and this+ // editor is read only, so it never takes it.+ cy.realType("QWERTY");cy.findByText("QWERTY").should("not.exist");}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsxindex 96bc7adc8bd..e8c18ca75b7 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx@@ -15,7 +15,7 @@ import { PythonEditor } from "../../PythonEditor";import { ResizableBoxHandle } from "./ResizableBoxHandle";import { createPythonImportTokenLocator } from "./utils";-type PythonEditorBodyProps = {+export type PythonEditorBodyProps = {disabled?: boolean;source: string;proposedSource?: string;diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/index.tsindex 1f7cef4b142..e7bc6274e1e 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/index.ts@@ -1 +1,2 @@-export * from "./PythonEditorBody";+export { PythonEditorBody } from "./PythonEditorBody";+export type { PythonEditorBodyProps } from "./PythonEditorBody";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/lazy.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/lazy.tsxnew file mode 100644index 00000000000..88ea9abad24--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/lazy.tsx@@ -0,0 +1,21 @@+import { Suspense, lazy } from "react";++import type { PythonTransformEditorProps } from "metabase/plugins";++// The plugin registry holds this component from boot, so registering the real+// one would put the Python editor and its CodeMirror extensions in the initial+// bundle no matter which route the user is on. The registry holds this stand-in+// instead, and the editor loads when a Python transform is actually opened.+const LazyPythonTransformEditor = lazy(() =>+ import("./PythonTransformEditor").then(({ PythonTransformEditor }) => ({+ default: PythonTransformEditor,+ })),+);++export function PythonTransformEditor(props: PythonTransformEditorProps) {+ return (+ <Suspense fallback={null}>+ <LazyPythonTransformEditor {...props} />+ </Suspense>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsxindex ef843757c84..77f44d64492 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx@@ -1,7 +1,7 @@import { PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";import { hasPremiumFeature } from "metabase-enterprise/settings";-import { PythonTransformEditor } from "./components/PythonTransformEditor";+import { PythonTransformEditor } from "./components/PythonTransformEditor/lazy";import { SHARED_LIB_IMPORT_PATH } from "./constants";import { PythonRunnerSettingsPage } from "./pages/PythonRunnerSettingsPage";import { getPythonTransformsRoutes, getPythonUpsellRoutes } from "./routes";diff --git a/frontend/build/shared/rspack/side-effect-free-modules.js b/frontend/build/shared/rspack/side-effect-free-modules.jsindex fd12696532e..7ef0ea9d4ba 100644--- a/frontend/build/shared/rspack/side-effect-free-modules.js+++ b/frontend/build/shared/rspack/side-effect-free-modules.js@@ -26,6 +26,10 @@ const SIDE_EFFECT_FREE_PATHS = [// Trailing separator: rspack prefix-matches `include`, so a bare directory path// would also claim a sibling like `router-utils.ts` or a future `router-v8/`.path.join(REPO_ROOT, "frontend/src/metabase/router") + path.sep,+ // The expression language: its barrel re-exports the autocomplete sources and+ // the lezer tokenizer, so a picker importing only `getClauseDefinition` from it+ // would otherwise pull CodeMirror into the initial bundle.+ path.join(REPO_ROOT, "frontend/src/metabase/querying/expressions") + path.sep,];const SIDE_EFFECT_FREE_RULE = {diff --git a/frontend/src/metabase/common/components/CodeEditor/CodeEditor.tsx b/frontend/src/metabase/common/components/CodeEditor/CodeEditor.tsxindex eb30f4077bb..40b4ac87bfe 100644--- a/frontend/src/metabase/common/components/CodeEditor/CodeEditor.tsx+++ b/frontend/src/metabase/common/components/CodeEditor/CodeEditor.tsx@@ -6,7 +6,7 @@ import { CodeMirror } from "metabase/common/components/CodeMirror";import type { CodeLanguage } from "./types";import { useExtensions } from "./utils";-type Props = {+export type CodeEditorProps = {className?: string;highlightRanges?: { start: number; end: number }[];id?: string;@@ -32,7 +32,7 @@ export function CodeEditor({onChange,extensions: externalExtensions,...rest-}: Props) {+}: CodeEditorProps) {const extensions = useExtensions({language,extensions: externalExtensions,diff --git a/frontend/src/metabase/common/components/CodeEditor/index.ts b/frontend/src/metabase/common/components/CodeEditor/index.tsindex 67db40cb179..187b5a6523b 100644--- a/frontend/src/metabase/common/components/CodeEditor/index.ts+++ b/frontend/src/metabase/common/components/CodeEditor/index.ts@@ -1,2 +1,3 @@-export * from "./CodeEditor";+export { CodeEditor } from "./lazy";+export type { CodeEditorProps } from "./CodeEditor";export type { CodeLanguage } from "./types";diff --git a/frontend/src/metabase/common/components/CodeEditor/lazy.tsx b/frontend/src/metabase/common/components/CodeEditor/lazy.tsxnew file mode 100644index 00000000000..77ecf89467e--- /dev/null+++ b/frontend/src/metabase/common/components/CodeEditor/lazy.tsx@@ -0,0 +1,35 @@+import { Suspense, lazy } from "react";++import type { CodeEditorProps } from "./CodeEditor";++// CodeMirror and its language modes are among the largest dependencies in the+// app bundle. Loading the editor lazily keeps all of them out of the initial+// page load, since no route renders a code editor on first paint.+//+// Nothing renders while it loads. The chunk is shared and cached after its first+// use, so only the first editor in a session waits, and showing the code+// uncoloured for that moment reads as a glitch rather than as progress.+const importCodeEditor = () =>+ import(+ /* webpackChunkName: "code-editor" */+ "./CodeEditor"+ );++/**+ * The editor's chunk, for a caller that wants it in hand before it renders.+ * A `route.lazy` loader can await this so its page or modal only appears once+ * the editor is ready, rather than appearing with an empty editor area.+ */+export const loadCodeEditor = () => importCodeEditor();++const LazyCodeEditor = lazy(() =>+ importCodeEditor().then(({ CodeEditor }) => ({ default: CodeEditor })),+);++export function CodeEditor(props: CodeEditorProps) {+ return (+ <Suspense fallback={null}>+ <LazyCodeEditor {...props} />+ </Suspense>+ );+}diff --git a/frontend/src/metabase/common/components/ModalRoute.tsx b/frontend/src/metabase/common/components/ModalRoute.tsxindex 5245ee37cb2..ab936b9452e 100644--- a/frontend/src/metabase/common/components/ModalRoute.tsx+++ b/frontend/src/metabase/common/components/ModalRoute.tsx@@ -46,6 +46,27 @@ export function modalRoute(return <Route key={path} path={path} element={<ModalRouteComponent />} />;}+/**+ * `modalRoute` for a modal that lives in a code-split chunk, for a route tree+ * still authored as `<Route>` elements. `createRoutesFromElements` reads `lazy`+ * off the element, so this defers the modal without the tree having to convert.+ */+export function lazyModalRouteElement(+ path: string,+ loadModal: () => Promise<ModalComponent>,+ options: ModalRouteOptions = {},+) {+ return (+ <Route+ key={path}+ path={path}+ lazy={async () => ({+ Component: createModalRouteComponent(await loadModal(), options),+ })}+ />+ );+}+/*** `modalRoute` for a modal that lives in a code-split chunk.*diff --git a/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsx b/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsxindex 22e27fcc75e..3a877763cad 100644--- a/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsx+++ b/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsx@@ -1,5 +1,5 @@import type { FormikHelpers } from "formik";-import { useCallback, useState } from "react";+import { startTransition, useCallback, useEffect, useState } from "react";import ActionParametersInputForm, {ActionParametersInputModal,@@ -8,7 +8,10 @@ import { useActionInitialValues } from "metabase/actions/hooks/use-action-initiaimport { getFormTitle, isImplicitUpdateAction } from "metabase/actions/utils";import { actionApi, publicApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";-import { ActionCreator } from "metabase/querying/action-creator";+import {+ ActionCreator,+ loadActionCreator,+} from "metabase/querying/action-creator";import { useDispatch } from "metabase/redux";import { Modal, PREVENT_AUTOCOMPLETE_CLIPPING_MODAL_PROPS } from "metabase/ui";import { getDashboardType } from "metabase/utils/dashboard";@@ -62,6 +65,13 @@ function ActionVizForm({const dispatch = useDispatch();const [showFormModal, setShowFormModal] = useState(false);const [showEditModal, setShowEditModal] = useState(false);++ // The action editor is a separate chunk. Fetching it up front, and opening in+ // a transition, keeps this card on screen until the editor is ready so the+ // modal opens complete rather than empty.+ useEffect(() => {+ loadActionCreator();+ }, []);const title = getFormTitle(action);// only show confirmation if there are no missing parameters@@ -81,7 +91,9 @@ function ActionVizForm({};const handleActionEdit = () => {- setShowEditModal(true);+ startTransition(() => {+ setShowEditModal(true);+ });};const closeEditModal = () => {diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.tsxindex b11f3a375a0..320035ac786 100644--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.tsx+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentSuggestionMessage.tsx@@ -1,14 +1,11 @@-import { unifiedMergeView } from "@codemirror/merge";import { useDisclosure } from "@mantine/hooks";import cx from "classnames";-import { useContext, useMemo, useState } from "react";+import { useContext, useEffect, useState } from "react";import { useLocation, useMount } from "react-use";import { P, match } from "ts-pattern";import { t } from "ttag";-import _ from "underscore";import { useLazyGetTransformQuery } from "metabase/api";-import { CodeMirror } from "metabase/common/components/CodeMirror";import { MetabotContext } from "metabase/metabot/context";import {type MetabotAgentDataPartMessage,@@ -17,7 +14,6 @@ import {getIsSuggestedTransformActive,} from "metabase/metabot/state";import { useMetadataToasts } from "metabase/metadata/hooks";-import EditorS from "metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.module.css";import { useDispatch, useSelector } from "metabase/redux";import { useNavigate } from "metabase/router";import { getMetadata } from "metabase/selectors/metadata";@@ -42,49 +38,15 @@ import type {} from "metabase-types/api";import S from "./MetabotAgentSuggestionMessage.module.css";+import {+ SuggestionPreviewContent,+ loadSuggestionPreview,+} from "./lazySuggestionPreviewContent";export type SuggestionMessage = Omit<MetabotAgentDataPartMessage, "part"> & {part: Extract<MetabotDataPart, { type: "data-transform_suggestion" }>;};-const PreviewContent = ({- oldSource,- newSource,-}: {- oldSource: string;- newSource: string;-}) => {- const extensions = useMemo(- () =>- _.compact([- oldSource &&- unifiedMergeView({- original: oldSource,- mergeControls: false,- collapseUnchanged: {- margin: 1,- minSize: 1,- },- }),- ]),- [oldSource],- );-- return (- <CodeMirror- className={cx(- EditorS.editor,- S.suggestionEditor,- !oldSource && S.suggestionEditorOnlyNew,- )}- extensions={extensions}- value={newSource}- readOnly- autoCorrect="off"- />- );-};-const useGetOldTransform = ({editorTransform,suggestedTransform,@@ -164,6 +126,21 @@ export const AgentSuggestionMessage = ({error,} = useGetOldTransform({ editorTransform, suggestedTransform });+ // The preview is a separate chunk. Waiting for it inside the existing+ // "Loading preview" state means one loading state rather than two in a row.+ const [isPreviewLoaded, setIsPreviewLoaded] = useState(false);+ useEffect(() => {+ let cancelled = false;+ loadSuggestionPreview().then(() => {+ if (!cancelled) {+ setIsPreviewLoaded(true);+ }+ });+ return () => {+ cancelled = true;+ };+ }, []);+const oldSource = originalTransform? getSourceCode(originalTransform, metadata): "";@@ -227,7 +204,7 @@ export const AgentSuggestionMessage = ({transitionDuration={0}transitionTimingFunction="linear">- {match({ isLoading, error })+ {match({ isLoading: isLoading || !isPreviewLoaded, error }).with({ error: P.not(P.nullish) }, () => (<Flexp="md"@@ -255,7 +232,10 @@ export const AgentSuggestionMessage = ({</Flex>)).with({ isLoading: false }, () => (- <PreviewContent oldSource={oldSource} newSource={newSource} />+ <SuggestionPreviewContent+ oldSource={oldSource}+ newSource={newSource}+ />)).exhaustive()}diff --git a/frontend/src/metabase/metabot/components/MetabotChat/SuggestionPreviewContent.tsx b/frontend/src/metabase/metabot/components/MetabotChat/SuggestionPreviewContent.tsxnew file mode 100644index 00000000000..fffe3d40ddc--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotChat/SuggestionPreviewContent.tsx@@ -0,0 +1,49 @@+import { unifiedMergeView } from "@codemirror/merge";+import cx from "classnames";+import { useMemo } from "react";+import _ from "underscore";++import { CodeMirror } from "metabase/common/components/CodeMirror";+import EditorS from "metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.module.css";++import S from "./MetabotAgentSuggestionMessage.module.css";++export type SuggestionPreviewContentProps = {+ oldSource: string;+ newSource: string;+};++export const SuggestionPreviewContent = ({+ oldSource,+ newSource,+}: SuggestionPreviewContentProps) => {+ const extensions = useMemo(+ () =>+ _.compact([+ oldSource &&+ unifiedMergeView({+ original: oldSource,+ mergeControls: false,+ collapseUnchanged: {+ margin: 1,+ minSize: 1,+ },+ }),+ ]),+ [oldSource],+ );++ return (+ <CodeMirror+ className={cx(+ EditorS.editor,+ S.suggestionEditor,+ !oldSource && S.suggestionEditorOnlyNew,+ )}+ extensions={extensions}+ value={newSource}+ readOnly+ autoCorrect="off"+ />+ );+};diff --git a/frontend/src/metabase/metabot/components/MetabotChat/lazySuggestionPreviewContent.tsx b/frontend/src/metabase/metabot/components/MetabotChat/lazySuggestionPreviewContent.tsxnew file mode 100644index 00000000000..6248903352d--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotChat/lazySuggestionPreviewContent.tsx@@ -0,0 +1,33 @@+import { Suspense, lazy } from "react";++import type { SuggestionPreviewContentProps } from "./SuggestionPreviewContent";++// Metabot chat mounts with the app shell, but this diff preview only renders+// once the user expands a suggested transform. Keeping it lazy keeps CodeMirror+// out of the initial bundle.+const importSuggestionPreviewContent = () =>+ import(+ /* webpackChunkName: "metabot-suggestion-preview" */+ "./SuggestionPreviewContent"+ );++/**+ * The preview's chunk. The message folds this into its own "Loading preview"+ * state, so the diff waits on the data and the chunk together rather than+ * showing a second spinner once the data arrives.+ */+export const loadSuggestionPreview = () => importSuggestionPreviewContent();++const LazySuggestionPreviewContent = lazy(() =>+ importSuggestionPreviewContent().then(({ SuggestionPreviewContent }) => ({+ default: SuggestionPreviewContent,+ })),+);++export const SuggestionPreviewContent = (+ props: SuggestionPreviewContentProps,+) => (+ <Suspense fallback={null}>+ <LazySuggestionPreviewContent {...props} />+ </Suspense>+);diff --git a/frontend/src/metabase/models/routes.tsx b/frontend/src/metabase/models/routes.tsxindex a2b3f8c268d..72b3ef2598b 100644--- a/frontend/src/metabase/models/routes.tsx+++ b/frontend/src/metabase/models/routes.tsx@@ -1,17 +1,20 @@-import { modalRoute } from "metabase/common/components/ModalRoute";+import { lazyModalRouteElement } from "metabase/common/components/ModalRoute";import ModelActions from "metabase/models/containers/ModelActions/ModelActions";+import { loadActionCreator } from "metabase/querying/action-creator";import { Route, redirect } from "metabase/router";import {type ModalProps,PREVENT_AUTOCOMPLETE_CLIPPING_MODAL_PROPS,} from "metabase/ui";-import ActionCreatorModal from "./containers/ActionCreatorModal/ActionCreatorModal";+// The action editor is a separate chunk. The loader awaits it so the modal only+// opens once the editor is ready, instead of opening around a loading state.+const actionCreatorModal = () =>+ Promise.all([+ import("./containers/ActionCreatorModal/ActionCreatorModal"),+ loadActionCreator(),+ ]).then(([{ default: ActionCreatorModal }]) => ActionCreatorModal);-/**- * The action pages stay eager: `modalRoute` takes a component rather than a- * loader, so deferring them needs more than a route change.- */const modelDetailPage = () =>import(/* webpackChunkName: "model-detail" */ "metabase/detail-view/pages/ModelDetailPage/ModelDetailPage"@@ -25,8 +28,8 @@ export const getRoutes = () => {return (<Route path="/model/:slug/detail"><Route path="actions" element={<ModelActions />}>- {modalRoute("new", ActionCreatorModal, { modalProps })}- {modalRoute(":actionId", ActionCreatorModal, { modalProps })}+ {lazyModalRouteElement("new", actionCreatorModal, { modalProps })}+ {lazyModalRouteElement(":actionId", actionCreatorModal, { modalProps })}</Route><Route path=":rowId" lazy={modelDetailPage} /><Route index element={redirect("actions")} />diff --git a/frontend/src/metabase/models/routes.unit.spec.tsx b/frontend/src/metabase/models/routes.unit.spec.tsxindex 7801369da93..78284e16802 100644--- a/frontend/src/metabase/models/routes.unit.spec.tsx+++ b/frontend/src/metabase/models/routes.unit.spec.tsx@@ -6,7 +6,7 @@ describe("model routes", () => {it("resolves every page", async () => {const loaders = lazyLoaders(getRoutes());- expect(loaders).toHaveLength(1);+ expect(loaders).toHaveLength(3);for (const load of loaders) {expect((await load()).Component).toBeDefined();diff --git a/frontend/src/metabase/monitor/routes.tsx b/frontend/src/metabase/monitor/routes.tsxindex 3e27917f37e..5e21178c109 100644--- a/frontend/src/metabase/monitor/routes.tsx+++ b/frontend/src/metabase/monitor/routes.tsx@@ -1,9 +1,12 @@import { createElement } from "react";+import { loadCodeEditor } from "metabase/common/components/CodeEditor/lazy";import { NotFound } from "metabase/common/components/ErrorPages";-import { modalRoute } from "metabase/common/components/ModalRoute";+import {+ lazyModalRouteElement,+ modalRoute,+} from "metabase/common/components/ModalRoute";import { canAccessMonitorDiagnostics } from "metabase/common/monitor/selectors";-import { LogLevelsModal } from "metabase/monitor/tools/components/LogLevelsModal";// From the file rather than the barrel beside it: the barrel also re-exports// the page this file loads lazily, so importing the modal through it would hold// the page in the initial bundle.@@ -38,9 +41,9 @@ function MonitorIndexRedirect() {}/**- * The monitor pages, in their own chunk. The access guards and the modal routes- * stay eager: a guard has to decide before there is anything to show, and a- * modal route is small.+ * The monitor pages, in their own chunk. The access guards stay eager: a guard+ * has to decide before there is anything to show. So does the job modal, which+ * is small. The log levels modal is not, so it has a loader of its own below.*/const monitorLayout = () =>import("./components/MonitorLayout").then(({ MonitorLayout }) => ({@@ -78,6 +81,17 @@ const modelPersistenceLogPage = () =>}),);+// The log levels modal renders a code editor, which nothing else on the logs+// page needs. Its parent route is already lazy, but a modal declared with+// `modalRoute` holds its component eagerly.+const logLevelsModal = () =>+ Promise.all([+ import("metabase/monitor/tools/components/LogLevelsModal"),+ // Awaited here so the modal appears with its editor already in place,+ // rather than opening around an empty area that fills in a moment later.+ loadCodeEditor(),+ ]).then(([{ LogLevelsModal }]) => LogLevelsModal);+export function getMonitorRoutes() {return (<Route element={<CanAccessMonitor />}>@@ -105,7 +119,7 @@ export function getMonitorRoutes() {<Route path=":jobKey" /></Route><Route path="logs" lazy={logs}>- {modalRoute("levels", LogLevelsModal)}+ {lazyModalRouteElement("levels", logLevelsModal)}</Route><Routepath="errors"diff --git a/frontend/src/metabase/monitor/routes.unit.spec.tsx b/frontend/src/metabase/monitor/routes.unit.spec.tsxindex 3f625764e98..80677628252 100644--- a/frontend/src/metabase/monitor/routes.unit.spec.tsx+++ b/frontend/src/metabase/monitor/routes.unit.spec.tsx@@ -6,7 +6,7 @@ describe("monitor routes", () => {it("resolves every page", async () => {const loaders = lazyLoaders(getMonitorRoutes());- expect(loaders).toHaveLength(12);+ expect(loaders).toHaveLength(13);for (const load of loaders) {expect((await load()).Component).toBeDefined();diff --git a/frontend/src/metabase/querying/action-creator/ActionCreator.tsx b/frontend/src/metabase/querying/action-creator/ActionCreator.tsxindex 32f0ea5da52..658aa412589 100644--- a/frontend/src/metabase/querying/action-creator/ActionCreator.tsx+++ b/frontend/src/metabase/querying/action-creator/ActionCreator.tsx@@ -21,7 +21,7 @@ import {DataReferenceTriggerButton,} from "./InlineDataReference";-interface ActionCreatorProps {+export interface ActionCreatorProps {actionId?: WritebackActionId;modelId?: CardId;databaseId?: DatabaseId;diff --git a/frontend/src/metabase/querying/action-creator/index.ts b/frontend/src/metabase/querying/action-creator/index.tsindex f485f36e8d7..0ab8bd35e8b 100644--- a/frontend/src/metabase/querying/action-creator/index.ts+++ b/frontend/src/metabase/querying/action-creator/index.ts@@ -1 +1,2 @@-export { ActionCreator } from "./ActionCreator";+export { ActionCreator, loadActionCreator } from "./lazy";+export type { ActionCreatorProps } from "./ActionCreator";diff --git a/frontend/src/metabase/querying/action-creator/lazy.tsx b/frontend/src/metabase/querying/action-creator/lazy.tsxnew file mode 100644index 00000000000..41a3f9d3735--- /dev/null+++ b/frontend/src/metabase/querying/action-creator/lazy.tsx@@ -0,0 +1,29 @@+import { Suspense, lazy } from "react";++import type { ActionCreatorProps } from "./ActionCreator";++// The action editor carries the native query editor and its CodeMirror+// extensions. Every consumer opens it inside a modal, and one of them is mounted+// with the app shell, so it loads on demand.+const importActionCreator = () => import("./ActionCreator");++/**+ * The editor's chunk, for a caller that wants it in hand before it renders. A+ * `route.lazy` loader awaits this so the modal opens complete, rather than+ * opening around an empty area that fills in a moment later.+ */+export const loadActionCreator = () => importActionCreator();++const LazyActionCreator = lazy(() =>+ importActionCreator().then(({ ActionCreator }) => ({+ default: ActionCreator,+ })),+);++export function ActionCreator(props: ActionCreatorProps) {+ return (+ <Suspense fallback={null}>+ <LazyActionCreator {...props} />+ </Suspense>+ );+}diff --git a/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.tsx b/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.tsxindex a2a129bfd80..fbcc6c0a231 100644--- a/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.tsx+++ b/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.tsx@@ -1,4 +1,11 @@-import { type ReactNode, useCallback, useMemo, useState } from "react";+import {+ type ReactNode,+ startTransition,+ useCallback,+ useEffect,+ useMemo,+ useState,+} from "react";import { t } from "ttag";import {@@ -19,6 +26,7 @@ import {ExpressionWidget,ExpressionWidgetHeader,} from "metabase/querying/components/expressions";+import { prefetchExpressionWidget } from "metabase/querying/components/expressions/ExpressionWidget";import {clausesForMode,getClauseDefinition,@@ -254,12 +262,21 @@ export function AggregationPicker({[onSelect, onClose],);+ // The widget is a separate chunk. Fetching it while the user reads the list,+ // and switching in a transition, keeps this list on screen until the whole+ // widget is ready, so it appears complete rather than as a shell that fills in.+ useEffect(() => {+ prefetchExpressionWidget();+ }, []);+const handleExpressionSelect = useCallback((clause?: Lib.DefinedClauseName) => {if (clause) {setInitialExpressionClause(clause);}- openExpressionEditor();+ startTransition(() => {+ openExpressionEditor();+ });},[openExpressionEditor],);@@ -335,7 +352,9 @@ export function AggregationPicker({const handleSectionChange = useCallback((section: Section) => {if (section.key === "custom-expression") {- openExpressionEditor();+ startTransition(() => {+ openExpressionEditor();+ });}},[openExpressionEditor],diff --git a/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsxindex 7563d4dcb60..607ab9e8aeb 100644--- a/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsx+++ b/frontend/src/metabase/querying/common/components/AggregationPicker/AggregationPicker.unit.spec.tsx@@ -345,7 +345,7 @@ describe("AggregationPicker", () => {await userEvent.click(screen.getByText("Custom Expression"));await userEvent.type(- screen.getByTestId("custom-expression-query-editor"),+ await screen.findByTestId("custom-expression-query-editor"),expression,);await userEvent.type(diff --git a/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsx b/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsxindex 5ece8b6538f..636c08f0524 100644--- a/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsx+++ b/frontend/src/metabase/querying/components/expressions/Editor/Editor.tsx@@ -39,7 +39,7 @@ import { useCustomTooltip } from "./custom-tooltip";import { useExtensions } from "./extensions";import { hasActiveSnippet, useInitialClause } from "./utils";-type EditorProps = {+export type EditorProps = {id?: string;clause?: Lib.Expressionable | null;initialClause?: Lib.Expressionable | null;diff --git a/frontend/src/metabase/querying/components/expressions/ExpressionWidget/ExpressionWidget.unit.spec.tsx b/frontend/src/metabase/querying/components/expressions/ExpressionWidget/ExpressionWidget.unit.spec.tsxindex a09970590fc..87a61b1ff4b 100644--- a/frontend/src/metabase/querying/components/expressions/ExpressionWidget/ExpressionWidget.unit.spec.tsx+++ b/frontend/src/metabase/querying/components/expressions/ExpressionWidget/ExpressionWidget.unit.spec.tsx@@ -9,10 +9,10 @@ import { ExpressionWidget } from "./ExpressionWidget";import { ExpressionWidgetHeader } from "./ExpressionWidgetHeader";describe("ExpressionWidget", () => {- it("should render proper controls", () => {+ it("should render proper controls", async () => {setup();expect(- screen.getByTestId("custom-expression-query-editor"),+ await screen.findByTestId("custom-expression-query-editor"),).toBeInTheDocument();expect(screen.getByText("Cancel")).toBeInTheDocument();expect(screen.getByText("Done")).toBeInTheDocument();diff --git a/frontend/src/metabase/querying/components/expressions/ExpressionWidget/index.ts b/frontend/src/metabase/querying/components/expressions/ExpressionWidget/index.tsindex fd3b9cffe6a..e55528441f0 100644--- a/frontend/src/metabase/querying/components/expressions/ExpressionWidget/index.ts+++ b/frontend/src/metabase/querying/components/expressions/ExpressionWidget/index.ts@@ -1,2 +1,7 @@-export * from "./ExpressionWidget";+export {+ ExpressionWidget,+ prefetchExpressionWidget,+ useExpressionWidgetChunk,+} from "./lazy";+export type { ExpressionWidgetProps } from "./ExpressionWidget";export * from "./ExpressionWidgetHeader";diff --git a/frontend/src/metabase/querying/components/expressions/ExpressionWidget/lazy.tsx b/frontend/src/metabase/querying/components/expressions/ExpressionWidget/lazy.tsxnew file mode 100644index 00000000000..e30f561bab2--- /dev/null+++ b/frontend/src/metabase/querying/components/expressions/ExpressionWidget/lazy.tsx@@ -0,0 +1,67 @@+import { Suspense, lazy, useEffect, useState } from "react";++import type { ExpressionWidgetProps } from "./ExpressionWidget";++let isExpressionWidgetLoaded = false;++// The widget carries the expression editor and its CodeMirror extensions, which+// no route needs on first paint.+const importExpressionWidget = () =>+ import(+ /* webpackChunkName: "expression-editor" */+ "./ExpressionWidget"+ ).then((module) => {+ isExpressionWidgetLoaded = true;+ return module;+ });++/**+ * Start the download before the user asks for the widget, so opening it does not+ * wait on the network. Callers pair this with a `startTransition` around the+ * state change that opens it: the picker they are looking at stays on screen+ * until the whole widget is ready, so it appears complete rather than as a shell+ * that fills in.+ */+export const prefetchExpressionWidget = () => {+ void importExpressionWidget();+};++/**+ * Report whether the widget is ready to render. Callers that open a popover+ * straight onto the widget use this to keep the popover shut until then, so it+ * never appears as an empty box that the editor drops into later.+ */+export const useExpressionWidgetChunk = () => {+ const [isLoaded, setIsLoaded] = useState(isExpressionWidgetLoaded);++ useEffect(() => {+ if (isLoaded) {+ return;+ }++ let isCancelled = false;+ importExpressionWidget().then(() => {+ if (!isCancelled) {+ setIsLoaded(true);+ }+ });++ return () => {+ isCancelled = true;+ };+ }, [isLoaded]);++ return isLoaded;+};++const LazyExpressionWidget = lazy(() =>+ importExpressionWidget().then(({ ExpressionWidget }) => ({+ default: ExpressionWidget,+ })),+);++export const ExpressionWidget = (props: ExpressionWidgetProps) => (+ <Suspense fallback={null}>+ <LazyExpressionWidget {...props} />+ </Suspense>+);diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsxindex 2974fa3f5b7..081c156f0d7 100644--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx@@ -19,7 +19,7 @@ import { NativeQuerySidebar } from "./NativeQuerySidebar";import { QueryEditorBody } from "./QueryEditorBody";import { QueryEditorVisualization } from "./QueryEditorVisualization";-type QueryEditorProps = {+export type QueryEditorProps = {query: Lib.Query;uiState: QueryEditorUiState;uiOptions?: QueryEditorUiOptions;diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/index.ts b/frontend/src/metabase/querying/editor/components/QueryEditor/index.tsindex 0c049b968f5..2aa9a6b4add 100644--- a/frontend/src/metabase/querying/editor/components/QueryEditor/index.ts+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/index.ts@@ -1,3 +1,4 @@-export * from "./QueryEditor";+export { QueryEditor, loadQueryEditor } from "./lazy";+export type { QueryEditorProps } from "./QueryEditor";export * from "../../types";export { getInitialUiState } from "./utils";diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/lazy.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/lazy.tsxnew file mode 100644index 00000000000..a26161b9ac7--- /dev/null+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/lazy.tsx@@ -0,0 +1,30 @@+import { Suspense, lazy } from "react";++import type { QueryEditorProps } from "./QueryEditor";++// The query editor carries the native query editor and its CodeMirror+// extensions. Metric and transform routes link to it but never render it on+// first paint, so it loads on demand.+const importQueryEditor = () =>+ import(+ /* webpackChunkName: "query-editor" */+ "./QueryEditor"+ );++/**+ * The editor's chunk. A page that already waits on its own data folds this into+ * that wait, so the editor arrives with the page instead of after it.+ */+export const loadQueryEditor = () => importQueryEditor();++const LazyQueryEditor = lazy(() =>+ importQueryEditor().then(({ QueryEditor }) => ({ default: QueryEditor })),+);++export function QueryEditor(props: QueryEditorProps) {+ return (+ <Suspense fallback={null}>+ <LazyQueryEditor {...props} />+ </Suspense>+ );+}diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.tsxindex 5a47408dda4..ea9c34ac6b0 100644--- a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.tsx+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.tsx@@ -1,5 +1,12 @@import { useDisclosure } from "@mantine/hooks";-import { useCallback, useLayoutEffect, useMemo, useState } from "react";+import {+ startTransition,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useState,+} from "react";import * as Lib from "metabase-lib";@@ -7,6 +14,7 @@ import {ExpressionWidget,ExpressionWidgetHeader,} from "../../../components/expressions";+import { prefetchExpressionWidget } from "../../../components/expressions/ExpressionWidget";import {FilterColumnPicker,@@ -91,9 +99,18 @@ export function FilterPicker({handleChange(item.segment);};+ // The widget is a separate chunk. Fetching it while the user reads the column+ // list, and switching in a transition, keeps this list on screen until the whole+ // widget is ready, so it appears complete rather than as a shell that fills in.+ useEffect(() => {+ prefetchExpressionWidget();+ }, []);+const handleExpressionSelect = (clause?: Lib.DefinedClauseName) => {setInitialExpressionClause(clause ?? null);- openExpressionEditor();+ startTransition(() => {+ openExpressionEditor();+ });};const checkItemIsSelected = useCallback(diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsxindex 94eeb02dfe8..688d7562d90 100644--- a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsx+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsx@@ -351,7 +351,9 @@ describe("FilterPicker", () => {const [filter] = Lib.filters(query, -1);setup({ query, filter });- expect(screen.getByText(/Custom expression/i)).toBeInTheDocument();+ expect(+ await screen.findByText(/Custom expression/i),+ ).toBeInTheDocument();// the expression editor formats its source asynchronously; wait for it// to settle so the resulting state updates stay inside act()await waitFor(() =>@@ -421,7 +423,7 @@ describe("FilterPicker", () => {text: string,{ delay }: { delay: number } = { delay: 0 },) {- const input = screen.getByTestId("custom-expression-query-editor");+ const input = await screen.findByTestId("custom-expression-query-editor");const button = screen.getByRole("button", { name: /(Done|Update)/ });// The expression editor applies changes on blur,@@ -451,7 +453,9 @@ describe("FilterPicker", () => {it("should open the expression editor for unsupported expressions", async () => {setup(createQueryWithNullStringFilter());- const editor = screen.getByTestId("custom-expression-query-editor");+ const editor = await screen.findByTestId(+ "custom-expression-query-editor",+ );expect(editor).toBeInTheDocument();// the expression editor formats its source asynchronously; wait for it// to settle so the resulting state updates stay inside act()diff --git a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsx b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsxindex fed4c7554f7..2c7799403d9 100644--- a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsx+++ b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsx@@ -4,7 +4,10 @@ import { useTranslateContent } from "metabase/content-translation/hooks";import * as Lib from "metabase-lib";import { getUniqueExpressionName } from "metabase-lib/v1/queries/utils/expression";-import { ExpressionWidget } from "../../../components/expressions/ExpressionWidget";+import {+ ExpressionWidget,+ useExpressionWidgetChunk,+} from "../../../components/expressions/ExpressionWidget";import type { NotebookStepProps } from "../../types";import { ClauseStep } from "../ClauseStep";@@ -18,6 +21,12 @@ export const ExpressionStep = ({}: NotebookStepProps): JSX.Element => {const { query, stageIndex } = step;const tc = useTranslateContent();++ // A new custom column opens its popover as soon as the step appears. The+ // widget is a separate chunk, so hold the popover shut until it arrives:+ // `renderPopover` returning null disables it.+ const isWidgetLoaded = useExpressionWidgetChunk();+const expressions = useMemo(() => Lib.expressions(query, stageIndex),[query, stageIndex],@@ -51,18 +60,20 @@ export const ExpressionStep = ({items={expressions}renderName={renderExpressionName}readOnly={readOnly}- renderPopover={({ item, index: expressionIndex, onClose }) => (- <ExpressionPopover- query={query}- stageIndex={stageIndex}- expression={item}- expressionIndex={expressionIndex}- reportTimezone={reportTimezone}- updateQuery={updateQuery}- onClose={onClose}- readOnly={readOnly}- />- )}+ renderPopover={({ item, index: expressionIndex, onClose }) =>+ !isWidgetLoaded ? null : (+ <ExpressionPopover+ query={query}+ stageIndex={stageIndex}+ expression={item}+ expressionIndex={expressionIndex}+ reportTimezone={reportTimezone}+ updateQuery={updateQuery}+ onClose={onClose}+ readOnly={readOnly}+ />+ )+ }isLastOpened={isLastOpened}onReorder={handleReorderExpression}onRemove={handleRemoveExpression}diff --git a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsxindex 6710fed332e..af7b6924edc 100644--- a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsx@@ -51,7 +51,7 @@ describe("Notebook Editor > Expression Step", () => {await userEvent.click(screen.getByRole("img", { name: "add icon" }));- const input = screen.getByTestId("custom-expression-query-editor");+ const input = await screen.findByTestId("custom-expression-query-editor");await userEvent.type(input, "1 + 1");await act(async () => {input.blur();@@ -151,7 +151,7 @@ describe("Notebook Editor > Expression Step", () => {await userEvent.click(screen.getByRole("img", { name: "add icon" }));- const input = screen.getByTestId("custom-expression-query-editor");+ const input = await screen.findByTestId("custom-expression-query-editor");await userEvent.type(input, "1 + 1");await act(async () => {input.blur();diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinConditionColumnPicker.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinConditionColumnPicker.tsxindex 74429265d74..78d895eb57c 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinConditionColumnPicker.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinConditionColumnPicker/JoinConditionColumnPicker.tsx@@ -1,3 +1,6 @@+import { useEffect } from "react";++import { prefetchExpressionWidget } from "metabase/querying/components/expressions/ExpressionWidget";import { Popover } from "metabase/ui";import type * as Lib from "metabase-lib";@@ -36,6 +39,13 @@ export function JoinConditionColumnPicker({onChange,onOpenChange,}: JoinConditionColumnPickerProps) {+ // The expression widget is a separate chunk. This picker is on screen before+ // anyone opens the custom expression, so fetching it here means the dropdown+ // opens with the editor already in place.+ useEffect(() => {+ prefetchExpressionWidget();+ }, []);+return (<Popover opened={isOpened} position="bottom-start" onChange={onOpenChange}><Popover.Target>diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsxindex df8e1d1d8d3..3ace92b1193 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx@@ -269,7 +269,7 @@ function setup({}async function enterCustomExpression(expression: string) {- const input = screen.getByTestId("custom-expression-query-editor");+ const input = await screen.findByTestId("custom-expression-query-editor");await waitFor(() => expect(input).toHaveProperty("readOnly", false));await userEvent.clear(input);await userEvent.type(input, expression);diff --git a/frontend/src/metabase/transforms/components/RunInfo/RunInfo.unit.spec.tsx b/frontend/src/metabase/transforms/components/RunInfo/RunInfo.unit.spec.tsxindex f547e78a858..a7ba2244f7b 100644--- a/frontend/src/metabase/transforms/components/RunInfo/RunInfo.unit.spec.tsx+++ b/frontend/src/metabase/transforms/components/RunInfo/RunInfo.unit.spec.tsx@@ -30,7 +30,7 @@ describe("RunInfo", () => {expect(screen.getByText("Failed at Oct 15, 2023 2:30 PM, with this error"),).toBeInTheDocument();- expect(screen.getByDisplayValue(message)).toBeInTheDocument();+ expect(await screen.findByDisplayValue(message)).toBeInTheDocument();});it("should show the error message when there is no date", async () => {@@ -41,6 +41,6 @@ describe("RunInfo", () => {await userEvent.click(button);expect(screen.getByText("Failed with this error")).toBeInTheDocument();- expect(screen.getByDisplayValue(message)).toBeInTheDocument();+ expect(await screen.findByDisplayValue(message)).toBeInTheDocument();});});diff --git a/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsx b/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsxindex ed2971f4613..c5492fd8183 100644--- a/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsx+++ b/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsx@@ -1,5 +1,5 @@import { useDisclosure } from "@mantine/hooks";-import { useCallback, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { t } from "ttag";import { skipToken, useGetCardQuery } from "metabase/api";@@ -15,7 +15,10 @@ import {PaneHeaderInput,} from "metabase/common/data-studio/components/PaneHeader";import { PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";-import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";+import {+ getInitialUiState,+ loadQueryEditor,+} from "metabase/querying/editor/components/QueryEditor";import { useSelector } from "metabase/redux";import { type Location, useNavigate, useParams } from "metabase/router";import { getMetadata } from "metabase/selectors/metadata";@@ -52,10 +55,13 @@ function NewTransformPage({ initialSource }: NewTransformPageProps) {const {transformsDatabases,remoteSyncReadOnly,- isLoadingDatabases: isLoading,+ isLoadingDatabases,databasesError: error,} = useTransformPermissions();+ const isEditorLoaded = useQueryEditorChunk();+ const isLoading = isLoadingDatabases || !isEditorLoaded;+if (isLoading || error != null || transformsDatabases == null) {return (<Center h="100%">@@ -272,3 +278,21 @@ export function NewCardTransformPage() {return <NewTransformPage initialSource={initialSource} />;}++// The editor is a separate chunk. Folding it into the wait this page already+// does for its own data means one wait rather than two in a row.+const useQueryEditorChunk = () => {+ const [isLoaded, setIsLoaded] = useState(false);+ useEffect(() => {+ let cancelled = false;+ loadQueryEditor().then(() => {+ if (!cancelled) {+ setIsLoaded(true);+ }+ });+ return () => {+ cancelled = true;+ };+ }, []);+ return isLoaded;+};diff --git a/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsx b/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsxindex 28d25c18f5d..2af41b7e49b 100644--- a/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsx+++ b/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsx@@ -16,7 +16,10 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrimport { PageContainer } from "metabase/common/data-studio/components/PageContainer";import { useMetadataToasts } from "metabase/metadata/hooks";import { PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";-import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";+import {+ getInitialUiState,+ loadQueryEditor,+} from "metabase/querying/editor/components/QueryEditor";import { useSelector } from "metabase/redux";import { useLocation, useNavigate, useParams } from "metabase/router";import { getMetadata } from "metabase/selectors/metadata";@@ -70,7 +73,8 @@ export function TransformQueryPage() {isLoadingDatabases,databasesError,} = useTransformPermissions({ transform });- const isLoading = isLoadingTransform || isLoadingDatabases;+ const isEditorLoaded = useQueryEditorChunk();+ const isLoading = isLoadingTransform || isLoadingDatabases || !isEditorLoaded;const error = transformError || databasesError;if (isLoading || error != null) {@@ -384,3 +388,21 @@ export function TransformQueryPageEditor({/>);}++// The editor is a separate chunk. Folding it into the wait this page already+// does for its own data means one wait rather than two in a row.+const useQueryEditorChunk = () => {+ const [isLoaded, setIsLoaded] = useState(false);+ useEffect(() => {+ let cancelled = false;+ loadQueryEditor().then(() => {+ if (!cancelled) {+ setIsLoaded(true);+ }+ });+ return () => {+ cancelled = true;+ };+ }, []);+ return isLoaded;+};diff --git a/rspack.main.config.js b/rspack.main.config.jsindex 02d1c094fdd..a08a99a4abd 100644--- a/rspack.main.config.js+++ b/rspack.main.config.js@@ -267,6 +267,15 @@ const config = {name: "vendor",priority: -10,},+ // Modules shared by two or more async chunks (e.g. CodeMirror, pulled+ // in by every lazily loaded editor) move into a shared async chunk+ // instead of being copied into each one. `vendors` above only claims+ // initial chunks, so this never grows the initial payload.+ asyncCommons: {+ chunks: "async",+ minChunks: 2,+ reuseExistingChunk: true,+ },sqlFormatter: {test: /[\\/]sql-formatter[\\/]/,chunks: "all",