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
Keep tiptap and prosemirror out of the initial bundle (#79964)
Romeo Van Snick70181282f370
diff --git a/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx b/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsxindex 0cfb2d4313d..d9813d0111e 100644--- a/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx+++ b/frontend/src/metabase/metabot/components/AIMarkdown/components/MarkdownSmartLink.tsx@@ -5,7 +5,7 @@ import { EntityIcon } from "metabase/common/components/EntityIcon";import { useGetIcon } from "metabase/hooks/use-icon";import { getConversationChart } from "metabase/metabot/state";import { useSelector } from "metabase/redux";-import { useEntityData } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode";+import { useEntityData } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data";import { entityToUrlableModel } from "metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils";import {type MetabaseProtocolEntityModel,diff --git a/frontend/src/metabase/metabot/components/Metabot.tsx b/frontend/src/metabase/metabot/components/Metabot.tsxindex 69af0a8ef76..14e8e7bee51 100644--- a/frontend/src/metabase/metabot/components/Metabot.tsx+++ b/frontend/src/metabase/metabot/components/Metabot.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { Suspense, useEffect, useState } from "react";import { tinykeys } from "tinykeys";import { t } from "ttag";@@ -29,8 +29,8 @@ import { metabotApi } from "../api";import { isHistoryEnabledProfile } from "../constants";import type { MetabotAgentId } from "../state";-import { MetabotChat } from "./MetabotChat";import { MetabotConversationHistory } from "./MetabotChat/MetabotConversationHistory";+import { createLazyMetabotChat, prefetchMetabotChat } from "./MetabotChat/lazy";const MetabotErrorFallback = ({ onRetry }: { onRetry: () => void }) => {return (@@ -124,9 +124,15 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {const agentId = config?.agentId ?? "omnibot";const { visible, setVisible } = useMetabotAgent(agentId);const [errorBoundaryKey, setErrorBoundaryKey] = useState(0);+ const [MetabotChat, setMetabotChat] = useState(createLazyMetabotChat);const isFullPageMetabot = useIsFullPageMetabot();- const handleRetry = () => setErrorBoundaryKey((prev) => prev + 1);+ const handleRetry = () => {+ // A failed fetch is one of the errors the boundary catches, and the panel+ // that failed can never load, so retry with a fresh one.+ setMetabotChat(createLazyMetabotChat());+ setErrorBoundaryKey((prev) => prev + 1);+ };useEffect(() => {return tinykeys(window, {@@ -143,6 +149,15 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {});}, [visible, setVisible, isFullPageMetabot]);+ useEffect(function prefetchChatPanelWhenIdle() {+ if (typeof requestIdleCallback !== "function") {+ prefetchMetabotChat();+ return;+ }+ const handle = requestIdleCallback(prefetchMetabotChat);+ return () => cancelIdleCallback(handle);+ }, []);+useEffect(function closeViaPropChange() {if (hide) {@@ -160,17 +175,20 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {return (<ErrorBoundary key={errorBoundaryKey} errorComponent={ErrorFallback}>- <Sidebar- isOpen={visible}- side="right"- width="30rem"- aria-hidden={!visible}- >- <MetabotChat- config={config}- headerActions={<MetabotSidebarActions agentId={agentId} />}- />- </Sidebar>+ {/* The fallback covers the sidebar too, so an empty panel never opens */}+ <Suspense fallback={null}>+ <Sidebar+ isOpen={visible}+ side="right"+ width="30rem"+ aria-hidden={!visible}+ >+ <MetabotChat+ config={config}+ headerActions={<MetabotSidebarActions agentId={agentId} />}+ />+ </Sidebar>+ </Suspense></ErrorBoundary>);};diff --git a/frontend/src/metabase/metabot/components/MetabotChat/lazy.ts b/frontend/src/metabase/metabot/components/MetabotChat/lazy.tsnew file mode 100644index 00000000000..a556a61b6ab--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotChat/lazy.ts@@ -0,0 +1,30 @@+import { lazy } from "react";++// The chat panel reaches the prompt editor, and through it the whole tiptap and+// prosemirror stack. `Metabot` is mounted for the whole session, so a direct+// import ships that stack on first paint. Loading the panel lazily moves it into+// its own async chunk instead.+const importMetabotChat = () => import("./MetabotChat");++// Start downloading the chunk before the user asks for the sidebar, so the+// sidebar still opens at once. rspack de-duplicates the request, so this shares+// the same chunk as the lazy component below. A failed prefetch is forgotten:+// rspack drops the chunk from its registry, so the render asks again and can+// show the error where the user is looking.+export const prefetchMetabotChat = () => {+ importMetabotChat().catch(() => undefined);+};++/**+ * A new lazy component on every call.+ *+ * `React.lazy` remembers a rejected import and re-throws it on every later+ * render, so a component that failed to fetch can never recover. Retrying needs+ * a component that has not failed yet.+ */+export const createLazyMetabotChat = () =>+ lazy(() =>+ importMetabotChat().then(({ MetabotChat }) => ({+ default: MetabotChat,+ })),+ );diff --git a/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsx b/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsxindex 9cb0a21ae3a..3c5e60c306a 100644--- a/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsx+++ b/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsx@@ -17,9 +17,32 @@ import { MetabotProvider } from "../context";import { getMetabotInitialState } from "../state/reducer-utils";let mockShouldThrow = false;+let mockShouldFailChunkLoad = false;-jest.mock("../components/MetabotChat", () => {- const metabotChatModule = jest.requireActual("../components/MetabotChat");+// Stand in for the chunk fetch. The factory reads the mocked module below, so a+// test can make the panel throw on render or the fetch fail, one at a time.+jest.mock("../components/MetabotChat/lazy", () => {+ const { lazy } = jest.requireActual("react");+ return {+ prefetchMetabotChat: jest.fn(),+ createLazyMetabotChat: () =>+ lazy(() =>+ mockShouldFailChunkLoad+ ? Promise.reject(new Error("Test chunk load failure"))+ : Promise.resolve({+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ default: require("../components/MetabotChat/MetabotChat")+ .MetabotChat,+ }),+ ),+ };+});++// The lazy loader imports the module, not the barrel, so mock the module.+jest.mock("../components/MetabotChat/MetabotChat", () => {+ const metabotChatModule = jest.requireActual(+ "../components/MetabotChat/MetabotChat",+ );return {...metabotChatModule,MetabotChat: (props: any) => {@@ -70,6 +93,7 @@ function setup() {describe("metabot error boundary", () => {beforeEach(() => {mockShouldThrow = false;+ mockShouldFailChunkLoad = false;});it("should show error fallback and recover when clicking try again", async () => {@@ -102,4 +126,27 @@ describe("metabot error boundary", () => {consoleErrorSpy.mockRestore();});++ it("should recover when the panel chunk fails to load", async () => {+ const consoleErrorSpy = jest+ .spyOn(console, "error")+ .mockImplementation(() => {});++ mockShouldFailChunkLoad = true;++ setup();++ expect(+ await screen.findByTestId("metabot-error-fallback"),+ ).toBeInTheDocument();++ // React.lazy re-throws a rejected import forever, so retrying has to build a+ // new component rather than re-render the one that failed.+ mockShouldFailChunkLoad = false;++ await userEvent.click(screen.getByTestId("metabot-error-retry"));+ expect(await screen.findByTestId("metabot-chat")).toBeInTheDocument();++ consoleErrorSpy.mockRestore();+ });});diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsxindex 98e1ed70433..8a9337b3083 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx@@ -8,23 +8,10 @@ import { memo, useEffect } from "react";import { t } from "ttag";import { isObject } from "underscore";-import {- useGetActionQuery,- useGetCardQuery,- useGetCollectionQuery,- useGetDashboardQuery,- useGetDatabaseQuery,- useGetDocumentQuery,- useGetSegmentQuery,- useGetTableQuery,- useGetTransformQuery,- useListMentionsQuery,-} from "metabase/api";import { EntityIcon } from "metabase/common/components/EntityIcon";import { Link } from "metabase/common/components/Link";import type { IconModel, ObjectWithModel } from "metabase/common/utils/icon";import { useGetIcon } from "metabase/hooks/use-icon";-import { PLUGIN_TRANSFORMS } from "metabase/plugins";import { useDispatch } from "metabase/redux";import { useEditorHost } from "metabase/rich_text_editing/tiptap/EditorHost";import { Icon } from "metabase/ui";@@ -55,6 +42,7 @@ import {import type { SuggestionModel } from "../shared/types";import styles from "./SmartLinkNode.module.css";+import { useEntityData } from "./use-entity-data";export type SmartLinkEntity =| Card@@ -299,144 +287,6 @@ export const SmartLink = Node.create<{},});-function assertUnreachable(value: never) {- console.warn(`Unhandled model type: ${value}`);-}--export const useEntityData = (- entityId: number | null,- model: SuggestionModel | null,-) => {- const isCard = model && ["card", "dataset", "metric"].includes(model);- const cardQuery = useGetCardQuery(- { id: entityId!, ignore_error: true },- { skip: !entityId || !isCard },- );-- const dashboardQuery = useGetDashboardQuery(- { id: entityId!, ignore_error: true },- { skip: !entityId || model !== "dashboard" },- );-- const collectionQuery = useGetCollectionQuery(- { id: entityId!, ignore_error: true },- { skip: !entityId || model !== "collection" },- );-- const tableQuery = useGetTableQuery(- { id: entityId! },- { skip: !entityId || model !== "table" },- );-- const databaseQuery = useGetDatabaseQuery(- { id: entityId! },- { skip: !entityId || model !== "database" },- );-- const documentQuery = useGetDocumentQuery(- {- id: entityId!,- },- {- skip: !entityId || model !== "document",- },- );-- const transformQuery = useGetTransformQuery(entityId!, {- skip: !PLUGIN_TRANSFORMS.isEnabled || !entityId || model !== "transform",- });-- const actionQuery = useGetActionQuery(- { id: entityId! },- { skip: !entityId || model !== "action" },- );-- const segmentQuery = useGetSegmentQuery(entityId!, {- skip: !entityId || model !== "segment",- });-- const usersQuery = useListMentionsQuery(undefined, {- skip: !entityId || model !== "user",- });-- // Determine which query is active and return its state- switch (model) {- case "card":- case "dataset":- case "metric":- return {- entity: cardQuery.data,- isLoading: cardQuery.isLoading,- error: cardQuery.error,- };- case "dashboard":- return {- entity: dashboardQuery.data,- isLoading: dashboardQuery.isLoading,- error: dashboardQuery.error,- };- case "collection":- return {- entity: collectionQuery.data,- isLoading: collectionQuery.isLoading,- error: collectionQuery.error,- };- case "table":- return {- entity: tableQuery.data,- isLoading: tableQuery.isLoading,- error: tableQuery.error,- };- case "database":- return {- entity: databaseQuery.data,- isLoading: databaseQuery.isLoading,- error: databaseQuery.error,- };- case "document":- return {- entity: documentQuery.data,- isLoading: documentQuery.isLoading,- error: documentQuery.error,- };- case "transform":- return {- entity: transformQuery.data,- isLoading: transformQuery.isLoading,- error: transformQuery.error,- };- case "action":- return {- entity: actionQuery.data,- isLoading: actionQuery.isLoading,- error: actionQuery.error,- };- case "segment":- return {- entity: segmentQuery.data,- isLoading: segmentQuery.isLoading,- error: segmentQuery.error,- };- case "user": {- const user = usersQuery.data?.data.find((user) => user.id === entityId);-- return {- entity: user ? { ...user, name: user.common_name } : null,- isLoading: usersQuery.isLoading,- error: usersQuery.error,- };- }- case "indexed-entity":- case "measure":- case "exploration":- case null:- return { entity: null, isLoading: false, error: null };- default:- assertUnreachable(model);- return { entity: null, isLoading: false, error: null };- }-};-export const SmartLinkComponent = memo(({ node, updateAttributes }: NodeViewProps) => {const getIcon = useGetIcon();diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data.tsnew file mode 100644index 00000000000..22b4482a1bf--- /dev/null+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/use-entity-data.ts@@ -0,0 +1,153 @@+import {+ useGetActionQuery,+ useGetCardQuery,+ useGetCollectionQuery,+ useGetDashboardQuery,+ useGetDatabaseQuery,+ useGetDocumentQuery,+ useGetSegmentQuery,+ useGetTableQuery,+ useGetTransformQuery,+ useListMentionsQuery,+} from "metabase/api";+import { PLUGIN_TRANSFORMS } from "metabase/plugins";++import type { SuggestionModel } from "../shared/types";++function assertUnreachable(value: never) {+ console.warn(`Unhandled model type: ${value}`);+}++export const useEntityData = (+ entityId: number | null,+ model: SuggestionModel | null,+) => {+ const isCard = model && ["card", "dataset", "metric"].includes(model);+ const cardQuery = useGetCardQuery(+ { id: entityId!, ignore_error: true },+ { skip: !entityId || !isCard },+ );++ const dashboardQuery = useGetDashboardQuery(+ { id: entityId!, ignore_error: true },+ { skip: !entityId || model !== "dashboard" },+ );++ const collectionQuery = useGetCollectionQuery(+ { id: entityId!, ignore_error: true },+ { skip: !entityId || model !== "collection" },+ );++ const tableQuery = useGetTableQuery(+ { id: entityId! },+ { skip: !entityId || model !== "table" },+ );++ const databaseQuery = useGetDatabaseQuery(+ { id: entityId! },+ { skip: !entityId || model !== "database" },+ );++ const documentQuery = useGetDocumentQuery(+ {+ id: entityId!,+ },+ {+ skip: !entityId || model !== "document",+ },+ );++ const transformQuery = useGetTransformQuery(entityId!, {+ skip: !PLUGIN_TRANSFORMS.isEnabled || !entityId || model !== "transform",+ });++ const actionQuery = useGetActionQuery(+ { id: entityId! },+ { skip: !entityId || model !== "action" },+ );++ const segmentQuery = useGetSegmentQuery(entityId!, {+ skip: !entityId || model !== "segment",+ });++ const usersQuery = useListMentionsQuery(undefined, {+ skip: !entityId || model !== "user",+ });++ // Determine which query is active and return its state+ switch (model) {+ case "card":+ case "dataset":+ case "metric":+ return {+ entity: cardQuery.data,+ isLoading: cardQuery.isLoading,+ error: cardQuery.error,+ };+ case "dashboard":+ return {+ entity: dashboardQuery.data,+ isLoading: dashboardQuery.isLoading,+ error: dashboardQuery.error,+ };+ case "collection":+ return {+ entity: collectionQuery.data,+ isLoading: collectionQuery.isLoading,+ error: collectionQuery.error,+ };+ case "table":+ return {+ entity: tableQuery.data,+ isLoading: tableQuery.isLoading,+ error: tableQuery.error,+ };+ case "database":+ return {+ entity: databaseQuery.data,+ isLoading: databaseQuery.isLoading,+ error: databaseQuery.error,+ };+ case "document":+ return {+ entity: documentQuery.data,+ isLoading: documentQuery.isLoading,+ error: documentQuery.error,+ };+ case "transform":+ return {+ entity: transformQuery.data,+ isLoading: transformQuery.isLoading,+ error: transformQuery.error,+ };+ case "action":+ return {+ entity: actionQuery.data,+ isLoading: actionQuery.isLoading,+ error: actionQuery.error,+ };+ case "segment":+ return {+ entity: segmentQuery.data,+ isLoading: segmentQuery.isLoading,+ error: segmentQuery.error,+ };+ case "user": {+ const user = usersQuery.data?.data.find((user) => user.id === entityId);++ return {+ entity: user ? { ...user, name: user.common_name } : null,+ isLoading: usersQuery.isLoading,+ error: usersQuery.error,+ };+ }+ case "indexed-entity":+ case "measure":+ case "exploration":+ case null:+ return { entity: null, isLoading: false, error: null };+ default:+ assertUnreachable(model);+ return { entity: null, isLoading: false, error: null };+ }+};diff --git a/frontend/src/metabase/routes-public.tsx b/frontend/src/metabase/routes-public.tsxindex 7d6c3cf44ef..e4437205c7b 100644--- a/frontend/src/metabase/routes-public.tsx+++ b/frontend/src/metabase/routes-public.tsx@@ -1,11 +1,34 @@import { PublicNotFound } from "metabase/public/components/PublicNotFound";import PublicAction from "metabase/public/containers/PublicAction";import PublicApp from "metabase/public/containers/PublicApp";-import { PublicDocument } from "metabase/public/containers/PublicDocument";import { PublicOrEmbeddedDashboardPage } from "metabase/public/containers/PublicOrEmbeddedDashboard";import { PublicOrEmbeddedQuestion } from "metabase/public/containers/PublicOrEmbeddedQuestion";import type { RouteObject } from "metabase/router";+/**+ * The public document page, in its own chunk. It renders the document with+ * tiptap, which the public question and dashboard pages have no use for.+ */+const importPublicDocument = () =>+ import("metabase/public/containers/PublicDocument");++const publicDocument = () =>+ importPublicDocument().then(({ PublicDocument }) => ({+ Component: PublicDocument,+ }));++/**+ * A public document is opened by link, so there is no hover to prefetch on. The+ * path is known before the router mounts, so the fetch starts here instead: it+ * then runs alongside the rest of startup rather than after it.+ *+ * Matched loosely because the app can be served under a path prefix. A path that+ * only looks like a document link costs one chunk that is never rendered.+ */+if (window.location.pathname.includes("/public/document/")) {+ importPublicDocument().catch(() => undefined);+}+export const getRoutes = (): RouteObject[] => [{children: [@@ -19,7 +42,7 @@ export const getRoutes = (): RouteObject[] => [path: "dashboard/:uuid/:tabSlug?",element: <PublicOrEmbeddedDashboardPage />,},- { path: "document/:uuid", element: <PublicDocument /> },+ { path: "document/:uuid", lazy: publicDocument },{ path: "*", element: <PublicNotFound /> },],},