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
fix Back button on eajs browser component (#69273)
Nicolò Prettob8ad77a58086
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/eajs-internal-navigation.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/eajs-internal-navigation.cy.spec.tsindex dd8c1e57c06..c12f40bb8a6 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/eajs-internal-navigation.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/eajs-internal-navigation.cy.spec.ts@@ -302,10 +302,27 @@ describe("scenarios > embedding > sdk iframe embedding > internal-navigation", (beforeEach(() => {H.prepareSdkIframeEmbedTest({ withToken: "bleeding-edge" });- H.createQuestion({- name: "Target Question",- query: { "source-table": ORDERS_ID, limit: 5 },- }).then(({ body }) => cy.wrap(body.id).as("targetQuestionId"));+ H.createDashboard({ name: "Target Dashboard" }).then(+ ({ body: targetDashboard }) => {+ cy.wrap(targetDashboard.id).as("targetDashboardId");++ H.createQuestion({+ name: "Orders in Target Dashboard",+ query: { "source-table": ORDERS_ID, limit: 5 },+ }).then(({ body: targetQuestion }) => {+ H.addOrUpdateDashboardCard({+ card_id: targetQuestion.id,+ dashboard_id: targetDashboard.id,+ card: {+ row: 0,+ col: 0,+ size_x: 24,+ size_y: 8,+ },+ });+ });+ },+ );cy.then(function () {H.createDashboard({ name: "First Dashboard" }).then(@@ -327,9 +344,9 @@ describe("scenarios > embedding > sdk iframe embedding > internal-navigation", ([`["ref",["field",${ORDERS.ID},null]]`]: {click_behavior: {type: "link",- linkType: "question",- linkTextTemplate: "Go to Target Question",- targetId: this.targetQuestionId,+ linkType: "dashboard",+ linkTextTemplate: "Go to Target Dashboard",+ targetId: this.targetDashboardId,parameterMapping: {},},},@@ -370,7 +387,7 @@ describe("scenarios > embedding > sdk iframe embedding > internal-navigation", (cy.log("click on click behavior link to trigger internal navigation");H.getSimpleEmbedIframeContent()- .findAllByText("Go to Target Question")+ .findAllByText("Go to Target Dashboard").first().click();@@ -381,11 +398,16 @@ describe("scenarios > embedding > sdk iframe embedding > internal-navigation", (cy.log("back button should be visible");H.getSimpleEmbedIframeContent()- .findByText(/Back to/)+ .findByText("Back to First Dashboard").should("be.visible").click();- cy.log("breadcrumbs should return after going back");+ cy.log("verify we returned to First Dashboard");+ H.getSimpleEmbedIframeContent()+ .findAllByText("First Dashboard")+ .should("have.length", 2); // breadcrumbs and the dashboard heading++ cy.log("breadcrumbs should be visible again");H.getSimpleEmbedIframeContent().findByTestId("sdk-breadcrumbs").should("be.visible");@@ -395,5 +417,67 @@ describe("scenarios > embedding > sdk iframe embedding > internal-navigation", (.findByText(/Back to/).should("not.exist");});++ it("should clean up navigation stack when clicking a collection breadcrumb after navigating back", () => {+ H.visitCustomHtmlPage(`+ ${H.getNewEmbedScriptTag()}+ ${H.getNewEmbedConfigurationScript({})}+ <metabase-browser initial-collection="root" enable-entity-navigation />+ `);++ cy.log("open First Dashboard from the browser");+ H.getSimpleEmbedIframeContent()+ .findByText("First Dashboard")+ .should("be.visible")+ .click();++ cy.wait("@getDashCardQuery");++ cy.log("navigate to Target Dashboard via click behavior link");+ H.getSimpleEmbedIframeContent()+ .findAllByText("Go to Target Dashboard")+ .first()+ .click();++ cy.wait("@getDashboard");++ cy.log("click back to return to First Dashboard");+ H.getSimpleEmbedIframeContent()+ .findByText("Back to First Dashboard")+ .should("be.visible")+ .click();++ cy.log(+ "click 'Our analytics' breadcrumb to go back to the collection browser",+ );+ H.getSimpleEmbedIframeContent()+ .findByTestId("sdk-breadcrumbs")+ .findByText("Our analytics")+ .click();++ cy.log("verify the collection browser is showing items again");+ H.getSimpleEmbedIframeContent()+ .findByText("First Dashboard")+ .should("be.visible");++ cy.log(+ "verify no back button is present (navigation stack should be clean)",+ );+ H.getSimpleEmbedIframeContent()+ .findByText(/Back to/)+ .should("not.exist");++ cy.log(+ "verify we can navigate to a dashboard again (no stale virtual entries)",+ );+ H.getSimpleEmbedIframeContent().findByText("First Dashboard").click();++ cy.wait("@getDashCardQuery");++ H.getSimpleEmbedIframeContent()+ .findByTestId("sdk-breadcrumbs")+ .findByText("First Dashboard")+ .should("be.visible");+ });});});diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsxindex 92c837c530d..9f2bac41296 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider.tsx@@ -33,6 +33,8 @@ type Props = {renderDrillThroughQuestion?: () => ReactNode;/** Props to pass to drill-through question components */drillThroughQuestionProps?: DrillThroughQuestionProps;+ /** When true, children are kept mounted (but hidden) during navigation instead of being unmounted */+ keepChildrenMounted?: boolean;style?: CSSProperties;className?: string;};@@ -44,6 +46,7 @@ const SdkInternalNavigationProviderInner = ({dashboardProps,renderDrillThroughQuestion: RenderDrillThroughQuestion,drillThroughQuestionProps,+ keepChildrenMounted = false,}: Props) => {const [stack, setStack] = useState<SdkInternalNavigationEntry[]>([]);@@ -81,7 +84,10 @@ const SdkInternalNavigationProviderInner = ({pop,currentEntry: stack.at(-1),previousEntry: stack.at(-2),- canGoBack: stack.length > 1,+ // When starting from the `metabase-browser`, we need to have > 2 items in+ // the stack to be able to go back, as the first navigation is handled by+ // the breadcrumbs.+ canGoBack: stack.filter((e) => e.type !== "metabase-browser").length > 1,initWithDashboard,}),[stack, push, pop, initWithDashboard],@@ -90,7 +96,7 @@ const SdkInternalNavigationProviderInner = ({// "Virtual" entries are entries that are rendered by the previous entity (ie: drills, new question from dashboard)// we don't have to render them, but we need them in the stack to make the back button work correctlyconst nonVirtualEntries = useMemo(- () => stack.filter((entry) => !entry.type.startsWith("virtual")),+ () => stack.filter((entry) => !entry.virtual),[stack],);@@ -144,14 +150,16 @@ const SdkInternalNavigationProviderInner = ({}).otherwise(() => children);- // When we don't render the children directly, we need to render a wrapper with the styles applied.- // Otherwise we don pass `style` and `className` to anything, we can't always wrap it otherwise we may render- // paddings and borders twice.return (<SdkInternalNavigationContext.Provider value={value}>- {entryIsOriginalEntity ? (- children- ) : (+ {/* When `keepChildrenMounted` is true, we keep the children mounted but hide them */}+ <div style={{ display: entryIsOriginalEntity ? "contents" : "none" }}>+ {entryIsOriginalEntity || keepChildrenMounted ? children : null}+ </div>+ {entryIsOriginalEntity ? null : (+ // When we don't render the children directly, we need to render a wrapper with the styles applied.+ // Otherwise we don't pass `style` and `className` to anything, we can't always wrap it otherwise we may render+ // paddings and borders twice.<SdkDashboardStyledWrapper className={className} style={style}>{maybeButton}{content}diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsxindex c9fcf6df037..fa8b2850eeb 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkInternalNavigation/context.tsx@@ -4,36 +4,56 @@ import type { SdkDashboardId } from "embedding-sdk-bundle/types/dashboard";import type { SdkQuestionId } from "embedding-sdk-bundle/types/question";import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";+// This type exists only to have a global place where to put the JSDoc for virtual+type BaseEntry = {+ /** "Virtual" entries are entries that are rendered by the previous entity and not by the SdkInternalNavigationProvider directly (ie: drills, new question from dashboard)+ * We still need the entry object in the stack to keep track of them and make the back button work correctly+ */+ virtual?: boolean;+};+export type SdkInternalNavigationEntry =- | {+ | (BaseEntry & {type: "dashboard";id: SdkDashboardId;name: string;+ virtual?: true;parameters?: ParameterValues;- }- | {+ onPop?: () => void;+ })+ | (BaseEntry & {type: "question";id: SdkQuestionId;name: string;+ virtual?: true;parameters?: ParameterValues;- }- | {- /** Virtual entry for question drills - parent component handles rendering, this just tracks navigation depth */- type: "virtual-question-drill";+ onPop?: () => void;+ })+ | (BaseEntry & {+ type: "metabase-browser";+ virtual: false;+ onPop?: () => void;+ })+ | (BaseEntry & {+ /** Parent component handles rendering, this just tracks navigation depth */+ type: "question-drill";+ virtual: true;name: string;onPop?: () => void;- }- | {- /** Virtual entry for opening a card from dashboard (clicking card title or click behavior) */- type: "virtual-open-card";+ })+ | (BaseEntry & {+ /** Opening a card from dashboard (clicking card title or click behavior) */+ type: "open-card";+ virtual: true;name: string;onPop?: () => void;- }- | {- /** Virtual entry for new question creation from dashboard */- type: "virtual-new-question";+ })+ | (BaseEntry & {+ /** New question creation from dashboard */+ type: "new-question";+ virtual: true;onPop?: () => void;- };+ });export type SdkInternalNavigationContextValue = {stack: SdkInternalNavigationEntry[];diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsxindex 8f16cc7b019..fbd734e21f5 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx@@ -186,9 +186,10 @@ export const SdkQuestionProvider = ({// Push virtual entry if last entry is NOT already a question drillconst currentEntry = navigation?.stack.at(-1);- if (currentEntry?.type !== "virtual-question-drill") {+ if (currentEntry?.type !== "question-drill") {navigation?.push({- type: "virtual-question-drill",+ type: "question-drill",+ virtual: true,name: question?.displayName() ?? t`Question`,onPop: () => loadAndQueryQuestion(),});diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsxindex 71d29c4bdec..acff5fc0817 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx@@ -317,16 +317,18 @@ const SdkDashboardInner = ({// For drills, only push if not already a question drill// One press of back button should undo all of themconst currentEntry = sdkNavigation?.stack.at(-1);- if (currentEntry?.type !== "virtual-question-drill") {+ if (currentEntry?.type !== "question-drill") {sdkNavigation?.push({- type: "virtual-question-drill",+ type: "question-drill",+ virtual: true,name: opts.previousCard.name ?? t`Question`,onPop: () => onNavigateBackToDashboard(),});}} else {sdkNavigation?.push({- type: "virtual-open-card",+ type: "open-card",+ virtual: true,name: opts.previousCard.name ?? t`Question`,onPop: () => onNavigateBackToDashboard(),});@@ -410,7 +412,8 @@ const SdkDashboardInner = ({* @see {@link https://github.com/metabase/metabase/blob/4453fa8363eb37062a159f398050d050d91397a9/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx#L30-L34}*/sdkNavigation?.push({- type: "virtual-new-question",+ type: "new-question",+ virtual: true,onPop: () => setRenderMode("dashboard"),});setRenderMode("queryBuilder");@@ -425,7 +428,8 @@ const SdkDashboardInner = ({});} else {sdkNavigation?.push({- type: "virtual-new-question",+ type: "new-question",+ virtual: true,onPop: () => setRenderMode("dashboard"),});setRenderMode("queryBuilder");diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsxindex 3722fe924ac..efc16929451 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx@@ -1,9 +1,11 @@-import { useEffect, useMemo, useState } from "react";+import { useMemo, useState } from "react";+import { useMount } from "react-use";import { P, match } from "ts-pattern";import { t } from "ttag";import _ from "underscore";import { SdkBreadcrumbs } from "embedding-sdk-bundle/components/private/SdkBreadcrumbs";+import { useSdkInternalNavigation } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";import { CollectionBrowser } from "embedding-sdk-bundle/components/public/CollectionBrowser";import { CreateDashboardModal } from "embedding-sdk-bundle/components/public/CreateDashboardModal";import { InteractiveQuestion } from "embedding-sdk-bundle/components/public/InteractiveQuestion";@@ -35,11 +37,12 @@ type MetabaseBrowserView =const BREADCRUMB_HEIGHT = "3.5rem";export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {+ const navigationContext = useSdkInternalNavigation();const { initialCollection } = settings;const isReadOnly = settings.readOnly ?? true;- const { breadcrumbs, currentLocation, reportLocation } = useSdkBreadcrumbs();+ const { breadcrumbs, reportLocation } = useSdkBreadcrumbs();const { canWrite: canWriteToInitialCollection } =useCollectionData(initialCollection);@@ -49,6 +52,21 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {id: initialCollection,});+ useMount(() => {+ if (navigationContext.stack.length === 0) {+ // Populate the initial entry of the stack when this is the root/starting point+ navigationContext.push({ type: "metabase-browser", virtual: false });+ }+ });++ const hasNavigatedAway = useMemo(() => {+ // If we've opened a dashboard and we navigate away with drills/SdkNavigationProvider, we need to unmount the dashboard.+ // Otherwise if we navigate to another dashboard we'll have two dashboards trying to access the same Redux state.+ return navigationContext.stack.some(+ (entry) => entry.type !== "metabase-browser" && !entry.virtual,+ );+ }, [navigationContext.stack]);+// Use the last collection in the breadcrumb as the target for saving new questions.const targetCollection = useMemo(() => {const collectionBreadcrumbs = breadcrumbs.filter(@@ -60,109 +78,125 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {return lastCollectionItem?.id ?? initialCollection;}, [breadcrumbs, initialCollection]);- // If a user clicks on a collection breadcrumb, switch the view.- useEffect(() => {- if (currentLocation?.type === "collection") {- setCurrentView({ type: currentLocation.type, id: currentLocation.id });- }- }, [currentLocation]);-- const viewContent = match(currentView)- .with({ type: "exploration" }, () => (- <Box px="xl" h="100%">- <InteractiveQuestion- questionId="new"- height="100%"- withDownloads- isSaveEnabled={!isReadOnly}- entityTypes={settings.dataPickerEntityTypes}- targetCollection={targetCollection}- />- </Box>- ))- .with({ type: "create-dashboard" }, () => (- <CreateDashboardModal- onCreate={(dashboard) => {- // Update the breadcrumbs to reflect the collection where the dashboard was saved- if (dashboard.collection) {- reportLocation({- type: "collection",- id: dashboard.collection.id,- name: dashboard.collection.name,- });- }-- // On the next tick, update the current view.- // This is needed for when we create new collections.- setTimeout(() => {- setCurrentView({ type: "dashboard", id: dashboard.id });- }, 0);- }}- onClose={() =>- setCurrentView({ type: "collection", id: targetCollection })- }- initialCollectionId={targetCollection}- />- ))- .with({ type: "dashboard", id: P.nonNullable }, ({ id }) => {- const dashboardView = isReadOnly ? (- <InteractiveDashboard- dashboardId={id}- withDownloads- style={{ height: "100%" }}- drillThroughQuestionProps={{ isSaveEnabled: false }}- enableEntityNavigation={settings.enableEntityNavigation}- />- ) : (- <EditableDashboard- withCardTitle- dashboardId={id}- style={{ height: "100%" }}- enableEntityNavigation={settings.enableEntityNavigation}- />- );-- // The overflow-scroll is needed otherwise the editable- // dashboard header gets scrolled out of view.- return (- <Group h="100%" style={{ overflowY: "scroll" }}>- {dashboardView}- </Group>- );- })- .with(- { type: P.union("question", "metric", "model"), id: P.nonNullable },- ({ id }) => (- <Box px="xl" h="100%">- <InteractiveQuestion- questionId={id}- height="100%"- withDownloads- isSaveEnabled={!isReadOnly}- targetCollection={targetCollection}+ const viewContent = hasNavigatedAway+ ? null+ : match(currentView)+ .with({ type: "exploration" }, () => (+ <Box px="xl" h="100%">+ <InteractiveQuestion+ questionId="new"+ height="100%"+ withDownloads+ isSaveEnabled={!isReadOnly}+ entityTypes={settings.dataPickerEntityTypes}+ targetCollection={targetCollection}+ />+ </Box>+ ))+ .with({ type: "create-dashboard" }, () => (+ <CreateDashboardModal+ onCreate={(dashboard) => {+ // Update the breadcrumbs to reflect the collection where the dashboard was saved+ if (dashboard.collection) {+ reportLocation({+ type: "collection",+ id: dashboard.collection.id,+ name: dashboard.collection.name,+ });+ }++ // On the next tick, update the current view.+ // This is needed for when we create new collections.+ setTimeout(() => {+ setCurrentView({ type: "dashboard", id: dashboard.id });+ }, 0);+ }}+ onClose={() =>+ setCurrentView({ type: "collection", id: targetCollection })+ }+ initialCollectionId={targetCollection}/>- </Box>- ),- )- .with({ type: "collection" }, (view) => (- <Box px="xl" pt="lg" style={{ overflowY: "auto" }}>- <CollectionBrowser- collectionId={view.id}- visibleColumns={settings.collectionVisibleColumns}- visibleEntityTypes={settings.collectionEntityTypes}- pageSize={settings.collectionPageSize}- onClick={(item) => {- const type = match<string, SdkBreadcrumbItemType>(item.model)- .with("card", () => "question")- .with("dataset", () => "model")- .otherwise((model) => model as SdkBreadcrumbItemType);-- setCurrentView({ type, id: item.id });- }}- />- </Box>- ))- .otherwise(() => null);+ ))+ .with({ type: "dashboard", id: P.nonNullable }, ({ id }) => {+ const dashboardView = isReadOnly ? (+ <InteractiveDashboard+ dashboardId={id}+ withDownloads+ style={{ height: "100%" }}+ drillThroughQuestionProps={{ isSaveEnabled: false }}+ enableEntityNavigation={settings.enableEntityNavigation}+ />+ ) : (+ <EditableDashboard+ withCardTitle+ dashboardId={id}+ style={{ height: "100%" }}+ enableEntityNavigation={settings.enableEntityNavigation}+ />+ );++ // The overflow-scroll is needed otherwise the editable+ // dashboard header gets scrolled out of view.+ return (+ <Group h="100%" style={{ overflowY: "scroll" }}>+ {dashboardView}+ </Group>+ );+ })+ .with(+ { type: P.union("question", "metric", "model"), id: P.nonNullable },+ ({ id }) => (+ <Box px="xl" h="100%">+ <InteractiveQuestion+ questionId={id}+ height="100%"+ withDownloads+ isSaveEnabled={!isReadOnly}+ targetCollection={targetCollection}+ />+ </Box>+ ),+ )+ .with({ type: "collection" }, (view) => (+ <Box px="xl" pt="lg" style={{ overflowY: "auto" }}>+ <CollectionBrowser+ collectionId={view.id}+ visibleColumns={settings.collectionVisibleColumns}+ visibleEntityTypes={settings.collectionEntityTypes}+ pageSize={settings.collectionPageSize}+ onClick={(item) => {+ const type = match<string, SdkBreadcrumbItemType>(item.model)+ .with("card", () => "question")+ .with("dataset", () => "model")+ .otherwise((model) => model as SdkBreadcrumbItemType);++ setCurrentView({ type, id: item.id });++ if (type !== "collection") {+ // If we're navigating to something other than a collection, we need to keep the navigation stack updated+ // to make the back button work correctly+ navigationContext.push({+ type: match(type)+ .with("dashboard", () => "dashboard" as const)+ .with(+ "question",+ "metric",+ "model",+ () => "question" as const,+ )+ .exhaustive(),+ virtual: true,+ id: item.id,+ name: item.name,+ onPop: () =>+ setCurrentView({ type: "collection", id: view.id }),+ });+ }+ }}+ />+ </Box>+ ))+ .otherwise(() => null);const handleNewExploration = () => {setCurrentView({ type: "exploration" });@@ -192,7 +226,20 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {w="100%"><Group>- <SdkBreadcrumbs />+ <SdkBreadcrumbs+ onBreadcrumbClick={(item) => {+ if (item.type === "collection") {+ setCurrentView({ type: item.type, id: item.id });++ // If we selected a collection, we go back to the browser component, we need to clear the stack+ // metabase-browser is always at index 0, so we can pop length-1 times+ const count = navigationContext.stack.length - 1;+ for (let i = 0; i < count; i++) {+ navigationContext.pop();+ }+ }+ }}+ /></Group>{currentView.type === "collection" && (diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsxindex 36f2bbf281c..64910d12989 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx@@ -140,7 +140,7 @@ const SdkIframeEmbedView = ({componentName: "metabase-browser",},(settings) => (- <SdkInternalNavigationProvider>+ <SdkInternalNavigationProvider keepChildrenMounted>{/* re-mount breadcrumbs when initial collection changes */}<SdkBreadcrumbsProvider key={settings.initialCollection}><MetabaseBrowser settings={settings} />