Skip to content

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

Sub-collections in the Library (#73179)

Nick Fitzpatrickfd827c2f72a1
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 60ee973e2ef..291a30b91c5 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -2485,6 +2485,7 @@
api
app-db
audit-app
+ collections
driver
lib
lib-be
diff --git a/e2e/support/helpers/api/publishTables.ts b/e2e/support/helpers/api/publishTables.ts
index 544c664258c..ad257717907 100644
--- a/e2e/support/helpers/api/publishTables.ts
+++ b/e2e/support/helpers/api/publishTables.ts
@@ -1,6 +1,29 @@
-import type { BulkTableSelection } from "metabase-types/api";
+import type { BulkTableRequest, Collection } from "metabase-types/api";
-export const publishTables = (request: BulkTableSelection) => {
+type LibraryResponse = Collection & {
+ effective_children?: Collection[];
+};
+
+export const publishTables = (request: BulkTableRequest) => {
+ if (request.collection_id != null) {
+ return requestPublishTables(request);
+ }
+
+ return cy
+ .request<LibraryResponse>("GET", "/api/ee/library")
+ .then(({ body }) => {
+ const dataCollection = body.effective_children?.find(
+ (collection) => collection.type === "library-data",
+ );
+
+ return requestPublishTables({
+ ...request,
+ collection_id: dataCollection?.id as number,
+ });
+ });
+};
+
+const requestPublishTables = (request: BulkTableRequest) => {
return cy.request(
"POST",
"/api/ee/data-studio/table/publish-tables",
diff --git a/e2e/support/helpers/api/unpublishTables.ts b/e2e/support/helpers/api/unpublishTables.ts
index dec2352d049..198a90f95e6 100644
--- a/e2e/support/helpers/api/unpublishTables.ts
+++ b/e2e/support/helpers/api/unpublishTables.ts
@@ -1,6 +1,6 @@
-import type { BulkTableSelection } from "metabase-types/api";
+import type { BulkTableRequest } from "metabase-types/api";
-export const unpublishTables = (request: BulkTableSelection) => {
+export const unpublishTables = (request: BulkTableRequest) => {
return cy.request(
"POST",
"/api/ee/data-studio/table/unpublish-tables",
diff --git a/e2e/support/helpers/e2e-data-studio-helpers.ts b/e2e/support/helpers/e2e-data-studio-helpers.ts
index ee1d2e247de..7d6cb28ad48 100644
--- a/e2e/support/helpers/e2e-data-studio-helpers.ts
+++ b/e2e/support/helpers/e2e-data-studio-helpers.ts
@@ -77,6 +77,8 @@ export const DataStudio = {
saveButton: () => cy.findByRole("button", { name: "Save" }),
cancelButton: () => cy.findByRole("button", { name: "Cancel" }),
editor: codeMirrorHelpers("snippet-editor", {}),
+ visitSnippet: (snippetId: number) =>
+ cy.visit(`/data-studio/library/snippets/${snippetId}`),
},
Metrics: MetricPage,
Tables: {
@@ -149,7 +151,7 @@ export const DataStudio = {
result: (name: string) =>
libraryPage().findByText(name).closest('[role="row"]'),
newButton: () => libraryPage().findByRole("button", { name: /New/ }),
- collectionItem: (name: string) =>
+ collectionItem: (name: string | RegExp) =>
libraryPage().findAllByTestId("collection-name").contains(name),
},
};
diff --git a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
index 479563aec43..3dd74f93e61 100644
--- a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
@@ -1497,8 +1497,15 @@ function updateTableAttributes({
}
function publishTables(tableIds: TableId[]) {
- return cy.request("POST", "/api/ee/data-studio/table/publish-tables", {
- table_ids: tableIds,
+ return cy.request("GET", "/api/ee/library").then(({ body }) => {
+ const dataCollection = body.effective_children?.find(
+ (collection: { type?: string }) => collection.type === "library-data",
+ );
+
+ return cy.request("POST", "/api/ee/data-studio/table/publish-tables", {
+ table_ids: tableIds,
+ collection_id: dataCollection.id,
+ });
});
}
diff --git a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts
index 7bd5e9da681..9d0461ddc45 100644
--- a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts
@@ -1,10 +1,23 @@
const { H } = cy;
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
TRUSTED_ORDERS_METRIC,
createLibraryWithItems,
createLibraryWithTable,
} from "e2e/support/test-library-data";
+import type { Collection } from "metabase-types/api";
+
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+type LibraryResponse = Collection & {
+ effective_children?: Collection[];
+};
+
+type LibraryRootCollections = {
+ dataCollection: Collection;
+ metricCollection: Collection;
+};
describe("scenarios > data studio > library", () => {
beforeEach(() => {
@@ -130,6 +143,8 @@ describe("scenarios > data studio > library", () => {
select: true,
});
+ H.modal().findByText("Publish to").should("be.visible");
+ H.modal().findByText("Data").should("be.visible");
H.modal().button("Publish this table").click();
cy.log("Verify the table is published");
@@ -152,6 +167,185 @@ describe("scenarios > data studio > library", () => {
});
});
+ describe("Library collection management", () => {
+ it("should create a new library collection from the New button", () => {
+ H.createLibrary();
+ H.createCollection({ name: "Outside Library" });
+ H.DataStudio.Library.visit();
+
+ cy.intercept("POST", "/api/collection").as("createCollection");
+
+ H.DataStudio.Library.newButton().click();
+ H.popover().findByText("Collection").click();
+
+ H.modal().within(() => {
+ cy.findByLabelText("Name").type("New Library Collection");
+ cy.findByTestId("collection-picker-button").should("contain", "Data");
+ cy.findByTestId("collection-picker-button").click();
+ });
+
+ H.entityPickerModalItem(0, "Library").should("be.visible");
+ H.entityPickerModalItem(1, "Data").should("be.visible");
+
+ cy.log("Check that non-library collection are not visible");
+ H.entityPickerModal().findByText("Our analytics").should("not.exist");
+ H.entityPickerModal().findByText("Outside Library").should("not.exist");
+ H.entityPickerModal().button("Cancel").click();
+
+ H.modal().button("Create").click();
+ cy.wait("@createCollection").then(({ response }) => {
+ expect(response?.statusCode).to.equal(200);
+ });
+
+ H.DataStudio.Library.collectionItem("New Library Collection").should(
+ "be.visible",
+ );
+ });
+
+ it("should edit a library collection name and description", () => {
+ H.createLibrary();
+ getLibraryRootCollections().then(({ dataCollection }) => {
+ createLibraryCollection({
+ name: "Collection Before Edit",
+ description: "Original description",
+ parent_id: dataCollection.id,
+ });
+ });
+
+ H.DataStudio.Library.visit();
+
+ cy.intercept("PUT", "/api/collection/*").as("updateCollection");
+
+ openCollectionOptions("Collection Before Edit");
+ H.popover().findByText("Edit collection details").click();
+
+ H.modal().within(() => {
+ cy.findByLabelText("Name").clear().type("Collection After Edit");
+ cy.findByLabelText("Description")
+ .clear()
+ .type("Updated library description");
+ cy.button("Save").click();
+ });
+
+ cy.wait("@updateCollection").then(({ response }) => {
+ expect(response?.statusCode).to.equal(200);
+ });
+
+ H.DataStudio.Library.collectionItem("Collection After Edit").should(
+ "be.visible",
+ );
+ H.DataStudio.Library.libraryPage()
+ .findByText("Collection Before Edit")
+ .should("not.exist");
+ });
+
+ it("should move a library collection to another subcollection", () => {
+ H.createLibrary();
+ getLibraryRootCollections().then(({ dataCollection }) => {
+ createLibraryCollection({
+ name: "Destination Collection",
+ parent_id: dataCollection.id,
+ });
+ createLibraryCollection({
+ name: "Collection To Move",
+ parent_id: dataCollection.id,
+ });
+ });
+
+ H.DataStudio.Library.visit();
+
+ cy.intercept("PUT", "/api/collection/*").as("updateCollection");
+
+ openCollectionOptions("Collection To Move");
+ H.popover().findByText("Edit collection details").click();
+
+ H.modal().findByTestId("collection-picker-button").click();
+ H.entityPickerModalItem(1, "Metrics").should(
+ "have.attr",
+ "data-disabled",
+ );
+ H.entityPickerModalItem(2, "Destination Collection").click();
+ H.entityPickerModal().button("Select").click();
+ H.modal().button("Save").click();
+
+ cy.wait("@updateCollection").then(({ response }) => {
+ expect(response?.statusCode).to.equal(200);
+ });
+
+ expandLibraryCollection("Destination Collection");
+ H.DataStudio.Library.result("Collection To Move")
+ .should("be.visible")
+ .and("have.attr", "aria-level", "3");
+ });
+
+ it("should archive a library collection and show it in trash", () => {
+ H.createLibrary();
+ getLibraryRootCollections().then(({ dataCollection }) => {
+ createLibraryCollection({
+ name: "Collection To Archive",
+ parent_id: dataCollection.id,
+ });
+ });
+
+ H.DataStudio.Library.visit();
+
+ cy.intercept("PUT", "/api/collection/*").as("updateCollection");
+
+ openCollectionOptions("Collection To Archive");
+ H.popover().findByText("Archive").click();
+ H.modal().button("Archive").click();
+
+ cy.wait("@updateCollection").then(({ response }) => {
+ expect(response?.statusCode).to.equal(200);
+ });
+ H.undoToast()
+ .findByText('"Collection To Archive" has been archived')
+ .should("be.visible");
+ H.DataStudio.Library.libraryPage()
+ .findByText("Collection To Archive")
+ .should("not.exist");
+
+ cy.visit("/trash");
+ cy.findByRole("table")
+ .findByText("Collection To Archive")
+ .should("be.visible");
+ });
+
+ it("should move a published table to a library subcollection", () => {
+ H.createLibrary();
+ getLibraryRootCollections().then(({ dataCollection }) => {
+ H.publishTables({ table_ids: [ORDERS_ID] });
+ createLibraryCollection({
+ name: "Table Destination Collection",
+ parent_id: dataCollection.id,
+ });
+ });
+
+ H.DataStudio.Library.visit();
+
+ cy.intercept("PUT", "/api/table/*").as("updateTable");
+
+ openTableOptions("Orders");
+ H.popover().findByText("Move").click();
+
+ H.entityPickerModalItem(1, "Metrics").should(
+ "have.attr",
+ "data-disabled",
+ );
+ H.entityPickerModalItem(2, "Table Destination Collection").click();
+ H.entityPickerModal().button("Move").click();
+
+ cy.wait("@updateTable").then(({ response }) => {
+ expect(response?.statusCode).to.equal(200);
+ });
+
+ expandLibraryCollection("Table Destination Collection");
+ H.DataStudio.Library.result("Orders")
+ .should("be.visible")
+ .and("have.attr", "aria-level", "3");
+ });
+ });
+
describe("empty state", () => {
it("should show empty states with interactions when sections are empty", () => {
H.createLibrary();
@@ -219,10 +413,14 @@ describe("scenarios > data studio > library", () => {
H.entityPickerModalItem(1, "Sample Database").click();
H.entityPickerModalItem(2, "Orders").click();
H.entityPickerModal().button("Publish").click();
+ H.modal().findByText("Publish to").should("be.visible");
+ H.modal().findByText("Data").should("be.visible");
H.modal().button("Publish this table").click();
cy.log("Navigate back to Library via breadcrumbs");
- H.DataStudio.breadcrumbs().findByRole("link", { name: "Data" }).click();
+ H.DataStudio.breadcrumbs()
+ .findByRole("link", { name: "Library" })
+ .click();
cy.log("Verify Data section shows the table (empty state hidden)");
H.DataStudio.Library.tableItem("Orders").should("be.visible");
@@ -250,7 +448,7 @@ describe("scenarios > data studio > library", () => {
H.createLibrary();
});
- it("should hide +New button and empty state actions in read-only mode (UXW-3341)", () => {
+ it("should hide +New button and empty state actions in read-only mode", () => {
H.DataStudio.Library.visit();
cy.log("Verify +New button is not visible");
@@ -285,3 +483,60 @@ describe("scenarios > data studio > library", () => {
});
});
});
+
+function getLibraryRootCollections(): Cypress.Chainable<LibraryRootCollections> {
+ return cy
+ .request<LibraryResponse>("GET", "/api/ee/library")
+ .then(({ body }) => {
+ const dataCollection = body.effective_children?.find(
+ (collection) => collection.type === "library-data",
+ );
+ const metricCollection = body.effective_children?.find(
+ (collection) => collection.type === "library-metrics",
+ );
+
+ expect(dataCollection, "Data collection").to.exist;
+ expect(metricCollection, "Metrics collection").to.exist;
+
+ return {
+ dataCollection: dataCollection as Collection,
+ metricCollection: metricCollection as Collection,
+ };
+ });
+}
+
+function createLibraryCollection({
+ name,
+ description = null,
+ parent_id,
+}: {
+ name: string;
+ description?: string | null;
+ parent_id: Collection["id"];
+}) {
+ return cy
+ .request<Collection>("POST", "/api/collection", {
+ name,
+ description,
+ parent_id,
+ })
+ .its("body");
+}
+
+function openCollectionOptions(name: string) {
+ H.DataStudio.Library.result(name)
+ .findByLabelText("Collection options")
+ .click();
+}
+
+function openTableOptions(name: string) {
+ H.DataStudio.Library.result(name)
+ .findByLabelText("Show table options")
+ .click();
+}
+
+function expandLibraryCollection(name: string) {
+ H.DataStudio.Library.result(name)
+ .findByRole("button", { name: "Expand" })
+ .click();
+}
diff --git a/e2e/test/scenarios/data-studio/snippets.cy.spec.ts b/e2e/test/scenarios/data-studio/snippets.cy.spec.ts
index 98f299d0975..13d4e7a31bf 100644
--- a/e2e/test/scenarios/data-studio/snippets.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/snippets.cy.spec.ts
@@ -258,17 +258,23 @@ describe("scenarios > data studio > snippets", () => {
H.DataStudio.Library.visit();
H.DataStudio.Library.newButton().click();
- H.popover().findByText("Snippet folder").click();
+ H.popover().findByText("Collection").click();
H.modal().within(() => {
- cy.findByLabelText("Give your folder a name").type("Test Folder");
- cy.findByLabelText("Add a description").type(
- "Folder for test snippets",
- );
+ cy.findByLabelText("Name").type("Test Folder");
+ cy.findByLabelText("Description").type("Folder for test snippets");
+ cy.findByTestId("collection-picker-button").click();
+ });
+ H.entityPickerModal().within(() => {
+ cy.findByText("SQL Snippets").click();
+ cy.button("Select").click();
+ });
+ H.modal().within(() => {
cy.button("Create").click();
cy.wait("@createCollection");
});
+ H.DataStudio.Library.visit();
H.DataStudio.Library.libraryPage()
.findByText("Test Folder")
.should("be.visible");
@@ -287,7 +293,9 @@ describe("scenarios > data studio > snippets", () => {
cy.wait("@createSnippet");
- H.DataStudio.nav().findByRole("link", { name: "Library" }).click();
+ H.DataStudio.breadcrumbs()
+ .findByRole("link", { name: /Test Folder/ })
+ .click();
H.DataStudio.Library.libraryPage()
.findByText("Folder snippet")
.should("be.visible");
@@ -305,10 +313,8 @@ describe("scenarios > data studio > snippets", () => {
H.popover().findByText("Edit folder details").click();
H.modal().within(() => {
- cy.findByLabelText("Give your folder a name")
- .clear()
- .type("Updated Folder");
- cy.button("Update").click();
+ cy.findByLabelText("Name").clear().type("Updated Folder");
+ cy.button("Save").click();
cy.wait("@updateCollection");
});
@@ -327,6 +333,8 @@ describe("scenarios > data studio > snippets", () => {
H.DataStudio.Library.result("Test Folder").icon("ellipsis").click();
H.popover().findByText("Archive").click();
+ cy.log("Clicks archive button on confirmation modal");
+ H.modal().findByRole("button", { name: "Archive" }).click();
cy.wait("@updateCollection");
@@ -360,33 +368,40 @@ describe("scenarios > data studio > snippets", () => {
H.createSnippetFolder({
name: "Sibling Folder",
}).then(({ body: siblingFolder }) => {
- H.createSnippet({
+ return H.createSnippet({
name: "Sibling Snippet",
content: "SELECT 2",
collection_id: siblingFolder.id,
+ }).then(({ body: snippet }) => {
+ H.DataStudio.Snippets.visitSnippet(snippet.id);
+ H.DataStudio.breadcrumbs()
+ .findByRole("link", { name: "Sibling Folder" })
+ .click();
});
});
- H.DataStudio.Library.visit();
-
- cy.log("Verify all folders and their contents are initially expanded");
+ cy.log(
+ "Verify the path to Sibling Folder is expanded, but child folder is collapsed",
+ );
H.DataStudio.Library.libraryPage()
.findByText("Parent Folder")
.should("be.visible");
H.DataStudio.Library.libraryPage()
.findByText("Child Folder")
- .should("be.visible");
- H.DataStudio.Library.libraryPage()
- .findByText("Sibling Folder")
- .should("be.visible");
+ .should("not.exist");
H.DataStudio.Library.libraryPage()
.findByText("Nested Snippet")
+ .should("not.exist");
+ H.DataStudio.Library.libraryPage()
+ .findByText("Sibling Folder")
.should("be.visible");
H.DataStudio.Library.libraryPage()
.findByText("Sibling Snippet")
.should("be.visible");
cy.log("Navigate to the nested snippet");
+ H.DataStudio.Library.collectionItem("Parent Folder").click();
+ H.DataStudio.Library.collectionItem("Child Folder").click();
H.DataStudio.Library.libraryPage().findByText("Nested Snippet").click();
H.DataStudio.Snippets.editPage().should("be.visible");
@@ -455,15 +470,13 @@ describe("scenarios > data studio > snippets", () => {
name: "Deep Snippet",
content: "SELECT 1",
collection_id: childFolder.id,
+ }).then(({ body: snippet }) => {
+ H.DataStudio.Snippets.visitSnippet(snippet.id);
});
});
});
});
- H.DataStudio.Library.visit();
-
- cy.log("Navigate to the deeply nested snippet");
- H.DataStudio.Library.libraryPage().findByText("Deep Snippet").click();
H.DataStudio.Snippets.editPage().should("be.visible");
cy.log(
diff --git a/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts b/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts
index 8246581139d..6a232c51bdd 100644
--- a/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts
@@ -2469,7 +2469,7 @@ LIMIT
getTransformsList()
.findByText("Original Name")
.closest('[role="row"]')
- .findByRole("button", { name: "Collection menu" })
+ .findByRole("button", { name: "Collection options" })
.click();
H.popover().findByText("Edit collection details").click();
@@ -2519,7 +2519,7 @@ LIMIT
getTransformsList()
.findByText("Archive Me")
.closest('[role="row"]')
- .findByRole("button", { name: "Collection menu" })
+ .findByRole("button", { name: "Collection options" })
.click();
H.popover().findByText("Archive").click();
@@ -2532,7 +2532,9 @@ LIMIT
cy.button("Archive").click();
});
- H.undoToast().findByText("Collection archived").should("be.visible");
+ H.undoToast()
+ .findByText('"Archive Me" has been archived')
+ .should("be.visible");
cy.log("verify collection and its children are no longer visible");
getTransformsList().within(() => {
diff --git a/e2e/test/scenarios/native/snippets.cy.spec.js b/e2e/test/scenarios/native/snippets.cy.spec.js
index e96fbf1b3a1..3e1ce92a100 100644
--- a/e2e/test/scenarios/native/snippets.cy.spec.js
+++ b/e2e/test/scenarios/native/snippets.cy.spec.js
@@ -261,10 +261,8 @@ describe("scenarios > question > snippets (EE)", () => {
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
H.popover().within(() => cy.findByText("New folder").click());
H.modal().within(() => {
- cy.findByText("Create your new folder");
- cy.findByLabelText("Give your folder a name").type(
- "my favorite snippets",
- );
+ cy.findByText("New collection");
+ cy.findByLabelText("Name").type("my favorite snippets");
cy.findByText("Create").click();
});
diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
index 3c83a7e65f3..f090f77173b 100644
--- a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
@@ -24,6 +24,12 @@
[:schema_ids {:optional true} [:sequential :string]]
[:table_ids {:optional true} [:sequential ms/PositiveInt]]])
+(mr/def ::publish-table-selectors
+ [:merge
+ ::table-selectors
+ [:map
+ [:collection_id ms/PositiveInt]]])
+
(mu/defn ^:private table-selectors->filter
[{:keys [database_ids table_ids schema_ids]}]
(let [schema-expr (fn [s]
@@ -131,20 +137,16 @@
"Set collection for each of selected tables and all upstream dependencies recursively."
[_route-params
_query-params
- body :- ::table-selectors]
+ body :- ::publish-table-selectors]
(api/check-data-analyst)
- (let [target-collection (api/let-404 [colls (seq (t2/select :model/Collection
- :type collection/library-data-collection-type
- {:limit 2}))]
- (if (next colls)
- (throw (ex-info (tru "Multiple library-data collections found.")
- {:status-code 409}))
- (first colls)))
- where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))
- upstream-ids (all-upstream-table-ids where)
- update-where (if (seq upstream-ids)
- [:or where [:in :id upstream-ids]]
- where)
+ (let [target-collection (api/check-404 (t2/select-one :model/Collection (:collection_id body)))
+ _ (api/check-400 (= (:type target-collection) collection/library-data-collection-type)
+ (tru "Tables can only be published to Library/Data collections."))
+ where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))
+ upstream-ids (all-upstream-table-ids where)
+ update-where (if (seq upstream-ids)
+ [:or where [:in :id upstream-ids]]
+ where)
;; Get table IDs before update for event publishing
table-ids-to-update (t2/select-pks-set :model/Table {:where update-where})]
(api/check-403 (can-publish-all-tables? table-ids-to-update))
diff --git a/enterprise/backend/src/metabase_enterprise/library/validation.clj b/enterprise/backend/src/metabase_enterprise/library/validation.clj
index 3b740d8a535..7baec10fad7 100644
--- a/enterprise/backend/src/metabase_enterprise/library/validation.clj
+++ b/enterprise/backend/src/metabase_enterprise/library/validation.clj
@@ -5,21 +5,34 @@
[metabase.premium-features.core :refer [defenterprise]]
[toucan2.core :as t2]))
+(def ^:private library-collection-content-specs
+ "A map from the `:type` of the parent collection to a spec for what contents it permits."
+ {collection/library-collection-type
+ {:allowed-content-types #{collection/library-data-collection-type
+ collection/library-metrics-collection-type}
+ :error-message "Cannot add anything to the Library collection"}
+
+ collection/library-data-collection-type
+ {:allowed-content-types #{:table collection/library-data-collection-type}
+ :error-message "Can only add tables to the 'Data' collection"}
+
+ collection/library-metrics-collection-type
+ {:allowed-content-types #{:metric collection/library-metrics-collection-type}
+ :error-message "Can only add metrics to the 'Metrics' collection"}})
+
(defenterprise check-allowed-content
"Check if the collection's content matches the allowed content.
Throws an exception if it does not"
:feature :library
[content-type collection-id]
(when collection-id
- (when-let [collection-type (t2/select-one-fn :type [:model/Collection :type] :id collection-id)]
- (when (and (= collection-type collection/library-collection-type) (not (contains? #{collection/library-data-collection-type
- collection/library-metrics-collection-type}
- content-type)))
- (throw (ex-info "Cannot add anything to the Library collection" {})))
- (when (and (= collection-type collection/library-data-collection-type) (not (= :table content-type)))
- (throw (ex-info "Can only add tables to the 'Data' collection" {})))
- (when (and (= collection-type collection/library-metrics-collection-type) (not (= :metric content-type)))
- (throw (ex-info "Can only add metrics to the 'Metrics' collection" {})))))
+ (let [collection-type (t2/select-one-fn :type [:model/Collection :type] :id collection-id)]
+ (when-let [{:keys [allowed-content-types error-message]} (some-> collection-type
+ library-collection-content-specs)]
+ (when-not (allowed-content-types content-type)
+ (throw (ex-info error-message {:status-code 400}))))
+ (when (and (= content-type :table) (not= collection-type collection/library-data-collection-type))
+ (throw (ex-info "Tables can only be added to 'Data' collections" {:status-code 400})))))
true)
(defenterprise check-library-update
@@ -27,10 +40,14 @@
metabase-enterprise.library.validation
:feature :library
[collection]
- (when (and (contains? #{collection/library-collection-type
- collection/library-data-collection-type
- collection/library-metrics-collection-type} (:type collection))
- (seq (set/intersection (set (keys (t2/changes collection)))
- #{:name :description :archived :location :personal_owner_id :slug :namespace :type :authority_level :is_sample})))
- (throw (ex-info "Cannot update properties on a Library collection" {})))
+ (let [change-keys (set (keys (t2/changes collection)))]
+ (when (and (collection/library-root-collection? collection)
+ (seq (set/intersection change-keys
+ #{:name :description :archived :location :personal_owner_id :slug :namespace :type :authority_level :is_sample})))
+ (throw (ex-info "Cannot update properties on a Library collection" {})))
+ (when (and (collection/is-library-collection? (:id collection))
+ (contains? change-keys :location)
+ (when-let [parent-id (collection/location-path->parent-id (:location collection))]
+ (not= (:type collection) (t2/select-one-fn :type :model/Collection :id parent-id))))
+ (throw (ex-info "Cannot move a Library collection outside the Library" {}))))
true)
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
index fee20a1ce18..75046657dbb 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
@@ -67,7 +67,7 @@
(-> (mt/user-http-request user :get 200 "user/current")
:permissions))]
(testing "user with collection permission on published table should have can_create_queries true"
- (mt/with-temp [:model/Collection collection {}
+ (mt/with-temp [:model/Collection collection {:type "library-data"}
:model/Table _table {:db_id (mt/id)
:is_published true
:collection_id (:id collection)}]
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
index 4edd1cb397b..4a7a6cb216a 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
@@ -11,9 +11,7 @@
(deftest collection-items-table-test
(mt/with-premium-features #{:library}
(testing "GET /api/collection/:id/items"
- (mt/with-temp [:model/Collection collection {}
- :model/Card _ {:collection_id (u/the-id collection)
- :name "a-card"}
+ (mt/with-temp [:model/Collection collection {:type "library-data"}
:model/Table {table-id :id :as table} {:collection_id (u/the-id collection)
:is_published true}
:model/Table {root-table-id :id :as root-table} {:is_published true}]
@@ -54,7 +52,7 @@
(mt/with-premium-features #{:library}
(testing "GET /api/collection/:id/items - published tables require view-data plus query access"
(mt/with-no-data-perms-for-all-users!
- (mt/with-temp [:model/Collection collection {}
+ (mt/with-temp [:model/Collection collection {:type "library-data"}
:model/Table {table-id :id :as table} {:collection_id (u/the-id collection)
:is_published true}
:model/PermissionsGroup {group-id :id} {}]
@@ -93,7 +91,7 @@
"User with both collection and data permissions should see published tables"))))))
(testing "GET /api/collection/:id/items - without collection read permission, user should NOT see published table"
(mt/with-no-data-perms-for-all-users!
- (mt/with-temp [:model/Collection collection {}
+ (mt/with-temp [:model/Collection collection {:type "library-data"}
:model/Table table {:collection_id (u/the-id collection)
:is_published true}
:model/PermissionsGroup {group-id :id} {}]
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/query_metadata_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/query_metadata_test.clj
index f02b2cd4997..6d0750cdff9 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/query_metadata_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/query_metadata_test.clj
@@ -11,7 +11,7 @@
(mt/with-premium-features #{:library}
(testing "GET /api/table/:id/query_metadata"
(testing "Published tables in collections should be accessible with collection read permission (no data permissions)"
- (mt/with-temp [:model/Collection coll {}
+ (mt/with-temp [:model/Collection coll {:type "library-data"}
:model/Database db {}
:model/Table table {:db_id (u/the-id db) :is_published true :collection_id (u/the-id coll)}
:model/Field _field-1 {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
@@ -60,7 +60,7 @@
(mt/with-premium-features #{:library}
(testing "GET /api/table/card__:id/query_metadata"
(testing "Should include Field metadata for published tables accessible via collection permissions"
- (mt/with-temp [:model/Collection table-coll {}
+ (mt/with-temp [:model/Collection table-coll {:type "library-data"}
:model/Table table {:is_published true :collection_id (u/the-id table-coll)}
:model/Field field {:table_id (u/the-id table) :name "test-field"}
:model/Card card {:dataset_query {:database (mt/id)
@@ -78,7 +78,7 @@
(deftest card-query-metadata-published-table-collection-perms-test
(testing "GET /api/card/:id/query_metadata should include published tables that are queryable"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection table-coll {}
+ (mt/with-temp [:model/Collection table-coll {:type "library-data"}
:model/Database db {}
:model/Table table {:db_id (u/the-id db) :is_published true :collection_id (u/the-id table-coll)}
:model/Field _field {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
@@ -104,7 +104,7 @@
(deftest dashboard-query-metadata-published-table-collection-perms-test
(testing "GET /api/dashboard/:id/query_metadata should include published tables accessible via collection permissions"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection table-coll {}
+ (mt/with-temp [:model/Collection table-coll {:type "library-data"}
:model/Database db {}
:model/Table table {:db_id (u/the-id db) :is_published true :collection_id (u/the-id table-coll)}
:model/Field _field {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
@@ -133,7 +133,7 @@
(testing "GET /api/automagic-dashboards/:entity/:entity-id-or-query/query_metadata"
(testing "Should include published tables accessible via collection permissions"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection table-coll {}
+ (mt/with-temp [:model/Collection table-coll {:type "library-data"}
:model/Table table {:is_published true :collection_id (u/the-id table-coll)}
:model/PermissionsGroup custom-group {}
:model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta)
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
index 2a3df43f3ce..7cd4cb1acb5 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
@@ -23,9 +23,11 @@
(mt/with-temp [:model/Collection {collection-id :id} {:type collection/library-data-collection-type}]
(testing "normal users are not allowed to publish"
(mt/user-http-request :rasta :post 403 "ee/data-studio/table/publish-tables"
- {:table_ids [(mt/id :users) (mt/id :venues)]}))
+ {:table_ids [(mt/id :users) (mt/id :venues)]
+ :collection_id collection-id}))
(let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"
- {:table_ids [(mt/id :users) (mt/id :venues)]})]
+ {:table_ids [(mt/id :users) (mt/id :venues)]
+ :collection_id collection-id})]
(is (=? {:id collection-id} (:target_collection response)))
(testing "collection_id and is_published are set"
(is (=? [{:display_name "Users"
@@ -61,19 +63,34 @@
(testing "returns 404 when no library-data collection exists"
(is (= "Not found."
(mt/user-http-request :crowberto :post 404 "ee/data-studio/table/publish-tables"
- {:table_ids [(mt/id :users)]}))))
- (testing "returns 409 when multiple library-data collections exist"
- (mt/with-temp [:model/Collection _ {:type collection/library-data-collection-type}
- :model/Collection _ {:type collection/library-data-collection-type}]
- (is (= "Multiple library-data collections found."
- (mt/user-http-request :crowberto :post 409 "ee/data-studio/table/publish-tables"
- {:table_ids [(mt/id :users)]}))))))))
+ {:table_ids [(mt/id :users)]
+ :collection_id Integer/MAX_VALUE}))))
+ (testing "returns 400 when collection_id is missing"
+ (mt/user-http-request :crowberto :post 400 "ee/data-studio/table/publish-tables"
+ {:table_ids [(mt/id :users)]}))
+ (testing "returns 400 when target collection is not a library-data collection"
+ (mt/with-temp [:model/Collection {collection-id :id} {}]
+ (is (= "Tables can only be published to Library/Data collections."
+ (mt/user-http-request :crowberto :post 400 "ee/data-studio/table/publish-tables"
+ {:table_ids [(mt/id :users)]
+ :collection_id collection-id})))))
+ (testing "publishes tables into library-data subcollections"
+ (mt/with-temp [:model/Collection {data-id :id} {:type collection/library-data-collection-type}
+ :model/Collection {subcollection-id :id} {:type collection/library-data-collection-type
+ :location (str "/" data-id "/")}]
+ (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"
+ {:table_ids [(mt/id :users)]
+ :collection_id subcollection-id})
+ (is (=? {:collection_id subcollection-id
+ :is_published true}
+ (t2/select-one :model/Table (mt/id :users)))))))))
(deftest requests-data-studio-feature-flag-test
(mt/with-premium-features #{}
(is (= "Library is a paid feature not currently available to your instance. Please upgrade to use it. Learn more at metabase.com/upgrade/"
(:message (mt/user-http-request :crowberto :post 402 "ee/data-studio/table/publish-tables"
- {:table_ids [(mt/id :users)]}))))))
+ {:table_ids [(mt/id :users)]
+ :collection_id 1}))))))
(deftest data-analyst-can-access-endpoints-test
(mt/with-premium-features #{:library :advanced-permissions}
@@ -86,12 +103,13 @@
:model/PermissionsGroupMembership _ {:user_id analyst-id :group_id data-analyst-group-id}
:model/Database {db-id :id} {}
:model/Table {table-id :id} {:db_id db-id}
- :model/Collection _ {:type collection/library-data-collection-type}]
+ :model/Collection {collection-id :id} {:type collection/library-data-collection-type}]
;; Grant data analyst group view-data permission on this database
(data-perms/set-database-permission! data-analyst-group-id db-id :perms/view-data :unrestricted)
(testing "data analyst can publish tables"
(is (map? (mt/user-http-request analyst-id :post 200 "ee/data-studio/table/publish-tables"
- {:table_ids [table-id]}))))
+ {:table_ids [table-id]
+ :collection_id collection-id}))))
(testing "data analyst can unpublish tables"
(is (nil? (mt/user-http-request analyst-id :post 204 "ee/data-studio/table/unpublish-tables"
{:table_ids [table-id]})))))))))
@@ -104,11 +122,12 @@
:model/Database {db-id :id} {}
:model/Table {table-id :id} {:db_id db-id}
- :model/Collection _ {:type collection/library-data-collection-type}]
+ :model/Collection {collection-id :id} {:type collection/library-data-collection-type}]
(testing "regular user cannot publish tables"
(is (= "You don't have permissions to do that."
(mt/user-http-request user-id :post 403 "ee/data-studio/table/publish-tables"
- {:table_ids [table-id]}))))
+ {:table_ids [table-id]
+ :collection_id collection-id}))))
(testing "regular user cannot unpublish tables"
(is (= "You don't have permissions to do that."
(mt/user-http-request user-id :post 403 "ee/data-studio/table/unpublish-tables"
@@ -119,7 +138,7 @@
(deftest publish-tables-with-upstream-dependencies-test
(mt/with-premium-features #{:library}
(testing "POST /api/ee/data-studio/table/publish-tables publishes upstream dependencies"
- (mt/with-temp [:model/Collection _ {:type collection/library-data-collection-type}
+ (mt/with-temp [:model/Collection {collection-id :id} {:type collection/library-data-collection-type}
:model/Database {db-id :id} {}
;; Products table (upstream)
:model/Table {products-id :id} {:db_id db-id :name "products" :is_published false}
@@ -139,14 +158,15 @@
:type :external}]
(testing "publishing orders also publishes products (upstream dependency)"
(mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"
- {:table_ids [orders-id]})
+ {:table_ids [orders-id]
+ :collection_id collection-id})
(are [table-id] (true? (t2/select-one-fn :is_published :model/Table table-id))
orders-id products-id))))))
(deftest publish-tables-recursive-upstream-test
(mt/with-premium-features #{:library}
(testing "POST /api/ee/data-studio/table/publish-tables publishes recursive upstream dependencies"
- (mt/with-temp [:model/Collection _ {:type collection/library-data-collection-type}
+ (mt/with-temp [:model/Collection {collection-id :id} {:type collection/library-data-collection-type}
:model/Database {db-id :id} {}
;; Customers table (upstream of orders)
:model/Table {customers-id :id} {:db_id db-id :name "customers" :is_published false}
@@ -177,7 +197,8 @@
:type :external}]
(testing "publishing order_items also publishes orders and customers (recursive upstream)"
(mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"
- {:table_ids [items-id]})
+ {:table_ids [items-id]
+ :collection_id collection-id})
(are [table-id] (true? (t2/select-one-fn :is_published :model/Table table-id))
items-id orders-id customers-id))))))
@@ -256,7 +277,7 @@
(deftest publish-tables-requires-write-and-query-perms-test
(mt/with-premium-features #{:library :advanced-permissions}
(testing "POST /api/ee/data-studio/table/publish-tables requires write and query permission on all tables"
- (mt/with-temp [:model/Collection _ {:type collection/library-data-collection-type}
+ (mt/with-temp [:model/Collection {collection-id :id} {:type collection/library-data-collection-type}
:model/Database {db-id :id} {}
:model/Table {table-id :id} {:db_id db-id :name "restricted_table"}
:model/User {analyst-id :id} {:first_name "Data"
@@ -271,7 +292,8 @@
;; Analyst has data analyst role but no data perms on the table
(is (= "You don't have permissions to do that."
(mt/user-http-request analyst-id :post 403 "ee/data-studio/table/publish-tables"
- {:table_ids [table-id]}))))))))
+ {:table_ids [table-id]
+ :collection_id collection-id}))))))))
(deftest unpublish-tables-requires-write-and-query-perms-test
(mt/with-premium-features #{:library :advanced-permissions}
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/can_read_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/can_read_test.clj
index a9796830865..746b553b80f 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/can_read_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/can_read_test.clj
@@ -27,7 +27,7 @@
(mt/with-temp [:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
- :model/Collection {collection-id :id} {}]
+ :model/Collection {collection-id :id} {:type "library-data"}]
;; Ensure All Users group has no create-queries permission and set view-data
;; (user is automatically in this group)
(perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data view-data)
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.clj
index ee04b2e7bf7..0325707e868 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.clj
@@ -14,7 +14,7 @@
(deftest can-access-via-collection?-returns-false-for-non-published-tables-test
(testing "Returns false for non-published tables"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection collection {}
+ (mt/with-temp [:model/Collection collection {:type "library-data"}
:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
@@ -26,7 +26,7 @@
(deftest can-access-via-collection?-returns-true-with-collection-access-test
(testing "Returns true for published tables when user has collection access"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection collection {}
+ (mt/with-temp [:model/Collection collection {:type "library-data"}
:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
@@ -38,7 +38,7 @@
(deftest can-access-via-collection?-returns-false-without-collection-access-test
(testing "Returns false for published tables when user lacks collection access"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection collection {}
+ (mt/with-temp [:model/Collection collection {:type "library-data"}
:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
@@ -64,8 +64,8 @@
(deftest published-table-visible-clause-filters-by-collection-perms-test
(testing "Returns clause that only includes published tables in readable collections"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection {allowed-coll-id :id} {}
- :model/Collection {blocked-coll-id :id} {}
+ (mt/with-temp [:model/Collection {allowed-coll-id :id} {:type "library-data"}
+ :model/Collection {blocked-coll-id :id} {:type "library-data"}
:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
@@ -102,8 +102,8 @@
(deftest published-table-perm-grant-rows-produces-create-queries-grants-test
(testing "Returns SELECT producing (id, perms/create-queries, query-builder) rows for published+visible tables"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection {allowed-coll-id :id} {}
- :model/Collection {blocked-coll-id :id} {}
+ (mt/with-temp [:model/Collection {allowed-coll-id :id} {:type "library-data"}
+ :model/Collection {blocked-coll-id :id} {:type "library-data"}
:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
@@ -140,8 +140,8 @@
(deftest visible-filter-clause-include-published-via-collection-test
(testing "visible-filter-clause :model/Table extends visibility via published+collection grants when requested"
(mt/with-premium-features #{:library}
- (mt/with-temp [:model/Collection {allowed-coll-id :id} {}
- :model/Collection {blocked-coll-id :id} {}
+ (mt/with-temp [:model/Collection {allowed-coll-id :id} {:type "library-data"}
+ :model/Collection {blocked-coll-id :id} {:type "library-data"}
:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
index c747887b4bf..23be2729399 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
@@ -28,7 +28,7 @@
(mt/with-temp [:model/PermissionsGroup {group-id :id} {}
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
- :model/Collection {collection-id :id} {}]
+ :model/Collection {collection-id :id} {:type "library-data"}]
;; Ensure All Users group has no create-queries permission and matching view-data
;; (user is automatically in this group)
(perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data view-data)
@@ -64,7 +64,7 @@
(t2/with-transaction [_conn nil {:rollback-only true}]
;; Create a test user that only belongs to all-users group (no extra permissions)
(mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
- :model/Collection collection {}]
+ :model/Collection collection {:type "library-data"}]
;; Publish the venues table into this collection
(t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
(let [all-users (perms/all-users-group)]
@@ -96,7 +96,7 @@
(testing "POST /api/dataset in EE: published table access GRANTS database access"
(t2/with-transaction [_conn nil {:rollback-only true}]
(mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
- :model/Collection collection {}]
+ :model/Collection collection {:type "library-data"}]
;; Publish the venues table into this collection
(t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
(let [all-users (perms/all-users-group)]
@@ -118,7 +118,7 @@
(testing "POST /api/dataset in EE: without collection permission, published table does NOT grant access"
(t2/with-transaction [_conn nil {:rollback-only true}]
(mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
- :model/Collection collection {}]
+ :model/Collection collection {:type "library-data"}]
;; Publish the venues table into this collection
(t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
(let [all-users (perms/all-users-group)]
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj
index f039d53b4b5..d9e11ff700d 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj
@@ -14,10 +14,12 @@
(mt/with-premium-features #{:library}
(testing "Published tables are included in collection-filtered search"
(mt/with-temp
- [:model/Collection {parent-coll :id} {:name "Parent Collection" :location "/"}
- :model/Collection {child-coll :id} {:name "Child Collection"
- :location (collection/location-path parent-coll)}
- :model/Card {card-1 :id} {:collection_id parent-coll :name "Parent Card"}
+ [:model/Collection {parent-coll :id} {:name "Parent Collection"
+ :location "/"
+ :type "library-data"}
+ :model/Collection {child-coll :id} {:name "Child Collection"
+ :location (collection/location-path parent-coll)
+ :type "library-data"}
:model/Table {table-1 :id} {:name "Published Table" :is_published true :collection_id parent-coll}
:model/Table {table-2 :id} {:name "Child Published Table" :is_published true :collection_id child-coll}
:model/Table {table-3 :id} {:name "Unpublished Table" :is_published false}
@@ -28,14 +30,14 @@
(testing (str "with engine " engine)
(testing "Global search"
(let [results (mt/user-http-request :crowberto :get 200 "search" :search_engine engine)]
- (is (=? [{:collection {:authority_level nil, :id parent-coll, :name "Parent Collection", :type nil}
+ (is (=? [{:collection {:authority_level nil, :id parent-coll, :name "Parent Collection", :type "library-data"}
:database_id (mt/id)
:id table-1
:model "table"
:name "Published Table"
:table_id table-1
:table_name "Published Table"}
- {:collection {:authority_level nil, :id child-coll, :name "Child Collection", :type nil}
+ {:collection {:authority_level nil, :id child-coll, :name "Child Collection", :type "library-data"}
:database_id (mt/id)
:id table-2
:model "table"
@@ -60,7 +62,10 @@
(sort-by :id))))))
(testing "Filter by parent collection returns published tables in that collection and descendants"
(let [results (mt/user-http-request :crowberto :get 200 "search" :collection parent-coll :search_engine engine)]
- (is (=? {:collection {:authority_level nil, :id parent-coll, :name "Parent Collection", :type nil}
+ (is (=? {:collection {:authority_level nil
+ :id parent-coll
+ :name "Parent Collection"
+ :type "library-data"}
:database_id (mt/id)
:id table-1
:model "table"
@@ -71,9 +76,7 @@
(is (contains? (set (map :id (:data results))) table-1)
"Published table in parent collection should be included")
(is (contains? (set (map :id (:data results))) table-2)
- "Published table in child collection should be included")
- (is (contains? (set (map :id (:data results))) card-1)
- "Card in parent collection should be included")))
+ "Published table in child collection should be included")))
(testing "Unpublished tables are not included in collection filter results"
(let [results (mt/user-http-request :crowberto :get 200 "search" :collection parent-coll :search_engine engine)]
(is (not (contains? (set (map :id (:data results))) table-3))
@@ -89,8 +92,10 @@
"Root published table should appear in search results"))))))
(testing "Published tables appear as collection items, unpublished as database items"
(mt/with-temp
- [:model/Database {db-id :id} {:name "Context Test DB"}
- :model/Collection {coll-id :id} {:name "Context Test Collection" :location "/"}
+ [:model/Database {db-id :id} {:name "Context Test DB"}
+ :model/Collection {coll-id :id} {:name "Context Test Collection"
+ :type "library-data"
+ :location "/"}
:model/Table {pub-table :id} {:name "ContextTestTablePub"
:db_id db-id
:is_published true
@@ -145,7 +150,9 @@
(let [search-term (random-name)
table-name (str search-term " published")]
(mt/with-no-data-perms-for-all-users!
- (mt/with-temp [:model/Collection {coll-id :id} {:name "No Access Collection" :location "/"}
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "No Access Collection"
+ :location "/"
+ :type "library-data"}
:model/Table {pub-table :id} {:name table-name :is_published true :collection_id coll-id}]
;; Grant data permissions on the table
(data-perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data :unrestricted)
@@ -163,6 +170,48 @@
(format "Published table should be visible with data permissions even without collection access (engine=%s)"
engine)))))))))))
+(deftest library-scoped-search-test
+ (mt/with-premium-features #{:library}
+ (let [search-term (random-name)]
+ (mt/with-temp
+ [:model/Collection {lib-id :id} {:name "Library" :type collection/library-collection-type :location "/"}
+ :model/Collection {data-coll :id} {:name "Data"
+ :type collection/library-data-collection-type
+ :location (collection/location-path lib-id)}
+ :model/Collection {metrics-coll :id} {:name "Metrics"
+ :type collection/library-metrics-collection-type
+ :location (collection/location-path lib-id)}
+ :model/Collection {data-sub :id} {:name "Data Sub"
+ :type collection/library-data-collection-type
+ :location (collection/location-path lib-id data-coll)}
+ :model/Table {pub-table :id} {:name (str search-term " Published Table")
+ :is_published true
+ :collection_id data-coll}
+ :model/Table {sub-table :id} {:name (str search-term " Sub Table")
+ :is_published true
+ :collection_id data-sub}
+ :model/Card {metric :id} {:name (str search-term " My Metric")
+ :type :metric
+ :collection_id metrics-coll}
+ :model/Collection {outside-coll :id} {:name "Outside" :location "/"}
+ :model/Card {outside-card :id} {:name (str search-term " Outside Card")
+ :collection_id outside-coll}]
+ (search/reindex! {:async? false :in-place? true})
+ (doseq [engine ["in-place" "appdb"]]
+ (testing (str "with engine " engine)
+ (let [results (mt/user-http-request :crowberto :get 200 "search"
+ :q search-term
+ :collection lib-id
+ :search_engine engine)
+ result-ids (set (map :id (:data results)))]
+ (testing "published tables in library subcollections are included"
+ (is (contains? result-ids pub-table))
+ (is (contains? result-ids sub-table)))
+ (testing "metrics in library subcollections are included"
+ (is (contains? result-ids metric)))
+ (testing "items outside the library are excluded"
+ (is (not (contains? result-ids outside-card)))))))))))
+
(deftest unpublished-table-visible-with-data-perms-test
(testing "Unpublished tables are discoverable when the user has data/query permissions"
(let [search-term (random-name)
@@ -182,3 +231,40 @@
(into #{}))]
(is (contains? result-ids unpub-table)
(format "Unpublished table should be visible with data permissions (engine=%s)" engine))))))))))
+
+(deftest no-access-library-subcollection-hidden-from-search-test
+ (mt/with-premium-features #{:library}
+ (testing "Items in library subcollections the user can't access are hidden from search"
+ (let [search-term (random-name)]
+ (mt/with-temp
+ [:model/Collection {metrics-coll :id} {:name "Metrics"
+ :type collection/library-metrics-collection-type
+ :location "/"}
+ :model/Collection {accessible :id} {:name "Accessible Sub"
+ :type collection/library-metrics-collection-type
+ :location (collection/location-path metrics-coll)}
+ :model/Collection {no-access :id} {:name "No Access Sub"
+ :type collection/library-metrics-collection-type
+ :location (collection/location-path metrics-coll)}
+ :model/Card {visible-metric :id} {:name (str search-term " Visible Metric")
+ :type :metric
+ :collection_id accessible}
+ :model/Card {hidden-metric :id} {:name (str search-term " Hidden Metric")
+ :type :metric
+ :collection_id no-access}]
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (perms/grant-collection-read-permissions! (perms/all-users-group) metrics-coll)
+ (perms/grant-collection-read-permissions! (perms/all-users-group) accessible)
+ (perms/revoke-collection-permissions! (perms/all-users-group) no-access)
+ (search/reindex! {:async? false :in-place? true})
+ (doseq [engine ["in-place" "appdb"]]
+ (testing (str "with engine " engine)
+ (let [result-ids (->> (mt/user-http-request :rasta :get 200 "search"
+ :q search-term :search_engine engine)
+ :data
+ (map :id)
+ (into #{}))]
+ (testing "metric in accessible subcollection is visible"
+ (is (contains? result-ids visible-metric)))
+ (testing "metric in no-access subcollection is hidden"
+ (is (not (contains? result-ids hidden-metric)))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/library/api_test.clj b/enterprise/backend/test/metabase_enterprise/library/api_test.clj
index 33960f88252..7936c713615 100644
--- a/enterprise/backend/test/metabase_enterprise/library/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/library/api_test.clj
@@ -35,3 +35,20 @@
(is (= "Library" (:name response)))
(is (= ["metric" "table"] (:below response)))
(is (= ["collection"] (:here response)))))))))))
+
+(deftest disallow-cross-type-collection-move-via-api-test
+ (mt/with-premium-features #{:library}
+ (mt/with-temp [:model/Collection data-parent {:name "Data Parent" :type collection/library-data-collection-type}
+ :model/Collection metrics-parent {:name "Metrics Parent" :type collection/library-metrics-collection-type}
+ :model/Collection data-child {:name "Data Child" :type collection/library-data-collection-type
+ :location (str "/" (:id data-parent) "/")}
+ :model/Collection metrics-child {:name "Metrics Child" :type collection/library-metrics-collection-type
+ :location (str "/" (:id metrics-parent) "/")}]
+ (testing "Moving a library-data collection into a library-metrics parent returns 400"
+ (let [response (mt/user-http-request :crowberto :put 400 (str "collection/" (:id data-child))
+ {:parent_id (:id metrics-parent)})]
+ (is (some? response))))
+ (testing "Moving a library-metrics collection into a library-data parent returns 400"
+ (let [response (mt/user-http-request :crowberto :put 400 (str "collection/" (:id metrics-child))
+ {:parent_id (:id data-parent)})]
+ (is (some? response)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/library/validation_test.clj b/enterprise/backend/test/metabase_enterprise/library/validation_test.clj
index 6a157c36cac..7daf0b41fe2 100644
--- a/enterprise/backend/test/metabase_enterprise/library/validation_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/library/validation_test.clj
@@ -34,14 +34,21 @@
(mt/with-temp [:model/Table table {:collection_id (:id allow-tables)
:is_published true}]
(is (some? table)))
- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add tables to the 'Data' collection"
- (t2/insert! :model/Collection (merge (mt/with-temp-defaults :model/Collection) {:location (str "/" (:id allow-tables) "/")}))))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add tables to the 'Data' collection"
(t2/insert! :model/Card (merge (mt/with-temp-defaults :model/Card) {:type :model :collection_id (:id allow-tables)}))))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add tables to the 'Data' collection"
(t2/insert! :model/Card (merge (mt/with-temp-defaults :model/Card) {:type :metric :collection_id (:id allow-tables)}))))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add tables to the 'Data' collection"
- (t2/insert! :model/Dashboard (merge (mt/with-temp-defaults :model/Dashboard) {:collection_id (:id allow-tables)}))))))))
+ (t2/insert! :model/Dashboard (merge (mt/with-temp-defaults :model/Dashboard) {:collection_id (:id allow-tables)})))))
+
+ (testing "Can add collections iff they have the same :type"
+ (let [new-coll (merge (mt/with-temp-defaults :model/Collection)
+ {:location (str "/" (:id allow-tables) "/")})]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add tables to the 'Data' collection"
+ (t2/insert! :model/Collection new-coll))
+ "basic new collection is rejected")
+ (is (= 1 (t2/insert! :model/Collection (assoc new-coll :type collection/library-data-collection-type)))
+ "new collection with :type set is allowed"))))))
(deftest check-allowed-content-metric
(mt/with-premium-features #{:library}
@@ -50,20 +57,161 @@
(mt/with-temp [:model/Card card {:collection_id (:id allow-metrics)
:type :metric}]
(is (some? card)))
- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add metrics to the 'Metrics' collection"
- (t2/insert! :model/Collection (merge (mt/with-temp-defaults :model/Collection) {:location (str "/" (:id allow-metrics) "/")}))))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add metrics to the 'Metrics' collection"
(t2/insert! :model/Card (merge (mt/with-temp-defaults :model/Card) {:type :model :collection_id (:id allow-metrics)}))))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add metrics to the 'Metrics' collection"
- (t2/insert! :model/Dashboard (merge (mt/with-temp-defaults :model/Dashboard) {:collection_id (:id allow-metrics)}))))))))
+ (t2/insert! :model/Dashboard (merge (mt/with-temp-defaults :model/Dashboard) {:collection_id (:id allow-metrics)})))))
+ (testing "Can add collections iff they have the same :type"
+ (let [new-coll (merge (mt/with-temp-defaults :model/Collection)
+ {:location (str "/" (:id allow-metrics) "/")})]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add metrics to the 'Metrics' collection"
+ (t2/insert! :model/Collection new-coll))
+ "basic new collection is rejected")
+ (is (= 1 (t2/insert! :model/Collection (assoc new-coll :type collection/library-metrics-collection-type)))
+ "new collection with :type set is allowed"))))))
+
+(deftest tables-cannot-be-moved-to-non-library-data-collections
+ (mt/with-premium-features #{:library}
+ (mt/with-temp [:model/Collection library-data {:name "Library Data" :type collection/library-data-collection-type}
+ :model/Collection regular {:name "Regular Collection" :type nil}
+ :model/Table table {:collection_id (:id library-data)
+ :is_published true}]
+ (testing "Cannot insert a published table into a regular collection"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tables can only be added to"
+ (t2/insert! :model/Table (merge (mt/with-temp-defaults :model/Table)
+ {:collection_id (:id regular)
+ :is_published true})))))
+ (testing "Cannot move a published table to a regular collection"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tables can only be added to"
+ (t2/update! :model/Table (:id table) {:collection_id (:id regular)}))))
+ (testing "Can move a table out to no collection"
+ (is (some? (t2/update! :model/Table (:id table) {:collection_id nil})))))))
(deftest cannot-update-library-collections
(mt/with-premium-features #{:library}
(mt/with-temp [:model/Collection library {:name "Test Library" :type collection/library-collection-type}
:model/Collection models {:name "Test Semantic Model Layer" :type collection/library-data-collection-type}
:model/Collection metrics {:name "Test Semantic Metrics Layer" :type collection/library-metrics-collection-type}]
- (doseq [col [library models metrics]]
- (testing (str "Checking type " (:type col))
- (is (thrown-with-msg? clojure.lang.ExceptionInfo
- #"Cannot update properties on a Library collection"
- (t2/update! :model/Collection (:id col) {:name "New Name"}))))))))
+ (with-redefs [collection/library-root-collection? (constantly true)]
+ (doseq [col [library models metrics]]
+ (testing (str "Checking type " (:type col))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Cannot update properties on a Library collection"
+ (t2/update! :model/Collection (:id col) {:name "New Name"})))))))))
+
+(deftest unpublish-tables-in-archived-collection-test
+ (mt/with-premium-features #{:library}
+ (mt/as-admin
+ (mt/with-temp [:model/Collection archive-me {:name "To be archived"
+ :type collection/library-data-collection-type}
+ :model/Table table {:collection_id (:id archive-me)
+ :is_published true}]
+ (collection/archive-collection! archive-me)
+ (testing "archiving a Library/Data subcollection unpublishes all the tables it contains"
+ (is (=? {:is_published false
+ :collection_id nil
+ :id (:id table)}
+ (t2/select-one :model/Table :id (:id table))))
+ (is (t2/select-one-fn :archived :model/Collection :id (:id archive-me))))))))
+
+(deftest unpublish-tables-in-archived-collection-recursively-test
+ (mt/with-premium-features #{:library}
+ (mt/as-admin
+ (mt/with-temp [:model/Collection archive-me {:name "To be archived"
+ :type collection/library-data-collection-type}
+ :model/Table table1 {:collection_id (:id archive-me)
+ :is_published true
+ :name "Grandparent_Table"}
+ :model/Collection parent {:name "Middle collection"
+ :type collection/library-data-collection-type
+ :location (str "/" (:id archive-me) "/")}
+ :model/Table table2 {:collection_id (:id parent)
+ :is_published true
+ :name "Parent_Table"}
+ :model/Collection child {:name "Innermost collection"
+ :type collection/library-data-collection-type
+ :location (str "/" (:id archive-me) "/" (:id parent) "/")}
+ :model/Table table3 {:collection_id (:id child)
+ :is_published true
+ :name "Child_Table"}]
+ (collection/archive-collection! archive-me)
+ (testing "archiving a Library/Data subcollection unpublishes all the tables it contains **recursively**"
+ (is (t2/select-one-fn :archived :model/Collection :id (:id archive-me)))
+ (doseq [table [table1 table2 table3]]
+ (is (=? {:is_published false
+ :collection_id nil
+ :id (:id table)}
+ (t2/select-one :model/Table :id (:id table))))))))))
+
+(deftest archive-metrics-subcollection-goes-to-trash-test
+ (mt/with-premium-features #{:library}
+ (mt/as-admin
+ (mt/with-temp [:model/Collection archive-me {:name "Metrics subcoll"
+ :type collection/library-metrics-collection-type}
+ :model/Card metric {:collection_id (:id archive-me)
+ :type :metric}]
+ (collection/archive-collection! archive-me)
+ (testing "the collection is archived"
+ (is (true? (t2/select-one-fn :archived :model/Collection :id (:id archive-me)))))
+ (testing "the metric inside is archived"
+ (is (true? (t2/select-one-fn :archived :model/Card :id (:id metric)))))
+ (testing "the metric stays in its original collection (not unpublished/ejected)"
+ (is (= (:id archive-me)
+ (t2/select-one-fn :collection_id :model/Card :id (:id metric)))))))))
+
+(deftest disallow-cross-type-collection-nesting-test
+ (mt/with-premium-features #{:library}
+ (mt/with-temp [:model/Collection data-parent {:name "Data Parent" :type collection/library-data-collection-type}
+ :model/Collection metrics-parent {:name "Metrics Parent" :type collection/library-metrics-collection-type}
+ :model/Collection data-child {:name "Data Child" :type collection/library-data-collection-type
+ :location (str "/" (:id data-parent) "/")}
+ :model/Collection metrics-child {:name "Metrics Child" :type collection/library-metrics-collection-type
+ :location (str "/" (:id metrics-parent) "/")}]
+ (testing "Cannot move a library-data collection into a library-metrics parent"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add metrics"
+ (t2/update! :model/Collection (:id data-child)
+ {:location (str "/" (:id metrics-parent) "/")}))))
+ (testing "Cannot move a library-metrics collection into a library-data parent"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add tables"
+ (t2/update! :model/Collection (:id metrics-child)
+ {:location (str "/" (:id data-parent) "/")}))))
+ (testing "Cannot move a library-data collection via API to a library-metrics parent"
+ (is (= "Can only add metrics to the 'Metrics' collection"
+ (mt/user-http-request :crowberto :put 400 (str "collection/" (:id data-child))
+ {:parent_id (:id metrics-parent)}))))
+ (testing "Cannot move a library-metrics collection via API to a library-data parent"
+ (is (= "Can only add tables to the 'Data' collection"
+ (mt/user-http-request :crowberto :put 400 (str "collection/" (:id metrics-child))
+ {:parent_id (:id data-parent)})))))))
+
+(deftest cannot-move-library-collections-to-vanilla-collection-test
+ (mt/with-premium-features #{:library}
+ (mt/with-temp [:model/Collection library-root {:name "Library" :type collection/library-collection-type}
+ :model/Collection data-root {:name "Data" :type collection/library-data-collection-type
+ :location (str "/" (:id library-root) "/")}
+ :model/Collection metrics-root {:name "Metrics" :type collection/library-metrics-collection-type
+ :location (str "/" (:id library-root) "/")}
+ :model/Collection data-sub {:name "Data Sub" :type collection/library-data-collection-type
+ :location (str "/" (:id library-root) "/" (:id data-root) "/")}
+ :model/Collection metrics-sub {:name "Metrics Sub" :type collection/library-metrics-collection-type
+ :location (str "/" (:id library-root) "/" (:id metrics-root) "/")}
+ :model/Collection vanilla {:name "Vanilla Collection" :type nil}]
+ (let [vanilla-location (str "/" (:id vanilla) "/")]
+ (with-redefs [collection/library-root-collection? (fn [coll]
+ (contains? #{(:id library-root) (:id data-root) (:id metrics-root)}
+ (:id coll)))]
+ (testing "Cannot move the Library collection itself into a vanilla collection"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot update properties on a Library collection"
+ (t2/update! :model/Collection (:id library-root) {:location vanilla-location}))))
+ (testing "Cannot move a top-level Data collection into a vanilla collection"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot update properties on a Library collection"
+ (t2/update! :model/Collection (:id data-root) {:location vanilla-location}))))
+ (testing "Cannot move a top-level Metrics collection into a vanilla collection"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot update properties on a Library collection"
+ (t2/update! :model/Collection (:id metrics-root) {:location vanilla-location})))))
+ (testing "Cannot move a Data subcollection into a vanilla collection"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot move a Library collection outside the Library"
+ (t2/update! :model/Collection (:id data-sub) {:location vanilla-location}))))
+ (testing "Cannot move a Metrics subcollection into a vanilla collection"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot move a Library collection outside the Library"
+ (t2/update! :model/Collection (:id metrics-sub) {:location vanilla-location}))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
index e44a8b3e73f..27664b48779 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
@@ -8,10 +8,12 @@
[metabase-enterprise.serialization.v2.ingest :as serdes.ingest]
[metabase-enterprise.serialization.v2.load :as serdes.load]
[metabase.actions.models :as action]
+ [metabase.collections.models.collection :as collection]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.models.serialization :as serdes]
+ [metabase.permissions.core :as perms]
[metabase.search.core :as search]
[metabase.test :as mt]
[metabase.util :as u]
@@ -2187,3 +2189,112 @@
(let [metabot (t2/select-one :model/Metabot :name "Minimal Bot")]
(is (some? metabot))
(is (= "Minimal Bot" (:name metabot))))))))))
+
+(deftest library-subcollection-round-trip-test
+ (testing "Library subcollection structure and types are preserved through serdes round-trip"
+ (let [serialized (atom nil)
+ library (atom nil)
+ data-root (atom nil)
+ metrics-root (atom nil)
+ data-sub (atom nil)]
+ (ts/with-dbs [source-db dest-db]
+ (testing "extraction of library hierarchy"
+ (ts/with-db source-db
+ (reset! library (ts/create! :model/Collection
+ :name "Library"
+ :type collection/library-collection-type
+ :location "/"
+ :entity_id @#'collection/library-entity-id))
+ (reset! data-root (ts/create! :model/Collection
+ :name "Data"
+ :type collection/library-data-collection-type
+ :location (format "/%d/" (:id @library))
+ :entity_id @#'collection/library-data-entity-id))
+ (reset! metrics-root (ts/create! :model/Collection
+ :name "Metrics"
+ :type collection/library-metrics-collection-type
+ :location (format "/%d/" (:id @library))
+ :entity_id @#'collection/library-metrics-entity-id))
+ (reset! data-sub (ts/create! :model/Collection
+ :name "Sales Tables"
+ :type collection/library-data-collection-type
+ :location (format "/%d/%d/" (:id @library) (:id @data-root))))
+ (reset! serialized (into [] (serdes.extract/extract {})))
+ (is (some (fn [{[{:keys [model id]}] :serdes/meta}]
+ (and (= model "Collection") (= id (:entity_id @library))))
+ @serialized))))
+
+ (testing "loading into destination preserves library structure"
+ (ts/with-db dest-db
+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))
+ (let [lib-dest (t2/select-one :model/Collection :entity_id (:entity_id @library))
+ data-dest (t2/select-one :model/Collection :entity_id (:entity_id @data-root))
+ metrics-dest (t2/select-one :model/Collection :entity_id (:entity_id @metrics-root))
+ sub-dest (t2/select-one :model/Collection :entity_id (:entity_id @data-sub))]
+ (testing "all collections exist"
+ (is (some? lib-dest))
+ (is (some? data-dest))
+ (is (some? metrics-dest))
+ (is (some? sub-dest)))
+ (testing "types are preserved"
+ (is (= collection/library-collection-type (:type lib-dest)))
+ (is (= collection/library-data-collection-type (:type data-dest)))
+ (is (= collection/library-metrics-collection-type (:type metrics-dest)))
+ (is (= collection/library-data-collection-type (:type sub-dest))))
+ (testing "parent-child hierarchy is correct"
+ (is (= "/" (:location lib-dest)))
+ (is (= (format "/%d/" (:id lib-dest)) (:location data-dest)))
+ (is (= (format "/%d/" (:id lib-dest)) (:location metrics-dest)))
+ (is (= (format "/%d/%d/" (:id lib-dest) (:id data-dest)) (:location sub-dest)))))))))))
+
+(deftest library-import-preserves-existing-permissions-test
+ (testing "Importing library subcollections does not overwrite existing permissions on destination"
+ (let [serialized (atom nil)
+ eid-data "testdataeid0000000000"
+ eid-sub "testsubeid00000000000"]
+ (ts/with-dbs [source-db dest-db]
+ (testing "extract from source"
+ (ts/with-db source-db
+ (let [data-coll (ts/create! :model/Collection
+ :name "Data"
+ :type collection/library-data-collection-type
+ :location "/"
+ :entity_id eid-data)
+ _sub-coll (ts/create! :model/Collection
+ :name "Sales Tables"
+ :type collection/library-data-collection-type
+ :location (format "/%d/" (:id data-coll))
+ :entity_id eid-sub)]
+ (reset! serialized (into [] (serdes.extract/extract {}))))))
+
+ (testing "pre-populate dest with same collections and custom permissions"
+ (ts/with-db dest-db
+ (let [data-dest (ts/create! :model/Collection
+ :name "Data"
+ :type collection/library-data-collection-type
+ :location "/"
+ :entity_id eid-data)
+ sub-dest (ts/create! :model/Collection
+ :name "Sales Tables"
+ :type collection/library-data-collection-type
+ :location (format "/%d/" (:id data-dest))
+ :entity_id eid-sub)
+ group (ts/create! :model/PermissionsGroup :name "Custom Group")]
+ (perms/grant-collection-readwrite-permissions! group data-dest)
+ (perms/grant-collection-read-permissions! group sub-dest)
+ (let [perms-before (set (map #(select-keys % [:group_id :object])
+ (t2/select :model/Permissions
+ :object [:like (format "/collection/%d/%%" (:id data-dest))])))]
+ (testing "custom permissions exist before import"
+ (is (seq perms-before)))
+
+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))
+
+ (let [data-after (t2/select-one :model/Collection :entity_id eid-data)
+ perms-after (set (map #(select-keys % [:group_id :object])
+ (t2/select :model/Permissions
+ :object [:like (format "/collection/%d/%%" (:id data-after))])))]
+ (testing "collection still exists with same ID"
+ (is (= (:id data-dest) (:id data-after))))
+ (testing "permissions are unchanged after import"
+ (is (= perms-before perms-after))))))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/api/table.ts b/enterprise/frontend/src/metabase-enterprise/api/table.ts
index 649f4e6d2d1..a22a37d0f47 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/table.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/table.ts
@@ -1,5 +1,5 @@
import type {
- BulkTableSelection,
+ BulkTableRequest,
PublishTablesResponse,
} from "metabase-types/api";
@@ -8,7 +8,7 @@ import { invalidateTags, tag } from "./tags";
export const tableApi = EnterpriseApi.injectEndpoints({
endpoints: (builder) => ({
- publishTables: builder.mutation<PublishTablesResponse, BulkTableSelection>({
+ publishTables: builder.mutation<PublishTablesResponse, BulkTableRequest>({
query: (body) => ({
method: "POST",
url: "/api/ee/data-studio/table/publish-tables",
@@ -17,7 +17,7 @@ export const tableApi = EnterpriseApi.injectEndpoints({
invalidatesTags: (_, error) =>
invalidateTags(error, [tag("table"), tag("card"), tag("collection")]),
}),
- unpublishTables: builder.mutation<void, BulkTableSelection>({
+ unpublishTables: builder.mutation<void, BulkTableRequest>({
query: (body) => ({
method: "POST",
url: "/api/ee/data-studio/table/unpublish-tables",
diff --git a/enterprise/frontend/src/metabase-enterprise/collections/utils.ts b/enterprise/frontend/src/metabase-enterprise/collections/utils.ts
index ec23872d86f..eb26f3b4206 100644
--- a/enterprise/frontend/src/metabase-enterprise/collections/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/collections/utils.ts
@@ -5,9 +5,8 @@ import type {
CollectionInstanceAnaltyicsConfig,
} from "metabase/collections/types";
import type { IconData, ObjectWithModel } from "metabase/common/utils/icon";
-import { getLibraryCollectionType } from "metabase/data-studio/utils";
import { useGetIconBase } from "metabase/hooks/use-icon";
-import type { ItemWithCollection } from "metabase/plugins";
+import { type ItemWithCollection, PLUGIN_LIBRARY } from "metabase/plugins";
import type {
Bookmark,
Collection,
@@ -78,10 +77,7 @@ export const useGetIcon = () => {
if (item.model === "collection") {
// Library collections keep their special icon regardless of sync status
- const libraryCollectionType = getLibraryCollectionType(
- item.type as CollectionType,
- );
- if (libraryCollectionType != null) {
+ if (PLUGIN_LIBRARY.isLibraryCollectionType(item.type)) {
return getIconBase(item);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx
index dc132b07d40..0e5235846b8 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx
@@ -1,93 +1,30 @@
-import { useCallback, useMemo, useState } from "react";
+import { useDisclosure } from "@mantine/hooks";
+import { useMemo, useState } from "react";
import { t } from "ttag";
-import _ from "underscore";
import { useListCollectionsTreeQuery } from "metabase/api";
-import { isLibraryCollection } from "metabase/collections/utils";
-import { DateTime } from "metabase/common/components/DateTime";
-import { ForwardRefLink } from "metabase/common/components/Link";
import { ListEmptyState } from "metabase/common/components/ListEmptyState";
import { useHasTokenFeature } from "metabase/common/hooks";
import { SectionLayout } from "metabase/data-studio/app/components/SectionLayout";
import { DataStudioBreadcrumbs } from "metabase/data-studio/common/components/DataStudioBreadcrumbs";
import { PaneHeader } from "metabase/data-studio/common/components/PaneHeader";
-import { useBuildSnippetTree } from "metabase/data-studio/common/hooks/use-build-snippet-tree";
-import type {
- EmptyStateData,
- TreeItem,
-} from "metabase/data-studio/common/types";
-import {
- isCollection,
- isEmptyStateData,
-} from "metabase/data-studio/common/utils";
-import type { ExpandedState } from "metabase/data-studio/data-model/components/TablePicker/types";
import { LibraryUpsellPage } from "metabase/data-studio/upsells/pages";
-import { PLUGIN_SNIPPET_FOLDERS } from "metabase/plugins";
-import { useSelector } from "metabase/redux";
-import { useRouter } from "metabase/router";
import {
- Anchor,
Card,
- EntityNameCell,
Flex,
Icon,
Stack,
- Text,
TextInput,
TreeTable,
- type TreeTableColumnDef,
TreeTableSkeleton,
- useTreeTableInstance,
} from "metabase/ui";
-import * as Urls from "metabase/urls";
-import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
-import type { Collection, CollectionId } from "metabase-types/api";
import { LibraryEmptyState } from "../components/LibraryEmptyState";
-import { CreateMenu } from "./CreateMenu";
-import { PublishTableModal } from "./PublishTableModal";
-import { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";
-import { useBuildTreeForCollection, useErrorHandling } from "./hooks";
-import { getAccessibleCollection, getWritableCollection } from "./utils";
-
-interface EmptyStateActionProps {
- data: EmptyStateData;
- onPublishTable: () => void;
-}
-
-function EmptyStateAction({ data, onPublishTable }: EmptyStateActionProps) {
- if (data.sectionType === "data") {
- return (
- <Anchor
- component="button"
- type="button"
- fz="inherit"
- onClick={(e) => {
- e.stopPropagation();
- onPublishTable();
- }}
- >
- {data.actionLabel}
- </Anchor>
- );
- }
-
- if (data.actionUrl) {
- return (
- <Anchor
- component={ForwardRefLink}
- to={data.actionUrl}
- fz="inherit"
- onClick={(e) => e.stopPropagation()}
- >
- {data.actionLabel}
- </Anchor>
- );
- }
-
- return null;
-}
+import { CreateMenu } from "./components/CreateMenu";
+import { PublishTableModal } from "./components/PublishTableModal";
+import { useLibraryCollections, useLibraryTreeTableInstance } from "./hooks";
+import { getTreeRowHref, getWritableCollection } from "./utils";
export function LibraryPage() {
const hasLibraryFeature = useHasTokenFeature("library");
@@ -100,54 +37,26 @@ export function LibraryPage() {
}
function LibraryPageContent() {
- const { location } = useRouter();
- const [editingCollection, setEditingCollection] = useState<Collection | null>(
- null,
- );
- const [permissionsCollectionId, setPermissionsCollectionId] =
- useState<CollectionId | null>(null);
const [searchQuery, setSearchQuery] = useState("");
- const [isPublishTableModalOpen, setIsPublishTableModalOpen] = useState(false);
- const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
-
- const expandedIdsFromUrl = useMemo(() => {
- const rawIds = location.query?.expandedId;
- if (!rawIds) {
- return null;
- }
-
- const ids = Array.isArray(rawIds) ? rawIds : [rawIds];
- return _.object(
- ids.map((id) => [`collection:${id}`, true]),
- ) as ExpandedState;
- }, [location.query?.expandedId]);
-
+ const [
+ showPublishTableModal,
+ { open: openPublishTableModal, close: closePublishTableModal },
+ ] = useDisclosure(false);
const { data: collections = [], isLoading: isLoadingCollections } =
useListCollectionsTreeQuery({
"exclude-other-user-collections": true,
"exclude-archived": true,
"include-library": true,
});
+ const { treeTableInstance, isChildrenLoading, isLoading, emptyMessage } =
+ useLibraryTreeTableInstance({
+ collections,
+ searchQuery,
+ onPublishTableClick: openPublishTableModal,
+ });
- const libraryCollection = useMemo(
- () => collections.find(isLibraryCollection),
- [collections],
- );
-
- const tableCollection = useMemo(
- () =>
- libraryCollection &&
- getAccessibleCollection(libraryCollection, "library-data"),
- [libraryCollection],
- );
-
- const metricCollection = useMemo(
- () =>
- libraryCollection &&
- getAccessibleCollection(libraryCollection, "library-metrics"),
- [libraryCollection],
- );
-
+ const { libraryCollection, tableCollection } =
+ useLibraryCollections(collections);
const writableMetricCollection = useMemo(
() =>
libraryCollection &&
@@ -155,202 +64,6 @@ function LibraryPageContent() {
[libraryCollection],
);
- const getItemHref = useCallback((item: TreeItem): string | null => {
- if (item.model === "empty-state" || isEmptyStateData(item.data)) {
- return null;
- }
- const entityId = item.data.id as number;
- if (item.model === "metric") {
- return Urls.dataStudioMetric(entityId);
- }
- if (item.model === "snippet") {
- return Urls.dataStudioSnippet(entityId);
- }
- if (item.model === "table") {
- return Urls.dataStudioTable(entityId);
- }
- return null;
- }, []);
- const {
- tree: tablesTree,
- isLoading: loadingTables,
- error: tablesError,
- } = useBuildTreeForCollection(tableCollection, "data");
- const {
- tree: metricsTree,
- isLoading: loadingMetrics,
- error: metricsError,
- } = useBuildTreeForCollection(
- metricCollection,
- "metrics",
- metricCollection?.id,
- );
- const {
- tree: snippetTree,
- isLoading: loadingSnippets,
- error: snippetsError,
- } = useBuildSnippetTree();
-
- const combinedTree = useMemo(
- () => [...tablesTree, ...metricsTree, ...snippetTree],
- [tablesTree, metricsTree, snippetTree],
- );
-
- const isLoading = loadingTables || loadingMetrics || loadingSnippets;
- useErrorHandling(tablesError || metricsError || snippetsError);
-
- // Collections with only empty-state children should always be expanded
- // (even when navigating back via breadcrumbs which may collapse other sections)
- const alwaysExpandedIds = useMemo(() => {
- const ids: Record<string, boolean> = {};
- combinedTree.forEach((node) => {
- if (node.model === "collection" && node.children) {
- const hasOnlyEmptyState = node.children.every(
- (child) => child.model === "empty-state",
- );
- if (hasOnlyEmptyState) {
- ids[node.id] = true;
- }
- }
- });
- return ids;
- }, [combinedTree]);
-
- // Merge URL-based expansion with always-expanded empty sections
- const effectiveExpandedState = useMemo(() => {
- if (!expandedIdsFromUrl) {
- return true; // Expand all by default
- }
- return {
- ...expandedIdsFromUrl,
- ...alwaysExpandedIds,
- };
- }, [expandedIdsFromUrl, alwaysExpandedIds]);
-
- const libraryHasContent = useMemo(
- () =>
- combinedTree.some(
- (node) =>
- node.children &&
- node.children.length > 0 &&
- node.children.some((child) => child.model !== "empty-state"),
- ),
- [combinedTree],
- );
-
- const libraryColumnDef = useMemo<TreeTableColumnDef<TreeItem>[]>(
- () => [
- {
- id: "name",
- header: t`Name`,
- enableSorting: true,
- accessorKey: "name",
- minWidth: 200,
- cell: ({ row }) => {
- const { data } = row.original;
-
- if (isEmptyStateData(data)) {
- return (
- <Flex align="center" gap="0.25rem" data-testid="empty-state-row">
- <Text c="text-tertiary" fz="inherit">
- {data.description}
- </Text>
- {!isRemoteSyncReadOnly && (
- <EmptyStateAction
- data={data}
- onPublishTable={() => setIsPublishTableModalOpen(true)}
- />
- )}
- </Flex>
- );
- }
-
- return (
- <EntityNameCell
- data-testid={`${row.original.model}-name`}
- icon={row.original.icon}
- name={row.original.name}
- />
- );
- },
- },
- {
- id: "updatedAt",
- header: t`Updated At`,
- accessorKey: "updatedAt",
- enableSorting: true,
- sortingFn: "datetime",
- width: "auto",
- widthPadding: 20,
- cell: ({ row, getValue }) => {
- if (row.original.model === "empty-state") {
- return null;
- }
- const dateValue = getValue() as string | undefined;
- return dateValue ? <DateTime value={dateValue} /> : null;
- },
- },
- {
- id: "actions",
- width: 48,
- cell: ({ row }) => {
- const { data } = row.original;
- if (isEmptyStateData(data)) {
- return null;
- }
- if (
- isCollection(data) &&
- data.model === "collection" &&
- data.namespace === "snippets"
- ) {
- if (data.id === "root") {
- return (
- <RootSnippetsCollectionMenu
- setPermissionsCollectionId={setPermissionsCollectionId}
- />
- );
- } else {
- return (
- <PLUGIN_SNIPPET_FOLDERS.CollectionMenu
- collection={data}
- onEditDetails={setEditingCollection}
- onChangePermissions={setPermissionsCollectionId}
- />
- );
- }
- }
-
- return null;
- },
- },
- ],
- [setIsPublishTableModalOpen, isRemoteSyncReadOnly],
- );
-
- const getRowHref = useCallback(
- (row: { original: TreeItem }) => getItemHref(row.original),
- [getItemHref],
- );
-
- const treeTableInstance = useTreeTableInstance({
- data: combinedTree,
- columns: libraryColumnDef,
- getSubRows: (node) => node.children,
- getNodeId: (node) => node.id,
- globalFilter: searchQuery,
- onGlobalFilterChange: setSearchQuery,
- isFilterable: (node) =>
- node.model !== "collection" && node.model !== "empty-state",
- defaultExpanded: effectiveExpandedState,
- });
-
- let emptyMessage = null;
- if (!libraryHasContent) {
- emptyMessage = t`No tables, metrics, or snippets yet`;
- } else if (searchQuery) {
- emptyMessage = t`No results for "${searchQuery}"`;
- }
-
return (
<>
<SectionLayout>
@@ -384,6 +97,8 @@ function LibraryPageContent() {
<CreateMenu
metricCollectionId={writableMetricCollection?.id}
canWriteToMetricCollection={!!writableMetricCollection}
+ dataCollectionId={tableCollection?.id}
+ canWriteToDataCollection={!!tableCollection?.can_write}
/>
</Flex>
<Card withBorder p={0}>
@@ -406,7 +121,8 @@ function LibraryPageContent() {
}
// Navigation for leaf nodes is handled by the link
}}
- getRowHref={getRowHref}
+ getRowHref={getTreeRowHref}
+ isChildrenLoading={isChildrenLoading}
/>
)}
</Card>
@@ -414,23 +130,10 @@ function LibraryPageContent() {
)}
</Stack>
</SectionLayout>
- {editingCollection && (
- <PLUGIN_SNIPPET_FOLDERS.CollectionFormModal
- collection={editingCollection}
- onClose={() => setEditingCollection(null)}
- onSaved={() => setEditingCollection(null)}
- />
- )}
- {permissionsCollectionId !== null && (
- <PLUGIN_SNIPPET_FOLDERS.CollectionPermissionsModal
- collectionId={permissionsCollectionId}
- onClose={() => setPermissionsCollectionId(null)}
- />
- )}
<PublishTableModal
- opened={isPublishTableModalOpen}
- onClose={() => setIsPublishTableModalOpen(false)}
- onPublished={() => setIsPublishTableModalOpen(false)}
+ opened={showPublishTableModal}
+ onClose={closePublishTableModal}
+ onPublished={closePublishTableModal}
/>
</>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/ActionCell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/ActionCell.tsx
new file mode 100644
index 00000000000..5d0fb46ad01
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/ActionCell.tsx
@@ -0,0 +1,63 @@
+import { CollectionRowMenu } from "metabase/collections/components/CollectionRowMenu";
+import type { TreeItem } from "metabase/data-studio/common/types";
+import {
+ isCollectionData,
+ isEmptyStateData,
+ isTableData,
+} from "metabase/data-studio/common/utils";
+import { PLUGIN_LIBRARY } from "metabase/plugins";
+import { TableMoreMenu } from "metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu";
+import type { CollectionId } from "metabase-types/api";
+
+import { LibraryCollectionRowMenu } from "./LibraryCollectionRowMenu";
+import { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";
+
+type ActionCellProps = {
+ treeItem: TreeItem;
+ refreshTableCollections: (collectionIds: CollectionId[]) => void;
+ refreshMetricCollections: (collectionIds: CollectionId[]) => void;
+};
+
+export function ActionCell(props: ActionCellProps) {
+ const { treeItem, refreshTableCollections, refreshMetricCollections } = props;
+ const { data, children } = treeItem;
+
+ if (isEmptyStateData(data)) {
+ return null;
+ }
+
+ if (isTableData(data)) {
+ return <TableMoreMenu table={data} onMoved={refreshTableCollections} />;
+ }
+
+ if (!isCollectionData(data) || data.model !== "collection") {
+ return null;
+ }
+
+ const isSnippetCollection = data.namespace === "snippets";
+
+ if (isSnippetCollection && data.id === "root") {
+ return <RootSnippetsCollectionMenu collectionId={data.id} />;
+ }
+
+ if (isSnippetCollection) {
+ return <CollectionRowMenu collection={data} />;
+ }
+
+ const isLibraryCollection =
+ PLUGIN_LIBRARY.isLibrarySubCollectionType(data.type) &&
+ !data.is_library_root;
+
+ if (isLibraryCollection) {
+ return (
+ <LibraryCollectionRowMenu
+ childCount={children?.length ?? 0}
+ collection={data}
+ refreshMetricCollections={refreshMetricCollections}
+ refreshTableCollections={refreshTableCollections}
+ />
+ );
+ }
+
+ return null;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/CreateMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.tsx
similarity index 56%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/CreateMenu.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.tsx
index 642cb771ecb..fbf0643b047 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/CreateMenu.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useDisclosure } from "@mantine/hooks";
import { push } from "react-router-redux";
import { t } from "ttag";
@@ -6,6 +6,7 @@ import { ForwardRefLink } from "metabase/common/components/Link";
import { trackMetricCreateStarted } from "metabase/data-studio/analytics";
import { PLUGIN_SNIPPET_FOLDERS } from "metabase/plugins";
import { useDispatch, useSelector } from "metabase/redux";
+import { setOpenModalWithProps } from "metabase/redux/ui";
import {
canUserCreateNativeQueries,
canUserCreateQueries,
@@ -13,20 +14,26 @@ import {
import { Button, FixedSizeIcon, Icon, Menu } from "metabase/ui";
import * as Urls from "metabase/urls";
import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
-import type { CollectionId } from "metabase-types/api";
+import type { CollectionId, CollectionNamespace } from "metabase-types/api";
import { PublishTableModal } from "./PublishTableModal";
export const CreateMenu = ({
metricCollectionId,
canWriteToMetricCollection,
+ dataCollectionId,
+ canWriteToDataCollection,
}: {
metricCollectionId?: CollectionId;
canWriteToMetricCollection?: boolean;
+ dataCollectionId?: CollectionId;
+ canWriteToDataCollection?: boolean;
}) => {
const dispatch = useDispatch();
- const [modal, setModal] = useState<"snippet-folder" | "publish-table">();
- const closeModal = () => setModal(undefined);
+ const [
+ showPublishTableModal,
+ { close: closePublishTableModal, open: openPublishTableModal },
+ ] = useDisclosure(false);
const hasNativeWrite = useSelector(canUserCreateNativeQueries);
const hasDataAccess = useSelector(canUserCreateQueries);
@@ -39,11 +46,34 @@ export const CreateMenu = ({
const canCreateMetric =
hasDataAccess && metricCollectionId && canWriteToMetricCollection;
+ const canCreateCollection =
+ (dataCollectionId && canWriteToDataCollection) ||
+ (metricCollectionId && canWriteToMetricCollection) ||
+ (hasNativeWrite && PLUGIN_SNIPPET_FOLDERS.isEnabled);
+
+ const collectionNamespaces: CollectionNamespace[] = [];
+
+ if (
+ (dataCollectionId && canWriteToDataCollection) ||
+ (metricCollectionId && canWriteToMetricCollection)
+ ) {
+ collectionNamespaces.push(null);
+ }
+
+ if (hasNativeWrite && PLUGIN_SNIPPET_FOLDERS.isEnabled) {
+ collectionNamespaces.push("snippets");
+ }
+
+ const initialCollectionId =
+ (dataCollectionId && canWriteToDataCollection && dataCollectionId) ||
+ (metricCollectionId && canWriteToMetricCollection && metricCollectionId) ||
+ null;
+
const menuItems = [
<Menu.Item
key="publish-table"
leftSection={<FixedSizeIcon name="publish" />}
- onClick={() => setModal("publish-table")}
+ onClick={openPublishTableModal}
>
{t`Published table`}
</Menu.Item>,
@@ -71,13 +101,26 @@ export const CreateMenu = ({
{t`Snippet`}
</Menu.Item>
),
- hasNativeWrite && PLUGIN_SNIPPET_FOLDERS.isEnabled && (
+ canCreateCollection && (
<Menu.Item
- key="snippet-folder"
+ key="collection"
leftSection={<FixedSizeIcon name="folder" />}
- onClick={() => setModal("snippet-folder")}
+ onClick={() =>
+ dispatch(
+ setOpenModalWithProps({
+ id: "collection",
+ props: {
+ initialCollectionId,
+ namespaces: collectionNamespaces,
+ pickerOptions: LIBRARY_COLLECTION_PICKER_OPTIONS,
+ showAuthorityLevelPicker: false,
+ inDataStudio: true,
+ },
+ }),
+ )
+ }
>
- {t`Snippet folder`}
+ {t`Collection`}
</Menu.Item>
),
].filter(Boolean);
@@ -94,20 +137,21 @@ export const CreateMenu = ({
</Menu.Target>
<Menu.Dropdown>{menuItems}</Menu.Dropdown>
</Menu>
- <PLUGIN_SNIPPET_FOLDERS.CollectionFormModal
- opened={modal === "snippet-folder"}
- collection={{
- name: "",
- description: null,
- }}
- onClose={closeModal}
- onSaved={closeModal}
- />
<PublishTableModal
- opened={modal === "publish-table"}
- onClose={closeModal}
+ opened={showPublishTableModal}
+ onClose={closePublishTableModal}
onPublished={(table) => dispatch(push(Urls.dataStudioTable(table.id)))}
/>
</>
);
};
+
+const LIBRARY_COLLECTION_PICKER_OPTIONS = {
+ hasLibrary: true,
+ hasRootCollection: false,
+ hasPersonalCollections: false,
+ hasRecents: false,
+ hasSearch: false,
+ hasConfirmButtons: true,
+ canCreateCollections: false,
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/CreateMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.unit.spec.tsx
similarity index 51%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/CreateMenu.unit.spec.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.unit.spec.tsx
index 9003d69d22d..24cf92d6ec0 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/CreateMenu.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.unit.spec.tsx
@@ -15,6 +15,8 @@ import { CreateMenu } from "./CreateMenu";
interface SetupOptions {
user?: Partial<User>;
+ dataCollectionId?: number;
+ canWriteToDataCollection?: boolean;
canWriteToMetricCollection?: boolean;
remoteSyncType?: EnterpriseSettings["remote-sync-type"];
}
@@ -29,12 +31,15 @@ const fullPermissionsUser: Partial<User> = {
const setup = ({
user,
+ dataCollectionId = 2,
+ canWriteToDataCollection = true,
canWriteToMetricCollection = true,
remoteSyncType,
}: SetupOptions = {}) => {
const state = createMockState({
settings: mockSettings({
"token-features": createMockTokenFeatures({
+ library: true,
snippet_collections: true,
}),
"remote-sync-type": remoteSyncType,
@@ -43,15 +48,19 @@ const setup = ({
currentUser: createMockUser(user),
});
setupEnterprisePlugins();
- return renderWithProviders(
+ const utils = renderWithProviders(
<CreateMenu
metricCollectionId={1}
+ dataCollectionId={dataCollectionId}
+ canWriteToDataCollection={canWriteToDataCollection}
canWriteToMetricCollection={canWriteToMetricCollection}
/>,
{
storeInitialState: state,
},
);
+
+ return utils;
};
describe("CreateMenu", () => {
@@ -62,17 +71,17 @@ describe("CreateMenu", () => {
expect(
screen.getAllByRole("menuitem").map((item) => item.textContent),
- ).toEqual(["Published table", "Metric", "Snippet", "Snippet folder"]);
+ ).toEqual(["Published table", "Metric", "Snippet", "Collection"]);
});
- it("renders publish option for data analysts", async () => {
+ it("renders publish and collection options for data analysts", async () => {
setup({ user: { is_data_analyst: true } });
await userEvent.click(screen.getByRole("button", { name: /New/ }));
expect(
screen.getAllByRole("menuitem").map((item) => item.textContent),
- ).toEqual(["Published table"]);
+ ).toEqual(["Published table", "Collection"]);
});
it("renders publish and metric options if user only has query builder access", async () => {
@@ -82,7 +91,7 @@ describe("CreateMenu", () => {
expect(
screen.getAllByRole("menuitem").map((item) => item.textContent),
- ).toEqual(["Published table", "Metric"]);
+ ).toEqual(["Published table", "Metric", "Collection"]);
});
it("does not render Metric option when canWriteToMetricCollection is false", async () => {
@@ -101,7 +110,80 @@ describe("CreateMenu", () => {
expect(
screen.getAllByRole("menuitem").map((item) => item.textContent),
- ).toEqual(["Published table", "Snippet", "Snippet folder"]);
+ ).toEqual(["Published table", "Snippet", "Collection"]);
+ });
+
+ it("renders Collection option when only Data collection is writable", async () => {
+ setup({
+ user: { is_data_analyst: true },
+ canWriteToDataCollection: true,
+ canWriteToMetricCollection: false,
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: /New/ }));
+
+ expect(
+ screen.getAllByRole("menuitem").map((item) => item.textContent),
+ ).toEqual(["Published table", "Collection"]);
+ });
+
+ it("does not render Collection option without writable Library collections or native write", async () => {
+ setup({
+ user: {},
+ canWriteToDataCollection: false,
+ canWriteToMetricCollection: false,
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: /New/ }));
+
+ expect(
+ screen.getAllByRole("menuitem").map((item) => item.textContent),
+ ).toEqual(["Published table"]);
+ });
+
+ it("opens the collection modal with Library and snippets picker options", async () => {
+ const { store } = setup({
+ user: fullPermissionsUser,
+ dataCollectionId: 42,
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: /New/ }));
+ await userEvent.click(screen.getByRole("menuitem", { name: /Collection/ }));
+
+ expect(store.getState().modal).toEqual({
+ id: "collection",
+ props: {
+ inDataStudio: true,
+ initialCollectionId: 42,
+ namespaces: [null, "snippets"],
+ pickerOptions: {
+ hasLibrary: true,
+ hasRootCollection: false,
+ hasPersonalCollections: false,
+ hasRecents: false,
+ hasSearch: false,
+ hasConfirmButtons: true,
+ canCreateCollections: false,
+ },
+ showAuthorityLevelPicker: false,
+ },
+ });
+ });
+
+ it("opens the collection modal scoped to snippets when only native write is available", async () => {
+ const { store } = setup({
+ user: { permissions: { can_create_native_queries: true } },
+ canWriteToDataCollection: false,
+ canWriteToMetricCollection: false,
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: /New/ }));
+ await userEvent.click(screen.getByRole("menuitem", { name: /Collection/ }));
+
+ expect(store.getState().modal.props).toMatchObject({
+ initialCollectionId: null,
+ namespaces: ["snippets"],
+ });
});
it("renders nothing if remote sync is set to read-only", () => {
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/EmptyStateAction.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/EmptyStateAction.tsx
new file mode 100644
index 00000000000..f0c20842a86
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/EmptyStateAction.tsx
@@ -0,0 +1,44 @@
+import { ForwardRefLink } from "metabase/common/components/Link";
+import type { EmptyStateData } from "metabase/data-studio/common/types";
+import { Anchor } from "metabase/ui";
+
+interface EmptyStateActionProps {
+ data: EmptyStateData;
+ onPublishTableClick: () => void;
+}
+
+export function EmptyStateAction({
+ data,
+ onPublishTableClick,
+}: EmptyStateActionProps) {
+ if (data.sectionType === "data") {
+ return (
+ <Anchor
+ component="button"
+ type="button"
+ fz="inherit"
+ onClick={(e) => {
+ e.stopPropagation();
+ onPublishTableClick();
+ }}
+ >
+ {data.actionLabel}
+ </Anchor>
+ );
+ }
+
+ if (data.actionUrl) {
+ return (
+ <Anchor
+ component={ForwardRefLink}
+ to={data.actionUrl}
+ fz="inherit"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {data.actionLabel}
+ </Anchor>
+ );
+ }
+
+ return null;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx
new file mode 100644
index 00000000000..8391e80bdae
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx
@@ -0,0 +1,78 @@
+import { useCallback } from "react";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { CollectionRowMenu } from "metabase/collections/components/CollectionRowMenu";
+import type { Collection, CollectionId } from "metabase-types/api";
+
+type LibraryCollectionRowMenuProps = {
+ childCount: number;
+ collection: Collection;
+ refreshMetricCollections: (collectionIds: CollectionId[]) => void;
+ refreshTableCollections: (collectionIds: CollectionId[]) => void;
+};
+
+export function LibraryCollectionRowMenu(props: LibraryCollectionRowMenuProps) {
+ const {
+ childCount,
+ collection,
+ refreshMetricCollections,
+ refreshTableCollections,
+ } = props;
+ const isLibraryDataCollection =
+ collection.type === "library-data" && !collection.is_library_root;
+ const refreshCollections = useCallback(
+ (collectionIds: CollectionId[]) => {
+ if (collection.type === "library-metrics") {
+ refreshMetricCollections(collectionIds);
+ }
+
+ if (collection.type === "library-data") {
+ refreshTableCollections(collectionIds);
+ }
+ },
+ [refreshMetricCollections, refreshTableCollections, collection.type],
+ );
+
+ const onArchiveSuccess = useCallback(() => {
+ const parentId = getParentCollectionId(collection);
+
+ if (parentId == null) {
+ return;
+ }
+
+ refreshCollections([parentId]);
+ }, [collection, refreshCollections]);
+
+ return (
+ <CollectionRowMenu
+ collection={collection}
+ onSave={(details) => {
+ refreshCollections(getAffectedCollectionIds(details));
+ }}
+ customArchiveMessage={
+ isLibraryDataCollection && childCount > 0
+ ? t`Archiving this collection will also unpublish the tables inside it and archive any other child items.`
+ : undefined
+ }
+ onArchiveSuccess={onArchiveSuccess}
+ />
+ );
+}
+
+const getAffectedCollectionIds = ({
+ previousParentId,
+ newParentId,
+}: {
+ previousParentId: CollectionId | null;
+ newParentId: CollectionId | null;
+}) => _.uniq([previousParentId, newParentId]).filter(_.isNumber);
+
+const getParentCollectionId = (collection: Collection) => {
+ const parentId =
+ "collection_id" in collection
+ ? collection.collection_id
+ : collection.parent_id;
+
+ return typeof parentId === "number" ? parentId : null;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx
new file mode 100644
index 00000000000..18b82a364a1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx
@@ -0,0 +1,124 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import {
+ setupCollectionByIdEndpoint,
+ setupUpdateCollectionEndpoint,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { createMockEntitiesState } from "__support__/store";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import {
+ createMockCollection,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { LibraryCollectionRowMenu } from "./LibraryCollectionRowMenu";
+
+function setup({
+ collection = createMockCollection({
+ id: 1,
+ name: "Library Data Collection",
+ type: "library-data",
+ parent_id: 22,
+ }),
+ childCount = 0,
+}: Partial<Parameters<typeof LibraryCollectionRowMenu>[0]> = {}) {
+ const refreshMetricCollections = jest.fn();
+ const refreshTableCollections = jest.fn();
+ const parentCollection = createMockCollection({
+ id: 22,
+ name: "Data",
+ type: "library-data",
+ });
+
+ setupEnterpriseOnlyPlugin("library");
+ setupEnterpriseOnlyPlugin("remote_sync");
+ setupUpdateCollectionEndpoint(collection);
+ setupCollectionByIdEndpoint({ collections: [parentCollection] });
+
+ renderWithProviders(
+ <LibraryCollectionRowMenu
+ childCount={childCount}
+ collection={collection}
+ refreshMetricCollections={refreshMetricCollections}
+ refreshTableCollections={refreshTableCollections}
+ />,
+ {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures({
+ library: true,
+ remote_sync: true,
+ }),
+ }),
+ entities: createMockEntitiesState({ collections: [parentCollection] }),
+ }),
+ },
+ );
+
+ return { refreshMetricCollections, refreshTableCollections };
+}
+
+describe("LibraryCollectionRowMenu", () => {
+ it("refreshes table collections after saving a Library Data collection", async () => {
+ const { refreshMetricCollections, refreshTableCollections } = setup();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Collection options" }),
+ );
+ await userEvent.click(
+ screen.getByRole("menuitem", { name: /Edit collection details/ }),
+ );
+ await userEvent.type(screen.getByLabelText("Name"), " Updated");
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => {
+ expect(refreshTableCollections).toHaveBeenCalledWith([22]);
+ });
+ expect(refreshMetricCollections).not.toHaveBeenCalled();
+ });
+
+ it("refreshes metric collections after saving a Library Metrics collection", async () => {
+ const { refreshMetricCollections, refreshTableCollections } = setup({
+ collection: createMockCollection({
+ id: 2,
+ name: "Library Metrics Collection",
+ type: "library-metrics",
+ parent_id: 22,
+ }),
+ });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Collection options" }),
+ );
+ await userEvent.click(
+ screen.getByRole("menuitem", { name: /Edit collection details/ }),
+ );
+ await userEvent.type(screen.getByLabelText("Name"), " Updated");
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => {
+ expect(refreshMetricCollections).toHaveBeenCalledWith([22]);
+ });
+ expect(refreshTableCollections).not.toHaveBeenCalled();
+ });
+
+ it("shows a table unpublish warning when archiving a non-empty Library Data collection", async () => {
+ setup({ childCount: 1 });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Collection options" }),
+ );
+ await userEvent.click(screen.getByRole("menuitem", { name: /Archive/ }));
+
+ expect(
+ screen.getByText(
+ "Archiving this collection will also unpublish the tables inside it and archive any other child items.",
+ ),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/PublishTableModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/PublishTableModal.tsx
similarity index 96%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/PublishTableModal.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/PublishTableModal.tsx
index 3e32e6620c5..d2f60d46923 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/PublishTableModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/PublishTableModal.tsx
@@ -7,7 +7,7 @@ import {
type OmniPickerTableItem,
} from "metabase/common/components/Pickers";
-import { PublishTablesModal } from "../components/PublishTablesModal";
+import { PublishTablesModal } from "../../components/PublishTablesModal";
interface PublishTableModalProps {
opened: boolean;
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/PublishTableModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/PublishTableModal.unit.spec.tsx
similarity index 65%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/PublishTableModal.unit.spec.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/PublishTableModal.unit.spec.tsx
index 69e548758e2..a3866d7bbac 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/PublishTableModal.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/PublishTableModal.unit.spec.tsx
@@ -1,15 +1,25 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
+ setupCollectionByIdEndpoint,
+ setupCollectionItemsEndpoint,
+ setupLibraryEndpoints,
setupPublishTablesEndpoint,
setupTableSelectionInfoEndpoint,
} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import type { OmniPickerItem } from "metabase/common/components/Pickers";
+import { createMockState } from "metabase/redux/store/mocks";
import type { BulkTableSelectionInfo } from "metabase-types/api";
import {
createMockBulkTableInfo,
createMockBulkTableSelectionInfo,
+ createMockCollection,
+ createMockCollectionItem,
+ createMockTokenFeatures,
} from "metabase-types/api/mocks";
import { PublishTableModal } from "./PublishTableModal";
@@ -59,6 +69,35 @@ function setup({
}: SetupOpts = {}) {
const onClose = jest.fn();
const onPublished = jest.fn();
+ const dataCollection = createMockCollection({
+ id: 10,
+ name: "Data",
+ type: "library-data",
+ });
+ const state = createMockState({
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures({ library: true }),
+ }),
+ });
+
+ setupEnterpriseOnlyPlugin("library");
+ setupLibraryEndpoints(true);
+ setupCollectionItemsEndpoint({
+ collection: { id: 6464 },
+ collectionItems: [
+ createMockCollectionItem({
+ id: dataCollection.id as number,
+ name: dataCollection.name,
+ model: "collection",
+ type: dataCollection.type,
+ can_write: true,
+ location: "/6464/",
+ here: ["table", "collection"],
+ below: ["table", "collection"],
+ }),
+ ],
+ });
+ setupCollectionByIdEndpoint({ collections: [dataCollection] });
setupTableSelectionInfoEndpoint(selectionInfo);
setupPublishTablesEndpoint();
@@ -69,9 +108,10 @@ function setup({
onClose={onClose}
onPublished={onPublished}
/>,
+ { storeInitialState: state },
);
- return { onClose, onPublished };
+ return { dataCollection, onClose, onPublished };
}
describe("PublishTableModal", () => {
@@ -81,11 +121,20 @@ describe("PublishTableModal", () => {
});
it("should show the publish confirmation modal after selecting a table and call onClose and onPublished on publish", async () => {
- const { onClose, onPublished } = setup();
+ const { dataCollection, onClose, onPublished } = setup();
await userEvent.click(screen.getByText("Select Orders"));
expect(await screen.findByText("Publish Orders?")).toBeInTheDocument();
+ expect(await screen.findByText("Publish to")).toBeInTheDocument();
+ expect(await screen.findByText("Data")).toBeInTheDocument();
await userEvent.click(screen.getByText("Publish this table"));
await waitFor(() => expect(onPublished).toHaveBeenCalled());
+ const request = fetchMock.callHistory.lastCall(
+ "path:/api/ee/data-studio/table/publish-tables",
+ )?.request;
+ expect(await request?.json()).toEqual({
+ table_ids: [1],
+ collection_id: dataCollection.id,
+ });
expect(onClose).toHaveBeenCalled();
});
@@ -112,8 +161,8 @@ describe("PublishTableModal", () => {
expect(
await screen.findByText("Publish Orders and the tables it depends on?"),
).toBeInTheDocument();
- expect(screen.getByText("Products")).toBeInTheDocument();
- expect(screen.getByText("People")).toBeInTheDocument();
+ expect(await screen.findByText("Products")).toBeInTheDocument();
+ expect(await screen.findByText("People")).toBeInTheDocument();
});
it("should return to picker when publish modal is closed", async () => {
@@ -121,7 +170,7 @@ describe("PublishTableModal", () => {
await userEvent.click(screen.getByText("Select Orders"));
expect(await screen.findByText("Publish Orders?")).toBeInTheDocument();
- await userEvent.click(screen.getByText("Cancel"));
+ await userEvent.click(await screen.findByText("Cancel"));
expect(screen.getByTestId("entity-picker-modal")).toBeInTheDocument();
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/RootSnippetsCollectionMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/RootSnippetsCollectionMenu.tsx
similarity index 72%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/RootSnippetsCollectionMenu.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/RootSnippetsCollectionMenu.tsx
index a5786244318..c68894d69f6 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/RootSnippetsCollectionMenu.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/RootSnippetsCollectionMenu.tsx
@@ -1,3 +1,4 @@
+import { useDisclosure } from "@mantine/hooks";
import { Link } from "react-router";
import { t } from "ttag";
@@ -6,16 +7,21 @@ import { getUserIsAdmin } from "metabase/selectors/user";
import { ActionIcon, FixedSizeIcon, Menu, Tooltip } from "metabase/ui";
import { dataStudioArchivedSnippets } from "metabase/urls";
import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
+import { SnippetCollectionPermissionsModal } from "metabase-enterprise/snippets/components/SnippetCollectionPermissionsModal";
import type { CollectionId } from "metabase-types/api";
+type RootSnippetsCollectionMenu = {
+ collectionId: CollectionId;
+};
+
export const RootSnippetsCollectionMenu = ({
- setPermissionsCollectionId,
-}: {
- setPermissionsCollectionId: (id: CollectionId) => void;
-}) => {
+ collectionId,
+}: RootSnippetsCollectionMenu) => {
const isAdmin = useSelector(getUserIsAdmin);
const remoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
const isReadOnly = remoteSyncReadOnly || !isAdmin;
+ const [showPermissionsModal, { toggle: togglePermissionsModal }] =
+ useDisclosure(false);
const optionsLabel = t`Snippet collection options`;
@@ -38,7 +44,7 @@ export const RootSnippetsCollectionMenu = ({
leftSection={<FixedSizeIcon name="lock" />}
onClick={(e) => {
e.stopPropagation();
- setPermissionsCollectionId("root");
+ togglePermissionsModal();
}}
>
{t`Change permissions`}
@@ -52,6 +58,12 @@ export const RootSnippetsCollectionMenu = ({
{t`View archived snippets`}
</Menu.Item>
</Menu.Dropdown>
+ {showPermissionsModal && (
+ <SnippetCollectionPermissionsModal
+ collectionId={collectionId}
+ onClose={togglePermissionsModal}
+ />
+ )}
</Menu>
);
};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/RootSnippetsCollectionMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/RootSnippetsCollectionMenu.unit.spec.tsx
similarity index 75%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/RootSnippetsCollectionMenu.unit.spec.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/RootSnippetsCollectionMenu.unit.spec.tsx
index 1e77f043da9..de6e821f2ed 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/RootSnippetsCollectionMenu.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/RootSnippetsCollectionMenu.unit.spec.tsx
@@ -1,12 +1,22 @@
import userEvent from "@testing-library/user-event";
import { Route } from "react-router";
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import {
+ setupCollectionPermissionsGraphEndpoint,
+ setupCollectionsEndpoints,
+ setupGroupsEndpoint,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, within } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks/state";
import { dataStudioArchivedSnippets } from "metabase/urls";
import type { EnterpriseSettings } from "metabase-types/api";
-import { createMockUser } from "metabase-types/api/mocks";
+import {
+ createMockCollection,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
import { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";
@@ -15,24 +25,28 @@ interface SetupOptions {
remoteSyncType?: EnterpriseSettings["remote-sync-type"];
}
-const setPermissionsCollectionId = jest.fn();
+const collection = createMockCollection({ id: "root", name: "SQL Snippets" });
const setup = ({ isSuperuser = true, remoteSyncType }: SetupOptions = {}) => {
const state = createMockState({
settings: mockSettings({
"remote-sync-type": remoteSyncType,
"remote-sync-enabled": !!remoteSyncType,
+ "token-features": createMockTokenFeatures({ snippet_collections: true }),
}),
currentUser: createMockUser({ is_superuser: isSuperuser }),
});
+ setupEnterpriseOnlyPlugin("snippets");
+ setupCollectionsEndpoints({ collections: [collection] });
+ setupGroupsEndpoint([]);
+ setupCollectionPermissionsGraphEndpoint({ revision: 1, groups: {} });
+
return renderWithProviders(
<>
<Route
path="/"
component={() => (
- <RootSnippetsCollectionMenu
- setPermissionsCollectionId={setPermissionsCollectionId}
- />
+ <RootSnippetsCollectionMenu collectionId={collection.id} />
)}
/>
<Route
@@ -92,7 +106,7 @@ describe("RootSnippetsCollectionMenu", () => {
).toBeInTheDocument();
});
- it("calls setPermissionsCollectionId on click", async () => {
+ it("shows permissions modal on click", async () => {
setup();
await userEvent.click(
screen.getByRole("button", { name: "Snippet collection options" }),
@@ -100,7 +114,11 @@ describe("RootSnippetsCollectionMenu", () => {
await userEvent.click(
screen.getByRole("menuitem", { name: /Change permissions/ }),
);
- expect(setPermissionsCollectionId).toHaveBeenCalledWith("root");
+ expect(
+ await within(screen.getByRole("dialog")).findByRole("heading", {
+ name: /Permissions for SQL Snippets/,
+ }),
+ ).toBeInTheDocument();
});
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks.ts
deleted file mode 100644
index 827babe49a2..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { useEffect, useMemo } from "react";
-import { t } from "ttag";
-import _ from "underscore";
-
-import { skipToken, useListCollectionItemsQuery } from "metabase/api";
-import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
-import type {
- LibrarySectionType,
- TreeItem,
-} from "metabase/data-studio/common/types";
-import { createEmptyStateItem } from "metabase/data-studio/common/utils";
-import { useGetIcon } from "metabase/hooks/use-icon";
-import { useMetadataToasts } from "metabase/metadata/hooks";
-import { useSelector } from "metabase/redux";
-import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
-import type { Collection, CollectionId } from "metabase-types/api";
-
-export const useBuildTreeForCollection = (
- collection: Collection | undefined,
- sectionType: LibrarySectionType,
- metricCollectionId?: CollectionId,
-): {
- isLoading: boolean;
- tree: TreeItem[];
- error?: unknown;
-} => {
- const getIcon = useGetIcon();
- const {
- data: items,
- isLoading,
- error,
- } = useListCollectionItemsQuery(
- collection ? { id: collection.id, models: ["metric", "table"] } : skipToken,
- );
- const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
-
- return useMemo(() => {
- if (isLoading || !items || !collection) {
- return {
- isLoading,
- tree: [],
- error,
- };
- }
-
- const hasItems = items.data.length > 0;
- const children: TreeItem[] = hasItems
- ? items.data.map((item) => ({
- name: item.name,
- updatedAt: item["last-edit-info"]?.timestamp,
- icon: getIcon({ model: item.model }).name,
- data: item,
- id: `${item.model}:${item.id}`,
- model: item.model,
- }))
- : [
- createEmptyStateItem(
- sectionType,
- metricCollectionId,
- isRemoteSyncReadOnly,
- ),
- ];
-
- return {
- isLoading,
- error,
- tree: [
- {
- name: collection.name,
- id: `collection:${collection.id}`,
- icon: getIcon({ ...collection, model: "collection" }).name,
- data: { ...collection, model: "collection" },
- model: "collection",
- children,
- },
- ],
- };
- }, [
- isLoading,
- items,
- collection,
- error,
- sectionType,
- metricCollectionId,
- isRemoteSyncReadOnly,
- getIcon,
- ]);
-};
-
-export const useErrorHandling = (_error: unknown) => {
- const error = useDebouncedValue(_error, 1000);
- const { sendErrorToast } = useMetadataToasts();
-
- useEffect(() => {
- if (_.isObject(error) && typeof error?.data?.message === "string") {
- sendErrorToast(
- t`Data couldn't be fetched properly: ${error.data.message}`,
- );
- }
- }, [error, sendErrorToast]);
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/index.ts
new file mode 100644
index 00000000000..8d36a866d5d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/index.ts
@@ -0,0 +1,2 @@
+export { useLibraryCollections } from "./useLibraryCollections";
+export { useLibraryTreeTableInstance } from "./useLibraryTreeTableInstance";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useErrorHandling.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useErrorHandling.ts
new file mode 100644
index 00000000000..ce0031acf08
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useErrorHandling.ts
@@ -0,0 +1,19 @@
+import { useEffect } from "react";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { getErrorMessage } from "metabase/api/utils";
+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+
+export const useErrorHandling = (_error: unknown) => {
+ const error = useDebouncedValue(_error, 1000);
+ const { sendErrorToast } = useMetadataToasts();
+
+ useEffect(() => {
+ if (_.isObject(error)) {
+ const extractedMessage = getErrorMessage(error, t`Server error`);
+ sendErrorToast(t`Data couldn't be fetched properly: ${extractedMessage}`);
+ }
+ }, [error, sendErrorToast]);
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollectionTree.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollectionTree.ts
new file mode 100644
index 00000000000..cf5b4b30ee9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollectionTree.ts
@@ -0,0 +1,236 @@
+import type { Row } from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+
+import {
+ collectionApi,
+ skipToken,
+ useListCollectionItemsQuery,
+} from "metabase/api";
+import type {
+ LibrarySectionType,
+ TreeItem,
+} from "metabase/data-studio/common/types";
+import {
+ createEmptyStateItem,
+ isEmptyStateData,
+} from "metabase/data-studio/common/utils";
+import { useGetIcon } from "metabase/hooks/use-icon";
+import { useDispatch, useSelector } from "metabase/redux";
+import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
+import type {
+ Collection,
+ CollectionId,
+ CollectionItem,
+} from "metabase-types/api";
+
+export function useLibraryCollectionTree(
+ collection: Collection | undefined,
+ sectionType: LibrarySectionType,
+ metricCollectionId?: CollectionId,
+) {
+ const dispatch = useDispatch();
+ const getIcon = useGetIcon();
+
+ // 1. Fetch top-level items
+ const {
+ data: topLevelItems,
+ isLoading,
+ error,
+ } = useListCollectionItemsQuery(
+ collection
+ ? {
+ id: collection.id,
+ models: ["metric", "table", "collection"],
+ archived: false,
+ }
+ : skipToken,
+ );
+
+ const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
+
+ // 2. Lazy-loaded subcollection items
+ const [loadedCollections, setLoadedCollections] = useState<
+ Map<CollectionId, CollectionItem[]>
+ >(new Map());
+ const loadingIds = useRef(new Set<string>());
+
+ useEffect(() => {
+ setLoadedCollections(new Map());
+ loadingIds.current = new Set();
+ }, [collection]);
+
+ const loadCollectionItems = useCallback(
+ async (collectionId: CollectionId) => {
+ const key = String(collectionId);
+ if (loadingIds.current.has(key)) {
+ return;
+ }
+ loadingIds.current.add(key);
+
+ const result = await dispatch(
+ collectionApi.endpoints.listCollectionItems.initiate(
+ {
+ id: collectionId,
+ models: ["metric", "table", "collection"],
+ archived: false,
+ },
+ { forceRefetch: true },
+ ),
+ );
+ const items = (result.data?.data ?? []).filter((item) => !item.archived);
+ setLoadedCollections((prev) => new Map([...prev, [collectionId, items]]));
+ },
+ [dispatch],
+ );
+
+ const refreshCollections = useCallback(
+ async (collectionIds: CollectionId[]) => {
+ for (const id of collectionIds) {
+ const key = String(id);
+ loadingIds.current.delete(key);
+ }
+ await Promise.all(collectionIds.map(loadCollectionItems));
+ },
+ [loadCollectionItems],
+ );
+
+ // 3. Build tree
+ const tree = useMemo((): TreeItem[] => {
+ if (isLoading || !topLevelItems || !collection) {
+ return [];
+ }
+
+ const children = buildChildren(
+ topLevelItems.data,
+ loadedCollections,
+ getIcon,
+ );
+ const hasItems = children.length > 0;
+
+ return [
+ {
+ name: collection.name,
+ id: `collection:${collection.id}`,
+ icon: getIcon({ ...collection, model: "collection" }).name,
+ data: { ...collection, model: "collection" as const },
+ model: "collection",
+ children: hasItems
+ ? children
+ : [
+ createEmptyStateItem(
+ sectionType,
+ metricCollectionId,
+ isRemoteSyncReadOnly,
+ ),
+ ],
+ },
+ ];
+ }, [
+ isLoading,
+ topLevelItems,
+ collection,
+ loadedCollections,
+ getIcon,
+ sectionType,
+ metricCollectionId,
+ isRemoteSyncReadOnly,
+ ]);
+
+ // 4. Watch rows for expanded-but-empty collections → trigger fetch
+ const watchRows = useCallback(
+ (rows: Row<TreeItem>[]) => {
+ for (const row of rows) {
+ const { original } = row;
+ if (
+ row.getIsExpanded() &&
+ row.getCanExpand() &&
+ original.model === "collection" &&
+ original.children?.length === 0 &&
+ !isEmptyStateData(original.data) &&
+ "id" in original.data
+ ) {
+ loadCollectionItems(original.data.id as number);
+ }
+ }
+ },
+ [loadCollectionItems],
+ );
+
+ // 5. isChildrenLoading for the spinner
+ const isChildrenLoading = useCallback(
+ (row: Row<TreeItem>): boolean =>
+ row.getIsExpanded() &&
+ row.getCanExpand() &&
+ row.original.children?.length === 0,
+ [],
+ );
+
+ return {
+ tree,
+ isLoading,
+ error,
+ watchRows,
+ isChildrenLoading,
+ refreshCollections,
+ };
+}
+
+/** Build children for a collection from its fetched items. Subcollections
+ * that haven't been loaded yet get `children: []` (if they have content
+ * according to `here`/`below`) so they render as expandable rows that
+ * trigger a lazy load, or `undefined` if they're empty. */
+function buildChildren(
+ items: CollectionItem[],
+ loadedCollections: Map<CollectionId, CollectionItem[]>,
+ getIcon: ReturnType<typeof useGetIcon>,
+): TreeItem[] {
+ const visibleItems = items.filter((i) => !i.archived);
+ const collections = visibleItems.filter((i) => i.model === "collection");
+ const leafItems = visibleItems.filter((i) => i.model !== "collection");
+
+ return [
+ ...collections.map((col): TreeItem => {
+ const childItems = loadedCollections.get(col.id);
+ let children: TreeItem[] | undefined;
+
+ if (childItems !== undefined) {
+ const built = buildChildren(childItems, loadedCollections, getIcon);
+ children = built.length > 0 ? built : undefined;
+ } else if (hasContent(col)) {
+ children = [];
+ }
+
+ return {
+ name: col.name,
+ id: `collection:${col.id}`,
+ icon: "folder",
+ data: col,
+ model: "collection",
+ children,
+ childrenLoaded: childItems !== undefined,
+ };
+ }),
+ ...leafItems.map((leafItem) => buildItemNode(leafItem, getIcon)),
+ ];
+}
+
+function buildItemNode(
+ item: CollectionItem,
+ getIcon: ReturnType<typeof useGetIcon>,
+): TreeItem {
+ return {
+ name: item.name,
+ updatedAt: item["last-edit-info"]?.timestamp,
+ icon: getIcon({ model: item.model }).name,
+ data: item,
+ id: `${item.model}:${item.id}`,
+ model: item.model,
+ };
+}
+
+function hasContent(item: CollectionItem): boolean {
+ return (
+ (item.here != null && item.here.length > 0) ||
+ (item.below != null && item.below.length > 0)
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollections.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollections.ts
new file mode 100644
index 00000000000..2c41082a5b7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollections.ts
@@ -0,0 +1,29 @@
+import { useMemo } from "react";
+
+import { isLibraryCollection } from "metabase/collections/utils";
+import type { Collection } from "metabase-types/api";
+
+import { getAccessibleCollection } from "../utils";
+
+export const useLibraryCollections = (collections: Collection[]) => {
+ const libraryCollection = useMemo(
+ () => collections.find(isLibraryCollection),
+ [collections],
+ );
+
+ const tableCollection = useMemo(
+ () =>
+ libraryCollection &&
+ getAccessibleCollection(libraryCollection, "library-data"),
+ [libraryCollection],
+ );
+
+ const metricCollection = useMemo(
+ () =>
+ libraryCollection &&
+ getAccessibleCollection(libraryCollection, "library-metrics"),
+ [libraryCollection],
+ );
+
+ return { libraryCollection, tableCollection, metricCollection };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibrarySearch.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibrarySearch.ts
new file mode 100644
index 00000000000..ff1d1d9cce1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibrarySearch.ts
@@ -0,0 +1,139 @@
+import { useMemo } from "react";
+import { t } from "ttag";
+
+import { skipToken, useSearchQuery } from "metabase/api";
+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
+import type { TreeItem } from "metabase/data-studio/common/types";
+import { useGetIcon } from "metabase/hooks/use-icon";
+import type { CollectionId } from "metabase-types/api";
+
+const SEARCH_DEBOUNCE_MS = 300;
+
+export function useLibrarySearch(
+ searchQuery: string,
+ libraryCollectionId: CollectionId | undefined,
+ snippetTree: TreeItem[],
+) {
+ const debouncedQuery = useDebouncedValue(searchQuery, SEARCH_DEBOUNCE_MS);
+ const isActive = debouncedQuery.trim().length > 0;
+ const getIcon = useGetIcon();
+
+ const {
+ data: searchResponse,
+ isLoading,
+ isFetching,
+ error,
+ } = useSearchQuery(
+ isActive && libraryCollectionId != null
+ ? {
+ q: debouncedQuery,
+ collection: libraryCollectionId,
+ models: ["table", "metric"],
+ }
+ : skipToken,
+ );
+
+ const tree = useMemo((): TreeItem[] => {
+ if (!isActive) {
+ return [];
+ }
+
+ const sections: TreeItem[] = [];
+
+ if (searchResponse) {
+ const dataItems: TreeItem[] = [];
+ const metricItems: TreeItem[] = [];
+
+ for (const result of searchResponse.data) {
+ if (result.model !== "table" && result.model !== "metric") {
+ continue;
+ }
+
+ const item: TreeItem = {
+ id: `${result.model}:${result.id}`,
+ name: result.name,
+ icon: getIcon({ model: result.model }).name,
+ updatedAt: result.last_edited_at ?? result.updated_at,
+ model: result.model,
+ parentCollectionName: result.collection?.name,
+ data: {
+ id: Number(result.id),
+ model: result.model,
+ name: result.name,
+ description: result.description,
+ collection_id: result.collection_id ?? null,
+ archived: result.archived ?? false,
+ collection_position: result.collection_position,
+ "last-edit-info": result["last-edit-info"],
+ },
+ };
+
+ if (result.model === "table") {
+ dataItems.push(item);
+ } else if (result.model === "metric") {
+ metricItems.push(item);
+ }
+ }
+
+ if (dataItems.length > 0) {
+ sections.push({
+ id: "search-section:data",
+ name: t`Data`,
+ icon: "table",
+ model: "collection",
+ data: {
+ model: "collection",
+ name: t`Data`,
+ },
+ children: dataItems,
+ });
+ }
+
+ if (metricItems.length > 0) {
+ sections.push({
+ id: "search-section:metrics",
+ name: t`Metrics`,
+ icon: "metric",
+ model: "collection",
+ data: {
+ model: "collection",
+ name: t`Metrics`,
+ },
+ children: metricItems,
+ });
+ }
+ }
+
+ // Client-side filter snippets
+ const filteredSnippets = filterSnippetTree(snippetTree, debouncedQuery);
+ sections.push(...filteredSnippets);
+
+ return sections;
+ }, [isActive, searchResponse, snippetTree, debouncedQuery, getIcon]);
+
+ return {
+ tree,
+ isActive,
+ isLoading: isLoading || isFetching,
+ error,
+ };
+}
+
+function filterSnippetTree(nodes: TreeItem[], query: string): TreeItem[] {
+ const lowerQuery = query.toLowerCase();
+
+ return nodes.flatMap((node) => {
+ if (node.model === "snippet") {
+ return node.name.toLowerCase().includes(lowerQuery) ? [node] : [];
+ }
+
+ if (node.children) {
+ const filteredChildren = filterSnippetTree(node.children, query);
+ if (filteredChildren.length > 0) {
+ return [{ ...node, children: filteredChildren }];
+ }
+ }
+
+ return [];
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
new file mode 100644
index 00000000000..e24288e6a07
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
@@ -0,0 +1,312 @@
+import type { ExpandedState } from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { DateTime } from "metabase/common/components/DateTime";
+import { useBuildSnippetTree } from "metabase/data-studio/common/hooks/use-build-snippet-tree";
+import type { TreeItem } from "metabase/data-studio/common/types";
+import { isEmptyStateData } from "metabase/data-studio/common/utils";
+import { useSelector } from "metabase/redux";
+import { useRouter } from "metabase/router";
+import {
+ EntityNameCell,
+ Flex,
+ Group,
+ Icon,
+ Text,
+ type TreeTableColumnDef,
+ useTreeTableInstance,
+} from "metabase/ui";
+import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
+import type { Collection } from "metabase-types/api";
+
+import { ActionCell } from "../components/ActionCell";
+import { EmptyStateAction } from "../components/EmptyStateAction";
+
+import { useErrorHandling } from "./useErrorHandling";
+import { useLibraryCollectionTree } from "./useLibraryCollectionTree";
+import { useLibraryCollections } from "./useLibraryCollections";
+import { useLibrarySearch } from "./useLibrarySearch";
+
+type Params = {
+ collections: Collection[];
+ searchQuery: string;
+ onPublishTableClick: VoidFunction;
+};
+
+export function useLibraryTreeTableInstance({
+ collections,
+ searchQuery,
+ onPublishTableClick,
+}: Params) {
+ const { location } = useRouter();
+ const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
+
+ const expandedIdsFromUrl = useMemo(() => {
+ const rawIds = location.query?.expandedId;
+ if (!rawIds) {
+ return null;
+ }
+
+ const ids = Array.isArray(rawIds) ? rawIds : [rawIds];
+ return _.object(
+ ids.map((id) => [`collection:${id}`, true]),
+ ) as ExpandedState;
+ }, [location.query?.expandedId]);
+ const { libraryCollection, tableCollection, metricCollection } =
+ useLibraryCollections(collections);
+
+ const {
+ tree: tablesTree,
+ isLoading: loadingTables,
+ error: tablesError,
+ watchRows: watchTableRows,
+ isChildrenLoading: isTableChildrenLoading,
+ refreshCollections: refreshTableCollections,
+ } = useLibraryCollectionTree(tableCollection, "data");
+ const {
+ tree: metricsTree,
+ isLoading: loadingMetrics,
+ error: metricsError,
+ watchRows: watchMetricRows,
+ isChildrenLoading: isMetricChildrenLoading,
+ refreshCollections: refreshMetricCollections,
+ } = useLibraryCollectionTree(
+ metricCollection,
+ "metrics",
+ metricCollection?.id,
+ );
+ const {
+ tree: snippetTree,
+ isLoading: loadingSnippets,
+ error: snippetsError,
+ } = useBuildSnippetTree();
+
+ // Server-side search for tables and metrics, client-side for snippets
+ const {
+ tree: searchTree,
+ isActive: isSearchActive,
+ isLoading: isSearchLoading,
+ } = useLibrarySearch(searchQuery, libraryCollection?.id, snippetTree);
+
+ const combinedTree = useMemo(
+ () =>
+ isSearchActive
+ ? searchTree
+ : [...tablesTree, ...metricsTree, ...snippetTree],
+ [isSearchActive, searchTree, tablesTree, metricsTree, snippetTree],
+ );
+
+ const isLoading =
+ loadingTables || loadingMetrics || loadingSnippets || isSearchLoading;
+ useErrorHandling(tablesError || metricsError || snippetsError);
+
+ const libraryHasContent = useMemo(
+ () =>
+ combinedTree.some(
+ (node) =>
+ node.children &&
+ node.children.length > 0 &&
+ node.children.some((child) => child.model !== "empty-state"),
+ ),
+ [combinedTree],
+ );
+
+ const libraryColumnDef = useMemo<TreeTableColumnDef<TreeItem>[]>(
+ () => [
+ {
+ id: "name",
+ header: t`Name`,
+ enableSorting: true,
+ accessorKey: "name",
+ minWidth: 200,
+ cell: ({ row }) => {
+ const { data } = row.original;
+
+ if (isEmptyStateData(data)) {
+ return (
+ <Flex align="center" gap="0.25rem" data-testid="empty-state-row">
+ <Text c="text-tertiary" fz="inherit">
+ {data.description}
+ </Text>
+ {!isRemoteSyncReadOnly && (
+ <EmptyStateAction
+ data={data}
+ onPublishTableClick={onPublishTableClick}
+ />
+ )}
+ </Flex>
+ );
+ }
+
+ return (
+ <EntityNameCell
+ data-testid={`${row.original.model}-name`}
+ icon={row.original.icon}
+ name={
+ row.original.parentCollectionName ? (
+ <Group gap="sm" miw={0} align="center">
+ <Text truncate>{row.original.name}</Text>
+ <Group gap="xs">
+ <Icon name="collection" size={12} c="text-tertiary" />
+ <Text fz="xs" c="text-tertiary" truncate>
+ {row.original.parentCollectionName}
+ </Text>
+ </Group>
+ </Group>
+ ) : (
+ row.original.name
+ )
+ }
+ />
+ );
+ },
+ },
+ {
+ id: "updatedAt",
+ header: t`Updated At`,
+ accessorKey: "updatedAt",
+ enableSorting: true,
+ sortingFn: "datetime",
+ width: "auto",
+ widthPadding: 20,
+ cell: ({ row, getValue }) => {
+ if (row.original.model === "empty-state") {
+ return null;
+ }
+ const dateValue = getValue() as string | undefined;
+ return dateValue ? <DateTime value={dateValue} /> : null;
+ },
+ },
+ {
+ id: "actions",
+ width: 48,
+ cell: ({ row }) => (
+ <ActionCell
+ treeItem={row.original}
+ refreshMetricCollections={refreshMetricCollections}
+ refreshTableCollections={refreshTableCollections}
+ />
+ ),
+ },
+ ],
+ [
+ isRemoteSyncReadOnly,
+ onPublishTableClick,
+ refreshMetricCollections,
+ refreshTableCollections,
+ ],
+ );
+
+ const snippetRootId = snippetTree[0]?.id;
+
+ // Controlled expansion: expand all during search, preserve user state when browsing.
+ // Default any IDs from the URL. If none are provided, default to Data, Metrics and SQL Snippets expanded
+ const defaultExpanded = useMemo<ExpandedState>(() => {
+ if (expandedIdsFromUrl) {
+ return expandedIdsFromUrl;
+ }
+ const ids: ExpandedState = {};
+ if (tableCollection) {
+ ids[`collection:${tableCollection.id}`] = true;
+ }
+ if (metricCollection) {
+ ids[`collection:${metricCollection.id}`] = true;
+ }
+
+ if (snippetRootId) {
+ ids[snippetRootId] = true;
+ }
+
+ return ids;
+ }, [expandedIdsFromUrl, tableCollection, metricCollection, snippetRootId]);
+
+ const [browseExpanded, setBrowseExpanded] = useState<ExpandedState | null>(
+ null,
+ );
+
+ // Initialize browseExpanded from defaultExpanded once collections are loaded,
+ // so we stop falling through to a recalculated defaultExpanded on every render.
+ useEffect(() => {
+ if (
+ browseExpanded === null &&
+ !isLoading &&
+ Object.keys(defaultExpanded).length > 0
+ ) {
+ setBrowseExpanded(defaultExpanded);
+ }
+ }, [browseExpanded, defaultExpanded, isLoading]);
+
+ const expanded = isSearchActive ? true : (browseExpanded ?? defaultExpanded);
+ const onExpandedChange = useCallback(
+ (updater: ExpandedState | ((old: ExpandedState) => ExpandedState)) => {
+ if (!isSearchActive) {
+ setBrowseExpanded((prev) => {
+ const current = prev ?? defaultExpanded;
+ return typeof updater === "function" ? updater(current) : updater;
+ });
+ }
+ },
+ [isSearchActive, defaultExpanded],
+ );
+
+ const treeTableInstance = useTreeTableInstance({
+ data: combinedTree,
+ columns: libraryColumnDef,
+ getSubRows: (node) => node.children,
+ getNodeId: (node) => node.id,
+ getRowCanExpand: (row) => {
+ const { model, data, children } = row.original;
+ if (model !== "collection") {
+ return false;
+ }
+ if (row.original.childrenLoaded) {
+ return children != null && children.length > 0;
+ }
+ // Already has children populated
+ if (children && children.length > 0) {
+ return true;
+ }
+ // Not loaded yet — check here/below from the API to know if expandable
+ if (!isEmptyStateData(data) && "here" in data) {
+ const item = data as { here?: string[]; below?: string[] };
+ return (
+ (item.here != null && item.here.length > 0) ||
+ (item.below != null && item.below.length > 0)
+ );
+ }
+ return false;
+ },
+ expanded,
+ onExpandedChange,
+ isFilterable: (node) =>
+ node.model !== "collection" && node.model !== "empty-state",
+ });
+
+ // Lazy-load subcollection items when expanded
+ useEffect(() => {
+ watchTableRows(treeTableInstance.rows);
+ watchMetricRows(treeTableInstance.rows);
+ }, [treeTableInstance.rows, watchTableRows, watchMetricRows]);
+
+ const isChildrenLoading = useCallback(
+ (row: Parameters<typeof isTableChildrenLoading>[0]) =>
+ isTableChildrenLoading(row) || isMetricChildrenLoading(row),
+ [isTableChildrenLoading, isMetricChildrenLoading],
+ );
+
+ let emptyMessage = null;
+ if (!libraryHasContent) {
+ emptyMessage = t`No tables, metrics, or snippets yet`;
+ } else if (searchQuery) {
+ emptyMessage = t`No results for "${searchQuery}"`;
+ }
+
+ return {
+ treeTableInstance,
+ isChildrenLoading,
+ isLoading,
+ emptyMessage,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts
index 9bc330e454b..9004ad5e73b 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts
@@ -1,3 +1,6 @@
+import type { TreeItem } from "metabase/data-studio/common/types";
+import { isEmptyStateData } from "metabase/data-studio/common/utils";
+import * as Urls from "metabase/urls";
import type { Collection, CollectionType } from "metabase-types/api";
export function getAccessibleCollection(
@@ -16,3 +19,22 @@ export function getWritableCollection(
const collection = getAccessibleCollection(rootCollection, type);
return collection?.can_write ? collection : undefined;
}
+
+export const getTreeRowHref = (row: { original: TreeItem }): string | null => {
+ const treeItem = row.original;
+
+ if (treeItem.model === "empty-state" || isEmptyStateData(treeItem.data)) {
+ return null;
+ }
+ const entityId = treeItem.data.id as number;
+ if (treeItem.model === "metric") {
+ return Urls.dataStudioMetric(entityId);
+ }
+ if (treeItem.model === "snippet") {
+ return Urls.dataStudioSnippet(entityId);
+ }
+ if (treeItem.model === "table") {
+ return Urls.dataStudioTable(entityId);
+ }
+ return null;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
new file mode 100644
index 00000000000..647e7244800
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
@@ -0,0 +1,31 @@
+import { useEffect } from "react";
+
+import CollectionPermissionsModalBase from "metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal";
+import { Modal } from "metabase/common/components/Modal";
+import { SnippetCollections } from "metabase/entities/snippet-collections";
+import type { CollectionPermissionsModalProps } from "metabase/plugins";
+import { useDispatch } from "metabase/redux";
+
+export function CollectionPermissionsModal({
+ collectionId,
+ namespace,
+ onClose,
+}: CollectionPermissionsModalProps) {
+ const dispatch = useDispatch();
+
+ useEffect(() => {
+ if (namespace === "snippets") {
+ dispatch(SnippetCollections.actions.fetchList());
+ }
+ }, [dispatch, namespace]);
+
+ return (
+ <Modal onClose={onClose}>
+ <CollectionPermissionsModalBase
+ params={{ slug: String(collectionId) }}
+ namespace={namespace}
+ onClose={onClose}
+ />
+ </Modal>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/index.ts
new file mode 100644
index 00000000000..ffa5b20562e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/index.ts
@@ -0,0 +1 @@
+export { CollectionPermissionsModal } from "./CollectionPermissionsModal";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx
index f88f62be079..c0e24e0596b 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx
@@ -2,6 +2,7 @@ import { push } from "react-router-redux";
import { jt, t } from "ttag";
import { useGetTableSelectionInfoQuery } from "metabase/api";
+import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker";
import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
import { trackDataStudioTablePublished } from "metabase/data-studio/analytics";
import {
@@ -11,7 +12,7 @@ import {
FormSubmitButton,
} from "metabase/forms";
import { useMetadataToasts } from "metabase/metadata/hooks";
-import type { PublishTablesModalProps } from "metabase/plugins";
+import { PLUGIN_LIBRARY, type PublishTablesModalProps } from "metabase/plugins";
import { useDispatch } from "metabase/redux";
import {
Box,
@@ -27,6 +28,7 @@ import * as Urls from "metabase/urls";
import { usePublishTablesMutation } from "metabase-enterprise/api";
import type {
BulkTableInfo,
+ BulkTableRequest,
DatabaseId,
SchemaId,
TableId,
@@ -107,18 +109,27 @@ function ModalBody({
const [publishTables] = usePublishTablesMutation();
const { sendSuccessToast } = useMetadataToasts();
const dispatch = useDispatch();
+ const dataCollection = PLUGIN_LIBRARY.useGetLibraryChildCollectionByType({
+ type: "library-data",
+ });
- if (isLoading || error != null || data == null) {
- return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;
+ if (isLoading || error != null || data == null || dataCollection == null) {
+ return (
+ <DelayedLoadingAndErrorWrapper
+ loading={isLoading || dataCollection == null}
+ error={error}
+ />
+ );
}
const { selected_table, unpublished_upstream_tables } = data;
- const handleSubmit = async () => {
+ const handleSubmit = async ({ collection_id }: BulkTableRequest) => {
const { target_collection: collection } = await publishTables({
database_ids: databaseIds,
schema_ids: schemaIds,
table_ids: tableIds,
+ collection_id,
}).unwrap();
if (collection != null) {
@@ -137,7 +148,11 @@ function ModalBody({
};
return (
- <FormProvider initialValues={{}} onSubmit={handleSubmit}>
+ <FormProvider<BulkTableRequest>
+ enableReinitialize
+ initialValues={{ collection_id: dataCollection.id as number }}
+ onSubmit={handleSubmit}
+ >
<Form>
<Stack gap="sm">
<Text>{t`Publishing a table saves it to the Library.`}</Text>
@@ -153,6 +168,23 @@ function ModalBody({
</List>
</>
)}
+ <FormCollectionPicker
+ mt="md"
+ name="collection_id"
+ title={t`Publish to`}
+ entityType="table"
+ collectionPickerModalProps={{
+ options: {
+ hasLibrary: true,
+ hasRootCollection: false,
+ hasPersonalCollections: false,
+ hasSearch: true,
+ hasRecents: false,
+ hasConfirmButtons: true,
+ canCreateCollections: false,
+ },
+ }}
+ />
</Stack>
<Group mt="xl" gap="sm" wrap="nowrap">
<Box flex={1}>
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.unit.spec.tsx
index f7e7af1faf2..0193e334ce8 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.unit.spec.tsx
@@ -1,11 +1,17 @@
import userEvent from "@testing-library/user-event";
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
+ setupCollectionByIdEndpoint,
+ setupCollectionItemsEndpoint,
+ setupLibraryEndpoints,
setupPublishTablesEndpoint,
setupPublishTablesEndpointError,
setupTableSelectionInfoEndpoint,
} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
import type {
BulkTableSelectionInfo,
DatabaseId,
@@ -15,6 +21,9 @@ import type {
import {
createMockBulkTableInfo,
createMockBulkTableSelectionInfo,
+ createMockCollection,
+ createMockCollectionItem,
+ createMockTokenFeatures,
} from "metabase-types/api/mocks";
import { PublishTablesModal } from "./PublishTablesModal";
@@ -36,6 +45,35 @@ function setup({
}: SetupOpts = {}) {
const onPublish = jest.fn();
const onClose = jest.fn();
+ const dataCollection = createMockCollection({
+ id: 10,
+ name: "Data",
+ type: "library-data",
+ });
+ const state = createMockState({
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures({ library: true }),
+ }),
+ });
+
+ setupEnterpriseOnlyPlugin("library");
+ setupLibraryEndpoints(true);
+ setupCollectionItemsEndpoint({
+ collection: { id: 6464 },
+ collectionItems: [
+ createMockCollectionItem({
+ id: dataCollection.id as number,
+ name: dataCollection.name,
+ model: "collection",
+ type: dataCollection.type,
+ can_write: true,
+ location: "/6464/",
+ here: ["table", "collection"],
+ below: ["table", "collection"],
+ }),
+ ],
+ });
+ setupCollectionByIdEndpoint({ collections: [dataCollection] });
setupTableSelectionInfoEndpoint(selectionInfo);
if (hasPublishError) {
@@ -53,6 +91,7 @@ function setup({
onPublish={onPublish}
onClose={onClose}
/>,
+ { storeInitialState: state },
);
return { onPublish, onClose };
@@ -69,7 +108,7 @@ describe("PublishTablesModal", () => {
}),
});
expect(await screen.findByText("Publish Orders?")).toBeInTheDocument();
- await userEvent.click(screen.getByText("Publish this table"));
+ await userEvent.click(await screen.findByText("Publish this table"));
await waitFor(() => expect(onPublish).toHaveBeenCalled());
});
@@ -95,9 +134,9 @@ describe("PublishTablesModal", () => {
expect(
await screen.findByText("Publish Orders and the tables it depends on?"),
).toBeInTheDocument();
- expect(screen.getByText("Products")).toBeInTheDocument();
- expect(screen.getByText("People")).toBeInTheDocument();
- await userEvent.click(screen.getByText("Publish these tables"));
+ expect(await screen.findByText("Products")).toBeInTheDocument();
+ expect(await screen.findByText("People")).toBeInTheDocument();
+ await userEvent.click(await screen.findByText("Publish these tables"));
await waitFor(() => expect(onPublish).toHaveBeenCalled());
});
@@ -110,7 +149,7 @@ describe("PublishTablesModal", () => {
expect(
await screen.findByText("Publish these tables?"),
).toBeInTheDocument();
- await userEvent.click(screen.getByText("Publish these tables"));
+ await userEvent.click(await screen.findByText("Publish these tables"));
await waitFor(() => expect(onPublish).toHaveBeenCalled());
});
@@ -135,9 +174,9 @@ describe("PublishTablesModal", () => {
"Publish these tables and the tables they depend on?",
),
).toBeInTheDocument();
- expect(screen.getByText("Products")).toBeInTheDocument();
- expect(screen.getByText("People")).toBeInTheDocument();
- await userEvent.click(screen.getByText("Publish these tables"));
+ expect(await screen.findByText("Products")).toBeInTheDocument();
+ expect(await screen.findByText("People")).toBeInTheDocument();
+ await userEvent.click(await screen.findByText("Publish these tables"));
await waitFor(() => expect(onPublish).toHaveBeenCalled());
});
@@ -152,7 +191,7 @@ describe("PublishTablesModal", () => {
hasPublishError: true,
});
expect(await screen.findByText("Publish Orders?")).toBeInTheDocument();
- await userEvent.click(screen.getByText("Publish this table"));
+ await userEvent.click(await screen.findByText("Publish this table"));
expect(await screen.findByText("An error occurred")).toBeInTheDocument();
expect(onPublish).not.toHaveBeenCalled();
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.tsx
index 07ac38365c4..e3769f04738 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.tsx
@@ -1,18 +1,12 @@
import { jt, t } from "ttag";
import { useGetTableSelectionInfoQuery } from "metabase/api";
+import { getErrorMessage } from "metabase/api/utils";
import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
import { trackDataStudioTableUnpublished } from "metabase/data-studio/analytics";
-import {
- Form,
- FormErrorMessage,
- FormProvider,
- FormSubmitButton,
-} from "metabase/forms";
import { useMetadataToasts } from "metabase/metadata/hooks";
import type { UnpublishTablesModalProps } from "metabase/plugins";
import {
- Box,
Button,
FocusTrap,
Group,
@@ -102,7 +96,7 @@ function ModalBody({
table_ids: tableIds,
});
const [unpublishTables] = useUnpublishTablesMutation();
- const { sendSuccessToast } = useMetadataToasts();
+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
if (isLoading || error != null || data == null) {
return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;
@@ -111,52 +105,46 @@ function ModalBody({
const { selected_table, published_downstream_tables } = data;
const handleSubmit = async () => {
- await unpublishTables({
- database_ids: databaseIds,
- schema_ids: schemaIds,
- table_ids: tableIds,
- }).unwrap();
- sendSuccessToast(t`Unpublished`);
- trackDataStudioTableUnpublished();
- onUnpublish();
+ try {
+ await unpublishTables({
+ database_ids: databaseIds,
+ schema_ids: schemaIds,
+ table_ids: tableIds,
+ }).unwrap();
+ sendSuccessToast(t`Unpublished`);
+ trackDataStudioTableUnpublished();
+ onUnpublish();
+ } catch (error) {
+ sendErrorToast(getErrorMessage(error, t`Failed to unpublish`));
+ }
};
return (
- <FormProvider initialValues={{}} onSubmit={handleSubmit}>
- <Form>
- <Stack gap="sm">
- <Text>
- {getInfoMessage(selected_table, published_downstream_tables)}
- </Text>
- {published_downstream_tables.length > 0 && (
- <>
- <Text>{getForeignKeyMessage(selected_table)}</Text>
- <List spacing="sm">
- {published_downstream_tables.map((table) => (
- <List.Item key={table.id} fw="bold">
- {table.display_name}
- </List.Item>
- ))}
- </List>
- </>
- )}
- </Stack>
- <Group mt="xl" gap="sm" wrap="nowrap">
- <Box flex={1}>
- <FormErrorMessage />
- </Box>
- <Button variant="subtle" onClick={onClose}>{t`Cancel`}</Button>
- <FormSubmitButton
- label={getSubmitButtonLabel(
- selected_table,
- published_downstream_tables,
- )}
- variant="filled"
- color="error"
- />
- </Group>
- </Form>
- </FormProvider>
+ <>
+ <Stack gap="sm" mt="sm">
+ <Text>
+ {getInfoMessage(selected_table, published_downstream_tables)}
+ </Text>
+ {published_downstream_tables.length > 0 && (
+ <>
+ <Text>{getForeignKeyMessage(selected_table)}</Text>
+ <List spacing="sm">
+ {published_downstream_tables.map((table) => (
+ <List.Item key={table.id} fw="bold">
+ {table.display_name}
+ </List.Item>
+ ))}
+ </List>
+ </>
+ )}
+ </Stack>
+ <Group mt="xl" gap="sm" wrap="nowrap" justify="flex-end">
+ <Button variant="subtle" onClick={onClose}>{t`Cancel`}</Button>
+ <Button onClick={handleSubmit} variant="filled" color="error">
+ {getSubmitButtonLabel(selected_table, published_downstream_tables)}
+ </Button>
+ </Group>
+ </>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.unit.spec.tsx
index c7c07f31ac0..39ac8e64969 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/UnpublishTablesModal/UnpublishTablesModal.unit.spec.tsx
@@ -5,7 +5,8 @@ import {
setupUnpublishTablesEndpoint,
setupUnpublishTablesEndpointError,
} from "__support__/server-mocks";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
import type {
BulkTableSelectionInfo,
DatabaseId,
@@ -45,14 +46,17 @@ function setup({
}
renderWithProviders(
- <UnpublishTablesModal
- databaseIds={databaseIds}
- schemaIds={schemaIds}
- tableIds={tableIds}
- isOpened
- onUnpublish={onUnpublish}
- onClose={onClose}
- />,
+ <>
+ <UnpublishTablesModal
+ databaseIds={databaseIds}
+ schemaIds={schemaIds}
+ tableIds={tableIds}
+ isOpened
+ onUnpublish={onUnpublish}
+ onClose={onClose}
+ />
+ <UndoListing />
+ </>,
);
return { onUnpublish, onClose };
@@ -145,7 +149,8 @@ describe("UnpublishTablesModal", () => {
});
expect(await screen.findByText("Unpublish Orders?")).toBeInTheDocument();
await userEvent.click(screen.getByText("Unpublish this table"));
- expect(await screen.findByText("An error occurred")).toBeInTheDocument();
+ const toast = await screen.findByRole("status");
+ expect(within(toast).getByText("Failed to unpublish")).toBeInTheDocument();
expect(onUnpublish).not.toHaveBeenCalled();
});
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts
index 92d387b1f9d..6ad5a598506 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts
@@ -2,11 +2,17 @@ import { PLUGIN_LIBRARY } from "metabase/plugins";
import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";
import { hasPremiumFeature } from "metabase-enterprise/settings";
+import { CollectionPermissionsModal } from "./components/CollectionPermissionsModal";
import { CreateLibraryModal } from "./components/CreateLibraryModal";
import { PublishTablesModal } from "./components/PublishTablesModal";
import { UnpublishTablesModal } from "./components/UnpublishTablesModal";
import { getDataStudioLibraryRoutes } from "./routes";
import {
+ getCollectionPickerItems,
+ getEntityPickerSyntheticLibraryItem,
+ getLibraryCollectionEmptyStateMessages,
+ isLibraryCollectionType,
+ isLibrarySubCollectionType,
useGetLibraryChildCollectionByType,
useGetLibraryCollection,
useGetResolvedLibraryCollection,
@@ -21,9 +27,17 @@ export function initializePlugin() {
useGetLibraryChildCollectionByType;
PLUGIN_LIBRARY.useGetResolvedLibraryCollection =
useGetResolvedLibraryCollection;
+ PLUGIN_LIBRARY.getCollectionPickerItems = getCollectionPickerItems;
+ PLUGIN_LIBRARY.getEntityPickerSyntheticLibraryItem =
+ getEntityPickerSyntheticLibraryItem;
PLUGIN_LIBRARY.CreateLibraryModal = CreateLibraryModal;
+ PLUGIN_LIBRARY.CollectionPermissionsModal = CollectionPermissionsModal;
PLUGIN_LIBRARY.PublishTablesModal = PublishTablesModal;
PLUGIN_LIBRARY.UnpublishTablesModal = UnpublishTablesModal;
PLUGIN_LIBRARY.useGetLibraryCollectionQuery = useGetLibraryCollectionQuery;
+ PLUGIN_LIBRARY.getLibraryCollectionEmptyStateMessages =
+ getLibraryCollectionEmptyStateMessages;
+ PLUGIN_LIBRARY.isLibraryCollectionType = isLibraryCollectionType;
+ PLUGIN_LIBRARY.isLibrarySubCollectionType = isLibrarySubCollectionType;
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/ArchivedSnippetsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/ArchivedSnippetsPage.tsx
index d25f25d62eb..f7c0262c74f 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/ArchivedSnippetsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/ArchivedSnippetsPage.tsx
@@ -36,7 +36,7 @@ export function ArchivedSnippetsPage() {
const [updateSnippet] = useUpdateSnippetMutation();
const handleUnarchiveClick = useCallback(
- async (item: CollectionItem) => {
+ async (item: Pick<CollectionItem, "id" | "name">) => {
try {
await updateSnippet({
id: item.id,
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/hooks/useColumnDef.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/hooks/useColumnDef.tsx
index 08356df7362..4da492a47c0 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/hooks/useColumnDef.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/snippets/pages/ArchivedSnippetsPage/hooks/useColumnDef.tsx
@@ -1,12 +1,12 @@
import { useMemo } from "react";
import { t } from "ttag";
+import { CollectionRowMenu } from "metabase/collections/components/CollectionRowMenu";
import type { TreeItem } from "metabase/data-studio/common/types";
import {
- isCollection,
+ isCollectionData,
isEmptyStateData,
} from "metabase/data-studio/common/utils";
-import { PLUGIN_SNIPPET_FOLDERS } from "metabase/plugins";
import { useSelector } from "metabase/redux";
import {
ActionIcon,
@@ -19,7 +19,7 @@ import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selecto
import type { CollectionItem } from "metabase-types/api";
type ColumnDefProps = {
- handleUnarchiveClick: (item: CollectionItem) => void;
+ handleUnarchiveClick: (item: Pick<CollectionItem, "id" | "name">) => void;
};
export const useColumnDef = ({ handleUnarchiveClick }: ColumnDefProps) => {
@@ -51,8 +51,8 @@ export const useColumnDef = ({ handleUnarchiveClick }: ColumnDefProps) => {
return null;
}
- if (isCollection(data)) {
- return <PLUGIN_SNIPPET_FOLDERS.CollectionMenu collection={data} />;
+ if (isCollectionData(data)) {
+ return <CollectionRowMenu collection={data} />;
}
return (
@@ -63,7 +63,10 @@ export const useColumnDef = ({ handleUnarchiveClick }: ColumnDefProps) => {
onClick={async (event) => {
event.stopPropagation();
event.preventDefault();
- handleUnarchiveClick(data);
+ handleUnarchiveClick({
+ id: Number(data.id),
+ name: data.name,
+ });
}}
>
<FixedSizeIcon name={"unarchive"} c="text-primary" />
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx
index b509a3d1455..ddeb98da701 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx
@@ -2,56 +2,112 @@ import { useState } from "react";
import { push } from "react-router-redux";
import { c, t } from "ttag";
+import { collectionApi, useUpdateTableMutation } from "metabase/api";
import { ForwardRefLink } from "metabase/common/components/Link";
+import { CollectionPickerModal } from "metabase/common/components/Pickers";
import { PLUGIN_LIBRARY, PLUGIN_REMOTE_SYNC } from "metabase/plugins";
import { useDispatch, useSelector } from "metabase/redux";
-import { ActionIcon, Icon, Menu } from "metabase/ui";
+import { ActionIcon, Box, FixedSizeIcon, Icon, Menu } from "metabase/ui";
import * as Urls from "metabase/urls";
-import type { Table } from "metabase-types/api";
+import type { CollectionId, CollectionItem, Table } from "metabase-types/api";
-type TableModalType = "unpublish";
+type TableModalType = "unpublish" | "move";
-type TableMoreMenuProps = {
- table: Table;
+export type TableMoreMenuProps = {
+ table:
+ | Pick<CollectionItem, "id" | "database_id" | "collection_id">
+ | Pick<Table, "id" | "db_id" | "collection_id">;
+ onMoved?: (collectionIds: CollectionId[]) => void;
};
-export function TableMoreMenu({ table }: TableMoreMenuProps) {
+export function TableMoreMenu({ table, onMoved }: TableMoreMenuProps) {
const dispatch = useDispatch();
const [modalType, setModalType] = useState<TableModalType>();
+ const [updateTable] = useUpdateTableMutation();
const remoteSyncReadOnly = useSelector(
PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,
);
+ const dbId = "db_id" in table ? table.db_id : table.database_id;
+
const handleUnpublish = () => {
setModalType(undefined);
dispatch(push(Urls.dataStudioLibrary()));
};
+ const handleMove = async (newCollection: { id: CollectionId }) => {
+ const sourceCollectionId = table.collection_id;
+ await updateTable({
+ id: table.id,
+ collection_id: newCollection.id,
+ }).unwrap();
+ dispatch(
+ collectionApi.util.invalidateTags([
+ { type: "collection", id: `${sourceCollectionId}-items` },
+ { type: "collection", id: `${newCollection.id}-items` },
+ ]),
+ );
+ const affectedIds: CollectionId[] = [newCollection.id];
+ if (sourceCollectionId != null) {
+ affectedIds.push(sourceCollectionId);
+ }
+ onMoved?.(affectedIds);
+ setModalType(undefined);
+ };
+
return (
- <>
- <Menu>
+ <Box
+ onClick={(event) => {
+ event.stopPropagation();
+ }}
+ >
+ <Menu withinPortal>
<Menu.Target>
- <ActionIcon size="sm" aria-label={t`Show table options`}>
- <Icon name="ellipsis" />
+ <ActionIcon
+ aria-label={t`Show table options`}
+ size="md"
+ onClick={(event) => {
+ event.preventDefault();
+ }}
+ >
+ <FixedSizeIcon name="ellipsis" size={16} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
- <Menu.Item
- leftSection={<Icon name="external" />}
- component={ForwardRefLink}
- to={Urls.queryBuilderTable(table.id, table.db_id)}
- target="_blank"
- >
- {c("A verb, not a noun").t`View`}
- </Menu.Item>
- {!remoteSyncReadOnly && (
+ {dbId != null && (
<Menu.Item
- leftSection={<Icon name="unpublish" />}
- onClick={() => setModalType("unpublish")}
+ leftSection={<Icon name="external" />}
+ component={ForwardRefLink}
+ to={Urls.queryBuilderTable(table.id, dbId)}
+ target="_blank"
>
- {t`Unpublish`}
+ {c("A verb, not a noun").t`View`}
</Menu.Item>
)}
+ {!remoteSyncReadOnly && (
+ <>
+ <Menu.Item
+ leftSection={<Icon name="move" />}
+ onClick={(event) => {
+ setModalType("move");
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ >
+ {t`Move`}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="unpublish" />}
+ onClick={(event) => {
+ setModalType("unpublish");
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ >
+ {t`Unpublish`}
+ </Menu.Item>
+ </>
+ )}
</Menu.Dropdown>
</Menu>
<PLUGIN_LIBRARY.UnpublishTablesModal
@@ -60,6 +116,27 @@ export function TableMoreMenu({ table }: TableMoreMenuProps) {
onUnpublish={handleUnpublish}
onClose={() => setModalType(undefined)}
/>
- </>
+ {modalType === "move" && (
+ <CollectionPickerModal
+ title={t`Move table to…`}
+ value={{
+ id: table.collection_id ?? "root",
+ model: "collection",
+ }}
+ onChange={handleMove}
+ onClose={() => setModalType(undefined)}
+ options={{
+ hasLibrary: true,
+ hasRootCollection: false,
+ hasPersonalCollections: false,
+ hasSearch: true,
+ hasRecents: false,
+ hasConfirmButtons: true,
+ confirmButtonText: t`Move`,
+ }}
+ entityType="table"
+ />
+ )}
+ </Box>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsx
index 3f8233f93e7..7c565ea51e8 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.unit.spec.tsx
@@ -1,31 +1,87 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { Route } from "react-router";
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import type { ENTERPRISE_PLUGIN_NAME } from "__support__/enterprise-typed";
+import {
+ setupCollectionByIdEndpoint,
+ setupCollectionItemsEndpoint,
+ setupCollectionsEndpoints,
+ setupLibraryEndpoints,
+ setupRootCollectionItemsEndpoint,
+ setupTableEndpoints,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { CollectionPickerModalProps } from "metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal";
import { createMockState } from "metabase/redux/store/mocks";
-import type { EnterpriseSettings, TokenFeatures } from "metabase-types/api";
+import type {
+ CollectionItem,
+ EnterpriseSettings,
+ TokenFeatures,
+} from "metabase-types/api";
import {
+ createMockCollection,
+ createMockCollectionItem,
createMockTable,
createMockTokenFeatures,
} from "metabase-types/api/mocks";
-import { TableMoreMenu } from "./TableMoreMenu";
+import { TableMoreMenu, type TableMoreMenuProps } from "./TableMoreMenu";
+
+// Mocking picker modal to limit overhead (picker functionality is tested in e2e tests)
+jest.mock("metabase/common/components/Pickers", () => ({
+ CollectionPickerModal: ({ onChange }: CollectionPickerModalProps) => (
+ <button
+ onClick={() =>
+ onChange({
+ id: 11,
+ name: "Destination",
+ model: "collection",
+ can_write: true,
+ })
+ }
+ >
+ Destination
+ </button>
+ ),
+}));
type SetupOpts = {
+ table?: TableMoreMenuProps["table"];
remoteSyncType?: EnterpriseSettings["remote-sync-type"];
+ onMoved?: TableMoreMenuProps["onMoved"];
};
-const setup = ({ remoteSyncType }: SetupOpts = {}) => {
- const mockTable = createMockTable({
- id: 1,
- db_id: 1,
- schema: "PUBLIC",
- });
+const dataCollection = createMockCollection({
+ id: 10,
+ name: "Data",
+ type: "library-data",
+ can_write: true,
+ location: "/6464/",
+});
+
+const destinationCollection = createMockCollection({
+ id: 11,
+ name: "Destination",
+ type: "library-data",
+ can_write: true,
+ location: "/6464/10/",
+});
+
+const setup = ({ table, remoteSyncType, onMoved }: SetupOpts = {}) => {
+ const tableData =
+ table ??
+ createMockTable({
+ id: 1,
+ db_id: 1,
+ schema: "PUBLIC",
+ collection_id: dataCollection.id as number,
+ });
const tokenFeatures: Partial<TokenFeatures> = {
+ library: true,
remote_sync: !!remoteSyncType,
};
const settings = mockSettings({
@@ -39,9 +95,68 @@ const setup = ({ remoteSyncType }: SetupOpts = {}) => {
const enterprisePlugins: ENTERPRISE_PLUGIN_NAME[] = ["remote_sync"];
enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
+ setupEnterpriseOnlyPlugin("library");
+ setupLibraryEndpoints(true);
+ setupCollectionsEndpoints({
+ collections: [],
+ rootCollection: createMockCollection({
+ id: "root",
+ name: "Our analytics",
+ can_write: true,
+ }),
+ });
+ setupRootCollectionItemsEndpoint({ rootCollectionItems: [] });
+ setupCollectionItemsEndpoint({
+ collection: { id: 1 },
+ collectionItems: [],
+ });
+ setupCollectionByIdEndpoint({
+ collections: [
+ createMockCollection({ id: 1, name: "Personal Collection" }),
+ dataCollection,
+ destinationCollection,
+ ],
+ });
+ setupCollectionItemsEndpoint({
+ collection: { id: 6464 },
+ collectionItems: [
+ createMockCollectionItem({
+ id: dataCollection.id as number,
+ name: dataCollection.name,
+ model: "collection",
+ type: dataCollection.type,
+ can_write: dataCollection.can_write,
+ collection_id: 6464,
+ location: "/6464/",
+ here: ["collection"],
+ below: ["collection"],
+ is_library_root: true,
+ }),
+ ],
+ });
+ setupCollectionItemsEndpoint({
+ collection: dataCollection,
+ collectionItems: [
+ createMockCollectionItem({
+ id: destinationCollection.id as number,
+ name: destinationCollection.name,
+ model: "collection",
+ type: destinationCollection.type,
+ can_write: destinationCollection.can_write,
+ collection_id: dataCollection.id as number,
+ location: "/6464/10/",
+ here: ["table"],
+ below: [],
+ }),
+ ],
+ });
+ setupTableEndpoints(createMockTable({ id: tableData.id }));
renderWithProviders(
- <Route path="/" component={() => <TableMoreMenu table={mockTable} />} />,
+ <Route
+ path="/"
+ component={() => <TableMoreMenu table={tableData} onMoved={onMoved} />}
+ />,
{
withRouter: true,
storeInitialState: state,
@@ -71,4 +186,80 @@ describe("TableMoreMenu", () => {
screen.queryByRole("menuitem", { name: /Unpublish/ }),
).not.toBeInTheDocument();
});
+
+ describe("with CollectionItem", () => {
+ it("renders View, Move, and Unpublish menu options", async () => {
+ const collectionItem = createMockCollectionItem({
+ id: 42,
+ model: "table",
+ name: "Orders",
+ database_id: 1,
+ collection_id: 10,
+ }) as CollectionItem;
+
+ setup({ table: collectionItem });
+ await userEvent.click(
+ screen.getByRole("button", { name: "Show table options" }),
+ );
+ expect(
+ screen.getByRole("menuitem", { name: /View/ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: /Move/ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: /Unpublish/ }),
+ ).toBeInTheDocument();
+ });
+
+ it("renders menu without View when database_id is missing", async () => {
+ const collectionItem = createMockCollectionItem({
+ id: 42,
+ model: "table",
+ name: "Orders",
+ database_id: undefined,
+ collection_id: 10,
+ }) as CollectionItem;
+
+ setup({ table: collectionItem });
+ await userEvent.click(
+ screen.getByRole("button", { name: "Show table options" }),
+ );
+ expect(
+ screen.queryByRole("menuitem", { name: /View/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: /Move/ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: /Unpublish/ }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("moves a table to another Library Data collection", async () => {
+ const onMoved = jest.fn();
+ const table = createMockCollectionItem({
+ id: 42,
+ model: "table",
+ name: "Orders",
+ database_id: 1,
+ collection_id: dataCollection.id as number,
+ }) as CollectionItem;
+
+ setup({ table, onMoved });
+ await userEvent.click(
+ screen.getByRole("button", { name: "Show table options" }),
+ );
+ await userEvent.click(screen.getByRole("menuitem", { name: /Move/ }));
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Destination" }),
+ );
+
+ await waitFor(() => expect(onMoved).toHaveBeenCalledWith([11, 10]));
+ const request = fetchMock.callHistory.lastCall("table-42-put")?.request;
+ expect(await request?.json()).toEqual({ collection_id: 11 });
+ expect(screen.queryByTestId("entity-picker-modal")).not.toBeInTheDocument();
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts
index f8103dd13f8..73c0ce11743 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts
@@ -1,7 +1,17 @@
import { useMemo } from "react";
import { match } from "ts-pattern";
+import { t } from "ttag";
import { skipToken, useListCollectionItemsQuery } from "metabase/api";
+import type {
+ OmniPickerCollectionItem,
+ OmniPickerItem,
+} from "metabase/common/components/Pickers/EntityPicker/types";
+import { allCollectionModels } from "metabase/common/components/Pickers/EntityPicker/utils";
+import type {
+ GetEntityPickerSyntheticLibraryItemFunction,
+ LibrarySubCollectionType,
+} from "metabase/plugins/oss/library";
import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";
import type { CollectionItem, CollectionType } from "metabase-types/api";
@@ -85,3 +95,108 @@ export const useGetResolvedLibraryCollection = ({
data: showableLibrary,
};
};
+
+type LibrarySectionCollectionItem = CollectionItem &
+ OmniPickerCollectionItem & {
+ model: "collection";
+ type: LibrarySubCollectionType;
+ };
+
+function getLibrarySectionName(type: LibrarySubCollectionType) {
+ switch (type) {
+ case "library-data":
+ return t`Data`;
+ case "library-metrics":
+ return t`Metrics`;
+ }
+}
+
+export function getCollectionPickerItems({
+ parentItem,
+ items,
+}: {
+ parentItem: OmniPickerItem;
+ items: CollectionItem[];
+}): OmniPickerItem[] | undefined {
+ if (parentItem.model !== "collection" || parentItem.type !== "library") {
+ return undefined;
+ }
+
+ const librarySubCollectionType: LibrarySubCollectionType[] = [
+ "library-data",
+ "library-metrics",
+ ];
+
+ return librarySubCollectionType.flatMap((type) => {
+ const sectionItems = items.filter((item) =>
+ isLibrarySectionCollectionItem(item, type),
+ );
+
+ const realRoot = sectionItems.find((item) => item.is_library_root);
+ if (realRoot) {
+ return [realRoot];
+ }
+
+ if (sectionItems.length > 0) {
+ const syntheticItem = getEntityPickerSyntheticLibraryItem({
+ collectionId: parentItem.id,
+ type,
+ });
+
+ return syntheticItem ? [syntheticItem] : [];
+ }
+
+ return [];
+ });
+}
+
+function isLibrarySectionCollectionItem(
+ item: CollectionItem,
+ type: LibrarySubCollectionType,
+): item is LibrarySectionCollectionItem {
+ return item.model === "collection" && item.type === type;
+}
+
+export const getEntityPickerSyntheticLibraryItem: GetEntityPickerSyntheticLibraryItemFunction =
+ ({ collectionId, type }) => {
+ return {
+ id: `${type}-${collectionId}`,
+ sourceCollectionId: collectionId,
+ name: getLibrarySectionName(type),
+ model: "collection",
+ type,
+ can_write: false,
+ location: "/",
+ here: [],
+ below: allCollectionModels,
+ childTypeFilter: type,
+ };
+ };
+
+export const getLibraryCollectionEmptyStateMessages = (
+ type: LibrarySubCollectionType,
+) => {
+ if (type === "library-data") {
+ return {
+ title: t`No published tables yet`,
+ description: t`Publish tables in the Library to see them here.`,
+ };
+ }
+
+ return {
+ title: t`No metrics yet`,
+ description: t`Put metrics in the Library to see them here.`,
+ };
+};
+
+export const isLibrarySubCollectionType = (
+ type?: string | null,
+): type is LibrarySubCollectionType => {
+ return type === "library-data" || type === "library-metrics";
+};
+
+export const isLibraryCollectionType = (
+ type?: string | null,
+): type is LibrarySubCollectionType => {
+ return isLibrarySubCollectionType(type) || type === "library";
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.unit.spec.ts
new file mode 100644
index 00000000000..75fb3f0fd00
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.unit.spec.ts
@@ -0,0 +1,101 @@
+import type { OmniPickerItem } from "metabase/common/components/Pickers/EntityPicker/types";
+import { createMockCollectionItem } from "metabase-types/api/mocks";
+
+import { getCollectionPickerItems } from "./utils";
+
+const libraryParentItem: OmniPickerItem = {
+ id: 1,
+ name: "Library",
+ model: "collection",
+ type: "library",
+};
+
+describe("getCollectionPickerItems", () => {
+ it("should return real Library section roots when available", () => {
+ const dataRoot = createMockCollectionItem({
+ id: 2,
+ name: "Data",
+ model: "collection",
+ type: "library-data",
+ is_library_root: true,
+ });
+ const metricsRoot = createMockCollectionItem({
+ id: 3,
+ name: "Metrics",
+ model: "collection",
+ type: "library-metrics",
+ is_library_root: true,
+ });
+
+ expect(
+ getCollectionPickerItems({
+ parentItem: libraryParentItem,
+ items: [dataRoot, metricsRoot],
+ }),
+ ).toEqual([dataRoot, metricsRoot]);
+ });
+
+ it("should create synthetic Library section roots for promoted descendants", () => {
+ const dataChild = createMockCollectionItem({
+ id: 4,
+ name: "Data Child",
+ model: "collection",
+ type: "library-data",
+ is_library_root: false,
+ });
+ const metricsChild = createMockCollectionItem({
+ id: 5,
+ name: "Metrics Child",
+ model: "collection",
+ type: "library-metrics",
+ is_library_root: false,
+ });
+
+ expect(
+ getCollectionPickerItems({
+ parentItem: libraryParentItem,
+ items: [dataChild, metricsChild],
+ }),
+ ).toEqual([
+ expect.objectContaining({
+ id: "library-data-1",
+ sourceCollectionId: 1,
+ name: "Data",
+ model: "collection",
+ type: "library-data",
+ childTypeFilter: "library-data",
+ }),
+ expect.objectContaining({
+ id: "library-metrics-1",
+ sourceCollectionId: 1,
+ name: "Metrics",
+ model: "collection",
+ type: "library-metrics",
+ childTypeFilter: "library-metrics",
+ }),
+ ]);
+ });
+
+ it("should return undefined for non-Library parent items", () => {
+ const regularParentItem: OmniPickerItem = {
+ id: 6,
+ name: "Regular Collection",
+ model: "collection",
+ type: null,
+ };
+
+ expect(
+ getCollectionPickerItems({
+ parentItem: regularParentItem,
+ items: [
+ createMockCollectionItem({
+ id: 7,
+ name: "Child",
+ model: "collection",
+ type: "library-data",
+ }),
+ ],
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx
index 55f29c2a76b..7bf3da6db98 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx
@@ -1,10 +1,14 @@
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import { setupCollectionTreeEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
import { TRANSFORMS_ROOT_ID } from "metabase-enterprise/remote_sync/displayGroups";
import type { Collection, RemoteSyncEntity } from "metabase-types/api";
-import { createMockCollection } from "metabase-types/api/mocks";
+import {
+ createMockCollection,
+ createMockTokenFeatures,
+} from "metabase-types/api/mocks";
import { createMockRemoteSyncEntity } from "metabase-types/api/mocks/remote-sync";
import { AllChangesView } from "./AllChangesView";
@@ -39,11 +43,15 @@ const setup = ({
collections?: Collection[];
isTransformsSyncEnabled?: boolean;
}) => {
+ setupEnterpriseOnlyPlugin("library");
setupCollectionTreeEndpoint(collections);
const storeInitialState = createMockState({
settings: mockSettings({
"remote-sync-transforms": isTransformsSyncEnabled,
+ "token-features": createMockTokenFeatures({
+ library: true,
+ }),
}),
});
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx
index ada205fabd7..4fc1e3d505c 100644
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx
+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx
@@ -2,21 +2,17 @@
import cx from "classnames";
import { Component } from "react";
+import { CollectionRowMenu } from "metabase/collections/components/CollectionRowMenu";
import CS from "metabase/css/core/index.css";
import { SnippetCollections } from "metabase/entities/snippet-collections";
import { Ellipsified, Icon } from "metabase/ui";
-import { SnippetCollectionMenu } from "./SnippetCollectionMenu";
-
const ICON_SIZE = 16;
class CollectionRow extends Component {
render() {
- const {
- snippetCollection: collection,
- setSnippetCollectionId,
- setSidebarState,
- } = this.props;
+ const { snippetCollection: collection, setSnippetCollectionId } =
+ this.props;
const onSelectCollection = () => {
if (setSnippetCollectionId) {
setSnippetCollectionId(collection.id);
@@ -31,7 +27,7 @@ class CollectionRow extends Component {
CS.hoverVisibility,
CS.flex,
CS.alignCenter,
- CS.py2,
+ CS.py1,
CS.px3,
CS.textBrand,
)}
@@ -46,16 +42,7 @@ class CollectionRow extends Component {
<Ellipsified className={cx(CS.flexFull, CS.ml1, CS.textBold)} flex={1}>
{collection.name}
</Ellipsified>
- <SnippetCollectionMenu
- className={CS.flexNoShrink}
- collection={collection}
- onEditDetails={() => {
- setSidebarState({ modalSnippetCollection: collection });
- }}
- onChangePermissions={() => {
- setSidebarState({ permissionsModalCollectionId: collection.id });
- }}
- />
+ <CollectionRowMenu collection={collection} />
</div>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionForm.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionForm.tsx
deleted file mode 100644
index e22a1c5dc30..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionForm.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-import { useCallback, useMemo } from "react";
-import { t } from "ttag";
-import _ from "underscore";
-import * as Yup from "yup";
-
-import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker";
-import { Button } from "metabase/common/components/Button";
-import { FormErrorMessage } from "metabase/common/components/FormErrorMessage";
-import { FormFooter } from "metabase/common/components/FormFooter";
-import { FormInput } from "metabase/common/components/FormInput";
-import { FormSubmitButton } from "metabase/common/components/FormSubmitButton";
-import { FormTextArea } from "metabase/common/components/FormTextArea";
-import type { OmniPickerItem } from "metabase/common/components/Pickers";
-import { isItemInCollectionOrItsDescendants } from "metabase/common/components/Pickers/utils";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
-import { Form, FormProvider } from "metabase/forms";
-import { connect } from "metabase/redux";
-import type { State } from "metabase/redux/store";
-import * as Errors from "metabase/utils/errors";
-import type { Collection, CollectionId } from "metabase-types/api";
-
-const SNIPPET_COLLECTION_SCHEMA = Yup.object({
- name: Yup.string()
- .required(Errors.required)
- .max(100, Errors.maxLength)
- .default(""),
- description: Yup.string().nullable().max(255, Errors.maxLength).default(null),
- parent_id: Yup.number().nullable().default(null),
-});
-
-type SnippetCollectionFormValues = Pick<
- Collection,
- "name" | "description" | "parent_id"
->;
-
-type UpdateSnippetCollectionFormValues = Partial<SnippetCollectionFormValues> &
- Pick<Collection, "id">;
-
-export interface SnippetCollectionFormOwnProps {
- collection: Partial<Collection>;
- onSave?: (collection: Collection) => void;
- onCancel?: () => void;
-}
-
-interface SnippetCollectionLoaderProps {
- snippetCollection?: Collection;
-}
-
-interface SnippetCollectionDispatchProps {
- handleCreateSnippetCollection: (
- values: SnippetCollectionFormValues,
- ) => Promise<Collection>;
- handleUpdateSnippetCollection: (
- values: UpdateSnippetCollectionFormValues,
- ) => Promise<Collection>;
-}
-
-type Props = SnippetCollectionFormOwnProps &
- SnippetCollectionLoaderProps &
- SnippetCollectionDispatchProps;
-
-const mapDispatchToProps = {
- handleCreateSnippetCollection: SnippetCollections.actions.create,
- handleUpdateSnippetCollection: SnippetCollections.actions.update,
-};
-
-function SnippetCollectionForm({
- collection: passedCollection,
- snippetCollection,
- onSave,
- onCancel,
- handleCreateSnippetCollection,
- handleUpdateSnippetCollection,
-}: Props) {
- const collection = snippetCollection || passedCollection;
- const isEditing = collection.id != null;
-
- const initialValues = useMemo(
- () =>
- collection
- ? SNIPPET_COLLECTION_SCHEMA.cast(collection, { stripUnknown: true })
- : SNIPPET_COLLECTION_SCHEMA.getDefault(),
- [collection],
- );
-
- const handleCreate = useCallback(
- async (values: SnippetCollectionFormValues) => {
- const action = await handleCreateSnippetCollection(values);
- return SnippetCollections.HACK_getObjectFromAction(action);
- },
- [handleCreateSnippetCollection],
- );
-
- const handleUpdate = useCallback(
- async (values: UpdateSnippetCollectionFormValues) => {
- const action = await handleUpdateSnippetCollection(values);
- return SnippetCollections.HACK_getObjectFromAction(action);
- },
- [handleUpdateSnippetCollection],
- );
-
- const handleSubmit = useCallback(
- async (values: SnippetCollectionFormValues) => {
- const nextCollection = isEditing
- ? await handleUpdate({ id: collection.id as CollectionId, ...values })
- : await handleCreate(values);
- onSave?.(nextCollection);
- },
- [collection.id, isEditing, handleCreate, handleUpdate, onSave],
- );
-
- const shouldDisableItem = useCallback(
- (item: OmniPickerItem) =>
- isItemInCollectionOrItsDescendants(item, passedCollection.id),
- [passedCollection.id],
- );
-
- return (
- <FormProvider
- initialValues={initialValues}
- validationSchema={SNIPPET_COLLECTION_SCHEMA}
- enableReinitialize
- onSubmit={handleSubmit}
- >
- {({ dirty }) => (
- <Form>
- <FormInput
- name="name"
- title={t`Give your folder a name`}
- placeholder={t`Something short but sweet`}
- />
- <FormTextArea
- name="description"
- title={t`Add a description`}
- placeholder={t`It's optional but oh, so helpful`}
- nullable
- />
- <FormCollectionPicker
- name="parent_id"
- title={t`Folder this should be in`}
- collectionPickerModalProps={{
- isDisabledItem: shouldDisableItem,
- namespaces: ["snippets"],
- }}
- />
- <FormFooter>
- <FormErrorMessage inline />
- {!!onCancel && (
- <Button type="button" onClick={onCancel}>{t`Cancel`}</Button>
- )}
- <FormSubmitButton
- title={isEditing ? t`Update` : t`Create`}
- disabled={!dirty}
- primary
- />
- </FormFooter>
- </Form>
- )}
- </FormProvider>
- );
-}
-
-function getCollectionId(state: State, props: SnippetCollectionFormOwnProps) {
- return props.collection?.id;
-}
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default _.compose(
- SnippetCollections.load({ id: getCollectionId }),
- connect(null, mapDispatchToProps),
-)(SnippetCollectionForm);
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionFormModal.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionFormModal.tsx
deleted file mode 100644
index 70e515b99a5..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionFormModal.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { t } from "ttag";
-
-import type { SnippetFormModalProps } from "metabase/plugins";
-import { Modal } from "metabase/ui";
-
-import SnippetCollectionForm from "./SnippetCollectionForm";
-
-function SnippetFormModal({
- collection,
- onSaved,
- onClose,
- opened = true,
-}: SnippetFormModalProps) {
- const isEditing = collection.id != null;
- const title = isEditing
- ? t`Editing ${collection.name}`
- : t`Create your new folder`;
-
- const handleSave = () => {
- onSaved?.();
- onClose();
- };
-
- return (
- <Modal opened={opened} onClose={onClose} title={title}>
- <SnippetCollectionForm
- collection={collection}
- onSave={handleSave}
- onCancel={onClose}
- />
- </Modal>
- );
-}
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default SnippetFormModal;
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionFormModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionFormModal.unit.spec.tsx
deleted file mode 100644
index 21d74e14299..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionFormModal.unit.spec.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
-
-import {
- renderWithProviders,
- screen,
- waitFor,
- waitForLoaderToBeRemoved,
-} from "__support__/ui";
-import type { Collection } from "metabase-types/api";
-import { createMockCollection } from "metabase-types/api/mocks";
-
-import SnippetCollectionFormModal from "./SnippetCollectionFormModal";
-
-const TOP_SNIPPETS_FOLDER = {
- id: "root",
- name: "SQL snippets",
- can_write: true,
-};
-
-type SetupOpts = {
- folder?: Partial<Collection>;
- onClose?: () => void;
-};
-
-async function setup({ folder = {}, onClose = jest.fn() }: SetupOpts = {}) {
- if (folder.id) {
- fetchMock.get(`path:/api/collection/${folder.id}`, folder);
-
- fetchMock.put(`path:/api/collection/${folder.id}`, async (call) => {
- return createMockCollection(
- await fetchMock.callHistory.lastCall(call.url)?.request?.json(),
- );
- });
- }
-
- fetchMock.get({
- url: "path:/api/collection/root",
- query: { namespace: "snippets" },
- response: TOP_SNIPPETS_FOLDER,
- });
-
- fetchMock.get({
- url: "path:/api/collection",
- query: { namespace: "snippets" },
- response: [TOP_SNIPPETS_FOLDER],
- });
-
- fetchMock.post("path:/api/collection", async (call) => {
- return createMockCollection(
- await fetchMock.callHistory.lastCall(call.url)?.request?.json(),
- );
- });
-
- renderWithProviders(
- <SnippetCollectionFormModal collection={folder} onClose={onClose} />,
- );
-
- if (folder.id) {
- await waitForLoaderToBeRemoved();
- }
-
- return { onClose };
-}
-
-function setupEditing({
- folder = createMockCollection(),
- ...opts
-}: SetupOpts = {}) {
- return setup({ folder, ...opts });
-}
-
-const LABEL = {
- NAME: /Give your folder a name/i,
- DESCRIPTION: /Add a description/i,
- FOLDER: /Folder this should be in/i,
-};
-
-describe("SnippetCollectionFormModal", () => {
- describe("new folder", () => {
- it("displays correct blank state", async () => {
- await setup();
-
- expect(screen.getByLabelText(LABEL.NAME)).toBeInTheDocument();
- expect(screen.getByLabelText(LABEL.NAME)).toHaveValue("");
-
- expect(screen.getByLabelText(LABEL.DESCRIPTION)).toBeInTheDocument();
- expect(screen.getByLabelText(LABEL.DESCRIPTION)).toHaveValue("");
-
- expect(screen.getByText(LABEL.FOLDER)).toBeInTheDocument();
- expect(screen.getByText(TOP_SNIPPETS_FOLDER.name)).toBeInTheDocument();
-
- expect(
- screen.getByRole("button", { name: "Cancel" }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: "Create" }),
- ).toBeInTheDocument();
- });
-
- it("shows expected title", async () => {
- await setup();
- expect(screen.getByText(/Create your new folder/i)).toBeInTheDocument();
- });
-
- it("can't submit if name is empty", async () => {
- await setup();
- expect(screen.getByRole("button", { name: "Create" })).toBeDisabled();
- });
-
- it("can submit when name is filled in", async () => {
- await setup();
-
- await userEvent.type(screen.getByLabelText(LABEL.NAME), "My folder");
-
- await waitFor(() => {
- expect(screen.getByRole("button", { name: "Create" })).toBeEnabled();
- });
- });
-
- it("calls onClose when cancel button is clicked", async () => {
- const { onClose } = await setup();
- await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
- await waitFor(() => {
- expect(onClose).toHaveBeenCalledTimes(1);
- });
- });
- });
-
- describe("editing folder", () => {
- it("shows correct initial state", async () => {
- const folder = createMockCollection({ description: "has description" });
- await setupEditing({ folder });
-
- expect(screen.getByLabelText(LABEL.NAME)).toBeInTheDocument();
- expect(screen.getByLabelText(LABEL.NAME)).toHaveValue(folder.name);
-
- expect(screen.getByLabelText(LABEL.DESCRIPTION)).toBeInTheDocument();
- expect(screen.getByLabelText(LABEL.DESCRIPTION)).toHaveValue(
- folder.description,
- );
-
- expect(screen.getByText(LABEL.FOLDER)).toBeInTheDocument();
- expect(screen.getByText(TOP_SNIPPETS_FOLDER.name)).toBeInTheDocument();
-
- expect(
- screen.getByRole("button", { name: "Cancel" }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: "Update" }),
- ).toBeInTheDocument();
- });
-
- it("shows expected title", async () => {
- const folder = createMockCollection();
- await setupEditing({ folder });
- expect(screen.getByText(`Editing ${folder.name}`)).toBeInTheDocument();
- });
-
- it("can't submit until changes are made", async () => {
- await setupEditing();
- expect(screen.getByRole("button", { name: "Update" })).toBeDisabled();
- });
-
- it("can't submit if name is empty", async () => {
- await setupEditing();
- await userEvent.clear(screen.getByLabelText(LABEL.NAME));
- await waitFor(() => {
- expect(screen.getByRole("button", { name: "Update" })).toBeDisabled();
- });
- });
-
- it("can submit when have changes", async () => {
- await setupEditing();
- await userEvent.type(screen.getByLabelText(LABEL.NAME), "My folder");
- await waitFor(() => {
- expect(screen.getByRole("button", { name: "Update" })).toBeEnabled();
- });
- });
-
- it("calls onClose when cancel button is clicked", async () => {
- const { onClose } = await setupEditing();
- await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
- await waitFor(() => {
- expect(onClose).toHaveBeenCalledTimes(1);
- });
- });
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.module.css b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.module.css
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.tsx
deleted file mode 100644
index 5898c922f41..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-import { t } from "ttag";
-
-import { snippetApi, useUpdateCollectionMutation } from "metabase/api";
-import { listTag } from "metabase/api/tags";
-import { isRootCollection } from "metabase/collections/utils";
-import type { SnippetCollectionMenuProps } from "metabase/plugins";
-import { useDispatch, useSelector } from "metabase/redux";
-import { addUndo } from "metabase/redux/undo";
-import { getUserIsAdmin } from "metabase/selectors/user";
-import {
- ActionIcon,
- Box,
- FixedSizeIcon,
- Icon,
- Menu,
- Tooltip,
-} from "metabase/ui";
-import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
-
-export function SnippetCollectionMenu({
- collection,
- onEditDetails,
- onChangePermissions,
-}: SnippetCollectionMenuProps) {
- const dispatch = useDispatch();
-
- const isAdmin = useSelector(getUserIsAdmin);
- const [updateCollection] = useUpdateCollectionMutation();
- const remoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
-
- const isRoot = isRootCollection(collection);
-
- if (!collection.can_write || remoteSyncReadOnly) {
- return null;
- }
-
- const handleArchiveToggle = async () => {
- const wasArchived = collection.archived;
- try {
- await updateCollection({
- id: collection.id,
- archived: !wasArchived,
- }).unwrap();
-
- dispatch(
- addUndo({
- message: wasArchived
- ? t`"${collection.name}" has been unarchived`
- : t`"${collection.name}" has been archived`,
- action: async () => {
- await updateCollection({
- id: collection.id,
- archived: wasArchived,
- });
- dispatch(snippetApi.util.invalidateTags([listTag("snippet")]));
- },
- }),
- );
- dispatch(snippetApi.util.invalidateTags([listTag("snippet")]));
- } catch (error) {
- console.error("Failed to update collection:", error);
- }
- };
-
- if (collection.archived) {
- return (
- <Tooltip label={t`Unarchive snippet folder`}>
- <ActionIcon
- aria-label={t`Unarchive snippet folder`}
- size="md"
- onClick={(event) => {
- event.stopPropagation();
- void handleArchiveToggle();
- }}
- >
- <FixedSizeIcon name="unarchive" c="text-primary" />
- </ActionIcon>
- </Tooltip>
- );
- }
-
- const optionsLabel = t`Snippet folder options`;
-
- return (
- <Box onClick={(e) => e.stopPropagation()}>
- <Menu position="bottom-end">
- <Menu.Target>
- <Tooltip
- label={optionsLabel}
- onClick={(e) => e.stopPropagation()}
- openDelay={1000}
- >
- <ActionIcon aria-label={optionsLabel} size="md">
- <FixedSizeIcon name="ellipsis" size={16} />
- </ActionIcon>
- </Tooltip>
- </Menu.Target>
- <Menu.Dropdown>
- {!isRoot && (
- <Menu.Item
- leftSection={<Icon name="pencil" />}
- onClick={() => onEditDetails?.(collection)}
- >
- {t`Edit folder details`}
- </Menu.Item>
- )}
- {isAdmin && (
- <Menu.Item
- leftSection={<Icon name="lock" />}
- onClick={() => onChangePermissions?.(collection.id)}
- >
- {t`Change permissions`}
- </Menu.Item>
- )}
- {!isRoot && (
- <Menu.Item
- leftSection={<Icon name="archive" />}
- onClick={handleArchiveToggle}
- c="error"
- >
- {t`Archive`}
- </Menu.Item>
- )}
- </Menu.Dropdown>
- </Menu>
- </Box>
- );
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.unit.spec.tsx
deleted file mode 100644
index 57336ce1c50..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/SnippetCollectionMenu.unit.spec.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen } from "__support__/ui";
-import { createMockState } from "metabase/redux/store/mocks/state";
-import type { Collection, EnterpriseSettings } from "metabase-types/api";
-import { createMockCollection, createMockUser } from "metabase-types/api/mocks";
-
-import { SnippetCollectionMenu } from "./SnippetCollectionMenu";
-
-interface SetupOptions {
- remoteSyncType?: EnterpriseSettings["remote-sync-type"];
- collection?: Partial<Collection>;
-}
-
-const onEditDetails = jest.fn();
-const onChangePermissions = jest.fn();
-
-const setup = ({ remoteSyncType, collection }: SetupOptions = {}) => {
- const state = createMockState({
- settings: mockSettings({
- "remote-sync-type": remoteSyncType,
- "remote-sync-enabled": !!remoteSyncType,
- }),
- currentUser: createMockUser(),
- });
-
- return renderWithProviders(
- <SnippetCollectionMenu
- collection={createMockCollection(collection)}
- onChangePermissions={onChangePermissions}
- onEditDetails={onEditDetails}
- />,
- {
- storeInitialState: state,
- },
- );
-};
-
-describe("RootSnippetsCollectionMenu", () => {
- it("renders snippet collection options menu", () => {
- setup();
- expect(
- screen.getByRole("button", { name: "Snippet folder options" }),
- ).toBeInTheDocument();
- });
-
- it("renders nothing if collection is not writable", () => {
- setup({ collection: { can_write: false } });
- expect(
- screen.queryByRole("button", { name: "Snippet folder options" }),
- ).not.toBeInTheDocument();
- });
-
- it("renders nothing if remote sync is set to read-only", () => {
- setup({ remoteSyncType: "read-only" });
- expect(
- screen.queryByRole("button", { name: "Snippet folder options" }),
- ).not.toBeInTheDocument();
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/index.ts
deleted file mode 100644
index 486d402da79..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionMenu/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./SnippetCollectionMenu";
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/index.js b/enterprise/frontend/src/metabase-enterprise/snippets/index.js
index 1c0af01db8a..1c9623a986f 100644
--- a/enterprise/frontend/src/metabase-enterprise/snippets/index.js
+++ b/enterprise/frontend/src/metabase-enterprise/snippets/index.js
@@ -1,21 +1,18 @@
import { t } from "ttag";
-import CollectionPermissionsModal from "metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal";
+import { CollectionRowMenu } from "metabase/collections/components/CollectionRowMenu";
import { canonicalCollectionId } from "metabase/collections/utils";
-import { Modal } from "metabase/common/components/Modal";
import {
PLUGIN_SNIPPET_FOLDERS,
PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS,
- PLUGIN_SNIPPET_SIDEBAR_MODALS,
PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS,
PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS,
} from "metabase/plugins";
+import { setOpenModalWithProps } from "metabase/redux/ui";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import CollectionRow from "./components/CollectionRow";
import { MoveSnippetModal } from "./components/MoveSnippetModal";
-import SnippetCollectionFormModal from "./components/SnippetCollectionFormModal";
-import { SnippetCollectionMenu } from "./components/SnippetCollectionMenu";
import { SnippetCollectionPermissionsModal } from "./components/SnippetCollectionPermissionsModal";
import { SnippetCollectionPickerModal } from "./components/SnippetCollectionPickerModal";
@@ -27,75 +24,40 @@ export function initializePlugin() {
// Add new menu option
PLUGIN_SNIPPET_FOLDERS.isEnabled = true;
PLUGIN_SNIPPET_FOLDERS.CollectionPickerModal = SnippetCollectionPickerModal;
- PLUGIN_SNIPPET_FOLDERS.CollectionFormModal = SnippetCollectionFormModal;
- PLUGIN_SNIPPET_FOLDERS.CollectionMenu = SnippetCollectionMenu;
PLUGIN_SNIPPET_FOLDERS.CollectionPermissionsModal =
SnippetCollectionPermissionsModal;
PLUGIN_SNIPPET_FOLDERS.MoveSnippetModal = MoveSnippetModal;
PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS.push((snippetSidebar) => ({
icon: "folder",
name: t`New folder`,
- onClick: () =>
- snippetSidebar.setState({
- modalSnippetCollection: {
- parent_id: canonicalCollectionId(
- snippetSidebar.props.snippetCollection.id,
- ),
- },
- }),
+ onClick: () => {
+ snippetSidebar.props.dispatch(
+ setOpenModalWithProps({
+ id: "collection",
+ props: {
+ initialCollectionId: canonicalCollectionId(
+ snippetSidebar.props.snippetCollection.id,
+ ),
+ namespaces: ["snippets"],
+ pickerOptions: SNIPPET_COLLECTION_PICKER_OPTIONS,
+ showAuthorityLevelPicker: false,
+ shouldNavigateOnCreate: false,
+ },
+ }),
+ );
+ },
}));
- // Add modals
- PLUGIN_SNIPPET_SIDEBAR_MODALS.push(
- (snippetSidebar) =>
- snippetSidebar.state.modalSnippetCollection && (
- <SnippetCollectionFormModal
- collection={snippetSidebar.state.modalSnippetCollection}
- onClose={() =>
- snippetSidebar.setState({ modalSnippetCollection: null })
- }
- onSaved={() => {
- snippetSidebar.setState({ modalSnippetCollection: null });
- }}
- />
- ),
- (snippetSidebar) =>
- snippetSidebar.state.permissionsModalCollectionId != null && (
- <Modal
- onClose={() =>
- snippetSidebar.setState({ permissionsModalCollectionId: null })
- }
- >
- <CollectionPermissionsModal
- params={{
- slug: snippetSidebar.state.permissionsModalCollectionId,
- }}
- onClose={() =>
- snippetSidebar.setState({ permissionsModalCollectionId: null })
- }
- namespace="snippets"
- />
- </Modal>
- ),
- );
-
// Set collection row renderer
PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS.collection = CollectionRow;
// Add header button
- PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.push((snippetSidebar, props) => {
+ PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.push((snippetSidebar) => {
const collection = snippetSidebar.props.snippetCollection;
- const setSidebarState = snippetSidebar.setState.bind(snippetSidebar);
-
return (
- <SnippetCollectionMenu
+ <CollectionRowMenu
+ key="snippet-collection-row-menu"
collection={collection}
- onEditDetails={() => {
- setSidebarState({ modalSnippetCollection: collection });
- }}
- onChangePermissions={() => {
- setSidebarState({ permissionsModalCollectionId: collection.id });
- }}
/>
);
});
@@ -109,7 +71,16 @@ export function initializePlugin() {
*/
export function resetPlugin() {
PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS.length = 0;
- PLUGIN_SNIPPET_SIDEBAR_MODALS.length = 0;
PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS.collection = null;
PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.length = 0;
}
+
+const SNIPPET_COLLECTION_PICKER_OPTIONS = {
+ hasLibrary: false,
+ hasRootCollection: true,
+ hasPersonalCollections: false,
+ hasRecents: false,
+ hasSearch: false,
+ hasConfirmButtons: true,
+ canCreateCollections: false,
+};
diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.ts
index 9d39222f640..1c3ae5069bd 100644
--- a/frontend/src/metabase-types/api/collection.ts
+++ b/frontend/src/metabase-types/api/collection.ts
@@ -31,7 +31,7 @@ export type CollectionId =
| "tenant"
| "trash";
-export type CollectionContentModel = "card" | "dataset" | "metric";
+export type CollectionContentModel = CollectionItemModel;
export type CollectionAuthorityLevel = "official" | null;
@@ -74,6 +74,7 @@ export interface Collection {
personal_owner_id?: UserId;
is_personal?: boolean;
is_sample?: boolean; // true if the collection part of the sample content
+ is_library_root?: boolean;
location: string | null;
effective_location?: string; // location path containing only those collections that the user has permission to access
@@ -112,14 +113,14 @@ export interface CollectionItem {
model: CollectionItemModel;
name: string;
description: string | null;
- archived: boolean;
+ archived?: boolean;
copy?: boolean;
collection_position?: number | null;
collection_preview?: boolean | null;
fully_parameterized?: boolean | null;
based_on_upload?: TableId | null; // only for models
collection?: Collection | null;
- collection_id: CollectionId | null; // parent collection id
+ collection_id?: CollectionId | null; // parent collection id
namespace?: CollectionNamespace; // namespace of the item itself
collection_namespace?: CollectionNamespace; // namespace of the parent collection
display?: VisualizationDisplay;
@@ -132,6 +133,7 @@ export interface CollectionItem {
can_write?: boolean;
can_restore?: boolean;
can_delete?: boolean;
+ is_library_root?: boolean;
can_run_adhoc_query?: boolean; // available only for data picker (#60021)
"last-edit-info"?: LastEditInfo;
location?: string | null;
diff --git a/frontend/src/metabase-types/api/mocks/table.ts b/frontend/src/metabase-types/api/mocks/table.ts
index e44138fa98c..ba1e900db64 100644
--- a/frontend/src/metabase-types/api/mocks/table.ts
+++ b/frontend/src/metabase-types/api/mocks/table.ts
@@ -1,6 +1,6 @@
import type {
BulkTableInfo,
- BulkTableSelection,
+ BulkTableRequest,
BulkTableSelectionInfo,
ForeignKey,
PublishTablesResponse,
@@ -66,8 +66,8 @@ export const createMockBulkTableInfo = (
};
export const createMockBulkTableSelection = (
- opts?: Partial<BulkTableSelection>,
-): BulkTableSelection => {
+ opts?: Partial<BulkTableRequest>,
+): BulkTableRequest => {
return {
...opts,
};
diff --git a/frontend/src/metabase-types/api/search.ts b/frontend/src/metabase-types/api/search.ts
index 10195da6503..09bd086fee4 100644
--- a/frontend/src/metabase-types/api/search.ts
+++ b/frontend/src/metabase-types/api/search.ts
@@ -119,6 +119,7 @@ export interface SearchResult<
based_on_upload?: TableId | null;
"last-edit-info"?: LastEditInfo;
result_metadata?: Field[];
+ collection_id?: CollectionId;
}
export type SearchContext =
diff --git a/frontend/src/metabase-types/api/table.ts b/frontend/src/metabase-types/api/table.ts
index 1724bd43fd9..9d25586173c 100644
--- a/frontend/src/metabase-types/api/table.ts
+++ b/frontend/src/metabase-types/api/table.ts
@@ -162,6 +162,7 @@ export interface UpdateTableRequest {
entity_type?: string | null;
owner_email?: string | null;
owner_user_id?: UserId | null;
+ collection_id?: CollectionId | null;
}
export interface UpdateTableListRequest {
@@ -257,10 +258,11 @@ export interface BulkTableInfo {
is_published: boolean;
}
-export interface BulkTableSelection {
+export interface BulkTableRequest {
database_ids?: DatabaseId[];
schema_ids?: SchemaId[];
table_ids?: TableId[];
+ collection_id?: CollectionId;
}
export interface BulkTableSelectionInfo {
diff --git a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx
index 3a9e0b8703b..c4d4d97c54b 100644
--- a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx
+++ b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx
@@ -196,7 +196,7 @@ const getFolder = (state: State, props: CollectionIdProps) => {
const folderId = getCurrentCollectionId(state, props);
const folders = SnippetCollections.selectors.getList(state);
- return folders.find((folder: Collection) => folder.id === folderId);
+ return folders?.find((folder: Collection) => folder.id === folderId);
};
export const getCollectionEntity = (state: State, props: CollectionIdProps) => {
diff --git a/frontend/src/metabase/api/table.ts b/frontend/src/metabase/api/table.ts
index 0e90edc4913..37da3b50108 100644
--- a/frontend/src/metabase/api/table.ts
+++ b/frontend/src/metabase/api/table.ts
@@ -1,7 +1,7 @@
import { updateMetadata } from "metabase/redux/metadata";
import { ForeignKeySchema, TableSchema } from "metabase/schema";
import type {
- BulkTableSelection,
+ BulkTableRequest,
BulkTableSelectionInfo,
DiscardTablesValuesRequest,
EditTablesRequest,
@@ -166,7 +166,7 @@ export const tableApi = Api.injectEndpoints({
/// DATA STUDIO
getTableSelectionInfo: builder.query<
BulkTableSelectionInfo,
- BulkTableSelection
+ BulkTableRequest
>({
query: (body) => ({
method: "POST",
diff --git a/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx b/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx
index dc50aa0bc3f..a1ea9bc6ed6 100644
--- a/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx
+++ b/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx
@@ -7,7 +7,7 @@ import {
isRootTrashCollection,
} from "metabase/collections/utils";
import { NewItemMenu } from "metabase/common/components/NewItemMenu";
-import { getLibraryCollectionType } from "metabase/data-studio/utils";
+import { PLUGIN_LIBRARY } from "metabase/plugins";
import { Box, Button, Icon, Stack, Text, useMantineTheme } from "metabase/ui";
import type { Collection } from "metabase-types/api";
@@ -84,23 +84,16 @@ const DefaultCollectionEmptyState = ({
};
function getDefaultEmptyStateMessages(collection: Collection | undefined) {
- switch (getLibraryCollectionType(collection?.type)) {
- case "data":
- return {
- title: t`No published tables yet`,
- description: t`Publish tables in the Library to see them here.`,
- };
- case "metrics":
- return {
- title: t`No metrics yet`,
- description: t`Put metrics in the Library to see them here.`,
- };
- default:
- return {
- title: t`This collection is empty`,
- description: t`Use collections to organize questions, dashboards, models, and other collections.`,
- };
+ if (PLUGIN_LIBRARY.isLibrarySubCollectionType(collection?.type)) {
+ return PLUGIN_LIBRARY.getLibraryCollectionEmptyStateMessages(
+ collection.type,
+ );
}
+
+ return {
+ title: t`This collection is empty`,
+ description: t`Use collections to organize questions, dashboards, models, and other collections.`,
+ };
}
export const CollectionEmptyIcon = (): JSX.Element => {
diff --git a/frontend/src/metabase/collections/components/CollectionRowMenu/CollectionRowMenu.tsx b/frontend/src/metabase/collections/components/CollectionRowMenu/CollectionRowMenu.tsx
new file mode 100644
index 00000000000..cd1ed6e0f2c
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionRowMenu/CollectionRowMenu.tsx
@@ -0,0 +1,217 @@
+import { useDisclosure } from "@mantine/hooks";
+import { t } from "ttag";
+
+import {
+ collectionApi,
+ snippetApi,
+ transformApi,
+ useUpdateCollectionMutation,
+} from "metabase/api";
+import { listTag } from "metabase/api/tags";
+import { isRootCollection } from "metabase/collections/utils";
+import { useConfirmation } from "metabase/common/hooks";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ PLUGIN_LIBRARY,
+ PLUGIN_REMOTE_SYNC,
+ PLUGIN_SNIPPET_FOLDERS,
+} from "metabase/plugins";
+import { useDispatch, useSelector } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import { getUserIsAdmin } from "metabase/selectors/user";
+import {
+ ActionIcon,
+ Box,
+ FixedSizeIcon,
+ Icon,
+ Menu,
+ Tooltip,
+} from "metabase/ui";
+import type { Collection, CollectionId } from "metabase-types/api";
+
+import { EditCollectionModal } from "./EditCollectionModal";
+
+type CollectionRowMenuProps = {
+ collection: Collection;
+ onSave?: (details: {
+ previousParentId: CollectionId | null;
+ newParentId: CollectionId | null;
+ }) => void;
+ onArchiveSuccess?: () => void;
+ customArchiveMessage?: string;
+};
+
+export function CollectionRowMenu(props: CollectionRowMenuProps) {
+ const { collection, onArchiveSuccess, onSave, customArchiveMessage } = props;
+ const dispatch = useDispatch();
+
+ const isAdmin = useSelector(getUserIsAdmin);
+ const [updateCollection] = useUpdateCollectionMutation();
+ const remoteSyncReadOnly = useSelector(
+ PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,
+ );
+ const { show, modalContent: confirmationModal } = useConfirmation();
+ const [isEditModalOpen, { toggle: toggleEditModal }] = useDisclosure(false);
+ const [isPermissionsModalOpen, { toggle: togglePermissionsModal }] =
+ useDisclosure(false);
+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
+
+ const showPermissionsOption =
+ isAdmin &&
+ (PLUGIN_LIBRARY.isEnabled || PLUGIN_SNIPPET_FOLDERS.isEnabled) &&
+ collection.namespace !== "transforms";
+
+ const isRoot = isRootCollection(collection);
+
+ if (!collection.can_write || remoteSyncReadOnly) {
+ return null;
+ }
+
+ const invalidateTags = () => {
+ if (collection.namespace === "snippets") {
+ dispatch(snippetApi.util.invalidateTags([listTag("snippet")]));
+ } else if (collection.namespace === "transforms") {
+ dispatch(transformApi.util.invalidateTags([listTag("transform")]));
+ } else {
+ dispatch(collectionApi.util.invalidateTags([listTag("collection")]));
+ }
+ };
+
+ const handleArchive = async () => {
+ try {
+ await updateCollection({ id: collection.id, archived: true }).unwrap();
+ sendSuccessToast(t`"${collection.name}" has been archived`);
+ invalidateTags();
+ onArchiveSuccess?.();
+ } catch {
+ sendErrorToast(t`"${collection.name}" could not be archived`);
+ }
+ };
+
+ const onArchiveClick = () => {
+ show({
+ title: t`Archive "${collection.name}"?`,
+ message: customArchiveMessage,
+ confirmButtonText: t`Archive`,
+ onConfirm: handleArchive,
+ });
+ };
+
+ if (collection.archived) {
+ const handleUnarchive = async () => {
+ try {
+ await updateCollection({ id: collection.id, archived: false }).unwrap();
+ void dispatch(
+ addUndo({
+ message: t`"${collection.name}" has been unarchived`,
+ action: async () => {
+ await updateCollection({ id: collection.id, archived: true });
+ invalidateTags();
+ },
+ }),
+ );
+ invalidateTags();
+ } catch (error) {
+ void dispatch(
+ addUndo({
+ message: t`"${collection.name}" could not be unarchived`,
+ icon: "warning",
+ }),
+ );
+ }
+ };
+
+ const label =
+ collection.namespace === "snippets"
+ ? t`Unarchive snippet folder`
+ : t`Unarchive collection`;
+
+ return (
+ <Tooltip label={label}>
+ <ActionIcon
+ aria-label={label}
+ size="md"
+ onClick={(event) => {
+ event.stopPropagation();
+ void handleUnarchive();
+ }}
+ >
+ <FixedSizeIcon name="unarchive" c="text-primary" />
+ </ActionIcon>
+ </Tooltip>
+ );
+ }
+
+ const optionsLabel =
+ collection.namespace === "snippets"
+ ? t`Snippet folder options`
+ : t`Collection options`;
+
+ return (
+ <Box onClick={(e) => e.stopPropagation()}>
+ <Menu position="bottom-end">
+ <Menu.Target>
+ <Tooltip
+ label={optionsLabel}
+ onClick={(e) => e.stopPropagation()}
+ openDelay={1000}
+ >
+ <ActionIcon aria-label={optionsLabel} size="md">
+ <FixedSizeIcon name="ellipsis" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {!isRoot && (
+ <Menu.Item
+ leftSection={<Icon name="pencil" />}
+ onClick={toggleEditModal}
+ >
+ {collection.namespace === "snippets"
+ ? t`Edit folder details`
+ : t`Edit collection details`}
+ </Menu.Item>
+ )}
+ {showPermissionsOption && (
+ <Menu.Item
+ leftSection={<Icon name="lock" />}
+ onClick={togglePermissionsModal}
+ >
+ {t`Change permissions`}
+ </Menu.Item>
+ )}
+ {!isRoot && (
+ <Menu.Item
+ leftSection={<Icon name="archive" />}
+ onClick={onArchiveClick}
+ c="error"
+ >
+ {t`Archive`}
+ </Menu.Item>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ {confirmationModal}
+ {isEditModalOpen && (
+ <EditCollectionModal
+ collection={collection}
+ onSave={onSave}
+ onClose={toggleEditModal}
+ />
+ )}
+ {isPermissionsModalOpen && collection.namespace === "snippets" && (
+ <PLUGIN_SNIPPET_FOLDERS.CollectionPermissionsModal
+ collectionId={collection.id}
+ onClose={togglePermissionsModal}
+ />
+ )}
+ {isPermissionsModalOpen && collection.namespace !== "snippets" && (
+ <PLUGIN_LIBRARY.CollectionPermissionsModal
+ collectionId={collection.id}
+ namespace={collection.namespace}
+ onClose={togglePermissionsModal}
+ />
+ )}
+ </Box>
+ );
+}
diff --git a/frontend/src/metabase/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx
new file mode 100644
index 00000000000..d10ef85d9bb
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx
@@ -0,0 +1,169 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import { setupUpdateCollectionEndpoint } from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks/state";
+import type { Collection, EnterpriseSettings } from "metabase-types/api";
+import {
+ createMockCollection,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { CollectionRowMenu } from "./CollectionRowMenu";
+
+interface SetupOptions {
+ remoteSyncType?: EnterpriseSettings["remote-sync-type"];
+ collection?: Partial<Collection>;
+ isAdmin?: boolean;
+ onArchiveSuccess?: () => void;
+ customArchiveMessage?: string;
+}
+
+const setup = ({
+ remoteSyncType,
+ collection,
+ isAdmin = true,
+ onArchiveSuccess,
+ customArchiveMessage,
+}: SetupOptions = {}) => {
+ const state = createMockState({
+ settings: mockSettings({
+ "remote-sync-type": remoteSyncType,
+ "remote-sync-enabled": !!remoteSyncType,
+ "token-features": createMockTokenFeatures({
+ library: true,
+ remote_sync: true,
+ }),
+ }),
+ currentUser: createMockUser({ is_superuser: isAdmin }),
+ });
+ setupEnterpriseOnlyPlugin("library");
+ setupEnterpriseOnlyPlugin("remote_sync");
+
+ return renderWithProviders(
+ <CollectionRowMenu
+ collection={createMockCollection(collection)}
+ customArchiveMessage={customArchiveMessage}
+ onArchiveSuccess={onArchiveSuccess}
+ />,
+ {
+ storeInitialState: state,
+ },
+ );
+};
+
+describe("CollectionRowMenu", () => {
+ it("renders collection options menu", async () => {
+ setup();
+ await openMenu();
+ expect(getMenuItem(/Archive/)).toBeInTheDocument();
+ expect(getMenuItem(/Edit collection details/)).toBeInTheDocument();
+ expect(getMenuItem(/Change permissions/)).toBeInTheDocument();
+ });
+
+ it("does not render archive and edit options when collection is root", async () => {
+ setup({ collection: { id: "root" } });
+ await openMenu();
+ expect(queryMenuItem(/Archive/)).not.toBeInTheDocument();
+ expect(queryMenuItem(/Edit collection details/)).not.toBeInTheDocument();
+ });
+
+ it("does not render the change permissions item for non-admins", async () => {
+ setup({ isAdmin: false });
+ await openMenu();
+ expect(queryMenuItem(/Change permissions/)).not.toBeInTheDocument();
+ });
+
+ it("renders nothing if collection is not writable", () => {
+ setup({ collection: { can_write: false } });
+ expect(
+ screen.queryByRole("button", { name: "Collection options" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders nothing if remote sync is set to read-only", () => {
+ setup({ remoteSyncType: "read-only" });
+ expect(
+ screen.queryByRole("button", { name: "Collection options" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("uses snippet folder labels for snippet collections", async () => {
+ setup({ collection: { namespace: "snippets" } });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Snippet folder options" }),
+ );
+
+ expect(getMenuItem(/Edit folder details/)).toBeInTheDocument();
+ });
+
+ it("does not render permissions option for transform collections", async () => {
+ setup({ collection: { namespace: "transforms" } });
+
+ await openMenu();
+
+ expect(queryMenuItem(/Change permissions/)).not.toBeInTheDocument();
+ });
+
+ it("archives a collection after confirmation", async () => {
+ const collection = createMockCollection({ id: 1, name: "Archived soon" });
+ const onArchiveSuccess = jest.fn();
+ setupUpdateCollectionEndpoint(collection);
+ setup({
+ collection,
+ customArchiveMessage: "Custom archive warning",
+ onArchiveSuccess,
+ });
+
+ await openMenu();
+ await userEvent.click(getMenuItem(/Archive/));
+
+ expect(
+ await screen.findByText('Archive "Archived soon"?'),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Custom archive warning")).toBeInTheDocument();
+ await userEvent.click(screen.getByRole("button", { name: "Archive" }));
+
+ await waitFor(() => expect(onArchiveSuccess).toHaveBeenCalled());
+ const request = fetchMock.callHistory.lastCall(
+ "update-collection-1",
+ )?.request;
+ expect(await request?.json()).toEqual({ archived: true });
+ });
+
+ it("unarchives an archived collection", async () => {
+ const collection = createMockCollection({
+ id: 1,
+ name: "Archived collection",
+ archived: true,
+ });
+ setupUpdateCollectionEndpoint(collection);
+ setup({ collection });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Unarchive collection" }),
+ );
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("update-collection-1")).toBe(true);
+ });
+ const request = fetchMock.callHistory.lastCall(
+ "update-collection-1",
+ )?.request;
+ expect(await request?.json()).toEqual({ archived: false });
+ });
+});
+
+const openMenu = async () => {
+ await userEvent.click(
+ screen.getByRole("button", { name: "Collection options" }),
+ );
+};
+const getMenuItem = (name: RegExp) => screen.getByRole("menuitem", { name });
+const queryMenuItem = (name: RegExp) =>
+ screen.queryByRole("menuitem", { name });
diff --git a/frontend/src/metabase/transforms/components/EditTransformCollectionModal/EditTransformCollectionModal.tsx b/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx
similarity index 51%
rename from frontend/src/metabase/transforms/components/EditTransformCollectionModal/EditTransformCollectionModal.tsx
rename to frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx
index 959cec33dcf..a7843016e30 100644
--- a/frontend/src/metabase/transforms/components/EditTransformCollectionModal/EditTransformCollectionModal.tsx
+++ b/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx
@@ -1,20 +1,18 @@
-import { useCallback, useMemo } from "react";
+import { type KeyboardEvent, useCallback, useMemo } from "react";
import { t } from "ttag";
-import {
- useGetCollectionQuery,
- useUpdateCollectionMutation,
-} from "metabase/api";
-import { getErrorMessage } from "metabase/api/utils";
+import { useUpdateCollectionMutation } from "metabase/api";
import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker";
import {
COLLECTION_FORM_SCHEMA,
type CollectionFormValues,
} from "metabase/collections/schemas";
-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import type { OmniPickerItem } from "metabase/common/components/Pickers";
+import type { EntityType } from "metabase/collections/utils";
+import type {
+ EntityPickerOptions,
+ OmniPickerItem,
+} from "metabase/common/components/Pickers";
import { isItemInCollectionOrItsDescendants } from "metabase/common/components/Pickers/utils";
-import { useToast } from "metabase/common/hooks";
import {
Form,
FormErrorMessage,
@@ -24,35 +22,34 @@ import {
FormTextarea,
} from "metabase/forms";
import { Button, Group, Modal, Stack } from "metabase/ui";
+import type {
+ Collection,
+ CollectionId,
+ CollectionItem,
+} from "metabase-types/api";
-type EditTransformCollectionModalProps = {
- collectionId: number;
+type EditCollectionModalProps = {
+ collection: Collection | CollectionItem;
onClose: () => void;
- onSave?: () => void;
+ onSave?: (details: {
+ previousParentId: CollectionId | null;
+ newParentId: CollectionId | null;
+ }) => void;
};
-export function EditTransformCollectionModal({
- collectionId,
- onClose,
- onSave,
-}: EditTransformCollectionModalProps) {
- const [sendToast] = useToast();
- const [updateCollection] = useUpdateCollectionMutation();
-
- const {
- data: collection,
- isLoading,
- error,
- } = useGetCollectionQuery({
- id: collectionId,
- namespace: "transforms",
- });
+const isCollectionItem = (
+ collection: Collection | CollectionItem,
+): collection is CollectionItem => {
+ return "collection_id" in collection;
+};
+export function EditCollectionModal(props: EditCollectionModalProps) {
+ const { collection, onClose, onSave } = props;
+ const [updateCollection] = useUpdateCollectionMutation();
const initialValues = useMemo<CollectionFormValues>(() => {
- if (!collection) {
- return COLLECTION_FORM_SCHEMA.getDefault();
- }
- const parentId = collection.parent_id;
+ const parentId = isCollectionItem(collection)
+ ? collection.collection_id
+ : collection.parent_id;
return {
name: collection.name ?? "",
description: collection.description ?? null,
@@ -62,53 +59,35 @@ export function EditTransformCollectionModal({
const handleSubmit = useCallback(
async (values: CollectionFormValues) => {
- try {
- await updateCollection({
- id: collectionId,
- name: values.name,
- description: values.description ?? undefined,
- parent_id: values.parent_id,
- }).unwrap();
- onSave?.();
- onClose();
- } catch (err) {
- sendToast({
- message: getErrorMessage(err, t`Failed to update collection`),
- icon: "warning",
- });
- }
+ await updateCollection({
+ id: collection.id,
+ name: values.name,
+ description: values.description ?? undefined,
+ parent_id: values.parent_id,
+ }).unwrap();
+ onSave?.({
+ previousParentId: initialValues.parent_id,
+ newParentId: values.parent_id,
+ });
+ onClose();
},
- [collectionId, updateCollection, onSave, onClose, sendToast],
+ [collection.id, initialValues.parent_id, updateCollection, onSave, onClose],
);
const shouldDisableItem = useCallback(
(item: OmniPickerItem) =>
- isItemInCollectionOrItsDescendants(item, collectionId),
- [collectionId],
+ isItemInCollectionOrItsDescendants(item, collection.id),
+ [collection.id],
);
const stopPropagation = useCallback(
- (e: React.KeyboardEvent) => e.stopPropagation(),
+ (e: KeyboardEvent) => e.stopPropagation(),
[],
);
- if (isLoading || error) {
- return (
- <Modal
- title={t`Edit collection`}
- opened
- onClose={onClose}
- padding="xl"
- onKeyDown={stopPropagation}
- >
- <LoadingAndErrorWrapper loading={isLoading} error={error} />
- </Modal>
- );
- }
-
return (
<Modal
- title={t`Editing ${collection?.name}`}
+ title={t`Editing ${collection.name}`}
opened
onClose={onClose}
padding="xl"
@@ -138,9 +117,14 @@ export function EditTransformCollectionModal({
<FormCollectionPicker
name="parent_id"
title={t`Parent collection`}
+ entityType={getPickerEntityType(collection.type)}
collectionPickerModalProps={{
+ options: pickerOptions,
isDisabledItem: shouldDisableItem,
- namespaces: ["transforms"],
+ namespaces: collection.namespace
+ ? [collection.namespace]
+ : [],
+ disableRecentLogging: true,
}}
/>
<Group justify="flex-end">
@@ -159,3 +143,27 @@ export function EditTransformCollectionModal({
</Modal>
);
}
+
+function getPickerEntityType(
+ collectionType: Collection["type"] | CollectionItem["type"],
+): EntityType | undefined {
+ if (collectionType === "library-data") {
+ return "table";
+ }
+
+ if (collectionType === "library-metrics") {
+ return "metric";
+ }
+
+ return undefined;
+}
+
+const pickerOptions: EntityPickerOptions = {
+ hasLibrary: true,
+ hasRootCollection: false,
+ hasPersonalCollections: false,
+ hasRecents: false,
+ hasSearch: false,
+ hasConfirmButtons: true,
+ canCreateCollections: true,
+};
diff --git a/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.unit.spec.tsx
new file mode 100644
index 00000000000..2c635870589
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.unit.spec.tsx
@@ -0,0 +1,118 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupCollectionByIdEndpoint,
+ setupUpdateCollectionEndpoint,
+} from "__support__/server-mocks";
+import { createMockEntitiesState } from "__support__/store";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import type { Collection, CollectionItem } from "metabase-types/api";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+} from "metabase-types/api/mocks";
+
+import { EditCollectionModal } from "./EditCollectionModal";
+
+const parentCollection = createMockCollection({
+ id: 22,
+ name: "Parent Collection",
+ can_write: true,
+});
+
+const itemParentCollection = createMockCollection({
+ id: 33,
+ name: "Item Parent Collection",
+ can_write: true,
+});
+
+function setup(collection: Collection | CollectionItem) {
+ const onClose = jest.fn();
+ const onSave = jest.fn();
+
+ setupUpdateCollectionEndpoint(collection as Collection);
+ setupCollectionByIdEndpoint({
+ collections: [parentCollection, itemParentCollection],
+ });
+
+ renderWithProviders(
+ <EditCollectionModal
+ collection={collection}
+ onClose={onClose}
+ onSave={onSave}
+ />,
+ {
+ storeInitialState: createMockState({
+ entities: createMockEntitiesState({
+ collections: [parentCollection, itemParentCollection],
+ }),
+ }),
+ },
+ );
+
+ return { onClose, onSave };
+}
+
+describe("EditCollectionModal", () => {
+ it("submits collection details using Collection.parent_id", async () => {
+ const collection = createMockCollection({
+ id: 1,
+ name: "Original name",
+ description: "Original description",
+ parent_id: parentCollection.id,
+ });
+ const { onClose, onSave } = setup(collection);
+
+ await userEvent.clear(screen.getByLabelText("Name"));
+ await userEvent.type(screen.getByLabelText("Name"), "Updated name");
+ await userEvent.clear(screen.getByLabelText("Description"));
+ await userEvent.type(
+ screen.getByLabelText("Description"),
+ "Updated description",
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(onSave).toHaveBeenCalledWith({
+ previousParentId: parentCollection.id,
+ newParentId: parentCollection.id,
+ });
+ const request = fetchMock.callHistory.lastCall(
+ "update-collection-1",
+ )?.request;
+ expect(await request?.json()).toEqual({
+ name: "Updated name",
+ description: "Updated description",
+ parent_id: parentCollection.id,
+ });
+ });
+
+ it("submits collection details using CollectionItem.collection_id", async () => {
+ const collectionItem = createMockCollectionItem({
+ id: 2,
+ model: "collection",
+ name: "Collection item",
+ collection_id: itemParentCollection.id as number,
+ }) as CollectionItem;
+ const { onSave } = setup(collectionItem);
+
+ await userEvent.clear(screen.getByLabelText("Name"));
+ await userEvent.type(screen.getByLabelText("Name"), "Updated item name");
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => expect(onSave).toHaveBeenCalled());
+ expect(onSave).toHaveBeenCalledWith({
+ previousParentId: itemParentCollection.id,
+ newParentId: itemParentCollection.id,
+ });
+ const request = fetchMock.callHistory.lastCall(
+ "update-collection-2",
+ )?.request;
+ expect(await request?.json()).toEqual({
+ name: "Updated item name",
+ parent_id: itemParentCollection.id,
+ });
+ });
+});
diff --git a/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/index.ts b/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/index.ts
new file mode 100644
index 00000000000..e7aad259751
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionRowMenu/EditCollectionModal/index.ts
@@ -0,0 +1 @@
+export { EditCollectionModal } from "./EditCollectionModal";
diff --git a/frontend/src/metabase/collections/components/CollectionRowMenu/index.ts b/frontend/src/metabase/collections/components/CollectionRowMenu/index.ts
new file mode 100644
index 00000000000..887932828dd
--- /dev/null
+++ b/frontend/src/metabase/collections/components/CollectionRowMenu/index.ts
@@ -0,0 +1 @@
+export * from "./CollectionRowMenu";
diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx
index b3c34a6b458..2f695455a43 100644
--- a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx
+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import type { WithRouterProps } from "react-router";
import { withRouter } from "react-router";
import { t } from "ttag";
@@ -15,6 +15,7 @@ import { FormInput } from "metabase/common/components/FormInput";
import { FormSubmitButton } from "metabase/common/components/FormSubmitButton";
import { FormTextArea } from "metabase/common/components/FormTextArea";
import type {
+ EntityPickerOptions,
FilterItemsInPersonalCollection,
OmniPickerItem,
} from "metabase/common/components/Pickers";
@@ -24,7 +25,7 @@ import { PLUGIN_TENANTS } from "metabase/plugins";
import { connect } from "metabase/redux";
import { Flex } from "metabase/ui";
import * as Errors from "metabase/utils/errors";
-import type { Collection } from "metabase-types/api";
+import type { Collection, CollectionNamespace } from "metabase-types/api";
import { FormAuthorityLevelField } from "../../containers/FormAuthorityLevelFieldContainer";
@@ -43,14 +44,18 @@ export interface CreateCollectionProperties {
name: string;
description: string | null;
parent_id: Collection["id"] | null;
+ namespace?: CollectionNamespace;
}
export interface CreateCollectionFormOwnProps {
collectionId?: Collection["id"]; // can be used by `getInitialCollectionId`
+ initialCollectionId?: Collection["id"];
onSubmit: (collection: CreateCollectionProperties) => void;
onCancel?: () => void;
filterPersonalCollections?: FilterItemsInPersonalCollection;
showCollectionPicker?: boolean;
+ pickerOptions?: EntityPickerOptions;
+ namespaces?: CollectionNamespace[];
showAuthorityLevelPicker?: boolean;
}
@@ -70,19 +75,24 @@ const mapDispatchToProps = {
function CreateCollectionForm({
collectionId,
+ initialCollectionId: explicitInitialCollectionId,
location,
params,
onSubmit,
onCancel,
filterPersonalCollections,
showCollectionPicker = true,
+ pickerOptions,
+ namespaces,
showAuthorityLevelPicker = true,
}: Props) {
- const initialCollectionId = useInitialCollectionId({
+ const defaultInitialCollectionId = useInitialCollectionId({
collectionId,
location,
params,
});
+ const initialCollectionId =
+ explicitInitialCollectionId ?? defaultInitialCollectionId;
const initialValues = useMemo(
() => ({
...COLLECTION_SCHEMA.getDefault(),
@@ -98,11 +108,27 @@ function CreateCollectionForm({
const [selectedParentCollection, setSelectedParentCollection] =
useState<OmniPickerItem | null>(null);
+ const handleSubmit = useCallback(
+ (values: CreateCollectionProperties) => {
+ const parentCollection = selectedParentCollection ?? initialCollection;
+ const namespace =
+ parentCollection && "namespace" in parentCollection
+ ? parentCollection.namespace
+ : namespaces?.[0];
+
+ onSubmit({
+ ...values,
+ namespace: namespace ?? undefined,
+ });
+ },
+ [initialCollection, namespaces, onSubmit, selectedParentCollection],
+ );
+
return (
<FormProvider
initialValues={initialValues}
validationSchema={COLLECTION_SCHEMA}
- onSubmit={onSubmit}
+ onSubmit={handleSubmit}
>
{({ dirty }) => {
const parentCollection = selectedParentCollection ?? initialCollection;
@@ -130,18 +156,22 @@ function CreateCollectionForm({
/>
{showCollectionPicker && (
<FormCollectionPicker
- name="parent_id"
- title={t`Collection it's saved in`}
- filterPersonalCollections={filterPersonalCollections}
+ collectionPickerModalProps={{
+ options: pickerOptions,
+ namespaces,
+ }}
entityType="collection"
- onCollectionSelect={setSelectedParentCollection}
+ filterPersonalCollections={filterPersonalCollections}
mb="1rem"
+ name="parent_id"
+ onCollectionSelect={setSelectedParentCollection}
+ title={t`Collection it's saved in`}
/>
)}
{showAuthorityLevelPicker && !isParentTenantCollection && (
<FormAuthorityLevelField />
)}
- <FormFooter>
+ <FormFooter mt="lg">
<FormErrorMessage inline />
<Flex style={{ flexShrink: 1 }} justify="flex-end" gap="sm">
{!!onCancel && (
diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/common.unit.spec.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/common.unit.spec.tsx
index 5fc5f29ff2a..0f5ff016d77 100644
--- a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/common.unit.spec.tsx
@@ -21,6 +21,13 @@ describe("CreateCollectionForm", () => {
expect(screen.getByRole("button", { name: "Create" })).toBeInTheDocument();
});
+ it("uses the explicit initial collection id", async () => {
+ setup({ initialCollectionId: 2 });
+
+ expect(await screen.findByText("Data")).toBeInTheDocument();
+ expect(screen.queryByText("Our analytics")).not.toBeInTheDocument();
+ });
+
it("can't submit if name is empty", () => {
setup();
expect(screen.getByRole("button", { name: "Create" })).toBeDisabled();
@@ -36,4 +43,19 @@ describe("CreateCollectionForm", () => {
setup();
expect(screen.queryByLabelText("Collection type")).not.toBeInTheDocument();
});
+
+ it("submits the namespace from the initial parent collection", async () => {
+ const { onSubmit } = setup({
+ initialCollectionId: 2,
+ parentCollectionNamespace: "snippets",
+ namespaces: ["snippets"],
+ });
+
+ await userEvent.type(screen.getByLabelText("Name"), "My snippets folder");
+ await userEvent.click(screen.getByRole("button", { name: "Create" }));
+
+ expect(onSubmit).toHaveBeenCalledWith(
+ expect.objectContaining({ namespace: "snippets" }),
+ );
+ });
});
diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsx
index e069f2129c7..6be15c274d3 100644
--- a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsx
+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsx
@@ -9,6 +9,7 @@ import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
import type {
+ CollectionId,
CollectionNamespace,
TokenFeatures,
User,
@@ -33,6 +34,9 @@ export interface SetupOpts {
showAuthorityLevelPicker?: boolean;
enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
parentCollectionNamespace?: CollectionNamespace | null;
+ initialCollectionId?: CollectionId;
+ namespaces?: CollectionNamespace[];
+ onSubmit?: jest.Mock;
}
export const setup = ({
@@ -41,6 +45,9 @@ export const setup = ({
showAuthorityLevelPicker,
enterprisePlugins,
parentCollectionNamespace,
+ initialCollectionId,
+ namespaces,
+ onSubmit = jest.fn(),
}: SetupOpts = {}) => {
const settings = mockSettings({ "token-features": tokenFeatures });
const onCancel = jest.fn();
@@ -60,6 +67,18 @@ export const setup = ({
? [ROOT_COLLECTION, parentCollection]
: [ROOT_COLLECTION];
+ const initialCollection = initialCollectionId
+ ? createMockCollection({
+ id: initialCollectionId,
+ name: "Data",
+ can_write: true,
+ namespace: parentCollectionNamespace,
+ })
+ : null;
+ const endpointCollections = initialCollection
+ ? [...collections, initialCollection]
+ : collections;
+
if (enterprisePlugins) {
enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
}
@@ -71,14 +90,17 @@ export const setup = ({
// Mock individual collection fetches
setupCollectionByIdEndpoint({
- collections,
+ collections: endpointCollections,
});
renderWithProviders(
<CreateCollectionForm
onCancel={onCancel}
+ onSubmit={onSubmit}
showAuthorityLevelPicker={showAuthorityLevelPicker}
collectionId={parentCollectionNamespace !== undefined ? 1 : undefined}
+ initialCollectionId={initialCollectionId}
+ namespaces={namespaces}
/>,
{
storeInitialState: createMockState({
@@ -91,5 +113,5 @@ export const setup = ({
},
);
- return { onCancel };
+ return { onCancel, onSubmit };
};
diff --git a/frontend/src/metabase/collections/containers/CreateCollectionModal.tsx b/frontend/src/metabase/collections/containers/CreateCollectionModal.tsx
index 29535548a66..3405715da23 100644
--- a/frontend/src/metabase/collections/containers/CreateCollectionModal.tsx
+++ b/frontend/src/metabase/collections/containers/CreateCollectionModal.tsx
@@ -5,6 +5,7 @@ import { t } from "ttag";
import { useEscapeToCloseModal } from "metabase/common/hooks/use-escape-to-close-modal";
import { Collections } from "metabase/entities/collections";
+import { PLUGIN_LIBRARY } from "metabase/plugins";
import { connect } from "metabase/redux";
import type { State } from "metabase/redux/store";
import { Modal } from "metabase/ui";
@@ -14,13 +15,15 @@ import type { Collection } from "metabase-types/api";
import type { CreateCollectionFormOwnProps } from "../components/CreateCollectionForm";
import { CreateCollectionForm } from "../components/CreateCollectionForm";
import type { CreateCollectionProperties } from "../components/CreateCollectionForm/CreateCollectionForm";
+import { getCollectionPathAsArray } from "../utils";
-interface CreateCollectionModalOwnProps extends Omit<
+export interface CreateCollectionModalOwnProps extends Omit<
CreateCollectionFormOwnProps,
"onCancel" | "onSubmit"
> {
onCreate?: (collection: Collection) => void;
onClose: () => void;
+ shouldNavigateOnCreate?: boolean;
}
interface CreateCollectionModalDispatchProps {
@@ -42,21 +45,46 @@ function CreateCollectionModal({
onChangeLocation,
onClose,
handleCreateCollection,
+ shouldNavigateOnCreate = true,
...props
}: Props) {
const handleCreate = useCallback(
async (values: CreateCollectionProperties) => {
const action = await handleCreateCollection(values);
- const collection = Collections.HACK_getObjectFromAction(action);
+ const collection: Collection =
+ Collections.HACK_getObjectFromAction(action);
if (typeof onCreate === "function") {
onCreate(collection);
+ onClose();
} else {
onClose();
- onChangeLocation(Urls.collection(collection));
+
+ if (!shouldNavigateOnCreate) {
+ return;
+ }
+
+ let visitUrl = Urls.collection(collection);
+
+ if (
+ PLUGIN_LIBRARY.isLibraryCollectionType(collection.type) ||
+ collection.namespace === "snippets"
+ ) {
+ visitUrl = Urls.dataStudioLibrary({
+ expandedIds: getCollectionPathAsArray(collection),
+ });
+ }
+
+ onChangeLocation(visitUrl);
}
},
- [onCreate, onChangeLocation, onClose, handleCreateCollection],
+ [
+ handleCreateCollection,
+ onCreate,
+ onClose,
+ onChangeLocation,
+ shouldNavigateOnCreate,
+ ],
);
useEscapeToCloseModal(onClose);
diff --git a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx
index 5981eb50154..95d695f16ec 100644
--- a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx
+++ b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx
@@ -1,6 +1,7 @@
import { useField } from "formik";
import { useCallback, useEffect, useMemo, useState } from "react";
import { t } from "ttag";
+import _ from "underscore";
import {
type EntityType,
@@ -9,13 +10,13 @@ import {
isValidCollectionId,
} from "metabase/collections/utils";
import { CollectionName } from "metabase/common/components/CollectionName";
-import type {
- EntityPickerOptions,
- EntityPickerProps,
- FilterItemsInPersonalCollection,
- OmniPickerItem,
+import {
+ CollectionPickerModal,
+ type EntityPickerModalProps,
+ type EntityPickerOptions,
+ type FilterItemsInPersonalCollection,
+ type OmniPickerItem,
} from "metabase/common/components/Pickers";
-import { CollectionPickerModal } from "metabase/common/components/Pickers";
import { SnippetCollectionName } from "metabase/common/components/SnippetCollectionName";
import { TransformCollectionName } from "metabase/common/components/TransformCollectionName";
import { useUniqueId } from "metabase/common/hooks/use-unique-id";
@@ -33,7 +34,7 @@ interface FormCollectionPickerProps extends InputWrapperProps {
onOpenCollectionChange?: (collectionId: CollectionId) => void;
filterPersonalCollections?: FilterItemsInPersonalCollection;
entityType?: EntityType;
- collectionPickerModalProps?: Partial<EntityPickerProps>;
+ collectionPickerModalProps?: Partial<EntityPickerModalProps>;
onCollectionSelect?: (collection: OmniPickerItem) => void;
}
@@ -120,7 +121,7 @@ function FormCollectionPicker({
const nonDefaultNamespace =
collectionPickerModalProps?.namespaces?.[0] ?? null;
- const options = useMemo<EntityPickerOptions>( // FIXME, this should throw more type errors 🤔
+ const defaultOptions = useMemo<EntityPickerOptions>( // FIXME, this should throw more type errors 🤔
() => ({
hasPersonalCollections:
!nonDefaultNamespace && filterPersonalCollections !== "exclude",
@@ -193,9 +194,9 @@ function FormCollectionPicker({
}}
onChange={handleChange}
onClose={() => setIsPickerOpen(false)}
- options={options}
+ options={collectionPickerModalProps?.options || defaultOptions}
entityType={entityType}
- {...collectionPickerModalProps}
+ {..._.omit(collectionPickerModalProps, ["options"])}
/>
)}
</>
diff --git a/frontend/src/metabase/collections/hooks.ts b/frontend/src/metabase/collections/hooks.ts
index 6b402bcbe13..2e47205f392 100644
--- a/frontend/src/metabase/collections/hooks.ts
+++ b/frontend/src/metabase/collections/hooks.ts
@@ -10,11 +10,7 @@ import { getUserPersonalCollectionId } from "metabase/selectors/user";
import * as Urls from "metabase/urls/collections";
import type { Collection, CollectionId } from "metabase-types/api";
-import {
- canonicalCollectionId,
- isLibraryCollection,
- isRootTrashCollection,
-} from "./utils";
+import { canonicalCollectionId, isRootTrashCollection } from "./utils";
export type UseInitialCollectionIdProps = {
collectionId?: Collection["id"] | null;
@@ -105,7 +101,7 @@ export function useInitialCollectionId({
if (collection == null || isRootTrashCollection(collection)) {
continue;
}
- if (collection.can_write && !isLibraryCollection(collection)) {
+ if (collection.can_write) {
return canonicalCollectionId(collection.id);
}
}
diff --git a/frontend/src/metabase/collections/utils.ts b/frontend/src/metabase/collections/utils.ts
index 2f15ce2e20a..4cbb7a478d6 100644
--- a/frontend/src/metabase/collections/utils.ts
+++ b/frontend/src/metabase/collections/utils.ts
@@ -3,10 +3,9 @@ import { t } from "ttag";
import {
canPlaceEntityInCollection as canPlaceEntityInCollectionImpl,
canPlaceEntityInCollectionOrDescendants as canPlaceEntityInCollectionOrDescendantsImpl,
- getLibraryCollectionType,
} from "metabase/data-studio/utils";
import { ROOT_COLLECTION } from "metabase/entities/collections";
-import { PLUGIN_COLLECTIONS } from "metabase/plugins";
+import { PLUGIN_COLLECTIONS, PLUGIN_LIBRARY } from "metabase/plugins";
import {
type CardType,
type Collection,
@@ -129,7 +128,7 @@ export function isSyncedCollection(collection: Partial<Collection>): boolean {
export function isLibraryCollection(
collection: Pick<Collection, "type">,
): boolean {
- return getLibraryCollectionType(collection.type) != null;
+ return PLUGIN_LIBRARY.isLibraryCollectionType(collection.type);
}
export function isExamplesCollection(collection: Collection): boolean {
@@ -375,3 +374,8 @@ export const getCollectionPathAsString = (collection: CollectionEssentials) => {
};
export const collectionPathSeparator = "/";
+
+export const getCollectionPathAsArray = (collection: Collection): string[] => {
+ const parentIds = (collection.location ?? "").split("/").filter(Boolean);
+ return [...parentIds, String(collection.id)];
+};
diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal.tsx
index 5def29fa0b7..1180497e746 100644
--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal.tsx
+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal.tsx
@@ -109,7 +109,7 @@ export const CollectionPickerModal = ({
const handleChange = (newItem: OmniPickerItem) => {
if (canSelectItem(newItem)) {
- onChange(newItem);
+ return onChange(newItem);
}
};
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPickerModal.tsx
index 91318c3b470..bcd875892f7 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPickerModal.tsx
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPickerModal.tsx
@@ -46,6 +46,7 @@ export type EntityPickerModalProps = {
value?: OmniPickerValue;
onClose: () => void;
recentsContext?: RecentContexts[];
+ disableRecentLogging?: boolean;
options?: EntityPickerOptions;
} & Omit<
EntityPickerProps,
@@ -64,6 +65,7 @@ export function EntityPickerModal({
options,
onClose,
onChange,
+ disableRecentLogging,
...rest
}: EntityPickerModalProps) {
const [modalContentMinWidth, setModalContentMinWidth] = useState(920);
@@ -97,9 +99,12 @@ export function EntityPickerModal({
return;
}
await onChange(item);
- tryLogRecentItem(item);
+
+ if (!disableRecentLogging) {
+ tryLogRecentItem(item);
+ }
},
- [isDialogOpen, onChange, tryLogRecentItem],
+ [disableRecentLogging, isDialogOpen, onChange, tryLogRecentItem],
);
useWindowEvent(
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/CollectionItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/CollectionItemList.tsx
index 25ae38044b1..caec018ae99 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/CollectionItemList.tsx
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/CollectionItemList.tsx
@@ -1,4 +1,6 @@
import { useListCollectionItemsQuery } from "metabase/api";
+import { PLUGIN_LIBRARY } from "metabase/plugins";
+import type { CollectionItem } from "metabase-types/api";
import { useOmniPickerContext } from "../../context";
import type { OmniPickerItem } from "../../types";
@@ -20,7 +22,7 @@ export const CollectionItemList = ({
error,
isLoading,
} = useListCollectionItemsQuery({
- id: !parentItem.id ? "root" : parentItem.id,
+ id: getCollectionItemsParentId(parentItem),
namespace:
"namespace" in parentItem && !!parentItem.namespace
? parentItem.namespace
@@ -28,12 +30,52 @@ export const CollectionItemList = ({
...getCollectionItemsOptions({ models }),
});
+ const items = getCollectionItems({
+ parentItem,
+ items: collectionItems?.data,
+ });
+
return (
<ItemList
- items={collectionItems?.data}
+ items={items}
pathIndex={pathIndex}
isLoading={isLoading}
error={error}
/>
);
};
+
+function getCollectionItemsParentId(parentItem: OmniPickerItem) {
+ if (parentItem.model === "collection" && parentItem.sourceCollectionId) {
+ return parentItem.sourceCollectionId;
+ }
+
+ return !parentItem.id ? "root" : parentItem.id;
+}
+
+function getCollectionItems({
+ parentItem,
+ items,
+}: {
+ parentItem: OmniPickerItem;
+ items?: CollectionItem[];
+}): OmniPickerItem[] | undefined {
+ if (!items || parentItem.model !== "collection") {
+ return items;
+ }
+
+ if (parentItem.childTypeFilter) {
+ return items.filter(
+ (item) =>
+ item.model !== "collection" || item.type === parentItem.childTypeFilter,
+ );
+ }
+
+ if (parentItem.type === "library") {
+ return (
+ PLUGIN_LIBRARY.getCollectionPickerItems({ parentItem, items }) ?? items
+ );
+ }
+
+ return items;
+}
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/EntityPickerModal.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/EntityPickerModal.unit.spec.tsx
index 4046d255656..7aafe706aa4 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/EntityPickerModal.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/EntityPickerModal.unit.spec.tsx
@@ -2,6 +2,12 @@ import userEvent from "@testing-library/user-event";
import { findRequests } from "__support__/server-mocks";
import { screen, waitFor, within } from "__support__/ui";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+} from "metabase-types/api/mocks";
+
+import type { OmniPickerItem } from "../../types";
import { setup } from "./setup";
@@ -26,6 +32,122 @@ const expectVisibleItem = async (itemName: string) =>
).toBeVisible(),
);
+const libraryCollection = createMockCollection({
+ id: 9,
+ name: "Library",
+ type: "library",
+ can_write: false,
+ location: "/",
+ here: ["collection"],
+ below: ["table"],
+});
+
+const hiddenDataCollection = createMockCollection({
+ id: 10,
+ name: "Data",
+ type: "library-data",
+ can_write: false,
+ location: "/9/",
+});
+
+const promotedDataCollection = createMockCollection({
+ id: 28,
+ name: "LibraryCollection3",
+ type: "library-data",
+ can_write: false,
+ location: "/9/10/",
+ effective_location: "/9/",
+ here: ["collection"],
+ below: ["table", "collection"],
+});
+
+const writableNestedDataCollection = createMockCollection({
+ id: 24,
+ name: "LibraryCollection1",
+ type: "library-data",
+ can_write: true,
+ location: "/9/10/28/",
+ effective_location: "/9/28/",
+ here: ["collection"],
+ below: ["table", "collection"],
+});
+
+const libraryRootItems = [
+ createMockCollectionItem({
+ id: promotedDataCollection.id as number,
+ model: "collection",
+ name: promotedDataCollection.name,
+ type: "library-data",
+ can_write: false,
+ collection_id: libraryCollection.id as number,
+ location: "/9/10/",
+ effective_location: "/9/",
+ here: ["collection"],
+ below: ["table", "collection"],
+ }),
+ createMockCollectionItem({
+ id: 30,
+ model: "collection",
+ name: "LibraryCollection5",
+ type: "library-data",
+ can_write: true,
+ collection_id: libraryCollection.id as number,
+ location: "/9/10/",
+ effective_location: "/9/",
+ }),
+ createMockCollectionItem({
+ id: 11,
+ model: "collection",
+ name: "Metrics",
+ type: "library-metrics",
+ is_library_root: true,
+ can_write: false,
+ collection_id: libraryCollection.id as number,
+ location: "/9/",
+ effective_location: "/9/",
+ here: ["collection"],
+ below: ["collection"],
+ }),
+];
+
+const promotedDataCollectionItems = [
+ createMockCollectionItem({
+ id: writableNestedDataCollection.id as number,
+ model: "collection",
+ name: writableNestedDataCollection.name,
+ type: "library-data",
+ can_write: true,
+ collection_id: promotedDataCollection.id as number,
+ location: "/9/10/28/",
+ effective_location: "/9/28/",
+ here: ["collection"],
+ below: ["table", "collection"],
+ }),
+];
+
+const libraryPickerSetup = {
+ additionalCollections: [
+ hiddenDataCollection,
+ promotedDataCollection,
+ writableNestedDataCollection,
+ ],
+ additionalCollectionItemEndpoints: [
+ {
+ collection: promotedDataCollection,
+ collectionItems: promotedDataCollectionItems,
+ },
+ {
+ collection: writableNestedDataCollection,
+ collectionItems: [],
+ },
+ ],
+ libraryCollection,
+ libraryCollectionItems: libraryRootItems,
+ options: { hasRecents: false, hasDatabases: false },
+ isSelectableItem: (item: OmniPickerItem) =>
+ !("can_write" in item) || item.can_write !== false,
+};
+
describe("EntityPickerModal", () => {
afterEach(() => {
jest.restoreAllMocks();
@@ -157,6 +279,125 @@ describe("EntityPickerModal", () => {
screen.queryByText("Question in Collection 1"),
).not.toBeInTheDocument();
});
+
+ it("should show non-selectable synthetic library sections for promoted descendants", async () => {
+ await setup({
+ ...libraryPickerSetup,
+ value: { id: "root", model: "collection" },
+ });
+
+ await userEvent.click(await screen.findByText("Library"));
+ await waitFor(() => {
+ const item = screen
+ .getAllByRole("link")
+ .find((item) => item.textContent?.trim() === "Library");
+
+ expect(item).toHaveAttribute("data-active", "true");
+ });
+ await expectInactiveItem("Data");
+ await expectInactiveItem("Metrics");
+ expect(screen.queryByText("LibraryCollection3")).not.toBeInTheDocument();
+
+ await userEvent.click(await screen.findByText("Data"));
+ await expectActiveItem("Data");
+ expect(
+ await screen.findByRole("button", { name: "Select" }),
+ ).toBeDisabled();
+ await expectInactiveItem("LibraryCollection3");
+ await expectInactiveItem("LibraryCollection5");
+
+ await userEvent.click(await screen.findByText("LibraryCollection3"));
+ await expectActiveItem("LibraryCollection3");
+ expect(
+ await screen.findByRole("button", { name: "Select" }),
+ ).toBeDisabled();
+
+ await userEvent.click(await screen.findByText("LibraryCollection1"));
+ await expectActiveItem("LibraryCollection1");
+ expect(
+ await screen.findByRole("button", { name: "Select" }),
+ ).toBeEnabled();
+ });
+
+ it("should include synthetic library sections when auto-selecting a promoted descendant path", async () => {
+ await setup({
+ ...libraryPickerSetup,
+ value: { id: writableNestedDataCollection.id, model: "collection" },
+ });
+
+ expect(await screen.findByText("Library")).toBeVisible();
+ expect(await screen.findByText("Data")).toBeVisible();
+ expect(await screen.findByText("LibraryCollection3")).toBeVisible();
+ expect(await screen.findByText("LibraryCollection1")).toBeVisible();
+ expect(
+ await screen.findByRole("button", { name: "Select" }),
+ ).toBeEnabled();
+ });
+
+ it("should use real library section roots when they are available", async () => {
+ await setup({
+ ...libraryPickerSetup,
+ libraryCollectionItems: [
+ createMockCollectionItem({
+ id: hiddenDataCollection.id as number,
+ model: "collection",
+ name: "Data",
+ type: "library-data",
+ can_write: true,
+ is_library_root: true,
+ collection_id: libraryCollection.id as number,
+ location: "/9/",
+ effective_location: "/9/",
+ here: ["collection"],
+ below: ["collection"],
+ }),
+ ],
+ additionalCollectionItemEndpoints: [
+ {
+ collection: hiddenDataCollection,
+ collectionItems: promotedDataCollectionItems,
+ },
+ ],
+ value: { id: "root", model: "collection" },
+ });
+
+ await userEvent.click(await screen.findByText("Library"));
+ await userEvent.click(await screen.findByText("Data"));
+
+ expect(await screen.findByText("LibraryCollection1")).toBeVisible();
+ const gets = await findRequests("GET");
+ expect(
+ gets.some((req) => req.url.includes("/api/collection/10/items")),
+ ).toBe(true);
+ });
+
+ it("should filter synthetic library section children by section type", async () => {
+ await setup({
+ ...libraryPickerSetup,
+ libraryCollectionItems: [
+ ...libraryRootItems,
+ createMockCollectionItem({
+ id: 31,
+ model: "collection",
+ name: "Promoted Metric Collection",
+ type: "library-metrics",
+ can_write: true,
+ collection_id: libraryCollection.id as number,
+ location: "/9/11/",
+ effective_location: "/9/",
+ }),
+ ],
+ value: { id: "root", model: "collection" },
+ });
+
+ await userEvent.click(await screen.findByText("Library"));
+ await userEvent.click(await screen.findByText("Data"));
+
+ expect(await screen.findByText("LibraryCollection3")).toBeVisible();
+ expect(
+ screen.queryByText("Promoted Metric Collection"),
+ ).not.toBeInTheDocument();
+ });
});
describe("Database Navigation", () => {
@@ -343,6 +584,51 @@ describe("EntityPickerModal", () => {
);
});
+ it("should record recent selections by default", async () => {
+ await setup({
+ options: { hasRecents: false },
+ });
+
+ await userEvent.click(await screen.findByText("Our analytics"));
+ await userEvent.click(await screen.findByText("First Collection"));
+ await userEvent.click(
+ await screen.findByText("Question in Collection 1"),
+ );
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Select" }),
+ );
+
+ const posts = await findRequests("POST");
+ expect(posts).toEqual([
+ expect.objectContaining({
+ body: {
+ context: "selection",
+ model: "card",
+ model_id: 100,
+ },
+ }),
+ ]);
+ });
+
+ it("should not record recent selections when logging is disabled", async () => {
+ await setup({
+ disableRecentLogging: true,
+ options: { hasRecents: false },
+ });
+
+ await userEvent.click(await screen.findByText("Our analytics"));
+ await userEvent.click(await screen.findByText("First Collection"));
+ await userEvent.click(
+ await screen.findByText("Question in Collection 1"),
+ );
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Select" }),
+ );
+
+ const posts = await findRequests("POST");
+ expect(posts).toHaveLength(0);
+ });
+
it("can disable selection based on provided models", async () => {
const { onChange } = await setup({
models: ["card"], // no collections
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/setup.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/setup.tsx
index 1d805cb4f4e..d136ed8cd20 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/setup.tsx
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/setup.tsx
@@ -1,5 +1,6 @@
import fetchMock from "fetch-mock";
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
setupCollectionByIdEndpoint,
setupCollectionItemsEndpoint,
@@ -8,13 +9,22 @@ import {
setupRecentViewsAndSelectionsEndpoints,
setupRootCollectionItemsEndpoint,
} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
import {
mockGetBoundingClientRect,
renderWithProviders,
waitForLoaderToBeRemoved,
} from "__support__/ui";
import { ROOT_COLLECTION } from "metabase/entities/collections";
-import type { Database, RecentItem, SearchResult } from "metabase-types/api";
+import { createMockState } from "metabase/redux/store/mocks";
+import type {
+ Collection,
+ CollectionItem,
+ Database,
+ LibraryCollection,
+ RecentItem,
+ SearchResult,
+} from "metabase-types/api";
import {
createMockCollection,
createMockCollectionItem,
@@ -24,6 +34,7 @@ import {
createMockSearchResult,
createMockSearchResults,
createMockTable,
+ createMockTokenFeatures,
} from "metabase-types/api/mocks";
import {
@@ -96,6 +107,26 @@ const mockSearchResults = createMockSearchResults({
}),
],
});
+
+const createMockLibraryCollectionItem = (
+ collection: Collection,
+): LibraryCollection => ({
+ ...createMockCollectionItem({
+ id: Number(collection.id),
+ name: collection.name,
+ description: collection.description,
+ archived: collection.archived,
+ model: "collection",
+ type: collection.type,
+ can_write: collection.can_write,
+ location: collection.location,
+ effective_location: collection.effective_location,
+ here: collection.here,
+ below: collection.below,
+ collection_id: collection.parent_id ?? null,
+ }),
+ effective_children: [],
+});
const mockRecentItems = [
createMockRecentCollectionItem({
id: 100,
@@ -318,9 +349,23 @@ export type SetupOpts = Partial<EntityPickerModalProps> & {
recentItems?: RecentItem[];
searchResults?: SearchResult[];
databases?: Database[];
+ additionalCollections?: Collection[];
+ additionalCollectionItemEndpoints?: Array<{
+ collection: Pick<Collection, "id">;
+ collectionItems: CollectionItem[];
+ }>;
+ libraryCollection?: Collection;
+ libraryCollectionItems?: CollectionItem[];
};
-export const setup = async ({ databases, ...rest }: SetupOpts = {}) => {
+export const setup = async ({
+ additionalCollections = [],
+ additionalCollectionItemEndpoints = [],
+ databases,
+ libraryCollection,
+ libraryCollectionItems,
+ ...rest
+}: SetupOpts = {}) => {
process.env.OVERSCAN = "20"; // for VirtualizedList overscan
mockGetBoundingClientRect();
setupRecentViewsAndSelectionsEndpoints(mockRecentItems, [
@@ -330,17 +375,56 @@ export const setup = async ({ databases, ...rest }: SetupOpts = {}) => {
setupDatabasesEndpoints(databases ?? mockDatabases);
+ const libraryCollectionItem = libraryCollection
+ ? createMockLibraryCollectionItem(libraryCollection)
+ : undefined;
+
+ const state = libraryCollectionItem
+ ? createMockState({
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures({ library: true }),
+ }),
+ })
+ : undefined;
+
+ if (libraryCollectionItem) {
+ setupEnterpriseOnlyPlugin("library");
+ }
+ fetchMock.get(
+ "path:/api/ee/library",
+ libraryCollectionItem ?? {
+ message: "not found",
+ },
+ );
+
// Setup collections
setupCollectionsEndpoints({
- collections: [collection1, collection2, nestedCollection],
+ collections: [
+ collection1,
+ collection2,
+ nestedCollection,
+ ...additionalCollections,
+ ],
rootCollection,
});
// Setup collection by ID endpoints
setupCollectionByIdEndpoint({
- collections: [collection1, collection2, nestedCollection],
+ collections: [
+ collection1,
+ collection2,
+ nestedCollection,
+ ...additionalCollections,
+ ],
});
+ if (libraryCollection && libraryCollectionItems) {
+ setupCollectionItemsEndpoint({
+ collection: libraryCollection,
+ collectionItems: libraryCollectionItems,
+ });
+ }
+
// Setup collection items endpoints for the tree structure
setupRootCollectionItemsEndpoint({
rootCollectionItems,
@@ -361,6 +445,10 @@ export const setup = async ({ databases, ...rest }: SetupOpts = {}) => {
collectionItems: nestedCollectionItems,
});
+ for (const endpoint of additionalCollectionItemEndpoints) {
+ setupCollectionItemsEndpoint(endpoint);
+ }
+
fetchMock.get("path:/api/search", mockSearchResults);
fetchMock.get("path:/api/user/recipients", { data: [] });
const onChange = jest.fn();
@@ -383,6 +471,7 @@ export const setup = async ({ databases, ...rest }: SetupOpts = {}) => {
]}
{...rest}
/>,
+ { storeInitialState: state },
);
await waitForLoaderToBeRemoved();
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts
index f50acf78920..ae111153152 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts
@@ -381,7 +381,9 @@ async function getCollectionPathFromValue({
}),
).unwrap();
- const location = collection?.effective_location ?? collection?.location;
+ const location = PLUGIN_LIBRARY.isLibraryCollectionType(collection?.type)
+ ? collection?.location
+ : (collection?.effective_location ?? collection?.location);
const locationPath = [rootCollectionItem];
@@ -425,6 +427,7 @@ async function getCollectionPathFromValue({
id: libraryCollection.id,
name: libraryCollection.name,
model: "collection",
+ type: libraryCollection.type,
below: allCollectionModels,
});
} else if (isInPersonalCollection && personalCollection) {
@@ -489,6 +492,45 @@ async function getCollectionPathFromValue({
);
if (!nextItem) {
+ if (
+ isInLibrary &&
+ libraryCollection &&
+ collectionId === libraryCollection.id &&
+ PLUGIN_LIBRARY.isLibrarySubCollectionType(collection?.type)
+ ) {
+ const promotedItem = collectionItems.data.find(
+ (item) =>
+ item.model === "collection" &&
+ item.id === collectionIds[i + 2] &&
+ item.type === collection.type,
+ );
+
+ const syntheticItem =
+ PLUGIN_LIBRARY.getEntityPickerSyntheticLibraryItem({
+ collectionId: libraryCollection.id,
+ type: collection.type,
+ });
+
+ if (syntheticItem) {
+ locationPath.push(syntheticItem);
+ }
+
+ if (promotedItem) {
+ locationPath.push({
+ id: promotedItem.id,
+ name: promotedItem.name,
+ model: "collection",
+ namespace: promotedItem.namespace,
+ can_write: promotedItem.can_write,
+ here: promotedItem.here,
+ below: promotedItem.below,
+ type: promotedItem.type,
+ });
+ i += 1;
+ continue;
+ }
+ }
+
break;
}
@@ -500,6 +542,7 @@ async function getCollectionPathFromValue({
can_write: nextItem.can_write,
here: nextItem.here,
below: nextItem.below,
+ type: nextItem.type,
});
}
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/types.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/types.ts
index 9d679b2f9c4..00c3e25bbca 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/types.ts
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/types.ts
@@ -6,6 +6,7 @@ import type {
CollectionId,
CollectionItem,
CollectionNamespace,
+ CollectionType,
DashboardId,
DatabaseId,
Measure,
@@ -90,8 +91,11 @@ export type OmniPickerCollectionItem = Pick<
| "type"
| "database_id"
| "effective_location"
+ | "is_library_root"
> & {
id: CollectionItem["id"] | CollectionId;
+ sourceCollectionId?: CollectionItem["id"] | CollectionId;
+ childTypeFilter?: NonNullable<CollectionType>;
collection?:
| (Pick<Collection, "id" | "name" | "authority_level"> & {
namespace?: CollectionNamespace;
diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsx
index eaa971f96f2..daa0acd3bb2 100644
--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsx
@@ -23,6 +23,7 @@ const LIBRARY_DATA_COLLECTION = createMockCollectionItem({
model: "collection",
id: 1338,
here: ["dataset"],
+ is_library_root: true,
});
const LIBRARY_METRICS_COLLECTION = createMockCollectionItem({
@@ -31,6 +32,7 @@ const LIBRARY_METRICS_COLLECTION = createMockCollectionItem({
model: "collection",
id: 1339,
here: ["metric"],
+ is_library_root: true,
});
describe("library", () => {
diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx
index ccede5526ff..28c7ecaf65f 100644
--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx
+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx
@@ -18,6 +18,7 @@ import { useSetting } from "metabase/common/hooks";
import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
import { useGetIcon } from "metabase/hooks/use-icon";
import { PLUGIN_LIBRARY } from "metabase/plugins";
+import type { LibrarySubCollectionType } from "metabase/plugins/oss/library";
import { useSelector } from "metabase/redux";
import {
Box,
@@ -120,6 +121,9 @@ function RootItemList() {
]).length &&
shouldShowLibrary
) {
+ if (libraryCollection.type === "library") {
+ return <LibraryRootItemList libraryCollectionId={libraryCollection.id} />;
+ }
return (
<CollectionItemList
parent={{
@@ -164,6 +168,115 @@ function RootItemList() {
);
}
+/**
+ * Shows the Data and Metrics sections at the library root.
+ * If the user has access to the real root collections (is_library_root),
+ * they render normally. If not, synthetic folders are created to group
+ * any promoted subcollections by their type.
+ */
+function LibraryRootItemList({
+ libraryCollectionId,
+}: {
+ libraryCollectionId: CollectionItem["id"];
+}) {
+ const { setPath } = useMiniPickerContext();
+
+ const { data, isLoading } = useListCollectionItemsQuery({
+ id: libraryCollectionId,
+ });
+
+ const sections = useMemo(() => {
+ type Section = {
+ key: string;
+ name: string;
+ type: LibrarySubCollectionType;
+ realCollection?: CollectionItem;
+ hasPromotedChildren: boolean;
+ };
+
+ const sectionDefs: Section[] = [
+ {
+ key: "data",
+ name: t`Data`,
+ type: "library-data",
+ hasPromotedChildren: false,
+ },
+ {
+ key: "metrics",
+ name: t`Metrics`,
+ type: "library-metrics",
+ hasPromotedChildren: false,
+ },
+ ];
+
+ const items = data?.data ?? [];
+
+ for (const item of items) {
+ if (item.model !== "collection") {
+ continue;
+ }
+
+ for (const section of sectionDefs) {
+ if (item.type !== section.type) {
+ continue;
+ }
+
+ if (item.is_library_root) {
+ section.realCollection = item;
+ } else {
+ section.hasPromotedChildren = true;
+ }
+ }
+ }
+
+ return sectionDefs.filter((s) => s.realCollection || s.hasPromotedChildren);
+ }, [data]);
+
+ if (isLoading) {
+ return <MiniPickerListLoader />;
+ }
+
+ return (
+ <ItemList>
+ {sections.map((section) => {
+ const collection = section.realCollection;
+
+ return (
+ <MiniPickerItem
+ key={section.key}
+ name={collection?.name ?? section.name}
+ model="collection"
+ isFolder
+ onClick={() => {
+ if (collection) {
+ setPath([
+ {
+ model: "collection",
+ id: collection.id,
+ name: collection.name,
+ type: collection.type,
+ },
+ ]);
+ } else {
+ setPath([
+ {
+ model: "collection",
+ id: `${section.type}-${libraryCollectionId}`,
+ sourceCollectionId: libraryCollectionId,
+ name: section.name,
+ type: section.type,
+ childTypeFilter: section.type,
+ },
+ ]);
+ }
+ }}
+ />
+ );
+ })}
+ </ItemList>
+ );
+}
+
function DatabaseItemList({
parent,
}: {
@@ -276,12 +389,19 @@ function CollectionItemList({ parent }: { parent: MiniPickerCollectionItem }) {
const { setPath, onChange, isFolder, isHidden } = useMiniPickerContext();
const { data, isLoading, isFetching } = useListCollectionItemsQuery({
- id: parent.id === null ? "root" : parent.id,
+ id: parent.sourceCollectionId ?? (parent.id === null ? "root" : parent.id),
include_can_run_adhoc_query: true,
});
- const allItems = data?.data?.filter(canCollectionCardBeUsed) ?? [];
- const items: CollectionItem[] = allItems.filter((item) => !isHidden(item));
+ const allItems: CollectionItem[] = (data?.data ?? []).filter(
+ (item) => canCollectionCardBeUsed(item) && !isHidden(item),
+ );
+ const typeFilter = parent.childTypeFilter;
+ const items = typeFilter
+ ? allItems.filter(
+ (item) => item.model !== "collection" || item.type === typeFilter,
+ )
+ : allItems;
if (isLoading || isFetching) {
return <MiniPickerListLoader />;
@@ -305,6 +425,7 @@ function CollectionItemList({ parent }: { parent: MiniPickerCollectionItem }) {
model: item.model,
id: item.id,
name: item.name,
+ type: item.type,
},
]);
} else {
diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/types.ts b/frontend/src/metabase/common/components/Pickers/MiniPicker/types.ts
index 20c997b2c38..5fa39644b9e 100644
--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/types.ts
+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/types.ts
@@ -1,6 +1,7 @@
import type {
CollectionId,
CollectionItem,
+ CollectionType,
DatabaseId,
MeasureId,
SchemaName,
@@ -9,9 +10,16 @@ import type {
export type MiniPickerCollectionItem = Pick<
CollectionItem,
- "id" | "name" | "model" | "here" | "below" | "display" | "collection"
+ "name" | "model" | "here" | "below" | "display" | "collection" | "type"
> & {
id: CollectionItem["id"] | CollectionId;
+ sourceCollectionId?: CollectionItem["id"] | CollectionId;
+ /** When set, CollectionItemList only shows children whose type matches */
+ childTypeFilter?: NonNullable<CollectionType>;
+};
+
+export type MiniPickerCollectionFolderItem = MiniPickerCollectionItem & {
+ model: "collection";
};
export type MiniPickerPickableCollectionItem = MiniPickerCollectionItem & {
@@ -77,7 +85,7 @@ export type MiniPickerItem =
export type MiniPickerFolderItem =
| MiniPickerDatabaseItem
| MiniPickerSchemaItem
- | (MiniPickerCollectionItem & { model: "collection" });
+ | MiniPickerCollectionFolderItem;
// this omits intermediate/folder types that cannot ultimately be picked
export type MiniPickerPickableItem =
diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts
index 0d6a8cb02f0..ab86119b2ae 100644
--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts
@@ -3,6 +3,7 @@ import { useDeepCompareEffect } from "react-use";
import { t } from "ttag";
import { cardApi, collectionApi, databaseApi, tableApi } from "metabase/api";
+import { PLUGIN_LIBRARY } from "metabase/plugins";
import type { DispatchFn } from "metabase/redux";
import { useDispatch } from "metabase/redux";
import type { SchemaName } from "metabase-types/api";
@@ -10,6 +11,7 @@ import type { SchemaName } from "metabase-types/api";
import type { DataPickerValue } from "../DataPicker";
import {
+ type MiniPickerCollectionFolderItem,
type MiniPickerCollectionItem,
type MiniPickerFolderItem,
MiniPickerFolderModel,
@@ -18,7 +20,7 @@ import {
type MiniPickerTableItem,
} from "./types";
-export const getOurAnalytics = (): MiniPickerFolderItem => ({
+export const getOurAnalytics = (): MiniPickerCollectionFolderItem => ({
model: "collection",
id: "root" as any, // cmon typescript
name: t`Our analytics`,
@@ -120,7 +122,7 @@ async function getTablePathFromValue(
async function getCollectionPathFromValue(
value: DataPickerValue,
dispatch: DispatchFn,
- libraryCollection?: MiniPickerCollectionItem,
+ collectionItem?: MiniPickerCollectionItem,
): Promise<MiniPickerFolderItem[]> {
const table =
value.model === "table"
@@ -137,7 +139,9 @@ async function getCollectionPathFromValue(
const collection = table?.collection ?? card?.collection;
- const location = collection?.effective_location ?? collection?.location;
+ const location = PLUGIN_LIBRARY.isLibrarySubCollectionType(collection?.type)
+ ? collection?.location
+ : (collection?.effective_location ?? collection?.location);
if (!location) {
return [getOurAnalytics()];
@@ -151,7 +155,7 @@ async function getCollectionPathFromValue(
collection?.id,
].filter(Boolean);
- if (collectionIds.includes(libraryCollection?.id)) {
+ if (collectionIds.includes(collectionItem?.id)) {
collectionIds.shift(); // pretend the library is at the top level
locationPath.shift();
}
@@ -178,6 +182,42 @@ async function getCollectionPathFromValue(
);
if (!nextItem) {
+ if (
+ collectionId === collectionItem?.id &&
+ PLUGIN_LIBRARY.isLibrarySubCollectionType(collection?.type)
+ ) {
+ const promotedItem = collectionItems.data.find(
+ (item) =>
+ item.model === "collection" &&
+ item.id === collectionIds[i + 2] &&
+ item.type === collection.type,
+ );
+
+ const syntheticItem =
+ PLUGIN_LIBRARY.getEntityPickerSyntheticLibraryItem({
+ collectionId: collectionItem.id,
+ type: collection.type,
+ miniPicker: true,
+ });
+
+ if (syntheticItem) {
+ locationPath.push(syntheticItem);
+ }
+
+ if (promotedItem) {
+ locationPath.push({
+ id: promotedItem.id,
+ name: promotedItem.name,
+ model: "collection",
+ here: promotedItem.here,
+ below: promotedItem.below,
+ type: promotedItem.type,
+ });
+ i += 1;
+ continue;
+ }
+ }
+
break;
}
@@ -187,6 +227,7 @@ async function getCollectionPathFromValue(
model: "collection",
here: nextItem.here,
below: nextItem.below,
+ type: nextItem.type,
});
}
diff --git a/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.tsx b/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.tsx
index be86c12a07b..a448d1b6158 100644
--- a/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.tsx
+++ b/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.tsx
@@ -17,7 +17,7 @@ import {
isInDbTree,
} from "metabase/common/components/Pickers";
import { isItemInCollectionOrItsDescendants } from "metabase/common/components/Pickers/utils";
-import { PLUGIN_TENANTS } from "metabase/plugins";
+import { PLUGIN_LIBRARY, PLUGIN_TENANTS } from "metabase/plugins";
import type { CollectionId, CollectionItem } from "metabase-types/api";
import type {
@@ -70,6 +70,10 @@ export const MoveModal = ({
}
if (item.model === "collection") {
+ if (!canMoveCollectionToLibraryDestination(movingItem, item)) {
+ return true;
+ }
+
return !canPlaceEntityInCollectionOrDescendants(
movingItem.model,
getCollectionType(item),
@@ -105,6 +109,13 @@ export const MoveModal = ({
return false;
}
+ if (
+ item.model === "collection" &&
+ !canPlaceEntityInCollection(movingItem.model, getCollectionType(item))
+ ) {
+ return false;
+ }
+
if (
!PLUGIN_TENANTS.canPlaceEntityInCollection({
entityType: movingItem.model,
@@ -194,6 +205,27 @@ export const MoveModal = ({
);
};
+export function canMoveCollectionToLibraryDestination(
+ movingItem: OmniPickerCollectionItem,
+ destination: OmniPickerCollectionItem,
+) {
+ if (movingItem.model !== "collection") {
+ return true;
+ }
+
+ const destinationType = getCollectionType(destination);
+
+ if (!PLUGIN_LIBRARY.isLibraryCollectionType(destinationType)) {
+ return true;
+ }
+
+ if (destinationType === "library") {
+ return PLUGIN_LIBRARY.isLibrarySubCollectionType(movingItem.type);
+ }
+
+ return movingItem.type === destinationType;
+}
+
interface BulkMoveModalProps {
onClose: () => void;
onMove: OnMoveWithOneItem<MoveDestination>;
@@ -234,6 +266,10 @@ export const BulkMoveModal = ({
if (item.model === "collection") {
const hasInvalidItem = selectedItems.some(
(selectedItem) =>
+ !canMoveCollectionToLibraryDestination(
+ selectedItem as OmniPickerCollectionItem,
+ item,
+ ) ||
!canPlaceEntityInCollectionOrDescendants(
selectedItem.model,
getCollectionType(item),
@@ -294,11 +330,16 @@ export const BulkMoveModal = ({
const shouldHideItem = useCallback(
(item: OmniPickerItem) => {
if (item.model === "collection") {
- return !selectedItems.every((selectedItem) =>
- canPlaceEntityInCollection(
- selectedItem.model,
- getCollectionType(item),
- ),
+ return !selectedItems.every(
+ (selectedItem) =>
+ canMoveCollectionToLibraryDestination(
+ selectedItem as OmniPickerCollectionItem,
+ item,
+ ) &&
+ canPlaceEntityInCollection(
+ selectedItem.model,
+ getCollectionType(item),
+ ),
);
}
return false;
diff --git a/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.unit.spec.ts
index 151967bb952..5f452d98050 100644
--- a/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.unit.spec.ts
+++ b/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.unit.spec.ts
@@ -1,6 +1,11 @@
+import { PLUGIN_LIBRARY, reinitialize } from "metabase/plugins";
+
import type { OmniPickerCollectionItem } from "../EntityPicker";
-import { isSameDestination } from "./MoveModal";
+import {
+ canMoveCollectionToLibraryDestination,
+ isSameDestination,
+} from "./MoveModal";
const makeItem = (
overrides: Partial<OmniPickerCollectionItem> = {},
@@ -65,3 +70,97 @@ describe("isSameDestination", () => {
expect(isSameDestination(movingItem, movingTarget)).toBe(false);
});
});
+
+describe("canMoveCollectionToLibraryDestination", () => {
+ beforeEach(() => {
+ PLUGIN_LIBRARY.isLibraryCollectionType = (type) => {
+ return (
+ type === "library" ||
+ type === "library-data" ||
+ type === "library-metrics"
+ );
+ };
+ PLUGIN_LIBRARY.isLibrarySubCollectionType = (type) => {
+ return type === "library-data" || type === "library-metrics";
+ };
+ });
+
+ afterEach(() => {
+ reinitialize();
+ });
+
+ it("should not allow moving a non-library collection into Library sections", () => {
+ const movingItem = makeItem({ model: "collection", type: null });
+
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library" }),
+ ),
+ ).toBe(false);
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library-data" }),
+ ),
+ ).toBe(false);
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library-metrics" }),
+ ),
+ ).toBe(false);
+ });
+
+ it("should only allow moving library-data collections into Data", () => {
+ const movingItem = makeItem({
+ model: "collection",
+ type: "library-data",
+ });
+
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library" }),
+ ),
+ ).toBe(true);
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library-data" }),
+ ),
+ ).toBe(true);
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library-metrics" }),
+ ),
+ ).toBe(false);
+ });
+
+ it("should only allow moving library-metrics collections into Metrics", () => {
+ const movingItem = makeItem({
+ model: "collection",
+ type: "library-metrics",
+ });
+
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library" }),
+ ),
+ ).toBe(true);
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library-data" }),
+ ),
+ ).toBe(false);
+ expect(
+ canMoveCollectionToLibraryDestination(
+ movingItem,
+ makeItem({ model: "collection", type: "library-metrics" }),
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/frontend/src/metabase/common/components/tree/types.ts b/frontend/src/metabase/common/components/tree/types.ts
index 0a85721d2f4..a097c65c5fc 100644
--- a/frontend/src/metabase/common/components/tree/types.ts
+++ b/frontend/src/metabase/common/components/tree/types.ts
@@ -6,6 +6,7 @@ export interface ITreeNodeItem<TData = unknown> {
icon: IconName | IconProps;
children?: ITreeNodeItem<TData>[];
data?: TData;
+ nonNavigable?: boolean;
}
export interface TreeNodeProps<TData = unknown> {
diff --git a/frontend/src/metabase/common/utils/icon.ts b/frontend/src/metabase/common/utils/icon.ts
index 15fa12d37d0..b73ff09a21e 100644
--- a/frontend/src/metabase/common/utils/icon.ts
+++ b/frontend/src/metabase/common/utils/icon.ts
@@ -34,6 +34,7 @@ export type ObjectWithModel = {
effective_location?: Collection["location"];
is_personal?: boolean;
is_remote_synced?: boolean;
+ is_library_root?: boolean;
};
export const modelIconMap: Record<IconModel, IconName> = {
diff --git a/frontend/src/metabase/data-studio/common/hooks/use-build-snippet-tree/use-build-snippet-tree.ts b/frontend/src/metabase/data-studio/common/hooks/use-build-snippet-tree/use-build-snippet-tree.ts
index 6befc8ca822..174115a4998 100644
--- a/frontend/src/metabase/data-studio/common/hooks/use-build-snippet-tree/use-build-snippet-tree.ts
+++ b/frontend/src/metabase/data-studio/common/hooks/use-build-snippet-tree/use-build-snippet-tree.ts
@@ -15,13 +15,20 @@ export const useBuildSnippetTree = ({ archived = false } = {}): {
const {
data: snippets,
isLoading: loadingSnippets,
+ isFetching: fetchingSnippets,
error,
- } = useListSnippetsQuery({ archived });
- const { data: snippetCollections, isLoading: loadingCollections } =
- useListCollectionsQuery({
+ } = useListSnippetsQuery({ archived }, { refetchOnMountOrArgChange: true });
+ const {
+ data: snippetCollections,
+ isLoading: loadingCollections,
+ isFetching: fetchingCollections,
+ } = useListCollectionsQuery(
+ {
namespace: "snippets",
archived,
- });
+ },
+ { refetchOnMountOrArgChange: true },
+ );
const isRemoteSyncReadOnly = useSelector(
PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,
);
@@ -29,7 +36,9 @@ export const useBuildSnippetTree = ({ archived = false } = {}): {
return useMemo(() => {
if (
loadingSnippets ||
+ fetchingSnippets ||
loadingCollections ||
+ fetchingCollections ||
!snippets ||
!snippetCollections
) {
@@ -53,7 +62,9 @@ export const useBuildSnippetTree = ({ archived = false } = {}): {
};
}, [
loadingSnippets,
+ fetchingSnippets,
loadingCollections,
+ fetchingCollections,
snippets,
snippetCollections,
error,
diff --git a/frontend/src/metabase/data-studio/common/types.ts b/frontend/src/metabase/data-studio/common/types.ts
index 025ca7205d1..30d37e057e7 100644
--- a/frontend/src/metabase/data-studio/common/types.ts
+++ b/frontend/src/metabase/data-studio/common/types.ts
@@ -3,7 +3,7 @@ import type {
Collection,
CollectionItem,
CollectionItemModel,
- CollectionNamespace,
+ Table,
} from "metabase-types/api";
export type LibrarySectionType = "data" | "metrics" | "snippets";
@@ -16,6 +16,28 @@ export type EmptyStateData = {
actionUrl?: string;
};
+export type CollectionItemData = Pick<CollectionItem, "model" | "name"> &
+ Partial<
+ Pick<
+ CollectionItem,
+ | "id"
+ | "description"
+ | "collection_id"
+ | "archived"
+ | "collection_position"
+ | "last-edit-info"
+ | "namespace"
+ >
+ >;
+
+export type CollectionData = Collection & {
+ model: "collection";
+};
+
+export type TableData = Table & {
+ model: "table";
+};
+
export type TreeItemModel = CollectionItemModel | "empty-state";
export type TreeItem = {
@@ -24,11 +46,8 @@ export type TreeItem = {
icon: IconName;
updatedAt?: string;
model: TreeItemModel;
- data:
- | ((Collection | Omit<CollectionItem, "getUrl">) & {
- model: CollectionItem["model"];
- namespace?: CollectionNamespace | null;
- })
- | EmptyStateData;
+ parentCollectionName?: string;
+ data: CollectionItemData | CollectionData | TableData | EmptyStateData;
children?: TreeItem[];
+ childrenLoaded?: boolean;
};
diff --git a/frontend/src/metabase/data-studio/common/utils/index.ts b/frontend/src/metabase/data-studio/common/utils/index.ts
index 1f307adb784..8de8835868a 100644
--- a/frontend/src/metabase/data-studio/common/utils/index.ts
+++ b/frontend/src/metabase/data-studio/common/utils/index.ts
@@ -1,10 +1,11 @@
-import type {
- Collection,
- CollectionItem,
- GetLibraryCollectionResponse,
-} from "metabase-types/api";
+import type { GetLibraryCollectionResponse } from "metabase-types/api";
-import type { EmptyStateData, TreeItem } from "../types";
+import type {
+ CollectionData,
+ EmptyStateData,
+ TableData,
+ TreeItem,
+} from "../types";
export { createEmptyStateItem } from "./create-empty-space-item";
export { getDatasetQueryPreviewUrl } from "./get-dataset-query-preview-url";
@@ -15,10 +16,16 @@ export const hasLibraryCollection = (
libraryCollection?: GetLibraryCollectionResponse,
) => libraryCollection != null && "name" in libraryCollection;
-export const isCollection = (
- c: Collection | Omit<CollectionItem, "getUrl">,
-): c is Collection => {
- return Object.keys(c).includes("namespace");
+export const isCollectionData = (
+ data: TreeItem["data"],
+): data is CollectionData => {
+ return data.model === "collection";
+};
+
+export const isTableData = (data: TreeItem["data"]): data is TableData => {
+ return (
+ data.model === "table" && "collection_id" in data && "database_id" in data
+ );
};
export const isEmptyStateData = (
diff --git a/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx b/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx
index f381c91a4fa..7189468421d 100644
--- a/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx
+++ b/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx
@@ -6,14 +6,18 @@ import { isLibraryCollection } from "metabase/collections/utils";
import { CollapseSection } from "metabase/common/components/CollapseSection";
import { Tree } from "metabase/common/components/tree";
import { useUserSetting } from "metabase/common/hooks";
-import { buildCollectionTree } from "metabase/entities/collections";
+import type { CollectionTreeItem } from "metabase/entities/collections";
+import {
+ buildCollectionTree,
+ getCollectionIcon,
+} from "metabase/entities/collections";
import {
SidebarHeading,
SidebarSection,
} from "metabase/nav/containers/MainNavbar/MainNavbar.styled";
import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";
import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";
-import type { Collection } from "metabase-types/api";
+import type { Collection, CollectionType } from "metabase-types/api";
type LibraryCollectionSectionProps = {
collections: Collection[];
@@ -21,6 +25,66 @@ type LibraryCollectionSectionProps = {
onItemSelect: () => void;
};
+/** Build the tree for a single library section (Data or Metrics).
+ * If the user has access to the root collection, use it directly.
+ * If not, create a synthetic container for any promoted children. */
+function buildSectionTree(
+ libraryCollection: Collection,
+ allCollections: Collection[],
+ sectionType: CollectionType,
+ sectionName: string,
+): CollectionTreeItem | null {
+ // Look for the real root collection (has is_library_root)
+ const rootCollection = libraryCollection.children?.find(
+ (c) => c.type === sectionType && c.is_library_root,
+ );
+
+ if (rootCollection) {
+ // User has access to the root — build its subtree normally
+ const [tree] = buildCollectionTree([rootCollection]);
+ return tree ?? null;
+ }
+
+ // User doesn't have access to the root collection. Find any promoted
+ // children of that type that were pulled up into the library collection.
+ const promotedChildren = allCollections.filter(
+ (c) => c.type === sectionType && !c.is_library_root,
+ );
+
+ // Also check direct children of the library collection that match the type
+ const libraryChildren = (libraryCollection.children ?? []).filter(
+ (c) => c.type === sectionType && !c.is_library_root,
+ );
+
+ const allOrphans = [...libraryChildren, ...promotedChildren];
+ if (allOrphans.length === 0) {
+ return null;
+ }
+
+ // Build subtrees for the orphaned children
+ const children = buildCollectionTree(allOrphans);
+
+ // Create a synthetic container node
+ return {
+ id: `synthetic-${sectionType}`,
+ name: sectionName,
+ description: null,
+ icon: getCollectionIcon({
+ type: sectionType,
+ is_library_root: true,
+ } as Collection),
+ children,
+ nonNavigable: true,
+ type: sectionType,
+ is_library_root: true,
+ namespace: null,
+ location: null,
+ can_write: false,
+ can_restore: false,
+ can_delete: false,
+ } as CollectionTreeItem;
+}
+
export function NavbarLibrarySection({
collections,
selectedId,
@@ -39,13 +103,23 @@ export function NavbarLibrarySection({
if (!libraryCollection) {
return [];
}
- const tree = buildCollectionTree([libraryCollection], {
- modelFilter: () => true,
- });
- if (tree.length === 0) {
- return [];
- }
- return tree[0].children || [];
+
+ const dataTree = buildSectionTree(
+ libraryCollection,
+ collections,
+ "library-data",
+ t`Data`,
+ );
+ const metricsTree = buildSectionTree(
+ libraryCollection,
+ collections,
+ "library-metrics",
+ t`Metrics`,
+ );
+
+ return [dataTree, metricsTree].filter(
+ (node): node is CollectionTreeItem => node != null,
+ );
}, [collections]);
const showChangesBadge = useCallback(
diff --git a/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/enterprise.unit.spec.tsx
index 9dc6cd6c826..9cf304fdf5e 100644
--- a/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/enterprise.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/enterprise.unit.spec.tsx
@@ -24,6 +24,34 @@ describe("NavbarLibrarySection", () => {
});
});
+ it("should render custom icons for library sections with promoted children", async () => {
+ const libraryCollection = createLibraryCollection();
+ const dataCollection = createChildCollection({
+ id: 10,
+ name: "Data Child",
+ type: "library-data",
+ is_library_root: false,
+ });
+ const metricsCollection = createChildCollection({
+ id: 11,
+ name: "Metrics Child",
+ type: "library-metrics",
+ is_library_root: false,
+ });
+
+ setup({
+ collections: [libraryCollection, dataCollection, metricsCollection],
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Data")).toBeInTheDocument();
+ expect(screen.getByText("Metrics")).toBeInTheDocument();
+ });
+
+ expect(screen.getByLabelText("table icon")).toBeInTheDocument();
+ expect(screen.getByLabelText("metric icon")).toBeInTheDocument();
+ });
+
it("should not render when no library collection exists", () => {
const regularCollection = createMockCollection({
id: 2,
@@ -101,8 +129,16 @@ describe("NavbarLibrarySection", () => {
it("should show badge only for collections with changes", async () => {
const libraryCollection = createLibraryCollection({
children: [
- createChildCollection({ id: 10, name: "Dirty Collection" }),
- createChildCollection({ id: 11, name: "Clean Collection" }),
+ createChildCollection({
+ id: 10,
+ name: "Dirty Collection",
+ type: "library-metrics",
+ }),
+ createChildCollection({
+ id: 11,
+ name: "Clean Collection",
+ type: "library-data",
+ }),
],
});
diff --git a/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/setup.tsx b/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/setup.tsx
index c9079abc222..5e181607067 100644
--- a/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/setup.tsx
+++ b/frontend/src/metabase/data-studio/nav/components/NavbarLibrarySection/tests/setup.tsx
@@ -26,12 +26,13 @@ export const createChildCollection = (
createMockCollection({
id: 10,
name: "Metrics",
- type: null,
+ type: "library-metrics",
+ is_library_root: true,
location: "/1/",
here: ["card"],
below: ["card"],
...overrides,
- } as Partial<Collection>);
+ });
export const createLibraryCollection = (
overrides: Partial<Collection> = {},
): Collection =>
@@ -43,7 +44,7 @@ export const createLibraryCollection = (
here: ["card"],
below: ["card"],
...overrides,
- } as Partial<Collection>);
+ });
export const setup = ({
collections = [createLibraryCollection()],
isEnterprise = false,
@@ -68,16 +69,20 @@ export const setup = ({
settings: mockSettings(settings),
currentUser: createMockUser({ is_superuser: true }),
});
-
- const pluginNames: ENTERPRISE_PLUGIN_NAME[] = ["library", "remote_sync"];
+ setupEnterpriseOnlyPlugin("library");
+ const pluginNames: ENTERPRISE_PLUGIN_NAME[] = ["remote_sync"];
pluginNames.forEach(setupEnterpriseOnlyPlugin);
} else {
+ const settings = {
+ "expand-library-in-nav": true,
+ "token-features": createMockTokenFeatures({ library: true }),
+ };
+
state = createMockState({
- settings: mockSettings({
- "expand-library-in-nav": true,
- }),
+ settings: mockSettings(settings),
currentUser: createMockUser({ is_superuser: true }),
});
+ setupEnterpriseOnlyPlugin("library");
}
setupSettingsEndpoints([]);
diff --git a/frontend/src/metabase/data-studio/utils.ts b/frontend/src/metabase/data-studio/utils.ts
index 6419502f9a7..a0df27e6841 100644
--- a/frontend/src/metabase/data-studio/utils.ts
+++ b/frontend/src/metabase/data-studio/utils.ts
@@ -1,44 +1,25 @@
+import { PLUGIN_LIBRARY } from "metabase/plugins";
import type { CollectionItemModel, CollectionType } from "metabase-types/api";
-export type LibraryCollectionType = "root" | "data" | "metrics";
-
-export function getLibraryCollectionType(
- type: CollectionType | null | undefined,
-): LibraryCollectionType | undefined {
- switch (type) {
- case "library":
- return "root";
- case "library-data":
- return "data";
- case "library-metrics":
- return "metrics";
- }
-}
-
export function canPlaceEntityInCollection(
entityType: CollectionItemModel,
collectionType: CollectionType | null | undefined,
): boolean {
- if (getLibraryCollectionType(collectionType) == null) {
+ if (!PLUGIN_LIBRARY.isLibraryCollectionType(collectionType)) {
return true;
}
- // Can't create subcollections in any of special collections
- if (entityType === "collection") {
- return false;
- }
-
// Can't create anything in the root Library collection
if (collectionType === "library") {
return false;
}
if (collectionType === "library-data") {
- return entityType === "table";
+ return entityType === "table" || entityType === "collection";
}
if (collectionType === "library-metrics") {
- return entityType === "metric";
+ return entityType === "metric" || entityType === "collection";
}
return false;
diff --git a/frontend/src/metabase/data-studio/utils.unit.spec.ts b/frontend/src/metabase/data-studio/utils.unit.spec.ts
new file mode 100644
index 00000000000..9b9e9e0dc35
--- /dev/null
+++ b/frontend/src/metabase/data-studio/utils.unit.spec.ts
@@ -0,0 +1,40 @@
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import { mockSettings } from "__support__/settings";
+import { createMockTokenFeatures } from "metabase-types/api/mocks";
+
+import { canPlaceEntityInCollection } from "./utils";
+
+describe("canPlaceEntityInCollection", () => {
+ beforeEach(() => {
+ mockSettings({
+ "token-features": createMockTokenFeatures({ library: true }),
+ });
+ setupEnterpriseOnlyPlugin("library");
+ });
+
+ it("should reject every entity type for the root Library collection", () => {
+ expect(canPlaceEntityInCollection("table", "library")).toBe(false);
+ expect(canPlaceEntityInCollection("metric", "library")).toBe(false);
+ expect(canPlaceEntityInCollection("collection", "library")).toBe(false);
+ });
+
+ it("should only allow tables and collections in Library Data collections", () => {
+ expect(canPlaceEntityInCollection("table", "library-data")).toBe(true);
+ expect(canPlaceEntityInCollection("collection", "library-data")).toBe(true);
+ expect(canPlaceEntityInCollection("metric", "library-data")).toBe(false);
+ });
+
+ it("should only allow metrics and collections in Library Metrics collections", () => {
+ expect(canPlaceEntityInCollection("metric", "library-metrics")).toBe(true);
+ expect(canPlaceEntityInCollection("collection", "library-metrics")).toBe(
+ true,
+ );
+ expect(canPlaceEntityInCollection("table", "library-metrics")).toBe(false);
+ });
+
+ it("should allow entities in non-Library collections", () => {
+ expect(canPlaceEntityInCollection("table", null)).toBe(true);
+ expect(canPlaceEntityInCollection("metric", undefined)).toBe(true);
+ expect(canPlaceEntityInCollection("collection", null)).toBe(true);
+ });
+});
diff --git a/frontend/src/metabase/entities/collections/utils.ts b/frontend/src/metabase/entities/collections/utils.ts
index 2b5f2ffbf9e..908deffe933 100644
--- a/frontend/src/metabase/entities/collections/utils.ts
+++ b/frontend/src/metabase/entities/collections/utils.ts
@@ -3,7 +3,6 @@ import {
isRootTrashCollection,
isSyncedCollection,
} from "metabase/collections/utils";
-import { getLibraryCollectionType } from "metabase/data-studio/utils";
import { PLUGIN_COLLECTIONS } from "metabase/plugins";
import type { State } from "metabase/redux/store";
import { getUserPersonalCollectionId } from "metabase/selectors/user";
@@ -39,13 +38,15 @@ export function getCollectionIcon(
return { name: "synced_collection" };
}
- switch (getLibraryCollectionType(collection.type)) {
- case "root":
- return { name: "repository" };
- case "data":
- return { name: "table" };
- case "metrics":
- return { name: "metric" };
+ if (collection.is_library_root) {
+ switch (collection.type) {
+ case "library":
+ return { name: "repository" };
+ case "library-data":
+ return { name: "table" };
+ case "library-metrics":
+ return { name: "metric" };
+ }
}
const type = PLUGIN_COLLECTIONS.getCollectionType(collection);
@@ -75,6 +76,7 @@ export interface CollectionTreeItem extends Collection {
icon: IconName | IconProps;
children: CollectionTreeItem[];
schemaName?: string;
+ nonNavigable?: boolean;
}
export function buildCollectionTree(
diff --git a/frontend/src/metabase/hooks/use-icon.ts b/frontend/src/metabase/hooks/use-icon.ts
index d29ee3a0523..b9c7ddbd043 100644
--- a/frontend/src/metabase/hooks/use-icon.ts
+++ b/frontend/src/metabase/hooks/use-icon.ts
@@ -2,11 +2,10 @@ import { useCallback } from "react";
import type { IconData, ObjectWithModel } from "metabase/common/utils/icon";
import { modelIconMap } from "metabase/common/utils/icon";
-import { getLibraryCollectionType } from "metabase/data-studio/utils";
import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";
import { PLUGIN_COLLECTIONS, PLUGIN_CUSTOM_VIZ } from "metabase/plugins";
import { getIconForVisualizationType } from "metabase/visualizations";
-import type { CollectionType, VisualizationDisplay } from "metabase-types/api";
+import type { VisualizationDisplay } from "metabase-types/api";
export const useGetIconForVisualizationType = () => {
const getCustomVizIcon = PLUGIN_CUSTOM_VIZ.useCustomVizPluginsIcon();
@@ -52,15 +51,13 @@ export const useGetIconBase = () => {
return { name: "database" };
}
- if (item.model === "collection") {
- switch (
- getLibraryCollectionType(item.type as unknown as CollectionType)
- ) {
- case "root":
+ if (item.model === "collection" && item.is_library_root === true) {
+ switch (item.type) {
+ case "library":
return { name: "repository" };
- case "data":
+ case "library-data":
return { name: "table" };
- case "metrics":
+ case "library-metrics":
return { name: "metric" };
}
}
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsx
index 652fd909a21..f4e748aa3dc 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsx
@@ -11,10 +11,13 @@ import {
import { ForwardRefLink } from "metabase/common/components/Link";
import { ToolbarButton } from "metabase/common/components/ToolbarButton";
import { canAccessDataStudio as canAccessDataStudioSelector } from "metabase/data-studio/selectors";
-import { getLibraryCollectionType } from "metabase/data-studio/utils";
import { isNumericMetric } from "metabase/metrics/utils/validation";
import { QuestionAlertListModal } from "metabase/notifications/modals/QuestionAlertListModal";
-import { PLUGIN_AUDIT, PLUGIN_MODERATION } from "metabase/plugins";
+import {
+ PLUGIN_AUDIT,
+ PLUGIN_LIBRARY,
+ PLUGIN_MODERATION,
+} from "metabase/plugins";
import { AddToDashSelectDashModal } from "metabase/query_builder/components/AddToDashSelectDashModal";
import { ArchiveCardModal } from "metabase/questions/components/ArchiveCardModal";
import { CardCopyModal } from "metabase/questions/components/CardCopyModal";
@@ -105,7 +108,7 @@ function MetricToolbarButtons({
const showDataStudioLink =
showDataStudioLinkProp &&
- getLibraryCollectionType(card.collection?.type) != null &&
+ PLUGIN_LIBRARY.isLibraryCollectionType(card.collection?.type) &&
canAccessDataStudio;
return (
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx
index 52edffbf3b9..b6d5d784200 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx
@@ -1,15 +1,17 @@
import userEvent from "@testing-library/user-event";
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import { setupBookmarksEndpoints } from "__support__/server-mocks/bookmark";
import { setupListNotificationEndpoints } from "__support__/server-mocks/notification";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, within } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
-import type { CollectionType, User } from "metabase-types/api";
+import type { CollectionType } from "metabase-types/api";
import {
createMockCard,
createMockCollection,
createMockSettings,
+ createMockTokenFeatures,
createMockUser,
} from "metabase-types/api/mocks";
@@ -49,6 +51,8 @@ function setup({
showDataStudioLink = false,
collectionType = null,
}: SetupOpts = {}) {
+ setupEnterpriseOnlyPlugin("library");
+
const Lib = jest.requireMock("metabase-lib");
Lib.queryDisplayInfo.mockReturnValue({ isEditable });
@@ -62,11 +66,13 @@ function setup({
is_superuser: isAdmin,
});
- const settingValues = createMockSettings();
+ const settingValues = createMockSettings({
+ "token-features": createMockTokenFeatures({ library: true }),
+ });
const state = createMockState({
settings: mockSettings(settingValues),
- currentUser: user as User,
+ currentUser: user,
});
setupBookmarksEndpoints([]);
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarCollectionLink.tsx b/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarCollectionLink.tsx
index 1eb72ea9d1c..e3ff68d2a89 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarCollectionLink.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarCollectionLink.tsx
@@ -18,6 +18,7 @@ import type { Collection } from "metabase-types/api";
import {
CollectionNodeRoot,
ExpandToggleButton,
+ FullWidthContainer,
FullWidthLink,
NameContainer,
SidebarIcon,
@@ -30,6 +31,7 @@ type DroppableProps = {
type Props = DroppableProps &
Omit<TreeNodeProps, "item"> & {
+ nonNavigable?: boolean;
collection: Collection;
};
@@ -39,6 +41,7 @@ const SidebarCollectionLink = forwardRef<HTMLLIElement, Props>(
function SidebarCollectionLink(
{
collection,
+ nonNavigable,
hovered: isHovered,
depth,
onSelect,
@@ -96,6 +99,16 @@ const SidebarCollectionLink = forwardRef<HTMLLIElement, Props>(
collection as unknown as Collection,
);
+ const content = (
+ <>
+ <TreeNode.IconContainer transparent={false}>
+ <SidebarIcon {...icon} isSelected={isSelected} />
+ </TreeNode.IconContainer>
+ <NameContainer>{collection.name}</NameContainer>
+ {rightSection?.(collection as unknown as ITreeNodeItem)}
+ </>
+ );
+
return (
<CollectionNodeRoot
role="treeitem"
@@ -114,13 +127,15 @@ const SidebarCollectionLink = forwardRef<HTMLLIElement, Props>(
size={12}
/>
</ExpandToggleButton>
- <FullWidthLink to={url} onClick={onSelect} onKeyDown={onKeyDown}>
- <TreeNode.IconContainer transparent={false}>
- <SidebarIcon {...icon} isSelected={isSelected} />
- </TreeNode.IconContainer>
- <NameContainer>{collection.name}</NameContainer>
- {rightSection?.(collection as unknown as ITreeNodeItem)}
- </FullWidthLink>
+ {nonNavigable ? (
+ <FullWidthContainer onKeyDown={onKeyDown}>
+ {content}
+ </FullWidthContainer>
+ ) : (
+ <FullWidthLink to={url} onClick={onSelect} onKeyDown={onKeyDown}>
+ {content}
+ </FullWidthLink>
+ )}
</CollectionNodeRoot>
);
},
@@ -132,18 +147,27 @@ const DroppableSidebarCollectionLink = forwardRef<HTMLLIElement, TreeNodeProps>(
ref,
) {
const collection = item as unknown as Collection;
+
+ const link = (droppableProps?: DroppableProps) => (
+ <SidebarCollectionLink
+ {...props}
+ hovered={droppableProps?.hovered ?? false}
+ highlighted={droppableProps?.highlighted ?? false}
+ collection={collection}
+ nonNavigable={item.nonNavigable}
+ ref={ref}
+ />
+ );
+
return (
<div data-testid="sidebar-collection-link-root">
- <CollectionDropTarget collection={collection}>
- {(droppableProps: DroppableProps) => (
- <SidebarCollectionLink
- {...props}
- {...droppableProps}
- collection={collection}
- ref={ref}
- />
- )}
- </CollectionDropTarget>
+ {item.nonNavigable ? (
+ link()
+ ) : (
+ <CollectionDropTarget collection={collection}>
+ {(droppableProps: DroppableProps) => link(droppableProps)}
+ </CollectionDropTarget>
+ )}
</div>
);
},
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarItems.styled.tsx b/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarItems.styled.tsx
index ebb14e3b71d..98c27d43560 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarItems.styled.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarItems.styled.tsx
@@ -128,6 +128,11 @@ export const FullWidthLink = styled(Link)`
}
`;
+export const FullWidthContainer = styled.div`
+ ${itemContentStyle}
+ cursor: pointer;
+`;
+
const ITEM_NAME_LENGTH_TOOLTIP_THRESHOLD = 35;
const ITEM_NAME_LABEL_WIDTH = Math.round(parseInt(NAV_SIDEBAR_WIDTH, 10) * 0.7);
diff --git a/frontend/src/metabase/new/components/NewModals/NewModals.tsx b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
index 47b87b2dc9b..171cf19c9f3 100644
--- a/frontend/src/metabase/new/components/NewModals/NewModals.tsx
+++ b/frontend/src/metabase/new/components/NewModals/NewModals.tsx
@@ -5,7 +5,9 @@ import { push } from "react-router-redux";
import { useLocation } from "react-use";
import ActionCreator from "metabase/actions/containers/ActionCreator";
-import CreateCollectionModal from "metabase/collections/containers/CreateCollectionModal";
+import CreateCollectionModal, {
+ type CreateCollectionModalOwnProps,
+} from "metabase/collections/containers/CreateCollectionModal";
import { useInitialCollectionId } from "metabase/collections/hooks";
import { CreateDashboardModal } from "metabase/common/CreateDashboard/CreateDashboardModal";
import { Modal } from "metabase/common/components/Modal";
@@ -28,7 +30,7 @@ import type { WritebackAction } from "metabase-types/api";
export const NewModals = withRouter((props: WithRouterProps) => {
const { pathname } = useLocation();
const { id: currentNewModalId, props: currentNewModalProps } = useSelector(
- getCurrentOpenModalState,
+ getCurrentOpenModalState<CreateCollectionModalOwnProps>,
);
const dispatch = useDispatch();
const collectionId = useInitialCollectionId(props) ?? undefined;
@@ -67,13 +69,17 @@ export const NewModals = withRouter((props: WithRouterProps) => {
);
switch (currentNewModalId) {
- case "collection":
+ case "collection": {
+ const collectionProps = currentNewModalProps || null;
+
return (
<CreateCollectionModal
onClose={handleModalClose}
- collectionId={collectionId}
+ {...collectionProps}
+ collectionId={collectionProps?.collectionId ?? collectionId}
/>
);
+ }
case "dashboard":
return (
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 52f925e77e4..21bb354f661 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -47,7 +47,6 @@ export {
PLUGIN_FORM_WIDGETS,
PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS,
PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS,
- PLUGIN_SNIPPET_SIDEBAR_MODALS,
PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS,
PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE,
PLUGIN_REDUCERS,
@@ -70,6 +69,7 @@ export { PLUGIN_EMBEDDING_SDK } from "./oss/embedding-sdk";
export { PLUGIN_ENTITIES } from "./oss/entities";
export {
PLUGIN_LIBRARY,
+ type CollectionPermissionsModalProps,
type CreateLibraryModalProps,
type PublishTablesModalProps,
type UnpublishTablesModalProps,
@@ -118,8 +118,6 @@ export { PLUGIN_SMTP_OVERRIDE } from "./oss/smtp-override";
export {
PLUGIN_SNIPPET_FOLDERS,
type MoveSnippetModalProps,
- type SnippetFormModalProps,
- type SnippetCollectionMenuProps,
type SnippetCollectionPermissionsModalProps,
type SnippetCollectionPickerModalProps,
} from "./oss/snippets";
diff --git a/frontend/src/metabase/plugins/oss/core.ts b/frontend/src/metabase/plugins/oss/core.ts
index c0e83266edb..9f366b53f16 100644
--- a/frontend/src/metabase/plugins/oss/core.ts
+++ b/frontend/src/metabase/plugins/oss/core.ts
@@ -108,14 +108,12 @@ export const PLUGIN_FORM_WIDGETS = getDefaultFormWidgets();
const getDefaultSnippetSidebarPlusMenuOptions = () => [];
const getDefaultSnippetSidebarRowRenderers = () => ({});
-const getDefaultSnippetSidebarModals = () => [];
const getDefaultSnippetSidebarHeaderButtons = () => [];
export const PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS =
getDefaultSnippetSidebarPlusMenuOptions();
export const PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS =
getDefaultSnippetSidebarRowRenderers();
-export const PLUGIN_SNIPPET_SIDEBAR_MODALS = getDefaultSnippetSidebarModals();
export const PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS =
getDefaultSnippetSidebarHeaderButtons();
@@ -183,9 +181,6 @@ export function reinitialize() {
getDefaultSnippetSidebarRowRenderers(),
);
- PLUGIN_SNIPPET_SIDEBAR_MODALS.length = 0;
- PLUGIN_SNIPPET_SIDEBAR_MODALS.push(...getDefaultSnippetSidebarModals());
-
PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.length = 0;
PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.push(
...getDefaultSnippetSidebarHeaderButtons(),
diff --git a/frontend/src/metabase/plugins/oss/library.ts b/frontend/src/metabase/plugins/oss/library.ts
index c9590cb37d8..485ba0d01b3 100644
--- a/frontend/src/metabase/plugins/oss/library.ts
+++ b/frontend/src/metabase/plugins/oss/library.ts
@@ -2,11 +2,18 @@ import type { BaseQueryFn, QueryDefinition } from "@reduxjs/toolkit/query";
import type { ComponentType, ReactNode } from "react";
import type { TagType } from "metabase/api/tags";
+import type {
+ OmniPickerCollectionItem,
+ OmniPickerItem,
+} from "metabase/common/components/Pickers/EntityPicker/types";
+import type { MiniPickerCollectionFolderItem } from "metabase/common/components/Pickers/MiniPicker/types";
import type { UseQuery } from "metabase/entities/containers/rtk-query/types/rtk";
import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";
import type {
Collection,
+ CollectionId,
CollectionItem,
+ CollectionNamespace,
CollectionType,
DatabaseId,
GetLibraryCollectionResponse,
@@ -40,6 +47,33 @@ export type UnpublishTablesModalProps = {
onClose: () => void;
};
+export type CollectionPermissionsModalProps = {
+ collectionId: CollectionId;
+ namespace?: CollectionNamespace | null;
+ onClose: () => void;
+};
+
+export type LibraryCollectionType =
+ | "library"
+ | "library-data"
+ | "library-metrics";
+
+export type LibrarySubCollectionType = "library-data" | "library-metrics";
+
+export type GetEntityPickerSyntheticLibraryItemFunction = {
+ (params: {
+ collectionId: CollectionId;
+ type: LibrarySubCollectionType;
+ miniPicker: true;
+ }): MiniPickerCollectionFolderItem | undefined;
+
+ (params: {
+ collectionId: CollectionId;
+ type: LibrarySubCollectionType;
+ miniPicker?: false | undefined;
+ }): OmniPickerCollectionItem | undefined;
+};
+
type LibraryPlugin = {
isEnabled: boolean;
getDataStudioLibraryRoutes: (IsAdmin: ComponentType) => ReactNode;
@@ -58,12 +92,31 @@ type LibraryPlugin = {
data: undefined | LibraryCollection | CollectionItem;
isLoading: boolean;
};
+ getCollectionPickerItems: ({
+ parentItem,
+ items,
+ }: {
+ parentItem: OmniPickerItem;
+ items: CollectionItem[];
+ }) => OmniPickerItem[] | undefined;
+ getEntityPickerSyntheticLibraryItem: GetEntityPickerSyntheticLibraryItemFunction;
CreateLibraryModal: ComponentType<CreateLibraryModalProps>;
+ CollectionPermissionsModal: ComponentType<CollectionPermissionsModalProps>;
PublishTablesModal: ComponentType<PublishTablesModalProps>;
UnpublishTablesModal: ComponentType<UnpublishTablesModalProps>;
useGetLibraryCollectionQuery: UseQuery<
QueryDefinition<void, BaseQueryFn, TagType, GetLibraryCollectionResponse>
>;
+ getLibraryCollectionEmptyStateMessages: (type: LibrarySubCollectionType) => {
+ title: string;
+ description: string;
+ };
+ isLibraryCollectionType: (
+ type?: string | null,
+ ) => type is LibraryCollectionType;
+ isLibrarySubCollectionType: (
+ type?: string | null,
+ ) => type is LibrarySubCollectionType;
};
const getDefaultPluginLibrary = (): LibraryPlugin => ({
@@ -75,14 +128,28 @@ const getDefaultPluginLibrary = (): LibraryPlugin => ({
isLoading: false,
data: undefined,
}),
+ getCollectionPickerItems: () => undefined,
+ getEntityPickerSyntheticLibraryItem: () => undefined,
CreateLibraryModal:
PluginPlaceholder as ComponentType<CreateLibraryModalProps>,
+ CollectionPermissionsModal:
+ PluginPlaceholder as ComponentType<CollectionPermissionsModalProps>,
PublishTablesModal:
PluginPlaceholder as ComponentType<PublishTablesModalProps>,
UnpublishTablesModal:
PluginPlaceholder as ComponentType<UnpublishTablesModalProps>,
useGetLibraryCollectionQuery:
(() => []) as unknown as LibraryPlugin["useGetLibraryCollectionQuery"],
+ getLibraryCollectionEmptyStateMessages: () => ({
+ title: "",
+ description: "",
+ }),
+ isLibraryCollectionType: (
+ _type?: string | null,
+ ): _type is LibraryCollectionType => false,
+ isLibrarySubCollectionType: (
+ _type?: string | null,
+ ): _type is LibrarySubCollectionType => false,
});
export const PLUGIN_LIBRARY = getDefaultPluginLibrary();
diff --git a/frontend/src/metabase/plugins/oss/snippets.ts b/frontend/src/metabase/plugins/oss/snippets.ts
index 7f806019f11..c8fdc7b177c 100644
--- a/frontend/src/metabase/plugins/oss/snippets.ts
+++ b/frontend/src/metabase/plugins/oss/snippets.ts
@@ -1,11 +1,7 @@
import type { Component, ComponentType } from "react";
import type { IconName } from "metabase/ui";
-import type {
- Collection,
- CollectionId,
- NativeQuerySnippet,
-} from "metabase-types/api";
+import type { CollectionId, NativeQuerySnippet } from "metabase-types/api";
import { PluginPlaceholder } from "../components/PluginPlaceholder";
@@ -17,7 +13,6 @@ export type SnippetSidebarMenuOption = {
};
export type SnippetSidebarState = {
- modalSnippetCollection?: Partial<Collection> | null;
permissionsModalCollectionId?: CollectionId | null;
};
@@ -36,19 +31,6 @@ export type SnippetCollectionPickerModalProps = {
onClose: () => void;
};
-export type SnippetFormModalProps = {
- collection: Partial<Collection>;
- onClose: () => void;
- onSaved?: () => void;
- opened?: boolean;
-};
-
-export type SnippetCollectionMenuProps = {
- collection: Collection;
- onEditDetails?: (collection: Collection) => void;
- onChangePermissions?: (collectionId: CollectionId) => void;
-};
-
export type SnippetCollectionPermissionsModalProps = {
collectionId: CollectionId;
onClose: () => void;
@@ -62,8 +44,6 @@ export type MoveSnippetModalProps = {
export type SnippetFoldersPlugin = {
isEnabled: boolean;
CollectionPickerModal: ComponentType<SnippetCollectionPickerModalProps>;
- CollectionFormModal: ComponentType<SnippetFormModalProps>;
- CollectionMenu: ComponentType<SnippetCollectionMenuProps>;
CollectionPermissionsModal: ComponentType<SnippetCollectionPermissionsModalProps>;
MoveSnippetModal: ComponentType<MoveSnippetModalProps>;
};
@@ -72,10 +52,6 @@ export const getDefaultPluginSnippetFolders = () => ({
isEnabled: false,
CollectionPickerModal:
PluginPlaceholder as ComponentType<SnippetCollectionPickerModalProps>,
- CollectionFormModal:
- PluginPlaceholder as ComponentType<SnippetFormModalProps>,
- CollectionMenu:
- PluginPlaceholder as ComponentType<SnippetCollectionMenuProps>,
CollectionPermissionsModal:
PluginPlaceholder as ComponentType<SnippetCollectionPermissionsModalProps>,
MoveSnippetModal: PluginPlaceholder as ComponentType<MoveSnippetModalProps>,
diff --git a/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx b/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx
index 2b2226c46e4..d14f503d590 100644
--- a/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx
+++ b/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx
@@ -119,7 +119,7 @@ function SnippetFormInner({
)}
<FormErrorMessage inline />
</Flex>
- <Flex align="center" justify="center" gap="sm">
+ <Flex align="center" justify="center" gap="sm" mt="md">
{!!onCancel && (
<Button type="button" onClick={onCancel}>{t`Cancel`}</Button>
)}
diff --git a/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx b/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx
index 5e4d9c55112..fe8cd7773b0 100644
--- a/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx
+++ b/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx
@@ -15,7 +15,6 @@ import { Snippets } from "metabase/entities/snippets";
import {
PLUGIN_REMOTE_SYNC,
PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS,
- PLUGIN_SNIPPET_SIDEBAR_MODALS,
PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS,
PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS,
} from "metabase/plugins";
@@ -244,7 +243,6 @@ class SnippetSidebarInner extends React.Component {
</Flex>
</>
)}
- {PLUGIN_SNIPPET_SIDEBAR_MODALS.map((f) => f(this))}
</SidebarContent>
);
}
diff --git a/frontend/src/metabase/querying/components/SnippetSidebar/tests/premium.unit.spec.tsx b/frontend/src/metabase/querying/components/SnippetSidebar/tests/premium.unit.spec.tsx
index d3552459980..e0d973cf6e2 100644
--- a/frontend/src/metabase/querying/components/SnippetSidebar/tests/premium.unit.spec.tsx
+++ b/frontend/src/metabase/querying/components/SnippetSidebar/tests/premium.unit.spec.tsx
@@ -10,7 +10,7 @@ import type { SetupOpts } from "./setup";
import { setup as baseSetup } from "./setup";
async function setup(options: SetupOpts = {}) {
- await baseSetup({
+ return await baseSetup({
enterprisePlugins: ["snippets"],
tokenFeatures: { snippet_collections: true },
...options,
@@ -42,4 +42,21 @@ describe("SnippetSidebar (EE with token feature)", () => {
expect(await screen.findByText("New snippet")).toBeInTheDocument();
expect(screen.getByText("New folder")).toBeInTheDocument();
});
+
+ it("should open the collection modal when creating a new folder", async () => {
+ const { store } = await setup();
+
+ await userEvent.click(getIcon("add"));
+ await userEvent.click(await screen.findByText("New folder"));
+
+ expect(store.getState().modal).toMatchObject({
+ id: "collection",
+ props: {
+ initialCollectionId: null,
+ namespaces: ["snippets"],
+ showAuthorityLevelPicker: false,
+ shouldNavigateOnCreate: false,
+ },
+ });
+ });
});
diff --git a/frontend/src/metabase/querying/components/SnippetSidebar/tests/setup.tsx b/frontend/src/metabase/querying/components/SnippetSidebar/tests/setup.tsx
index b216a511ae3..455b83dc688 100644
--- a/frontend/src/metabase/querying/components/SnippetSidebar/tests/setup.tsx
+++ b/frontend/src/metabase/querying/components/SnippetSidebar/tests/setup.tsx
@@ -54,7 +54,7 @@ export async function setup({
enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
}
- renderWithProviders(
+ const utils = renderWithProviders(
<SnippetSidebar
onClose={() => null}
setModalSnippet={() => null}
@@ -68,4 +68,6 @@ export async function setup({
},
);
await waitForLoaderToBeRemoved();
+
+ return utils;
}
diff --git a/frontend/src/metabase/transforms/components/EditTransformCollectionModal/index.ts b/frontend/src/metabase/transforms/components/EditTransformCollectionModal/index.ts
deleted file mode 100644
index a03442a23ca..00000000000
--- a/frontend/src/metabase/transforms/components/EditTransformCollectionModal/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { EditTransformCollectionModal } from "./EditTransformCollectionModal";
diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsx b/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsx
index 4b5c39a6101..96d46ed706a 100644
--- a/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsx
+++ b/frontend/src/metabase/transforms/pages/TransformListPage/CollectionRowMenu.tsx
@@ -1,98 +1,28 @@
-import { useState } from "react";
import { msgid, ngettext, t } from "ttag";
-import { useUpdateCollectionMutation } from "metabase/api";
-import { useConfirmation } from "metabase/common/hooks/use-confirmation";
-import { useDispatch } from "metabase/redux";
-import { addUndo } from "metabase/redux/undo";
-import { EditTransformCollectionModal } from "metabase/transforms/components/EditTransformCollectionModal";
-import { ActionIcon, Box, Icon, Menu } from "metabase/ui";
+import { CollectionRowMenu as BaseCollectionRowMenu } from "metabase/collections/components/CollectionRowMenu";
+import type { Collection } from "metabase-types/api";
type CollectionRowMenuProps = {
- collectionId: number;
- collectionName: string;
+ collection: Collection;
transformCount: number;
};
-export function CollectionRowMenu({
- collectionId,
- collectionName,
- transformCount,
-}: CollectionRowMenuProps) {
- const dispatch = useDispatch();
- const [updateCollection] = useUpdateCollectionMutation();
- const { show, modalContent } = useConfirmation();
- const [isEditModalOpen, setIsEditModalOpen] = useState(false);
-
- const handleArchive = async () => {
- try {
- await updateCollection({ id: collectionId, archived: true }).unwrap();
- dispatch(
- addUndo({
- message: t`Collection archived`,
- action: async () => {
- await updateCollection({ id: collectionId, archived: false });
- },
- }),
- );
- } catch {
- dispatch(
- addUndo({
- message: t`Failed to archive collection`,
- icon: "warning",
- }),
- );
- }
- };
-
- const handleArchiveClick = () => {
- const message =
- transformCount > 0
- ? ngettext(
- msgid`This will also archive ${transformCount} transform inside it.`,
- `This will also archive ${transformCount} transforms inside it.`,
- transformCount,
- )
- : t`Are you sure you want to archive this collection?`;
-
- show({
- title: t`Archive "${collectionName}"?`,
- message,
- confirmButtonText: t`Archive`,
- onConfirm: handleArchive,
- });
- };
+export function CollectionRowMenu(props: CollectionRowMenuProps) {
+ const { collection, transformCount } = props;
return (
- <Box onClick={(e) => e.stopPropagation()}>
- <Menu position="bottom-end">
- <Menu.Target>
- <ActionIcon size="sm" aria-label={t`Collection menu`}>
- <Icon name="ellipsis" />
- </ActionIcon>
- </Menu.Target>
- <Menu.Dropdown>
- <Menu.Item
- leftSection={<Icon name="pencil" />}
- onClick={() => setIsEditModalOpen(true)}
- >
- {t`Edit collection details`}
- </Menu.Item>
- <Menu.Item
- leftSection={<Icon name="archive" />}
- onClick={handleArchiveClick}
- >
- {t`Archive`}
- </Menu.Item>
- </Menu.Dropdown>
- </Menu>
- {modalContent}
- {isEditModalOpen && (
- <EditTransformCollectionModal
- collectionId={collectionId}
- onClose={() => setIsEditModalOpen(false)}
- />
- )}
- </Box>
+ <BaseCollectionRowMenu
+ collection={collection}
+ customArchiveMessage={
+ transformCount > 0
+ ? ngettext(
+ msgid`This will also archive ${transformCount} transform inside it.`,
+ `This will also archive ${transformCount} transforms inside it.`,
+ transformCount,
+ )
+ : t`Are you sure you want to archive this folder?`
+ }
+ />
);
}
diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
index 321cc2e8f02..e6b8e85884b 100644
--- a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
+++ b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
@@ -259,8 +259,7 @@ export const TransformListPage = ({
cell: ({ row }) =>
isCollectionNode(row.original) ? (
<CollectionRowMenu
- collectionId={row.original.collectionId}
- collectionName={row.original.name}
+ collection={row.original.collection}
transformCount={countTransforms(row.original)}
/>
) : null,
diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/types.ts b/frontend/src/metabase/transforms/pages/TransformListPage/types.ts
index 8748cfe2b08..36ea4b051cc 100644
--- a/frontend/src/metabase/transforms/pages/TransformListPage/types.ts
+++ b/frontend/src/metabase/transforms/pages/TransformListPage/types.ts
@@ -1,5 +1,5 @@
import type { IconName } from "metabase/ui";
-import type { Transform, TransformOwner } from "metabase-types/api";
+import type { Collection, Transform, TransformOwner } from "metabase-types/api";
export type TreeNodeType = "folder" | "transform" | "library";
@@ -14,7 +14,7 @@ export type TreeNode = {
owner_email?: string | null;
children?: TreeNode[];
transformId?: number;
- collectionId?: number;
+ collection?: Collection;
url?: string;
source_readable?: boolean;
warningTooltip?: string;
@@ -22,8 +22,8 @@ export type TreeNode = {
export function isCollectionNode(
node: TreeNode,
-): node is TreeNode & { collectionId: number } {
- return node.nodeType === "folder" && typeof node.collectionId === "number";
+): node is TreeNode & { collection: Collection } {
+ return node.nodeType === "folder" && typeof node.collection?.id === "number";
}
export function getCollectionNodeId(collectionId: number): string {
diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/utils.ts b/frontend/src/metabase/transforms/pages/TransformListPage/utils.ts
index 374c78a9caa..d6116e5098e 100644
--- a/frontend/src/metabase/transforms/pages/TransformListPage/utils.ts
+++ b/frontend/src/metabase/transforms/pages/TransformListPage/utils.ts
@@ -125,7 +125,7 @@ export function buildTreeData(
nodeType: "folder",
icon: getCollectionIcon(collection).name,
children: [...childFolders, ...childTransforms],
- collectionId: collection.id as number,
+ collection,
};
}
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index 8cd438cb7ee..9d3dc597788 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -192,6 +192,12 @@
(def ^:private library-metrics-entity-id
"librarylibrarymetrics")
+(def ^:private library-entity-id?
+ "Returns true if the given entity ID is one of the hard-coded Library keys."
+ #{library-entity-id
+ library-data-entity-id
+ library-metrics-entity-id})
+
(defn create-library-collection!
"Create the Library collection. Returns Created collection. Throws if it already exists."
[]
@@ -226,16 +232,30 @@
{:namespace mi/transform-keyword
:authority_level mi/transform-keyword})
+(defn library-root-collection?
+ "Is this one of the immutable system-created Library collections (root, data, or metrics)?
+ Returns false for user-created subcollections that inherit a library type."
+ [collection]
+ (library-entity-id? (:entity_id collection)))
+
(defn maybe-localize-system-collection-name
"If the collection is a system-defined collection (Trash, Library, Data, or Metrics), translate the `name`.
+ Only overrides names for the system-created library collections, not user-created subcollections.
This is a public function because we can't rely on `define-after-select` in all circumstances, e.g. when searching
or listing collection items (where we do a direct DB query without `:model/Collection`)."
[collection]
(cond-> collection
- (is-trash? collection) (assoc :name (tru "Trash"))
- (is-library? collection) (assoc :name (tru "Library"))
- (is-library-data-collection? collection) (assoc :name (tru "Data"))
- (is-library-metrics-collection? collection) (assoc :name (tru "Metrics"))))
+ (is-trash? collection)
+ (assoc :name (tru "Trash"))
+
+ (and (is-library? collection) (library-root-collection? collection))
+ (assoc :name (tru "Library"))
+
+ (and (is-library-data-collection? collection) (library-root-collection? collection))
+ (assoc :name (tru "Data"))
+
+ (and (is-library-metrics-collection? collection) (library-root-collection? collection))
+ (assoc :name (tru "Metrics"))))
(t2/define-after-select :model/Collection [collection]
(maybe-localize-system-collection-name collection))
@@ -519,6 +539,16 @@
:name collection-name
:slug (u/slugify collection-name))))) collections)))
+(defn maybe-mark-collection-as-library-root
+ "Given a collection, adds `:is_library_root true` to exactly those collections which have hard-coded Library
+ `:entity_id`s - the Library itself, and it's magic top-level collections.
+
+ This uses the `:entity_id`s rather than `:type`s because it only applies to those root collections at the top level,
+ not to all of them."
+ [{:keys [entity_id] :as collection}]
+ (cond-> collection
+ (library-entity-id? entity_id) (assoc :is_library_root true)))
+
(defn personal-collection-with-ui-details
"For Personal collection, we make sure the collection's name and slug is translated to user's locale
This is only used for displaying purposes, For insertion or updating the name, use site's locale instead"
@@ -1151,13 +1181,13 @@
[collection :- CollectionWithLocationAndIDOrRoot
visibility-config :- CollectionVisibilityConfig
& additional-honeysql-where-clauses]
- {:select [:id :name :description]
+ {:select [:id :name :description :type]
:from [[:collection :col]]
:where (apply effective-children-where-clause collection :col visibility-config additional-honeysql-where-clauses)})
(mu/defn- effective-children* :- [:set (ms/InstanceOf :model/Collection)]
[collection :- CollectionWithLocationAndIDOrRoot & additional-honeysql-where-clauses]
- (set (t2/select [:model/Collection :id :name :description]
+ (set (t2/select [:model/Collection :id :name :description :type]
{:where (apply effective-children-where-clause
collection
(t2/table-name :model/Collection)
@@ -1555,7 +1585,14 @@
(doseq [model (archived-directly-models)]
(t2/update! model {:collection_id [:in affected-collection-ids]
:archived_directly false}
- {:archived true})))
+ {:archived true}))
+ (let [library-data-ids (t2/select-pks-set :model/Collection
+ :id [:in affected-collection-ids]
+ :type library-data-collection-type)]
+ (when (seq library-data-ids)
+ (t2/update! :model/Table {:collection_id [:in library-data-ids]}
+ {:collection_id nil
+ :is_published false}))))
(let [updated-collection (t2/select-one :model/Collection :id (:id collection))]
(when (:is_remote_synced updated-collection)
(check-remote-synced-dependents updated-collection)))))
diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.clj
index 978ce3f0909..77079d70767 100644
--- a/src/metabase/collections_rest/api.clj
+++ b/src/metabase/collections_rest/api.clj
@@ -174,10 +174,22 @@
;; remove the :metabase.collection.models.collection.root/is-root? tag since FE doesn't need it
;; and for personal/tenant collections we translate the name to user's locale
(->> (for [collection collections]
- (dissoc collection ::collection.root/is-root?))
+ (-> collection
+ (dissoc ::collection.root/is-root?)
+ collection/maybe-mark-collection-as-library-root))
collection/personal-collections-with-ui-details
collection/maybe-localize-tenant-collection-names)))
+(defn- prep-collection-for-export
+ "Given a collection, tweaks it to be ready for returning to the FE.
+
+ These same functions were called in several places in this namespace, so they're combined here to keep it DRY."
+ [coll]
+ (-> coll
+ collection/personal-collection-with-ui-details
+ collection/maybe-localize-tenant-collection-name
+ collection/maybe-mark-collection-as-library-root))
+
(defn- shallow-tree-from-collection-id
"Returns only a shallow Collection in the provided collection-id, e.g.
@@ -194,8 +206,7 @@
```"
[colls]
(->> colls
- (map (comp collection/maybe-localize-tenant-collection-name
- collection/personal-collection-with-ui-details))
+ (map prep-collection-for-export)
(collection/collections->tree nil)
(map (fn [coll] (update coll :children #(boolean (seq %)))))))
@@ -282,9 +293,7 @@
[:= :archived_at nil]]})
(map :collection_id)
(into #{}))}))
- collections-with-details (map (comp collection/maybe-localize-tenant-collection-name
- collection/personal-collection-with-ui-details)
- collections)]
+ collections-with-details (map prep-collection-for-export collections)]
(collection/collections->tree collection-type-ids collections-with-details)))))
;;; --------------------------------- Fetching a single Collection & its 'children' ----------------------------------
@@ -888,6 +897,7 @@
(-> (t2/instance :model/Collection row)
collection/maybe-localize-system-collection-name
collection/maybe-localize-tenant-collection-name
+ collection/maybe-mark-collection-as-library-root
(update :archived api/bit->boolean)
(update :is_remote_synced api/bit->boolean)
(t2/hydrate :can_write :effective_location :can_restore :can_delete :is_shared_tenant_collection)
@@ -1151,8 +1161,7 @@
Works for either a normal Collection or the Root Collection."
[collection :- collection/CollectionWithLocationAndIDOrRoot]
(-> collection
- collection/personal-collection-with-ui-details
- collection/maybe-localize-tenant-collection-name
+ prep-collection-for-export
(t2/hydrate :parent_id
:effective_location
[:effective_ancestors :can_write]
@@ -1429,7 +1438,8 @@
(malli.util/assoc :location [:maybe ms/NonBlankString])
(malli.util/assoc :namespace [:maybe [:or :keyword ms/NonBlankString]])
(malli.util/assoc :is_remote_synced [:maybe :boolean])
- (malli.util/optional-keys [:location])
+ (malli.util/assoc :type [:enum "trash" "library" "library-data" "library-metrics"])
+ (malli.util/optional-keys [:location :type])
(malli.util/closed-schema)))
(mu/defn- apply-defaults-to-collection :- NewCollectionArguments
@@ -1441,7 +1451,9 @@
(-> (cond-> coll-data
(and (:namespace parent-coll)
(nil? (:namespace coll-data))) (assoc :namespace (:namespace parent-coll))
- parent-coll (assoc :location (collection/children-location parent-coll)))
+ parent-coll (assoc :location (collection/children-location parent-coll))
+ (and (:type parent-coll)
+ (not= (:type parent-coll) "trash")) (assoc :type (:type parent-coll)))
(assoc :is_remote_synced (boolean (:is_remote_synced parent-coll)))
(select-keys (malli.util/keys NewCollectionArguments)))))
diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.clj
index 069b0731bf3..121046d1510 100644
--- a/src/metabase/warehouse_schema/models/table.clj
+++ b/src/metabase/warehouse_schema/models/table.clj
@@ -3,6 +3,7 @@
[metabase.api.common :as api]
[metabase.app-db.core :as app-db]
[metabase.audit-app.core :as audit]
+ [metabase.collections.models.collection :as collection]
[metabase.driver :as driver]
[metabase.models.humanization :as humanization]
[metabase.models.interface :as mi]
@@ -174,6 +175,7 @@
(let [defaults {:display_name (humanization/name->human-readable-name (:name table))
:field_order (driver/default-field-order (t2/select-one-fn :engine :model/Database :id (:db_id table)))
:data_layer :internal}]
+ (collection/check-allowed-content :table (:collection_id table))
(merge defaults table)))
(t2/define-before-delete :model/Table
@@ -189,6 +191,11 @@
current-active (:active original-table)
new-active (:active changes)]
+ ;; Don't allow tables to be moved into collections which are not part of the Library's "Data" collection.
+ ;; Tables can be moved out of any collection, however.
+ (when (:collection_id changes)
+ (collection/check-allowed-content :table (:collection_id changes)))
+
;; Prevent setting data_authority back to unconfigured once configured
(when (and (not= (keyword (:data_authority original-table :unconfigured)) :unconfigured)
(= (keyword (:data_authority changes)) :unconfigured))
diff --git a/src/metabase/warehouse_schema_rest/api/table.clj b/src/metabase/warehouse_schema_rest/api/table.clj
index 689a077979a..1016bf8dc1e 100644
--- a/src/metabase/warehouse_schema_rest/api/table.clj
+++ b/src/metabase/warehouse_schema_rest/api/table.clj
@@ -191,7 +191,7 @@
body]
(when-let [changes (-> body
(u/select-keys-when
- :non-nil [:display_name :show_in_getting_started :entity_type :field_order]
+ :non-nil [:display_name :show_in_getting_started :entity_type :field_order :collection_id]
:present [:description :caveats :points_of_interest :visibility_type
:data_layer :data_authority :data_source :owner_email :owner_user_id])
(u/update-some :data_layer keyword)
@@ -262,7 +262,8 @@
[:data_source {:optional true} [:maybe :string]]
[:data_layer {:optional true} [:maybe :string]]
[:owner_email {:optional true} [:maybe :string]]
- [:owner_user_id {:optional true} [:maybe :int]]]]
+ [:owner_user_id {:optional true} [:maybe :int]]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]]]
(first (update-tables! [id] body)))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.clj
index 081af6520e1..c521f212da4 100644
--- a/test/metabase/collections/models/collection_test.clj
+++ b/test/metabase/collections/models/collection_test.clj
@@ -63,6 +63,29 @@
(is (-> trash :name i18n/localized-string?)
"Trash name must be a localized string")))
+(deftest ^:parallel library-collection-names-localized-test
+ (testing "maybe-localize-system-collection-name overrides names for system library collections"
+ (testing "Library root gets canonical name regardless of DB value"
+ (let [result (collection/maybe-localize-system-collection-name
+ {:name "Wrong Name" :type collection/library-collection-type
+ :entity_id @#'collection/library-entity-id})]
+ (is (= "Library" (str (:name result))))))
+ (testing "Data gets canonical name"
+ (let [result (collection/maybe-localize-system-collection-name
+ {:name "Wrong Name" :type collection/library-data-collection-type
+ :entity_id @#'collection/library-data-entity-id})]
+ (is (= "Data" (str (:name result))))))
+ (testing "Metrics gets canonical name"
+ (let [result (collection/maybe-localize-system-collection-name
+ {:name "Wrong Name" :type collection/library-metrics-collection-type
+ :entity_id @#'collection/library-metrics-entity-id})]
+ (is (= "Metrics" (str (:name result)))))))
+ (testing "User-created subcollections keep their custom names"
+ (let [result (collection/maybe-localize-system-collection-name
+ {:name "My Custom Folder" :type collection/library-data-collection-type
+ :entity_id "some-random-entity-id"})]
+ (is (= "My Custom Folder" (:name result))))))
+
(deftest personal-collection-with-ui-details-test
(testing "With personal_owner"
(is (= {:personal_owner_id (mt/user->id :lucky)
@@ -666,7 +689,7 @@
(testing "make sure that `effective-children` isn't returning children or location of children! Those should get discarded."
(with-current-user-perms-for-collections! [a b c d e f g]
- (is (= #{:name :id :description}
+ (is (= #{:name :id :description :type}
(set (keys (first (collection/effective-children a))))))))
(testing "If we don't have permissions for C, C's children (D and F) should be moved up one level"
@@ -3289,11 +3312,8 @@
non-archived-card]))))))))
(deftest create-library
- (mt/with-discard-model-updates! [:model/Collection]
+ (mt/with-empty-h2-app-db!
(testing "Can create a library if none exist"
- (t2/update! :model/Collection :type collection/library-collection-type {:type nil})
- (t2/update! :model/Collection :type collection/library-data-collection-type {:type nil})
- (t2/update! :model/Collection :type collection/library-metrics-collection-type {:type nil})
(let [library (collection/create-library-collection!)]
(is (= "Library" (:name library)))
(is (= ["Data" "Metrics"] (sort (map :name (collection/descendants library)))))
@@ -3340,7 +3360,7 @@
(deftest serdes-descendants-includes-published-tables-test
(testing "Collection descendants includes published tables"
(mt/with-temp [:model/Database db {:name "Test DB"}
- :model/Collection coll {:name "Test Collection"}
+ :model/Collection coll {:name "Test Collection", :type "library-data"}
:model/Table pub-table {:name "Published Table"
:db_id (:id db)
:is_published true
@@ -3363,7 +3383,7 @@
(deftest serdes-descendants-skip-archived-tables-test
(testing "Collection descendants with skip-archived handles published tables"
(mt/with-temp [:model/Database db {:name "Test DB"}
- :model/Collection coll {:name "Test Collection"}
+ :model/Collection coll {:name "Test Collection", :type "library-data"}
:model/Table active-table {:name "Active Published Table"
:db_id (:id db)
:is_published true
diff --git a/test/metabase/collections/test_utils.clj b/test/metabase/collections/test_utils.clj
index a82a9a20c07..3a013f4cdf0 100644
--- a/test/metabase/collections/test_utils.clj
+++ b/test/metabase/collections/test_utils.clj
@@ -19,6 +19,7 @@
```"
[& body]
`(do
+ (mt/initialize-if-needed! :db)
;; Clear existing library collections
(t2/update! (t2/table-name :model/Collection)
:type collection/library-collection-type
diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.clj
index 7346a01d2aa..156d8699c8a 100644
--- a/test/metabase/collections_rest/api_test.clj
+++ b/test/metabase/collections_rest/api_test.clj
@@ -8,7 +8,7 @@
[metabase.collections-rest.settings :as collections-rest.settings]
[metabase.collections.models.collection :as collection]
[metabase.collections.models.collection-test :as collection-test]
- [metabase.collections.test-utils :refer [without-library]]
+ [metabase.collections.test-utils :refer [with-library-not-synced without-library]]
[metabase.notification.api.notification-test :as api.notification-test]
[metabase.notification.test-util :as notification.tu]
[metabase.permissions.core :as perms]
@@ -596,6 +596,78 @@
(is (some #{collection/library-metrics-collection-type} all-types))
(is (some #{collection/library-data-collection-type} all-types))))))))
+(defn- flatten-tree
+ "Flatten a tree of collections into a flat sequence."
+ [collections]
+ (mapcat (fn [collection]
+ (cons collection
+ (when-let [children (:children collection)]
+ (flatten-tree children))))
+ collections))
+
+(deftest is-library-root-on-collection-tree-test
+ (testing "GET /api/collection/tree with include-library"
+ (without-library
+ (mt/with-model-cleanup [:model/Collection]
+ (collection/create-library-collection!)
+ (with-library-not-synced
+ (let [data-coll (t2/select-one :model/Collection :entity_id @#'collection/library-data-entity-id)
+ _subcoll (mt/user-http-request :crowberto :post 200 "collection"
+ {:name "My Data Subcollection" :parent_id (:id data-coll)})
+ response (mt/user-http-request :crowberto :get 200 "collection/tree" :include-library true)
+ all-colls (flatten-tree response)
+ by-type (group-by :type all-colls)]
+ (testing "System library collections have is_library_root true"
+ (doseq [coll (concat (get by-type collection/library-collection-type)
+ (get by-type collection/library-data-collection-type)
+ (get by-type collection/library-metrics-collection-type))]
+ (when (contains? @#'collection/library-entity-id? (:entity_id coll))
+ (is (true? (:is_library_root coll))
+ (str "System library collection " (:name coll) " should have is_library_root true")))))
+ (testing "User-created subcollections do NOT have is_library_root true"
+ (let [subcoll (first (filter #(= "My Data Subcollection" (:name %)) all-colls))]
+ (is (some? subcoll) "Subcollection should appear in the tree")
+ (is (not (:is_library_root subcoll))
+ "User-created subcollection should not have is_library_root")))))))))
+
+(deftest is-library-root-on-collection-items-test
+ (testing "GET /api/collection/:id/items"
+ (without-library
+ (mt/with-model-cleanup [:model/Collection]
+ (collection/create-library-collection!)
+ (with-library-not-synced
+ (let [library (t2/select-one :model/Collection :type collection/library-collection-type)
+ data-coll (t2/select-one :model/Collection :entity_id @#'collection/library-data-entity-id)
+ _subcoll (mt/user-http-request :crowberto :post 200 "collection"
+ {:name "My Metrics Subcollection" :parent_id
+ (:id (t2/select-one :model/Collection
+ :entity_id @#'collection/library-metrics-entity-id))})
+ lib-items (:data (mt/user-http-request :crowberto :get 200
+ (str "collection/" (:id library) "/items")))]
+ (testing "System library children (Data, Metrics) have is_library_root true"
+ (doseq [item (filter :is_library_root lib-items)]
+ (is (contains? #{collection/library-data-collection-type
+ collection/library-metrics-collection-type}
+ (:type item)))))
+ (testing "Data and Metrics collections both marked as is_library_root"
+ (let [roots (filter :is_library_root lib-items)]
+ (is (= #{collection/library-data-collection-type
+ collection/library-metrics-collection-type}
+ (set (map :type roots))))))
+ (testing "User-created subcollections inside Data do NOT have is_library_root"
+ (let [data-items (:data (mt/user-http-request :crowberto :get 200
+ (str "collection/" (:id data-coll) "/items")))
+ subcoll (first (filter #(= "My Metrics Subcollection" (:name %)) data-items))]
+ (is (nil? subcoll)
+ "Subcollection created under Metrics should not appear under Data"))
+ (let [metrics-coll (t2/select-one :model/Collection :entity_id @#'collection/library-metrics-entity-id)
+ metrics-items (:data (mt/user-http-request :crowberto :get 200
+ (str "collection/" (:id metrics-coll) "/items")))
+ subcoll (first (filter #(= "My Metrics Subcollection" (:name %)) metrics-items))]
+ (is (some? subcoll) "Subcollection should appear under Metrics")
+ (is (not (:is_library_root subcoll))
+ "User-created subcollection should not have is_library_root")))))))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /collection/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
@@ -2732,6 +2804,32 @@
(is (= "snippets" (:namespace root-collection-with-ns))
"Root collection should use explicitly provided namespace"))))))
+(deftest create-child-collection-of-library-collection-test
+ (testing "POST /api/collection"
+ (testing "Child collection of library collection should inherit the :type"
+ (mt/with-model-cleanup [:model/Collection]
+ (collection/create-library-collection!)
+ (with-library-not-synced
+ (doseq [[entity-id collection-type] [[@#'collection/library-data-entity-id "library-data"]
+ [@#'collection/library-metrics-entity-id "library-metrics"]]]
+ (let [;; Create a parent collection with snippets namespace
+ lib-root (t2/select-one :model/Collection :entity_id entity-id)
+ child-collection (mt/user-http-request :crowberto :post 200 "collection"
+ ;; Deliberately not setting `:type` here - it's automatic.
+ {:name "Child Collection"
+ :parent_id (u/the-id lib-root)})
+ child-id (:id child-collection)]
+ (is (= collection-type (:type child-collection))
+ "Children of the Library's magic collections inherit their :type")
+ (is (=? {:id number?
+ :name "Grandchild Collection"
+ :type collection-type}
+ (mt/user-http-request :crowberto :post 200 "collection"
+ ;; Likewise, deliberately no `:type`.
+ {:name "Grandchild Collection"
+ :parent_id child-id}))
+ "Grandchild collection should also inherit the :type of their non-magic parent"))))))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | PUT /api/collection/:id |
;;; +----------------------------------------------------------------------------------------------------------------+