Skip to content

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

feat(sdk, eajs): add support to show "all" collections in the browser components (#80881)

Nicolò Pretto2176f1859788
diff --git a/e2e/test-component/scenarios/embedding-sdk/collection-browser.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/collection-browser.cy.spec.tsx
index 48d4ba2877c..da5c3e2d62e 100644
--- a/e2e/test-component/scenarios/embedding-sdk/collection-browser.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/collection-browser.cy.spec.tsx
@@ -2,14 +2,21 @@ const { H } = cy;
import { CollectionBrowser } from "@metabase/embedding-sdk-react";
import { useState } from "react";
+import { USERS } from "e2e/support/cypress_data";
import {
+ DATA_GROUP_ID,
FIRST_COLLECTION_ENTITY_ID,
SECOND_COLLECTION_ENTITY_ID,
} from "e2e/support/cypress_sample_instance_data";
import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
+import { JWT_SHARED_SECRET } from "e2e/support/helpers/e2e-jwt-helpers";
import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers";
import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+import type { CollectionPermission } from "metabase-types/api";
+
+const READ: CollectionPermission = "read";
+const NONE: CollectionPermission = "none";
describe("scenarios > embedding-sdk > collection browser", () => {
describe("personal collection", () => {
@@ -91,6 +98,178 @@ describe("scenarios > embedding-sdk > collection browser", () => {
});
});
+ describe('collectionId="all"', () => {
+ const SHARED_TENANT_NAMESPACE = "shared-tenant-collection";
+
+ const TENANT = { name: "Acme", slug: "acme" };
+
+ const TENANT_USER = {
+ first_name: "Tina",
+ last_name: "Tenanton",
+ email: "[email protected]",
+ "@tenant": TENANT.slug,
+ };
+
+ const createSharedCollection = (name: string, parentId?: number) =>
+ cy.request("POST", "/api/collection", {
+ name,
+ namespace: SHARED_TENANT_NAMESPACE,
+ parent_id: parentId ?? null,
+ });
+
+ const setUpTenantsInstance = () => {
+ signInAsAdminAndEnableEmbeddingSdk();
+ H.updateSetting("use-tenants", true);
+
+ createSharedCollection("Shared Reports").then(({ body: collection }) => {
+ createSharedCollection("Shared Sub-Collection", collection.id);
+ });
+ };
+
+ describe("for a normal user", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn(USERS.normal);
+ });
+
+ it("should list the reachable roots, drill into one and come back", () => {
+ mountSdkContent(<CollectionBrowser collectionId="all" />);
+
+ getSdkRoot().within(() => {
+ cy.log("the personal collection sits beside `Our analytics`");
+ cy.findByTestId("all-collections-list").within(() => {
+ cy.findByText("Our analytics").should("exist");
+ cy.findByText("Your personal collection").should("exist");
+ });
+
+ cy.log("`Our analytics` opens and shows its contents");
+ cy.findByText("Our analytics").click();
+ // wait for the navigation out of the virtual root
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByText("Orders in a dashboard").should("exist");
+
+ cy.log("the `All collections` crumb returns to the virtual root");
+ cy.findByText("All collections").click();
+ cy.findByTestId("all-collections-list")
+ .findByText("Your personal collection")
+ .click();
+
+ cy.log("the personal collection does not sit under `Our analytics`");
+ cy.findByText("Robert Tableton's Personal Collection").should(
+ "exist",
+ );
+ cy.findByText("Our analytics").should("not.exist");
+ });
+ });
+ });
+
+ describe("for a tenant user", () => {
+ beforeEach(() => {
+ setUpTenantsInstance();
+
+ cy.request("PUT", "/api/setting", {
+ "jwt-user-provisioning-enabled?": true,
+ });
+ cy.request("POST", "/api/ee/tenant", TENANT);
+
+ cy.signOut();
+
+ cy.task<string>("signJwt", {
+ payload: {
+ ...TENANT_USER,
+ exp: Math.round(Date.now() / 1000) + 10 * 60,
+ },
+ secret: JWT_SHARED_SECRET,
+ }).then((jwt) => mockAuthProviderAndJwtSignIn(undefined, { jwt }));
+ });
+
+ it("should list Our data and the shared tenant collections, and drill into them", () => {
+ mountSdkContent(<CollectionBrowser collectionId="all" />);
+
+ getSdkRoot().within(() => {
+ cy.log("the tenant collection shows up as `Our data`");
+ cy.findByTestId("all-collections-list").within(() => {
+ cy.findByText("Shared Reports").should("exist");
+ cy.findByText("Our data").should("exist");
+ cy.findByText("Your personal collection").should("exist");
+ });
+
+ cy.log("the shallow tree lists only the top level, not the children");
+ cy.findByText("Shared Sub-Collection").should("not.exist");
+
+ cy.log("a shared tenant collection opens like any other row");
+ cy.findByText("Shared Reports").click();
+ // wait for the navigation out of the virtual root
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByText("Shared Sub-Collection").should("exist");
+ cy.findByText("Our analytics").should("not.exist");
+
+ cy.log("`Our data` opens the same way");
+ cy.findByText("All collections").click();
+ cy.findByTestId("all-collections-list")
+ .findByText("Our data")
+ .click();
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByText("All collections").should("exist");
+ cy.findByText("Our analytics").should("not.exist");
+ });
+ });
+ });
+
+ describe("for a user with no access to the root", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ H.createCollection({ name: "Accessible Collection" }).then(
+ ({ body: collection }) => {
+ H.createDashboard({
+ name: "Accessible Dashboard",
+ collection_id: collection.id,
+ });
+
+ cy.updateCollectionGraph({
+ [DATA_GROUP_ID]: { root: NONE, [collection.id]: READ },
+ });
+ },
+ );
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn(USERS.nocollection);
+ });
+
+ it("should promote the collections below the root, drill into one and come back", () => {
+ mountSdkContent(<CollectionBrowser collectionId="all" />);
+
+ getSdkRoot().within(() => {
+ cy.log("the reachable collections replace `Our analytics`, no error");
+ cy.findByTestId("all-collections-list").within(() => {
+ cy.findByText("Accessible Collection").should("exist");
+ cy.findByText("Your personal collection").should("exist");
+ });
+ cy.findByText("Our analytics").should("not.exist");
+ cy.findByText("You don't have access to this collection").should(
+ "not.exist",
+ );
+
+ cy.log("drilling in shows the contents, with no unreachable crumb");
+ cy.findByText("Accessible Collection").click();
+ // wait for the navigation out of the virtual root
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByText("Accessible Dashboard").should("exist");
+ cy.findByText("Our analytics").should("not.exist");
+
+ cy.log("the `All collections` crumb returns to the virtual root");
+ cy.findByText("All collections").click();
+ cy.findByTestId("all-collections-list")
+ .findByText("Accessible Collection")
+ .should("exist");
+ });
+ });
+ });
+ });
+
describe("collection using entity ids", () => {
beforeEach(() => {
signInAsAdminAndEnableEmbeddingSdk();
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/metabase-browser.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/metabase-browser.cy.spec.ts
index d70d374e9e2..76e7d2c9892 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/metabase-browser.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/metabase-browser.cy.spec.ts
@@ -1,5 +1,8 @@
+import { USERS } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { DATA_GROUP_ID } from "e2e/support/cypress_sample_instance_data";
+import { JWT_SHARED_SECRET } from "e2e/support/helpers/e2e-jwt-helpers";
+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
import type { CollectionPermission } from "metabase-types/api";
const { H } = cy;
@@ -147,6 +150,203 @@ describe("scenarios > embedding > sdk iframe embedding > metabase-browser", () =
});
});
+ describe('initial-collection="all"', () => {
+ const SHARED_TENANT_NAMESPACE = "shared-tenant-collection";
+
+ const TENANT = { name: "Acme", slug: "acme" };
+
+ const TENANT_USER = {
+ first_name: "Tina",
+ last_name: "Tenanton",
+ email: "[email protected]",
+ "@tenant": TENANT.slug,
+ };
+
+ const createSharedCollection = (name: string, parentId?: number) =>
+ cy.request("POST", "/api/collection", {
+ name,
+ namespace: SHARED_TENANT_NAMESPACE,
+ parent_id: parentId ?? null,
+ });
+
+ const setUpTenantsInstance = () => {
+ H.prepareSdkIframeEmbedTest({ signOut: false });
+ H.updateSetting("use-tenants", true);
+
+ createSharedCollection("Shared Reports").then(({ body: collection }) => {
+ createSharedCollection("Shared Sub-Collection", collection.id);
+ });
+ };
+
+ const embedAllCollections = () =>
+ setupEmbed(`
+ <metabase-browser
+ initial-collection="all"
+ read-only="false"
+ />
+ `);
+
+ describe("for a normal user", () => {
+ beforeEach(() => {
+ H.prepareSdkIframeEmbedTest({ signOut: false });
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn(USERS.normal);
+ });
+
+ it("should list the reachable roots, drill into one and come back", () => {
+ embedAllCollections();
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.log("the personal collection sits beside `Our analytics`");
+ cy.findByTestId("all-collections-list").within(() => {
+ cy.findByText("Our analytics").should("be.visible");
+ cy.findByText("Your personal collection").should("be.visible");
+ });
+
+ cy.log("`Our analytics` opens and shows its contents");
+ cy.findByText("Our analytics").click();
+ // wait for the navigation out of the virtual root
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByText("Orders in a dashboard").should("be.visible");
+
+ cy.log("the `All collections` crumb returns to the virtual root");
+ cy.findByTestId("sdk-breadcrumbs")
+ .findByText("All collections")
+ .click();
+ cy.findByTestId("all-collections-list")
+ .findByText("Your personal collection")
+ .click();
+
+ cy.log("the personal collection does not sit under `Our analytics`");
+ cy.findByTestId("sdk-breadcrumbs")
+ .findByText("Our analytics")
+ .should("not.exist");
+ });
+ });
+ });
+
+ describe("for a tenant user", () => {
+ beforeEach(() => {
+ setUpTenantsInstance();
+
+ cy.request("PUT", "/api/setting", {
+ "jwt-user-provisioning-enabled?": true,
+ });
+ cy.request("POST", "/api/ee/tenant", TENANT);
+
+ cy.signOut();
+
+ cy.task<string>("signJwt", {
+ payload: {
+ ...TENANT_USER,
+ exp: Math.round(Date.now() / 1000) + 10 * 60,
+ },
+ secret: JWT_SHARED_SECRET,
+ }).then((jwt) => mockAuthProviderAndJwtSignIn(undefined, { jwt }));
+ });
+
+ it("should list Our data and the shared tenant collections, and drill into them", () => {
+ embedAllCollections();
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.log("the tenant collection shows up as `Our data`");
+ cy.findByTestId("all-collections-list").within(() => {
+ cy.findByText("Shared Reports").should("be.visible");
+ cy.findByText("Our data").should("be.visible");
+ cy.findByText("Your personal collection").should("be.visible");
+ });
+
+ cy.log("the shallow tree lists only the top level, not the children");
+ cy.findByText("Shared Sub-Collection").should("not.exist");
+
+ cy.log("a shared tenant collection opens like any other row");
+ cy.findByText("Shared Reports").click();
+ // wait for the navigation out of the virtual root
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByText("Shared Sub-Collection").should("be.visible");
+ cy.findByTestId("sdk-breadcrumbs")
+ .findByText("Our analytics")
+ .should("not.exist");
+
+ cy.log("`Our data` opens the same way");
+ cy.findByTestId("sdk-breadcrumbs")
+ .findByText("All collections")
+ .click();
+ cy.findByTestId("all-collections-list")
+ .findByText("Our data")
+ .click();
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByTestId("sdk-breadcrumbs").within(() => {
+ cy.findByText("All collections").should("be.visible");
+ cy.findByText("Our analytics").should("not.exist");
+ });
+ });
+ });
+ });
+
+ describe("for a user with no access to the root", () => {
+ it("should promote the collections below the root, drill into one and come back", () => {
+ H.prepareSdkIframeEmbedTest({ signOut: false });
+
+ H.createCollection({ name: "Accessible Collection" }).then(
+ ({ body: collection }) => {
+ H.createDashboard({
+ name: "Accessible Dashboard",
+ collection_id: collection.id,
+ });
+
+ cy.updateCollectionGraph({
+ [DATA_GROUP_ID]: {
+ root: NONE,
+ [collection.id]: READ,
+ },
+ });
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn(USERS.nocollection);
+
+ embedAllCollections();
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.log(
+ "the virtual root lists what the user can reach, with no error",
+ );
+ cy.findByTestId("all-collections-list").within(() => {
+ cy.findByText("Your personal collection").should("be.visible");
+ cy.findByText("Accessible Collection").should("be.visible");
+ });
+ cy.findByText("Our analytics").should("not.exist");
+ cy.findByText("You don't have access to this collection").should(
+ "not.exist",
+ );
+
+ cy.log("drilling in shows the collection's contents");
+ cy.findByText("Accessible Collection").click();
+ // wait for the navigation out of the virtual root
+ cy.findByTestId("all-collections-list").should("not.exist");
+ cy.findByText("Accessible Dashboard").should("be.visible");
+
+ cy.log("the trail has no unreachable root crumb");
+ cy.findByTestId("sdk-breadcrumbs").within(() => {
+ cy.findByText("All collections").should("be.visible");
+ cy.findByText("Our analytics").should("not.exist");
+ });
+
+ cy.log("the `All collections` crumb returns to the virtual root");
+ cy.findByTestId("sdk-breadcrumbs")
+ .findByText("All collections")
+ .click();
+ cy.findByTestId("all-collections-list")
+ .findByText("Your personal collection")
+ .should("be.visible");
+ });
+ },
+ );
+ });
+ });
+ });
+
it("should reset `New question` editor state when clicking 'New question' breadcrumb after selecting a filter", () => {
H.prepareSdkIframeEmbedTest({
withToken: "bleeding-edge",
diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.ts
index a8d9e9aea81..4dfe11dc349 100644
--- a/enterprise/frontend/src/embedding-sdk-package/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts
@@ -148,6 +148,7 @@ export type {
ParameterChangePayload,
UseMetabotResult,
SdkEntityToken,
+ SdkBrowserCollectionId,
SdkCollectionId,
SdkDashboardId,
SdkDashboardEntityPublicProps,
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.stories.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.stories.tsx
index 264975db588..15da50e9b08 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.stories.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.stories.tsx
@@ -23,9 +23,14 @@ export default {
decorators: [CommonSdkStoryWrapper],
};
+type EntityBreadcrumbType = Exclude<SdkBreadcrumbItemType, "all-collections">;
+
type View =
| { type: "collection"; id: SdkCollectionId }
- | { type: Exclude<SdkBreadcrumbItemType, "collection">; id: string | number };
+ | {
+ type: Exclude<EntityBreadcrumbType, "collection">;
+ id: string | number;
+ };
const SdkBreadcrumbStory = () => {
const { currentLocation } = useSdkBreadcrumbs();
@@ -44,11 +49,11 @@ const SdkBreadcrumbStory = () => {
<CollectionBrowser
collectionId={view.id}
onClick={(item) => {
- const type = match<string, SdkBreadcrumbItemType>(item.model)
+ const type = match<string, EntityBreadcrumbType>(item.model)
.with("card", () => "question")
.with("dataset", () => "model")
- // Unjustified type cast. FIXME
- .otherwise((model) => model as SdkBreadcrumbItemType);
+ // A collection item is never the virtual "all collections" root.
+ .otherwise((model) => model as EntityBreadcrumbType);
setView({ type, id: item.id });
}}
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsx
index 1059d3f20cc..f0e8d6e3122 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbs.tsx
@@ -37,7 +37,7 @@ export const SdkBreadcrumbs = ({
<PublicComponentStylesWrapper className={className} style={style}>
<Flex align="center" data-testid="sdk-breadcrumbs">
{breadcrumbs.map((breadcrumb, index) => (
- <Fragment key={breadcrumb.id}>
+ <Fragment key={`${breadcrumb.type}-${breadcrumb.id}`}>
<Breadcrumb
icon={getBreadcrumbIcon(breadcrumb.type)}
onClick={() => {
@@ -60,6 +60,7 @@ export const SdkBreadcrumbs = ({
const getBreadcrumbIcon = (type: SdkBreadcrumbItemType): IconName =>
match<SdkBreadcrumbItemType, IconName>(type)
+ .with("all-collections", () => "folder")
.with("collection", () => "folder")
.with("dashboard", () => "dashboard")
.with("question", () => "table2")
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx
index 0df1765cbeb..40a30fca193 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/setup.spec.tsx
@@ -51,9 +51,14 @@ jest.mock("metabase/common/hooks/use-locale", () => ({
// Unjustified type cast. FIXME
const useLocaleMock = useLocale as jest.Mock;
+type EntityBreadcrumbType = Exclude<SdkBreadcrumbItemType, "all-collections">;
+
type View =
| { type: "collection"; id: SdkCollectionId }
- | { type: Exclude<SdkBreadcrumbItemType, "collection">; id: string | number };
+ | {
+ type: Exclude<EntityBreadcrumbType, "collection">;
+ id: string | number;
+ };
export const BreadcrumbsTestComponent = () => {
const { currentLocation } = useSdkBreadcrumbs();
@@ -70,11 +75,11 @@ export const BreadcrumbsTestComponent = () => {
<CollectionBrowser
collectionId={view.id}
onClick={(item) => {
- const type = match<string, SdkBreadcrumbItemType>(item.model)
+ const type = match<string, EntityBreadcrumbType>(item.model)
.with("card", () => "question")
.with("dataset", () => "model")
- // Unjustified type cast. FIXME
- .otherwise((model) => model as SdkBreadcrumbItemType);
+ // A collection item is never the virtual "all-collections" root.
+ .otherwise((model) => model as EntityBreadcrumbType);
setView({ type, id: item.id });
}}
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/utils/update-breadcrumbs.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/utils/update-breadcrumbs.ts
index 6ea589138aa..11fc746857f 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/utils/update-breadcrumbs.ts
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkBreadcrumbs/utils/update-breadcrumbs.ts
@@ -16,7 +16,7 @@ export function updateBreadcrumbsWithItem(
return breadcrumbs;
}
- if (nextItem.type === "collection") {
+ if (nextItem.type === "collection" || nextItem.type === "all-collections") {
return (
removeBreadcrumbsAfterItem(breadcrumbs, nextItem) ?? [
...breadcrumbs,
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx
index 363672bbaf9..d759044dc44 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx
@@ -1,27 +1,43 @@
-import { type ComponentType, useEffect } from "react";
+import { type ComponentType, useEffect, useMemo } from "react";
import { t } from "ttag";
import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";
import {
CollectionNotFoundError,
+ SdkError,
SdkLoader,
withPublicComponentWrapper,
} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
+import {
+ useAllCollectionsItems,
+ withRealCollectionId,
+} from "embedding-sdk-bundle/hooks/private/use-all-collections-items";
import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
import type {
MetabaseCollectionItem,
- SdkCollectionId,
+ SdkBrowserCollectionId,
} from "embedding-sdk-bundle/types/collection";
import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";
import { COLLECTION_PAGE_SIZE } from "metabase/collections/components/CollectionContent";
import { CollectionItemsTable } from "metabase/collections/components/CollectionContent/CollectionItemsTable";
import { EmptyState } from "metabase/common/components/EmptyState";
+import { ItemsTable } from "metabase/common/components/ItemsTable";
+import { getVisibleColumnsMap } from "metabase/common/components/ItemsTable/utils";
+import { PaginationControls } from "metabase/common/components/PaginationControls";
import { useLocale } from "metabase/common/hooks/use-locale";
+import { usePagination } from "metabase/common/hooks/use-pagination";
+import { CollectionBreadcrumbsView } from "metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbsView";
+import { collectionToCrumbs } from "metabase/nav/components/CollectionBreadcrumbs/utils";
import { CollectionBreadcrumbs } from "metabase/nav/containers/CollectionBreadcrumbs";
-import { Icon, Stack } from "metabase/ui";
+import { Box, Group, Icon, Stack } from "metabase/ui";
import { isNotNull } from "metabase/utils/types";
-import type { CollectionItemModel } from "metabase-types/api";
+import type {
+ Collection,
+ CollectionId,
+ CollectionItem,
+ CollectionItemModel,
+} from "metabase-types/api";
import { isObject } from "metabase-types/guards";
import { collectionBrowserPropsSchema } from "./CollectionBrowser.schema";
@@ -60,6 +76,16 @@ const ENTITY_NAME_MAP: Partial<
model: "dataset",
};
+/**
+ * The API reports "Our analytics" as an ancestor of every top-level collection,
+ * the personal one included. Under the virtual root they are siblings, so keep
+ * the crumb only for collections really inside it.
+ */
+const getAllModeBaseCollectionId = (
+ collection: Collection,
+): CollectionId | null =>
+ collection.is_personal || collection.namespace != null ? null : "root";
+
/**
* @interface
* @expand
@@ -67,9 +93,17 @@ const ENTITY_NAME_MAP: Partial<
*/
export type CollectionBrowserProps = {
/**
- * The numerical ID of the collection, "personal" for the user's personal collection, "tenant" for the user's tenant collection, or "root" for the root collection. You can find this ID in the URL when accessing a collection in your Metabase instance. For example, the collection ID in `http://localhost:3000/collection/1-my-collection` would be `1`. Defaults to "personal"
+ * The collection to show:
+ * - a number - the collection ID. You can find it in the URL of a collection in your Metabase instance. For `http://localhost:3000/collection/1-my-collection` the ID is `1`.
+ * - an entity ID string, e.g. `"nT4gT_MOnU1uJ1zLsGaTV"`.
+ * - `"personal"` - the user's personal collection.
+ * - `"tenant"` - the user's tenant collection.
+ * - `"root"` - the root collection, "Our analytics".
+ * - `"all"` - a list that contains the root collection, the tenant collections, and the user's personal collection.
+ *
+ * Defaults to `"personal"`.
*/
- collectionId?: SdkCollectionId;
+ collectionId?: SdkBrowserCollectionId;
/**
* The number of items to display per page. The default is 25.
@@ -115,6 +149,9 @@ export const CollectionBrowserInner = ({
}: CollectionBrowserProps) => {
useTrackSdkComponentMount("CollectionBrowser", null, {});
+ // "all" is a virtual top level, not a collection, so it never reaches a URL
+ const isAllMode = collectionId === "all";
+
const {
baseCollectionId,
internalCollectionId,
@@ -128,12 +165,46 @@ export const CollectionBrowserInner = ({
const { isBreadcrumbEnabled: isGlobalBreadcrumbEnabled, reportLocation } =
useSdkBreadcrumbs();
+ const isAtAllModeRoot = isAllMode && effectiveCollectionId == null;
+
+ const {
+ items: allCollections,
+ isLoading: isLoadingAllCollections,
+ error: allCollectionsError,
+ } = useAllCollectionsItems({ enabled: isAtAllModeRoot });
+
+ // The virtual root rows are synthesized, so they carry no edit info and cannot
+ // be archived. Those columns would render empty for every row.
+ const allModeRootColumnsMap = useMemo(
+ () =>
+ getVisibleColumnsMap(
+ visibleColumns.filter(
+ (column) =>
+ !["lastEditedBy", "lastEditedAt", "archive"].includes(column),
+ ),
+ ),
+ [visibleColumns],
+ );
+
+ // pagination for the virtual root
+ const { page, setPage, handleNextPage, handlePreviousPage } = usePagination();
+
useEffect(() => {
setInternalCollectionId(baseCollectionId);
}, [baseCollectionId, setInternalCollectionId]);
useEffect(() => {
- if (isGlobalBreadcrumbEnabled && !isFetchingCollection && collection) {
+ if (!isGlobalBreadcrumbEnabled || isFetchingCollection) {
+ return;
+ }
+
+ if (isAtAllModeRoot) {
+ reportLocation({
+ type: "all-collections",
+ id: "all",
+ name: t`All collections`,
+ });
+ } else if (collection) {
reportLocation({
type: "collection",
id: collection.id,
@@ -143,6 +214,7 @@ export const CollectionBrowserInner = ({
}, [
isGlobalBreadcrumbEnabled,
isFetchingCollection,
+ isAtAllModeRoot,
collection,
reportLocation,
]);
@@ -159,10 +231,20 @@ export const CollectionBrowserInner = ({
);
}
+ if (isAtAllModeRoot && allCollectionsError) {
+ return <SdkError message={t`Failed to load collections`} />;
+ }
+
+ if (isAtAllModeRoot && isLoadingAllCollections) {
+ return <SdkLoader />;
+ }
+
const onClickItem = (item: MetabaseCollectionItem) => {
onClick?.(item);
if (item.model === "collection") {
+ setPage(0);
+
if (isGlobalBreadcrumbEnabled) {
reportLocation({
type: "collection",
@@ -176,29 +258,99 @@ export const CollectionBrowserInner = ({
}
};
+ const onClickAllModeRootItem = (item: CollectionItem) =>
+ onClickItem(withRealCollectionId(item));
+
const collectionTypes = visibleEntityTypes
.map((entityType) => ENTITY_NAME_MAP[entityType])
.filter(isNotNull);
+ const allModeCrumbs = [
+ {
+ kind: "static" as const,
+ key: "all",
+ icon: "collection" as const,
+ label: t`All collections`,
+ onClick: () => {
+ setPage(0);
+ setInternalCollectionId(undefined);
+ },
+ },
+ ...(collection
+ ? collectionToCrumbs({
+ collection,
+ baseCollectionId: getAllModeBaseCollectionId(collection),
+ onClick: (item) => setInternalCollectionId(item.id),
+ })
+ : []),
+ ];
+
+ // api keys don't have a personal collection, so the root could be empty
+ const isAllModeRootEmpty = isAtAllModeRoot && allCollections.length === 0;
+
+ const visibleAllModeRootItems = allCollections.slice(
+ page * pageSize,
+ (page + 1) * pageSize,
+ );
+
return (
<Stack w="100%" h="100%" gap="sm" className={className} style={style}>
- {!isGlobalBreadcrumbEnabled && (
- <CollectionBreadcrumbs
- collectionId={internalCollectionId ?? undefined}
- onClick={(item) => setInternalCollectionId(item.id)}
- baseCollectionId={baseCollectionId}
- />
+ {!isGlobalBreadcrumbEnabled &&
+ (isAllMode ? (
+ <CollectionBreadcrumbsView path={allModeCrumbs} />
+ ) : (
+ <CollectionBreadcrumbs
+ collectionId={internalCollectionId ?? undefined}
+ onClick={(item) => setInternalCollectionId(item.id)}
+ baseCollectionId={baseCollectionId}
+ />
+ ))}
+
+ {isAllModeRootEmpty &&
+ (EmptyContentComponent ? (
+ <EmptyContentComponent />
+ ) : (
+ <EmptyState
+ title={t`There are no collections to show`}
+ illustrationElement={<Icon name="collection" size={100} />}
+ />
+ ))}
+
+ {isAtAllModeRoot && !isAllModeRootEmpty && (
+ <Box w="100%" data-testid="all-collections-list">
+ <ItemsTable
+ items={visibleAllModeRootItems}
+ visibleColumnsMap={allModeRootColumnsMap}
+ onClick={onClickAllModeRootItem}
+ />
+
+ {allCollections.length > pageSize && (
+ <Group justify="flex-end" my="md">
+ <PaginationControls
+ showTotal
+ page={page}
+ pageSize={pageSize}
+ total={allCollections.length}
+ itemsLength={visibleAllModeRootItems.length}
+ onNextPage={handleNextPage}
+ onPreviousPage={handlePreviousPage}
+ />
+ </Group>
+ )}
+ </Box>
)}
- <CollectionItemsTable
- collectionId={effectiveCollectionId ?? undefined}
- onClick={onClickItem}
- pageSize={pageSize}
- models={collectionTypes}
- showDashboardQuestions={showDashboardQuestions}
- visibleColumns={visibleColumns}
- EmptyContentComponent={EmptyContentComponent ?? undefined}
- />
+ {!isAtAllModeRoot && (
+ <CollectionItemsTable
+ collectionId={effectiveCollectionId ?? undefined}
+ onClick={onClickItem}
+ pageSize={pageSize}
+ models={collectionTypes}
+ showDashboardQuestions={showDashboardQuestions}
+ visibleColumns={visibleColumns}
+ EmptyContentComponent={EmptyContentComponent ?? undefined}
+ />
+ )}
</Stack>
);
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
index 330a40caf59..16d07cfa1b8 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
@@ -1,9 +1,13 @@
+import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import type { ComponentProps } from "react";
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
+ setupCollectionByIdEndpoint,
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
+ setupRootCollectionItemsEndpoint,
} from "__support__/server-mocks";
import { screen, waitFor, within } from "__support__/ui";
import {
@@ -15,12 +19,21 @@ import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
import { ROOT_COLLECTION } from "metabase/common/collections/constants";
import { useLocale } from "metabase/common/hooks/use-locale";
-import type { Collection, CollectionItem, User } from "metabase-types/api";
+import { reinitialize as reinitializePlugins } from "metabase/plugins";
+import { defer } from "metabase/utils/promise";
+import type {
+ Collection,
+ CollectionItem,
+ TokenFeatures,
+ User,
+} from "metabase-types/api";
import {
createMockCollection,
createMockCollectionItem,
+ createMockSettings,
createMockUser,
} from "metabase-types/api/mocks";
+import { createMockEntityId } from "metabase-types/api/mocks/entity-id";
jest.mock("metabase/common/hooks/use-locale", () => ({
useLocale: jest.fn(),
@@ -29,24 +42,74 @@ jest.mock("metabase/common/hooks/use-locale", () => ({
// Unjustified type cast. FIXME
const useLocaleMock = useLocale as jest.Mock;
+const ROOT_TEST_COLLECTION = createMockCollection({
+ ...ROOT_COLLECTION,
+ can_write: false,
+ effective_ancestors: [],
+ id: "root",
+});
+
+const PERSONAL_COLLECTION_ID = 1;
+
const BOBBY_TEST_COLLECTION = createMockCollection({
archived: false,
can_write: true,
description: null,
- id: 1,
+ id: PERSONAL_COLLECTION_ID,
location: "/",
name: "Bobby Tables's Personal Collection",
personal_owner_id: 100,
+ is_personal: true,
+ effective_ancestors: [ROOT_TEST_COLLECTION],
});
-const ROOT_TEST_COLLECTION = createMockCollection({
- ...ROOT_COLLECTION,
- can_write: false,
+const TEST_COLLECTIONS = [ROOT_TEST_COLLECTION, BOBBY_TEST_COLLECTION];
+
+const NESTED_COLLECTION_ID = 2;
+const NESTED_COLLECTION_NAME = "Nested Collection";
+
+const TENANT_COLLECTION_ID = 777;
+
+const TENANT_USER = createMockUser({
+ tenant_collection_id: TENANT_COLLECTION_ID,
+});
+
+const SHARED_REPORTS_ID = 11;
+const SHARED_REPORTS_ENTITY_ID = createMockEntityId("sharedEntityId1234567");
+
+const SHARED_TENANT_COLLECTIONS = [
+ createMockCollection({
+ id: SHARED_REPORTS_ID,
+ name: "Shared reports",
+ namespace: "shared-tenant-collection",
+ entity_id: SHARED_REPORTS_ENTITY_ID,
+ }),
+ createMockCollection({
+ id: 12,
+ name: "Shared metrics",
+ namespace: "shared-tenant-collection",
+ }),
+];
+
+const TENANT_TOKEN_FEATURES: Partial<TokenFeatures> = {
+ embedding_sdk: true,
+ tenants: true,
+};
+
+// The promoted rows of a root 403. The API drops root from `effective_ancestors`
+// when the user cannot read it, so the fixture drops it too.
+const PROMOTED_COLLECTION_ID = 42;
+
+const PROMOTED_TEST_COLLECTION = createMockCollection({
+ id: PROMOTED_COLLECTION_ID,
+ name: "Promoted Collection",
+ location: "/",
effective_ancestors: [],
- id: "root",
});
-const TEST_COLLECTIONS = [ROOT_TEST_COLLECTION, BOBBY_TEST_COLLECTION];
+const USER_WITHOUT_PERSONAL_COLLECTION = createMockUser({
+ personal_collection_id: null,
+});
describe("CollectionBrowser", () => {
it("should render a loader when a locale is loading", async () => {
@@ -85,18 +148,10 @@ describe("CollectionBrowser", () => {
rootCollection: ROOT_TEST_COLLECTION,
});
- // API-key users (the data-app preview) come back with no
- // `personal_collection_id`, though the type marks it required — simulate
- // that shape.
- const userWithoutPersonalCollection = {
- ...createMockUser(),
- personal_collection_id: undefined,
- } as unknown as User;
-
renderWithSDKProviders(<CollectionBrowserInner collectionId="personal" />, {
componentProviderProps: { authConfig: createMockSdkConfig() },
storeInitialState: setupSdkState({
- currentUser: userWithoutPersonalCollection,
+ currentUser: USER_WITHOUT_PERSONAL_COLLECTION,
}),
});
@@ -121,15 +176,7 @@ describe("CollectionBrowser", () => {
expect(screen.getByTestId("items-table-head")).toBeInTheDocument();
});
- const columnNames: (string | null)[] = [];
-
- within(screen.getByTestId("items-table-head"))
- .getAllByRole("button")
- .forEach((el) => {
- columnNames.push(el.textContent);
- });
-
- expect(columnNames).toStrictEqual(["Type", "Name"]);
+ expect(getColumnNames()).toStrictEqual(["Type", "Name"]);
});
it("should NOT include description column by default", async () => {
@@ -139,15 +186,7 @@ describe("CollectionBrowser", () => {
expect(screen.getByTestId("items-table-head")).toBeInTheDocument();
});
- const columnNames: (string | null)[] = [];
-
- within(screen.getByTestId("items-table-head"))
- .getAllByRole("button")
- .forEach((el) => {
- columnNames.push(el.textContent);
- });
-
- expect(columnNames).not.toContain("Description");
+ expect(getColumnNames()).not.toContain("Description");
});
it("should show description column when explicitly included", async () => {
@@ -161,33 +200,7 @@ describe("CollectionBrowser", () => {
expect(screen.getByTestId("items-table-head")).toBeInTheDocument();
});
- const columnNames: (string | null)[] = [];
-
- within(screen.getByTestId("items-table-head"))
- .getAllByRole("button")
- .forEach((el) => {
- columnNames.push(el.textContent);
- });
-
- expect(columnNames).toStrictEqual(["Type", "Name", "Description"]);
- });
-
- it("should display description column as configured", async () => {
- await setup({
- props: {
- visibleColumns: ["type", "name", "description"],
- },
- });
-
- await waitFor(() => {
- expect(screen.getByTestId("items-table-head")).toBeInTheDocument();
- });
-
- const headerRow = screen.getByTestId("items-table-head");
- const columnHeaders = within(headerRow).getAllByRole("button");
- const columnTexts = columnHeaders.map((header) => header.textContent);
-
- expect(columnTexts).toContain("Description");
+ expect(getColumnNames()).toStrictEqual(["Type", "Name", "Description"]);
});
it("should hide dashboard questions by default", async () => {
@@ -231,8 +244,274 @@ describe("CollectionBrowser", () => {
expect(await screen.findByText(tenantCollection.name)).toBeInTheDocument();
expect(await screen.findByText(dashboardItem.name)).toBeInTheDocument();
});
+
+ describe('collectionId="all"', () => {
+ beforeEach(() => {
+ reinitializePlugins();
+ });
+
+ // GET /api/collection/root has three outcomes and each one leads somewhere
+ // different. Only a 403 means "you cannot read the root itself, but you can
+ // read what is inside it".
+ describe("/api/collection/root", () => {
+ it('should show the "Our analytics" row when the root is readable', async () => {
+ await setupAll();
+
+ expect(await screen.findByText("Our analytics")).toBeInTheDocument();
+ expect(
+ fetchMock.callHistory.calls("path:/api/collection/root/items"),
+ ).toHaveLength(0);
+ });
+
+ it("should show the collections inside the root when the root is forbidden", async () => {
+ await setupAll({
+ rootReadable: false,
+ rootCollectionItems: [
+ createMockCollectionItem({
+ id: PROMOTED_COLLECTION_ID,
+ model: "collection",
+ name: PROMOTED_TEST_COLLECTION.name,
+ }),
+ ],
+ });
+
+ expect(
+ await screen.findByText("Promoted Collection"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Our analytics")).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("sdk-error-container"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should show an error when the root fails for any other reason", async () => {
+ await setupAll({
+ rootReadable: false,
+ rootErrorStatus: 500,
+ waitForList: false,
+ });
+
+ expect(
+ await screen.findByText("Failed to load collections"),
+ ).toBeInTheDocument();
+ expect(
+ fetchMock.callHistory.calls("path:/api/collection/root/items"),
+ ).toHaveLength(0);
+ });
+ });
+
+ describe("should show an error when", () => {
+ it("the promoted items fail after a root 403", async () => {
+ await setupAll({
+ rootReadable: false,
+ rootItemsErrorStatus: 500,
+ waitForList: false,
+ });
+
+ expect(
+ await screen.findByText("Failed to load collections"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("all-collections-list"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("the shared tenant tree fails", async () => {
+ // Registered first, so it wins over the route setupAll adds.
+ fetchMock.get("path:/api/collection/tree", { status: 500, body: "" });
+
+ await setupAll({
+ currentUser: TENANT_USER,
+ tokenFeatures: TENANT_TOKEN_FEATURES,
+ hasTenantsPlugin: true,
+ useTenants: true,
+ waitForList: false,
+ });
+
+ expect(
+ await screen.findByText("Failed to load collections"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("all-collections-list"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("one request fails while another is still in flight", async () => {
+ // The loader must not outlive the error, or a dead screen waits on the
+ // request that never comes back.
+ const tree = defer<Collection[]>();
+ fetchMock.get("path:/api/collection/tree", () => tree.promise);
+
+ await setupAll({
+ rootReadable: false,
+ rootErrorStatus: 500,
+ tokenFeatures: TENANT_TOKEN_FEATURES,
+ hasTenantsPlugin: true,
+ useTenants: true,
+ waitForList: false,
+ });
+
+ try {
+ expect(
+ await screen.findByText("Failed to load collections"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("loading-indicator"),
+ ).not.toBeInTheDocument();
+ } finally {
+ tree.resolve([]);
+ }
+ });
+ });
+
+ // RTK re-runs a rejected query when something subscribes to it again, and
+ // coming back to the virtual root does exactly that. The rows are all known
+ // already, so the list must stay put instead of blinking out for the refetch.
+ it("should not show a loader when the root is forbidden and the user comes back to the virtual root", async () => {
+ const secondRootCall = defer<{ status: number; body: string }>();
+ let rootCalls = 0;
+
+ fetchMock.get("path:/api/collection/root", () => {
+ rootCalls += 1;
+ return rootCalls === 1
+ ? { status: 403, body: "" }
+ : secondRootCall.promise;
+ });
+
+ await setupAll({
+ rootReadable: false,
+ rootCollectionItems: [
+ createMockCollectionItem({
+ id: PROMOTED_COLLECTION_ID,
+ model: "collection",
+ name: PROMOTED_TEST_COLLECTION.name,
+ }),
+ ],
+ });
+
+ await userEvent.click(await screen.findByText("Promoted Collection"));
+ expect(await screen.findByTestId("collection-table")).toBeInTheDocument();
+
+ try {
+ await userEvent.click(screen.getByText("All collections"));
+
+ expect(screen.getByTestId("all-collections-list")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("loading-indicator"),
+ ).not.toBeInTheDocument();
+ } finally {
+ secondRootCall.resolve({ status: 403, body: "" });
+ }
+ });
+
+ describe("table shape and callbacks", () => {
+ it("should only show the type and name columns", async () => {
+ // Synthesized rows have no edit info, so those columns are dropped.
+ await setupAll();
+
+ expect(getColumnNames()).toStrictEqual(["Type", "Name"]);
+ });
+
+ it("should pass the whole item to onClick", async () => {
+ // `onClick` is a public prop, so the host page receives this item. An
+ // item rebuilt from a few fields drops `namespace`, `authority_level`
+ // and `entity_id` without anything going red.
+ const onClick = jest.fn();
+
+ await setupAll({
+ currentUser: TENANT_USER,
+ tokenFeatures: TENANT_TOKEN_FEATURES,
+ hasTenantsPlugin: true,
+ useTenants: true,
+ sharedTenantCollections: SHARED_TENANT_COLLECTIONS,
+ props: { onClick },
+ });
+
+ await userEvent.click(await screen.findByText("Shared reports"));
+
+ expect(onClick).toHaveBeenCalledWith(
+ expect.objectContaining({
+ ...SHARED_TENANT_COLLECTIONS[0],
+ model: "collection",
+ }),
+ );
+ });
+
+ it('should map the "Our analytics" placeholder id back to the real root id', async () => {
+ // Every collection has a numeric id, except the root, whose id is the
+ // string "root". `ItemsTable` needs a number, so that row carries a
+ // placeholder. Skip the conversion back and both the host page and the
+ // request get an id that is not a collection.
+ const onClick = jest.fn();
+
+ await setupAll({ props: { onClick } });
+
+ await userEvent.click(await screen.findByText("Our analytics"));
+
+ expect(onClick).toHaveBeenCalledWith(
+ expect.objectContaining({ id: ROOT_COLLECTION.id }),
+ );
+ expect(
+ await screen.findByTestId("collection-table"),
+ ).toBeInTheDocument();
+ expect(
+ fetchMock.callHistory.calls("path:/api/collection/root/items").length,
+ ).toBeGreaterThan(0);
+ });
+ });
+
+ it("should page the virtual root and reset the page on the way back", async () => {
+ await setupAll({
+ rootReadable: false, // to force showing more collections
+ rootCollectionItems: [
+ createMockCollectionItem({
+ id: 101,
+ model: "collection",
+ name: "Collection A",
+ }),
+ createMockCollectionItem({
+ id: 102,
+ model: "collection",
+ name: "Collection B",
+ }),
+ createMockCollectionItem({
+ id: PROMOTED_COLLECTION_ID,
+ model: "collection",
+ name: PROMOTED_TEST_COLLECTION.name,
+ }),
+ ],
+ props: { pageSize: 2 },
+ });
+
+ expect(screen.getByText("Collection A")).toBeInTheDocument();
+ expect(screen.getByText("Collection B")).toBeInTheDocument();
+ expect(
+ screen.queryByText(PROMOTED_TEST_COLLECTION.name),
+ ).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByLabelText("Next page"));
+
+ expect(
+ screen.getByText(PROMOTED_TEST_COLLECTION.name),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Collection A")).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByText(PROMOTED_TEST_COLLECTION.name));
+ expect(await screen.findByText("Promoted Dashboard")).toBeInTheDocument();
+
+ await userEvent.click(screen.getByText("All collections"));
+
+ expect(await screen.findByText("Collection A")).toBeInTheDocument();
+ });
+ });
});
+function getColumnNames(): (string | null)[] {
+ return within(screen.getByTestId("items-table-head"))
+ .getAllByRole("button")
+ .map((header) => header.textContent);
+}
+
function getLastItemsRequestParam(param: string): string | null {
const calls = fetchMock.callHistory.calls("path:/api/collection/root/items");
const lastCall = calls[calls.length - 1];
@@ -294,3 +573,120 @@ async function setup({
).toHaveLength(1);
});
}
+
+type SetupAllOptions = {
+ rootReadable?: boolean;
+ rootErrorStatus?: number;
+ rootCollectionItems?: CollectionItem[];
+ rootItemsErrorStatus?: number;
+ currentUser?: User;
+ tokenFeatures?: Partial<TokenFeatures>;
+ hasTenantsPlugin?: boolean;
+ useTenants?: boolean;
+ sharedTenantCollections?: Collection[];
+ waitForList?: boolean;
+ props?: Partial<ComponentProps<typeof CollectionBrowserInner>>;
+};
+
+async function setupAll({
+ rootReadable = true,
+ rootErrorStatus = 403,
+ rootCollectionItems = [],
+ rootItemsErrorStatus,
+ currentUser,
+ tokenFeatures,
+ hasTenantsPlugin = false,
+ useTenants = false,
+ sharedTenantCollections = [],
+ waitForList = true,
+ props,
+}: SetupAllOptions = {}) {
+ useLocaleMock.mockReturnValue({ isLocaleLoading: false });
+
+ const drillableCollections = [
+ ...TEST_COLLECTIONS,
+ PROMOTED_TEST_COLLECTION,
+ ...sharedTenantCollections,
+ ];
+
+ if (rootReadable) {
+ setupCollectionsEndpoints({
+ collections: sharedTenantCollections,
+ rootCollection: ROOT_TEST_COLLECTION,
+ });
+ setupCollectionItemsEndpoint({
+ collection: ROOT_TEST_COLLECTION,
+ collectionItems: [
+ createMockCollectionItem({
+ id: NESTED_COLLECTION_ID,
+ model: "collection",
+ name: NESTED_COLLECTION_NAME,
+ }),
+ ],
+ });
+ } else {
+ fetchMock.get("path:/api/collection/root", {
+ status: rootErrorStatus,
+ body: "",
+ });
+
+ if (rootItemsErrorStatus != null) {
+ fetchMock.get("path:/api/collection/root/items", {
+ status: rootItemsErrorStatus,
+ body: "",
+ });
+ } else {
+ setupRootCollectionItemsEndpoint({ rootCollectionItems });
+ }
+
+ setupCollectionsEndpoints({
+ collections: sharedTenantCollections,
+ rootCollection: ROOT_TEST_COLLECTION,
+ });
+ }
+
+ setupCollectionByIdEndpoint({ collections: drillableCollections });
+
+ setupCollectionItemsEndpoint({
+ collection: PROMOTED_TEST_COLLECTION,
+ collectionItems: [
+ createMockCollectionItem({
+ id: 8,
+ model: "dashboard",
+ name: "Promoted Dashboard",
+ }),
+ ],
+ });
+ sharedTenantCollections.forEach((collection) =>
+ setupCollectionItemsEndpoint({ collection, collectionItems: [] }),
+ );
+
+ const { state } = setupSdkState({
+ ...(currentUser ? { currentUser } : {}),
+ ...(tokenFeatures ? { tokenFeatures } : {}),
+ settingValues: createMockSettings({
+ "enable-embedding-sdk": true,
+ "use-tenants": useTenants,
+ }),
+ });
+
+ if (hasTenantsPlugin) {
+ setupEnterpriseOnlyPlugin("tenants");
+ }
+
+ renderWithSDKProviders(
+ <CollectionBrowserInner collectionId="all" {...props} />,
+ {
+ componentProviderProps: {
+ authConfig: createMockSdkConfig(),
+ },
+ storeInitialState: state,
+ },
+ );
+
+ if (waitForList) {
+ expect(
+ await screen.findByTestId("all-collections-list"),
+ ).toBeInTheDocument();
+ }
+}
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-all-collections-items.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-all-collections-items.ts
new file mode 100644
index 00000000000..5bcb5c2cebe
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-all-collections-items.ts
@@ -0,0 +1,194 @@
+import { match } from "ts-pattern";
+import { t } from "ttag";
+
+import { useSdkSelector } from "embedding-sdk-bundle/store";
+import { getUserTenantCollectionId } from "embedding-sdk-bundle/store/collections";
+import {
+ skipToken,
+ useGetCollectionQuery,
+ useListCollectionItemsQuery,
+ useListCollectionsTreeQuery,
+} from "metabase/api";
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import { getUserPersonalCollectionId } from "metabase/current-user";
+import { PLUGIN_TENANTS } from "metabase/plugins";
+import { useSetting } from "metabase/settings";
+import { isNotNull } from "metabase/utils/types";
+import type { Collection, CollectionItem } from "metabase-types/api";
+import { isObject } from "metabase-types/guards";
+
+export type AllCollectionsItem = CollectionItem &
+ Pick<Collection, "is_personal">;
+
+type UseAllCollectionsItemsResult = {
+ items: AllCollectionsItem[];
+ isLoading: boolean;
+ error: unknown;
+};
+
+const EMPTY_COLLECTIONS: Collection[] = [];
+
+/**
+ * "Our analytics" has the id "root", but the table needs a number. Real
+ * collection ids start at 1, so -1 stands in for it and the caller maps it back.
+ */
+const ROOT_ITEM_ID = -1;
+
+/**
+ * Maps the id back to "root" for the virtual root collection, so the host app
+ * and the navigation don't get the fake id.
+ */
+export const withRealCollectionId = (item: CollectionItem) => ({
+ ...item,
+ id: item.id === ROOT_ITEM_ID ? ROOT_COLLECTION.id : item.id,
+});
+
+type RootState =
+ /** The root collection is known */
+ | { kind: "readable"; collection: Collection }
+ /** No permission on root (403) but might still read nested collections. */
+ | { kind: "forbidden" }
+ /** No root to show: still loading it, or it failed with something else. */
+ | { kind: "unavailable" };
+
+const getRootState = (
+ collection: Collection | undefined,
+ error: unknown,
+): RootState => {
+ if (isObject(error) && error.status === 403) {
+ return { kind: "forbidden" };
+ }
+
+ return collection
+ ? { kind: "readable", collection }
+ : { kind: "unavailable" };
+};
+
+/**
+ * The rows of the virtual "All collections" root: "Our analytics", the shared
+ * tenant collections, the tenant collection and the personal one, as siblings.
+ */
+export const useAllCollectionsItems = ({
+ enabled,
+}: {
+ enabled: boolean;
+}): UseAllCollectionsItemsResult => {
+ const personalCollectionId = useSdkSelector(getUserPersonalCollectionId);
+ const tenantCollectionId = useSdkSelector(getUserTenantCollectionId);
+
+ const {
+ data: rootCollection,
+ error: rootCollectionError,
+ isFetching: isFetchingRootCollection,
+ } = useGetCollectionQuery(enabled ? { id: "root" } : skipToken);
+
+ const rootState = getRootState(rootCollection, rootCollectionError);
+
+ // The user may have no permission on "Our analytics" but still have it on
+ // sub collections. /root/items returns those, /root would just 403.
+ const {
+ data: rootItems,
+ error: rootItemsError,
+ isFetching: isFetchingRootItems,
+ } = useListCollectionItemsQuery(
+ rootState.kind === "forbidden"
+ ? { id: "root", models: ["collection"] }
+ : skipToken,
+ );
+
+ const hasTenantsSetting = useSetting("use-tenants");
+ const isTenantsActive =
+ enabled && hasTenantsSetting && PLUGIN_TENANTS.isEnabled;
+
+ const {
+ data: sharedTenantCollections = EMPTY_COLLECTIONS,
+ error: sharedTenantCollectionsError,
+ isFetching: isFetchingSharedTenantCollections,
+ } = useListCollectionsTreeQuery(
+ isTenantsActive
+ ? {
+ namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,
+ "exclude-archived": true,
+ shallow: true,
+ }
+ : skipToken,
+ );
+
+ // Either "Our analytics" itself, or the collections inside it the user can reach.
+ const sharedCollectionItems: AllCollectionsItem[] = match(rootState)
+ .with({ kind: "readable" }, ({ collection }): AllCollectionsItem[] => [
+ {
+ id: ROOT_ITEM_ID,
+ model: "collection",
+ name: collection.name || t`Our analytics`,
+ description: collection.description ?? null,
+ },
+ ])
+ .with({ kind: "forbidden" }, () => rootItems?.data ?? [])
+ .with({ kind: "unavailable" }, () => [])
+ .exhaustive();
+
+ // Shared tenant collections always have numeric ids; the check only narrows
+ // `Collection["id"]` for the table item.
+ const sharedTenantCollectionItems: AllCollectionsItem[] =
+ sharedTenantCollections.flatMap(({ children, ...collection }) =>
+ typeof collection.id === "number"
+ ? [
+ {
+ ...collection,
+ id: collection.id,
+ // `Collection` also allows "", which `CollectionItem` does not.
+ entity_id: collection.entity_id || undefined,
+ model: "collection" as const,
+ description: collection.description ?? null,
+ },
+ ]
+ : [],
+ );
+
+ // The backend excludes tenant-specific root collections from
+ // `/api/collection/root/items`, so the tenant collection has to be added here.
+ const tenantCollectionItem: AllCollectionsItem | null =
+ typeof tenantCollectionId === "number"
+ ? {
+ id: tenantCollectionId,
+ model: "collection",
+ name: t`Our data`,
+ description: null,
+ }
+ : null;
+
+ const personalCollectionItem: AllCollectionsItem | null =
+ typeof personalCollectionId === "number"
+ ? {
+ id: personalCollectionId,
+ model: "collection",
+ name: t`Your personal collection`,
+ description: null,
+ is_personal: true,
+ location: "/",
+ }
+ : null;
+
+ // Same order the entity picker lists its roots in.
+ const items = [
+ ...sharedCollectionItems,
+ ...sharedTenantCollectionItems,
+ tenantCollectionItem,
+ personalCollectionItem,
+ ].filter(isNotNull);
+
+ // A root refetch keeps the cached rows up instead of showing the loader again.
+ const isLoadingRows =
+ rootState.kind === "forbidden"
+ ? isFetchingRootItems && !rootItems
+ : isFetchingRootCollection && !rootCollection;
+
+ return {
+ items,
+ isLoading: isLoadingRows || isFetchingSharedTenantCollections,
+ error:
+ (rootState.kind === "forbidden" ? rootItemsError : rootCollectionError) ??
+ sharedTenantCollectionsError,
+ };
+};
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
index 13def55dcff..26879eb70e4 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
@@ -3,20 +3,20 @@ import { useMemo, useState } from "react";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
import { useSdkSelector } from "embedding-sdk-bundle/store";
import { getCollectionIdSlugFromReference } from "embedding-sdk-bundle/store/collections";
-import type { SdkCollectionId } from "embedding-sdk-bundle/types/collection";
+import type { SdkBrowserCollectionId } from "embedding-sdk-bundle/types/collection";
import { skipToken, useGetCollectionQuery } from "metabase/api";
import type { CollectionId } from "metabase-types/api";
export const useCollectionData = (
- collectionId: SdkCollectionId = "personal",
+ collectionId: SdkBrowserCollectionId = "personal",
{ skipCollectionFetching = false }: { skipCollectionFetching?: boolean } = {},
) => {
const baseCollectionId = useSdkSelector((state) =>
getCollectionIdSlugFromReference(state, collectionId),
);
- // Internal collection state. Nullish when "personal" cannot be resolved — see
- // [[getCollectionIdSlugFromReference]].
+ // Internal collection state. Nullish when there is no current collection, and
+ // when "personal" cannot be resolved — see [[getCollectionIdSlugFromReference]].
const [internalCollectionId, setInternalCollectionId] = useState<
CollectionId | null | undefined
>(baseCollectionId);
@@ -25,15 +25,24 @@ export const useCollectionData = (
useSdkBreadcrumbs();
const effectiveCollectionId = useMemo(() => {
- if (isGlobalBreadcrumbEnabled && currentLocation?.type === "collection") {
- return currentLocation.id;
+ if (isGlobalBreadcrumbEnabled) {
+ if (currentLocation?.type === "collection") {
+ return currentLocation.id;
+ }
+
+ if (currentLocation?.type === "all-collections") {
+ return undefined;
+ }
}
return internalCollectionId;
}, [isGlobalBreadcrumbEnabled, currentLocation, internalCollectionId]);
+ // `currentData`, not `data`: `data` keeps serving the previous collection
+ // while a new one loads, so the caller would read the `can_write` of the
+ // collection the user just left and offer to create things in this one.
const {
- data: collection,
+ currentData: collection,
error: collectionLoadingError,
isFetching: isFetchingCollection,
} = useGetCollectionQuery(
diff --git a/frontend/src/embedding-sdk-bundle/store/collections.ts b/frontend/src/embedding-sdk-bundle/store/collections.ts
index 41267d883b2..3ac0307942b 100644
--- a/frontend/src/embedding-sdk-bundle/store/collections.ts
+++ b/frontend/src/embedding-sdk-bundle/store/collections.ts
@@ -4,9 +4,12 @@ import { P, match } from "ts-pattern";
import { getUser, getUserPersonalCollectionId } from "metabase/current-user";
import type { CollectionId, RegularCollectionId } from "metabase-types/api";
-import type { SdkCollectionId } from "../types/collection";
+import type {
+ SdkBrowserCollectionId,
+ SdkCollectionId,
+} from "../types/collection";
-const getUserTenantCollectionId = createSelector(
+export const getUserTenantCollectionId = createSelector(
[getUser],
(user) => user?.tenant_collection_id,
);
@@ -58,12 +61,16 @@ export const getCollectionIdValueFromReference = createSelector(
* `null` for a user the backend gives no personal collection — an API-key user, which is how
* the data-app dev server authenticates. Callers must handle both (e.g. with `skipToken`);
* `/api/collection/undefined` and `/api/collection/null` are each a 404.
+ *
+ * `"all"` is the virtual top level and resolves to `undefined`: there is no
+ * collection to fetch. Its branch has to stay above the string one, which would
+ * otherwise match it as an entity id.
*/
export const getCollectionIdSlugFromReference = createSelector(
[
getUserPersonalCollectionId,
getUserTenantCollectionId,
- (_, collectionReference: SdkCollectionId) => collectionReference,
+ (_, collectionReference: SdkBrowserCollectionId) => collectionReference,
],
(
personalCollectionId,
@@ -82,10 +89,11 @@ export const getCollectionIdSlugFromReference = createSelector(
return tenantCollectionId;
})
.with("root", () => "root" as const)
+ .with("all", () => undefined)
.with(P.union(P.number, P.string), (id) => id)
.otherwise(() => {
throw new Error(
- "Invalid collection id, expected `number | string | 'root' | 'personal' | 'tenant'`",
+ "Invalid collection id, expected `number | string | 'root' | 'personal' | 'tenant' | 'all'`",
);
});
},
diff --git a/frontend/src/embedding-sdk-bundle/types/breadcrumb.ts b/frontend/src/embedding-sdk-bundle/types/breadcrumb.ts
index dc5c6287959..faf9cc8c467 100644
--- a/frontend/src/embedding-sdk-bundle/types/breadcrumb.ts
+++ b/frontend/src/embedding-sdk-bundle/types/breadcrumb.ts
@@ -1,6 +1,8 @@
import type { SdkCollectionId } from "./collection";
export type SdkBreadcrumbItemType =
+ /** The virtual top level of the "all collections" browser. */
+ | "all-collections"
| "collection"
| "dashboard"
| "question"
diff --git a/frontend/src/embedding-sdk-bundle/types/collection.ts b/frontend/src/embedding-sdk-bundle/types/collection.ts
index d78c97eb84c..575a68f240e 100644
--- a/frontend/src/embedding-sdk-bundle/types/collection.ts
+++ b/frontend/src/embedding-sdk-bundle/types/collection.ts
@@ -12,6 +12,12 @@ export type SdkCollectionId =
| "tenant"
| SdkEntityId;
+/**
+ * `SdkCollectionId` plus `"all"`, a virtual read-only top level showing
+ * everything the current user can access.
+ */
+export type SdkBrowserCollectionId = SdkCollectionId | "all";
+
/**
* The Collection entity
*/
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionContent.module.css b/frontend/src/metabase/collections/components/CollectionContent/CollectionContent.module.css
index e47c1b924fc..0a164c50f42 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionContent.module.css
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionContent.module.css
@@ -5,8 +5,3 @@
.main {
overflow-y: auto;
}
-
-.table {
- container-name: ItemsTableContainer;
- container-type: inline-size;
-}
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
index d052665d7f2..35e0a1d7afe 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
@@ -46,7 +46,6 @@ import type {
SortingOptions,
} from "metabase-types/api";
-import S from "./CollectionContent.module.css";
import { CollectionItemsToolbar } from "./CollectionItemsToolbar";
const shouldDebounceSearchText = (
@@ -368,7 +367,7 @@ const CollectionItemsTableContent = ({
)}
{showNoResults && <CollectionNoResults hasSearchText={hasSearchText} />}
{showTable && (
- <Box className={S.table} data-testid="collection-table">
+ <Box data-testid="collection-table">
<ItemsTable
databases={databases}
bookmarks={bookmarks}
diff --git a/frontend/src/metabase/common/components/ItemsTable/ItemsTable.module.css b/frontend/src/metabase/common/components/ItemsTable/ItemsTable.module.css
new file mode 100644
index 00000000000..4341b2b40ed
--- /dev/null
+++ b/frontend/src/metabase/common/components/ItemsTable/ItemsTable.module.css
@@ -0,0 +1,4 @@
+.container {
+ container-name: ItemsTableContainer;
+ container-type: inline-size;
+}
diff --git a/frontend/src/metabase/common/components/ItemsTable/ItemsTable.tsx b/frontend/src/metabase/common/components/ItemsTable/ItemsTable.tsx
index 9d48a1c8b2a..5e851b8570e 100644
--- a/frontend/src/metabase/common/components/ItemsTable/ItemsTable.tsx
+++ b/frontend/src/metabase/common/components/ItemsTable/ItemsTable.tsx
@@ -1,3 +1,5 @@
+import cx from "classnames";
+
import PinDropZone from "metabase/common/collections/components/PinDropZone";
import type { ItemRendererProps } from "metabase/common/components/ItemsTable/DefaultItemRenderer";
import CS from "metabase/css/core/index.css";
@@ -5,6 +7,7 @@ import type { CollectionItem } from "metabase-types/api";
import type { BaseItemsTableProps } from "./BaseItemsTable";
import { BaseItemsTable } from "./BaseItemsTable";
+import S from "./ItemsTable.module.css";
import { ItemsTableRoot } from "./ItemsTable.styled";
const Item = ({
@@ -39,7 +42,7 @@ export const ItemsTable = ({
}
return (
- <div className={CS.relative}>
+ <div className={cx(CS.relative, S.container)}>
<PinDropZone variant="unpin" />
<BaseItemsTable items={items} {...props} ItemComponent={ItemComponent} />
</div>
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx
index 4b0363e1a43..e3bfaf02ca6 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx
@@ -15,7 +15,7 @@ import {
} from "embedding-sdk-bundle/components/public/dashboard";
import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
-import type { SdkCollectionId } from "embedding-sdk-bundle/types";
+import type { SdkBrowserCollectionId } from "embedding-sdk-bundle/types";
import type { SdkBreadcrumbItemType } from "embedding-sdk-bundle/types/breadcrumb";
import { Box, Button, Group, Stack } from "metabase/ui";
@@ -28,12 +28,14 @@ interface MetabaseBrowserProps {
}
type MetabaseBrowserView =
- | { type: "collection"; id: SdkCollectionId }
+ | { type: "collection"; id: SdkBrowserCollectionId }
| { type: "dashboard"; id: number | string }
| { type: "question" | "metric" | "model"; id: number | string }
| { type: "new-question" }
| { type: "create-dashboard" };
+type EntityBreadcrumbType = Exclude<SdkBreadcrumbItemType, "all-collections">;
+
const BREADCRUMB_HEIGHT = "3.5rem";
export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
@@ -70,6 +72,7 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
}, [navigationContext.stack]);
// Use the last collection in the breadcrumb as the target for saving new questions.
+ // The virtual "all-collections" root has its own breadcrumb type, so it's excluded here.
const targetCollection = useMemo(() => {
const collectionBreadcrumbs = breadcrumbs.filter(
(item) => item.type === "collection",
@@ -77,7 +80,11 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
const lastCollectionItem = _.last(collectionBreadcrumbs);
- return lastCollectionItem?.id ?? initialCollection;
+ if (lastCollectionItem) {
+ return lastCollectionItem.id;
+ }
+
+ return initialCollection === "all" ? undefined : initialCollection;
}, [breadcrumbs, initialCollection]);
const viewContent = hasNavigatedAway
@@ -115,7 +122,10 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
}, 0);
}}
onClose={() =>
- setCurrentView({ type: "collection", id: targetCollection })
+ setCurrentView({
+ type: "collection",
+ id: targetCollection ?? "all",
+ })
}
initialCollectionId={targetCollection}
/>
@@ -169,11 +179,11 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
showDashboardQuestions={settings.collectionShowDashboardQuestions}
pageSize={settings.collectionPageSize}
onClick={(item) => {
- const type = match<string, SdkBreadcrumbItemType>(item.model)
+ const type = match<string, EntityBreadcrumbType>(item.model)
.with("card", () => "question")
.with("dataset", () => "model")
- // Unjustified type cast. FIXME
- .otherwise((model) => model as SdkBreadcrumbItemType);
+ // A collection item is never the virtual "all collections" root.
+ .otherwise((model) => model as EntityBreadcrumbType);
setCurrentView({ type, id: item.id });
@@ -193,8 +203,6 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
virtual: true,
id: item.id,
name: item.name,
- onPop: () =>
- setCurrentView({ type: "collection", id: view.id }),
});
}
}}
@@ -234,8 +242,11 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
<Group>
<SdkBreadcrumbs
onBreadcrumbClick={(item) => {
- if (item.type === "collection") {
- setCurrentView({ type: item.type, id: item.id });
+ if (
+ item.type === "collection" ||
+ item.type === "all-collections"
+ ) {
+ setCurrentView({ type: "collection", 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
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.unit.spec.tsx
new file mode 100644
index 00000000000..accad9afad6
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.unit.spec.tsx
@@ -0,0 +1,221 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupCollectionByIdEndpoint,
+ setupCollectionItemsEndpoint,
+ setupCollectionsEndpoints,
+ setupDashboardEndpoints,
+ setupDashboardQueryMetadataEndpoint,
+ setupNotificationChannelsEndpoints,
+} from "__support__/server-mocks";
+import { screen, within } from "__support__/ui";
+import { SdkBreadcrumbsProvider } from "embedding-sdk-bundle/components/private/SdkBreadcrumbs/SdkBreadcrumbsProvider";
+import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";
+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import { useLocale } from "metabase/common/hooks/use-locale";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+ createMockDashboard,
+ createMockDashboardQueryMetadata,
+} from "metabase-types/api/mocks";
+
+import type { SdkIframeEmbedSettings } from "../types/embed";
+
+import { MetabaseBrowser } from "./MetabaseBrowser";
+
+jest.mock("metabase/common/hooks/use-locale", () => ({
+ useLocale: jest.fn(),
+}));
+
+// The mock replaces the whole module, so the hook has to be typed back here.
+const useLocaleMock = useLocale as jest.Mock;
+
+const ROOT_TEST_COLLECTION = createMockCollection({
+ ...ROOT_COLLECTION,
+ id: "root",
+ name: "Our analytics",
+ can_write: true,
+});
+
+const PERSONAL_COLLECTION_ID = 1;
+
+const NESTED_COLLECTION_ID = 2;
+const ROOT_DASHBOARD_ID = 10;
+
+const NESTED_TEST_COLLECTION = createMockCollection({
+ id: NESTED_COLLECTION_ID,
+ name: "Nested Collection",
+ location: "/",
+ can_write: false,
+ effective_ancestors: [ROOT_TEST_COLLECTION],
+});
+
+describe("MetabaseBrowser", () => {
+ it("should walk in and back out of the virtual root", async () => {
+ // Opening an entity pushes an entry onto the internal navigation stack.
+ // Popping that entry must not overwrite the view the breadcrumb click asked
+ // for, or every crumb click after a dashboard lands on the wrong collection.
+ setup();
+
+ expect(
+ await screen.findByTestId("all-collections-list"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(await screen.findByText("Our analytics"));
+ expect(await screen.findByText("Nested Collection")).toBeInTheDocument();
+
+ await userEvent.click(await screen.findByText("Nested Collection"));
+ expect(await screen.findByText("Nested Dashboard")).toBeInTheDocument();
+
+ await userEvent.click(getBreadcrumb("All collections"));
+ expect(
+ await screen.findByTestId("all-collections-list"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(await screen.findByText("Our analytics"));
+ await userEvent.click(await screen.findByText("Root Dashboard"));
+ expect(await screen.findByTestId("dashboard-header")).toBeInTheDocument();
+
+ await userEvent.click(getBreadcrumb("All collections"));
+
+ const list = await screen.findByTestId("all-collections-list");
+ expect(within(list).getByText("Our analytics")).toBeInTheDocument();
+ expect(
+ within(list).getByText("Your personal collection"),
+ ).toBeInTheDocument();
+ });
+
+ it("should only show the create buttons inside a writable collection", async () => {
+ // The virtual root resolves no collection, so `canWrite` is false there.
+ setup();
+
+ const list = await screen.findByTestId("all-collections-list");
+ expect(queryNewQuestionButton()).not.toBeInTheDocument();
+ expect(queryNewDashboardButton()).not.toBeInTheDocument();
+
+ await userEvent.click(within(list).getByText("Your personal collection"));
+
+ expect(await screen.findByText("Personal Dashboard")).toBeInTheDocument();
+ expect(queryNewQuestionButton()).toBeInTheDocument();
+ expect(queryNewDashboardButton()).toBeInTheDocument();
+
+ await userEvent.click(getBreadcrumb("All collections"));
+
+ expect(
+ await screen.findByTestId("all-collections-list"),
+ ).toBeInTheDocument();
+ expect(queryNewQuestionButton()).not.toBeInTheDocument();
+ expect(queryNewDashboardButton()).not.toBeInTheDocument();
+ });
+});
+
+function getBreadcrumb(name: string) {
+ return within(screen.getByTestId("sdk-breadcrumbs")).getByText(name);
+}
+
+function queryNewQuestionButton() {
+ return screen.queryByRole("button", { name: "New question" });
+}
+
+function queryNewDashboardButton() {
+ return screen.queryByRole("button", { name: "New dashboard" });
+}
+
+function setup() {
+ useLocaleMock.mockReturnValue({ isLocaleLoading: false });
+
+ const personalCollection = createMockCollection({
+ id: PERSONAL_COLLECTION_ID,
+ name: "Bobby Tables's Personal Collection",
+ personal_owner_id: 1,
+ is_personal: true,
+ can_write: true,
+ });
+
+ const collections = [
+ ROOT_TEST_COLLECTION,
+ personalCollection,
+ NESTED_TEST_COLLECTION,
+ ];
+
+ setupCollectionsEndpoints({
+ collections,
+ rootCollection: ROOT_TEST_COLLECTION,
+ });
+ setupCollectionByIdEndpoint({ collections });
+
+ setupCollectionItemsEndpoint({
+ collection: ROOT_TEST_COLLECTION,
+ collectionItems: [
+ createMockCollectionItem({
+ id: ROOT_DASHBOARD_ID,
+ model: "dashboard",
+ name: "Root Dashboard",
+ }),
+ createMockCollectionItem({
+ id: NESTED_COLLECTION_ID,
+ model: "collection",
+ name: NESTED_TEST_COLLECTION.name,
+ }),
+ ],
+ });
+ setupCollectionItemsEndpoint({
+ collection: NESTED_TEST_COLLECTION,
+ collectionItems: [
+ createMockCollectionItem({
+ id: 30,
+ model: "dashboard",
+ name: "Nested Dashboard",
+ }),
+ ],
+ });
+ setupCollectionItemsEndpoint({
+ collection: personalCollection,
+ collectionItems: [
+ createMockCollectionItem({
+ id: 20,
+ model: "dashboard",
+ name: "Personal Dashboard",
+ }),
+ ],
+ });
+
+ const rootDashboard = createMockDashboard({
+ id: ROOT_DASHBOARD_ID,
+ name: "Root Dashboard",
+ });
+ setupDashboardEndpoints(rootDashboard);
+ setupDashboardQueryMetadataEndpoint(
+ rootDashboard,
+ createMockDashboardQueryMetadata(),
+ );
+ setupNotificationChannelsEndpoints({});
+
+ const { state } = setupSdkState();
+
+ const settings: SdkIframeEmbedSettings & {
+ componentName: "metabase-browser";
+ } = {
+ componentName: "metabase-browser",
+ instanceUrl: "http://localhost",
+ initialCollection: "all",
+ // `MetabaseBrowser` defaults `readOnly` to true when the key is absent.
+ readOnly: false,
+ };
+
+ renderWithSDKProviders(
+ <SdkInternalNavigationProvider keepChildrenMounted>
+ <SdkBreadcrumbsProvider>
+ <MetabaseBrowser settings={settings} />
+ </SdkBreadcrumbsProvider>
+ </SdkInternalNavigationProvider>,
+ {
+ componentProviderProps: { authConfig: createMockSdkConfig() },
+ storeInitialState: state,
+ },
+ );
+}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
index 03a723ad5e5..da029a4e451 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
@@ -174,7 +174,7 @@ export interface BrowserEmbedOptions {
componentName: "metabase-browser";
/** Which collection to start from? */
- initialCollection: CollectionId;
+ initialCollection: CollectionId | "all";
/** Whether the content manager is in read-only mode. Defaults to true. */
readOnly?: boolean;
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts
index 301f07ef2ae..3e18d6f5546 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts
@@ -234,8 +234,10 @@ export interface MetabaseBrowserAttributes {
/**
* Which collection to start from. Values: regular ID, entity ID, `"root"` for
* the top-level "Our Analytics" collection, `"personal"` for the viewer's
- * personal collection, or `"tenant"` for the viewer's tenant collection.
- * People who aren't tenant members get an error for `"tenant"`.
+ * personal collection, `"tenant"` for the viewer's tenant collection, or
+ * `"all"` to show everything the viewer can access: their personal collection
+ * plus the shared collections. People who aren't tenant members get an error
+ * for `"tenant"`.
*/
"initial-collection": number | string;
diff --git a/frontend/src/metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbs.tsx b/frontend/src/metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbs.tsx
index b69a1e02789..a65b325305d 100644
--- a/frontend/src/metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbs.tsx
+++ b/frontend/src/metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbs.tsx
@@ -1,11 +1,4 @@
-import { Fragment } from "react";
-import { t } from "ttag";
-
-import { CollectionBadge } from "metabase/common/collections/components/CollectionBadge";
-import { Breadcrumb } from "metabase/common/components/Breadcrumb";
-import { useToggle } from "metabase/common/hooks/use-toggle";
import { useTranslateContent } from "metabase/content-translation/hooks";
-import { ActionIcon, Box, Flex, Icon } from "metabase/ui";
import * as Urls from "metabase/urls";
import type {
Collection,
@@ -14,7 +7,8 @@ import type {
Dashboard,
} from "metabase-types/api";
-import { getCollectionList } from "./utils";
+import { CollectionBreadcrumbsView } from "./CollectionBreadcrumbsView";
+import { collectionToCrumbs } from "./utils";
export interface CollectionBreadcrumbsProps {
collection?: Collection;
@@ -29,75 +23,27 @@ export const CollectionBreadcrumbs = ({
onClick,
baseCollectionId = null,
}: CollectionBreadcrumbsProps): JSX.Element | null => {
- const [isExpanded, { toggle }] = useToggle(false);
const tc = useTranslateContent();
if (!collection) {
return null;
}
- const parts = getCollectionList({
- baseCollectionId,
- collection,
- });
-
- const separator = (
- <Box
- c="text-disabled"
- fz="0.8em"
- fw="bold"
- mx="0.5rem"
- style={{ userSelect: "none" }}
- >
- /
- </Box>
- );
-
- const content =
- parts.length > 1 && !isExpanded ? (
- <>
- <CollectionBadge
- collectionId={parts[0].id}
- onClick={onClick ? () => onClick(collection) : undefined}
- />
- {separator}
- <ActionIcon
- onClick={toggle}
- aria-label={isExpanded ? t`Collapse` : t`Expand`}
- >
- <Icon name="ellipsis" />
- </ActionIcon>
- {separator}
- </>
- ) : (
- parts.map((collection) => (
- <Fragment key={collection.id}>
- <CollectionBadge
- collectionId={collection.id}
- onClick={onClick ? () => onClick(collection) : undefined}
- />
- {separator}
- </Fragment>
- ))
- );
-
return (
- <Flex align="center" miw="0">
- {content}
- <CollectionBadge
- collectionId={collection.id}
- onClick={onClick ? () => onClick(collection) : undefined}
- />
- {dashboard && (
- <>
- {separator}
-
- <Breadcrumb icon="dashboard" to={Urls.dashboard(dashboard)}>
- {tc(dashboard.name)}
- </Breadcrumb>
- </>
- )}
- </Flex>
+ <CollectionBreadcrumbsView
+ path={collectionToCrumbs({ collection, baseCollectionId, onClick })}
+ terminal={
+ dashboard
+ ? {
+ kind: "static",
+ key: `dashboard-${dashboard.id}`,
+ icon: "dashboard",
+ label: tc(dashboard.name),
+ to: Urls.dashboard(dashboard),
+ }
+ : undefined
+ }
+ />
);
};
diff --git a/frontend/src/metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbsView.tsx b/frontend/src/metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbsView.tsx
new file mode 100644
index 00000000000..b39257a1b4f
--- /dev/null
+++ b/frontend/src/metabase/nav/components/CollectionBreadcrumbs/CollectionBreadcrumbsView.tsx
@@ -0,0 +1,110 @@
+import { Fragment, type ReactNode, useState } from "react";
+import { t } from "ttag";
+
+import { CollectionBadge } from "metabase/common/collections/components/CollectionBadge";
+import { Breadcrumb } from "metabase/common/components/Breadcrumb";
+import { ActionIcon, Box, Flex, Icon } from "metabase/ui";
+import type { CollectionEssentials, IconName } from "metabase-types/api";
+
+/**
+ * A collection crumb carries the collection rather than a name and an icon:
+ * `effective_ancestors` only reports name, id, personal_owner_id and type, so
+ * CollectionBadge has to fetch the rest by id to pick the right icon.
+ */
+export type BreadcrumbCrumb =
+ | {
+ kind: "collection";
+ collection: CollectionEssentials;
+ onClick?: () => void;
+ }
+ | {
+ kind: "static";
+ key: string;
+ icon: IconName;
+ label: string;
+ to?: string;
+ onClick?: () => void;
+ };
+
+type CollectionBreadcrumbsViewProps = {
+ /** Collapses to first, ellipsis, last once it holds more than two crumbs. */
+ path: BreadcrumbCrumb[];
+ /** Pinned after the path, and never collapsed away. */
+ terminal?: BreadcrumbCrumb;
+};
+
+const BreadcrumbSeparator = () => (
+ <Box
+ c="text-disabled"
+ fz="0.8em"
+ fw="bold"
+ mx="0.5rem"
+ style={{ userSelect: "none" }}
+ >
+ /
+ </Box>
+);
+
+const getCrumbKey = (crumb: BreadcrumbCrumb) =>
+ crumb.kind === "collection"
+ ? `collection-${crumb.collection.id}`
+ : `static-${crumb.key}`;
+
+const CrumbContent = ({ crumb }: { crumb: BreadcrumbCrumb }) =>
+ crumb.kind === "collection" ? (
+ <CollectionBadge
+ collectionId={crumb.collection.id}
+ onClick={crumb.onClick}
+ />
+ ) : (
+ <Breadcrumb icon={crumb.icon} to={crumb.to} onClick={crumb.onClick}>
+ {crumb.label}
+ </Breadcrumb>
+ );
+
+type TrailItem = { key: string; node: ReactNode };
+
+const toTrailItem = (crumb: BreadcrumbCrumb): TrailItem => ({
+ key: getCrumbKey(crumb),
+ node: <CrumbContent crumb={crumb} />,
+});
+
+export const CollectionBreadcrumbsView = ({
+ path,
+ terminal,
+}: CollectionBreadcrumbsViewProps) => {
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ const isCollapsed = path.length > 2 && !isExpanded;
+
+ const pathItems: TrailItem[] = isCollapsed
+ ? [
+ toTrailItem(path[0]),
+ {
+ key: "expand",
+ node: (
+ <ActionIcon
+ onClick={() => setIsExpanded(true)}
+ aria-label={t`Expand`}
+ >
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ ),
+ },
+ toTrailItem(path[path.length - 1]),
+ ]
+ : path.map(toTrailItem);
+
+ const items = terminal ? [...pathItems, toTrailItem(terminal)] : pathItems;
+
+ return (
+ <Flex align="center" miw="0">
+ {items.map(({ key, node }, index) => (
+ <Fragment key={key}>
+ {index > 0 && <BreadcrumbSeparator />}
+ {node}
+ </Fragment>
+ ))}
+ </Flex>
+ );
+};
diff --git a/frontend/src/metabase/nav/components/CollectionBreadcrumbs/utils.ts b/frontend/src/metabase/nav/components/CollectionBreadcrumbs/utils.ts
index 8bd8328fc73..1166218ae9e 100644
--- a/frontend/src/metabase/nav/components/CollectionBreadcrumbs/utils.ts
+++ b/frontend/src/metabase/nav/components/CollectionBreadcrumbs/utils.ts
@@ -1,5 +1,11 @@
import { isRootCollection } from "metabase/common/collections/utils";
-import type { Collection, CollectionId } from "metabase-types/api";
+import type {
+ Collection,
+ CollectionEssentials,
+ CollectionId,
+} from "metabase-types/api";
+
+import type { BreadcrumbCrumb } from "./CollectionBreadcrumbsView";
type GetCollectionListProps = {
collection: Collection;
@@ -33,3 +39,20 @@ export const getCollectionList = ({
return hasRoot ? crumbsWithoutRoot : ancestors;
}
};
+
+type CollectionToCrumbsProps = GetCollectionListProps & {
+ onClick?: (collection: CollectionEssentials) => void;
+};
+
+export const collectionToCrumbs = ({
+ collection,
+ baseCollectionId = null,
+ onClick,
+}: CollectionToCrumbsProps): BreadcrumbCrumb[] =>
+ [...getCollectionList({ baseCollectionId, collection }), collection].map(
+ (part) => ({
+ kind: "collection" as const,
+ collection: part,
+ onClick: onClick ? () => onClick(part) : undefined,
+ }),
+ );