The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Entity Picker v26 (#66978)
Ryan Laurie23be6baa0e2d
diff --git a/e2e/support/helpers/e2e-collection-helpers.ts b/e2e/support/helpers/e2e-collection-helpers.tsindex 3b0afbf85cf..bbde98a5e44 100644--- a/e2e/support/helpers/e2e-collection-helpers.ts+++ b/e2e/support/helpers/e2e-collection-helpers.ts@@ -1,7 +1,6 @@import {entityPickerModal,entityPickerModalLevel,- entityPickerModalTab,getFullName,navigationSidebar,popover,@@ -79,11 +78,12 @@ export const openUnpinnedItemMenu = (name: string) => {};export const moveOpenedCollectionTo = (newParent: string) => {+ cy.intercept("GET", "/api/collection/*/items**").as("getCollectionItems");openCollectionMenu();popover().within(() => cy.findByText("Move").click());+ cy.wait(["@getCollectionItems", "@getCollectionItems"]);entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Collections/ }).click();cy.findByTestId("nested-item-picker").findByText(newParent).click();cy.button("Move").click();});@@ -94,16 +94,10 @@ export const moveOpenedCollectionTo = (newParent: string) => {export function pickEntity({path,select,- tab,}: {- path?: string[];+ path?: (string | RegExp)[];select?: boolean;- tab?: string;}) {- if (tab) {- entityPickerModalTab(tab).click();- }-if (path) {cy.findByTestId("nested-item-picker").within(() => {for (const [index, name] of path.entries()) {diff --git a/e2e/support/helpers/e2e-embedding-sdk-interactive-question-helpers.tsx b/e2e/support/helpers/e2e-embedding-sdk-interactive-question-helpers.tsxindex b83083db7d8..1e960747515 100644--- a/e2e/support/helpers/e2e-embedding-sdk-interactive-question-helpers.tsx+++ b/e2e/support/helpers/e2e-embedding-sdk-interactive-question-helpers.tsx@@ -1,8 +1,6 @@-import {- entityPickerModal,- modal,- popover,-} from "e2e/support/helpers/e2e-ui-elements-helpers";+import { modal, popover } from "e2e/support/helpers/e2e-ui-elements-helpers";++import { pickEntity } from "./e2e-collection-helpers";export function saveInteractiveQuestionAsNewQuestion(options: {questionName: string;@@ -29,15 +27,7 @@ export function saveInteractiveQuestionAsNewQuestion(options: {if (collectionPickerPath) {cy.findByTestId("dashboard-and-collection-picker-button").click();- entityPickerModal().within(() => {- cy.findByText("Browse").click();-- collectionPickerPath.forEach((collectionName) =>- cy.findByText(collectionName).click(),- );-- cy.findByRole("button", { name: "Select this collection" }).click();- });+ pickEntity({ path: collectionPickerPath, select: true });}modal().within(() => {diff --git a/e2e/support/helpers/e2e-filter-helpers.js b/e2e/support/helpers/e2e-filter-helpers.jsindex d70e9c52898..b719ff605f4 100644--- a/e2e/support/helpers/e2e-filter-helpers.js+++ b/e2e/support/helpers/e2e-filter-helpers.js@@ -1,8 +1,6 @@-import {- entityPickerModal,- modal,- popover,-} from "e2e/support/helpers/e2e-ui-elements-helpers";+import { modal, popover } from "e2e/support/helpers/e2e-ui-elements-helpers";++import { pickEntity } from "./e2e-collection-helpers";export function setDropdownFilterType() {cy.findByText("Dropdown list").click();@@ -20,9 +18,7 @@ export function setFilterQuestionSource({ question, field }) {cy.findByText("Pick a model or question…").click();});- entityPickerModal().within(() => {- cy.findByText(question).click();- });+ pickEntity({ path: [/Our analytics/, question], select: true });modal().within(() => {cy.findByText("Pick a column…").click();diff --git a/e2e/support/helpers/e2e-misc-helpers.js b/e2e/support/helpers/e2e-misc-helpers.jsindex cc3b3fa3674..bb6023c69d0 100644--- a/e2e/support/helpers/e2e-misc-helpers.js+++ b/e2e/support/helpers/e2e-misc-helpers.js@@ -359,7 +359,7 @@ export function checkSavedToCollectionQuestionToast(addToDashboard) {export function saveQuestionToCollection(name,- pickEntityOptions = { tab: "Browse", path: ["Our analytics"] },+ pickEntityOptions = { path: ["Our analytics"] },reqInfo,) {saveQuestion(name, reqInfo, pickEntityOptions);diff --git a/e2e/support/helpers/e2e-notebook-helpers.ts b/e2e/support/helpers/e2e-notebook-helpers.tsindex 7434eb1a02f..8ca2afcb94e 100644--- a/e2e/support/helpers/e2e-notebook-helpers.ts+++ b/e2e/support/helpers/e2e-notebook-helpers.ts@@ -2,7 +2,6 @@ import type { CyHttpMessages } from "cypress/types/net-stubbing";import {entityPickerModal,- entityPickerModalTab,miniPicker,miniPickerBrowseAll,popover,@@ -206,7 +205,10 @@ export function selectSavedQuestionsToJoin() {cy.intercept("GET", "/api/table/*/query_metadata").as("joinedTableMetadata");miniPickerBrowseAll().click();- entityPickerModal().findByText(firstQuestionName).click();+ entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();+ cy.findByText(firstQuestionName).click();+ });cy.wait("@joinedTableMetadata");@@ -214,8 +216,10 @@ export function selectSavedQuestionsToJoin(cy.icon("join_left_outer").click();miniPickerBrowseAll().click();- entityPickerModalTab("Data").click();- entityPickerModal().findByText(secondQuestionName).click();+ entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();+ cy.findByText(secondQuestionName).click();+ });}export function selectFilterOperator(operatorName: string) {diff --git a/e2e/support/helpers/e2e-remote-sync-helpers.ts b/e2e/support/helpers/e2e-remote-sync-helpers.tsindex 91c209a0cdc..056588f380e 100644--- a/e2e/support/helpers/e2e-remote-sync-helpers.ts+++ b/e2e/support/helpers/e2e-remote-sync-helpers.ts@@ -182,7 +182,6 @@ export const moveCollectionItemToSyncedCollection = (popover().findByText("Move").click();entityPickerModal().within(() => {- cy.findAllByRole("tab", { name: /Browse|Collections/ }).click();entityPickerModalItem(1, targetCollection).click();cy.button("Move").click();});diff --git a/e2e/support/helpers/e2e-ui-elements-helpers.js b/e2e/support/helpers/e2e-ui-elements-helpers.jsindex f7710053dc8..8ae3ad2e756 100644--- a/e2e/support/helpers/e2e-ui-elements-helpers.js+++ b/e2e/support/helpers/e2e-ui-elements-helpers.js@@ -74,30 +74,14 @@ export function entityPickerModalLevel(level) {* @param {string | RegExp} name*/export function entityPickerModalItem(level, name) {- return entityPickerModalLevel(level).findByText(name).parents("a");-}--export function entityPickerModalTab(name) {- return cy.findAllByRole("tab").filter(`:contains(${name})`);-}--// displays at least these tabs:-export function shouldDisplayTabs(tabs) {- tabs.forEach((tab) => {- entityPickerModalTab(tab).should("exist");- });-}--export function tabsShouldBe(selected, tabs) {- cy.log(tabs);- cy.findAllByRole("tab").should("have.length", tabs.length);- tabs.forEach((tab) => {- if (tab === selected) {- entityPickerModalTab(tab).and("have.attr", "aria-selected", "true");- } else {- entityPickerModalTab(tab).should("exist");- }- });+ return (+ entityPickerModalLevel(level)+ // in the recents and search results, the items look like: [collection name] [parent collection name]+ // which makes matching difficult as you may inadvertently match the parent collection name+ // so we ignore the parent collection name by ignoring data-testid="picker-item-location"+ .findByText(name, { ignore: '[data-testid="picker-item-location"]' })+ .parents("a")+ );}export function collectionOnTheGoModal() {diff --git a/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsxindex 3c2e0722aea..afefb4bee1a 100644--- a/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsx@@ -11,7 +11,6 @@ import {assertSdkNotebookEditorUsable,createQuestion,entityPickerModal,- entityPickerModalTab,modal,popover,} from "e2e/support/helpers";@@ -55,7 +54,6 @@ describe("scenarios > embedding-sdk > interactive-question > creating a question});entityPickerModal().within(() => {- entityPickerModalTab("Browse").click();cy.findByText("First collection").click();cy.button("Select this collection").click();});@@ -156,7 +154,6 @@ describe("scenarios > embedding-sdk > interactive-question > creating a question});entityPickerModal().within(() => {- entityPickerModalTab("Browse").click();cy.findByText("Orders in a dashboard").click();cy.button("Select this dashboard").click();});diff --git a/e2e/test/scenarios/actions/actions-reproductions.cy.spec.js b/e2e/test/scenarios/actions/actions-reproductions.cy.spec.jsindex 492890d05e9..1d4d9101263 100644--- a/e2e/test/scenarios/actions/actions-reproductions.cy.spec.js+++ b/e2e/test/scenarios/actions/actions-reproductions.cy.spec.js@@ -402,10 +402,9 @@ describe("issue 51020", () => {H.newButton("Question").click();H.miniPickerBrowseAll().click();- H.entityPickerModalTab("Data").click();+ H.entityPickerModalItem(0, "Our analytics").click();H.entityPickerModalItem(1, "Model 51020").click();H.saveQuestion("Question 51020", undefined, {- tab: "Browse",path: ["Our analytics"],});diff --git a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.jsindex ae01f9d05be..de88296fd65 100644--- a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js+++ b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js@@ -187,9 +187,7 @@ describe("(metabase#46714)", () => {cy.findByTestId("segment-editor").findByText("Select a table").click();- H.entityPickerModal().within(() => {- cy.findByText("Orders").click();- });+ H.pickEntity({ path: ["Databases", /Sample Database/, "Orders"] });cy.findByTestId("entity-picker-modal").should("not.exist");cy.findByTestId("segment-editor").findByText("Orders").should("be.visible");diff --git a/e2e/test/scenarios/admin/datamodel/segments.cy.spec.ts b/e2e/test/scenarios/admin/datamodel/segments.cy.spec.tsindex e534701eef9..393db8e51c5 100644--- a/e2e/test/scenarios/admin/datamodel/segments.cy.spec.ts+++ b/e2e/test/scenarios/admin/datamodel/segments.cy.spec.ts@@ -22,9 +22,7 @@ describe("scenarios > admin > datamodel > segments", () => {cy.button("New segment").click();cy.findByTestId("segment-editor").findByText("Select a table").click();- H.entityPickerModal().within(() => {- cy.findByText("Orders").click();- });+ H.pickEntity({ path: ["Databases", /Sample Database/, "Orders"] });cy.findByTestId("segment-editor").findByText("Orders").should("exist");diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.tsindex 71087df00eb..a5c92adde11 100644--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts@@ -108,7 +108,7 @@ describe("Remote Sync", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();+ H.entityPickerModalItem(0, "Our analytics").click();H.entityPickerModalItem(1, "Test Synced Collection").click();cy.button("Move").click();});@@ -125,7 +125,7 @@ describe("Remote Sync", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();+ H.entityPickerModalItem(0, "Our analytics").click();H.entityPickerModalItem(1, "Test Synced Collection").click();cy.button("Move").click();});diff --git a/e2e/test/scenarios/collections/collection-picker-tenants.cy.spec.ts b/e2e/test/scenarios/collections/collection-picker-tenants.cy.spec.tsindex 4f5f6c8b0ca..9485ee5d74a 100644--- a/e2e/test/scenarios/collections/collection-picker-tenants.cy.spec.ts+++ b/e2e/test/scenarios/collections/collection-picker-tenants.cy.spec.ts@@ -70,7 +70,6 @@ describe("scenarios > collections > collection picker with tenants", () => {H.entityPickerModal().within(() => {cy.log("Select 'Our analytics' (a normal collection)");- H.entityPickerModalTab("Collections").click();cy.findByText("Our analytics").click();cy.button("Select").click();});@@ -154,7 +153,6 @@ describe("scenarios > collections > collection picker with tenants", () => {});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.log("Navigate to Shared collections");cy.findByText("Shared collections").click();cy.findByText("Target Shared Collection").click();@@ -191,7 +189,6 @@ describe("scenarios > collections > collection picker with tenants", () => {});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.log("Select 'Our analytics' (normal collection)");cy.findByText("Our analytics").click();cy.button("Select").click();diff --git a/e2e/test/scenarios/collections/collections-reproductions.cy.spec.js b/e2e/test/scenarios/collections/collections-reproductions.cy.spec.jsdeleted file mode 100644index cefe5436542..00000000000--- a/e2e/test/scenarios/collections/collections-reproductions.cy.spec.js+++ /dev/null@@ -1,168 +0,0 @@-const { H } = cy;-import {- ADMIN_PERSONAL_COLLECTION_ID,- FIRST_COLLECTION_ID,- ORDERS_COUNT_QUESTION_ID,- ORDERS_QUESTION_ID,-} from "e2e/support/cypress_sample_instance_data";--describe("issue 20911", () => {- const COLLECTION_ACCESS_PERMISSION_INDEX = 0;- const FIRST_COLLECTION = "First collection";-- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- cy.intercept("GET", "/api/collection/graph").as("getGraph");- });-- it("should allow to change sub-collections permissions after access change (metabase#20911)", () => {- cy.visit("/collection/root/permissions");- cy.wait("@getGraph");- H.assertPermissionTable([- ["Administrators", "Curate"],- ["All Users", "No access"],- ["collection", "Curate"],- ["data", "No access"],- ["nosql", "No access"],- ["readonly", "View"],- ]);- H.modifyPermission(- "collection",- COLLECTION_ACCESS_PERMISSION_INDEX,- "No access",- false,- );- H.modifyPermission(- "collection",- COLLECTION_ACCESS_PERMISSION_INDEX,- "No access",- true,- );- H.modal().within(() => {- cy.button("Save").click();- });-- H.navigationSidebar().within(() => {- cy.findByText(FIRST_COLLECTION).click();- });- H.getCollectionActions().within(() => {- cy.icon("ellipsis").click();- });- H.popover().within(() => {- cy.icon("lock").click();- });- H.assertPermissionTable([- ["Administrators", "Curate"],- ["All Users", "No access"],- ["collection", "No access"],- ["data", "No access"],- ["nosql", "No access"],- ["readonly", "View"],- ]);-- cy.signInAsNormalUser();- cy.visit("/collection/root");- cy.get("main").findByText("You don't have permissions to do that.");-- cy.visit(`/collection/${FIRST_COLLECTION_ID}`);- cy.get("main").findByText("Sorry, you don’t have permission to see that.");- });-});--describe("issue 24660", () => {- const collectionName = "Parent";-- const questions = {- [ORDERS_QUESTION_ID]: "Orders",- [ORDERS_COUNT_QUESTION_ID]: "Orders, Count",- };-- function createParentCollectionAndMoveQuestionToIt(questionId) {- return H.createCollection({- name: collectionName,- parent_id: null,- }).then(({ body: { id } }) => {- cy.request("PUT", `/api/card/${questionId}`, {- collection_id: id,- });- });- }-- beforeEach(() => {- H.restore();- cy.signInAsAdmin();-- createParentCollectionAndMoveQuestionToIt(ORDERS_QUESTION_ID);- createParentCollectionAndMoveQuestionToIt(ORDERS_COUNT_QUESTION_ID);- });-- it("should properly show contents of different collections with the same name (metabase#24660)", () => {- H.startNewQuestion();- H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- cy.findAllByText(collectionName).first().click();-- cy.findByText(questions[ORDERS_QUESTION_ID]).should("exist");- cy.findByText(questions[ORDERS_COUNT_QUESTION_ID]).should("not.exist");- cy.realType("{esc}");- });-- cy.findByPlaceholderText("Search for tables and more...").click();- H.miniPicker().within(() => {- cy.findByText("Our analytics").click();- cy.findAllByText(collectionName).first().click();- cy.findByText(questions[ORDERS_QUESTION_ID]).should("exist");- cy.findByText(questions[ORDERS_COUNT_QUESTION_ID]).should("not.exist");- });- });-});--describe("issue 30235", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("pro-self-hosted");- });-- it("should allow to turn to official collection after moving it from personal to root parent collection (metabase#30235)", () => {- const COLLECTION_NAME = "C30235";-- H.createCollection({- name: COLLECTION_NAME,- parent_id: ADMIN_PERSONAL_COLLECTION_ID,- }).then(({ body: { id } }) => {- cy.visit(`/collection/${id}`);-- H.moveOpenedCollectionTo("Our analytics");-- H.openCollectionMenu();-- H.popover().within(() => {- cy.findByText("Make collection official").should("be.visible");- cy.findByText("Edit permissions").should("be.visible");- });- });- });-});--describe("issue 58231", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- });-- it("should allow to edit permissions for Usage Analytics collection (metabase#58231)", () => {- cy.visit("/collection/2-usage-analytics");-- cy.findByTestId("collection-menu")- .findByLabelText("Edit permissions")- .should("be.visible")- .click();-- H.modal()- .findByText("Permissions for Usage analytics")- .should("be.visible");- });-});diff --git a/e2e/test/scenarios/collections/collections-reproductions.cy.spec.ts b/e2e/test/scenarios/collections/collections-reproductions.cy.spec.tsindex 72a448f5d5e..2f8eb740a7e 100644--- a/e2e/test/scenarios/collections/collections-reproductions.cy.spec.ts+++ b/e2e/test/scenarios/collections/collections-reproductions.cy.spec.ts@@ -104,6 +104,7 @@ describe("issue 24660", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();cy.findAllByText(collectionName).first().click();cy.findByText(questions[ORDERS_QUESTION_ID]).should("exist");diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.jsindex ca52790462d..6dc714ea2a8 100644--- a/e2e/test/scenarios/collections/collections.cy.spec.js+++ b/e2e/test/scenarios/collections/collections.cy.spec.js@@ -147,7 +147,6 @@ describe("scenarios > collection defaults", () => {H.pickEntity({path: ["Our analytics", `Collection ${COLLECTIONS_COUNT}`],select: true,- tab: "Collections",});cy.findByTestId("new-collection-modal").button("Create").click();@@ -392,16 +391,16 @@ describe("scenarios > collection defaults", () => {H.openCollectionMenu();H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- cy.findByRole("button", { name: /First collection / }).should("exist");- cy.findByRole("button", { name: /Second collection/ }).should(- "not.exist",- );+ // wait for collections to load before clicking on recents to prevent flakiness+ cy.findByText("Third collection").should("exist");+ cy.findByText("Recent items").click();+ // the space is important, since search results are of the form "[collection name] [parent collection name]"+ cy.findByRole("link", { name: /First collection / }).should("exist");+ cy.findByRole("link", { name: /Second collection / }).should("not.exist");cy.findByPlaceholderText("Search…").type("coll");- cy.findByRole("button", { name: /Robert Tableton/ }).should("exist");- cy.findByRole("button", { name: /Second collection/ }).should(- "not.exist",- );+ cy.findByRole("link", { name: /Robert Tableton's / }).should("exist");+ cy.findByRole("link", { name: /Second collection / }).should("not.exist");});});@@ -411,7 +410,7 @@ describe("scenarios > collection defaults", () => {cy.signInAsAdmin();});- it("should handle moving a question when you don't have access to entier collection path (metabase#44316", () => {+ it("should handle moving a question when you don't have access to entire collection path (metabase#44316", () => {H.createCollection({name: "Collection A",}).then(({ body: collectionA }) => {@@ -605,7 +604,6 @@ describe("scenarios > collection defaults", () => {});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText("Bobby Tables's Personal Collection").click();cy.findByText(COLLECTION).click();cy.button("Move").should("not.be.disabled");@@ -634,7 +632,6 @@ describe("scenarios > collection defaults", () => {H.entityPickerModal().within(() => {cy.findByTestId("loading-indicator").should("not.exist");- H.entityPickerModalTab("Collections").click();cy.wait(["@getCollectionItems","@getCollectionItems",@@ -689,7 +686,6 @@ describe("scenarios > collection defaults", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();H.entityPickerModalItem(0, "Our analytics").click();cy.button("Move").click();cy.log("Entity picker should show an error message");@@ -806,7 +802,6 @@ describe("scenarios > collection defaults", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.log("parent collection should be selected");findPickerItem("First collection").should("have.attr",@@ -832,7 +827,6 @@ describe("scenarios > collection defaults", () => {H.entityPickerModal().within(() => {cy.log("parent collection should be selected");- H.entityPickerModalTab("Collections").click();findPickerItem("Second collection").should("have.attr","data-active",@@ -894,10 +888,12 @@ describe("scenarios > collection defaults", () => {);H.createCollection({ name: "Outer collection 2" });- // modify the inner collection so that it shows up in recents+ // mark the inner collection as recently selectedcy.get("@innerCollectionId").then((innerCollectionId) => {- cy.request("PUT", `/api/collection/${innerCollectionId}`, {- name: "Inner collection 1 - modified",+ cy.request("POST", "/api/activity/recents", {+ context: "selection",+ model: "collection",+ model_id: innerCollectionId,});});cy.visit("/collection/root");@@ -911,14 +907,7 @@ describe("scenarios > collection defaults", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Recents").should(- "have.attr",- "data-active",- "true",- );-cy.findByText(/inner collection/).should("not.exist");-cy.button("Cancel").click();});@@ -932,12 +921,6 @@ describe("scenarios > collection defaults", () => {cy.findByTestId("toast-card").button("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Recents").should(- "have.attr",- "data-active",- "true",- );-cy.findByText(/inner collection/).should("not.exist");});});diff --git a/e2e/test/scenarios/collections/permissions.cy.spec.js b/e2e/test/scenarios/collections/permissions.cy.spec.jsindex 67fb5feeb5c..572af7e5e68 100644--- a/e2e/test/scenarios/collections/permissions.cy.spec.js+++ b/e2e/test/scenarios/collections/permissions.cy.spec.js@@ -353,9 +353,7 @@ describe("collection permissions", () => {// Test will fail on this step firstcy.findByText("First collection").should("not.exist");// This is the second step that makes sure not even search returns collections with read-only access- cy.findByPlaceholderText(- "Search this collection or everywhere…",- ).type("third{Enter}");+ cy.findByPlaceholderText("Search…").type("third{Enter}");cy.wait("@search");cy.findByText(/Loading/i).should("not.exist");diff --git a/e2e/test/scenarios/custom-column/cc-boolean-functions.cy.spec.ts b/e2e/test/scenarios/custom-column/cc-boolean-functions.cy.spec.tsindex 58369148cf4..167304cd1a8 100644--- a/e2e/test/scenarios/custom-column/cc-boolean-functions.cy.spec.ts+++ b/e2e/test/scenarios/custom-column/cc-boolean-functions.cy.spec.ts@@ -627,7 +627,6 @@ describe("scenarios > custom column > boolean functions", () => {cy.findByText("Saved question").click();});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Questions").click();cy.findByText("Q1").click();});H.sidebar()@@ -660,7 +659,6 @@ describe("scenarios > custom column > boolean functions", () => {cy.findByText("Dashboard").click();});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();cy.findByText("D1").click();});H.sidebar()@@ -698,7 +696,6 @@ describe("scenarios > custom column > boolean functions", () => {cy.findByText("Dashboard").click();});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();cy.findByText("D2").click();});H.sidebar()diff --git a/e2e/test/scenarios/custom-column/custom-column-reproductions.cy.spec.js b/e2e/test/scenarios/custom-column/custom-column-reproductions.cy.spec.jsindex c26deb91a8c..f02f259731f 100644--- a/e2e/test/scenarios/custom-column/custom-column-reproductions.cy.spec.js+++ b/e2e/test/scenarios/custom-column/custom-column-reproductions.cy.spec.js@@ -1302,7 +1302,7 @@ describe("issue 49305", () => {H.saveQuestion("49305 Base question",{ wrapId: true },- { tab: "Browse", path: ["Our analytics"], select: true },+ { path: ["Our analytics"], select: true },);cy.get("@questionId").then((id) => {diff --git a/e2e/test/scenarios/custom-column/custom-column.cy.spec.js b/e2e/test/scenarios/custom-column/custom-column.cy.spec.jsindex 5afb8096b3f..cee5eb48712 100644--- a/e2e/test/scenarios/custom-column/custom-column.cy.spec.js+++ b/e2e/test/scenarios/custom-column/custom-column.cy.spec.js@@ -67,6 +67,7 @@ describe("scenarios > question > custom column", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {+ H.entityPickerModalLevel(0).findByText("Our analytics").click();H.entityPickerModalLevel(1).findByText(name).click();});cy.button("Custom column").click();@@ -271,6 +272,7 @@ describe("scenarios > question > custom column", () => {H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {H.entityPickerModalLevel(0).findByText("Databases").click();+ H.entityPickerModalLevel(1).findByText("Sample Database").click();cy.findByText("Products").click();});diff --git a/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js b/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.jsindex a08a05387cf..028f9e3f1ef 100644--- a/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js+++ b/e2e/test/scenarios/dashboard-cards/click-behavior.cy.spec.js@@ -2734,7 +2734,6 @@ describe("scenarios > dashboard > dashboard cards > click behavior", () => {cy.findByText("Saved question").click();});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Questions").click();cy.findByText("Orders").click();});cy.findByTestId("click-mappings").findByText("Product ID").click();@@ -2776,10 +2775,7 @@ const clickLineChartPoint = () => {const addDashboardDestination = () => {cy.get("aside").findByText("Go to a custom destination").click();cy.get("aside").findByText("Dashboard").click();- H.entityPickerModal()- .findByRole("tab", { name: /Dashboards/ })- .click();- H.entityPickerModal().findByText(TARGET_DASHBOARD.name).click();+ H.pickEntity({ path: ["Our analytics", TARGET_DASHBOARD.name] });};const addUrlDestination = () => {@@ -2790,9 +2786,6 @@ const addUrlDestination = () => {const addSavedQuestionDestination = () => {cy.get("aside").findByText("Go to a custom destination").click();cy.get("aside").findByText("Saved question").click();- H.entityPickerModal()- .findByRole("tab", { name: /Questions/ })- .click();H.entityPickerModal().findByText(TARGET_QUESTION.name).click();};diff --git a/e2e/test/scenarios/dashboard-cards/dashboard-drill.cy.spec.js b/e2e/test/scenarios/dashboard-cards/dashboard-drill.cy.spec.jsindex 471b28aed5f..d2a4939a9a8 100644--- a/e2e/test/scenarios/dashboard-cards/dashboard-drill.cy.spec.js+++ b/e2e/test/scenarios/dashboard-cards/dashboard-drill.cy.spec.js@@ -240,7 +240,6 @@ describe("scenarios > dashboard > dashboard drill", () => {// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage.within(() => cy.findByText("Dashboard").click());H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Dashboards/ }).click();cy.findByText("end dash").click();});// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usagediff --git a/e2e/test/scenarios/dashboard-cards/dashboard-sections.cy.spec.js b/e2e/test/scenarios/dashboard-cards/dashboard-sections.cy.spec.jsindex 22593c93e24..7ae6646bb45 100644--- a/e2e/test/scenarios/dashboard-cards/dashboard-sections.cy.spec.js+++ b/e2e/test/scenarios/dashboard-cards/dashboard-sections.cy.spec.js@@ -109,9 +109,10 @@ describe("scenarios > dashboard cards > sections > read only collections", () =>beforeEach(() => {H.restore();cy.signIn("readonly");+ cy.intercept("GET", "/api/collection/*/items*").as("getCollectionItems");});- it("Should allow you to select entites in collections you have read access to (metabase#50602)", () => {+ it("Should allow you to select entities in collections you have read access to (metabase#50602)", () => {H.createDashboard({ collection_id: READ_ONLY_PERSONAL_COLLECTION_ID }).then(({ body }) => {H.visitDashboard(body.id);@@ -124,11 +125,8 @@ describe("scenarios > dashboard cards > sections > read only collections", () =>.findAllByText("Select question").first().click({ force: true });- H.entityPickerModal()- .findByRole("tab", { name: /Questions/ })- .click();- H.entityPickerModalItem(0, "Our analytics").click();- H.entityPickerModalItem(1, "Orders, Count").click();+ cy.wait(["@getCollectionItems", "@getCollectionItems"]);+ H.pickEntity({ path: ["Our analytics", "Orders, Count"] });H.dashboardGrid().findByText("Orders, Count").should("exist");});});@@ -143,10 +141,7 @@ function selectQuestion(question) {.findAllByText("Select question").first().click({ force: true });- H.entityPickerModal()- .findByRole("tab", { name: /Questions/ })- .click();- H.entityPickerModal().findByText(question).click();+ H.pickEntity({ path: ["Our analytics", question] });cy.wait("@cardQuery");H.dashboardGrid().findByText(question).should("exist");}diff --git a/e2e/test/scenarios/dashboard-cards/dashcard-replace-question.cy.spec.js b/e2e/test/scenarios/dashboard-cards/dashcard-replace-question.cy.spec.jsindex b9cfe6cd57d..3adaebb0d1c 100644--- a/e2e/test/scenarios/dashboard-cards/dashcard-replace-question.cy.spec.js+++ b/e2e/test/scenarios/dashboard-cards/dashcard-replace-question.cy.spec.js@@ -151,7 +151,6 @@ describe("scenarios > dashboard cards > replace question", () => {// Ensure can replace with a modelreplaceQuestion(findTargetDashcard(), {nextQuestionName: "Orders Model",- tab: "Models",});findTargetDashcard().within(() => {assertDashCardTitle("Orders Model");@@ -259,13 +258,10 @@ function findTargetDashcard() {function replaceQuestion(dashcardElement,- { nextQuestionName, collectionName, tab },+ { nextQuestionName, collectionName },) {dashcardElement.realHover().findByLabelText("Replace").click();H.entityPickerModal().within(() => {- if (tab) {- cy.findByRole("tablist").findByText(tab).click();- }if (collectionName) {cy.findByText(collectionName).click();}diff --git a/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.js b/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.jsindex faca607116c..26791f66b79 100644--- a/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.js+++ b/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.js@@ -821,11 +821,7 @@ function addQuestionFromQueryBuilder({H.openQuestionActions();H.popover().findByText("Add to dashboard").click();- H.entityPickerModal().within(() => {- H.modal().findByText("Dashboards").click();- H.modal().findByText("36275").click();- cy.button("Select").click();- });+ H.pickEntity({ path: ["Our analytics", "36275"], select: true });H.undoToast().findByRole("button", { name: "Auto-connect" }).click();H.undoToast().should("contain", "Undo");diff --git a/e2e/test/scenarios/dashboard-filters/dashboard-filters-boolean.cy.spec.ts b/e2e/test/scenarios/dashboard-filters/dashboard-filters-boolean.cy.spec.tsindex 8c51ff4c471..ea13fc470da 100644--- a/e2e/test/scenarios/dashboard-filters/dashboard-filters-boolean.cy.spec.ts+++ b/e2e/test/scenarios/dashboard-filters/dashboard-filters-boolean.cy.spec.ts@@ -463,7 +463,6 @@ function setupDashboardClickBehavior({ targetName }: { targetName: string }) {cy.findByText("Dashboard").click();});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();cy.findByText(DASHBOARD_NAME).click();});H.sidebar().findByText(PARAMETER_NAME).click();diff --git a/e2e/test/scenarios/dashboard/dashboard-management.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-management.cy.spec.jsindex a6a5d492d73..eb369a16c4d 100644--- a/e2e/test/scenarios/dashboard/dashboard-management.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashboard-management.cy.spec.js@@ -205,13 +205,6 @@ describe("managing dashboard from the dashboard's edit menu", () => {cy.findByTestId("collection-picker-button").click();});- if (user === "admin") {- // admin has recents tab- H.entityPickerModal()- .findByRole("tab", { name: /Collections/ })- .click();- }-H.entityPickerModal().findByText("New collection").click();const NEW_COLLECTION = "Foo Collection";H.collectionOnTheGoModal().within(() => {@@ -248,6 +241,7 @@ describe("managing dashboard from the dashboard's edit menu", () => {cy.location("pathname").should("eq", `/dashboard/${id}/move`);H.entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();cy.findByText("First collection").click();cy.button("Move").click();});@@ -269,32 +263,6 @@ describe("managing dashboard from the dashboard's edit menu", () => {H.appBar().contains("Our analytics");H.appBar().should("not.contain", "First collection");-- // Assert that dashboard parent does not show up in recents- if (user === "admin") {- H.openDashboardMenu();- // Move the dashboard back to first collection- H.popover().findByText("Move").click();-- H.entityPickerModal().within(() => {- cy.findByText("First collection").click();- cy.button("Move").click();- });-- H.openDashboardMenu();- H.popover().findByText("Move").click();- H.entityPickerModal().within(() => {- cy.findByRole("button", {- name: /Third collection /,- }).should("exist");- // The space at the end of the regex is important since the "second collection"- // recent item also contains the text "in First collection", but at the end of the- // name- cy.findByRole("button", {- name: /First collection /,- }).should("not.exist");- });- }});});diff --git a/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.jsindex 3f94e1233ce..992514c3379 100644--- a/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.js@@ -59,7 +59,6 @@ describe("Dashboard > Dashboard Questions", () => {H.appBar().findByText("Orders in a dashboard");H.openQuestionActions();H.popover().findByText("Move").click();- H.entityPickerModalTab("Browse").click();H.entityPickerModal().findByText("First collection").click();H.entityPickerModal().button("Move").click();@@ -101,7 +100,6 @@ describe("Dashboard > Dashboard Questions", () => {H.openQuestionActions();H.popover().findByText("Move").click();- H.entityPickerModalTab("Browse").click();H.entityPickerModal().findByText("Orders in a dashboard").click();H.entityPickerModal().button("Move").click();H.undoToast().findByText("Orders in a dashboard");@@ -126,7 +124,6 @@ describe("Dashboard > Dashboard Questions", () => {H.openQuestionActions();H.popover().findByText("Move").click();- H.entityPickerModalTab("Browse").click();H.entityPickerModal().findByText("First collection").click();H.entityPickerModal().findByText("Second collection").click();H.entityPickerModal().button("Move").click();@@ -145,7 +142,6 @@ describe("Dashboard > Dashboard Questions", () => {H.openQuestionActions();H.popover().findByText("Move").click();- H.entityPickerModalTab("Browse").click();H.entityPickerModal().findByText("First collection").click();H.entityPickerModal().findByText("Second collection").click();H.entityPickerModal().button("Move").click();@@ -194,7 +190,6 @@ describe("Dashboard > Dashboard Questions", () => {H.openQuestionActions();H.popover().findByText("Move").click();- H.entityPickerModalTab("Browse").click();H.entityPickerModal().findByText("Our analytics").click();H.entityPickerModal().findByText("Orders in a dashboard").click();@@ -300,7 +295,7 @@ describe("Dashboard > Dashboard Questions", () => {cy.findByTestId("toast-card").button("Move").click();H.entityPickerModal().within(() => {- cy.findByRole("button", { name: /Orders in a dashboard/ }).click();+ cy.findByText("Orders in a dashboard").click();cy.button("Move").click();});@@ -411,28 +406,6 @@ describe("Dashboard > Dashboard Questions", () => {H.dashboardCards().findByText("Half Orders");});- it("can create a question using a dashboard question as a data source", () => {- H.createQuestion({- name: "Total Orders Dashboard Question",- dashboard_id: S.ORDERS_DASHBOARD_ID,- query: {- "source-table": SAMPLE_DATABASE.ORDERS_ID,- aggregation: [["count"]],- },- display: "scalar",- });-- H.startNewQuestion();- H.miniPickerBrowseAll().click();- H.entityPickerModalItem(0, "Our analytics").click();- H.entityPickerModal().findByText("Orders in a dashboard").click();- H.entityPickerModal()- .findByText("Total Orders Dashboard Question")- .click();- H.visualize();- cy.findByTestId("query-visualization-root").findByText("18,760");- });-it("can find dashboard questions in the search", () => {H.createQuestion({name: "Total Orders Dashboard Question",@@ -877,7 +850,6 @@ describe("Dashboard > Dashboard Questions", () => {H.visitQuestion("@avgQuanityQuestionId");H.openQuestionActions("Move");- H.entityPickerModalTab("Browse").click();H.entityPickerModal().findByText("Orders in a dashboard").click();H.entityPickerModal().button("Move").click();@@ -961,10 +933,9 @@ describe("Dashboard > Dashboard Questions", () => {cy.findByLabelText(/Where do you want to save this/).click();});- H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();- cy.findByText("Dashboard with tabs").click();- cy.findByText("Select this dashboard").click();+ H.pickEntity({+ path: ["Our analytics", "Dashboard with tabs"],+ select: true,});cy.findByTestId("save-question-modal").within(() => {@@ -1023,7 +994,6 @@ describe("Dashboard > Dashboard Questions", () => {});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText("Dashboard with tabs").click();cy.findByText("Select this dashboard").click();});diff --git a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.jsindex 80e474d9eb4..3d766f6034c 100644--- a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js@@ -96,8 +96,8 @@ describe("issue 61013", () => {H.modal().within(() => {cy.findByPlaceholderText("Search…").type(dashboardName);- cy.findByTestId("result-item").click();- cy.findByText("Select").click();+ cy.findByText(dashboardName).click();+ cy.findByTestId("entity-picker-select-button").click();});H.getDashboardCards().should("have.length", 1);@@ -133,8 +133,8 @@ describe("issue 61013", () => {H.modal().within(() => {cy.findByPlaceholderText("Search…").type(dashboardName);- cy.findByTestId("result-item").click();- cy.findByText("Select").click();+ cy.findByText(dashboardName).click();+ cy.findByTestId("entity-picker-select-button").click();});cy.findByTestId("edit-bar")diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.jsindex c0bebcbb970..709cd358350 100644--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js@@ -93,9 +93,7 @@ describe("scenarios > dashboard", () => {H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {cy.findByText("Databases").click();- cy.findByPlaceholderText("Search this database or everywhere…").type(- "Pro",- );+ cy.findByPlaceholderText("Search…").type("Pro");cy.findByText("Products").click();});@@ -125,62 +123,6 @@ describe("scenarios > dashboard", () => {.and("not.contain", newQuestionName);});- it(- "should create new dashboard inside a collection created on the go",- // Increased height to avoid scrolling when opening a collection picker- { viewportHeight: 1000 },- () => {- cy.intercept("POST", "api/collection").as("createCollection");- cy.visit("/");- cy.findByTestId("home-page").should(- "contain",- "Try out these sample x-rays to see what Metabase can do.",- );- H.closeNavigationSidebar();- H.appBar().findByText("New").click();- H.popover().findByText("Dashboard").should("be.visible").click();- const NEW_DASHBOARD = "Foo";- cy.findByTestId("new-dashboard-modal").then((modal) => {- cy.findByRole("heading", { name: "New dashboard" });- cy.findByLabelText("Name").type(NEW_DASHBOARD).blur();- cy.findByTestId("collection-picker-button")- .should("have.text", "Our analytics")- .click();- });-- H.entityPickerModal()- .findByRole("tab", { name: /Collections/ })- .click();- H.entityPickerModal()- .findByText("New collection")- .click({ force: true });- const NEW_COLLECTION = "Bar";- H.collectionOnTheGoModal().within(() => {- cy.findByText("Create a new collection");- cy.findByPlaceholderText(/My new collection/)- .type(NEW_COLLECTION)- .blur();- cy.findByText("Create").click();- cy.wait("@createCollection");- });- H.entityPickerModal().within(() => {- cy.findByText(NEW_COLLECTION).click();- cy.button("Select").click();- });- H.modal().within(() => {- cy.findByText("New dashboard");- cy.findByTestId("collection-picker-button").should(- "have.text",- NEW_COLLECTION,- );- cy.button("Create").click();- });-- H.saveDashboard({ awaitRequest: false });- cy.findByTestId("app-bar").findByText(NEW_COLLECTION);- },- );-it("adding question to one dashboard shouldn't affect previously visited unrelated dashboards (metabase#26826)", () => {cy.intercept("POST", "/api/card").as("saveQuestion");@@ -192,9 +134,9 @@ describe("scenarios > dashboard", () => {cy.findByTestId("save-question-modal").within(() => {cy.findByTestId("dashboard-and-collection-picker-button").click();});- H.entityPickerModal().within(() => {- cy.findByText("First collection").click();- cy.findByText("Select this collection").click();+ H.pickEntity({+ path: ["Our analytics", "First collection"],+ select: true,});cy.findByTestId("save-question-modal").within(() => {cy.findByText("Save").click();@@ -205,9 +147,6 @@ describe("scenarios > dashboard", () => {H.checkSavedToCollectionQuestionToast(true);- H.entityPickerModal()- .findByRole("tab", { name: /Dashboards/ })- .click();H.entityPickerModal().findByText("New dashboard").click();cy.findByTestId("create-dashboard-on-the-go").within(() => {cy.findByPlaceholderText("My new dashboard").type("Foo");@@ -313,7 +252,6 @@ describe("scenarios > dashboard", () => {H.openDashboardMenu();H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Collections/ }).click();cy.findByText("Bobby Tables's Personal Collection").click();cy.button("Move").click();});@@ -332,7 +270,6 @@ describe("scenarios > dashboard", () => {H.openDashboardMenu();H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Collections/ }).click();cy.findByText("Our analytics").click();cy.button("Move").click();});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.tsindex bd90f6e586c..c8debeaed17 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@@ -81,7 +81,6 @@ describe("scenarios > data studio > library", () => {H.openQuestionActions("Duplicate");H.modal().findByTestId("dashboard-and-collection-picker-button").click();- H.entityPickerModalTab("Collections").click();H.entityPickerModalItem(0, "Library").click();H.entityPickerModalItem(1, "Metrics").click();H.entityPickerModal().button("Select this collection").click();@@ -109,8 +108,10 @@ describe("scenarios > data studio > library", () => {H.popover().findByText("Published table").click();cy.log("Select a table and click 'Publish'");- H.entityPickerModalItem(3, "Orders").click();- H.entityPickerModal().button("Publish").click();+ H.pickEntity({+ path: ["Databases", /Sample Database/, "Orders"],+ select: true,+ });cy.log("Verify the table is published");H.DataStudio.Tables.overviewPage().should("exist");@@ -123,8 +124,9 @@ describe("scenarios > data studio > library", () => {);H.DataStudio.Library.newButton().click();H.popover().findByText("Published table").click();- H.entityPickerModalItem(3, "Orders").should("have.attr", "data-disabled");- H.entityPickerModalItem(3, "People").should(+ H.entityPickerModalItem(1, /Sample Database/).click();+ H.entityPickerModalItem(2, "Orders").should("have.attr", "data-disabled");+ H.entityPickerModalItem(2, "People").should("not.have.attr","data-disabled",);@@ -170,7 +172,8 @@ describe("scenarios > data studio > library", () => {.findByRole("button", { name: "Publish a table" }).click();H.entityPickerModal().should("be.visible");- H.entityPickerModalItem(3, "Orders").should("exist");+ H.entityPickerModalItem(1, "Sample Database").click();+ H.entityPickerModalItem(2, "Orders").should("exist");H.entityPickerModal().button("Close").click();cy.log("Search for text and verify empty states are excluded");@@ -194,7 +197,8 @@ describe("scenarios > data studio > library", () => {cy.log("Publish a table via the +New menu");H.DataStudio.Library.newButton().click();H.popover().findByText("Published table").click();- H.entityPickerModalItem(3, "Orders").click();+ H.entityPickerModalItem(1, "Sample Database").click();+ H.entityPickerModalItem(2, "Orders").click();H.entityPickerModal().button("Publish").click();cy.log("Navigate back to Library via breadcrumbs");diff --git a/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.tsindex 255bd8744c6..c82dcb0255a 100644--- a/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts@@ -27,10 +27,7 @@ describe("scenarios > data studio > library > metrics", () => {H.DataStudio.Metrics.saveButton().should("be.disabled");H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- cy.findByText("Databases").click();- cy.findByText("Orders").click();- });+ H.pickEntity({ path: ["Databases", /Sample Database/, "Orders"] });H.getNotebookStep("summarize").findByText("Pick a column to group by")@@ -286,7 +283,6 @@ describe("scenarios > data studio > library > metrics", () => {.should("have.value", "Trusted Orders Metric - Duplicate");H.modal().findByTestId("dashboard-and-collection-picker-button").click();- H.entityPickerModalTab("Collections").click();H.entityPickerModal().within(() => {cy.findByText("Our analytics").click();cy.findByText("Library").click();@@ -331,8 +327,7 @@ describe("scenarios > data studio > library > metrics", () => {H.popover().findByText("Move").click();cy.log("Select First collection as destination");- H.entityPickerModal().findByText("First collection").click();- H.entityPickerModal().button("Move").click();+ H.pickEntity({ path: ["Our analytics", "First collection"], select: true });cy.wait("@updateCard");diff --git a/e2e/test/scenarios/data-studio/table-collection-permissions.cy.spec.ts b/e2e/test/scenarios/data-studio/table-collection-permissions.cy.spec.tsindex 0e214c59b82..deb0ef5fedc 100644--- a/e2e/test/scenarios/data-studio/table-collection-permissions.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/table-collection-permissions.cy.spec.ts@@ -188,6 +188,7 @@ describe("scenarios > data studio > table collection permissions", () => {H.getNotebookStep("data").button("Join data").click();H.popover().findByText("Browse all").click();H.entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();cy.findByText("Orders Model").click();});H.getNotebookStep("join").button("Summarize").click();diff --git a/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts b/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.tsindex ab6ad573939..bf3055aaabd 100644--- a/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/transforms/transforms.cy.spec.ts@@ -350,20 +350,14 @@ describe("scenarios > admin > transforms", () => {);it("should be able to create and run a transform from a question or a model", () => {- function testCardSource({- type,- label,- }: {- type: CardType;- label: string;- }) {+ function testCardSource({ type }: { type: CardType }) {H.resetSnowplow();cy.log("create a query in the target database");H.getTableId({ name: SOURCE_TABLE, databaseId: WRITABLE_DB_ID }).then((tableId) =>H.createQuestion({- name: "Test",+ name: `Test ${type}`,type,database: WRITABLE_DB_ID,query: {@@ -381,10 +375,8 @@ describe("scenarios > admin > transforms", () => {event_detail: "saved-question",});- H.entityPickerModal().within(() => {- H.entityPickerModalTab(label);- cy.findByText("Test").click();- });+ H.pickEntity({ path: ["Our analytics", `Test ${type}`], select: true });+getQueryEditor().button("Save").click();H.modal().within(() => {cy.findByLabelText("Name").clear().type(`${type} transform`);@@ -410,8 +402,8 @@ describe("scenarios > admin > transforms", () => {H.assertQueryBuilderRowCount(3);}- testCardSource({ type: "question", label: "Questions" });- testCardSource({ type: "model", label: "Models" });+ testCardSource({ type: "question" });+ testCardSource({ type: "model" });});it("should be possible to convert an MBQL transform to a SQL transform", () => {@@ -608,6 +600,7 @@ LIMITH.miniPickerHeader().click(); // go backH.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();cy.findAllByTestId("picker-item").contains("Animal Metric").should("have.attr", "data-disabled", "true");@@ -664,16 +657,10 @@ LIMIT});it("should not be possible to create a transform from a question or a model that is based of an unsupported database", () => {- function testCardSource({- type,- label,- }: {- type: CardType;- label: string;- }) {+ function testCardSource({ type }: { type: CardType }) {cy.log("create a query in the target database");H.createQuestion({- name: "Test",+ name: `Test ${type}`,type,database: SAMPLE_DB_ID,query: {@@ -686,15 +673,15 @@ LIMITcy.button("Create a transform").click();H.popover().findByText("Copy of a saved question").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab(label);- cy.findAllByTestId("picker-item")- .contains("Test")+ cy.findByText("Our analytics").click();+ cy.findByText(`Test ${type}`)+ .closest("a").should("have.attr", "data-disabled", "true");});}- testCardSource({ type: "question", label: "Questions" });- testCardSource({ type: "model", label: "Models" });+ testCardSource({ type: "question" });+ testCardSource({ type: "model" });});it("should not auto-pivot query results for MBQL transforms", () => {@@ -2244,7 +2231,7 @@ LIMIT.click();H.entityPickerModal().within(() => {- cy.findByText("Schema a").click();+ cy.findByText("Schema A").click();cy.findByText("Animals").click();});@@ -2357,7 +2344,7 @@ LIMIT.click();H.entityPickerModal().within(() => {- cy.findByText("Schema a").click();+ cy.findByText("Schema A").click();cy.findByText("Animals").click();});@@ -2574,7 +2561,7 @@ LIMIT});cy.findByRole("dialog", { name: "Select a collection" }).within(() => {- cy.findByRole("button", { name: /New collection/ }).click();+ cy.findByRole("button", { name: /New folder/ }).click();});cy.findByRole("dialog", { name: "Create a new collection" }).within(diff --git a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.tsindex 62652e534d0..1f0d5197217 100644--- a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts+++ b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts@@ -97,23 +97,18 @@ describe("scenarios > dependencies > dependency graph", () => {}function testEntityPicker({- tabName,- itemName,- itemLevel,+ path,itemIcon,}: {- tabName: string;- itemName: string;- itemLevel: number;+ path: (string | RegExp)[];itemIcon: IconName;}) {+ const itemName = path[path.length - 1];+ const itemLevel = path.length - 1;cy.log(`verify that "${itemName}" can be selected in the picker`);H.DependencyGraph.entrySearchInput().click();H.popover().findByText("Browse all").click();- H.entityPickerModal().within(() => {- H.entityPickerModalTab(tabName).click();- H.entityPickerModalItem(itemLevel, itemName).click();- });+ H.pickEntity({ path });H.DependencyGraph.entryButton().should("have.text", itemName);H.DependencyGraph.entryButton().icon(itemIcon).should("be.visible");@@ -133,9 +128,11 @@ describe("scenarios > dependencies > dependency graph", () => {H.DependencyGraph.entrySearchInput().click();H.popover().findByText("Browse all").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab(tabName).click();- cy.findByPlaceholderText(/Search/).type(itemName);- cy.findByText(/result for/).should("exist");+ cy.findByPlaceholderText(/Search/).type(itemName as string);+ cy.findByText(/results for/).should("be.visible");+ cy.findByTestId("search-scope-selector")+ .findByText("Everywhere")+ .click();cy.findByText(itemName).click();});H.DependencyGraph.entryButton().should("have.text", itemName);@@ -185,33 +182,23 @@ describe("scenarios > dependencies > dependency graph", () => {visitGraph();testEntityPicker({- tabName: "Tables",- itemName: "Products",- itemLevel: 3,+ path: ["Databases", /Sample Database/, "Products"],itemIcon: "table",});testEntityPicker({- tabName: "Questions",- itemName: "Orders, Count, Grouped by Created At (year)",- itemLevel: 1,+ path: ["Our analytics", "Orders, Count, Grouped by Created At (year)"],itemIcon: "line",});testEntityPicker({- tabName: "Models",- itemName: "Orders Model",- itemLevel: 1,+ path: ["Our analytics", "Orders Model"],itemIcon: "model",});testEntityPicker({- tabName: "Metrics",- itemName: TABLE_BASED_METRIC_NAME,- itemLevel: 1,+ path: ["Our analytics", TABLE_BASED_METRIC_NAME],itemIcon: "metric",});testEntityPicker({- tabName: "Transforms",- itemName: TABLE_BASED_TRANSFORM_NAME,- itemLevel: 0,+ path: [/Transforms/, TABLE_BASED_TRANSFORM_NAME],itemIcon: "transform",});});diff --git a/e2e/test/scenarios/documents/card-embed-node.cy.spec.ts b/e2e/test/scenarios/documents/card-embed-node.cy.spec.tsindex 4f2008a53f2..04e9ca8f527 100644--- a/e2e/test/scenarios/documents/card-embed-node.cy.spec.ts+++ b/e2e/test/scenarios/documents/card-embed-node.cy.spec.ts@@ -308,7 +308,7 @@ describe("documents card embed node custom logic", () => {});// Add another card to try to exceed the limit- addNewStandaloneCard("Orders Model", "model");+ addNewStandaloneCard("Orders Model");// Wait for the new card to be addedH.documentContent()@@ -454,7 +454,7 @@ describe("documents card embed node custom logic", () => {it("should handle moving cards between different flexContainers", () => {// First create another flexContainer by dragging the standalone card onto a new location// Add another standalone card first- addNewStandaloneCard("Orders Model", "model");+ addNewStandaloneCard("Orders Model");// Wait for the new cardH.documentContent()@@ -780,18 +780,12 @@ function assertFlexContainerCardsOrder(expectedCardTitles: string[]) {}}-function addNewStandaloneCard(- cardName: string,- cardType: "question" | "model",-) {+function addNewStandaloneCard(cardName: string) {cy.get(".node-paragraph.is-empty").click();H.addToDocument("/", false);H.commandSuggestionItem("Chart").click();H.commandSuggestionItem(/Browse all/).click();- H.entityPickerModalTab(- cardType === "question" ? "Questions" : "Models",- ).click();- H.entityPickerModalItem(1, cardName).click();+ H.pickEntity({ path: ["Our analytics", cardName], select: true });}function getCardWidths(diff --git a/e2e/test/scenarios/documents/document-links.cy.spec.ts b/e2e/test/scenarios/documents/document-links.cy.spec.tsindex 6fd16f184b4..c96371b6dfe 100644--- a/e2e/test/scenarios/documents/document-links.cy.spec.ts+++ b/e2e/test/scenarios/documents/document-links.cy.spec.ts@@ -163,18 +163,8 @@ describe("Links in documents", () => {H.modal().within(() => {cy.findByText("Choose an item to link").should("be.visible");- cy.findByTestId("tabs-view")- .should("be.visible")- .within(() => {- cy.findByText("Recents").should("be.visible");- cy.findByText("Tables").should("be.visible");- cy.findByText("Questions").should("be.visible");- cy.findByText("Models").should("be.visible");- cy.findByText("Dashboards").should("be.visible");- cy.findByText("Collections").should("be.visible");- });-- cy.findByText("Dashboards").click();++ cy.findByText("Our analytics").click();cy.findByText("Orders in a dashboard").click();cy.button("Select").should("be.visible").and("be.enabled").click();});@@ -191,7 +181,6 @@ describe("Links in documents", () => {openLinkSuggestionBrowseAllPicker();H.modal().within(() => {- cy.findByText("Collections").click();cy.findByText("All personal collections").click();cy.log(@@ -221,19 +210,8 @@ describe("Links in documents", () => {H.modal().within(() => {cy.findByText("Choose an item to link").should("be.visible");- cy.findByTestId("tabs-view")- .should("be.visible")- .within(() => {- cy.findByText("Recents").should("be.visible");- cy.findByText("Tables").should("be.visible");- cy.findByText("Questions").should("be.visible");- cy.findByText("Models").should("be.visible");- cy.findByText("Dashboards").should("be.visible");- cy.findByText("Collections").should("be.visible");- });-- cy.findByText("Tables").click();- cy.findByText("Products").click();++ H.pickEntity({ path: ["Databases", "Sample Database", "Products"] });cy.button("Select").should("be.visible").and("be.enabled").click();});diff --git a/e2e/test/scenarios/documents/document-permissions.cy.spec.ts b/e2e/test/scenarios/documents/document-permissions.cy.spec.tsindex 74f7d6ee76a..c91ef8d8b75 100644--- a/e2e/test/scenarios/documents/document-permissions.cy.spec.ts+++ b/e2e/test/scenarios/documents/document-permissions.cy.spec.ts@@ -35,9 +35,7 @@ describe("document permissions", () => {cy.findByRole("button", { name: "Save" }).click();- cy.findByTestId("item-picker-level-0")- .findByText("Our analytics")- .should("not.exist");+ H.entityPickerModalLevel(0).findByText("Our analytics").should("not.exist");H.entityPickerModalItem(0, "Collections").should("exist");H.entityPickerModalItem(0, /Personal Collection/).click();diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.tsindex b8b47d5acd8..badc8662a6d 100644--- a/e2e/test/scenarios/documents/documents.cy.spec.ts+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts@@ -46,12 +46,7 @@ describe("documents", () => {cy.findByRole("button", { name: "Save" }).click();- H.entityPickerModalTab("Collections").click();- H.entityPickerModalItem(0, "Our analytics").should(- "have.attr",- "data-active",- "true",- );+ H.entityPickerModalItem(0, "Our analytics").click();H.entityPickerModalItem(1, "First collection").click();H.entityPickerModal().findByRole("button", { name: "Select" }).click();@@ -88,7 +83,6 @@ describe("documents", () => {H.popover().findByText("Move").click();- H.entityPickerModalTab("Collections").click();H.entityPickerModalItem(0, "Our analytics").should("have.attr", "data-active", "true").click();@@ -126,7 +120,6 @@ describe("documents", () => {);cy.findByTestId("collection-picker-button").click();- H.entityPickerModalTab("Collections").click();H.entityPickerModalItem(0, /Personal Collection/).click();H.entityPickerModal().findByRole("button", { name: "Select" }).click();H.modal().findByRole("button", { name: "Copy" }).click();@@ -677,29 +670,12 @@ describe("documents", () => {H.commandSuggestionItem("Chart").click();H.commandSuggestionItem(/Browse all/).click();- H.entityPickerModalTab("Questions").click();H.entityPickerModalItem(1, PRODUCTS_AVERAGE_BY_CATEGORY.name).click();+ H.entityPickerModal().findByRole("button", { name: "Select" }).click();H.getDocumentCard(PRODUCTS_AVERAGE_BY_CATEGORY.name).should("exist");cy.realPress("{downarrow}");- cy.log("dashboard question via entity picker");- H.addToDocument("/", false);-- H.commandSuggestionItem("Chart").click();- H.commandSuggestionItem(/Browse all/).click();-- H.entityPickerModalTab("Questions").click();- H.entityPickerModalItem(1, "Fancy Dashboard").click();- H.entityPickerModalItem(- 2,- ORDERS_COUNT_BY_PRODUCT_CATEGORY.name,- ).click();-- H.getDocumentCard(ORDERS_COUNT_BY_PRODUCT_CATEGORY.name).should(- "exist",- );-cy.log("change a cards display type");H.openDocumentCardMenu(ACCOUNTS_COUNT_BY_CREATED_AT.name);H.popover().findByText("Edit Visualization").click();@@ -735,7 +711,7 @@ describe("documents", () => {.should("have.length", 7);//Replace Card- H.openDocumentCardMenu(ORDERS_COUNT_BY_PRODUCT_CATEGORY.name);+ H.openDocumentCardMenu(PRODUCTS_COUNT_BY_CATEGORY_PIE.name);H.popover().findByText("Replace").click();H.modal().within(() => {@@ -744,6 +720,8 @@ describe("documents", () => {cy.findAllByPlaceholderText("Search…").click().type("Orders");cy.findAllByTestId("result-item").findByText("Orders").click();++ cy.findByRole("button", { name: "Select" }).click();});cy.get("@documentId").then((id) => {@@ -1591,13 +1569,8 @@ describe("documents", () => {// make changes and attempt to savecy.findByRole("textbox", { name: "Document Title" }).type("Title");H.documentSaveButton().click();- H.entityPickerModalTab("Collections").click();cy.wait("@getCollection");- H.entityPickerModalItem(0, "Our analytics").should(- "have.attr",- "data-active",- "true",- );+ H.entityPickerModalItem(0, "Our analytics").click();H.entityPickerModal().findByRole("button", { name: "Select" }).click();// assert error toast is visible and user can reattempt savediff --git a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.tsindex 56f80dca55e..4b96fc33bd0 100644--- a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts+++ b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts@@ -36,8 +36,7 @@ describe("scenarios - embedding hub", () => {cy.findByText("Choose a table to generate a dashboard").should("be.visible",);- // Click on the first available table- H.entityPickerModalItem(3, "Accounts").click();+ H.pickEntity({ path: ["Databases", "Sample Database", "Accounts"] });});cy.log("Should navigate to auto dashboard creation");diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.tsindex 76f31502a00..2096b9f5526 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts@@ -157,7 +157,6 @@ describe("scenarios > embedding > sdk iframe embed setup > guest-embed", () => {H.entityPickerModal().within(() => {cy.findByText("Select a chart").should("be.visible");- cy.findByText("Questions").click();cy.findByText(FIRST_QUESTION_NAME).click();});@@ -299,7 +298,7 @@ describe("scenarios > embedding > sdk iframe embed setup > guest-embed", () => {});entityPickerModal().within(() => {- cy.findByText("Questions").click();+ cy.findByText("Our analytics").click();cy.findAllByText(SECOND_QUESTION_NAME).first().click();});@@ -328,7 +327,7 @@ describe("scenarios > embedding > sdk iframe embed setup > guest-embed", () => {});entityPickerModal().within(() => {- cy.findByText("Questions").click();+ cy.findByText("Our analytics").click();cy.findAllByText(FIRST_QUESTION_NAME).first().click();});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.tsindex 65305d4db6e..32cebc0e7d1 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts@@ -154,7 +154,6 @@ describe(H.entityPickerModal().within(() => {cy.findByText("Select a chart").should("be.visible");- cy.findByText("Questions").click();cy.findByText(FIRST_QUESTION_NAME).click();});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.tsindex 39e3f506a04..d98d472d567 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/helpers/index.ts@@ -132,7 +132,7 @@ export const navigateToEntitySelectionStep = (});entityPickerModal().within(() => {- cy.findByText(resourceType).click();+ cy.findByText("Our analytics").click();cy.findAllByText(options.resourceName).first().click();// Collection picker requires an explicit confirmation.diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.tsindex c06931e14fc..38cd55b5897 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-entity.cy.spec.ts@@ -164,7 +164,7 @@ describe(suiteTitle, () => {H.entityPickerModal().within(() => {cy.findByText("Select a dashboard").should("be.visible");- cy.findByText("Dashboards").click();+ cy.findByText("Our analytics").click();cy.findByText(SECOND_DASHBOARD_NAME).click();});@@ -194,7 +194,7 @@ describe(suiteTitle, () => {H.entityPickerModal().within(() => {cy.findByText("Select a chart").should("be.visible");- cy.findByText("Questions").click();+ cy.findByText("Our analytics").click();cy.findByText(FIRST_QUESTION_NAME).click();});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/content-translations.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/content-translations.cy.spec.tsindex c9b904d073f..9d6c42609cd 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/content-translations.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/content-translations.cy.spec.ts@@ -126,33 +126,10 @@ describe("scenarios > embedding > sdk iframe embedding > content-translations",.click();H.getSimpleEmbedIframeContent().within(() => {- H.modal().within(() => {- cy.findByText("Test Sammlung").should("be.visible");- cy.findByText("Test Sammlung").click();- });-- H.modal()- .should("have.length", 2)- .last()- .within(() => {- cy.findAllByTestId("result-item").first().should("be.visible");-- cy.findAllByTestId("result-item")- .first()- .within(() => {- cy.icon("info").click();- });- });-- H.tooltip().should("contain", "Testbeschreibung");-- H.modal()- .should("have.length", 2)- .last()- .within(() => {- cy.findByText("Sammlungen").click();- cy.findByText("Test Sammlung").should("be.visible");- });+ H.modal().findByText("Test Sammlung").should("be.visible").click();+ H.entityPickerModal()+ .findByText("Test Sammlung")+ .should("be.visible");});});});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/view-and-curate-content.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/view-and-curate-content.cy.spec.tsindex 0a2c3c739fc..3b3d7f673c9 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/view-and-curate-content.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/view-and-curate-content.cy.spec.ts@@ -231,7 +231,6 @@ describe("scenarios > embedding > sdk iframe embedding > view and curate contentcy.findByText("Our analytics").click();});- cy.findByText("Collections").click();cy.findByText("New collection").click();H.modal()diff --git a/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions.cy.spec.js b/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions.cy.spec.jsindex 36e9e6c9139..0b075f9beff 100644--- a/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions.cy.spec.js+++ b/e2e/test/scenarios/filters-reproductions/dashboard-filters-reproductions.cy.spec.js@@ -5347,7 +5347,7 @@ describe("issue 46541", () => {});H.entityPickerModal().within(() => {- cy.findByText("Dashboards").click();+ cy.findByText("Our analytics").click();cy.findByText("Dashboard B").click();});diff --git a/e2e/test/scenarios/filters/filter.cy.spec.js b/e2e/test/scenarios/filters/filter.cy.spec.jsindex 0313318f226..190ceb1544a 100644--- a/e2e/test/scenarios/filters/filter.cy.spec.js+++ b/e2e/test/scenarios/filters/filter.cy.spec.js@@ -803,7 +803,6 @@ describe("scenarios > question > filter", () => {.findByLabelText(/Where do you want to save this/).click();H.pickEntity({- tab: "Browse",path: ["Our analytics"],});H.entityPickerModal().findByText("Select this collection").click();diff --git a/e2e/test/scenarios/joins/joins-reproductions.cy.spec.js b/e2e/test/scenarios/joins/joins-reproductions.cy.spec.jsindex 1aa6c79326e..ed68e8cf247 100644--- a/e2e/test/scenarios/joins/joins-reproductions.cy.spec.js+++ b/e2e/test/scenarios/joins/joins-reproductions.cy.spec.js@@ -803,7 +803,6 @@ describe("issue 23293", () => {.findByLabelText(/Where do you want to save this/).click();H.pickEntity({- tab: "Browse",path: ["Our analytics"],});H.entityPickerModal().findByText("Select this collection").click();diff --git a/e2e/test/scenarios/joins/joins.cy.spec.js b/e2e/test/scenarios/joins/joins.cy.spec.jsindex 1318d1b53d7..1ea220713b0 100644--- a/e2e/test/scenarios/joins/joins.cy.spec.js+++ b/e2e/test/scenarios/joins/joins.cy.spec.js@@ -76,7 +76,6 @@ describe("scenarios > question > joined questions", () => {.findByLabelText(/Where do you want to save this/).click();H.pickEntity({- tab: "Browse",path: ["Our analytics"],});H.entityPickerModal().button("Select this collection").click();diff --git a/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.js b/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.jsindex c9df8c4db91..27b06b52fb9 100644--- a/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.js+++ b/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.js@@ -248,8 +248,7 @@ describe("scenarios > metrics > dashboard", () => {H.visitDashboard(ORDERS_DASHBOARD_ID);H.editDashboard();H.getDashboardCard().realHover().findByLabelText("Replace").click();- H.modal().within(() => {- cy.findByText("Metrics").click();+ H.entityPickerModal().within(() => {cy.findByText(ORDERS_SCALAR_METRIC.name).click();});// eslint-disable-next-line metabase/no-unsafe-element-filtering@@ -262,9 +261,8 @@ describe("scenarios > metrics > dashboard", () => {cy.findByText("18,760").should("be.visible");});H.getDashboardCard().realHover().findByLabelText("Replace").click();- H.modal().within(() => {+ H.entityPickerModal().within(() => {cy.findByText(ORDERS_SCALAR_METRIC.name).should("be.visible");- cy.findByText("Questions").click();cy.findByText("Orders").click();});// eslint-disable-next-line metabase/no-unsafe-element-filteringdiff --git a/e2e/test/scenarios/metrics/metrics-editing.cy.spec.js b/e2e/test/scenarios/metrics/metrics-editing.cy.spec.jsindex aeaa95dccd4..d4715a3738e 100644--- a/e2e/test/scenarios/metrics/metrics-editing.cy.spec.js+++ b/e2e/test/scenarios/metrics/metrics-editing.cy.spec.js@@ -297,10 +297,9 @@ describe("scenarios > metrics > editing", () => {});H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Data").click();+ cy.findByText("Sample Database").click();cy.findByText("Orders").should("be.visible");- // FIXME: metabase#66210- // cy.findByText(ORDERS_SCALAR_METRIC.name).should("not.exist");+ cy.findByText(ORDERS_SCALAR_METRIC.name).should("not.exist");});});diff --git a/e2e/test/scenarios/models/models.cy.spec.js b/e2e/test/scenarios/models/models.cy.spec.jsindex 41f70aa8dfa..227e5a0a531 100644--- a/e2e/test/scenarios/models/models.cy.spec.js+++ b/e2e/test/scenarios/models/models.cy.spec.js@@ -322,8 +322,6 @@ describe("scenarios > models", () => {});H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Collections/ }).click();-cy.findByText(/Select a collection$/).should("exist"); // title should not have trailing "or dashboard"cy.findByText("Orders in a dashboard").should("not.exist"); // this dashboard would be present if dashboards were an allowed save targetcy.findByText("First collection").should("exist").click();@@ -375,21 +373,19 @@ describe("scenarios > models", () => {cy.findByText("Products").should("exist");H.entityPickerModalItem(0, "Databases").click();+ H.entityPickerModalItem(1, "Sample Database").click();- H.entityPickerModalItem(1, "Orders").should("exist");- H.entityPickerModalItem(1, "People").should("exist");- H.entityPickerModalItem(1, "Products").should("exist");- H.entityPickerModalItem(1, "Reviews").should("exist");+ H.entityPickerModalItem(2, "Orders").should("exist");+ H.entityPickerModalItem(2, "People").should("exist");+ H.entityPickerModalItem(2, "Products").should("exist");+ H.entityPickerModalItem(2, "Reviews").should("exist");cy.findByText("Orders, Count").should("not.exist");- cy.findByPlaceholderText("Search this database or everywhere…").type(- "Ord",- );+ cy.findByPlaceholderText("Search…").type("Ord");cy.wait("@search");getResults().should("have.length", 1);- cy.findByText("1 result").should("be.visible");getResults().eq(0).should("have.attr", "data-model-type", "table")@@ -397,7 +393,6 @@ describe("scenarios > models", () => {cy.findByText("Everywhere").click();getResults().should("have.length", 5);- cy.findByText("5 results").should("be.visible");getResults().eq(0).should("have.attr", "data-model-type", "dataset")@@ -433,15 +428,16 @@ describe("scenarios > models", () => {cy.icon("join_left_outer").click();H.miniPickerBrowseAll().click();- H.entityPickerModalTab("Data").click();H.entityPickerModal().within(() => {H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalItem(1, "Orders").should("exist");- H.entityPickerModalItem(1, "People").should("exist");- H.entityPickerModalItem(1, "Products").should("exist");- H.entityPickerModalItem(1, "Reviews").should("exist");+ H.entityPickerModalItem(1, "Sample Database").click();++ H.entityPickerModalItem(2, "Orders").should("exist");+ H.entityPickerModalItem(2, "People").should("exist");+ H.entityPickerModalItem(2, "Products").should("exist");+ H.entityPickerModalItem(2, "Reviews").should("exist");- H.entityPickerModalItem(1, "Products").click();+ H.entityPickerModalItem(2, "Products").click();});H.getNotebookStep("filter")@@ -487,6 +483,7 @@ describe("scenarios > models", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {+ H.entityPickerModalItem(1, "Sample Database").click();cy.findByText("Orders").should("exist");cy.findByText("People").should("exist");cy.findByText("Products").should("exist");diff --git a/e2e/test/scenarios/models/reproductions.cy.spec.js b/e2e/test/scenarios/models/reproductions.cy.spec.jsindex db03121db25..884e49a8ffb 100644--- a/e2e/test/scenarios/models/reproductions.cy.spec.js+++ b/e2e/test/scenarios/models/reproductions.cy.spec.js@@ -64,9 +64,11 @@ describe("issue 19737", () => {openEllipsisMenuFor(modelName);H.popover().findByText("Move").click();+ H.pickEntity({+ path: Array.isArray(collectionName) ? collectionName : [collectionName],+ });+H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Browse|Collections/ }).click();- cy.findByText(collectionName).click();cy.button("Move").click();});}@@ -105,7 +107,7 @@ describe("issue 19737", () => {// move "Orders Model" to "First collection"cy.visit("/collection/root");- moveModel(modelName, "First collection");+ moveModel(modelName, ["Our analytics", "First collection"]);// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usagecy.findByText("Moved model");@@ -121,6 +123,7 @@ describe("issue 19737", () => {// Open question picker (this is crucial) so the collection list are loaded.H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();cy.findByText("First collection").click();cy.findByText(modelName);});@@ -327,7 +330,6 @@ describe("issue 20963", () => {questionName,{ wrapId: true },{- tab: "Browse",path: ["Our analytics"],},);@@ -794,7 +796,6 @@ describe("issue 26091", () => {cy.findByText("Orders").click();});H.saveQuestion("New model", undefined, {- tab: "Browse",path: ["Our analytics"],});turnIntoModel();diff --git a/e2e/test/scenarios/models/reproductions.cy.spec.ts b/e2e/test/scenarios/models/reproductions.cy.spec.tsindex 1e0b556ba3b..70562623a57 100644--- a/e2e/test/scenarios/models/reproductions.cy.spec.ts+++ b/e2e/test/scenarios/models/reproductions.cy.spec.ts@@ -1078,11 +1078,8 @@ describe("issue 35840", () => {cy.signInAsNormalUser();});- function checkColumnMapping(entityTab: string, entityName: string) {- H.entityPickerModal().within(() => {- H.entityPickerModalTab(entityTab).click();- cy.findByText(entityName).click();- });+ function checkColumnMapping(path: string[]) {+ H.pickEntity({ path, select: true });H.modal().findByText("Pick a column…").click();H.popover().findAllByText("Category").eq(0).click();H.modal().within(() => {@@ -1107,11 +1104,11 @@ describe("issue 35840", () => {cy.findByText("From another model or question").click();cy.findByText("Pick a model or question…").click();});- checkColumnMapping("Models", modelName);+ checkColumnMapping(["Our analytics", modelName]);cy.log("Use model-based question for dropdown source");H.modal().findByText(modelName).click();- checkColumnMapping("Questions", questionName);+ checkColumnMapping(["Our analytics", questionName]);});});@@ -1979,8 +1976,7 @@ describe("issue 38747", () => {cy.findByRole("link", { name: /notebook editor/ }).click();H.miniPickerBrowseAll().click();- H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalItem(1, "Products").click();+ H.pickEntity({ path: ["Databases", "Sample Database", "Products"] });H.runButtonInOverlay().click();// Wait for the query to run so we can click the columns "button"diff --git a/e2e/test/scenarios/native-filters/sql-field-filter-types.cy.spec.js b/e2e/test/scenarios/native-filters/sql-field-filter-types.cy.spec.jsindex 8f2eb73336d..136f68d92d7 100644--- a/e2e/test/scenarios/native-filters/sql-field-filter-types.cy.spec.js+++ b/e2e/test/scenarios/native-filters/sql-field-filter-types.cy.spec.js@@ -289,7 +289,6 @@ describe(field: "Boolean",});H.saveQuestion("SQL", undefined, {- tab: "Browse",path: ["Our analytics"],});diff --git a/e2e/test/scenarios/native-filters/sql-filters-source.cy.spec.js b/e2e/test/scenarios/native-filters/sql-filters-source.cy.spec.jsindex b81e7f909f1..fd57a0c05f2 100644--- a/e2e/test/scenarios/native-filters/sql-filters-source.cy.spec.js+++ b/e2e/test/scenarios/native-filters/sql-filters-source.cy.spec.js@@ -51,7 +51,6 @@ describe("scenarios > filters > sql filters > values source", () => {FieldFilter.mapTo({ table: "Products", field: "Category" });H.setFilterQuestionSource({ question: "MBQL source", field: "Category" });H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -77,7 +76,6 @@ describe("scenarios > filters > sql filters > values source", () => {H.setDropdownFilterType();H.setFilterQuestionSource({ question: "MBQL source", field: "Category" });H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -138,7 +136,6 @@ describe("scenarios > filters > sql filters > values source", () => {checkFilterValueInList("A");H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});FieldFilter.openEntryForm();@@ -232,7 +229,6 @@ describe("scenarios > filters > sql filters > values source", () => {FieldFilter.setWidgetType("String");H.setFilterQuestionSource({ question: "SQL source", field: "EAN" });H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -317,7 +313,6 @@ describe("scenarios > filters > sql filters > values source", () => {FieldFilter.setWidgetType("String");H.setFilterListSource({ values: ["1018947080336", "7663515285824"] });H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -371,7 +366,6 @@ describe("scenarios > filters > sql filters > values source", () => {values: [["1018947080336", "Custom Label"], "7663515285824"],});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -430,7 +424,6 @@ describe("scenarios > filters > sql filters > values source", () => {values: ["1018947080336", "7663515285824"],});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -506,7 +499,6 @@ describe("scenarios > filters > sql filters > values source", () => {values: [["1018947080336", "Custom Label"], "7663515285824"],});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -654,7 +646,6 @@ describe("scenarios > filters > sql filters > values source > number parameter",values: [["10", "Ten"], ["20", "Twenty"], "30"],});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -719,7 +710,6 @@ describe("scenarios > filters > sql filters > values source > number parameter",values: [["10", "Ten"], ["20", "Twenty"], "30"],});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -805,7 +795,6 @@ describe("scenarios > filters > sql filters > values source > number parameter",values: [["10", "Ten"], ["20", "Twenty"], "30"],});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -875,7 +864,6 @@ describe("scenarios > filters > sql filters > values source > number parameter",});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -893,7 +881,6 @@ describe("scenarios > filters > sql filters > values source > number parameter",values: ["Foo", "Bar"],});H.saveQuestion("SQL filter", undefined, {- tab: "Browse",path: ["Our analytics"],});diff --git a/e2e/test/scenarios/native/native.cy.spec.js b/e2e/test/scenarios/native/native.cy.spec.jsindex 255edc6457e..9e13d6817e7 100644--- a/e2e/test/scenarios/native/native.cy.spec.js+++ b/e2e/test/scenarios/native/native.cy.spec.js@@ -900,10 +900,9 @@ describe("scenarios > native question > data reference sidebar", () => {H.openQuestionActions();H.popover().findByTestId("move-button").click();- H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Collections/ }).click();- cy.findByText("Bobby Tables's Personal Collection").click();- cy.button("Move").click();+ H.pickEntity({+ path: ["Bobby Tables's Personal Collection"],+ select: true,});H.startNewNativeQuestion();diff --git a/e2e/test/scenarios/native/native_subquery.cy.spec.js b/e2e/test/scenarios/native/native_subquery.cy.spec.jsindex baba2d45fc6..9a9403ebc93 100644--- a/e2e/test/scenarios/native/native_subquery.cy.spec.js+++ b/e2e/test/scenarios/native/native_subquery.cy.spec.js@@ -69,8 +69,7 @@ describe("scenarios > question > native subquery", () => {H.openQuestionActions();cy.findByTestId("move-button").click();H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Collections/ }).click();- cy.findByText("Bobby Tables's Personal Collection").click();+ cy.findByText(/Our analytics/).click();cy.button("Move").click();});@@ -90,7 +89,7 @@ describe("scenarios > question > native subquery", () => {H.NativeEditor.completions().within(() => {H.NativeEditor.completion(`${questionId2}-a-`).should("be.visible")- .should("contain", "Model in Bobby Tables's Personal Collection");+ .should("contain", "Model in Our analytics");H.NativeEditor.completion(`${questionId1}-a-`).should("be.visible").should("contain", "Question in Our analytics");diff --git a/e2e/test/scenarios/native/snippet-tags.cy.spec.ts b/e2e/test/scenarios/native/snippet-tags.cy.spec.tsindex ba8f85b105d..e0faa7e6e90 100644--- a/e2e/test/scenarios/native/snippet-tags.cy.spec.ts+++ b/e2e/test/scenarios/native/snippet-tags.cy.spec.ts@@ -305,7 +305,6 @@ describe("scenarios > native > snippet tags", () => {);H.NativeEditor.clear().type("select 1");H.saveQuestion("SQL", undefined, {- tab: "Browse",path: ["Our analytics"],});H.NativeEditor.clear().type("select {{snippet: snippet1}}");diff --git a/e2e/test/scenarios/native/snippets.cy.spec.js b/e2e/test/scenarios/native/snippets.cy.spec.jsindex 2599f88402e..c4403e26327 100644--- a/e2e/test/scenarios/native/snippets.cy.spec.js+++ b/e2e/test/scenarios/native/snippets.cy.spec.js@@ -313,7 +313,7 @@ describe("scenarios > question > snippets (EE)", () => {H.modal().findByTestId("collection-picker-button").click();H.entityPickerModal()- .findByRole("button", { name: /New collection/ })+ .findByRole("button", { name: /New folder/ }).click();H.collectionOnTheGoModal().findByLabelText("Give it a name")diff --git a/e2e/test/scenarios/onboarding/home/homepage.cy.spec.js b/e2e/test/scenarios/onboarding/home/homepage.cy.spec.jsindex b10e5e2ed9a..6c00b6dd20d 100644--- a/e2e/test/scenarios/onboarding/home/homepage.cy.spec.js+++ b/e2e/test/scenarios/onboarding/home/homepage.cy.spec.js@@ -435,7 +435,6 @@ describe("scenarios > home > custom homepage", () => {});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();//Ensure that personal collections have been removedcy.findByText("First collection").should("exist");cy.findByText(/personal collection/).should("not.exist");diff --git a/e2e/test/scenarios/onboarding/setup/user_settings.cy.spec.js b/e2e/test/scenarios/onboarding/setup/user_settings.cy.spec.jsindex aaa521638fa..274302c2a48 100644--- a/e2e/test/scenarios/onboarding/setup/user_settings.cy.spec.js+++ b/e2e/test/scenarios/onboarding/setup/user_settings.cy.spec.js@@ -165,7 +165,7 @@ describe("user > settings", () => {// should be redirected to new question pagecy.wait("@getUser");H.miniPicker().findByText("Parcourir tout").click();- H.entityPickerModal().findByText("Orders Model").click();+ H.pickEntity({ path: ["Nos analyses", "Orders Model"] });cy.findByTestId("step-summarize-0-0").findByText("Summarize").should("not.exist");diff --git a/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts b/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.tsindex 2aa626b2282..426ad7518ae 100644--- a/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts+++ b/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts@@ -51,7 +51,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText(TENANT_ROOT_NAME).should("be.visible");});});@@ -65,7 +64,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText(TENANT_ROOT_NAME).should("not.exist");});});@@ -77,7 +75,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText(TENANT_ROOT_NAME).click();cy.findByText("Test Tenant Collection").should("be.visible");@@ -101,7 +98,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection na});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.findByText(TENANT_ROOT_NAME).click();cy.button("Select").should("not.be.disabled");@@ -124,7 +120,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.findByText(TENANT_ROOT_NAME).should("not.exist");// Close the modal@@ -156,7 +151,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection na});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.findByText(TENANT_ROOT_NAME).click();cy.button("Select").should("be.disabled");@@ -175,7 +169,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection na});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.findByText(TENANT_ROOT_NAME).click();cy.findByText("Test Tenant Collection").click();@@ -204,7 +197,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();cy.findByText(TENANT_ROOT_NAME).click();cy.button("Move").should("be.disabled");@@ -224,6 +216,7 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {H.entityPickerModalItem(0, "Databases").click();+ H.entityPickerModalItem(1, "Sample Database").click();cy.findByText("Orders").click();});@@ -235,7 +228,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection na});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText(TENANT_ROOT_NAME).click();cy.button("Select this collection").should("be.disabled");@@ -249,6 +241,7 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {H.entityPickerModalItem(0, "Databases").click();+ H.entityPickerModalItem(1, "Sample Database").click();cy.findByText("Orders").click();});@@ -260,7 +253,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection na});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText(TENANT_ROOT_NAME).click();cy.findByText("Test Tenant Collection").click();@@ -289,7 +281,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText(TENANT_ROOT_NAME).click();cy.button("Move").should("be.disabled");@@ -352,7 +343,6 @@ describe("scenarios > organization > entity picker > shared-tenant-collection naH.popover().findByText("Add to dashboard").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();cy.findByText(TENANT_ROOT_NAME).click();cy.button(/New dashboard/).should("be.disabled");});diff --git a/e2e/test/scenarios/organization/entity-picker.cy.spec.ts b/e2e/test/scenarios/organization/entity-picker.cy.spec.tsindex 8e92021e96e..f3eb408b2d6 100644--- a/e2e/test/scenarios/organization/entity-picker.cy.spec.ts+++ b/e2e/test/scenarios/organization/entity-picker.cy.spec.ts@@ -43,12 +43,11 @@ describe("scenarios > organization > entity picker", () => {H.entityPickerModalItem(0, "Databases").click();enterSearchText({text: "prod",- placeholder: "Search this database or everywhere…",+ placeholder: "Search…",});- localSearchTab("Sample Database").should("be.checked");+ localSearchTab("Databases").should("be.checked");assertSearchResults({foundItems: ["Products"],- totalFoundItemsCount: 1,});cy.findByText("Products").click();});@@ -62,7 +61,7 @@ describe("scenarios > organization > entity picker", () => {H.entityPickerModalItem(0, "Databases").click();enterSearchText({text: "prod",- placeholder: "Search this database or everywhere…",+ placeholder: "Search…",});selectGlobalSearchTab();assertSearchResults({@@ -74,90 +73,6 @@ describe("scenarios > organization > entity picker", () => {H.getNotebookStep("data").findByText("Products").should("be.visible");});- it("should switch between recents and table tabs", () => {- cy.signInAsAdmin();- H.startNewQuestion();-- cy.log("create a recent item");- H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalItem(0, "Databases").click();- cy.findByText("Products").click();- });-- cy.log(- "should search globally for recents and locally for tables by default",- );- H.getNotebookStep("data").findByText("Products").click();- H.miniPickerHeader().click();- H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- cy.log("local -> global transition without changing search text");- H.entityPickerModalTab("Data").click();- enterSearchText({- text: "Orders",- placeholder: "Search this database or everywhere…",- });- localSearchTab("Sample Database").should("be.checked");- H.entityPickerModalTab("Recents").click();- existingSearchTab().click();- globalSearchTab().should("not.exist");- localSearchTab("Sample Database").should("not.exist");- assertSearchResults({- foundItems: ["Orders, Count", "Orders Model"],- });-- cy.log("global -> local transition without changing search text");- H.entityPickerModalTab("Data").click();- existingSearchTab().click();- localSearchTab("Sample Database").should("be.checked");- assertSearchResults({- foundItems: ["Orders"],- totalFoundItemsCount: 1,- });-- cy.log("local -> global transition with changing search text");- H.entityPickerModalTab("Recents").click();- enterSearchText({- text: "people",- placeholder: "Search…",- });- globalSearchTab().should("not.exist");- localSearchTab("Sample Database").should("not.exist");- assertSearchResults({- foundItems: ["People"],- });-- cy.log("return to the previous tab when the search input is cleared");- cy.findByPlaceholderText("Search…").clear();- H.entityPickerModalTab("Recents").should(- "have.attr",- "aria-selected",- "true",- );- });- });-- it("should search for tables in the only database", () => {- H.startNewQuestion();- H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalItem(0, "Databases").click();- enterSearchText({- text: "prod",- placeholder: "Search this database or everywhere…",- });- localSearchTab("Sample Database").should("be.checked");- assertSearchResults({- foundItems: ["Products"],- notFoundItems: ["Orders"],- totalFoundItemsCount: 1,- });- cy.findByText("Products").click();- });- H.getNotebookStep("data").findByText("Products").should("be.visible");- });-it("should search by table display names and not real names", () => {cy.signInAsAdmin();cy.request("PUT", `/api/table/${ORDERS_ID}`, {@@ -172,23 +87,21 @@ describe("scenarios > organization > entity picker", () => {H.entityPickerModalItem(0, "Databases").click();enterSearchText({text: "Orders",- placeholder: "Search this database or everywhere…",+ placeholder: "Search…",});- localSearchTab("Sample Database").should("be.checked");+ localSearchTab("Databases").should("be.checked");assertSearchResults({notFoundItems: ["Orders"],- totalFoundItemsCount: 0,});- cy.findByText("Didn't find anything").should("be.visible");});cy.log("display table name should be used to search for a table");H.entityPickerModal().within(() => {enterSearchText({text: "Events",- placeholder: "Search this database or everywhere…",+ placeholder: "Search…",});- localSearchTab("Sample Database").should("be.checked");+ localSearchTab("Databases").should("be.checked");assertSearchResults({foundItems: ["Events"],notFoundItems: ["Orders"],@@ -208,53 +121,31 @@ describe("scenarios > organization > entity picker", () => {cy.signInAsAdmin();H.resyncDatabase({ dbId: WRITABLE_DB_ID });- cy.log("first database - pre-selected");+ cy.log("first database");H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {H.entityPickerModalItem(0, "Databases").click();enterSearchText({text: "prod",- placeholder: "Search this database or everywhere…",+ placeholder: "Search…",});- localSearchTab("Sample Database").should("be.checked");+ localSearchTab("Databases").should("be.checked");assertSearchResults({foundItems: ["Products"],- notFoundItems: ["Orders"],- totalFoundItemsCount: 1,});});cy.log("second database");H.entityPickerModal().within(() => {- H.entityPickerModalTab("Data").click();- cy.findByText("Writable Postgres12").click();+ H.entityPickerModalItem(0, "Databases").click();enterSearchText({text: "s",- placeholder: "Search this schema or everywhere…",+ placeholder: "Search…",});- localSearchTab("Domestic").should("be.checked");+ localSearchTab("Databases").should("be.checked");assertSearchResults({- foundItems: ["Animals"],- notFoundItems: ["Birds"],- totalFoundItemsCount: 1,- });- });-- cy.log("first database - manually selected");- H.startNewQuestion();- H.entityPickerModal().within(() => {- H.entityPickerModalTab("Data").click();- cy.findByText("Sample Database").click();- enterSearchText({- text: "prod",- placeholder: "Search this database or everywhere…",- });- localSearchTab("Sample Database").should("be.checked");- assertSearchResults({- foundItems: ["Products"],- notFoundItems: ["Orders"],- totalFoundItemsCount: 1,+ foundItems: ["Birds"],});});},@@ -269,38 +160,20 @@ describe("scenarios > organization > entity picker", () => {cy.signInAsAdmin();H.resyncDatabase({ dbId: WRITABLE_DB_ID });- cy.log("first schema");H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {H.entityPickerModalItem(0, "Databases").click();cy.findByText("Writable Postgres12").click();enterSearchText({- text: "s",- placeholder: "Search this schema or everywhere…",- });- localSearchTab("Domestic").should("be.checked");- assertSearchResults({- foundItems: ["Animals"],- notFoundItems: ["Birds"],- totalFoundItemsCount: 1,- });- });-- cy.log("second schema");- H.entityPickerModal().within(() => {- H.entityPickerModalTab("Data").click();- cy.findByText("Writable Postgres12").click();- cy.findByText("Wild").click();- enterSearchText({- text: "s",- placeholder: "Search this schema or everywhere…",- });- localSearchTab("Wild").should("be.checked");- assertSearchResults({- foundItems: ["Animals", "Birds"],- totalFoundItemsCount: 2,+ text: "anim",+ placeholder: "Search…",});+ localSearchTab("Databases").should("be.checked");+ cy.findByRole("link", { name: /animals.*wild/i }).should("exist");+ cy.findByRole("link", { name: /animals.*domestic/i }).should(+ "exist",+ );});},);@@ -318,22 +191,18 @@ describe("scenarios > organization > entity picker", () => {cy.findByText("QA MySQL8").click();enterSearchText({text: "orders",- placeholder: "Search this database or everywhere…",- });- localSearchTab("QA MySQL8").should("be.checked");- assertSearchResults({- foundItems: ["Orders"],- notFoundItems: ["Products"],- totalFoundItemsCount: 1,+ placeholder: "Search…",});+ localSearchTab("Databases").should("be.checked");+ cy.findByRole("link", { name: /orders.*QA MySQL8/i }).should(+ "exist",+ );});},);});describe("cards", () => {- const tabs = ["Data"];-it("should select a card from local search results", () => {cy.signInAsAdmin();createTestCards();@@ -357,6 +226,7 @@ describe("scenarios > organization > entity picker", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {+ H.entityPickerModalItem(0, "Our analytics").click();enterSearchText({text: cardName,placeholder: /Search/,@@ -366,23 +236,6 @@ describe("scenarios > organization > entity picker", () => {H.getNotebookStep("data").findByText(sourceName).should("be.visible");H.visualize();});-- cy.log("scope search in a dashboard");- H.startNewQuestion();- H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalTab("Data").click();- H.entityPickerModalItem(1, "Orders in a dashboard").click();- enterSearchText({- text: "Orders",- placeholder: "Search this dashboard or everywhere…",- });- cy.findByText("Orders Dashboard question 2").click();- });- H.getNotebookStep("data")- .findByText("Orders Dashboard question 2")- .should("be.visible");- H.visualize();});it("should select a card from global search results", () => {@@ -404,13 +257,10 @@ describe("scenarios > organization > entity picker", () => {sourceName: "Orders",},];- testCases.forEach(({ cardName, sourceName }, i) => {+ testCases.forEach(({ cardName, sourceName }) => {H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {- if (i > 0) {- H.entityPickerModalTab("Data").click();- }enterSearchText({text: cardName,placeholder: /Search/,@@ -426,10 +276,9 @@ describe("scenarios > organization > entity picker", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Data").click();enterSearchText({text: "Dashboard question 1",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});selectGlobalSearchTab();cy.findByText("Orders Dashboard question 1").click();@@ -446,7 +295,7 @@ describe("scenarios > organization > entity picker", () => {cy.signInAsNormalUser();H.startNewQuestion();H.miniPickerBrowseAll().click();- testCardSearchForNormalUser({ tabs });+ testCardSearchForNormalUser();});it("should search for cards when there is no access to the root collection", () => {@@ -461,10 +310,7 @@ describe("scenarios > organization > entity picker", () => {cy.signIn("nocollection");H.startNewQuestion();H.miniPickerBrowseAll().click();- testCardSearchForInaccessibleRootCollection({- tabs,- isRootSelected: true,- });+ testCardSearchForInaccessibleRootCollection();});it("should not allow local search for `all personal collections`", () => {@@ -478,25 +324,22 @@ describe("scenarios > organization > entity picker", () => {});describe("question picker", () => {- const tabs = ["Questions", "Models", "Metrics"];-it("should select a card from local search results", () => {cy.signInAsAdmin();createTestCards();cy.signInAsNormalUser();const testCases = [- { tab: "Questions", cardName: "Root question 1" },- { tab: "Models", cardName: "Root model 2" },- { tab: "Metrics", cardName: "Root metric 1" },+ { cardName: "Root question 1" },+ { cardName: "Root model 2" },+ { cardName: "Root metric 1" },];- testCases.forEach(({ tab, cardName }) => {+ testCases.forEach(({ cardName }) => {selectQuestionFromDashboard();H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();enterSearchText({text: cardName,- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});cy.findByText(cardName).click();});@@ -510,17 +353,16 @@ describe("scenarios > organization > entity picker", () => {cy.signInAsNormalUser();const testCases = [- { tab: "Questions", cardName: "Regular question 1" },- { tab: "Models", cardName: "Regular model 2" },- { tab: "Metrics", cardName: "Regular metric 1" },+ { cardName: "Regular question 1" },+ { cardName: "Regular model 2" },+ { cardName: "Regular metric 1" },];- testCases.forEach(({ tab, cardName }) => {+ testCases.forEach(({ cardName }) => {selectQuestionFromDashboard();H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();enterSearchText({text: cardName,- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});selectGlobalSearchTab();cy.findByText(cardName).click();@@ -534,7 +376,7 @@ describe("scenarios > organization > entity picker", () => {createTestCards();cy.signInAsNormalUser();selectQuestionFromDashboard();- testCardSearchForNormalUser({ tabs });+ testCardSearchForNormalUser();});it("should search for cards when there is no access to the root collection", () => {@@ -548,10 +390,7 @@ describe("scenarios > organization > entity picker", () => {cy.signIn("nocollection");selectQuestionFromDashboard({ collection_id: FIRST_COLLECTION_ID });- testCardSearchForInaccessibleRootCollection({- tabs,- isRootSelected: false,- });+ testCardSearchForInaccessibleRootCollection();});it("should not allow local search for `all personal collections`", () => {@@ -569,15 +408,16 @@ describe("scenarios > organization > entity picker", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {+ H.pickEntity({ path: ["Our analytics", "First collection"] });enterSearchText({- text: "first",- placeholder: "Search this collection or everywhere…",+ text: "second",+ placeholder: "Search…",});- localSearchTab("Our analytics").should("be.checked");- cy.findByText("First collection").click();+ localSearchTab("First collection").should("be.checked");+ cy.findByText("Second collection").click();cy.button("Move").click();});- H.undoToast().findByText("First collection").should("be.visible");+ H.undoToast().findByText("Second collection").should("be.visible");});it("should select a collection from global search results", () => {@@ -586,9 +426,10 @@ describe("scenarios > organization > entity picker", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {+ H.pickEntity({ path: ["Our analytics", "First collection"] });enterSearchText({text: "second",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});selectGlobalSearchTab();cy.findByText("Second collection").click();@@ -605,54 +446,36 @@ describe("scenarios > organization > entity picker", () => {H.openQuestionActions();H.popover().findByText("Move").click();- cy.log("root collection - automatically selected");H.entityPickerModal().within(() => {+ cy.findByText("First collection").click();enterSearchText({text: "collection",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("Our analytics").should("be.checked");+ localSearchTab("First collection").should("be.checked");assertSearchResults({- foundItems: ["First collection"],- notFoundItems: ["Second collection"],+ foundItems: ["Second collection"],+ // notFoundItems: ["First collection"],});selectGlobalSearchTab();assertSearchResults({foundItems: ["First collection", "Second collection"],});- selectLocalSearchTab("Our analytics");- assertSearchResults({- foundItems: ["First collection"],- notFoundItems: ["Second collection"],- });- });-- cy.log("regular collection");- H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();- cy.findByText("First collection").click();- enterSearchText({- text: "collection",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("First collection").should("be.checked");+ selectLocalSearchTab("First collection");assertSearchResults({foundItems: ["Second collection"],- notFoundItems: ["First collection", "Third collection"],+ // notFoundItems: ["First collection"],});});cy.log("personal collection");H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText(/Personal Collection/).click();enterSearchText({text: "personal collection 1",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("Robert Tableton's Personal Collection").should(- "be.checked",- );+ localSearchTab(/robert tableton/i).should("be.checked");assertSearchResults({foundItems: ["Normal personal collection 1"],notFoundItems: [@@ -693,37 +516,23 @@ describe("scenarios > organization > entity picker", () => {cy.findByText("Collections").click();enterSearchText({text: "collection",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("Collections").should("be.checked");+ globalSearchTab().should("be.checked");assertSearchResults({foundItems: ["Another collection"],- notFoundItems: [- "No Collection Tableton's Personal Collection",- "First Collection",- ],- });- selectGlobalSearchTab();- assertSearchResults({- foundItems: [- "Another collection",- "No Collection Tableton's Personal Collection",- ],notFoundItems: ["First Collection"],});});cy.log("personal collection");H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();- cy.findByText(/Personal Collection/).click();+ H.entityPickerModalItem(0, /Personal Collection/).click();enterSearchText({text: "personal collection 2",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("No Collection Tableton's Personal Collection").should(- "be.checked",- );+ localSearchTab(/no collection/i).should("be.checked");assertSearchResults({foundItems: ["No collection personal collection 2"],notFoundItems: [@@ -743,7 +552,6 @@ describe("scenarios > organization > entity picker", () => {H.popover().findByText("Move").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();cy.findByText("All personal collections").click();enterSearchText({text: "personal collection",@@ -773,7 +581,6 @@ describe("scenarios > organization > entity picker", () => {});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();H.entityPickerModalItem(0, "All personal collections").click();H.entityPickerModalItem(1,@@ -791,7 +598,6 @@ describe("scenarios > organization > entity picker", () => {});H.entityPickerModal().within(() => {- H.entityPickerModalTab("Collections").click();H.entityPickerModalItem(0, "All personal collections").should("have.attr","data-active",@@ -823,7 +629,6 @@ describe("scenarios > organization > entity picker", () => {.should("contain.text", "Orders in a dashboard").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Browse").click();H.entityPickerModalItem(0, "Bobby Tables's Personal Collection").should("be.visible",);@@ -846,21 +651,24 @@ describe("scenarios > organization > entity picker", () => {describe("dashboard picker", () => {it("should select a dashboard from local search results", () => {+ cy.signInAsAdmin();+ createTestDashboards();+ cy.signInAsNormalUser();+H.visitQuestion(ORDERS_COUNT_QUESTION_ID);H.openQuestionActions();H.popover().findByText("Add to dashboard").click();-H.entityPickerModal().within(() => {- cy.findByText("Our analytics").click();+ H.pickEntity({ path: ["Our analytics", "First collection"] });enterSearchText({text: "dashboard",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("Our analytics").should("be.checked");- cy.findByText("Orders in a dashboard").click();+ localSearchTab("First collection").should("be.checked");+ cy.findByText("Regular dashboard 1").click();cy.button("Select").click();});- H.getDashboardCard(1).findByText("Orders, Count").should("be.visible");+ H.getDashboardCard(0).findByText("Orders, Count").should("be.visible");});it("should select a dashboard from global search results", () => {@@ -872,7 +680,7 @@ describe("scenarios > organization > entity picker", () => {cy.findByText("Our analytics").click();enterSearchText({text: "dashboard",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});selectGlobalSearchTab();cy.findByText("Orders in a dashboard").click();@@ -889,63 +697,40 @@ describe("scenarios > organization > entity picker", () => {H.openQuestionActions();H.popover().findByText("Add to dashboard").click();- cy.log("root collection - automatically selected");H.entityPickerModal().within(() => {- cy.findByText("Our analytics").click();+ cy.findByText("First collection").click();enterSearchText({text: "dashboard 1",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("Our analytics").should("be.checked");+ localSearchTab("First collection").should("be.checked");assertSearchResults({- foundItems: ["Root dashboard 1"],- notFoundItems: ["Root dashboard 2", "Regular dashboard 1"],+ foundItems: ["Regular dashboard 1"],+ notFoundItems: ["Regular dashboard 2", "Root dashboard 1"],});selectGlobalSearchTab();assertSearchResults({foundItems: ["Root dashboard 1", "Regular dashboard 1"],});- selectLocalSearchTab("Our analytics");+ selectLocalSearchTab("First collection");assertSearchResults({- foundItems: ["Root dashboard 1"],+ foundItems: ["Regular dashboard 1"],notFoundItems: [- "Root dashboard 2",- "Regular dashboard 1",+ "Regular dashboard 2",+ "Root dashboard 1","Personal dashboard 1",],});});- cy.log("regular collection");- H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();- cy.findByText("First collection").click();- enterSearchText({- text: "dashboard 2",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("First collection").should("be.checked");- assertSearchResults({- foundItems: ["Regular dashboard 2"],- notFoundItems: [- "Regular dashboard 1",- "Root dashboard 2",- "Personal dashboard 2",- ],- });- });-cy.log("personal collection");H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();cy.findByText(/Personal Collection/).click();enterSearchText({text: "personal dashboard 1",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("Robert Tableton's Personal Collection").should(- "be.checked",- );+ localSearchTab(/robert tableton/i).should("be.checked");assertSearchResults({foundItems: ["Normal personal dashboard 1"],notFoundItems: [@@ -979,38 +764,23 @@ describe("scenarios > organization > entity picker", () => {cy.findByText("Collections").click();enterSearchText({text: "dashboard 1",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("Collections").should("be.checked");- assertSearchResults({- notFoundItems: [- "Regular dashboard 1",- "Regular dashboard 2",- "Root dashboard 1",- "No collection personal dashboard 1",- ],+ placeholder: "Search…",});- cy.findByText("Didn't find anything").should("be.visible");- selectGlobalSearchTab();+ globalSearchTab().should("be.checked");assertSearchResults({- foundItems: [- "Regular dashboard 1",- "No collection personal dashboard 1",- ],+ foundItems: ["Regular dashboard 1"],+ notFoundItems: ["Regular dashboard 2", "Root dashboard 1"],});});cy.log("personal collection");H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();- cy.findByText(/Personal Collection/).click();+ H.entityPickerModalItem(0, /Personal Collection/).click();enterSearchText({text: "personal dashboard 2",- placeholder: "Search this collection or everywhere…",+ placeholder: "Search…",});- localSearchTab("No Collection Tableton's Personal Collection").should(- "be.checked",- );+ localSearchTab(/no collection/i).should("be.checked");assertSearchResults({foundItems: ["No collection personal dashboard 2"],notFoundItems: [@@ -1031,7 +801,6 @@ describe("scenarios > organization > entity picker", () => {H.popover().findByText("Add to dashboard").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();cy.findByText("All personal collections").click();enterSearchText({text: "personal dashboard",@@ -1066,7 +835,6 @@ describe("scenarios > organization > entity picker", () => {.findByLabelText(/Collection it's saved in/).click();- H.entityPickerModalTab("Collections").click();H.entityPickerModal().button(/New collection/).click();@@ -1083,7 +851,6 @@ describe("scenarios > organization > entity picker", () => {.findByLabelText(/Which collection/).click();- H.entityPickerModalTab("Collections").click();H.entityPickerModal().button(/New collection/).click();@@ -1097,20 +864,13 @@ describe("scenarios > organization > entity picker", () => {H.newButton("Question").click();H.miniPickerBrowseAll().click();- H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalLevel(3).findByText("People").click();+ H.pickEntity({ path: ["Databases", "Sample Database", "People"] });H.queryBuilderHeader().findByRole("button", { name: "Save" }).click();H.modal().findByLabelText(/Where do you/).click();- H.entityPickerModalTab("Browse").click();-- H.entityPickerModal()- .button(/New dashboard/)- .click();- closeAndAssertModal(H.dashboardOnTheGoModal);H.entityPickerModal().button(/New collection/).click();@@ -1125,7 +885,6 @@ describe("scenarios > organization > entity picker", () => {H.visitQuestion(ORDERS_QUESTION_ID);H.openQuestionActions("Add to dashboard");- H.entityPickerModalTab("Dashboards").click();H.entityPickerModal().button(/New dashboard/)@@ -1138,7 +897,6 @@ describe("scenarios > organization > entity picker", () => {H.modal().findByLabelText(/Where do you/).click();- H.entityPickerModalTab("Browse").click();// wait for data to avoid flakinessH.entityPickerModalLevel(1).should("contain", "First collection");@@ -1158,7 +916,6 @@ describe("scenarios > organization > entity picker", () => {cy.findByTestId("new-collection-modal").findByLabelText(/Collection it's saved in/).click();- H.entityPickerModalTab("Collections").click();//Initial width of entity pickercy.findByRole("dialog", { name: "Select a collection" })@@ -1185,6 +942,48 @@ describe("scenarios > organization > entity picker", () => {.should("have.css", "width").and("eq", "1198px");});++ it("should restore previous path when clearing search from search results", () => {+ cy.visit("/");+ H.startNewQuestion();+ H.miniPickerBrowseAll().click();+ H.entityPickerModal().within(() => {+ H.pickEntity({ path: ["Databases", "Sample Database"] });+ enterSearchText({+ text: "1",+ placeholder: "Search…",+ });+ cy.findByText(/Search results for/i).should("be.visible");+ cy.findByTestId("clear-search").click();+ H.entityPickerModalItem(1, "Sample Database").should(+ "have.attr",+ "data-active",+ "true",+ );+ });+ });++ it("should not restore previous path when clearing search outside of search results", () => {+ cy.visit("/");+ H.startNewQuestion();+ H.miniPickerBrowseAll().click();+ H.entityPickerModal().within(() => {+ H.pickEntity({ path: ["Databases", "Sample Database"] });+ enterSearchText({+ text: "1",+ placeholder: "Search…",+ });+ cy.findByText(/Search results for/i).should("be.visible");+ //after clicking on Our Analytics, I shouldn't be returned to Sample Database after clearing search+ H.pickEntity({ path: ["Our analytics"] });+ cy.findByTestId("clear-search").click();+ H.entityPickerModalItem(0, "Our analytics").should(+ "have.attr",+ "data-active",+ "true",+ );+ });+ });});});@@ -1340,10 +1139,6 @@ function enterSearchText({cy.findByPlaceholderText(placeholder).clear().type(text);}-function existingSearchTab() {- return cy.findByText(/results? for/);-}-function globalSearchTab() {return cy.findByLabelText("Everywhere");}@@ -1352,12 +1147,22 @@ function selectGlobalSearchTab() {cy.findByText("Everywhere").click();}-function localSearchTab(selectedItem: string) {- return cy.findByLabelText(`“${selectedItem}”`);+function localSearchTab(selectedItem: string | RegExp) {+ return cy.findByLabelText(selectedItem);}function selectLocalSearchTab(selectedItem: string) {- cy.findByText(`“${selectedItem}”`).click();+ cy.findByTestId("search-scope-selector").findByText(selectedItem).click();+}++function findSearchItem(item: string) {+ //entityPickerModalItem can also match the search tab, so we need to scope down to the scroll container+ return (+ H.entityPickerModalLevel(1)+ .findByTestId("scroll-container")+ // see the comment in entityPickerModalItem+ .findByText(item, { ignore: '[data-testid="picker-item-location"]' })+ );}function assertSearchResults({@@ -1370,217 +1175,141 @@ function assertSearchResults({totalFoundItemsCount?: number;}) {foundItems.forEach((item) => {- cy.findByText(item).should("exist");+ findSearchItem(item).should("exist");});notFoundItems.forEach((item) => {- cy.findByText(item).should("not.exist");+ findSearchItem(item).should("not.exist");});if (totalFoundItemsCount != null) {- const foundItemsCountMessage =- totalFoundItemsCount === 1- ? `${totalFoundItemsCount} result`- : `${totalFoundItemsCount} results`;- cy.findByTestId("entity-picker-search-result-count").should(- "have.text",- foundItemsCountMessage,+ cy.findAllByTestId("result-item").should(+ "have.length",+ totalFoundItemsCount,);}}-function testCardSearchForNormalUser({ tabs }: { tabs: string[] }) {- tabs.forEach((tab) => {- cy.log("root collection - automatically selected");- H.entityPickerModal().within(() => {- if (tabs.length > 1) {- H.entityPickerModalTab(tab).click();- }- enterSearchText({- text: "2",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("Our analytics").should("be.checked");- assertSearchResults({- foundItems: ["Root question 2", "Root model 2", "Root metric 2"],- notFoundItems: [- "Root question 1",- "Regular question 2",- "Admin personal collection question 2",- "Normal personal collection question 2",- ],- });+function testCardSearchForNormalUser() {+ cy.log("root collection");+ H.entityPickerModal().within(() => {+ H.pickEntity({ path: ["Our analytics"] });+ enterSearchText({+ text: "2",+ placeholder: "Search…",});-- cy.log("regular collection");- H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();- cy.findByText("First collection").click();- enterSearchText({- text: "1",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("First collection").should("be.checked");- assertSearchResults({- foundItems: [- "Regular question 1",- "Regular model 1",- "Regular metric 1",- ],- notFoundItems: [- "Root question 1",- "Regular question 2",- "Admin personal collection question 1",- "Normal personal collection question 1",- ],- });+ localSearchTab("Everywhere").should("be.checked");+ assertSearchResults({+ foundItems: ["Root question 2", "Root model 2", "Root metric 2"],+ notFoundItems: [+ "Root question 1",+ "Admin personal collection question 2",+ ],});+ });- cy.log("root collection - manually selected");- H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();- cy.findByText("Our analytics").click();- enterSearchText({- text: "2",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("Our analytics").should("be.checked");- assertSearchResults({- foundItems: ["Root question 2", "Root model 2", "Root metric 2"],- notFoundItems: [- "Root model 1",- "Regular model 2",- "Admin personal collection model 2",- "Normal personal collection model 2",- ],- });+ cy.log("regular collection");+ H.entityPickerModal().within(() => {+ H.pickEntity({ path: ["Our analytics", "First collection"] });+ enterSearchText({+ text: "1",+ placeholder: "Search…",+ });+ localSearchTab("First collection").should("be.checked");+ assertSearchResults({+ foundItems: ["Regular question 1", "Regular model 1", "Regular metric 1"],+ notFoundItems: [+ "Root question 1",+ "Regular question 2",+ "Admin personal collection question 1",+ "Normal personal collection question 1",+ ],});+ });- cy.log("personal collection");- H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();- cy.findByText(/Personal Collection/).click();- enterSearchText({- text: "1",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("Robert Tableton's Personal Collection").should(- "be.checked",- );- assertSearchResults({- foundItems: [- "Normal personal collection question 1",- "Normal personal collection model 1",- "Normal personal collection metric 1",- ],- notFoundItems: [- "Root metric 1",- "Regular metric 1",- "Admin personal collection metric 1",- "Normal personal collection metric 2",- ],- });+ cy.log("personal collection");+ H.entityPickerModal().within(() => {+ cy.findByText(/Personal Collection/).click();+ enterSearchText({+ text: "2",+ placeholder: "Search…",+ });+ localSearchTab(/robert tableton/i).should("be.checked");+ assertSearchResults({+ foundItems: [+ "Normal personal collection question 2",+ "Normal personal collection model 2",+ "Normal personal collection metric 2",+ ],+ notFoundItems: [+ "Root metric 2",+ "Regular metric 2",+ "Admin personal collection metric 2",+ "Normal personal collection metric 1",+ ],});});}-function testCardSearchForInaccessibleRootCollection({- tabs,- isRootSelected,-}: {- tabs: string[];- isRootSelected: boolean;-}) {- tabs.forEach((tab) => {- if (isRootSelected) {- cy.log("inaccessible root collection - automatically selected");- H.entityPickerModal().within(() => {- enterSearchText({- text: "1",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("Collections").should("be.checked");- assertSearchResults({- notFoundItems: [- "Root metric 1",- "Regular metric 1",- "Admin personal collection metric 1",- "Normal personal collection metric 2",- ],- });- cy.findByText("Didn't find anything").should("be.visible");- });- }-- cy.log("regular collection");- H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();- cy.findByText("First collection").click();- enterSearchText({- text: "1",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("First collection").should("be.checked");- assertSearchResults({- foundItems: [- "Regular question 1",- "Regular model 1",- "Regular metric 1",- ],- notFoundItems: [- "Root question 1",- "Regular question 2",- "Admin personal collection question 1",- "Normal personal collection question 1",- "No collection personal collection question 1",- ],- });+function testCardSearchForInaccessibleRootCollection() {+ cy.log("regular collection");+ H.entityPickerModal().within(() => {+ H.pickEntity({ path: ["Collections", "First collection"] });+ enterSearchText({+ text: "1",+ placeholder: "Search…",+ });+ localSearchTab("First collection").should("be.checked");+ assertSearchResults({+ foundItems: ["Regular question 1", "Regular model 1", "Regular metric 1"],+ notFoundItems: [+ "Root question 1",+ "Regular question 2",+ "Admin personal collection question 1",+ "Normal personal collection question 1",+ "No collection personal collection question 1",+ ],});+ });- cy.log("inaccessible root collection - manually selected");- H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();- H.entityPickerModalItem(0, "Collections").click();- enterSearchText({- text: "1",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("Collections").should("be.checked");- assertSearchResults({- notFoundItems: [- "Root metric 1",- "Regular metric 1",- "Admin personal collection metric 1",- "Normal personal collection metric 2",- ],- });- cy.findByText("Didn't find anything").should("be.visible");+ cy.log("inaccessible root collection");+ H.entityPickerModal().within(() => {+ H.entityPickerModalItem(0, "Collections").click();+ enterSearchText({+ text: "2",+ placeholder: "Search…",+ });+ globalSearchTab().should("be.checked");+ assertSearchResults({+ notFoundItems: [+ "Root metric 1",+ "Regular metric 1",+ "Admin personal collection metric 1",+ "Normal personal collection metric 2",+ ],});+ });- cy.log("personal collection");- H.entityPickerModal().within(() => {- H.entityPickerModalTab(tab).click();- cy.findByText(/Personal Collection/).click();- enterSearchText({- text: "1",- placeholder: "Search this collection or everywhere…",- });- localSearchTab("No Collection Tableton's Personal Collection").should(- "be.checked",- );- assertSearchResults({- foundItems: [- "No collection personal collection question 1",- "No collection personal collection model 1",- "No collection personal collection metric 1",- ],- notFoundItems: [- "Root metric 1",- "Regular metric 1",- "Admin personal collection metric 1",- "Normal personal collection metric 2",- ],- });+ cy.log("personal collection");+ H.entityPickerModal().within(() => {+ H.entityPickerModalItem(0, /Personal Collection/).click();+ enterSearchText({+ text: "1",+ placeholder: "Search…",+ });+ localSearchTab(/no collection/i).should("be.checked");+ assertSearchResults({+ foundItems: [+ "No collection personal collection question 1",+ "No collection personal collection model 1",+ "No collection personal collection metric 1",+ ],+ notFoundItems: [+ "Root metric 1",+ "Regular metric 1",+ "Admin personal collection metric 1",+ "Normal personal collection metric 2",+ ],});});}diff --git a/e2e/test/scenarios/organization/timelines-collection.cy.spec.js b/e2e/test/scenarios/organization/timelines-collection.cy.spec.jsindex c6a17af378d..0da0f5a0dfd 100644--- a/e2e/test/scenarios/organization/timelines-collection.cy.spec.js+++ b/e2e/test/scenarios/organization/timelines-collection.cy.spec.js@@ -385,7 +385,6 @@ describe("scenarios > organization > timelines > collection", () => {H.popover().findByText("Move timeline").click();H.entityPickerModal().within(() => {- cy.findByRole("tab", { name: /Collections/ }).click();cy.findByText("Bobby Tables's Personal Collection").click();cy.button("Move").click();cy.wait("@updateTimeline");diff --git a/e2e/test/scenarios/permissions/impersonated.cy.spec.js b/e2e/test/scenarios/permissions/impersonated.cy.spec.jsindex ab1341d24fc..2b8c15b11f0 100644--- a/e2e/test/scenarios/permissions/impersonated.cy.spec.js+++ b/e2e/test/scenarios/permissions/impersonated.cy.spec.js@@ -109,7 +109,6 @@ describe("impersonated permission", { tags: "@external" }, () => {H.saveQuestion("foo", undefined, {path: ["Our analytics", "First collection"],select: true,- tab: "Browse",});cy.log("configure caching");diff --git a/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.ts b/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.tsindex 923c025b921..030e89399a9 100644--- a/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.ts+++ b/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.ts@@ -338,8 +338,7 @@ export const configureSandboxPolicy = (policy: SandboxPolicy,{ databaseId = 1, tableName = "Products" } = {},) => {- const { filterTableBy, customViewName, customViewType, filterColumn } =- policy;+ const { filterTableBy, customViewName, filterColumn } = policy;cy.log(`Configure sandboxing policy: ${JSON.stringify(policy)}`);cy.log(@@ -368,14 +367,25 @@ export const configureSandboxPolicy = (name: /Filter by a column in the table/,}).should("be.checked");} else if (customViewName) {+ // activity/recents invalidates the card cache, causing the component to refetch and show the loading spinner+ // which makes this test flaky. so we'll return an error to prevent the invalidation+ cy.intercept("POST", "/api/activity/recents", {+ statusCode: 500,+ body: { message: "Stubbed to prevent flaky test" },+ }).as("activityRecents");+ cy.intercept("GET", "/api/collection/*/items*").as("getCollectionItems");+cy.findByText(/Use a saved question to create a custom view for this table/,).click();cy.findByTestId("custom-view-picker-button").click();++ cy.wait(["@getCollectionItems", "@getCollectionItems"]);H.entityPickerModal().within(() => {- H.entityPickerModalTab(customViewType).click();- cy.findByText(/Sandboxing/).click(); // collection name- cy.findByText(customViewName).click();+ cy.findByText(/Our analytics/).click();+ cy.findByText(/Sandboxing/).click();+ cy.contains(customViewName).click();+ cy.findByText("Select").click();});}diff --git a/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.js b/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.jsindex 76acc430d1c..80aa940dfa9 100644--- a/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.js+++ b/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-api.cy.spec.js@@ -948,7 +948,7 @@ describe("admin > permissions > sandboxes (tested via the API)", () => {H.modal().findByText("Select a question").click();- H.entityPickerModal().findByText(QUESTION_NAME).click();+ H.pickEntity({ path: ["Our analytics", QUESTION_NAME], select: true });H.modal().button("Save").click();cy.wait("@sandboxTable").then(({ response }) => {expect(response.statusCode).to.eq(400);diff --git a/e2e/test/scenarios/question-reproductions/reproductions-1.cy.spec.js b/e2e/test/scenarios/question-reproductions/reproductions-1.cy.spec.jsindex a6dd711a842..ea909022736 100644--- a/e2e/test/scenarios/question-reproductions/reproductions-1.cy.spec.js+++ b/e2e/test/scenarios/question-reproductions/reproductions-1.cy.spec.js@@ -142,7 +142,6 @@ describe("issue 9027", () => {cy.findByTestId("native-query-editor-container").icon("play").click();H.saveQuestion(QUESTION_NAME, undefined, {- tab: "Browse",path: ["Our analytics"],});});@@ -285,7 +284,6 @@ describe("issue 14957", { tags: "@external" }, () => {cy.findByLabelText(PG_DB_NAME).click();H.NativeEditor.type("select pg_sleep(60)");H.saveQuestion("14957", undefined, {- tab: "Browse",path: ["Our analytics"],});H.modal().should("not.exist");@@ -960,13 +958,11 @@ describe("issue 19341", () => {H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {cy.findByTestId("loading-indicator").should("not.exist");+ cy.findByText("Sample Database").click();cy.findByText("Orders").should("exist");- cy.findAllByRole("tab").should("not.exist");// Ensure the search doesn't list saved questions- cy.findByPlaceholderText("Search this database or everywhere…").type(- "Ord",- );+ cy.findByPlaceholderText("Search…").type("Ord");cy.findByTestId("loading-indicator").should("not.exist");cy.findAllByTestId("result-item").then(($result) => {@@ -979,7 +975,6 @@ describe("issue 19341", () => {expect(modelTypes).to.include("table");});- H.entityPickerModalTab("Tables").click();cy.findByText("Orders").click();});@@ -1014,6 +1009,7 @@ describe("issue 19742", () => {H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {H.entityPickerModalItem(0, "Databases").click();+ H.entityPickerModalItem(1, "Sample Database").click();cy.findByText("Orders").should("exist");cy.button("Close").click();});@@ -1034,6 +1030,7 @@ describe("issue 19742", () => {H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {H.entityPickerModalItem(0, "Databases").click();+ H.entityPickerModalItem(1, "Sample Database").click();cy.findByText("Orders").should("not.exist");cy.findByText("Products").should("exist");diff --git a/e2e/test/scenarios/question-reproductions/reproductions-3.cy.spec.js b/e2e/test/scenarios/question-reproductions/reproductions-3.cy.spec.jsindex d3dc230041a..ead06309811 100644--- a/e2e/test/scenarios/question-reproductions/reproductions-3.cy.spec.js+++ b/e2e/test/scenarios/question-reproductions/reproductions-3.cy.spec.js@@ -1535,6 +1535,7 @@ describe("issue 44974", { tags: "@external" }, () => {const PG_DB_ID = 2;beforeEach(() => {+ cy.intercept("GET", "/api/collection/*/items*").as("getCollectionItems");H.restore("postgres-12");cy.signInAsAdmin();});@@ -1562,11 +1563,16 @@ describe("issue 44974", { tags: "@external" }, () => {H.miniPickerHeader().click();H.miniPickerBrowseAll().click();+ cy.wait(["@getCollectionItems", "@getCollectionItems"]);+H.entityPickerModal().within(() => {- cy.findAllByRole("tab").should("not.exist");H.entityPickerModalItem(0, "Our analytics").click();cy.findByText("Orders Model").should("be.visible");- cy.findByText(questionDetails.name).should("not.exist");+ H.entityPickerModalItem(1, questionDetails.name).should(+ "have.attr",+ "data-disabled",+ "true",+ );cy.button("Close").click();});});@@ -2309,7 +2315,10 @@ describe("issue 48829", () => {cy.findByText("Saved question").click();});- H.entityPickerModal().findByText(questionDetails.name).click();+ H.entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();+ cy.findByText(questionDetails.name).click();+ });H.sidebar().findByTestId("click-mappings").findByText("Title").click();H.popover().findByText("Title").click();H.saveDashboard();diff --git a/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.ts b/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.tsindex fd1a5e42340..7cad21764e9 100644--- a/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.ts+++ b/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.ts@@ -964,10 +964,7 @@ describe("issue 55631", () => {cy.findByLabelText("Where do you want to save this?").click();});- H.entityPickerModal().within(() => {- cy.findByText("First collection").click();- cy.button("Select this collection").click();- });+ H.pickEntity({ path: ["Our analytics", "First collection"], select: true });H.modal().within(() => {cy.button("Save").click();@@ -1406,7 +1403,9 @@ describe("issue 13347", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();- H.entityPickerModalLevel(1).within(() => {+ H.entityPickerModalItem(1, "Sample Database").click();++ H.entityPickerModalLevel(2).within(() => {cy.findByText("Orders").should("exist");cy.findByText("13347 structured").should("not.exist");@@ -1505,11 +1504,12 @@ describe("issue 66210", () => {it("should not allow you to join on metrics", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();+ H.entityPickerModalItem(0, "Our analytics").click();H.entityPickerModalItem(1, METRIC_NAME).should("be.visible");H.entityPickerModalItem(1, "Orders").click();H.join();H.miniPickerBrowseAll().click();- H.entityPickerModalTab("Data").click();+ H.entityPickerModalItem(0, "Our analytics").click();H.entityPickerModalLevel(1).findByText(METRIC_NAME).should("not.exist");});});@@ -1521,10 +1521,10 @@ describe("issue #67903", () => {cy.signInAsAdmin();});- it("shoult not show preview table headers on top of other elements (metabase#67903)", () => {+ it("should not show preview table headers on top of other elements (metabase#67903)", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();- H.entityPickerModalItem(1, "Orders").click();+ H.pickEntity({ path: ["Databases", /Sample Database/, "Orders"] });H.getNotebookStep("data").findByTestId("step-preview-button").click();H.queryBuilderHeader().findByLabelText("View SQL").click();cy.findByTestId("table-header").should("not.be.visible");diff --git a/e2e/test/scenarios/question/new.cy.spec.js b/e2e/test/scenarios/question/new.cy.spec.jsindex d589ea42eb7..57a06117f83 100644--- a/e2e/test/scenarios/question/new.cy.spec.js+++ b/e2e/test/scenarios/question/new.cy.spec.js@@ -40,40 +40,31 @@ describe("scenarios > question > new", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {- cy.get("[role='tab']:contains('Search')").should("not.exist");+ H.entityPickerModalLevel(0)+ .findByText(/Search results for /)+ .should("not.exist");H.entityPickerModalItem(0, "Our analytics").click();- cy.findByPlaceholderText("Search this collection or everywhere…")- .type(" ")- .blur();- cy.findByText("Everywhere").click();- cy.findByPlaceholderText("Search this collection or everywhere…").type(- "ord",- );+ cy.findByPlaceholderText("Search…").type(" ").blur();+ cy.findByPlaceholderText("Search…").type("ord");cy.wait("@search");// should not trigger search for an empty stringcy.get("@searchQuery").should("have.been.calledOnce");- cy.get("[role='tab']:contains('Search')").should("be.visible");- cy.findAllByTestId("result-item").should("not.exist");- cy.findByText("Everywhere").click();- cy.findAllByTestId("result-item").should("have.length.at.least", 4);+ H.entityPickerModalLevel(0)+ .findByText(/Search results for /)+ .should("be.visible");- cy.findAllByTestId("result-item").then(($results) => {- const types = $results- .toArray()- .map((element) => element.getAttribute("data-model-type"));-- // Search results include both saved questions and database tables- expect(types).to.include("card");- expect(types).to.include("dataset");- expect(types).to.include("table");+ [+ "Orders, Count", //question+ "Orders Model", //model+ "Orders", //table+ ].forEach((text) => {+ cy.findAllByText(text).should("have.length.at.least", 1);});// Discarding the search query should take us back to the original tab- cy.findByPlaceholderText("Search this collection or everywhere…")- .clear()- .blur();+ cy.findByPlaceholderText("Search…").clear().blur();cy.get("[role='tab']:contains('Search')").should("not.exist");cy.findByText("Orders, Count").click();@@ -103,8 +94,7 @@ describe("scenarios > question > new", () => {cy.findByText("Orders").should("exist");cy.findByText("Orders, Count").should("exist");- H.entityPickerModalItem(0, "Databases").click();- cy.findByText("Products").click();+ H.pickEntity({ path: ["Databases", "Sample Database", "Products"] });});cy.findByTestId("data-step-cell").contains("Products");H.visualize();@@ -168,8 +158,7 @@ describe("scenarios > question > new", () => {cy.signIn("nocollection");H.startNewQuestion();H.miniPickerBrowseAll().click();- H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalItem(1, "Orders").click();+ H.pickEntity({ path: ["Databases", "Sample Database", "Orders"] });H.visualize();H.saveQuestion("Personal question");@@ -254,10 +243,7 @@ describe("scenarios > question > new", () => {H.popover().findByText("Question").click();H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalItem(1, "Orders").click();- });+ H.pickEntity({ path: ["Databases", "Sample Database", "Orders"] });cy.log("The selected table should be saved and show in recents (metabase#45003)",@@ -266,9 +252,9 @@ describe("scenarios > question > new", () => {cy.findByRole("button", { name: /Orders/ }).click();H.miniPickerHeader().click();H.miniPickerBrowseAll().click();- H.entityPickerModalTab("Recents").click();+ H.entityPickerModalItem(0, "Recent items").click();cy.findByRole("dialog", { name: "Pick your starting data" })- .findByRole("button", { name: /Orders/ })+ .findByText("Orders").should("exist");cy.findByRole("dialog", { name: "Pick your starting data" }).findByRole("button", { name: /Close/ })@@ -343,13 +329,13 @@ describe("scenarios > question > new", () => {cy.findByLabelText(/Where do you want to save this/).click();});- H.pickEntity({ tab: "Recents" });- H.entityPickerModal().within(() => {- cy.log("test valid recents appear");- cy.findByText("Second collection").should("exist");- cy.findByText("Orders in a dashboard").should("exist");+ H.entityPickerModalItem(0, "Recent items").click();+ cy.log("test valid recents appear");+ H.entityPickerModalItem(1, "Second collection").should("exist");+ H.entityPickerModalItem(1, "Orders in a dashboard").should("exist");- cy.log("test invalid recents do not appear");+ cy.log("test invalid recents do not appear");+ H.entityPickerModal().within(() => {cy.findByText("Third collection").should("not.exist");cy.findByText("Third collection dashboard").should("not.exist");});@@ -364,9 +350,7 @@ describe("scenarios > question > new", () => {cy.findByLabelText("Navigation bar").findByText("New").click();H.popover().findByText("Question").click();H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- cy.findByText("Orders").click();- });+ H.pickEntity({ path: ["Our analytics", "Orders"] });cy.findByTestId("qb-header").findByText("Save").click();cy.log("should be able to tab through fields (metabase#41683)");@@ -378,10 +362,6 @@ describe("scenarios > question > new", () => {.findByLabelText(/Where do you want to save/).click();- H.entityPickerModal()- .findByRole("tab", { name: /Browse/ })- .click();-H.entityPickerModal().findByText("New collection").click();const NEW_COLLECTION = "Foo";@@ -406,59 +386,6 @@ describe("scenarios > question > new", () => {},);- it(- "should be able to save a question to a dashboard created on the go",- { tags: "@smoke" },- () => {- H.visitCollection(THIRD_COLLECTION_ID);-- cy.findByLabelText("Navigation bar").findByText("New").click();- H.popover().findByText("Question").click();-- H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- cy.findByText("Orders").click();- });- cy.findByTestId("qb-header").findByText("Save").click();-- cy.log("should be able to tab through fields (metabase#41683)");- // Since the submit button has initial focus on this modal, we need an extra tab to get past the modal close button- cy.realPress("Tab").realPress("Tab").realPress("Tab");- cy.findByLabelText("Description").should("be.focused");-- cy.findByTestId("save-question-modal")- .findByLabelText(/Where do you want to save/)- .click();-- H.entityPickerModal()- .findByRole("tab", { name: /Browse/ })- .click();-- H.entityPickerModal().findByText("New dashboard").click();-- const NEW_DASHBOARD = "Foo Dashboard";- H.dashboardOnTheGoModal().within(() => {- cy.findByLabelText(/Give it a name/).type(NEW_DASHBOARD);- cy.findByText("Create").click();- });- H.entityPickerModal().within(() => {- cy.findByText(NEW_DASHBOARD).click();- cy.button(/Select/).click();- });- cy.findByTestId("save-question-modal").within(() => {- cy.findByText("Save new question");- cy.findByLabelText(/Where do you want to save/).should(- "have.text",- NEW_DASHBOARD,- );- cy.findByText("Save").click();- });-- cy.get("header").findByText(NEW_DASHBOARD);- cy.url().should("include", "/dashboard/");- },- );-it("should preserve the original question name (metabase#41196)", () => {const originalQuestionName = "Foo";const modifiedQuestionName = `${originalQuestionName} - Modified`;@@ -527,7 +454,6 @@ describe("scenarios > question > new", () => {H.pickEntity({path: [myPersonalCollectionName],select: true,- tab: "Browse",});cy.findByTestId("save-question-modal").button("Save").click();@@ -560,7 +486,6 @@ describe("scenarios > question > new", () => {H.pickEntity({path: ["Our analytics"],select: true,- tab: "Browse",});cy.findByTestId("save-question-modal").button("Save").click();@@ -571,7 +496,6 @@ describe("scenarios > question > new", () => {H.entityPickerModal().within(() => {cy.findByText("Add this question to a dashboard").should("be.visible");- cy.findByRole("tab", { name: /Dashboards/ }).click();cy.findByText("Bobby Tables's Personal Collection").should("be.visible",);@@ -595,7 +519,6 @@ describe("scenarios > question > new", () => {});H.pickEntity({- tab: "Browse",path: ["Our analytics"],select: true,});@@ -611,8 +534,9 @@ describe("scenarios > question > new", () => {it("when selecting a collection", () => {// H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();- H.entityPickerModalItem(1, "Collection in root collection").click();+ H.pickEntity({+ path: ["Our analytics", "Collection in root collection"],+ });cy.button(/New dashboard/).click();});@@ -643,8 +567,7 @@ describe("scenarios > question > new", () => {it("when selecting a collection with no child dashboards (metabase#47000)", () => {H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();- H.entityPickerModalItem(1, "First collection").click();+ H.pickEntity({ path: ["Our analytics", "First collection"] });cy.button(/New dashboard/).click();});@@ -675,8 +598,7 @@ describe("scenarios > question > new", () => {it("when a dashboard is currently selected", () => {H.entityPickerModal().within(() => {- H.entityPickerModalTab("Dashboards").click();- H.entityPickerModalItem(1, "Orders in a dashboard").click();+ H.pickEntity({ path: ["Our analytics", "Orders in a dashboard"] });cy.button(/New dashboard/).click();});@@ -718,10 +640,7 @@ describe(cy.visit("/question/new");H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalLevel(0).findByText("Databases").click();- H.entityPickerModalItem(3, "Products").click();- });+ H.pickEntity({ path: ["Databases", "Sample Database", "Products"] });// strange: we get different behavior when we go to question/newcy.findAllByTestId("run-button").first().click();@@ -735,9 +654,7 @@ describe(cy.visit("/question/new");H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalItem(1, "Orders").click();- });+ H.pickEntity({ path: ["Our analytics", "Orders"] });// strange: we get different behavior when we go to question/newcy.findAllByTestId("run-button").first().click();@@ -759,9 +676,7 @@ describe(cy.visit("/question/notebook");H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalItem(1, "Orders Model").click();- });+ H.pickEntity({ path: ["Our analytics", "Orders Model"] });cy.wait("@recents");@@ -770,8 +685,7 @@ describe(H.miniPickerBrowseAll().click();H.entityPickerModal().within(() => {- H.tabsShouldBe("Collections", ["Recents", "Data"]);- H.entityPickerModalTab("Recents").click();+ cy.findByText("Recent items").click();cy.findByTestId("result-item").should("contain.text", "Orders Model");});});diff --git a/e2e/test/scenarios/question/notebook-data-source.cy.spec.ts b/e2e/test/scenarios/question/notebook-data-source.cy.spec.tsindex d09fe3468d7..8aeb81c2361 100644--- a/e2e/test/scenarios/question/notebook-data-source.cy.spec.ts+++ b/e2e/test/scenarios/question/notebook-data-source.cy.spec.ts@@ -18,64 +18,25 @@ describe("scenarios > notebook > data source", () => {cy.signInAsAdmin();});- it(- "should display tables from the only existing database by default",- { tags: "@OSS" },- () => {- cy.visit("/");- cy.findByTestId("app-bar").findByText("New").click();- H.popover().findByTextEnsureVisible("Question").click();- cy.findByPlaceholderText("Search for tables and more...").should(- "exist",- );-- H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- cy.log("Should not have Recents tab");- cy.findAllByRole("tab").should("not.exist");-- H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalLevel(0)- .findByText("Sample Database")- .should("not.exist");- H.entityPickerModalLevel(3)- .find("[data-index]")- .should("have.length", 8);- assertDataPickerEntityNotSelected(3, "Accounts");- assertDataPickerEntityNotSelected(3, "Analytic Events");- assertDataPickerEntityNotSelected(3, "Feedback");- assertDataPickerEntityNotSelected(3, "Invoices");- assertDataPickerEntityNotSelected(3, "Orders");- assertDataPickerEntityNotSelected(3, "People");- assertDataPickerEntityNotSelected(3, "Products");- assertDataPickerEntityNotSelected(3, "Reviews");- });- },- );-- it("should include dashboard questions (metabase#56887)", () => {- const QUESTION_NAME = "Find me";-- H.createDashboard({- name: "Test Dashboard",- }).then((dashboard) => {- H.createQuestionAndAddToDashboard(- {- name: QUESTION_NAME,- dashboard_id: dashboard.body.id,- query: {- "source-table": ORDERS_ID,- },- },- dashboard.body.id,- );- });-- H.startNewQuestion();+ it("should display databases by default", { tags: "@OSS" }, () => {+ cy.visit("/");+ cy.findByTestId("app-bar").findByText("New").click();+ H.popover().findByTextEnsureVisible("Question").click();+ cy.findByPlaceholderText("Search for tables and more...").should("exist");H.miniPickerBrowseAll().click();- H.entityPickerModalItem(1, "Test Dashboard").click();- H.entityPickerModalItem(2, QUESTION_NAME).should("exist");+ H.entityPickerModal().within(() => {+ // databases is selected already+ H.entityPickerModalLevel(1).findByText("Sample Database").click();+ assertDataPickerEntityNotSelected(2, "Accounts");+ assertDataPickerEntityNotSelected(2, "Analytic Events");+ assertDataPickerEntityNotSelected(2, "Feedback");+ assertDataPickerEntityNotSelected(2, "Invoices");+ assertDataPickerEntityNotSelected(2, "Orders");+ assertDataPickerEntityNotSelected(2, "People");+ assertDataPickerEntityNotSelected(2, "Products");+ assertDataPickerEntityNotSelected(2, "Reviews");+ });});});@@ -94,11 +55,7 @@ describe("scenarios > notebook > data source", () => {H.miniPickerHeader().click();H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- // should not show schema step if there's only 1 schema- H.entityPickerModalLevel(2).should("not.exist");- assertDataPickerEntitySelected(3, "Reviews");- });+ assertDataPickerEntitySelected(2, "Reviews");});it("should correctly display the source data for a simple saved question", () => {@@ -110,11 +67,7 @@ describe("scenarios > notebook > data source", () => {H.miniPickerHeader().click();H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- // should not show schema step if there's only 1 schema- H.entityPickerModalLevel(2).should("not.exist");- assertDataPickerEntitySelected(3, "Orders");- });+ assertDataPickerEntitySelected(2, "Orders");});it(@@ -237,7 +190,6 @@ describe("scenarios > notebook > data source", () => {H.join();H.popover().findByText("Browse all").click();H.entityPickerModal().within(() => {- H.entityPickerModalTab("Data").click();H.entityPickerModalLevel(0).findByText("Library").click();H.entityPickerModalLevel(1).findByText("Data").click();cy.findByText("Products").click();@@ -444,6 +396,7 @@ describe("issue 28106", () => {H.entityPickerModal().within(() => {cy.findByText("Databases").click();cy.findByText("Writable Postgres12").click();+ cy.findByText("Schema A").click();H.entityPickerModalLevel(2).findByTestId("scroll-container")@@ -454,11 +407,11 @@ describe("issue 28106", () => {cy.get("@schemasList").scrollTo("bottom");// assert scrolling worked and the last item is visible- H.entityPickerModalItem(1, "Schema Z").should("be.visible");+ H.entityPickerModalItem(2, "Schema Z").should("be.visible");// simulate scrolling up using mouse wheel 3 timesfor (let i = 0; i < 3; ++i) {- cy.get("@schemasList").realMouseWheel({ deltaY: -100 });+ cy.get("@schemasList").realMouseWheel({ deltaY: -50 });cy.wait(100);}diff --git a/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.ts b/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.tsindex 458e349f891..8a439050f10 100644--- a/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.ts+++ b/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.ts@@ -283,7 +283,6 @@ describe("should be possible to save a question and `Explore results` (metabase#32121)",);H.saveQuestion("foo", undefined, {- tab: "Browse",path: ["Our analytics"],});cy.findByTestId("qb-header").findByText("Explore results").click();diff --git a/e2e/test/scenarios/question/notebook.cy.spec.js b/e2e/test/scenarios/question/notebook.cy.spec.jsindex 36d1f96ff85..36f593594ed 100644--- a/e2e/test/scenarios/question/notebook.cy.spec.js+++ b/e2e/test/scenarios/question/notebook.cy.spec.js@@ -16,7 +16,6 @@ describe("scenarios > question > notebook", { tags: "@slow" }, () => {H.openOrdersTable();// save question initiallyH.saveQuestion(undefined, undefined, {- tab: "Browse",path: ["Our analytics"],});diff --git a/e2e/test/scenarios/question/question-management.cy.spec.js b/e2e/test/scenarios/question/question-management.cy.spec.jsindex be27b5bbd95..d7246731a03 100644--- a/e2e/test/scenarios/question/question-management.cy.spec.js+++ b/e2e/test/scenarios/question/question-management.cy.spec.js@@ -75,7 +75,7 @@ describe(.should("have.attr", "aria-selected", "false");});- moveQuestionTo(/Personal Collection/, user === "admin");+ moveQuestionTo(/Personal Collection/);assertRequestNot403("updateQuestion");cy.findAllByRole("status")@@ -102,12 +102,15 @@ describe(H.openQuestionActions();cy.findByTestId("move-button").click();H.entityPickerModal().within(() => {- cy.findByRole("button", {- name: /Orders in a dashboard/,- }).should("exist");- cy.findByRole("button", { name: /Bobby Table/ }).should(- "not.exist",- );+ cy.findByText("Recent items").click();+ H.entityPickerModalLevel(1).within(() => {+ cy.findByRole("link", {+ name: /Orders in a dashboard/,+ }).should("exist");+ cy.findByRole("link", { name: /Bobby Table/ }).should(+ "not.exist",+ );+ });});}});@@ -118,9 +121,6 @@ describe(H.openQuestionActions();cy.findByTestId("move-button").click();H.entityPickerModal().within(() => {- if (user === "admin") {- cy.findByRole("tab", { name: /Browse/ }).click();- }cy.findByText(/Personal Collection/).click();cy.findByText("New collection").click();});@@ -154,7 +154,7 @@ describe(.should("have.attr", "aria-selected", "false");});- moveQuestionTo(/Personal Collection/, user === "admin");+ moveQuestionTo(/Personal Collection/);assertRequestNot403("updateQuestion");cy.findAllByRole("status")@@ -187,6 +187,7 @@ describe(H.entityPickerModal().as("modal").within(() => {+ cy.findByText("Our analytics").click();cy.findByText("Orders in a dashboard").click();cy.button("Select").click();});@@ -237,7 +238,7 @@ describe(cy.log("Move the question to a personal collection");- moveQuestionTo(/Personal Collection/, true);+ moveQuestionTo(/Personal Collection/);cy.log("assert public collections are not visible");H.openQuestionActions();@@ -248,17 +249,13 @@ describe("be.visible",);- H.tabsShouldBe("Recents", ["Recents", "Dashboards"]);-- cy.findByRole("button", {+ cy.findByRole("link", {name: /Personal Dashboard/,}).should("exist");- cy.findByRole("button", {+ cy.findByRole("link", {name: /Orders in a dashboard/,}).should("not.exist");- H.entityPickerModalTab("Dashboards").click();-cy.findByText(/'s personal collection/i).should("be.visible",);@@ -267,7 +264,7 @@ describe(});cy.log("Move the question to the root collection");- moveQuestionTo("Our analytics", true);+ moveQuestionTo("Our analytics");cy.log("assert all collections are visible");H.openQuestionActions();@@ -276,22 +273,20 @@ describe(cy.findByText("Add this question to a dashboard").should("be.visible",);-- H.tabsShouldBe("Recents", ["Recents", "Dashboards"]);-- cy.findByRole("button", {+ cy.findByText("Recent items").click();+ cy.findByRole("link", {name: /Personal Dashboard/,}).should("exist");- cy.findByRole("button", {+ cy.findByRole("link", {name: /Orders in a dashboard/,}).should("exist");- H.entityPickerModalTab("Dashboards").click();-- cy.findByText(/'s personal collection/i).should(- "be.visible",- );- cy.findByText(/our analytics/i).should("be.visible");+ H.entityPickerModalLevel(0).within(() => {+ cy.findByText(/'s personal collection/i).should(+ "be.visible",+ );+ cy.findByText(/our analytics/i).should("be.visible");+ });});});@@ -309,9 +304,9 @@ describe(H.openQuestionActions();cy.findByTestId("add-to-dashboard-button").click();- H.entityPickerModalTab("Dashboards").click();-- findActivePickerItem("Orders in a dashboard");+ H.pickEntity({+ path: ["Our analytics", "Orders in a dashboard"],+ });});it("should handle lost access", () => {@@ -334,9 +329,6 @@ describe(cy.findByTestId("add-to-dashboard-button").click();cy.wait("@mostRecentlyViewedDashboard");- H.entityPickerModal()- .findByRole("tab", { name: /Dashboards/ })- .click();findActivePickerItem("Orders in a dashboard");@@ -358,7 +350,11 @@ describe(cy.wait("@mostRecentlyViewedDashboard");- findInactivePickerItem("Orders in a dashboard");+ H.entityPickerModalItem(1, "Orders in a dashboard").should(+ "have.attr",+ "data-disabled",+ "true",+ );});});});@@ -376,10 +372,6 @@ describe(H.openQuestionActions();cy.findByTestId("add-to-dashboard-button").click();- H.entityPickerModal()- .findByText("First collection")- .should("be.visible");-findInactivePickerItem("Orders in a dashboard");H.entityPickerModal().within(() => {@@ -387,7 +379,7 @@ describe("Orders in a dashboard{Enter}",{ delay: 0 },);- cy.findByText(/weren't any results/).should("be.visible");+ cy.findByText(/didn't find anything/).should("be.visible");});});@@ -414,8 +406,9 @@ describe(cy.findByTestId("add-to-dashboard-button").click();H.entityPickerModal()- .findByText("Orders in a dashboard")- .should("not.exist");+ .findByText(/Orders in a dashboard/)+ .closest("a")+ .should("have.attr", "data-disabled", "true");// before visiting the dashboard, we don't have any historyH.visitDashboard(ORDERS_DASHBOARD_ID);@@ -424,10 +417,10 @@ describe(H.openQuestionActions();cy.findByTestId("add-to-dashboard-button").click();- // still no dataH.entityPickerModal()- .findByText("Orders in a dashboard")- .should("not.exist");+ .findByText(/Orders in a dashboard/)+ .closest("a")+ .should("have.attr", "data-disabled", "true");});});});@@ -452,8 +445,10 @@ describe("question moving", () => {.closest("button").click();H.popover().findByTestId("move-button").click();- H.modal().findByText("Second collection").click();- H.modal().button("Move").click();+ H.pickEntity({+ path: ["Our analytics", "First collection", "Second collection"],+ select: true,+ });cy.wait("@updateQuestion").its("response.statusCode").should("eq", 200);cy.findAllByRole("status").contains("Question moved to Second collection");H.appBar().findByText("Second collection").should("be.visible");@@ -472,8 +467,10 @@ describe("question moving", () => {.closest("button").click();H.popover().findByTestId("move-button").click();- H.modal().findByText("Second collection").click();- H.modal().button("Move").click();+ H.pickEntity({+ path: ["Our analytics", "First collection", "Second collection"],+ select: true,+ });cy.wait("@updateQuestion");H.modal().findByText("Sorry buddy, only cool kids in this collection")@@ -540,11 +537,10 @@ function findInactivePickerItem(name) {});}-function moveQuestionTo(newCollectionName, clickTab = false) {+function moveQuestionTo(newCollectionName) {H.openQuestionActions();cy.findByTestId("move-button").click();H.entityPickerModal().within(() => {- clickTab && cy.findByRole("tab", { name: /Collections|Browse/ }).click();cy.findByText(newCollectionName).click();cy.button("Move").click();});diff --git a/e2e/test/scenarios/question/saved.cy.spec.js b/e2e/test/scenarios/question/saved.cy.spec.jsindex a1c366446b5..fb6619898fc 100644--- a/e2e/test/scenarios/question/saved.cy.spec.js+++ b/e2e/test/scenarios/question/saved.cy.spec.js@@ -152,53 +152,6 @@ describe("scenarios > question > saved", () => {cy.get("header").findByText(NEW_COLLECTION);});- it("should duplicate a saved question to a dashboard created on the go", () => {- cy.intercept("POST", "/api/card").as("cardCreate");-- H.visitQuestion(ORDERS_QUESTION_ID);-- H.openQuestionActions();- H.popover().within(() => {- cy.findByText("Duplicate").click();- });-- H.modal().within(() => {- cy.findByLabelText("Name").should("have.value", "Orders - Duplicate");- cy.findByTestId("dashboard-and-collection-picker-button").click();- });-- H.entityPickerModal().findByText("New dashboard").click();-- const NEW_DASHBOARD = "Foo Dashboard";- H.dashboardOnTheGoModal().within(() => {- cy.findByLabelText(/Give it a name/).type(NEW_DASHBOARD);- cy.findByText("Create").click();- });-- H.entityPickerModal().within(() => {- cy.findByText(NEW_DASHBOARD).click();- cy.button(/Select/).click();- });- H.entityPickerModal().should("not.exist");-- H.modal().within(() => {- cy.findByLabelText("Name").should("have.value", "Orders - Duplicate");- cy.findByTestId("dashboard-and-collection-picker-button").should(- "have.text",- NEW_DASHBOARD,- );- cy.button("Duplicate").click();- cy.wait("@cardCreate");- });-- cy.findByTestId("qb-header-left-side").within(() => {- cy.findByDisplayValue("Orders - Duplicate");- });-- cy.get("header").findByText(NEW_DASHBOARD);- cy.url().should("include", "/dashboard/");- });-it("should not add scrollbar to duplicate modal if question name is long (metabase#53364)", () => {H.createQuestion({@@ -469,11 +422,10 @@ describe("scenarios > question > saved", () => {});});- function moveQuestionTo(newCollectionName, clickTab = false) {+ function moveQuestionTo(newCollectionName) {H.openQuestionActions();cy.findByTestId("move-button").click();H.entityPickerModal().within(() => {- clickTab && cy.findByRole("tab", { name: /Browse/ }).click();cy.findByText(newCollectionName).click();cy.button("Move").click();});@@ -506,7 +458,7 @@ describe("scenarios > question > saved", () => {);H.visitQuestion(ORDERS_QUESTION_ID);- moveQuestionTo(/Personal Collection/, true);+ moveQuestionTo(/Personal Collection/);cy.signInAsNormalUser();cy.get("@questionId").then(H.visitQuestion);diff --git a/e2e/test/scenarios/question/settings.cy.spec.js b/e2e/test/scenarios/question/settings.cy.spec.jsindex d885dc39d4c..a6c4602b532 100644--- a/e2e/test/scenarios/question/settings.cy.spec.js+++ b/e2e/test/scenarios/question/settings.cy.spec.js@@ -545,12 +545,13 @@ describe("scenarios > question > settings", () => {cy.findByTestId("save-question-modal").within(() => {cy.findByLabelText(/Where do you want to save this/).click();});- H.pickEntity({ tab: "Browse", path: ["Our analytics"], select: false });+ H.pickEntity({ path: ["Our analytics"], select: false });H.entityPickerModal().findByText("Select this collection").click();cy.findByTestId("save-question-modal").findByText("Save").click();H.checkSavedToCollectionQuestionToast(true);H.entityPickerModal().within(() => {+ cy.findByText("Our analytics").click();cy.findByText("Orders in a dashboard").click();cy.findByText("Cancel").click();});diff --git a/e2e/test/scenarios/search/recently-viewed.cy.spec.js b/e2e/test/scenarios/search/recently-viewed.cy.spec.jsindex 6af45d04978..3efc6dec3c6 100644--- a/e2e/test/scenarios/search/recently-viewed.cy.spec.js+++ b/e2e/test/scenarios/search/recently-viewed.cy.spec.js@@ -94,10 +94,6 @@ describe("Recently Viewed > Entity Picker", () => {H.entityPickerModal().within(() => {cy.findByText("Select a collection").click();- cy.findByRole("tab", { name: /Recents/ });- cy.findByRole("tab", { name: /Collections/ });-- cy.findByText("Today");cy.findByText("My Fresh Collection");});});@@ -111,10 +107,7 @@ describe("Recently Viewed > Entity Picker", () => {H.entityPickerModal().within(() => {cy.findByText("Add this question to a dashboard").click();- cy.findByRole("tab", { name: /Recents/ });- cy.findByRole("tab", { name: /Dashboards/ });-- cy.findByText("Today");+ cy.findByText("Our analytics").click();cy.findByText("Orders in a dashboard").click();cy.button("Select").click();});diff --git a/e2e/test/scenarios/search/search-snowplow.cy.spec.js b/e2e/test/scenarios/search/search-snowplow.cy.spec.jsindex 12b60d5ca12..be418de73c3 100644--- a/e2e/test/scenarios/search/search-snowplow.cy.spec.js+++ b/e2e/test/scenarios/search/search-snowplow.cy.spec.js@@ -114,7 +114,7 @@ describe("scenarios > search > snowplow", () => {});H.entityPickerModal()- .findByRole("button", { name: /Second/ })+ .findByRole("link", { name: /Second collection/ }).click();H.expectUnstructuredSnowplowEvent({diff --git a/e2e/test/scenarios/sharing/public-question.cy.spec.js b/e2e/test/scenarios/sharing/public-question.cy.spec.jsindex 9e21b392e84..1465c663c7c 100644--- a/e2e/test/scenarios/sharing/public-question.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-question.cy.spec.js@@ -145,7 +145,6 @@ describe("scenarios > public > question", () => {"test question",{ wrapId: true },{- tab: "Browse",path: ["Our analytics"],},);@@ -176,7 +175,6 @@ describe("scenarios > public > question", () => {"test question",{ wrapId: true },{- tab: "Browse",path: ["Our analytics"],},);diff --git a/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js b/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.jsindex 4d18e581b0b..65427d4fe8e 100644--- a/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js@@ -224,10 +224,7 @@ describe("#39152 sharing an unsaved question", () => {it("should ask the user to save the question before creating a public link", () => {H.startNewQuestion();H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalItem(1, "People").click();- });+ H.pickEntity({ path: ["Databases", "Sample Database", "People"] });H.visualize();H.openSharingMenu();diff --git a/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js b/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.jsindex cb5e96d0dcb..4d2d595d101 100644--- a/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js+++ b/e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js@@ -1119,7 +1119,6 @@ describe("scenarios > visualizations > pivot tables", { tags: "@slow" }, () => {});H.saveQuestion(undefined, undefined, {- tab: "Browse",path: ["Our analytics"],});@@ -1192,7 +1191,6 @@ describe("scenarios > visualizations > pivot tables", { tags: "@slow" }, () => {);H.saveQuestion(undefined, undefined, {- tab: "Browse",path: ["Our analytics"],});cy.wait("@createCard");diff --git a/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js b/e2e/test/scenarios/visualizations-tabular/table.cy.spec.jsindex 80471d291fe..df8bb906ee1 100644--- a/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js+++ b/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js@@ -16,10 +16,7 @@ describe("scenarios > visualizations > table", () => {function joinTable(table) {cy.findByText("Join data").click();H.miniPickerBrowseAll().click();- H.entityPickerModal().within(() => {- H.entityPickerModalItem(0, "Databases").click();- H.entityPickerModalItem(1, table).click();- });+ H.pickEntity({ path: ["Databases", "Sample Database", table] });}function selectFromDropdown(option, clickOpts) {diff --git a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsx b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsxindex 9ac12ae87c2..13a9da2aade 100644--- a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsx+++ b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityList.tsx@@ -85,7 +85,9 @@ const SavedEntityList = ({size: 16,}}onSelect={() => onSelect(virtualTableId)}- rightIcon={PLUGIN_MODERATION.getStatusIcon(moderated_status)}+ rightIcon={PLUGIN_MODERATION.getStatusIcon(+ moderated_status ?? undefined,+ )}/>);})}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/PublishTableModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/PublishTableModal.tsxindex afa0bcb41f1..0d5347e57cd 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/PublishTableModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/PublishTableModal.tsx@@ -1,14 +1,11 @@-import { useState } from "react";import { t } from "ttag";-import { EntityPickerModal } from "metabase/common/components/EntityPicker/components/EntityPickerModal/EntityPickerModal";import {- TablePicker,- type TablePickerItem,- type TablePickerStatePath,-} from "metabase/common/components/Pickers/TablePicker";+ EntityPickerModal,+ type OmniPickerItem,+ type OmniPickerTableItem,+} from "metabase/common/components/Pickers";import { useMetadataToasts } from "metabase/metadata/hooks/useMetadataToasts";-import { Box } from "metabase/ui";import { usePublishTablesMutation } from "metabase-enterprise/api/table";import { trackDataStudioTablePublished } from "metabase-enterprise/data-studio/analytics";import { isConcreteTableId } from "metabase-types/api";@@ -16,21 +13,22 @@ import { isConcreteTableId } from "metabase-types/api";interface PublishTableModalProps {opened: boolean;onClose: () => void;- onPublished: (table: TablePickerItem) => void;+ onPublished: (table: OmniPickerTableItem) => void;}+const isTableItem = (item?: OmniPickerItem): item is OmniPickerTableItem =>+ !!item && item.model === "table";+export function PublishTableModal({opened,onClose,onPublished,}: PublishTableModalProps) {- const [tablesPath, setTablesPath] = useState<TablePickerStatePath>();const { sendSuccessToast } = useMetadataToasts();const [publishTables] = usePublishTablesMutation();- const [item, setItem] = useState<TablePickerItem | null>(null);- const onConfirm = async () => {- if (!item) {+ const onConfirm = async (item: OmniPickerItem) => {+ if (!isTableItem(item)) {return;}await publishTables({ table_ids: [item.id] }).unwrap(); // unwrap() allows EntityPicker's error handling to take over@@ -46,42 +44,25 @@ export function PublishTableModal({return null;}+ const shouldDisableItem = (item: OmniPickerItem) =>+ item.model === "table" && "is_published" in item && !!item.is_published;+return (<EntityPickerModaltitle={t`Select a table to publish`}- searchModels={["table"]}- canSelectItem={item?.model === "table"}+ models={["table"]}options={{+ hasLibrary: false,hasRecents: false,+ hasDatabases: true,hasConfirmButtons: true,+ hasRootCollection: false,+ hasPersonalCollections: false,confirmButtonText: t`Publish`,}}- tabs={[- {- id: "tables-tab",- displayName: t`Tables`,- models: ["table"],- folderModels: ["database", "schema"],- icon: "table",- render: ({ onItemSelect }) => (- <Box h="100%" style={{ overflow: "auto" }}>- <TablePicker- path={tablesPath}- value={undefined}- onItemSelect={onItemSelect}- onPathChange={setTablesPath}- shouldDisableItem={(item) =>- item.model === "table" && !!item.is_published- }- />- </Box>- ),- },- ]}- onItemSelect={setItem}+ isDisabledItem={shouldDisableItem}+ onChange={onConfirm}onClose={onClose}- onConfirm={onConfirm}- selectedItem={item}/>);}diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/EntryPickerModal.tsx b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/EntryPickerModal.tsxindex f11efd968eb..3a410512332 100644--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/EntryPickerModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/EntryPickerModal.tsx@@ -1,222 +1,36 @@-import { useMemo, useState } from "react";+import { useMemo } from "react";import { t } from "ttag";-import { useLogRecentItemMutation, useSearchQuery } from "metabase/api";import {EntityPickerModal,- type EntityPickerTab,-} from "metabase/common/components/EntityPicker";-import {- DashboardPicker,- type DashboardPickerStatePath,-} from "metabase/common/components/Pickers/DashboardPicker";-import {- QuestionPicker,- type QuestionPickerStatePath,-} from "metabase/common/components/Pickers/QuestionPicker";-import {- TablePicker,- type TablePickerStatePath,-} from "metabase/common/components/Pickers/TablePicker";-import { PLUGIN_TRANSFORMS } from "metabase/plugins";-import {- type DependencyEntry,- type DependencyNode,- isActivityModel,-} from "metabase-types/api";+ type OmniPickerItem,+} from "metabase/common/components/Pickers";+import type { DependencyEntry, DependencyNode } from "metabase-types/api";import {- DASHBOARD_PICKER_OPTIONS,ENTITY_PICKER_OPTIONS,- QUESTION_PICKER_OPTIONS,+ ENTRY_PICKER_MODELS,RECENTS_CONTEXT,} from "./constants";-import type {- EntryPickerItem,- EntryPickerItemId,- EntryPickerItemModel,-} from "./types";-import {- getDashboardPickerItem,- getEntryPickerItem,- getEntryPickerValue,- getMetricPickerItem,- getModelPickerItem,- getQuestionPickerItem,- getTablePickerValue,- getTransformPickerItem,- hasAvailableModels,- selectOnlyCards,-} from "./utils";+import { getEntryPickerItem, getEntryPickerValue } from "./utils";type EntryPickerModalProps = {value: DependencyNode | null;onChange: (value: DependencyEntry) => void;onClose: () => void;};-export function EntryPickerModal({value,onChange,onClose,}: EntryPickerModalProps) {- const [tablesPath, setTablesPath] = useState<TablePickerStatePath>();- const [questionsPath, setQuestionsPath] = useState<QuestionPickerStatePath>();- const [modelsPath, setModelsPath] = useState<QuestionPickerStatePath>();- const [metricsPath, setMetricsPath] = useState<QuestionPickerStatePath>();- const [dashboardsPath, setDashboardsPath] =- useState<DashboardPickerStatePath>();- const { data: searchResponse, isLoading: isSearchLoading } = useSearchQuery({- models: ["card"],- limit: 0,- calculate_available_models: true,- });- const [logRecentItem] = useLogRecentItemMutation();-const selectedItem = useMemo(() => {return value != null ? getEntryPickerItem(value) : undefined;}, [value]);- const tabs = useMemo(() => {- const computedTabs: EntityPickerTab<- EntryPickerItemId,- EntryPickerItemModel,- EntryPickerItem- >[] = [];-- computedTabs.push({- id: "tables-tab",- displayName: t`Tables`,- models: ["table"],- folderModels: ["database", "schema"],- icon: "table",- render: ({ onItemSelect }) => (- <TablePicker- value={value ? getTablePickerValue(value) : undefined}- path={tablesPath}- onItemSelect={onItemSelect}- onPathChange={setTablesPath}- />- ),- });-- if (hasAvailableModels(searchResponse, ["transform"])) {- computedTabs.push({- id: "transforms-tab",- displayName: t`Transforms`,- models: ["transform"],- folderModels: [],- icon: "transform",- render: ({ onItemSelect }) => (- <PLUGIN_TRANSFORMS.TransformPicker- value={value ? getTransformPickerItem(value) : undefined}- onItemSelect={onItemSelect}- />- ),- });- }-- if (hasAvailableModels(searchResponse, ["card"])) {- computedTabs.push({- id: "questions-tab",- displayName: t`Questions`,- models: ["card"],- folderModels: ["collection", "dashboard"],- icon: "table2",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={value ? getQuestionPickerItem(value) : undefined}- models={["card", "dashboard"]}- options={QUESTION_PICKER_OPTIONS}- path={questionsPath}- onInit={selectOnlyCards(onItemSelect)}- onItemSelect={selectOnlyCards(onItemSelect)}- onPathChange={setQuestionsPath}- />- ),- });- }-- if (hasAvailableModels(searchResponse, ["dataset"])) {- computedTabs.push({- id: "models-tab",- displayName: t`Models`,- models: ["dataset"],- folderModels: ["collection"],- icon: "model",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={value ? getModelPickerItem(value) : undefined}- models={["dataset"]}- options={QUESTION_PICKER_OPTIONS}- path={modelsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setModelsPath}- />- ),- });- }-- if (hasAvailableModels(searchResponse, ["metric"])) {- computedTabs.push({- id: "metrics-tab",- displayName: t`Metrics`,- models: ["metric"],- folderModels: ["collection"],- icon: "metric",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={value ? getMetricPickerItem(value) : undefined}- models={["metric"]}- options={DASHBOARD_PICKER_OPTIONS}- path={metricsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setMetricsPath}- />- ),- });- }-- if (hasAvailableModels(searchResponse, ["dashboard"])) {- computedTabs.push({- id: "dashboards-tab",- displayName: t`Dashboards`,- models: ["dashboard"],- folderModels: ["collection"],- icon: "dashboard",- render: ({ onItemSelect }) => (- <DashboardPicker- initialValue={value ? getDashboardPickerItem(value) : undefined}- models={["dashboard"]}- options={QUESTION_PICKER_OPTIONS}- path={dashboardsPath}- onItemSelect={onItemSelect}- onPathChange={setDashboardsPath}- />- ),- });- }-- return computedTabs;- }, [- value,- searchResponse,- tablesPath,- questionsPath,- modelsPath,- metricsPath,- dashboardsPath,- ]);-- const handleItemSelect = (item: EntryPickerItem) => {+ const handleItemSelect = (item: OmniPickerItem) => {const value = getEntryPickerValue(item);if (value != null) {- if (isActivityModel(item.model)) {- logRecentItem({ model: item.model, model_id: value.id });- }-onChange(value);}};@@ -224,15 +38,11 @@ export function EntryPickerModal({return (<EntityPickerModaltitle={t`Pick an item to see its dependencies`}- tabs={tabs}- initialValue={selectedItem}- selectedItem={selectedItem ?? null}+ models={ENTRY_PICKER_MODELS}+ value={selectedItem}options={ENTITY_PICKER_OPTIONS}recentsContext={RECENTS_CONTEXT}- isLoadingTabs={isSearchLoading}- canSelectItem- defaultToRecentTab={false}- onItemSelect={handleItemSelect}+ onChange={handleItemSelect}onClose={onClose}/>);diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.tsindex 12be07ce37d..2f46f50fa0e 100644--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.ts@@ -1,25 +1,32 @@-import {- type EntityPickerModalOptions,- defaultOptions,-} from "metabase/common/components/EntityPicker";-import type { DashboardPickerOptions } from "metabase/common/components/Pickers/DashboardPicker";-import type { QuestionPickerOptions } from "metabase/common/components/Pickers/QuestionPicker";+import type {+ EntityPickerOptions,+ EntityPickerProps,+} from "metabase/common/components/Pickers";import type { RecentContexts } from "metabase-types/api";export const RECENTS_CONTEXT: RecentContexts[] = ["selections"];-export const ENTITY_PICKER_OPTIONS: EntityPickerModalOptions = {- ...defaultOptions,+export const ENTITY_PICKER_OPTIONS = {+ hasDatabases: true,hasConfirmButtons: false,hasRecents: true,};-export const QUESTION_PICKER_OPTIONS: QuestionPickerOptions = {- showRootCollection: true,- showPersonalCollections: true,+export const QUESTION_PICKER_OPTIONS: EntityPickerOptions = {+ hasRootCollection: true,+ hasPersonalCollections: true,};-export const DASHBOARD_PICKER_OPTIONS: DashboardPickerOptions = {- showRootCollection: true,- showPersonalCollections: true,+export const DASHBOARD_PICKER_OPTIONS: EntityPickerOptions = {+ hasRootCollection: true,+ hasPersonalCollections: true,};++export const ENTRY_PICKER_MODELS: EntityPickerProps["models"] = [+ "table",+ "card",+ "dataset",+ "metric",+ "dashboard",+ "transform",+];diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/types.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/types.tsdeleted file mode 100644index 51822f80ec0..00000000000--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/types.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { QuestionPickerItem } from "metabase/common/components/Pickers/QuestionPicker";-import type { TablePickerItem } from "metabase/common/components/Pickers/TablePicker";-import type { TransformPickerItem } from "metabase/plugins";--export type EntryPickerItem =- | TablePickerItem- | QuestionPickerItem- | TransformPickerItem;--export type EntryPickerItemId = EntryPickerItem["id"];--export type EntryPickerItemModel = EntryPickerItem["model"];diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.tsindex 1aba68ed859..af3296994ea 100644--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.ts@@ -1,9 +1,10 @@-import type { DashboardPickerItem } from "metabase/common/components/Pickers/DashboardPicker";-import type { QuestionPickerItem } from "metabase/common/components/Pickers/QuestionPicker";import type {- TablePickerItem,- TablePickerValue,-} from "metabase/common/components/Pickers/TablePicker";+ OmniPickerCollectionItem,+ OmniPickerItem,+ OmniPickerQuestionItem,+ OmniPickerTableItem,+ OmniPickerValue,+} from "metabase/common/components/Pickers";import type { TransformPickerItem } from "metabase/plugins";import type {CardType,@@ -16,25 +17,9 @@ import type {import { getDependencyType } from "../../../../utils";import { SEARCH_MODEL_TO_GROUP_TYPE } from "../constants";-import type { EntryPickerItem } from "./types";--export function getTablePickerValue(- node: DependencyNode,-): TablePickerValue | undefined {- if (node.type === "table") {- return {- id: node.id,- model: "table",- name: node.data.name,- schema: node.data.schema,- db_id: node.data.db_id,- };- }-}-export function getTablePickerItem(node: DependencyNode,-): TablePickerItem | undefined {+): OmniPickerTableItem | undefined {if (node.type !== "table") {return;}@@ -58,10 +43,11 @@ export function getTransformPickerItem(id: node.id,name: node.data.name,model: "transform",+ namespace: "transforms",};}-function getCardPickerModel(type: CardType): QuestionPickerItem["model"] {+function getCardPickerModel(type: CardType): OmniPickerQuestionItem["model"] {switch (type) {case "question":return "card";@@ -75,7 +61,7 @@ function getCardPickerModel(type: CardType): QuestionPickerItem["model"] {function getCardPickerItem(node: DependencyNode,cardType: CardType,-): QuestionPickerItem | undefined {+): OmniPickerQuestionItem | undefined {if (node.type !== "card" || node.data.type !== cardType) {return;}@@ -89,25 +75,25 @@ function getCardPickerItem(export function getQuestionPickerItem(node: DependencyNode,-): QuestionPickerItem | undefined {+): OmniPickerQuestionItem | undefined {return getCardPickerItem(node, "question");}export function getModelPickerItem(node: DependencyNode,-): QuestionPickerItem | undefined {+): OmniPickerQuestionItem | undefined {return getCardPickerItem(node, "model");}export function getMetricPickerItem(node: DependencyNode,-): QuestionPickerItem | undefined {+): OmniPickerQuestionItem | undefined {return getCardPickerItem(node, "metric");}export function getDashboardPickerItem(node: DependencyNode,-): DashboardPickerItem | undefined {+): (OmniPickerCollectionItem & { model: "dashboard" }) | undefined {if (node.type !== "dashboard") {return;}@@ -116,7 +102,7 @@ export function getDashboardPickerItem(export function getEntryPickerItem(node: DependencyNode,-): EntryPickerItem | undefined {+): OmniPickerValue | undefined {return (getTablePickerItem(node) ??getTransformPickerItem(node) ??@@ -128,7 +114,7 @@ export function getEntryPickerItem(}export function getEntryPickerValue(- item: EntryPickerItem,+ item: OmniPickerItem,): DependencyEntry | undefined {if (typeof item.id !== "number" ||@@ -138,7 +124,7 @@ export function getEntryPickerValue(return;}- const groupType = SEARCH_MODEL_TO_GROUP_TYPE[item.model];+ const groupType = SEARCH_MODEL_TO_GROUP_TYPE[item.model as SearchModel];if (groupType != null) {return { id: item.id, type: getDependencyType(groupType) };}@@ -151,10 +137,3 @@ export function hasAvailableModels(const availableModels = response?.available_models ?? [];return models.some((model) => availableModels.includes(model));}--export function selectOnlyCards(- onItemSelect: (item: QuestionPickerItem) => void,-) {- return (item: QuestionPickerItem) =>- item.model === "card" ? onItemSelect(item) : undefined;-}diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsxindex cb1eb7379b4..7ae606d5820 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsx@@ -268,14 +268,12 @@ function MetabotCollectionConfigurationPane({model: "collection",}}onChange={(item) =>- handleUpdateCollectionId(- item as unknown as Pick<MetabotInfo, "id" | "name">,- )+ handleUpdateCollectionId(item as Pick<MetabotInfo, "id" | "name">)}onClose={close}options={{- showRootCollection: true,- showPersonalCollections: false,+ hasRootCollection: true,+ hasPersonalCollections: false,}}/>)}diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.unit.spec.tsxindex a58073645f4..3c434fe301b 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.unit.spec.tsx@@ -5,13 +5,21 @@ import { Route } from "react-router";import {findRequests,setupCollectionByIdEndpoint,+ setupCollectionsEndpoints,setupRecentViewsAndSelectionsEndpoints,+ setupRootCollectionItemsEndpoint,} from "__support__/server-mocks";import {setupMetabotPromptSuggestionsEndpoint,setupMetabotsEndpoints,} from "__support__/server-mocks/metabot";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ waitForLoaderToBeRemoved,+} from "__support__/ui";import {FIXED_METABOT_ENTITY_IDS,FIXED_METABOT_IDS,@@ -54,28 +62,31 @@ const defaultSeedCollections = [id: 21,name: "Collection Two",model: "collection",+ can_write: true,collection_name: "Collection Two Prime",parent_collection: {id: 3,- name: "Collection Two Prime",+ name: "Collection Beta Prime",},},{id: 31,name: "Collection Three",model: "collection",+ can_write: true,parent_collection: {id: 3,- name: "Collection Three Prime",+ name: "Collection Delta Prime",},},{id: 32,name: "Collection Four",model: "collection",+ can_write: true,parent_collection: {id: 3,- name: "Collection Four Prime",+ name: "Collection Sigma Prime",},},];@@ -85,11 +96,14 @@ const setup = async (seedCollections = defaultSeedCollections,error = false,) => {+ mockGetBoundingClientRect();mockPathParam(initialPathParam);setupMetabotsEndpoints(metabots, error ? 500 : undefined);setupCollectionByIdEndpoint({collections: seedCollections.map((c: any) => ({ id: c.model_id, ...c })),});+ setupRootCollectionItemsEndpoint({ rootCollectionItems: [] });+ setupCollectionsEndpoints({ collections: [] });setupRecentViewsAndSelectionsEndpoints(seedCollections as RecentItem[]);@@ -134,7 +148,7 @@ describe("MetabotAdminPage", () => {await setup();expect(await screen.findByText("Configure Metabot")).toBeInTheDocument();expect(- screen.getByText("Collection for natural language querying"),+ await screen.findByText(/Collection for natural language querying/),).toBeInTheDocument();});@@ -177,8 +191,10 @@ describe("MetabotAdminPage", () => {await userEvent.click(screen.getByText("Pick a different collection"));await screen.findByText("Select a collection");- await userEvent.click(screen.getByText("Collection Three"));- await userEvent.click(screen.getByText("Select"));+ await userEvent.click(await screen.findByText(/Recent items/));+ await waitForLoaderToBeRemoved();+ await userEvent.click(await screen.findByText(/Collection Three/));+ await userEvent.click(screen.getByRole("button", { name: "Select" }));await waitFor(async () => {const puts = await findRequests("PUT");diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsxindex 00ce49ae802..2fd074cf508 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx@@ -37,8 +37,6 @@ import {DataAttributeMappingEditor,} from "../AttributeMappingEditor";-import { shouldDisableItem } from "./utils";-// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045const ERROR_MESSAGE = t`An error occurred.`;@@ -221,7 +219,14 @@ const EditSandboxingModal = ({hideModal();}}onClose={hideModal}- shouldDisableItem={shouldDisableItem}+ models={["card", "dataset"]}+ namespaces={[null]}+ options={{+ hasLibrary: false,+ hasRootCollection: true,+ hasPersonalCollections: true,+ hasConfirmButtons: true,+ }}/>)}</div>diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.unit.spec.tsxindex 52363390398..a801db6ae55 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.unit.spec.tsx@@ -242,6 +242,9 @@ describe("EditSandboxingModal", () => {await userEvent.click(await screen.findByRole("link", { name: /sandbox question/i }),);+ await userEvent.click(+ await screen.findByRole("button", { name: "Select" }),+ );await userEvent.click(await screen.findByText("Save"));@@ -249,11 +252,13 @@ describe("EditSandboxingModal", () => {expect(screen.queryByText("Saving...")).not.toBeInTheDocument();});- expect(onSave).toHaveBeenCalledWith({- attribute_remappings: {},- card_id: 1,- group_id: 1,- table_id: PEOPLE_ID,+ await waitFor(() => {+ expect(onSave).toHaveBeenCalledWith({+ attribute_remappings: {},+ card_id: 1,+ group_id: 1,+ table_id: PEOPLE_ID,+ });});});});@@ -292,6 +297,9 @@ describe("EditSandboxingModal", () => {await userEvent.click(await screen.findByRole("link", { name: /sandbox question/i }),);+ await userEvent.click(+ await screen.findByRole("button", { name: "Select" }),+ );await userEvent.click(await screen.findByText("Save"));diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/utils.ts b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/utils.tsdeleted file mode 100644index 1813130c417..00000000000--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/utils.ts+++ /dev/null@@ -1,29 +0,0 @@-import _ from "underscore";--import type {- QuestionPickerItem,- QuestionPickerModel,-} from "metabase/common/components/Pickers/QuestionPicker";--export const shouldDisableItem = (- item: QuestionPickerItem,- models?: QuestionPickerModel[],-) =>- !(- isRootCollection(item) ||- isPersonalCollection(item) ||- isCollectionWithModels(item, models) ||- item.model === "dataset" ||- item.model === "card"- );--const isRootCollection = (item: QuestionPickerItem) => item.id === "root";-const isPersonalCollection = (item: QuestionPickerItem) =>- item.model === "collection" && item.is_personal && item.location === "/";-const isCollectionWithModels = (- item: QuestionPickerItem,- models: QuestionPickerModel[] = [],-) =>- (item.model === "collection" || item.model === "dashboard") &&- _.intersection([...(item.below || []), ...(item.here || [])], models).length >- 0;diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionForm.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionForm.tsxindex 59d7123f8f4..fcea127295b 100644--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionForm.tsx@@ -10,7 +10,7 @@ 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 { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+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";@@ -110,7 +110,7 @@ function SnippetCollectionForm({);const shouldDisableItem = useCallback(- (item: CollectionPickerItem) =>+ (item: OmniPickerItem) =>isItemInCollectionOrItsDescendants(item, passedCollection.id),[passedCollection.id],);@@ -138,9 +138,9 @@ function SnippetCollectionForm({<FormCollectionPickername="parent_id"title={t`Folder this should be in`}- type="snippet-collections"collectionPickerModalProps={{- shouldDisableItem: shouldDisableItem,+ isDisabledItem: shouldDisableItem,+ namespaces: ["snippets"],}}/><FormFooter>diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPickerModal.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPickerModal.tsxindex 39c4f129e9c..39d5afbc027 100644--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPickerModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPickerModal.tsx@@ -1,8 +1,8 @@import { useCallback } from "react";import { t } from "ttag";-import type { CollectionPickerValueItem } from "metabase/common/components/Pickers/CollectionPicker";-import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";+import { CollectionPickerModal } from "metabase/common/components/Pickers";import type { SnippetCollectionPickerModalProps } from "metabase/plugins";import type { CollectionId } from "metabase-types/api";@@ -12,7 +12,7 @@ export function SnippetCollectionPickerModal({onClose,}: SnippetCollectionPickerModalProps) {const handleChange = useCallback(- (item: CollectionPickerValueItem) => {+ (item: OmniPickerItem) => {const collectionId: CollectionId | null =item.id === "root" ? null : item.id;onSelect(collectionId);@@ -30,14 +30,15 @@ export function SnippetCollectionPickerModal({onChange={handleChange}onClose={onClose}title={t`Select a folder for your snippet`}+ namespaces={["snippets"]}options={{- namespace: "snippets",- showPersonalCollections: false,- showRootCollection: true,- showSearch: false,+ hasPersonalCollections: false,+ canCreateCollections: true,+ hasRootCollection: true,+ hasSearch: false,hasConfirmButtons: true,hasRecents: false,- showLibrary: false,+ hasLibrary: false,}}/>);diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/TenantCollectionItemList.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/TenantCollectionItemList.tsxindex 888048f05ab..c4eb66c864a 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/TenantCollectionItemList.tsx+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/TenantCollectionItemList.tsx@@ -1,18 +1,11 @@import { useListCollectionItemsQuery } from "metabase/api";-import { ItemList } from "metabase/common/components/EntityPicker/components/ItemList";-import type {- CollectionItemListProps,- CollectionPickerItem,-} from "metabase/common/components/Pickers/CollectionPicker/types";+import { ItemList } from "metabase/common/components/Pickers/EntityPicker/components";export const TenantCollectionItemList = ({- onClick,- selectedItem,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,-}: CollectionItemListProps) => {+ pathIndex,+}: {+ pathIndex: number;+}) => {const {data: collectionItems,error,@@ -24,15 +17,10 @@ export const TenantCollectionItemList = ({return (<ItemList- items={collectionItems?.data as CollectionPickerItem[] | undefined}+ items={collectionItems?.data}isLoading={isLoading}error={error}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}+ pathIndex={pathIndex}/>);};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/TenantSpecificCollectionsItemList.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/TenantSpecificCollectionsItemList.tsxindex d7d5f42d96a..c2a112492c4 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/TenantSpecificCollectionsItemList.tsx+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/TenantSpecificCollectionsItemList.tsx@@ -1,21 +1,16 @@import { useMemo } from "react";-import { ItemList } from "metabase/common/components/EntityPicker/components/ItemList";-import type {- CollectionItemListProps,- CollectionPickerItem,-} from "metabase/common/components/Pickers/CollectionPicker/types";+import type { OmniPickerItem } from "metabase/common/components/Pickers";+import { ItemList } from "metabase/common/components/Pickers/EntityPicker";+import { allCollectionModels } from "metabase/common/components/Pickers/EntityPicker/utils";import { useListTenantsQuery } from "metabase-enterprise/api";import type { Tenant } from "metabase-types/api";export const TenantSpecificCollectionsItemList = ({- onClick,- selectedItem,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,-}: CollectionItemListProps) => {+ pathIndex,+}: {+ pathIndex: number;+}) => {const {data: tenantsData,error,@@ -32,31 +27,27 @@ export const TenantSpecificCollectionsItemList = ({items={tenantCollections}error={error}isLoading={isLoading}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}+ pathIndex={pathIndex}/>);};const getTenantCollections = (tenants?: Tenant[],-): CollectionPickerItem[] | null =>+): OmniPickerItem[] | undefined =>tenants?.filter((tenant) => tenant.tenant_collection_id != null).map(- (tenant): CollectionPickerItem => ({+ (tenant): OmniPickerItem => ({id: tenant.tenant_collection_id!,name: tenant.name,here: ["collection"], // tenant collections can contain collections+ below: allCollectionModels,model: "collection",location: "/",can_write: true,type: "tenant-specific-root-collection",- collection_id: "tenant-specific",+ collection: { id: "tenant-specific", name: "" },}),)- .sort((a, b) => a.name.localeCompare(b.name)) ?? null;+ .sort((a, b) => a.name.localeCompare(b.name)) ?? undefined;diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsxindex 246c777f6a8..880b9d3c21c 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx@@ -25,12 +25,10 @@ import {PLUGIN_ADMIN_USER_MENU_ROUTES,PLUGIN_TENANTS,} from "metabase/plugins";-import type { TenantCollectionPathItem } from "metabase/plugins/oss/tenants";import { getIsTenantUser } from "metabase/selectors/user";import { getApplicationName } from "metabase/selectors/whitelabel";import { Box, Text } from "metabase/ui";import { hasPremiumFeature } from "metabase-enterprise/settings";-import type { CollectionId, CollectionNamespace } from "metabase-types/api";import { EditUserStrategyModal } from "./EditUserStrategyModal";import { EditUserStrategySettingsButton } from "./EditUserStrategySettingsButton";@@ -53,74 +51,19 @@ import { NewTenantModal } from "./containers/NewTenantModal";import { TenantActivationModal } from "./containers/TenantActivationModal";import { TenantsListingApp } from "./containers/TenantsListingApp";import {+ SHARED_TENANT_NAMESPACE,+ TENANT_SPECIFIC_NAMESPACE,+} from "./utils/constants";+import {+ canPlaceEntityInCollection,+ getNamespaceDisplayName,+ getRootCollectionItem,isExternalUser,isExternalUsersGroup,isTenantCollection,isTenantGroup,} from "./utils/utils";-const SHARED_TENANT_NAMESPACE: CollectionNamespace = "shared-tenant-collection";--const isTenantNamespace = (namespace?: CollectionNamespace): boolean => {- return (- namespace === SHARED_TENANT_NAMESPACE || namespace === "tenant-specific"- );-};--const isTenantCollectionId = (id: CollectionId): boolean => {- return id === "tenant" || id === "tenant-specific";-};--const getNamespaceForTenantId = (id: CollectionId): CollectionNamespace => {- if (id === "tenant") {- return SHARED_TENANT_NAMESPACE;- }- return null;-};--const getTenantCollectionPathPrefix = (- collection: TenantCollectionPathItem,-): CollectionId[] | null => {- if (collection.id === "tenant") {- return ["tenant"];- }- if (collection.id === "tenant-specific") {- return ["tenant-specific"];- }-- if (collection.type === "tenant-specific-root-collection") {- if (collection.collection_id === "tenant-specific") {- return ["tenant-specific", collection.id];- }- return [collection.id];- }-- if (collection.namespace === "tenant-specific") {- return ["tenant"];- }-- const isTenant =- isTenantNamespace(collection.namespace) ||- isTenantNamespace(collection.collection_namespace) ||- collection.is_shared_tenant_collection ||- collection.is_tenant_dashboard;-- if (isTenant) {- return ["tenant"];- }-- return null;-};--const getNamespaceDisplayName = (- namespace?: CollectionNamespace,-): string | null => {- if (namespace === SHARED_TENANT_NAMESPACE) {- return t`Shared collections`;- }- return null;-};-export function initializePlugin() {if (hasPremiumFeature("tenants")) {PLUGIN_TENANTS.isEnabled = true;@@ -238,6 +181,7 @@ export function initializePlugin() {PLUGIN_TENANTS.TenantUsersList = TenantUsersList;PLUGIN_TENANTS.TenantUsersPersonalCollectionList =TenantUsersPersonalCollectionList;+ PLUGIN_TENANTS.canPlaceEntityInCollection = canPlaceEntityInCollection;// Category 1: UI ComponentsPLUGIN_TENANTS.GroupDescription = function GroupDescription({ group }) {@@ -266,24 +210,11 @@ export function initializePlugin() {// Category 2: Collection namespace utilitiesPLUGIN_TENANTS.SHARED_TENANT_NAMESPACE = SHARED_TENANT_NAMESPACE;- PLUGIN_TENANTS.isTenantNamespace = isTenantNamespace;- PLUGIN_TENANTS.isTenantCollectionId = isTenantCollectionId;- PLUGIN_TENANTS.getNamespaceForTenantId = getNamespaceForTenantId;- PLUGIN_TENANTS.getTenantCollectionPathPrefix =- getTenantCollectionPathPrefix;+ PLUGIN_TENANTS.TENANT_SPECIFIC_NAMESPACE = TENANT_SPECIFIC_NAMESPACE;PLUGIN_TENANTS.getTenantRootDisabledReason = () =>t`Items cannot be saved directly to the tenant root collection. Please select a sub-collection.`;PLUGIN_TENANTS.getNamespaceDisplayName = getNamespaceDisplayName;- PLUGIN_TENANTS.TENANT_SPECIFIC_COLLECTIONS = {- id: "tenant-specific" as const,- get name() {- return t`Tenant collections`;- },- location: "/",- path: ["root"],- can_write: false,- };-+ PLUGIN_TENANTS.getRootCollectionItem = getRootCollectionItem;PLUGIN_TENANTS.getFlattenedCollectionsForNavbar = ({currentUser,sharedTenantCollections,diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/utils/constants.ts b/enterprise/frontend/src/metabase-enterprise/tenants/utils/constants.tsnew file mode 100644index 00000000000..43a98aa0630--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/utils/constants.ts@@ -0,0 +1,10 @@+import type { CollectionNamespace } from "metabase-types/api";++export const SHARED_TENANT_NAMESPACE: CollectionNamespace =+ "shared-tenant-collection";+export const TENANT_SPECIFIC_NAMESPACE: CollectionNamespace = "tenant-specific";++export const TENANT_NAMESPACES: CollectionNamespace[] = [+ SHARED_TENANT_NAMESPACE,+ TENANT_SPECIFIC_NAMESPACE,+];diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.tsindex e773ac8a836..a8e0a3121e1 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts@@ -1,4 +1,23 @@-import type { Collection, Group, User } from "metabase-types/api";+import { t } from "ttag";++import {+ type OmniPickerCollectionItem,+ type OmniPickerItem,+ isInDbTree,+} from "metabase/common/components/Pickers";+import type {+ Collection,+ CollectionItemModel,+ CollectionNamespace,+ Group,+ User,+} from "metabase-types/api";++import {+ SHARED_TENANT_NAMESPACE,+ TENANT_NAMESPACES,+ TENANT_SPECIFIC_NAMESPACE,+} from "./constants";export const isExternalUsersGroup = (group: Pick<Group, "magic_group_type">,@@ -17,3 +36,80 @@ export const isExternalUser = (user?: Pick<User, "tenant_id">): boolean => {export const isTenantCollection = (collection: Partial<Pick<Collection, "namespace">>,) => collection.namespace === "shared-tenant-collection";++const isRootCollection = (collection: OmniPickerCollectionItem): boolean => {+ return collection.id === "root" || collection.id === null;+};++export const canPlaceEntityInCollection = ({+ entityType,+ collection,+}: {+ entityType?: CollectionItemModel;+ collection: OmniPickerItem;+}): boolean => {+ if (!entityType) {+ return true;+ }+ if (isInDbTree(collection)) {+ return false;+ }++ if (+ !isRootCollection(collection) ||+ !isTenantNamespace(collection.namespace)+ ) {+ return true;+ }++ if (entityType === "collection") {+ // can create collections in shared tenant root, nothing+ return collection.namespace === SHARED_TENANT_NAMESPACE;+ }++ return false;+};++const isTenantNamespace = (namespace?: CollectionNamespace): boolean => {+ return !!(namespace && TENANT_NAMESPACES.includes(namespace));+};++export const getNamespaceDisplayName = (+ namespace?: CollectionNamespace,+): string | null => {+ if (namespace === SHARED_TENANT_NAMESPACE) {+ return t`Shared collections`;+ }+ return null;+};++export const getRootCollectionItem = ({+ namespace,+}: {+ namespace: CollectionNamespace;+}): OmniPickerCollectionItem | null => {+ if (namespace === SHARED_TENANT_NAMESPACE) {+ return {+ id: "root",+ name: t`Shared collections`,+ namespace: SHARED_TENANT_NAMESPACE,+ here: ["collection"],+ below: ["collection", "card", "dashboard"],+ model: "collection",+ location: "/",+ };+ }+ if (namespace === TENANT_SPECIFIC_NAMESPACE) {+ return {+ id: "root",+ name: t`Tenant collections`,+ namespace: TENANT_SPECIFIC_NAMESPACE,+ here: ["collection"],+ below: ["collection", "card", "dashboard"],+ model: "collection",+ can_write: false, // this is fake so it's always false+ location: "/",+ };+ }+ return null;+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.unit.spec.tsnew file mode 100644index 00000000000..be52892dce1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.unit.spec.ts@@ -0,0 +1,267 @@+import type {+ OmniPickerCollectionItem,+ OmniPickerItem,+} from "metabase/common/components/Pickers";+import type {+ Collection,+ CollectionId,+ CollectionNamespace,+ Group,+ User,+} from "metabase-types/api";++import {+ SHARED_TENANT_NAMESPACE,+ TENANT_SPECIFIC_NAMESPACE,+} from "./constants";+import {+ canPlaceEntityInCollection,+ getNamespaceDisplayName,+ getRootCollectionItem,+ isExternalUser,+ isExternalUsersGroup,+ isTenantCollection,+ isTenantGroup,+} from "./utils";++describe("isExternalUsersGroup", () => {+ it("should return true for all-external-users magic group type", () => {+ const group: Pick<Group, "magic_group_type"> = {+ magic_group_type: "all-external-users",+ };+ expect(isExternalUsersGroup(group)).toBe(true);+ });++ it("should return false for other magic group types", () => {+ const group: Pick<Group, "magic_group_type"> = {+ magic_group_type: "all-internal-users",+ };+ expect(isExternalUsersGroup(group)).toBe(false);+ });++ it("should return false for groups without magic group type", () => {+ const group: Pick<Group, "magic_group_type"> = {+ // @ts-expect-error testing invalid case+ magic_group_type: undefined,+ };+ expect(isExternalUsersGroup(group)).toBe(false);+ });+});++describe("isTenantGroup", () => {+ it("should return true when is_tenant_group is true", () => {+ const group: Pick<Group, "is_tenant_group"> = {+ is_tenant_group: true,+ };+ expect(isTenantGroup(group)).toBe(true);+ });++ it("should return false when is_tenant_group is false", () => {+ const group: Pick<Group, "is_tenant_group"> = {+ is_tenant_group: false,+ };+ expect(isTenantGroup(group)).toBe(false);+ });++ it("should return false when is_tenant_group is undefined", () => {+ const group: Pick<Group, "is_tenant_group"> = {+ is_tenant_group: undefined,+ };+ expect(isTenantGroup(group)).toBe(false);+ });+});++describe("isExternalUser", () => {+ it("should return true when user has a non-null tenant_id", () => {+ const user: Pick<User, "tenant_id"> = {+ tenant_id: 123,+ };+ expect(isExternalUser(user)).toBe(true);+ });++ it("should return false when user has null tenant_id", () => {+ const user: Pick<User, "tenant_id"> = {+ tenant_id: null,+ };+ expect(isExternalUser(user)).toBe(false);+ });++ it("should return false when user is undefined", () => {+ expect(isExternalUser(undefined)).toBe(false);+ });+});++describe("isTenantCollection", () => {+ it("should return true for shared-tenant-collection namespace", () => {+ const collection: Partial<Pick<Collection, "namespace">> = {+ namespace: "shared-tenant-collection",+ };+ expect(isTenantCollection(collection)).toBe(true);+ });++ it("should return false for other namespaces", () => {+ const collection: Partial<Pick<Collection, "namespace">> = {+ namespace: "snippets" as CollectionNamespace,+ };+ expect(isTenantCollection(collection)).toBe(false);+ });++ it("should return false when namespace is undefined", () => {+ const collection: Partial<Pick<Collection, "namespace">> = {};+ expect(isTenantCollection(collection)).toBe(false);+ });+});++describe("canPlaceEntityInCollection (tenants plugin)", () => {+ const createMockCollection = (+ id: CollectionId,+ namespace?: CollectionNamespace,+ ): OmniPickerCollectionItem => ({+ id,+ name: "Test Collection",+ namespace,+ model: "collection",+ location: "/",+ can_write: true,+ });++ const createDbTreeItem = (): OmniPickerItem => ({+ id: 1,+ name: "Test Database",+ model: "database",+ });++ it("should return true when entityType is not provided", () => {+ const collection = createMockCollection("123");+ expect(+ canPlaceEntityInCollection({ collection, entityType: undefined }),+ ).toBe(true);+ });++ it("should return false for items in database tree", () => {+ const collection = createDbTreeItem();+ expect(canPlaceEntityInCollection({ collection, entityType: "card" })).toBe(+ false,+ );+ });++ it("should return true for non-root collections", () => {+ const collection = createMockCollection("123");+ expect(canPlaceEntityInCollection({ collection, entityType: "card" })).toBe(+ true,+ );+ });++ it("should return true for non-tenant namespace collections", () => {+ const collection = createMockCollection("root", "snippets");+ expect(canPlaceEntityInCollection({ collection, entityType: "card" })).toBe(+ true,+ );+ });++ describe("root tenant collections", () => {+ it("should allow collections in shared tenant root", () => {+ const collection = createMockCollection("root", SHARED_TENANT_NAMESPACE);+ expect(+ canPlaceEntityInCollection({ collection, entityType: "collection" }),+ ).toBe(true);+ });++ it("should not allow collections in tenant-specific root", () => {+ const collection = createMockCollection(+ "root",+ TENANT_SPECIFIC_NAMESPACE,+ );+ expect(+ canPlaceEntityInCollection({ collection, entityType: "collection" }),+ ).toBe(false);+ });++ it("should not allow cards in shared tenant root", () => {+ const collection = createMockCollection("root", SHARED_TENANT_NAMESPACE);+ expect(+ canPlaceEntityInCollection({ collection, entityType: "card" }),+ ).toBe(false);+ });++ it("should not allow dashboards in shared tenant root", () => {+ const collection = createMockCollection("root", SHARED_TENANT_NAMESPACE);+ expect(+ canPlaceEntityInCollection({ collection, entityType: "dashboard" }),+ ).toBe(false);+ });++ it("should handle null collection id", () => {+ // @ts-expect-error testing null id case+ const collection = createMockCollection(null, SHARED_TENANT_NAMESPACE);+ expect(+ canPlaceEntityInCollection({ collection, entityType: "card" }),+ ).toBe(false);+ });+ });+});++describe("getNamespaceDisplayName", () => {+ it("should return 'Shared collections' for shared-tenant-collection namespace", () => {+ expect(getNamespaceDisplayName(SHARED_TENANT_NAMESPACE)).toBe(+ "Shared collections",+ );+ });++ it("should return null for tenant-specific namespace", () => {+ expect(getNamespaceDisplayName(TENANT_SPECIFIC_NAMESPACE)).toBe(null);+ });++ it("should return null for other namespaces", () => {+ expect(getNamespaceDisplayName("snippets" as CollectionNamespace)).toBe(+ null,+ );+ });++ it("should return null for undefined namespace", () => {+ expect(getNamespaceDisplayName(undefined)).toBe(null);+ });+});++describe("getRootCollectionItem", () => {+ it("should return correct item for shared tenant namespace", () => {+ const result = getRootCollectionItem({+ namespace: SHARED_TENANT_NAMESPACE,+ });++ expect(result).toEqual({+ id: "root",+ name: "Shared collections",+ namespace: SHARED_TENANT_NAMESPACE,+ here: ["collection"],+ below: ["collection", "card", "dashboard"],+ model: "collection",+ location: "/",+ });+ });++ it("should return correct item for tenant-specific namespace", () => {+ const result = getRootCollectionItem({+ namespace: TENANT_SPECIFIC_NAMESPACE,+ });++ expect(result).toEqual({+ id: "root",+ name: "Tenant collections",+ namespace: TENANT_SPECIFIC_NAMESPACE,+ here: ["collection"],+ below: ["collection", "card", "dashboard"],+ model: "collection",+ can_write: false,+ location: "/",+ });+ });++ it("should return null for other namespaces", () => {+ const result = getRootCollectionItem({+ namespace: "snippets",+ });++ expect(result).toBe(null);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsxindex 1964e03b134..248c341c88f 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsx@@ -1,12 +1,11 @@import { useDisclosure } from "@mantine/hooks";import { t } from "ttag";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import {- type DataPickerItem,DataPickerModal,+ type DataPickerValue,} from "metabase/common/components/Pickers/DataPicker";-import type { TablePickerValue } from "metabase/common/components/Pickers/TablePicker";import {ActionIcon,Box,@@ -19,7 +18,6 @@ import {import type {ConcreteTableId,DatabaseId,- RecentItem,Table,TableId,} from "metabase-types/api";@@ -53,20 +51,12 @@ export function TableSelector({}}- function shouldDisableItem(- item: DataPickerItem | CollectionPickerItem | RecentItem,- ) {+ function shouldDisableItem(item: OmniPickerItem) {if (item.model === "table") {// Filter available tables to exclude already selected ones (except current selection)return !isConcreteTableId(item.id) || selectedTableIds.includes(item.id);}- if (item.model === "database") {- return item.id !== database;- }- if (item.model === "collection" && item.id === "databases") {- return false;- }- return true;+ return false;}return (@@ -110,16 +100,17 @@ export function TableSelector({{isOpened && (<DataPickerModaltitle={t`Pick a table`}- value={getDataPickerValue(table)}- databaseId={database}+ value={getDataPickerValue(table) ?? getDefaultDatabase(database)}+ onlyDatabaseId={database}onChange={handleChange}onClose={close}shouldDisableItem={shouldDisableItem}models={["table"]}options={{- showLibrary: false,- showRootCollection: false,- showPersonalCollections: false,+ hasLibrary: false,+ hasDatabases: true,+ hasRootCollection: false,+ hasPersonalCollections: false,}}/>)}@@ -127,17 +118,24 @@ export function TableSelector({);}+function getDefaultDatabase(dbId?: DatabaseId): DataPickerValue | undefined {+ if (!dbId) {+ return;+ }+ return {+ model: "database",+ id: dbId,+ };+}+function getDataPickerValue(table: Table | undefined,-): TablePickerValue | undefined {+): DataPickerValue | undefined {if (!table) {return;}return {model: "table",id: table.id,- name: table.display_name,- db_id: table.db_id,- schema: table.schema,};}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformCollectionModal/CreateTransformCollectionModal.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformCollectionModal/CreateTransformCollectionModal.tsxindex 2abde439846..51396b60c1a 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformCollectionModal/CreateTransformCollectionModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformCollectionModal/CreateTransformCollectionModal.tsx@@ -93,7 +93,7 @@ export function CreateTransformCollectionModal({<FormCollectionPickername="parent_id"title={t`Parent collection`}- type="transform-collections"+ collectionPickerModalProps={{ namespaces: ["transforms"] }}/><Group justify="flex-end"><FormErrorMessage />diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/CreateTransformMenu.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/CreateTransformMenu.tsxindex 5bf637d7945..24128b966aa 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/CreateTransformMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/CreateTransformMenu.tsx@@ -4,7 +4,7 @@ import { t } from "ttag";import { UpsellGem } from "metabase/admin/upsells/components/UpsellGem";import { useListDatabasesQuery } from "metabase/api";-import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker";+import { QuestionPickerModal } from "metabase/common/components/Pickers";import { useHasTokenFeature } from "metabase/common/hooks";import { useDispatch } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";@@ -115,12 +115,10 @@ export const CreateTransformMenu = () => {<QuestionPickerModaltitle={t`Pick a question or a model`}models={["card", "dataset"]}- shouldDisableItem={(item) => shouldDisableItem(item, databases?.data)}+ isDisabledItem={(item) => shouldDisableItem(item, databases?.data)}onChange={(item) => {- if (item.model === "card") {- dispatch(push(Urls.newTransformFromCard(item.id)));- closePicker();- }+ dispatch(push(Urls.newTransformFromCard(item.id)));+ closePicker();}}onClose={closePicker}/>diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/utils.ts b/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/utils.tsindex 71a0d7a5ab1..15ac9228326 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/transforms/components/CreateTransformMenu/utils.ts@@ -1,10 +1,10 @@-import type { QuestionPickerItem } from "metabase/common/components/Pickers/QuestionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import type { Database } from "metabase-types/api";import { doesDatabaseSupportTransforms } from "../../utils";export function shouldDisableItem(- item: QuestionPickerItem,+ item: OmniPickerItem,databases?: Database[],) {if (diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/components/EditTransformCollectionModal/EditTransformCollectionModal.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/components/EditTransformCollectionModal/EditTransformCollectionModal.tsxindex 193270b4aa6..959cec33dcf 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/components/EditTransformCollectionModal/EditTransformCollectionModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/components/EditTransformCollectionModal/EditTransformCollectionModal.tsx@@ -12,7 +12,7 @@ import {type CollectionFormValues,} from "metabase/collections/schemas";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import { isItemInCollectionOrItsDescendants } from "metabase/common/components/Pickers/utils";import { useToast } from "metabase/common/hooks";import {@@ -82,7 +82,7 @@ export function EditTransformCollectionModal({);const shouldDisableItem = useCallback(- (item: CollectionPickerItem) =>+ (item: OmniPickerItem) =>isItemInCollectionOrItsDescendants(item, collectionId),[collectionId],);@@ -138,9 +138,9 @@ export function EditTransformCollectionModal({<FormCollectionPickername="parent_id"title={t`Parent collection`}- type="transform-collections"collectionPickerModalProps={{- shouldDisableItem,+ isDisabledItem: shouldDisableItem,+ namespaces: ["transforms"],}}/><Group justify="flex-end">diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformHeader/TransformMoreMenu/MoveTransformModal.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformHeader/TransformMoreMenu/MoveTransformModal.tsxindex 5eb606d1b46..074bf4da630 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformHeader/TransformMoreMenu/MoveTransformModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformHeader/TransformMoreMenu/MoveTransformModal.tsx@@ -2,23 +2,24 @@ import { useCallback, useMemo } from "react";import { c } from "ttag";import { canonicalCollectionId } from "metabase/collections/utils";-import {- type CollectionPickerItem,- CollectionPickerModal,- type CollectionPickerOptions,-} from "metabase/common/components/Pickers/CollectionPicker";+import type {+ EntityPickerOptions,+ OmniPickerItem,+ OmniPickerValue,+} from "metabase/common/components/Pickers";+import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";import { useUpdateTransformMutation } from "metabase-enterprise/api";import type { Transform } from "metabase-types/api";-const TRANSFORM_COLLECTION_PICKER_OPTIONS: CollectionPickerOptions = {- namespace: "transforms",- showPersonalCollections: false,- showRootCollection: true,- showSearch: false,- hasConfirmButtons: true,- allowCreateNew: true,+const TRANSFORM_COLLECTION_PICKER_OPTIONS: EntityPickerOptions = {+ hasSearch: false,hasRecents: false,- showLibrary: false,+ hasLibrary: false,+ hasRootCollection: true,+ hasPersonalCollections: false,++ hasConfirmButtons: true,+ canCreateCollections: true,};type MoveTransformModalProps = {@@ -35,7 +36,7 @@ export function MoveTransformModal({const [updateTransform] = useUpdateTransformMutation();const handleChange = useCallback(- async ({ id }: CollectionPickerItem) => {+ async ({ id }: OmniPickerItem) => {const collectionId = canonicalCollectionId(id);await updateTransform({id: transform.id,@@ -46,10 +47,11 @@ export function MoveTransformModal({[transform.id, updateTransform, onMove],);- const pickerValue = useMemo(+ const pickerValue: OmniPickerValue = useMemo(() => ({id: transform.collection_id ?? "root",- model: "collection" as const,+ model: "collection",+ namespace: "transforms",}),[transform.collection_id],);@@ -59,6 +61,7 @@ export function MoveTransformModal({title={c("dialog title for moving a transform to another collection").t`Move "${transform.name}"`}value={pickerValue}+ namespaces={["transforms"]}onChange={handleChange}onClose={onClose}options={TRANSFORM_COLLECTION_PICKER_OPTIONS}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformPicker/TransformPicker.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformPicker/TransformPicker.tsxdeleted file mode 100644index da8c93649c8..00000000000--- a/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformPicker/TransformPicker.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { useMemo, useState } from "react";--import {- AutoScrollBox,- ItemList,- ListBox,-} from "metabase/common/components/EntityPicker";-import type {- TransformPickerItem,- TransformPickerProps,-} from "metabase/plugins";-import { Flex } from "metabase/ui";-import { useListTransformsQuery } from "metabase-enterprise/api";-import type { TransformId } from "metabase-types/api";--export function TransformPicker({ value, onItemSelect }: TransformPickerProps) {- const [selectedTransformId, setSelectedTransformId] = useState(value?.id);- const { data: transforms, error, isLoading } = useListTransformsQuery({});-- const items: TransformPickerItem[] | undefined = useMemo(() => {- return transforms?.map((transform) => ({- id: transform.id,- model: "transform",- name: transform.name,- }));- }, [transforms]);-- const selectedItem = useMemo(() => {- return items?.find((item) => item.id === selectedTransformId) ?? null;- }, [items, selectedTransformId]);-- const handleTransformClick = (item: TransformPickerItem) => {- setSelectedTransformId(item.id);- onItemSelect(item);- };-- return (- <AutoScrollBox- contentHash={getContentHash(selectedTransformId)}- data-testid="nested-item-picker"- >- <Flex h="100%" w="fit-content">- <ListBox data-testid="item-picker-level-0">- <ItemList- items={items}- selectedItem={selectedItem}- error={error}- isLoading={isLoading}- isFolder={isFolder}- isCurrentLevel- onClick={handleTransformClick}- />- </ListBox>- </Flex>- </AutoScrollBox>- );-}--function isFolder() {- return false;-}--function getContentHash(selectedTransformId?: TransformId) {- return selectedTransformId?.toString() ?? "";-}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformPicker/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformPicker/index.tsdeleted file mode 100644index 7bdaa7d547d..00000000000--- a/enterprise/frontend/src/metabase-enterprise/transforms/components/TransformPicker/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./TransformPicker";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/index.tsxindex d4fc30307c7..e5c368d0173 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx@@ -1,12 +1,12 @@import { PLUGIN_ENTITIES, PLUGIN_TRANSFORMS } from "metabase/plugins";import { getUser, getUserIsAdmin } from "metabase/selectors/user";-import { useGetTransformQuery } from "metabase-enterprise/api";+import { transformApi, useGetTransformQuery } from "metabase-enterprise/api";import { Transforms } from "metabase-enterprise/entities/transforms";import { hasPremiumFeature } from "metabase-enterprise/settings";import type { State } from "metabase-types/store";-import { TransformPicker } from "./components/TransformPicker";import { getDataStudioTransformRoutes } from "./routes";+import { getRootCollectionItem } from "./utils";const canAccessTransforms = (state: State): boolean => {if (getUserIsAdmin(state)) {@@ -33,7 +33,9 @@ export function initializePlugin() {PLUGIN_TRANSFORMS.canAccessTransforms = canAccessTransforms;PLUGIN_TRANSFORMS.getDataStudioTransformRoutes =getDataStudioTransformRoutes;- PLUGIN_TRANSFORMS.TransformPicker = TransformPicker;PLUGIN_TRANSFORMS.useGetTransformQuery = useGetTransformQuery;+ PLUGIN_TRANSFORMS.getRootCollectionItem = getRootCollectionItem;+ // @ts-expect-error - FIXME: this is a nightmare to type, and it's moving to OSS anyway+ PLUGIN_TRANSFORMS.transformApi = transformApi;}}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/pages/NewTransformPage/CreateTransformModal/CreateTransformModal.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/pages/NewTransformPage/CreateTransformModal/CreateTransformModal.tsxindex 96989c74d8b..caff90a03a9 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/pages/NewTransformPage/CreateTransformModal/CreateTransformModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/pages/NewTransformPage/CreateTransformModal/CreateTransformModal.tsx@@ -148,7 +148,7 @@ function CreateTransformForm({<FormCollectionPickername="collection_id"title={t`Collection`}- type="transform-collections"+ collectionPickerModalProps={{ namespaces: ["transforms"] }}style={{ marginBottom: 0 }}/><IncrementalTransformSettingsdiff --git a/enterprise/frontend/src/metabase-enterprise/transforms/utils.ts b/enterprise/frontend/src/metabase-enterprise/transforms/utils.tsindex 0e10f6d5675..e019f7b54ff 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/transforms/utils.ts@@ -2,11 +2,13 @@ import { t } from "ttag";import _ from "underscore";import { hasFeature } from "metabase/admin/databases/utils";+import type { OmniPickerCollectionItem } from "metabase/common/components/Pickers/EntityPicker/types";import { parseTimestamp } from "metabase/lib/time-dayjs";import { isNotNull } from "metabase/lib/types";import * as Lib from "metabase-lib";import type Metadata from "metabase-lib/v1/metadata/Metadata";import type {+ CollectionNamespace,Database,DatabaseId,DraftTransformSource,@@ -227,3 +229,22 @@ export const isMbqlQuery = (}return !Lib.queryDisplayInfo(query).isNative;};++export const getRootCollectionItem = ({+ namespace,+}: {+ namespace: CollectionNamespace;+}): OmniPickerCollectionItem | null => {+ if (namespace === "transforms") {+ return {+ model: "collection",+ id: "root",+ namespace: "transforms",+ location: "/",+ name: t`Transforms`,+ here: ["collection"],+ below: ["table", "metric"],+ };+ }+ return null;+};diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.tsindex 39d6bf21f01..7ed072a330a 100644--- a/frontend/src/metabase-types/analytics/event.ts+++ b/frontend/src/metabase-types/analytics/event.ts@@ -96,7 +96,8 @@ export type MoveToTrashEvent = ValidateEvent<{| "indexed-entity"| "snippet"| "document"- | "table";+ | "table"+ | "transform";}>;export type ErrorDiagnosticModalOpenedEvent = ValidateEvent<{diff --git a/frontend/src/metabase-types/api/activity.ts b/frontend/src/metabase-types/api/activity.tsindex e4c85d79843..f40079b5c42 100644--- a/frontend/src/metabase-types/api/activity.ts+++ b/frontend/src/metabase-types/api/activity.ts@@ -1,3 +1,5 @@+import type { OmniPickerItem } from "metabase/common/components/Pickers";+import type { CollectionId, CollectionType } from "./collection";import type { DashboardId } from "./dashboard";import type { DatabaseId, InitialSyncStatus } from "./database";@@ -79,7 +81,7 @@ export const isRecentTableItem = (item: RecentItem): item is RecentTableItem =>item.model === "table";export const isRecentCollectionItem = (- item: RecentItem,+ item: OmniPickerItem,): item is RecentCollectionItem =>["collection", "dashboard", "card", "dataset", "metric"].includes(item.model);diff --git a/frontend/src/metabase-types/api/bookmark.ts b/frontend/src/metabase-types/api/bookmark.tsindex dee42f6b0a6..60e901eee0d 100644--- a/frontend/src/metabase-types/api/bookmark.ts+++ b/frontend/src/metabase-types/api/bookmark.ts@@ -10,6 +10,7 @@ export const BOOKMARK_TYPES = ["dashboard","snippet","indexed-entity",+ "transform","document","table",] as const;diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.tsindex a63a875e9ca..0670496b29f 100644--- a/frontend/src/metabase-types/api/collection.ts+++ b/frontend/src/metabase-types/api/collection.ts@@ -20,6 +20,7 @@ export type CollectionNamespace =| null| "snippets"| "transforms"+ | "analytics"| "tenant-specific"| "shared-tenant-collection";@@ -118,6 +119,7 @@ export const COLLECTION_ITEM_MODELS = ["indexed-entity","document","table",+ "transform",] as const;export type CollectionItemModel = (typeof COLLECTION_ITEM_MODELS)[number];@@ -137,11 +139,12 @@ export interface CollectionItem {based_on_upload?: TableId | null; // only for modelscollection?: Collection | null;collection_id: CollectionId | null; // parent collection id+ namespace?: CollectionNamespace; // namespace of the item itselfcollection_namespace?: CollectionNamespace; // namespace of the parent collectiondisplay?: VisualizationDisplay;personal_owner_id?: UserId;database_id?: DatabaseId;- moderated_status?: string;+ moderated_status?: string | null;type?: CollectionType | CardType;here?: CollectionItemModel[];below?: CollectionItemModel[];@@ -150,7 +153,7 @@ export interface CollectionItem {can_delete?: boolean;can_run_adhoc_query?: boolean; // available only for data picker (#60021)"last-edit-info"?: LastEditInfo;- location?: string;+ location?: string | null;effective_location?: string;authority_level?: CollectionAuthorityLevel;dashboard_count?: number | null;@@ -285,6 +288,8 @@ type LibraryChild = {name: string;};-export type GetLibraryCollectionResponse =- | (CollectionItem & { effective_children: LibraryChild[] })- | { data: null };+export type LibraryCollection = CollectionItem & {+ effective_children: LibraryChild[];+};++export type GetLibraryCollectionResponse = LibraryCollection | { data: null };diff --git a/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsx b/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsxindex ff3c7348745..03993aff2c0 100644--- a/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsx+++ b/frontend/src/metabase/admin/datamodel/containers/SegmentApp.unit.spec.tsx@@ -41,7 +41,7 @@ const setup = ({ initialRoute = FORM_URL }: SetupOpts = {}) => {setupSearchEndpoints([]);setupCardDataset({data: {- rows: [[null]],+ rows: [[1, 2, 3]],},});setupRecentViewsAndSelectionsEndpoints([], ["selections"]);@@ -144,6 +144,8 @@ describe("SegmentApp", () => {await waitForLoaderToBeRemoved();+ await userEvent.click(await screen.findByText("Databases"));+ await userEvent.click(await screen.findByText("Sample Database"));await userEvent.click(await screen.findByText("Orders"));await waitForLoaderToBeRemoved();diff --git a/frontend/src/metabase/admin/settings/components/widgets/CustomHomepageDashboardSetting.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/widgets/CustomHomepageDashboardSetting.unit.spec.tsxindex 4299fcb0d55..67875b5b797 100644--- a/frontend/src/metabase/admin/settings/components/widgets/CustomHomepageDashboardSetting.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/CustomHomepageDashboardSetting.unit.spec.tsx@@ -3,6 +3,9 @@ import fetchMock from "fetch-mock";import {findRequests,+ setupCollectionByIdEndpoint,+ setupCollectionItemsEndpoint,+ setupCollectionsEndpoints,setupCurrentUserEndpoint,setupDashboardEndpoints,setupPropertiesEndpoints,@@ -10,9 +13,16 @@ import {setupSettingsEndpoints,setupUpdateSettingEndpoint,} from "__support__/server-mocks";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+} from "__support__/ui";import { UndoListing } from "metabase/common/components/UndoListing";import {+ createMockCollection,+ createMockCollectionItem,createMockDashboard,createMockRecentCollectionItem,createMockSettingDefinition,@@ -33,8 +43,43 @@ const setup = ("dismissed-custom-dashboard-toast": false,},) => {+ mockGetBoundingClientRect();const settings = createMockSettings(props);+ const collection = createMockCollection({+ id: 1,+ name: "Good Collection",+ });++ setupCollectionsEndpoints({+ collections: [collection],+ });++ setupCollectionByIdEndpoint({ collections: [collection] });+ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ model: "dashboard",+ id: 4242,+ can_write: true,+ name: "My dashboard",+ }),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: { id: 1 },+ collectionItems: [+ createMockCollectionItem({+ model: "dashboard",+ id: 4243,+ can_write: true,+ name: "My other dashboard",+ }),+ ],+ });+setupRecentViewsAndSelectionsEndpoints([createMockRecentCollectionItem({model: "dashboard",@@ -133,7 +178,8 @@ describe("CustomHomepageDashboardSetting", () => {"custom-homepage-dashboard": 4242,}),);- await userEvent.click(screen.getByText("My dashboard"));++ await userEvent.click(await screen.findByText(/My dashboard/));await waitFor(() => {// modal closesexpect(screen.queryByText("Choose a dashboard")).not.toBeInTheDocument();@@ -165,7 +211,7 @@ describe("CustomHomepageDashboardSetting", () => {const dashboardSelector = await screen.findByText("Pick a dashboard");await userEvent.click(dashboardSelector);- await userEvent.click(await screen.findByText("My dashboard"));+ await userEvent.click(await screen.findByText(/My dashboard/));await waitFor(() => {const calls = fetchMock.callHistory.calls();diff --git a/frontend/src/metabase/archive/components/ArchivedEntityBanner/ArchivedEntityBanner.tsx b/frontend/src/metabase/archive/components/ArchivedEntityBanner/ArchivedEntityBanner.tsxindex 648263cee98..88d4bdcf70a 100644--- a/frontend/src/metabase/archive/components/ArchivedEntityBanner/ArchivedEntityBanner.tsx+++ b/frontend/src/metabase/archive/components/ArchivedEntityBanner/ArchivedEntityBanner.tsx@@ -89,10 +89,10 @@ export const ArchivedEntityBanner = ({value={{ id: "root", model: "collection" }}onChange={(collection) => onMove?.(collection)}options={{- showSearch: true,+ hasSearch: true,hasConfirmButtons: true,- showRootCollection: true,- showPersonalCollections: true,+ hasRootCollection: true,+ hasPersonalCollections: true,confirmButtonText: t`Move`,}}onClose={() => setModal(null)}diff --git a/frontend/src/metabase/collections/analytics.ts b/frontend/src/metabase/collections/analytics.tsindex 44fc2390d64..1733d63c6ee 100644--- a/frontend/src/metabase/collections/analytics.ts+++ b/frontend/src/metabase/collections/analytics.ts@@ -15,8 +15,17 @@ export const trackCollectionBookmarked = () => {});};-export const trackCollectionItemBookmarked = (item: CollectionItem) => {- if (item.model === "indexed-entity" || item.model === "snippet") {+export const trackCollectionItemBookmarked = (+ item: CollectionItem & {+ model: CollectionItem["model"];+ },+) => {+ if (+ item.model === "indexed-entity" ||+ item.model === "snippet" ||+ item.model === "transform"+ ) {+ // can't bookmark thesereturn;}diff --git a/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.tsx b/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.tsxindex 8231a9f028c..3b3510504a6 100644--- a/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.tsx+++ b/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.tsx@@ -125,7 +125,8 @@ function ActionMenu({if (!isBookmarked) {trackCollectionItemBookmarked(item);}- toggleBookmark?.(item.id.toString(), normalizeItemModel(item));+ const normalizedModel = normalizeItemModel(item);+ toggleBookmark?.(item.id.toString(), normalizedModel);};return handler;}, [createBookmark, deleteBookmark, isBookmarked, item]);diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsxindex d84e59bfed8..289e2569da9 100644--- a/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/CollectionBulkActions.tsx@@ -5,8 +5,8 @@ import _ from "underscore";import CollectionCopyEntityModal from "metabase/collections/components/CollectionCopyEntityModal";import { isTrashedCollection } from "metabase/collections/utils";import { BulkActionBar } from "metabase/common/components/BulkActionBar";-import { BulkMoveModal } from "metabase/common/components/MoveModal";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";+import { BulkMoveModal } from "metabase/common/components/Pickers/MoveModal/MoveModal";import type { Collection, CollectionItem } from "metabase-types/api";import { ArchivedBulkActions } from "./ArchivedBulkActions";@@ -122,7 +122,7 @@ export const CollectionBulkActions = memo(// This is a little cheeky, but by virtue of the screens we show the BulkMoveModal, all// selected items should have the same collection id. yatta!- const recentAndSearchFilter = (item: CollectionPickerItem) =>+ const recentAndSearchFilter = (item: OmniPickerItem) =>item.model === "collection" && item.id === collection.id;return (diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsxindex 212d52fe25f..78b2aa3b624 100644--- a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx@@ -7,13 +7,15 @@ import * as Yup from "yup";import { skipToken, useGetCollectionQuery } from "metabase/api";import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker";import { Button } from "metabase/common/components/Button";-import type { FilterItemsInPersonalCollection } from "metabase/common/components/EntityPicker";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 { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import type {+ FilterItemsInPersonalCollection,+ OmniPickerItem,+} from "metabase/common/components/Pickers";import { Collections } from "metabase/entities/collections";import { Form, FormProvider } from "metabase/forms";import * as Errors from "metabase/lib/errors";@@ -101,7 +103,7 @@ function CreateCollectionForm({);const [selectedParentCollection, setSelectedParentCollection] =- useState<CollectionPickerItem | null>(null);+ useState<OmniPickerItem | null>(null);return (<FormProvider@@ -113,9 +115,10 @@ function CreateCollectionForm({const parentCollection = selectedParentCollection ?? initialCollection;// Hide the authority level picker if the parent is a tenant collection.- const isParentTenantCollection = parentCollection- ? PLUGIN_TENANTS.isTenantCollection(parentCollection)- : false;+ const isParentTenantCollection =+ parentCollection && "namespace" in parentCollection+ ? PLUGIN_TENANTS.isTenantCollection(parentCollection)+ : false;return (<Form>@@ -138,7 +141,6 @@ function CreateCollectionForm({title={t`Collection it's saved in`}filterPersonalCollections={filterPersonalCollections}entityType="collection"- savingModel="collection"onCollectionSelect={setSelectedParentCollection}/>)}diff --git a/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx b/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsxindex d7fd3506a64..87ad7b083ff 100644--- a/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx+++ b/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx@@ -6,8 +6,7 @@ import type {OnMoveWithSourceAndDestination,} from "metabase/collections/types";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { MoveModal } from "metabase/common/components/MoveModal";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import { MoveModal } from "metabase/common/components/Pickers/MoveModal/MoveModal";import { useCollectionQuery } from "metabase/common/hooks";import { Collections } from "metabase/entities/collections";import { useDispatch } from "metabase/lib/redux";@@ -33,20 +32,20 @@ const MoveCollectionModalView = ({[collection, onMove, onClose],);- const recentsAndSearchFilter = (item: CollectionPickerItem) =>- item.model === "collection" && item.id === collection.parent_id;-return (<MoveModaltitle={t`Move "${collection.name}"?`}- initialCollectionId={collection.parent_id ?? "root"}- movingCollectionId={collection.id}- movingCollectionNamespace={collection.namespace ?? undefined}- entityType="collection"+ movingItem={{+ ...collection,+ collection: {+ id: collection.parent_id || "root ",+ name: "",+ namespace: collection.namespace,+ }, // parent collection info+ model: "collection",+ }}onMove={handleMove}onClose={onClose}- recentAndSearchFilter={recentsAndSearchFilter}- savingModel="collection"/>);};diff --git a/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsx b/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsxindex c52e9242581..18350858f68 100644--- a/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsx+++ b/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsx@@ -11,14 +11,18 @@ import {isValidCollectionId,} from "metabase/collections/utils";import { CollectionName } from "metabase/common/components/CollectionName";-import type { FilterItemsInPersonalCollection } from "metabase/common/components/EntityPicker";import { FormField } from "metabase/common/components/FormField";+import type {+ EntityPickerOptions,+ EntityPickerProps,+ FilterItemsInPersonalCollection,+ OmniPickerItem,+ OmniPickerValue,+} from "metabase/common/components/Pickers";import {- type CollectionPickerItem,CollectionPickerModal,- type CollectionPickerModalProps,- type CollectionPickerOptions,-} from "metabase/common/components/Pickers/CollectionPicker";+ isInDbTree,+} from "metabase/common/components/Pickers";import { SnippetCollectionName } from "metabase/common/components/SnippetCollectionName";import { useUniqueId } from "metabase/common/hooks/use-unique-id";import { Collections } from "metabase/entities/collections";@@ -66,7 +70,6 @@ function ItemName({</Flex>);}-interface FormCollectionPickerProps extends HTMLAttributes<HTMLDivElement> {collectionIdFieldName: string;dashboardIdFieldName: string;@@ -79,12 +82,7 @@ interface FormCollectionPickerProps extends HTMLAttributes<HTMLDivElement> {filterPersonalCollections?: FilterItemsInPersonalCollection;entityType?: EntityType;zIndex?: number;- collectionPickerModalProps?: Partial<CollectionPickerModalProps>;- /**- * When set to "collection", allows saving to namespace root collections- * (like tenant root). When null/undefined, namespace roots are disabled.- */- savingModel?: "collection" | null;+ collectionPickerModalProps?: Partial<EntityPickerProps>;}export function FormCollectionAndDashboardPicker({@@ -99,7 +97,6 @@ export function FormCollectionAndDashboardPicker({dashboardIdFieldName,dashboardTabIdFieldName,entityType,- savingModel,}: FormCollectionPickerProps) {const id = useUniqueId();@@ -117,10 +114,6 @@ export function FormCollectionAndDashboardPicker({? t`Select a collection or dashboard`: t`Select a collection`;- const pickerValue = dashboardIdInput.value- ? ({ id: dashboardIdInput.value, model: "dashboard" } as const)- : ({ id: collectionIdInput.value, model: "collection" } as const);-const touched = dashboardIdMeta.touched || collectionIdMeta.touched;const error = dashboardIdMeta.error || collectionIdMeta.error;@@ -142,6 +135,12 @@ export function FormCollectionAndDashboardPicker({}),);+ const namespace = selectedItem?.namespace;++ const pickerValue: OmniPickerValue = dashboardIdInput.value+ ? { id: dashboardIdInput.value, model: "dashboard", namespace }+ : { id: collectionIdInput.value, model: "collection", namespace };+useEffect(function preventUsingArchivedItem() {if (@@ -160,35 +159,31 @@ export function FormCollectionAndDashboardPicker({filterPersonalCollections !== "only" ||isOpenCollectionInPersonalCollection;- const options = useMemo<CollectionPickerOptions>(+ const options = useMemo<EntityPickerOptions>(() => ({- showPersonalCollections: filterPersonalCollections !== "exclude",- showRootCollection: filterPersonalCollections !== "only",+ hasPersonalCollections: filterPersonalCollections !== "exclude",+ hasRootCollection: filterPersonalCollections !== "only",// Search API doesn't support collection namespaces yet- showSearch: type === "collections",- hasConfirmButtons: true,- namespace: type === "snippet-collections" ? "snippets" : undefined,- allowCreateNew: showCreateNewCollectionOption,+ hasSearch: type === "collections",hasRecents: type !== "snippet-collections",+ hasConfirmButtons: true,+ namespaces: type === "snippet-collections" ? ["snippets"] : undefined,+ canCreateCollections: showCreateNewCollectionOption,confirmButtonText: (item) =>- item === "dashboard"+ item?.model === "dashboard"? t`Select this dashboard`: t`Select this collection`,- savingModel,}),- [- filterPersonalCollections,- type,- showCreateNewCollectionOption,- savingModel,- ],+ [filterPersonalCollections, type, showCreateNewCollectionOption],);const [fetchDashboard] = useLazyGetDashboardQuery();const handleChange = useCallback(- async (item: CollectionPickerItem) => {- const { id, collection_id, model } = item;+ async (item: OmniPickerItem) => {+ const { id, model } = item;+ const collection_id = isInDbTree(item) ? undefined : item.collection?.id;+collectionIdHelpers.setValue(canonicalCollectionId(model === "dashboard" ? collection_id : id),);diff --git a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsxindex c8bbb39cbdd..2ba38e0a443 100644--- a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx+++ b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx@@ -10,14 +10,14 @@ import {isValidCollectionId,} from "metabase/collections/utils";import { CollectionName } from "metabase/common/components/CollectionName";-import type { FilterItemsInPersonalCollection } from "metabase/common/components/EntityPicker";import { FormField } from "metabase/common/components/FormField";-import {- type CollectionPickerItem,- CollectionPickerModal,- type CollectionPickerModalProps,- type CollectionPickerOptions,-} from "metabase/common/components/Pickers/CollectionPicker";+import type {+ EntityPickerOptions,+ EntityPickerProps,+ FilterItemsInPersonalCollection,+ 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";@@ -27,51 +27,37 @@ import { PLUGIN_TENANTS } from "metabase/plugins";import { Button, Icon } from "metabase/ui";import type { CollectionId, CollectionNamespace } from "metabase-types/api";-const NAMESPACE_BY_TYPE: Record<string, "snippets" | "transforms"> = {- "snippet-collections": "snippets",- "transform-collections": "transforms",-};-interface FormCollectionPickerProps extends HTMLAttributes<HTMLDivElement> {name: string;title?: string;placeholder?: string;- type?: "collections" | "snippet-collections" | "transform-collections";initialOpenCollectionId?: CollectionId;onOpenCollectionChange?: (collectionId: CollectionId) => void;filterPersonalCollections?: FilterItemsInPersonalCollection;entityType?: EntityType;- collectionPickerModalProps?: Partial<CollectionPickerModalProps>;- onCollectionSelect?: (collection: CollectionPickerItem) => void;- /**- * When set to "collection", allows saving to namespace root collections- * (like tenant root). When null/undefined, namespace roots are disabled.- */- savingModel?: "collection" | null;+ collectionPickerModalProps?: Partial<EntityPickerProps>;+ onCollectionSelect?: (collection: OmniPickerItem) => void;}function ItemName({id,- type = "collections",namespace = null,}: {id: CollectionId;- type?: "collections" | "snippet-collections" | "transform-collections";- namespace?: string | null;+ namespace: CollectionNamespace;}) {- if (type === "snippet-collections") {+ if (namespace === "snippets") {return <SnippetCollectionName id={id} />;}- if (type === "transform-collections") {+ if (namespace === "transforms") {return <TransformCollectionName id={id} />;}// Check for tenant namespace display name via pluginif (id === null) {- const namespaceDisplayName = PLUGIN_TENANTS.getNamespaceDisplayName(- namespace as CollectionNamespace,- );+ const namespaceDisplayName =+ PLUGIN_TENANTS.getNamespaceDisplayName(namespace);if (namespaceDisplayName) {return <span>{namespaceDisplayName}</span>;}@@ -86,19 +72,14 @@ function FormCollectionPicker({name,title,placeholder = t`Select a collection`,- type = "collections",filterPersonalCollections,entityType,collectionPickerModalProps,- savingModel,onCollectionSelect,}: FormCollectionPickerProps) {const id = useUniqueId();const [{ value }, { error, touched }, { setValue }] = useField(name);- const [collectionNamespace, setCollectionNamespace] = useState<string | null>(- null,- );const formFieldRef = useRef<HTMLDivElement>(null);const [isPickerOpen, setIsPickerOpen] = useState(false);@@ -117,6 +98,13 @@ function FormCollectionPicker({}),);+ const [collectionNamespace, setCollectionNamespace] =+ useState<CollectionNamespace>(+ selectedCollection?.namespace ??+ collectionPickerModalProps?.namespaces?.[0] ??+ null,+ );+useEffect(function preventUsingArchivedCollection() {if (selectedCollection && isTrashedCollection(selectedCollection)) {@@ -131,33 +119,36 @@ function FormCollectionPicker({filterPersonalCollections !== "only" ||isOpenCollectionInPersonalCollection;- const namespace = NAMESPACE_BY_TYPE[type];+ const nonDefaultNamespace =+ collectionPickerModalProps?.namespaces?.[0] ?? null;- const options = useMemo<CollectionPickerOptions>(+ const options = useMemo<EntityPickerOptions>( // FIXME, this should throw more type errors 🤔() => ({- showPersonalCollections:- !namespace && filterPersonalCollections !== "exclude",- showRootCollection: !!namespace || filterPersonalCollections !== "only",- showSearch: !namespace,+ hasPersonalCollections:+ !nonDefaultNamespace && filterPersonalCollections !== "exclude",+ hasRootCollection:+ !!nonDefaultNamespace || filterPersonalCollections !== "only",+ hasSearch: !nonDefaultNamespace,+ hasRecents: !nonDefaultNamespace,+ hasLibrary: !nonDefaultNamespace,hasConfirmButtons: true,- namespace,- allowCreateNew: showCreateNewCollectionOption,- hasRecents: !namespace,- showLibrary: !namespace,- savingModel,+ canCreateCollections: showCreateNewCollectionOption,}),[filterPersonalCollections,- namespace,showCreateNewCollectionOption,- savingModel,+ nonDefaultNamespace,],);const handleChange = useCallback(- (collection: CollectionPickerItem) => {+ (collection: OmniPickerItem) => {onCollectionSelect?.(collection);- setCollectionNamespace(collection.namespace ?? null);+ if ("namespace" in collection) {+ setCollectionNamespace(collection.namespace ?? null);+ } else {+ setCollectionNamespace(null);+ }setValue(canonicalCollectionId(collection.id));setIsPickerOpen(false);},@@ -188,7 +179,7 @@ function FormCollectionPicker({}}>{isValidCollectionId(value) ? (- <ItemName id={value} type={type} namespace={collectionNamespace} />+ <ItemName id={value} namespace={collectionNamespace} />) : (placeholder)}@@ -197,7 +188,11 @@ function FormCollectionPicker({{isPickerOpen && (<CollectionPickerModaltitle={t`Select a collection`}- value={{ id: value, model: "collection" }}+ value={{+ id: value,+ model: "collection",+ namespace: collectionNamespace,+ }}onChange={handleChange}onClose={() => setIsPickerOpen(false)}options={options}diff --git a/frontend/src/metabase/collections/utils.ts b/frontend/src/metabase/collections/utils.tsindex dc15423e7a5..e1ed5201ea3 100644--- a/frontend/src/metabase/collections/utils.ts+++ b/frontend/src/metabase/collections/utils.ts@@ -191,7 +191,7 @@ export function isItemMetric(item: CollectionItem) {return item.model === "metric";}-export function isItemCollection(item: CollectionItem) {+export function isItemCollection(item: Pick<CollectionItem, "model">) {return item.model === "collection";}diff --git a/frontend/src/metabase/common/components/DashboardSelector/DashboardSelector.tsx b/frontend/src/metabase/common/components/DashboardSelector/DashboardSelector.tsxindex 14cf8965acb..034ce1475d9 100644--- a/frontend/src/metabase/common/components/DashboardSelector/DashboardSelector.tsx+++ b/frontend/src/metabase/common/components/DashboardSelector/DashboardSelector.tsx@@ -3,10 +3,7 @@ import { t } from "ttag";import { skipToken, useGetDashboardQuery } from "metabase/api";import { getErrorMessage } from "metabase/api/utils";-import {- DashboardPickerModal,- type DashboardPickerValueItem,-} from "metabase/common/components/Pickers/DashboardPicker";+import { DashboardPickerModal } from "metabase/common/components/Pickers/DashboardPicker";import { Flex, Group, Icon } from "metabase/ui";import type { DashboardId } from "metabase-types/api";@@ -66,19 +63,17 @@ export const DashboardSelector = ({</DashboardPickerButton>{isOpen && (<DashboardPickerModal- title={t`Choose a dashboard`}value={dashboard?.id ? { model: "dashboard", id: dashboard.id } : undefined}- onChange={(dashboard: DashboardPickerValueItem) => {+ onChange={(dashboard) => {onChange(dashboard.id);setIsOpen(false);}}onClose={() => setIsOpen(false)}options={{- showPersonalCollections: false,- showRootCollection: true,- allowCreateNew: false,+ hasPersonalCollections: false,+ hasRootCollection: true,hasConfirmButtons: false,}}/>diff --git a/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/AutoScrollBox.styled.tsx b/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/AutoScrollBox.styled.tsxdeleted file mode 100644index 749893cf259..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/AutoScrollBox.styled.tsx+++ /dev/null@@ -1,12 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";-import type React from "react";--import type { BoxProps } from "metabase/ui";-import { Box } from "metabase/ui";--export const HorizontalScrollBox = styled(Box)<- BoxProps & React.HTMLProps<HTMLDivElement>->`- overflow-x: auto;-` as unknown as typeof Box;diff --git a/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/index.tsdeleted file mode 100644index c9e92f7bff5..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./AutoScrollBox";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/ButtonBar.tsx b/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/ButtonBar.tsxdeleted file mode 100644index f1ce4d232ef..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/ButtonBar.tsx+++ /dev/null@@ -1,81 +0,0 @@-import { useEffect, useState } from "react";-import { t } from "ttag";--import { getErrorMessage } from "metabase/api/utils";-import { Button, Flex, Text } from "metabase/ui";--export const ButtonBar = ({- onConfirm,- onCancel,- canConfirm,- actionButtons,- confirmButtonText,- cancelButtonText,-}: {- onConfirm: () => void;- onCancel: () => void;- canConfirm?: boolean;- actionButtons: JSX.Element[];- confirmButtonText?: string;- cancelButtonText?: string;-}) => {- const [error, setError] = useState<string | null>(null);- const [loading, setLoading] = useState(false);-- useEffect(() => {- const handleKeyPress = (e: KeyboardEvent) => {- if (e.isComposing) {- return;- }- if (canConfirm && e.key === "Enter") {- onConfirm();- }- };- document.addEventListener("keypress", handleKeyPress);- return () => {- document.removeEventListener("keypress", handleKeyPress);- };- }, [canConfirm, onConfirm]);-- return (- <Flex- justify="space-between"- align="center"- p="md"- style={{- borderTop: "1px solid var(--mb-color-border)",- }}- >- <Flex gap="md">{actionButtons}</Flex>- {error && (- <Text color="error" px="md" lh="1rem">- {error}- </Text>- )}- <Flex gap="md">- <Button onClick={onCancel} type="button">- {cancelButtonText ?? t`Cancel`}- </Button>- <Button- ml={1}- variant="filled"- onClick={async () => {- try {- setError(null);- setLoading(true);- await onConfirm();- } catch (e: any) {- console.error(e);- setError(getErrorMessage(e));- }- setLoading(false);- }}- disabled={!canConfirm || loading}- data-testid="entity-picker-select-button"- >- {confirmButtonText ?? t`Select`}- </Button>- </Flex>- </Flex>- );-};diff --git a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntityPickerModal.tsx b/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntityPickerModal.tsxdeleted file mode 100644index 516baf9756b..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntityPickerModal.tsx+++ /dev/null@@ -1,540 +0,0 @@-import { useWindowEvent } from "@mantine/hooks";-import {- type ReactNode,- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from "react";-import { useDebounce, usePreviousDistinct } from "react-use";-import { t } from "ttag";--import ErrorBoundary from "metabase/ErrorBoundary";-import { useListRecentsQuery, useSearchQuery } from "metabase/api";-import { useModalOpen } from "metabase/common/hooks/use-modal-open";-import { useUniqueId } from "metabase/common/hooks/use-unique-id";-import resizeObserver from "metabase/lib/resize-observer";-import {- Box,- Flex,- Icon,- Modal,- Repeat,- Skeleton,- TextInput,-} from "metabase/ui";-import type {- RecentContexts,- RecentItem,- SearchModel,- SearchRequest,- SearchResult,- SearchResultId,-} from "metabase-types/api";--import { RECENTS_TAB_ID, SEARCH_TAB_ID } from "../../constants";-import { useScopedSearchResults } from "../../hooks";-import type {- EntityPickerOptions,- EntityPickerSearchScope,- EntityPickerTab,- EntityPickerTabId,- TabFolderState,- TypeWithModel,-} from "../../types";-import {- computeInitialTabId,- getSearchFolderModels,- getSearchInputPlaceholder,- getSearchModels,- getSearchTabText,- isSearchFolder,-} from "../../utils";-import { RecentsTab } from "../RecentsTab";-import { SearchTab } from "../SearchTab";--import { ButtonBar } from "./ButtonBar";-import S from "./EntitityPickerModal.module.css";-import { TabsView } from "./TabsView";--export type EntityPickerModalOptions = {- showSearch?: boolean;- hasConfirmButtons?: boolean;- confirmButtonText?: string | ((model?: string) => string);- cancelButtonText?: string;- hasRecents?: boolean;- showDatabases?: boolean;- showLibrary?: boolean;-};--export const defaultOptions: EntityPickerModalOptions = {- showSearch: true,- hasConfirmButtons: true,- hasRecents: true,- showLibrary: true,-};--export const DEFAULT_RECENTS_CONTEXT: RecentContexts[] = [- "selections",- "views",-];--const DEFAULT_RECENTS_FILTER = (item: RecentItem[]) => item;--const DEFAULT_SEARCH_RESULT_FILTER = (results: SearchResult[]) => results;--export interface EntityPickerModalProps<- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> {- title?: string;- selectedItem: Item | null;- initialValue?: Partial<Item>;- canSelectItem: boolean;- tabs: EntityPickerTab<Id, Model, Item>[];- options?: Partial<EntityPickerOptions>;- searchResultFilter?: (results: SearchResult[]) => SearchResult[];- recentFilter?: (results: RecentItem[]) => RecentItem[];- searchParams?: Partial<SearchRequest>;- actionButtons?: JSX.Element[];- trapFocus?: boolean;- /**defaultToRecentTab: If set to true, will initially show the recent tab when the modal appears. If set to false, it will show the tab- * with the same model as the initialValue. Defaults to true. */- defaultToRecentTab?: boolean;- /**recentsContext: Defaults to returning recents based off both views and selections. Can be overridden by props */- recentsContext?: RecentContexts[];- onClose: () => void;- onConfirm?: () => void;- onItemSelect: (item: Item) => void;- isLoadingTabs?: boolean;- searchExtraButtons?: ReactNode[];- children?: ReactNode;- disableCloseOnEscape?: boolean;- searchModels?: (SearchModel | "table")[];-}--export function EntityPickerModal<- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->({- title = t`Choose an item`,- canSelectItem,- selectedItem,- initialValue,- tabs: passedTabs,- options,- actionButtons = [],- searchResultFilter = DEFAULT_SEARCH_RESULT_FILTER,- recentFilter = DEFAULT_RECENTS_FILTER,- trapFocus = true,- searchParams,- defaultToRecentTab = true,- recentsContext = DEFAULT_RECENTS_CONTEXT,- onClose,- onConfirm,- onItemSelect,- isLoadingTabs = false,- disableCloseOnEscape = false,- children,- searchModels: _searchModels,-}: EntityPickerModalProps<Id, Model, Item>) {- const [modalContentMinWidth, setModalContentMinWidth] = useState(920);- const modalContentRef = useRef<HTMLDivElement | null>(null);- const [searchQuery, setSearchQuery] = useState<string>("");- const [searchScope, setSearchScope] =- useState<EntityPickerSearchScope>("everywhere");- const { data: recentItems, isLoading: isLoadingRecentItems } =- useListRecentsQuery(- { context: recentsContext },- {- refetchOnMountOrArgChange: true,- },- );- const searchModels = useMemo(- () => _searchModels || getSearchModels(passedTabs),- [passedTabs, _searchModels],- );-- const folderModels = useMemo(- () => getSearchFolderModels(passedTabs),- [passedTabs],- );- const [selectedTabId, setSelectedTabId] = useState<EntityPickerTabId>("");- const previousTabId = usePreviousDistinct(selectedTabId);- const [tabFolderState, setTabFolderState] = useState<- TabFolderState<Id, Model, Item>- >({});- const selectedFolder =- tabFolderState[- selectedTabId === SEARCH_TAB_ID- ? (previousTabId ?? selectedTabId)- : selectedTabId- ];- const scopedSearchResults = useScopedSearchResults(- searchQuery,- searchModels,- searchScope,- selectedFolder,- );- const hydratedOptions = useMemo(- () => ({ ...defaultOptions, ...options }),- [options],- );-- assertValidProps(hydratedOptions, onConfirm);-- const { open } = useModalOpen();-- const [debouncedSearchQuery, setDebouncedSearchQuery] = useState(searchQuery);- useDebounce(() => setDebouncedSearchQuery(searchQuery), 200, [searchQuery]);-- const { data, isFetching, requestId } = useSearchQuery(- {- q: debouncedSearchQuery,- models: searchModels,- context: "entity-picker",- ...searchParams,- },- {- skip: !debouncedSearchQuery || searchScope === "folder",- },- );-- const finalSearchResults = useMemo(() => {- if (searchScope === "folder") {- if (!scopedSearchResults) {- return null;- }- return searchResultFilter(scopedSearchResults as SearchResult[]);- } else {- if (isFetching || !data) {- return null;- }- return searchResultFilter(data.data);- }- }, [searchScope, scopedSearchResults, isFetching, data, searchResultFilter]);-- const filteredRecents = useMemo(() => {- if (!recentItems) {- return [];- }-- const relevantModelRecents = recentItems.filter((recentItem) => {- return searchModels.includes(recentItem.model);- });-- return recentFilter(relevantModelRecents);- }, [recentItems, recentFilter, searchModels]);-- const tabs: EntityPickerTab<Id, Model, Item>[] = useMemo(- function getTabs() {- const computedTabs: EntityPickerTab<Id, Model, Item>[] = [];- const hasRecentsTab =- hydratedOptions.hasRecents && filteredRecents.length > 0;- const hasSearchTab = !!searchQuery;- // This is to prevent different tab being initially open and then flickering back- // to recents tab once recents have loaded (due to computeInitialTab)- const shouldOptimisticallyAddRecentsTabWhileLoading =- defaultToRecentTab && isLoadingRecentItems;-- if (hasRecentsTab || shouldOptimisticallyAddRecentsTabWhileLoading) {- computedTabs.push({- id: RECENTS_TAB_ID,- models: [],- folderModels: [],- displayName: t`Recents`,- icon: "clock",- render: ({ onItemSelect }) => (- <RecentsTab- isLoading={isLoadingRecentItems}- recentItems={filteredRecents}- selectedItem={selectedItem}- onItemSelect={onItemSelect}- />- ),- });- }-- computedTabs.push(...passedTabs);-- if (hasSearchTab) {- computedTabs.push({- id: SEARCH_TAB_ID,- models: [],- folderModels: [],- displayName: getSearchTabText(finalSearchResults, searchQuery),- icon: "search",- render: ({ onItemSelect }) => (- <SearchTab- folder={selectedFolder}- isLoading={isFetching}- searchScope={searchScope}- searchResults={finalSearchResults ?? []}- searchEngine={data?.engine}- searchRequestId={requestId}- searchTerm={searchQuery}- selectedItem={selectedItem}- onItemSelect={onItemSelect}- onSearchScopeChange={setSearchScope}- />- ),- });- }-- return computedTabs;- },- [- data?.engine,- defaultToRecentTab,- filteredRecents,- finalSearchResults,- hydratedOptions.hasRecents,- isFetching,- isLoadingRecentItems,- passedTabs,- requestId,- searchQuery,- searchScope,- selectedFolder,- selectedItem,- ],- );-- const hasTabs = tabs.length > 1;- const initialTabId = useMemo(- () => computeInitialTabId({ initialValue, tabs, defaultToRecentTab }),- [initialValue, tabs, defaultToRecentTab],- );- // we don't want to show bonus actions on recents or search tabs- const showActionButtons = ![SEARCH_TAB_ID, RECENTS_TAB_ID].includes(- selectedTabId,- );-- const handleSelectItem = useCallback(- (item: Item, tabId: EntityPickerTabId) => {- if (tabId !== SEARCH_TAB_ID && tabId !== RECENTS_TAB_ID) {- if (isSearchFolder(item, folderModels)) {- setTabFolderState((state) => ({ ...state, [tabId]: item }));- setSearchScope("folder");- } else {- setTabFolderState((state) => ({ ...state, [tabId]: undefined }));- setSearchScope("everywhere");- }- }-- onItemSelect(item);- },- [folderModels, onItemSelect],- );-- const handleTabChange = useCallback(- (tabId: EntityPickerTabId) => {- setSelectedTabId(tabId);- if (tabId !== SEARCH_TAB_ID) {- setSearchScope(tabFolderState[tabId] ? "folder" : "everywhere");- }- },- [tabFolderState],- );-- const handleQueryChange = useCallback(- (newSearchQuery: string) => {- setSearchQuery(newSearchQuery);-- // automatically switch to search tab- if (newSearchQuery) {- handleTabChange(SEARCH_TAB_ID);-- if (!searchQuery) {- setSearchScope(selectedFolder ? "folder" : "everywhere");- }- }-- // restore previous tab when clearing search while on search tab- if (searchQuery && !newSearchQuery && selectedTabId === SEARCH_TAB_ID) {- handleTabChange(previousTabId ?? initialTabId);- }- },- [- selectedFolder,- searchQuery,- selectedTabId,- previousTabId,- initialTabId,- handleTabChange,- ],- );-- useEffect(() => {- setSelectedTabId(initialTabId);- }, [initialTabId]);-- useWindowEvent(- "keydown",- (event) => {- if (event.key === "Escape") {- event.stopPropagation();- !disableCloseOnEscape && onClose();- }- },- { capture: true },- );-- const titleId = useUniqueId("entity-picker-modal-title-");-- const modalContentResizeHandler = useCallback(- (entry: ResizeObserverEntry) => {- const width = entry.contentRect.width;- setModalContentMinWidth((currentWidth) =>- currentWidth < width ? width : currentWidth,- );- },- [],- );-- const modalContentCallbackRef = useCallback(- (element: HTMLDivElement | null) => {- if (element) {- resizeObserver.subscribe(element, modalContentResizeHandler);- modalContentRef.current = element;- } else {- if (modalContentRef.current) {- resizeObserver.unsubscribe(- modalContentRef.current,- modalContentResizeHandler,- );- }- }- },- [modalContentResizeHandler],- );-- return (- <Modal.Root- opened={open}- onClose={onClose}- data-testid="entity-picker-modal"- /**- * Both children of this component have "position: fixed" so the element's height is 0 by default.- * This makes the following assertion to fail in Cypress:- * cy.findByTestId("entity-picker-modal").should("be.visible");- * Height is specified here to make that assertion pass.- */- h="100vh"- w="100vw"- trapFocus={trapFocus}- closeOnEscape={false} // we're doing this manually in useWindowEvent- yOffset="10dvh"- >- <Modal.Overlay />- <Modal.Content- className={S.modalContent}- aria-labelledby={titleId}- miw={`min(${modalContentMinWidth}px, 80vw)`}- w="fit-content"- maw="80vw"- ref={modalContentCallbackRef}- >- <Modal.Header- px="2.5rem"- pt="1rem"- pb={hasTabs ? "1rem" : "1.5rem"}- bg="background-primary"- >- <Modal.Title id={titleId} lh="2.5rem">- {title}- </Modal.Title>- <Modal.CloseButton size={21} pos="relative" top="1px" />- </Modal.Header>- <Modal.Body className={S.modalBody} p="0">- {hydratedOptions.showSearch && (- <Box px="2.5rem" mb="1.5rem">- <TextInput- classNames={{ input: S.textInput }}- data-autofocus- type="search"- leftSection={<Icon name="search" size={16} />}- miw={400}- placeholder={getSearchInputPlaceholder(selectedFolder)}- value={searchQuery}- onChange={(e) => handleQueryChange(e.target.value ?? "")}- />- </Box>- )}- {!isLoadingTabs && !isLoadingRecentItems ? (- <ErrorBoundary>- {hasTabs ? (- <TabsView- selectedTabId={selectedTabId}- tabs={tabs}- onItemSelect={handleSelectItem}- onTabChange={handleTabChange}- />- ) : (- <div- className={S.singlePickerView}- data-testid="single-picker-view"- >- {tabs[0]?.render({- onItemSelect: (item) => handleSelectItem(item, tabs[0].id),- }) ?? null}- </div>- )}- {!!hydratedOptions.hasConfirmButtons && onConfirm && (- <ButtonBar- onConfirm={onConfirm}- onCancel={onClose}- canConfirm={canSelectItem}- actionButtons={showActionButtons ? actionButtons : []}- confirmButtonText={- typeof options?.confirmButtonText === "function"- ? options.confirmButtonText(selectedItem?.model)- : options?.confirmButtonText- }- cancelButtonText={options?.cancelButtonText}- />- )}- </ErrorBoundary>- ) : (- <EntityPickerLoadingSkeleton />- )}- {children}- </Modal.Body>- </Modal.Content>- </Modal.Root>- );-}--const assertValidProps = (- options: EntityPickerModalOptions,- onConfirm: (() => void) | undefined,-) => {- if (options.hasConfirmButtons && !onConfirm) {- throw new Error(- "onConfirm prop is required when hasConfirmButtons is true",- );- }-};--const EntityPickerLoadingSkeleton = () => (- <Box data-testid="loading-indicator" className={S.loadingSkeleton}>- <Flex px="2rem" gap="1.5rem" mb="3.5rem">- <Repeat times={3}>- <Skeleton h="2rem" w="5rem" mb="0.5rem" />- </Repeat>- </Flex>- <Flex px="2rem" mb="2.5rem" direction="column">- <Repeat times={2}>- <Skeleton h="3rem" mb="0.5rem" />- </Repeat>- </Flex>- <Flex px="2rem" direction="column">- <Repeat times={3}>- <Skeleton h="3rem" mb="0.5rem" />- </Repeat>- </Flex>- </Box>-);diff --git a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntityPickerModal.unit.spec.tsx b/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntityPickerModal.unit.spec.tsxdeleted file mode 100644index cb09693c148..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntityPickerModal.unit.spec.tsx+++ /dev/null@@ -1,496 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { setupRecentViewsAndSelectionsEndpoints } from "__support__/server-mocks";-import {- mockGetBoundingClientRect,- renderWithProviders,- screen,- within,-} from "__support__/ui";-import { Button } from "metabase/ui";-import type { RecentItem } from "metabase-types/api";-import {- createMockRecentCollectionItem,- createMockRecentTableItem,- createMockSearchResult,- createMockSearchResults,-} from "metabase-types/api/mocks";--import type { EntityPickerTab, TypeWithModel } from "../../types";--import type { EntityPickerModalOptions } from "./EntityPickerModal";-import { EntityPickerModal } from "./EntityPickerModal";--type SampleId = number;-type SampleModel = "card" | "table" | "collection";-type SampleItem = TypeWithModel<SampleId, SampleModel>;-type SampleTab = EntityPickerTab<SampleId, SampleModel, SampleItem>;--interface SetupOpts {- title?: string;- onItemSelect?: () => void;- onClose?: () => void;- onConfirm?: () => void;- tabs?: SampleTab[];- options?: EntityPickerModalOptions;- selectedItem?: SampleItem | null;- actionButtons?: JSX.Element[];- recentFilter?: (item: RecentItem[]) => RecentItem[];- recentItems?: RecentItem[];- defaultToRecentTab?: boolean;- initialValue?: { model: SampleModel };- searchDelay?: number;- recentsDelay?: number;- isLoadingTabs?: boolean;-}--const TestPicker = ({ name }: { name: string }) => (- <p>{`Test picker ${name}`}</p>-);--const TEST_CARD_TAB: SampleTab = {- id: "cards-tab",- icon: "audit",- displayName: "All the foo",- models: ["card"],- folderModels: ["collection" as const],- render: () => <TestPicker name="foo" />,-};--const TEST_TABLE_TAB: SampleTab = {- id: "tables-tab",- icon: "audit",- displayName: "All the bar",- models: ["table"],- folderModels: ["collection" as const],- render: () => <TestPicker name="bar" />,-};--const mockSearchResults = createMockSearchResults({- items: [- createMockSearchResult({- name: "Search Result 1",- model: "collection",- can_write: true,- id: 100,- }),- createMockSearchResult({- name: "Search Result 2",- model: "collection",- can_write: true,- id: 101,- }),- ],-});--const setup = ({- onItemSelect = jest.fn(),- onClose = jest.fn(),- onConfirm = jest.fn(),- tabs = [TEST_CARD_TAB],- selectedItem = null,- recentItems = [],- recentFilter,- searchDelay = 0,- recentsDelay = 0,- ...rest-}: SetupOpts = {}) => {- mockGetBoundingClientRect();- setupRecentViewsAndSelectionsEndpoints(recentItems, ["selections", "views"], {- delay: recentsDelay,- });-- fetchMock.get("path:/api/search", mockSearchResults, { delay: searchDelay });-- fetchMock.get("path:/api/user/recipients", { data: [] });-- renderWithProviders(- <EntityPickerModal- title={"Pick a thing"}- onItemSelect={onItemSelect}- canSelectItem={true}- onClose={onClose}- onConfirm={onConfirm}- tabs={tabs}- selectedItem={selectedItem}- recentFilter={recentFilter}- {...rest}- />,- );-};--describe("EntityPickerModal", () => {- afterEach(() => {- jest.restoreAllMocks();- });-- it("should show a loading state when isLoadingTabs is true", async () => {- setup({- isLoadingTabs: true,- });-- expect(await screen.findByTestId("loading-indicator")).toBeInTheDocument();- expect(screen.queryByRole("tab")).not.toBeInTheDocument();- });-- it("should throw when options.hasConfirmButtons is true but onConfirm prop is missing", async () => {- expect(() => {- setup({- options: {- hasConfirmButtons: true,- },- // @ts-expect-error testing invalid prop- onConfirm: null,- });- }).toThrow("onConfirm prop is required when hasConfirmButtons is true");- });-- it("should render a picker", async () => {- setup();-- expect(await screen.findByText("Test picker foo")).toBeInTheDocument();- });-- it("should show a tab list when more than 1 tab is supplied", async () => {- setup({- tabs: [TEST_CARD_TAB, TEST_TABLE_TAB],- });-- const tabList = await screen.findByRole("tablist");-- expect(tabList).toBeInTheDocument();-- expect(- await within(tabList).findByRole("tab", { name: /All the foo/ }),- ).toBeInTheDocument();- expect(- await within(tabList).findByRole("tab", { name: /All the bar/ }),- ).toBeInTheDocument();-- await userEvent.click(- await within(tabList).findByRole("tab", { name: /All the bar/ }),- );-- expect(await screen.findByText("Test picker bar")).toBeInTheDocument();- });-- it("should accept an array of action buttons", async () => {- const actionFn = jest.fn();-- const actionButtons = [- <Button onClick={actionFn} key="1">- Click Me- </Button>,- ];-- setup({ actionButtons });-- expect(- await screen.findByRole("button", { name: "Click Me" }),- ).toBeInTheDocument();- await userEvent.click(- await screen.findByRole("button", { name: "Click Me" }),- );-- expect(actionFn).toHaveBeenCalledTimes(1);- });-- describe("Search", () => {- it("should show a search tab list when we type in the search input", async () => {- const onItemSelect = jest.fn();-- setup({- onItemSelect,- });-- await userEvent.type(- await screen.findByPlaceholderText("Search…"),- "My ",- { delay: 50 },- );-- expect(await screen.findByRole("tablist")).toBeInTheDocument();- expect(- await screen.findByRole("tab", { name: /2 results for "My"/ }),- ).toBeInTheDocument();-- expect(await screen.findAllByTestId("result-item")).toHaveLength(2);-- await userEvent.click(await screen.findByText("Search Result 1"));-- expect(onItemSelect).toHaveBeenCalledTimes(1);- });-- it("should return to previous tab when clearing the search input while search tab is open", async () => {- setup({- tabs: [TEST_CARD_TAB, TEST_TABLE_TAB],- });-- expect(- await screen.findByRole("tab", { name: /All the foo/ }),- ).toHaveAttribute("data-active", "true");-- await userEvent.click(- await screen.findByRole("tab", { name: /All the bar/ }),- );-- expect(- await screen.findByRole("tab", { name: /All the bar/ }),- ).toHaveAttribute("data-active", "true");-- await userEvent.type(await screen.findByPlaceholderText("Search…"), "M");-- expect(- await screen.findByRole("tab", { name: /results for "M"/ }),- ).toHaveAttribute("data-active", "true");-- await userEvent.clear(await screen.findByPlaceholderText("Search…"));-- expect(- await screen.findByRole("tab", { name: /All the bar/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should not switch tab when clearing the search input while search tab is closed", async () => {- setup({- tabs: [TEST_CARD_TAB, TEST_TABLE_TAB],- });-- await userEvent.type(await screen.findByPlaceholderText("Search…"), "M");-- expect(- await screen.findByRole("tab", { name: /results for "M"/ }),- ).toHaveAttribute("data-active", "true");-- await userEvent.click(- await screen.findByRole("tab", { name: /All the foo/ }),- );-- await userEvent.click(- await screen.findByRole("tab", { name: /All the bar/ }),- );-- expect(- await screen.findByRole("tab", { name: /All the bar/ }),- ).toHaveAttribute("data-active", "true");-- await userEvent.clear(await screen.findByPlaceholderText("Search…"));-- expect(- await screen.findByRole("tab", { name: /All the bar/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should show a loading state while search is happening", async () => {- setup({- searchDelay: 2000,- });-- await userEvent.type(- await screen.findByPlaceholderText("Search…"),- "My ",- { delay: 50 },- );- expect(await screen.findByRole("tablist")).toBeInTheDocument();- expect(- await screen.findByRole("tab", { name: /Search results/ }),- ).toBeInTheDocument();-- expect(await screen.findByText(/loading/i)).toBeInTheDocument();- });-- it("should render a search bar by default and show confirmation button", async () => {- setup();-- expect(await screen.findByPlaceholderText("Search…")).toBeInTheDocument();- expect(- await screen.findByRole("button", { name: "Select" }),- ).toBeInTheDocument();- });-- it("should be able to disable the search bar", () => {- setup({- options: {- showSearch: false,- },- });-- expect(screen.queryByPlaceholderText("Search…")).not.toBeInTheDocument();- });-- it("should not show action buttons on search tab", async () => {- const actionFn = jest.fn();-- const actionButtons = [- <Button onClick={actionFn} key="1">- Click Me- </Button>,- ];-- setup({- actionButtons,- });-- expect(- await screen.findByRole("button", { name: "Click Me" }),- ).toBeInTheDocument();-- await userEvent.type(- await screen.findByPlaceholderText("Search…"),- "caterpie",- { delay: 50 },- );-- await userEvent.click(await screen.findByRole("tab", { name: /Search/ }));-- expect(- screen.queryByRole("button", { name: "Click Me" }),- ).not.toBeInTheDocument();- });- });-- describe("Recents Tab", () => {- const recentItems = [- createMockRecentCollectionItem({- id: 100,- model: "card",- name: "Recent Question",- description: "A card",- timestamp: "2021-09-01T00:00:00",- }),- createMockRecentCollectionItem({- id: 200,- model: "card",- name: "Recent Question 2",- description: "sometimes invisible",- timestamp: "2021-09-01T00:00:00",- }),- createMockRecentCollectionItem({- id: 101,- model: "dashboard",- name: "Recent dashboard",- description: "A board",- timestamp: "2021-09-01T00:00:00",- }),- createMockRecentTableItem({- id: 102,- model: "table",- name: "Recent_Table",- display_name: "Recent Table",- description: "A tableau",- timestamp: "2021-09-01T00:00:00",- }),- ];-- it("should not show a recents tab when there are no recent items", async () => {- setup();-- await screen.findByText("Test picker foo");-- expect(screen.queryByText("Recents")).not.toBeInTheDocument();- });-- it("should show a recents tab when there are recent items", async () => {- setup({- recentItems,- });-- expect(- await screen.findByRole("tab", { name: /Recents/ }),- ).toBeInTheDocument();- expect(await screen.findByText("Recent Question")).toBeInTheDocument();- });-- it("should not default to the recent tab if defaultToRecents is false", async () => {- setup({- recentItems,- defaultToRecentTab: false,- initialValue: { model: "card" },- });-- expect(- await screen.findByRole("tab", { name: /Recents/ }),- ).toBeInTheDocument();- expect(await screen.findByText("Test picker foo")).toBeInTheDocument();- });-- it("should group recents by time", async () => {- setup({- recentItems,- });-- expect(await screen.findByText("Earlier")).toBeInTheDocument();- });-- it("should filter out irrelevant models", async () => {- setup({- recentItems,- tabs: [TEST_CARD_TAB, TEST_TABLE_TAB],- });-- expect(await screen.findByText("Recent Question")).toBeInTheDocument();- expect(await screen.findByText("Recent Table")).toBeInTheDocument();- expect(screen.queryByText("Recent Dashboard")).not.toBeInTheDocument();- });-- it("should accept an arbitrary filter", async () => {- setup({- recentItems,- recentFilter: (items) =>- items.filter((item) => !item.description?.includes("invisible")),- });-- expect(await screen.findByText("Recent Question")).toBeInTheDocument();- expect(screen.queryByText("Recent Question 2")).not.toBeInTheDocument();- });-- it("should not show action buttons on recents tab", async () => {- const actionFn = jest.fn();-- const actionButtons = [- <Button onClick={actionFn} key="1">- Click Me- </Button>,- ];-- setup({- actionButtons,- recentItems,- });-- await screen.findByRole("tab", { name: /Recents/ });-- expect(- screen.queryByRole("button", { name: "Click Me" }),- ).not.toBeInTheDocument();-- await userEvent.click(- await screen.findByRole("tab", { name: /All the foo/ }),- );-- expect(- await screen.findByRole("button", { name: "Click Me" }),- ).toBeInTheDocument();- });-- it("should wait until all tabs are determined before rendering", async () => {- setup({- recentsDelay: 500,- recentItems,- });-- expect(- await screen.findByTestId("loading-indicator"),- ).toBeInTheDocument();-- expect(- screen.queryByRole("tab", { name: /Recents/ }),- ).not.toBeInTheDocument();-- expect(- await screen.findByRole("tab", { name: /Recents/ }),- ).toBeInTheDocument();- });- });-});diff --git a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/TabsView.tsx b/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/TabsView.tsxdeleted file mode 100644index 0484fbee7be..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/TabsView.tsx+++ /dev/null@@ -1,95 +0,0 @@-import { Flex, Icon, Tabs } from "metabase/ui";-import type { SearchResultId } from "metabase-types/api";--import type {- EntityPickerTab,- EntityPickerTabId,- TypeWithModel,-} from "../../types";--interface Props<- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> {- selectedTabId: EntityPickerTabId;- tabs: EntityPickerTab<Id, Model, Item>[];- onItemSelect: (item: Item, tabId: EntityPickerTabId) => void;- onTabChange: (tabId: EntityPickerTabId) => void;-}--export const TabsView = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->({- selectedTabId,- tabs,- onItemSelect,- onTabChange,-}: Props<Id, Model, Item>) => {- return (- <Tabs- value={selectedTabId}- style={{- flexGrow: 1,- height: 0,- display: "flex",- flexDirection: "column",- }}- data-testid="tabs-view"- >- <Flex- justify="space-between"- align="center"- px="2.5rem"- style={{- borderBottom: "1px solid var(--mb-color-border)",- }}- >- <Tabs.List- h="2.5rem"- style={{- // eslint-disable-next-line metabase/no-color-literals- "--tab-border-color": "rgba(0, 0, 0, 0)",- }}- >- {tabs.map((tab) => {- const { id, icon, displayName } = tab;-- return (- <Tabs.Tab- key={id}- value={id}- leftSection={<Icon name={icon} />}- onClick={() => onTabChange(id)}- >- {displayName}- </Tabs.Tab>- );- })}- </Tabs.List>- {tabs.find((tab) => tab.id === selectedTabId)?.extraButtons || null}- </Flex>-- {tabs.map((tab) => {- const { id } = tab;-- return (- <Tabs.Panel- key={id}- value={id}- style={{- flexGrow: 1,- height: 0,- }}- >- {tab.render({- onItemSelect: (item) => onItemSelect(item, id),- })}- </Tabs.Panel>- );- })}- </Tabs>- );-};diff --git a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/index.tsdeleted file mode 100644index 8bb692bc102..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./EntityPickerModal";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/ItemList/ItemList.styled.tsx b/frontend/src/metabase/common/components/EntityPicker/components/ItemList/ItemList.styled.tsxdeleted file mode 100644index 55d6bff7002..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/ItemList/ItemList.styled.tsx+++ /dev/null@@ -1,10 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--import { Box } from "metabase/ui";--export const PickerColumn = styled(Box)`- width: 100%;- flex-basis: 310px;- padding: 1rem;-` as unknown as typeof Box;diff --git a/frontend/src/metabase/common/components/EntityPicker/components/ItemList/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/ItemList/index.tsdeleted file mode 100644index 69af28d6e0d..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/ItemList/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./ItemList";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/LoadingSpinner/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/LoadingSpinner/index.tsdeleted file mode 100644index ba09efca201..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/LoadingSpinner/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./LoadingSpinner";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/NestedItemPicker.styled.tsx b/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/NestedItemPicker.styled.tsxdeleted file mode 100644index 70878413496..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/NestedItemPicker.styled.tsx+++ /dev/null@@ -1,16 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--import { Box } from "metabase/ui";--export const ListBox = styled(Box)<React.PropsWithChildren>`- border-right: 1px solid var(--mb-color-border);- height: 100%;- width: 365px;- flex-basis: 365px;- background-color: var(--mb-color-background-secondary);-- &:last-child {- background-color: var(--mb-color-background-primary);- }-` as unknown as typeof Box;diff --git a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/NestedItemPicker.tsx b/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/NestedItemPicker.tsxdeleted file mode 100644index 89bd9c151a2..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/NestedItemPicker.tsx+++ /dev/null@@ -1,116 +0,0 @@-import type { ComponentType } from "react";-import { useState } from "react";--import ErrorBoundary from "metabase/ErrorBoundary";-import type {- TablePickerStatePath,- TablePickerValue,-} from "metabase/common/components/Pickers/TablePicker";-import { Flex } from "metabase/ui";--import type {- EntityPickerOptions,- IsFolder,- ListProps,- PickerState,- TypeWithModel,-} from "../../types";-import { isSelectedItem } from "../../utils";-import { AutoScrollBox } from "../AutoScrollBox";--import { ListBox } from "./NestedItemPicker.styled";-import { findLastSelectedItem, generateKey } from "./utils";--export interface NestedItemPickerProps<- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,- Query,- Options extends EntityPickerOptions,-> {- onFolderSelect: ({ folder }: { folder: Item }) => void;- onItemSelect: (item: Item) => void;- options: Options;- path: PickerState<Item, Query>;- initialValue?: TablePickerValue;- isFolder: IsFolder<Id, Model, Item>;- listResolver: ComponentType<ListProps<Id, Model, Item, Query, Options>>;- shouldDisableItem?: (item: Item) => boolean;- shouldShowItem?: (item: Item) => boolean;- tablesPath?: TablePickerStatePath;- onTablesPathChange?: (tablesPath: TablePickerStatePath) => void;-}--export function NestedItemPicker<- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,- Query,- Options extends EntityPickerOptions,->({- onFolderSelect,- onItemSelect,- options,- path,- isFolder,- listResolver: ListResolver,- shouldDisableItem,- shouldShowItem,- initialValue,- tablesPath,- onTablesPathChange,-}: NestedItemPickerProps<Id, Model, Item, Query, Options>) {- const handleClick = (item: Item) => {- if (isFolder(item)) {- onFolderSelect({ folder: item });- } else {- onItemSelect(item);- }- };- const [hashBuster, setHashBuster] = useState(0);-- const lastSelectedItem = findLastSelectedItem(path);-- return (- <AutoScrollBox- data-testid="nested-item-picker"- contentHash={generateKey(path[path.length - 1].query) + hashBuster}- >- <Flex h="100%" w="fit-content">- {path.map((level, index) => {- const { query, selectedItem, entity } = level;- const isCurrentLevel = Boolean(- selectedItem &&- lastSelectedItem &&- isSelectedItem(selectedItem, lastSelectedItem),- );-- return (- <ListBox- key={generateKey(query)}- data-testid={`item-picker-level-${index}`}- >- <ErrorBoundary>- <ListResolver- entity={entity}- query={query}- selectedItem={selectedItem}- options={options}- onClick={(item: Item) => handleClick(item)}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- isFolder={isFolder}- refresh={() => setHashBuster((b) => b + 1)}- initialValue={initialValue}- tablesPath={tablesPath}- onTablesPathChange={onTablesPathChange}- />- </ErrorBoundary>- </ListBox>- );- })}- </Flex>- </AutoScrollBox>- );-}diff --git a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/index.tsdeleted file mode 100644index 616899bdc89..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./NestedItemPicker";-export * from "./NestedItemPicker.styled";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/utils.ts b/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/utils.tsdeleted file mode 100644index 25e675655e4..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/NestedItemPicker/utils.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { PickerState } from "../../types";--// reverse-traverse the statePath to find the last selected item-export const findLastSelectedItem = <Item, Query>(- statePath: PickerState<Item, Query>,-) => {- for (let i = statePath.length - 1; i >= 0; i--) {- if (statePath[i].selectedItem) {- return statePath[i].selectedItem;- }- }- return undefined;-};--export const generateKey = <Query>(query?: Query) =>- JSON.stringify(query ?? "root");diff --git a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/GroupedRecentsList.tsx b/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/GroupedRecentsList.tsxdeleted file mode 100644index ded654b08e9..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/GroupedRecentsList.tsx+++ /dev/null@@ -1,68 +0,0 @@-import { useMemo } from "react";--import { Box, Text } from "metabase/ui";-import type { RecentItem } from "metabase-types/api";--import { ChunkyList, ResultItem } from "../ResultItem";--import { getRecentGroups, recentItemToResultItem } from "./utils";--export function GroupedRecentsList({- items,- onItemSelect,- isSelectedItem,-}: {- items: RecentItem[];- onItemSelect: (item: RecentItem) => void;- isSelectedItem: (item: RecentItem) => boolean;-}) {- const recentGroups = useMemo(() => getRecentGroups(items), [items]);-- return (- <Box style={{ overflowY: "auto" }} p="xl">- {recentGroups.map((group) => (- <RecentSection- key={group.title}- title={group.title}- items={group.items}- onItemSelect={onItemSelect}- isSelectedItem={isSelectedItem}- />- ))}- </Box>- );-}--function RecentSection({- title,- items,- onItemSelect,- isSelectedItem,-}: {- title: string;- items: RecentItem[];- onItemSelect: (item: RecentItem) => void;- isSelectedItem: (item: RecentItem) => boolean;-}) {- if (!items?.length) {- return null;- }- return (- <Box pb="lg">- <Text fw="bold" color="text-tertiary" mb="sm" pl="xs">- {title}- </Text>- <ChunkyList>- {items.map((item, index) => (- <ResultItem- key={item.model + item.id}- item={recentItemToResultItem(item)}- onClick={() => onItemSelect(item)}- isSelected={isSelectedItem(item)}- isLast={index === items.length - 1}- />- ))}- </ChunkyList>- </Box>- );-}diff --git a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/RecentsTab.tsx b/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/RecentsTab.tsxdeleted file mode 100644index e7a165194b4..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/RecentsTab.tsx+++ /dev/null@@ -1,54 +0,0 @@-import { t } from "ttag";--import { EmptyState } from "metabase/common/components/EmptyState";-import { NoObjectError } from "metabase/common/components/errors/NoObjectError";-import { SearchLoadingSpinner } from "metabase/nav/components/search/SearchResults";-import { Flex, Stack } from "metabase/ui";-import type { RecentItem } from "metabase-types/api";--import type { TypeWithModel } from "../../types";-import { isSelectedItem } from "../../utils";--import { GroupedRecentsList } from "./GroupedRecentsList";--export const RecentsTab = <- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,->({- recentItems,- onItemSelect,- selectedItem,- isLoading,-}: {- recentItems: RecentItem[] | null;- onItemSelect: (item: Item) => void;- selectedItem: Item | null;- isLoading: boolean;-}) => {- if (isLoading || !recentItems) {- return <SearchLoadingSpinner />;- }-- return (- <Stack h="100%" bg="background-secondary">- {recentItems.length > 0 ? (- <GroupedRecentsList- items={recentItems}- onItemSelect={(item) => onItemSelect(item as unknown as Item)}- isSelectedItem={(item) =>- isSelectedItem(item as unknown as Item, selectedItem)- }- />- ) : (- <Flex direction="column" justify="center" h="100%">- <EmptyState- title={t`Didn't find anything`}- message={t`There weren't any recent items.`}- illustrationElement={<NoObjectError mb="-1.5rem" />}- />- </Flex>- )}- </Stack>- );-};diff --git a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/index.tsdeleted file mode 100644index 2d6b3a50694..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./RecentsTab";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/utils.ts b/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/utils.tsdeleted file mode 100644index f7511cdb115..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/utils.ts+++ /dev/null@@ -1,80 +0,0 @@-import dayjs from "dayjs";-import relativeTime from "dayjs/plugin/relativeTime";-import { t } from "ttag";-dayjs.extend(relativeTime);--import type { RecentItem } from "metabase-types/api";--import type { SearchItem } from "../../types";--const dateBuckets = [- {- get title() {- return t`Today`;- },- days: 1,- },- {- get title() {- return t`Yesterday`;- },- days: 2,- },- {- get title() {- return t`Last week`;- },- days: 7,- },- {- get title() {- return t`Earlier`;- },- days: Infinity,- },-];--type RecentsGroup = {- title: string;- days: number;- items: RecentItem[];-};--/**- * groups recent items into date buckets- */-export function getRecentGroups(items: RecentItem[]) {- const now = dayjs();-- const groups = items.reduce(- (groups: RecentsGroup[], item) => {- const itemDate = dayjs(item.timestamp);-- for (const group of groups) {- if (now.diff(itemDate, "days") < group.days) {- group.items.push(item);- break;- }- }- return groups;- },- dateBuckets.map((bucket) => ({ ...bucket, items: [] })),- );-- return groups.filter((group) => group.items.length > 0);-}--// put a recent item into the shape expected by ResultItem component-export const recentItemToResultItem = (item: RecentItem): SearchItem => ({- ...item,- ...("parent_collection" in item- ? {- collection: {- ...item.parent_collection,- id: item.parent_collection.id ?? "root",- },- }- : {- database_name: item.database.name,- }),-});diff --git a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/utils.unit.spec.ts b/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/utils.unit.spec.tsdeleted file mode 100644index 788bd14358e..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/RecentsTab/utils.unit.spec.ts+++ /dev/null@@ -1,76 +0,0 @@-import dayjs from "dayjs";--import { createMockRecentCollectionItem } from "metabase-types/api/mocks";--import { getRecentGroups } from "./utils";--const items = [- createMockRecentCollectionItem({- name: "This Week Q",- timestamp: dayjs().subtract(2, "day").toISOString(),- }),- createMockRecentCollectionItem({- name: "This Week Q2",- timestamp: dayjs().subtract(6, "day").toISOString(),- }),-- createMockRecentCollectionItem({- name: "Yesterday Q1",- timestamp: dayjs().subtract(25, "hour").toISOString(),- }),- createMockRecentCollectionItem({- name: "Yesterday Q2",- timestamp: dayjs().subtract(47, "hour").toISOString(),- }),-- createMockRecentCollectionItem({- name: "Today Q1",- timestamp: dayjs().subtract(1, "hour").toISOString(),- }),- createMockRecentCollectionItem({- name: "Today Q2",- timestamp: dayjs().subtract(23, "hour").toISOString(),- }),-- createMockRecentCollectionItem({- name: "Old Q1",- timestamp: dayjs().subtract(8, "day").toISOString(),- }),- createMockRecentCollectionItem({- name: "Old Q2",- timestamp: dayjs().subtract(12, "day").toISOString(),- }),- createMockRecentCollectionItem({- name: "Old Q3",- timestamp: dayjs().subtract(19, "day").toISOString(),- }),- createMockRecentCollectionItem({- name: "Old Q4",- timestamp: dayjs().subtract(400, "day").toISOString(),- }),-];--describe("EntityPicker -> RecentsTab -> utils", () => {- it("should group recent items into date buckets", () => {- const groups = getRecentGroups(items);-- expect(groups).toEqual([- { title: "Today", days: 1, items: [items[4], items[5]] },- { title: "Yesterday", days: 2, items: [items[2], items[3]] },- { title: "Last week", days: 7, items: [items[0], items[1]] },- {- title: "Earlier",- days: Infinity,- items: [items[6], items[7], items[8], items[9]],- },- ]);- });-- it("should omit empty groups", () => {- const groups = getRecentGroups(items.slice(2, 4));-- expect(groups).toEqual([- { title: "Yesterday", days: 2, items: [items[2], items[3]] },- ]);- });-});diff --git a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.styled.tsx b/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.styled.tsxdeleted file mode 100644index e3d0b3701a9..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.styled.tsx+++ /dev/null@@ -1,50 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import { css } from "@emotion/react";-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--export const ChunkyListItem = styled.button<{- isSelected?: boolean;- isLast?: boolean;-}>`- padding: 1.5rem;- cursor: pointer;- background-color: ${({ isSelected }) =>- isSelected- ? "var(--mb-color-brand)"- : "var(--mb-color-background-primary)"};- color: ${({ isSelected }) =>- isSelected- ? "var(--mb-color-text-primary-inverse)"- : "var(--mb-color-text-primary)"};- outline-offset: -3px;-- &:hover {- ${({ isSelected }) =>- !isSelected &&- css`- background-color: var(--mb-color-background-hover);- color: var(--mb-color-text-primary);- `}- }-- ${({ isLast }) =>- !isLast &&- css`- border-bottom: 1px solid var(--mb-color-border);- `};-- display: flex;- gap: 1rem;- justify-content: space-between;- align-items: center;- width: 100%;-`;--export const ChunkyList = styled.div`- border: 1px solid var(--mb-color-border);- border-radius: 0.5rem;- display: flex;- flex-direction: column;- overflow: hidden;-`;diff --git a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.tsx b/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.tsxdeleted file mode 100644index cd19c4198e1..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.tsx+++ /dev/null@@ -1,116 +0,0 @@-import { t } from "ttag";--import { Ellipsified } from "metabase/common/components/Ellipsified";-import { useTranslateContent } from "metabase/i18n/hooks";-import { humanize, titleize } from "metabase/lib/formatting";-import { getIcon } from "metabase/lib/icon";-import { getName } from "metabase/lib/name";-import { PLUGIN_MODERATION } from "metabase/plugins";-import { FixedSizeIcon, Flex, Tooltip } from "metabase/ui";--import type { SearchItem } from "../../types";--import { ChunkyListItem } from "./ResultItem.styled";--export const ResultItem = ({- item,- onClick,- isSelected,- isLast,-}: {- item: SearchItem;- onClick: () => void;- isSelected?: boolean;- isLast?: boolean;-}) => {- const tc = useTranslateContent();-- const icon = getIcon(item);- const parentInfo = getParentInfo(item);-- return (- <ChunkyListItem- aria-selected={isSelected}- onClick={onClick}- isSelected={isSelected}- isLast={isLast}- data-model-type={item.model}- data-testid="result-item"- >- <Flex gap="md" miw="10rem" align="center" style={{ flex: 1 }}>- <FixedSizeIcon- c={icon.color ?? (isSelected ? "text-primary-inverse" : "brand")}- name={icon.name}- style={{- flexShrink: 0,- }}- />- <Ellipsified style={{ fontWeight: "bold" }}>- {tc(getName(item))}- </Ellipsified>- <PLUGIN_MODERATION.ModerationStatusIcon- status={item.moderated_status}- filled- size={14}- />- {item.description && (- <Tooltip maw="20rem" multiline label={tc(item.description)}>- <FixedSizeIcon c="brand" name="info" />- </Tooltip>- )}- </Flex>-- {parentInfo && (- <Flex- c={isSelected ? "text-primary-inverse" : "text-tertiary"}- align="center"- gap="sm"- w="20rem"- >- <FixedSizeIcon name={parentInfo.icon} />- <Ellipsified>{t`in ${parentInfo.name}`}</Ellipsified>- </Flex>- )}- </ChunkyListItem>- );-};--function getParentInfo(item: SearchItem) {- if (item.model === "table") {- const icon = getIcon({ model: "database" }).name;- const databaseName = item.database_name ?? t`Database`;-- if (!item.table_schema) {- return {- icon,- name: databaseName,- };- }-- return {- icon,- name: `${databaseName} (${titleize(humanize(item.table_schema))})`,- };- }-- if (item.model === "collection" && item?.collection?.id === item?.id) {- // some APIs return collection items with themselves populated as their own parent 🥴- return null;- }-- if (item.dashboard) {- return {- icon: getIcon({ model: "dashboard", ...item.dashboard }).name,- name: getName(item.dashboard),- };- }-- if (!item.collection) {- return null;- }-- return {- icon: getIcon({ model: "collection", ...item.collection }).name,- name: getName(item.collection) || t`Our Analytics`,- };-}diff --git a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.unit.spec.tsx b/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.unit.spec.tsxdeleted file mode 100644index 0c162682ff2..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/ResultItem.unit.spec.tsx+++ /dev/null@@ -1,268 +0,0 @@-import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";-import { mockSettings } from "__support__/settings";-import {- getIcon,- queryIcon,- renderWithProviders,- screen,-} from "__support__/ui";-import register from "metabase/visualizations/register";-import {- createMockSettings,- createMockTokenFeatures,-} from "metabase-types/api/mocks";-import { createMockState } from "metabase-types/store/mocks";--import type { SearchItem } from "../../types";--import { ResultItem } from "./ResultItem";--function setup({- item,- isSelected = false,- onClick = jest.fn(),-}: {- item: SearchItem;- isSelected?: boolean;- onClick?: () => void;-}) {- const tokenFeatures = createMockTokenFeatures({- content_verification: true,- official_collections: true,- });- const settings = createMockSettings();-- const settingValuesWithToken = {- ...settings,- "token-features": tokenFeatures,- };-- const state = createMockState({- settings: mockSettings(settingValuesWithToken),- });-- setupEnterpriseOnlyPlugin("collections");- setupEnterpriseOnlyPlugin("moderation");-- return renderWithProviders(- <ResultItem item={item} isSelected={isSelected} onClick={onClick} />,- { storeInitialState: state },- );-}--const collectionItemWithInvalidParent: SearchItem = {- id: 301,- model: "collection",- name: "Foo Collection",- description: "",- collection: { name: "should not show this collection", id: 301 },- collection_authority_level: null,- moderated_status: null,- display: null,-};--const collectionItemWithValidParent: SearchItem = {- id: 302,- model: "collection",- name: "Foo Collection",- description: "",- collection: { name: "should show this collection", id: 303 },- collection_authority_level: null,- moderated_status: null,- display: null,-};--const questionItem: SearchItem = {- id: 303,- model: "card",- name: "My Bar Chart",- description: "",- collection: { name: "My parent collection", id: 101 },- collection_authority_level: null,- moderated_status: null,- display: "bar",-};--const dashboardItem: SearchItem = {- id: 304,- model: "dashboard",- name: "My Awesome Dashboard ",- description: "This dashboard contains awesome stuff",- collection: { name: "My parent collection", id: 101 },- collection_authority_level: null,- moderated_status: null,- display: null,-};--const questionInOfficialCollection: SearchItem = {- id: 305,- model: "card",- name: "My Line Chart",- description: "",- collection: {- name: "My official parent collection",- id: 101,- authority_level: "official",- },- collection_authority_level: "official",- moderated_status: null,- display: "line",-};--const verifiedModelItem: SearchItem = {- id: 306,- model: "dataset",- name: "My Verified Model",- description: "",- collection: { name: "My parent collection", id: 101 },- collection_authority_level: null,- moderated_status: "verified",- display: null,-};--const tableItem: SearchItem = {- id: 307,- model: "table",- name: "My Flat Table",- description: null,- database_name: "My Database",-};--const tableItemWithSchema: SearchItem = {- ...tableItem,- table_schema: "my_schema",-};--const tableItemWithEmptySchema: SearchItem = {- ...tableItem,- table_schema: "",-};--describe("EntityPicker > ResultItem", () => {- beforeAll(() => {- register();- });-- it("should render a collection item ignoring an invalid parent", () => {- setup({- item: collectionItemWithInvalidParent,- });- expect(screen.getByText("Foo Collection")).toBeInTheDocument();- expect(screen.queryByText(/should not show/i)).not.toBeInTheDocument();- expect(getIcon("folder")).toBeInTheDocument();- });-- it("should render a collection item with parent", () => {- setup({- item: collectionItemWithValidParent,- });- expect(screen.getByText("Foo Collection")).toBeInTheDocument();- expect(screen.getByText(/should show/i)).toBeInTheDocument();- expect(screen.getAllByLabelText("folder icon")).toHaveLength(2);- });-- it("should render a bar chart item", () => {- setup({- item: questionItem,- });- expect(screen.getByText("My Bar Chart")).toBeInTheDocument();- expect(getIcon("bar")).toBeInTheDocument();-- expect(screen.getByText("in My parent collection")).toBeInTheDocument();- });-- it("should render a dashboard item", () => {- setup({- item: dashboardItem,- });- expect(screen.getByText("My Awesome Dashboard")).toBeInTheDocument();-- expect(getIcon("dashboard")).toBeInTheDocument();- expect(screen.getByText("in My parent collection")).toBeInTheDocument();- });-- it("should render an info icon when an item lacks a description", () => {- setup({- item: dashboardItem,- });-- expect(getIcon("info")).toBeInTheDocument();- });-- it("should not render an info icon when an item has a description", () => {- setup({- item: questionItem,- });-- expect(queryIcon("info")).not.toBeInTheDocument();- });-- it("should render a line chart item in an official collection", () => {- setup({- item: questionInOfficialCollection,- });- expect(screen.getByText("My Line Chart")).toBeInTheDocument();- expect(getIcon("line")).toBeInTheDocument();-- expect(- screen.getByText("in My official parent collection"),- ).toBeInTheDocument();- expect(- screen.getByText("in My official parent collection"),- ).toBeInTheDocument();- expect(getIcon("official_collection")).toBeInTheDocument();- });-- it("should render a verified model item", () => {- setup({- item: verifiedModelItem,- });- expect(screen.getByText("My Verified Model")).toBeInTheDocument();-- expect(getIcon("model_with_badge")).toBeInTheDocument();- expect(getIcon("verified_filled")).toBeInTheDocument();- expect(screen.getByText("in My parent collection")).toBeInTheDocument();- });-- it("should render a table model item", () => {- setup({- item: tableItem,- });- expect(screen.getByText(tableItem.name)).toBeInTheDocument();-- expect(getIcon("table")).toBeInTheDocument();- expect(getIcon("database")).toBeInTheDocument();- expect(- screen.getByText(`in ${tableItem.database_name}`),- ).toBeInTheDocument();- });-- it("should display table schema when available (metabase#44460)", () => {- setup({- item: tableItemWithSchema,- });- expect(screen.getByText(tableItem.name)).toBeInTheDocument();-- expect(getIcon("table")).toBeInTheDocument();- expect(getIcon("database")).toBeInTheDocument();- expect(- screen.getByText(`in ${tableItem.database_name} (My Schema)`),- ).toBeInTheDocument();- });-- it("should not display empty table schema", () => {- setup({- item: tableItemWithEmptySchema,- });- expect(screen.getByText(tableItem.name)).toBeInTheDocument();-- expect(getIcon("table")).toBeInTheDocument();- expect(getIcon("database")).toBeInTheDocument();- expect(- screen.getByText(`in ${tableItem.database_name}`),- ).toBeInTheDocument();- expect(- screen.queryByText(`in ${tableItem.database_name} ()`),- ).not.toBeInTheDocument();- });-});diff --git a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/index.tsdeleted file mode 100644index 4f9f05a0b03..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/ResultItem/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./ResultItem";-export * from "./ResultItem.styled";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/SearchResults.tsx b/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/SearchResults.tsxdeleted file mode 100644index 833ae75915c..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/SearchResults.tsx+++ /dev/null@@ -1,89 +0,0 @@-import { t } from "ttag";--import { EmptyState } from "metabase/common/components/EmptyState";-import { VirtualizedList } from "metabase/common/components/VirtualizedList";-import { NoObjectError } from "metabase/common/components/errors/NoObjectError";-import { trackSearchClick } from "metabase/search/analytics";-import { Box, Flex, Stack } from "metabase/ui";-import type { SearchResultId } from "metabase-types/api";--import type { SearchItem, TypeWithModel } from "../../types";-import { ChunkyList, ResultItem } from "../ResultItem";--interface Props<- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> {- folder: Item | undefined;- searchResults: SearchItem[];- searchEngine?: string;- searchRequestId?: string;- searchTerm?: string;- selectedItem: Item | null;- onItemSelect: (item: Item) => void;-}--export const SearchResults = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->({- folder,- searchResults,- searchEngine,- searchRequestId,- searchTerm,- selectedItem,- onItemSelect,-}: Props<Id, Model, Item>) => {- return (- <Box h="100%">- {searchResults.length > 0 ? (- <Stack h="100%">- <VirtualizedList- Wrapper={({ children, ...props }) => (- <Box p="xl" pt={folder ? 0 : "xl"} {...props}>- <ChunkyList>{children}</ChunkyList>- </Box>- )}- estimatedItemSize={66}- >- {searchResults?.map((item, index) => (- <ResultItem- key={item.model + item.id}- item={item}- onClick={() => {- trackSearchClick({- itemType: "item",- position: index,- context: "entity-picker",- searchEngine: searchEngine || "unknown",- requestId: searchRequestId,- entityModel: item.model,- entityId: typeof item.id === "number" ? item.id : null,- searchTerm,- });- onItemSelect(item as unknown as Item);- }}- isSelected={- selectedItem?.id === item.id &&- selectedItem?.model === item.model- }- isLast={index === searchResults.length - 1}- />- ))}- </VirtualizedList>- </Stack>- ) : (- <Flex direction="column" justify="center" h="100%">- <EmptyState- title={t`Didn't find anything`}- message={t`There weren't any results for your search.`}- illustrationElement={<NoObjectError mb="-1.5rem" />}- />- </Flex>- )}- </Box>- );-};diff --git a/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/SearchTab.tsx b/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/SearchTab.tsxdeleted file mode 100644index 0697c372745..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/SearchTab.tsx+++ /dev/null@@ -1,116 +0,0 @@-import { msgid, ngettext, t } from "ttag";--import { Box, Flex, SegmentedControl, Stack, Text } from "metabase/ui";-import type { SearchResultId } from "metabase-types/api";--import type {- EntityPickerSearchScope,- SearchItem,- TypeWithModel,-} from "../../types";-import { isSchemaItem } from "../../utils";-import { DelayedLoadingSpinner } from "../LoadingSpinner";--import { SearchResults } from "./SearchResults";--interface Props<- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> {- folder: Item | undefined;- isLoading: boolean;- searchScope: EntityPickerSearchScope;- searchResults: SearchItem[];- searchEngine?: string;- searchRequestId?: string;- searchTerm?: string;- selectedItem: Item | null;- onItemSelect: (item: Item) => void;- onSearchScopeChange: (scope: EntityPickerSearchScope) => void;-}--export const SearchTab = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->({- folder,- isLoading,- searchScope,- searchResults,- searchEngine,- searchRequestId,- searchTerm,- selectedItem,- onItemSelect,- onSearchScopeChange,-}: Props<Id, Model, Item>) => {- return (- <Stack bg="background-secondary" h="100%" gap={0}>- {folder && (- <Flex align="center" justify="space-between" p="xl">- <Flex align="center">- <Text mr={12} fw="bold">- {t`Search:`}- </Text>-- <SegmentedControl- data={[- { label: t`Everywhere`, value: "everywhere" as const },- {- label: `“${getFolderName(folder)}”`,- value: "folder" as const,- },- ]}- value={searchScope}- onChange={(value) =>- onSearchScopeChange(value as EntityPickerSearchScope)- }- />- </Flex>-- {!isLoading && (- <div data-testid="entity-picker-search-result-count">- {ngettext(- msgid`${searchResults.length} result`,- `${searchResults.length} results`,- searchResults.length,- )}- </div>- )}- </Flex>- )}-- <Box style={{ flex: 1, overflow: "hidden" }}>- {isLoading && <DelayedLoadingSpinner text={t`Loading…`} />}-- {!isLoading && (- <SearchResults- folder={folder}- searchResults={searchResults}- searchEngine={searchEngine}- searchRequestId={searchRequestId}- searchTerm={searchTerm}- selectedItem={selectedItem}- onItemSelect={onItemSelect}- />- )}- </Box>- </Stack>- );-};--const getFolderName = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- folder: Item,-) => {- if (isSchemaItem(folder) && (!folder.name || folder.isOnlySchema)) {- return folder.dbName;- }-- return folder.name;-};diff --git a/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/index.ts b/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/index.tsdeleted file mode 100644index 741ebe80670..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/components/SearchTab/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./SearchTab";diff --git a/frontend/src/metabase/common/components/EntityPicker/hooks/index.ts b/frontend/src/metabase/common/components/EntityPicker/hooks/index.tsdeleted file mode 100644index 337b015d6b3..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/hooks/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./use-log-recent-item";-export * from "./use-scoped-search-results";diff --git a/frontend/src/metabase/common/components/EntityPicker/hooks/use-scoped-search-results.ts b/frontend/src/metabase/common/components/EntityPicker/hooks/use-scoped-search-results.tsdeleted file mode 100644index ecd8bffef92..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/hooks/use-scoped-search-results.ts+++ /dev/null@@ -1,207 +0,0 @@-import { useMemo } from "react";--import {- skipToken,- useGetDatabaseQuery,- useListCollectionItemsQuery,- useListDashboardItemsQuery,- useListDatabaseSchemaTablesQuery,-} from "metabase/api";-import { DATABASES_COLLECTION } from "metabase/entities/collections";-import { isNotNull } from "metabase/lib/types";-import type {- CollectionId,- CollectionItem,- CollectionItemModel,- DashboardId,- SearchResultId,- Table,-} from "metabase-types/api";--import type {- EntityPickerSearchScope,- SearchItem,- TypeWithModel,-} from "../types";-import { isSchemaItem } from "../utils";--const searchModelsToCollectionItemModels = (- searchModels: string[],-): CollectionItemModel[] => {- const validModels = [- "card",- "collection",- "dataset",- "dashboard",- "snippet",- "metric",- ] as const;- return validModels.filter((model) => searchModels.includes(model));-};--export const useScopedSearchResults = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- searchQuery: string,- searchModels: string[],- searchScope: EntityPickerSearchScope,- folder: Item | undefined,-): SearchItem[] | null => {- const isScopedSearchEnabled =- searchScope === "folder" && folder != null && folder.id !== "tenant";-- const shouldUseCollectionItems =- isScopedSearchEnabled &&- folder.model === "collection" &&- folder.id !== DATABASES_COLLECTION.id;- const shouldUseDashboardItems =- isScopedSearchEnabled && folder.model === "dashboard";-- const shouldUseTables = isScopedSearchEnabled && folder.model === "schema";-- const { data: collectionItemsData, isFetching: isFetchingCollectionItems } =- useListCollectionItemsQuery(- shouldUseCollectionItems && searchQuery- ? {- id: folder.id as CollectionId,- models: searchModelsToCollectionItemModels(searchModels),- }- : skipToken,- );-- const { data: dashboardItemsData, isFetching: isFetchingDashboardItems } =- useListDashboardItemsQuery(- shouldUseDashboardItems && searchQuery- ? { id: folder.id as DashboardId }- : skipToken,- );-- const dbId =- shouldUseTables && isSchemaItem(folder) ? folder.dbId : undefined;- const schemaName =- shouldUseTables && isSchemaItem(folder) ? folder.id : undefined;-- const { data: tables, isFetching: isFetchingTables } =- useListDatabaseSchemaTablesQuery(- shouldUseTables && isNotNull(dbId) && isNotNull(schemaName)- ? { id: dbId, schema: schemaName as string }- : skipToken,- );-- const { data: database } = useGetDatabaseQuery(- shouldUseTables && isNotNull(dbId) ? { id: dbId } : skipToken,- );-- const collectionItems = useMemo(() => {- return collectionItemsToSearchResults(- collectionItemsData?.data ?? [],- folder,- );- }, [collectionItemsData, folder]);-- const dashboardItems = useMemo(() => {- return collectionItemsToSearchResults(- dashboardItemsData?.data ?? [],- folder,- );- }, [dashboardItemsData, folder]);-- const tableItems = useMemo(() => {- return tablesToSearchResults(tables ?? [], database?.name);- }, [tables, database]);-- const scopedSearchResults: SearchItem[] | null = useMemo(() => {- if (isScopedSearchEnabled && shouldUseCollectionItems) {- return isFetchingCollectionItems- ? null- : filterSearchResults(collectionItems, searchQuery, searchModels);- }-- if (isScopedSearchEnabled && shouldUseDashboardItems) {- return isFetchingDashboardItems- ? null- : filterSearchResults(dashboardItems, searchQuery, searchModels);- }-- if (isScopedSearchEnabled && shouldUseTables) {- return isFetchingTables- ? null- : filterSearchResults(tableItems, searchQuery, searchModels);- }-- return null;- }, [- isFetchingTables,- isFetchingCollectionItems,- isFetchingDashboardItems,- shouldUseCollectionItems,- shouldUseDashboardItems,- shouldUseTables,- collectionItems,- dashboardItems,- tableItems,- searchQuery,- searchModels,- isScopedSearchEnabled,- ]);-- return scopedSearchResults;-};--const collectionItemsToSearchResults = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- items: CollectionItem[],- folder: Item | undefined,-): SearchItem[] => {- return items.reduce((items: SearchItem[], item) => {- if (item.model !== "snippet") {- items.push({- ...item,- model: item.model,- collection: folder && { ...folder, id: Number(folder.id) },- database_name: null,- display: null,- table_schema: null,- moderated_status: null,- collection_authority_level: null,- });- }- return items;- }, []);-};--const tablesToSearchResults = (- tables: Table[],- dbName: string | undefined,-): SearchItem[] => {- return tables.map((table) => ({- ...table,- id: Number(table.id),- name: table.display_name,- model: "table",- database_name: dbName ?? null,- table_schema: table.schema,- display: null,- moderated_status: null,- collection_authority_level: null,- }));-};--const filterSearchResults = (- results: SearchItem[],- searchQuery: string,- searchModels: string[],-) => {- return results.filter((result) => {- const matchesQuery = result.name- .toLowerCase()- .includes(searchQuery.toLowerCase());- const matchesModel = searchModels.includes(result.model);- return matchesQuery && matchesModel;- });-};diff --git a/frontend/src/metabase/common/components/EntityPicker/types.ts b/frontend/src/metabase/common/components/EntityPicker/types.tsdeleted file mode 100644index 4c14ada7f74..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/types.ts+++ /dev/null@@ -1,115 +0,0 @@-import type { ReactNode } from "react";--import type { IconName } from "metabase/ui";-import type {- CollectionType,- SearchResult,- SearchResultId,-} from "metabase-types/api";--import type {- TablePickerStatePath,- TablePickerValue,-} from "../Pickers/TablePicker";--import type { EntityPickerModalOptions } from "./components/EntityPickerModal";--export type TypeWithModel<Id, Model extends string> = {- id: Id;- model: Model;- name: string;- can_write?: boolean;- moderated_status?: "verified" | null;- type?: CollectionType;-};--export type IsFolder<- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> = (item: Item) => boolean;--export type PickerState<Item, Query> = PickerStateItem<Item, Query>[];--export type PickerStateItem<Item, Query> = {- query?: Query;- selectedItem: Item | null;- entity?: "collection" | "dashboard";-};--export type EntityPickerOptions = EntityPickerModalOptions;--export type EntityPickerTabRenderProps<- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> = {- onItemSelect: (item: Item) => void;-};--export type EntityPickerTabId = string;--export type EntityPickerTab<- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> = {- id: EntityPickerTabId;- displayName: string;- render: (props: EntityPickerTabRenderProps<Id, Model, Item>) => JSX.Element;- icon: IconName;- /**- * Recents & Search tabs don't have models associated with them - hence null- * (they provide the same models as the other tabs combined).- */- models: Model[];- folderModels: Model[];- extraButtons?: ReactNode[];-};--export type EntityPickerSearchScope = "everywhere" | "folder";--export type ListProps<- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,- Query,- Options extends EntityPickerOptions,-> = {- query?: Query;- onClick: (val: Item) => void;- selectedItem: Item | null;- isFolder: IsFolder<Id, Model, Item>;- isCurrentLevel: boolean;- options: Options;- shouldDisableItem?: (item: Item) => boolean;- shouldShowItem?: (item: Item) => boolean;- entity?: "collection" | "dashboard";- refresh?: () => void;- initialValue?: TablePickerValue;- tablesPath?: TablePickerStatePath;- onTablesPathChange?: (tablesPath: TablePickerStatePath) => void;-};--export type FilterItemsInPersonalCollection = "only" | "exclude";--export type TabFolderState<- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> = Partial<Record<EntityPickerTabId, Item>>;--export type SearchItem = Pick<SearchResult, "id" | "model" | "name"> &- Partial<- Pick<- SearchResult,- | "collection"- | "dashboard"- | "description"- | "collection_authority_level"- | "moderated_status"- | "display"- | "database_name"- | "table_schema"- >- >;diff --git a/frontend/src/metabase/common/components/EntityPicker/utils.ts b/frontend/src/metabase/common/components/EntityPicker/utils.tsdeleted file mode 100644index f88bb4b4502..00000000000--- a/frontend/src/metabase/common/components/EntityPicker/utils.ts+++ /dev/null@@ -1,247 +0,0 @@-import { c, msgid, t } from "ttag";--import type { ObjectWithModel } from "metabase/lib/icon";-import { getIcon } from "metabase/lib/icon";-import {- type DatabaseId,- SEARCH_MODELS,- type SearchModel,- type SearchResult,- type SearchResultId,-} from "metabase-types/api";-import { isObject } from "metabase-types/guards";--import { RECENTS_TAB_ID } from "./constants";-import type {- EntityPickerSearchScope,- EntityPickerTab,- SearchItem,- TypeWithModel,-} from "./types";--export const getEntityPickerIcon = <Id, Model extends string>(- item: TypeWithModel<Id, Model>,- {- isSelected,- isTenantUser,- }: {- isSelected?: boolean;- isTenantUser?: boolean;- } = {},-) => {- const icon = getIcon(item as ObjectWithModel, { isTenantUser });-- if (["person", "group"].includes(icon.name)) {- // should inherit color- return icon;- }-- if (isSelected && !icon.color) {- icon.color = "text-primary-inverse";- }-- if (icon.name === "folder" && isSelected) {- icon.name = "folder_filled";- }-- return { ...icon, color: undefined, c: icon.color ?? "brand" };-};--export const isSelectedItem = <Id, Model extends string>(- item: TypeWithModel<Id, Model>,- selectedItem: TypeWithModel<Id, Model> | null,-): boolean => {- return (- !!selectedItem &&- item.id === selectedItem.id &&- item.model === selectedItem.model- );-};--export const computeInitialTabId = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->({- initialValue,- tabs,- defaultToRecentTab,-}: {- initialValue?: Partial<Item>;- tabs: EntityPickerTab<Id, Model, Item>[];- defaultToRecentTab: boolean;-}): string => {- const hasRecents = tabs.some((tab) => tab.id === RECENTS_TAB_ID);-- if (hasRecents && defaultToRecentTab) {- return RECENTS_TAB_ID;- }-- const initialValueTab =- initialValue?.model &&- tabs.find((tab) => tab.models.includes(initialValue.model as Model));-- if (initialValueTab) {- return initialValueTab.id;- }-- return tabs[0]?.id;-};--const emptySearchResultTranslationContext = c(- "the title of a ui tab that contains search results",-);-const searchResultTranslationContext = c(- "the title of a ui tab that contains search results where {0} is the number of search results and {1} is the user-supplied search query.",-);--export function getSearchTabText(- searchResults: SearchItem[] | null,- searchQuery: string,-): string {- if (!searchResults || !searchResults.length) {- return emptySearchResultTranslationContext.t`Search results`;- }-- return searchResultTranslationContext.ngettext(- msgid`${searchResults.length} result for "${searchQuery.trim()}"`,- `${searchResults.length} results for "${searchQuery.trim()}"`,- searchResults.length,- );-}--export const getSearchModels = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- tabs: EntityPickerTab<Id, Model, Item>[],-): SearchModel[] => {- return tabs.flatMap(({ models }) => {- return models && isArrayOfSearchModels(models) ? models : [];- });-};--export const getSearchFolderModels = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- tabs: EntityPickerTab<Id, Model, Item>[],-): Model[] => {- return tabs.flatMap(({ folderModels }) => folderModels);-};--export const isSearchFolder = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- folder: Item,- folderModels: Model[],-) => {- return (- folder.id !== "personal" &&- folder.id !== "databases" &&- folderModels.includes(folder.model)- );-};--const isSearchModel = (model: string): model is SearchModel => {- return SEARCH_MODELS.some((searchModel) => searchModel === model);-};--const isArrayOfSearchModels = (models: string[]): models is SearchModel[] => {- return models.every(isSearchModel);-};--export const getSearchInputPlaceholder = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- folder: Item | undefined,-): string => {- if (folder?.model === "collection") {- return t`Search this collection or everywhere…`;- }-- if (folder?.model === "database") {- return t`Search this database or everywhere…`;- }-- if (folder?.model === "schema") {- // we're not showing schema selection step if there's only 1 schema- if (isSchemaItem(folder) && folder.isOnlySchema) {- return t`Search this database or everywhere…`;- }-- return t`Search this schema or everywhere…`;- }-- if (folder?.model === "dashboard") {- return t`Search this dashboard or everywhere…`;- }-- return t`Search…`;-};--export const getScopedSearchResults = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- searchResults: SearchResult[] | null,- searchScope: EntityPickerSearchScope,- folder: Item | undefined,-): SearchResult[] => {- if (!searchResults) {- return [];- }-- if (searchScope === "everywhere" || !folder) {- return searchResults;- }-- if (folder.model === "database") {- return searchResults.filter(- (result) => result.model === "table" && result.database_id === folder.id,- );- }-- if (folder.model === "schema") {- return searchResults.filter(- (result) => result.model === "table" && result.table_schema === folder.id,- );- }-- if (folder.model === "collection") {- return searchResults.filter(- (result) => result.collection?.id === folder.id,- );- }-- return [];-};--export const isSchemaItem = <- Id extends SearchResultId,- Model extends string,- Item extends TypeWithModel<Id, Model>,->(- item: Item,-): item is Item & {- dbId: DatabaseId;- dbName: string;- isOnlySchema: boolean;-} => {- return (- isObject(item) &&- "dbId" in item &&- typeof item.dbId === "number" &&- "dbName" in item &&- typeof item.dbName === "string" &&- "isOnlySchema" in item &&- typeof item.isOnlySchema === "boolean"- );-};diff --git a/frontend/src/metabase/common/components/MoveModal.tsx b/frontend/src/metabase/common/components/MoveModal.tsxdeleted file mode 100644index bc8a7cd36e4..00000000000--- a/frontend/src/metabase/common/components/MoveModal.tsx+++ /dev/null@@ -1,318 +0,0 @@-import { useCallback } from "react";-import { t } from "ttag";-import _ from "underscore";--import type {- MoveCollectionDestination,- MoveDestination,- OnMoveWithOneItem,-} from "metabase/collections/types";-import {- type EntityType,- canPlaceEntityInCollection,- canPlaceEntityInCollectionOrDescendants,- isItemCollection,-} from "metabase/collections/utils";-import {- type CollectionPickerItem,- CollectionPickerModal,- type CollectionPickerModel,- type CollectionPickerValueItem,- getCollectionType,-} from "metabase/common/components/Pickers/CollectionPicker";-import { isItemInCollectionOrItsDescendants } from "metabase/common/components/Pickers/utils";-import { PLUGIN_TENANTS } from "metabase/plugins";-import type {- CollectionId,- CollectionItem,- CollectionNamespace,- RecentItem,- SearchResult,-} from "metabase-types/api";--interface BaseMoveModalProps {- title: string;- onClose: () => void;- initialCollectionId: CollectionId;- movingCollectionId?: CollectionId;- entityType?: EntityType;- recentAndSearchFilter?: (item: CollectionPickerItem) => boolean;- /**- * When set to "collection", allows saving to namespace root collections- * (like tenant root). When null/undefined, namespace roots are disabled.- */- savingModel?: "collection" | null;- /**- * The namespace of the collection being moved. Used to restrict which- * collections are shown in the picker:- * - If "shared-tenant-collection", only tenant collections are shown- * - Otherwise, tenant collections are hidden from the picker- */- movingCollectionNamespace?: CollectionNamespace;-}--type MoveModalProps =- | (BaseMoveModalProps & {- canMoveToDashboard?: true | undefined;- onMove: OnMoveWithOneItem;- })- | (BaseMoveModalProps & {- canMoveToDashboard?: false;- onMove: OnMoveWithOneItem<MoveCollectionDestination>;- });--const makeRecentFilter = (- disableFns: (((item: CollectionPickerItem) => boolean) | undefined)[],-) => {- return (recentItems: RecentItem[]) =>- recentItems.filter((result) =>- disableFns- .map((disableFn) => !disableFn?.(result as CollectionPickerItem))- .every((val) => val === true),- );-};--const makeSearchResultFilter = (- disableFns: (((item: CollectionPickerItem) => boolean) | undefined)[],-) => {- return (searchResults: SearchResult[]) =>- searchResults.filter((result) =>- disableFns- .map((disableFn) => !disableFn?.(result as CollectionPickerItem))- .every((val) => val === true),- );-};--export const MoveModal = ({- title,- onClose,- onMove,- initialCollectionId,- movingCollectionId,- entityType,- canMoveToDashboard,- recentAndSearchFilter,- savingModel,- movingCollectionNamespace,-}: MoveModalProps) => {- const isMovingTenantCollection = PLUGIN_TENANTS.isTenantNamespace(- movingCollectionNamespace,- );- const shouldDisableItem = (item: CollectionPickerItem): boolean => {- if (isItemInCollectionOrItsDescendants(item, movingCollectionId)) {- return true;- }-- if (entityType && item.model === "collection") {- return !canPlaceEntityInCollectionOrDescendants(- entityType,- getCollectionType(item),- );- }-- return false;- };-- const searchResultFilter = makeSearchResultFilter([- shouldDisableItem,- recentAndSearchFilter,- ]);-- const recentFilter = makeRecentFilter([- (item) => {- return Boolean(!item.can_write || shouldDisableItem?.(item));- },- recentAndSearchFilter,- ]);-- const handleMove = useCallback(- (destination: CollectionPickerValueItem) => {- // GROSS:- // - CollectionPicker's `onChange` prop isn't generic to its `models` prop, so- // `onChange`'s destination arg isn't narrowed based on the `models` passed in. This- // requires we do additional type gauarding / unneeded error handling below.- // - To keep this same issue from bubbling up to consumers of MoveModal, we need- // do some extra type casting so it has an external API where `canMoveToDashboard`- // narrows the `destination` arg for its `onMove` prop.- // - Making CollectionPicker properly generic is hard due to some internal typing- // being used by components other than the CollectionPicker. One type- // cast here avoids a large headache-inducing refactor there.-- if (!canMoveToDashboard) {- if (destination.model === "dashboard") {- throw new Error(- "MoveModal can't move to a dashboard with canMoveToDashboard=false",- );- }-- return onMove({ id: destination.id, model: destination.model });- } else {- return onMove({- id: destination.id,- model: destination.model,- } as MoveDestination);- }- },- [onMove, canMoveToDashboard],- );-- const models: CollectionPickerModel[] = canMoveToDashboard- ? ["collection", "dashboard"]- : ["collection"];-- const restrictToNamespace: string | undefined = movingCollectionId- ? isMovingTenantCollection && PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE- ? PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE- : "default"- : undefined;-- return (- <CollectionPickerModal- title={title}- value={{- id: initialCollectionId,- model: "collection",- }}- onChange={handleMove}- models={models}- options={{- showSearch: !isMovingTenantCollection,- allowCreateNew: true,- hasConfirmButtons: true,- showRootCollection: !isMovingTenantCollection,- showPersonalCollections: !isMovingTenantCollection,- confirmButtonText: t`Move`,- savingModel,- hasRecents: !isMovingTenantCollection,- restrictToNamespace,- }}- shouldDisableItem={shouldDisableItem}- entityType={entityType}- searchResultFilter={searchResultFilter}- recentFilter={recentFilter}- onClose={onClose}- />- );-};--interface BulkMoveModalProps {- onClose: () => void;- onMove: OnMoveWithOneItem<MoveDestination>;- selectedItems: CollectionItem[];- initialCollectionId: CollectionId;- recentAndSearchFilter?: (item: CollectionPickerItem) => boolean;-}--export const BulkMoveModal = ({- onClose,- onMove,- selectedItems,- initialCollectionId,- recentAndSearchFilter,-}: BulkMoveModalProps) => {- const movingCollectionIds = selectedItems- .filter((item: CollectionItem) => isItemCollection(item))- .map((item: CollectionItem) => String(item.id));-- const shouldDisableItem = (item: CollectionPickerItem): boolean => {- if (movingCollectionIds.length > 0) {- const collectionItemFullPath =- (item?.effective_location ?? item?.location)- ?.split("/")- .map(String)- .concat(String(item.id)) ?? [];- if (- _.intersection(collectionItemFullPath, movingCollectionIds).length > 0- ) {- return true;- }- }-- if (item.model === "collection") {- const hasInvalidItem = selectedItems.some(- (selectedItem) =>- !canPlaceEntityInCollectionOrDescendants(- selectedItem.model,- getCollectionType(item),- ),- );- if (hasInvalidItem) {- return true;- }- }-- return false;- };-- const searchResultFilter = makeSearchResultFilter([- shouldDisableItem,- recentAndSearchFilter,- ]);- const recentFilter = makeRecentFilter([- shouldDisableItem,- recentAndSearchFilter,- ]);-- const title =- selectedItems.length > 1- ? t`Move ${selectedItems.length} items?`- : t`Move "${selectedItems[0].name}"?`;-- const canMoveToDashboard = selectedItems.every(- (item) => item.model === "card",- );-- const models: CollectionPickerModel[] = canMoveToDashboard- ? ["collection", "dashboard"]- : ["collection"];-- const canSelectItem = useCallback(- (item: CollectionPickerItem) => {- if (item.model === "collection") {- return selectedItems.every((selectedItem) =>- canPlaceEntityInCollection(- selectedItem.model,- getCollectionType(item),- ),- );- }- return true;- },- [selectedItems],- );-- const handleMove = useCallback(- async (destination: CollectionPickerValueItem) => {- return onMove({- id: destination.id,- model: destination.model,- });- },- [onMove],- );-- return (- <CollectionPickerModal- title={title}- value={{- id: initialCollectionId,- model: "collection",- }}- onChange={handleMove}- options={{- showSearch: true,- allowCreateNew: true,- hasConfirmButtons: true,- showRootCollection: true,- showPersonalCollections: true,- confirmButtonText: t`Move`,- }}- shouldDisableItem={shouldDisableItem}- canSelectItem={canSelectItem}- searchResultFilter={searchResultFilter}- recentFilter={recentFilter}- onClose={onClose}- models={models}- />- );-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal.tsxnew file mode 100644index 00000000000..5def29fa0b7--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/CollectionPickerModal.tsx@@ -0,0 +1,126 @@+import { useCallback, useMemo } from "react";+import { t } from "ttag";++import {+ type EntityType,+ canPlaceEntityInCollection,+ canPlaceEntityInCollectionOrDescendants,+} from "metabase/collections/utils";+import { PLUGIN_TENANTS } from "metabase/plugins/oss/tenants";++import {+ EntityPickerModal,+ type EntityPickerModalProps,+ type OmniPickerItem,+} from "../EntityPicker";+import { getCollectionType } from "../EntityPicker/utils";++import type { CollectionPickerValueItem } from "./types";++const baseCanSelectItem = (+ item: OmniPickerItem,+): item is CollectionPickerValueItem => {+ return (+ !!item &&+ "can_write" in item &&+ item.can_write !== false &&+ (item.model === "collection" || item.model === "dashboard")+ );+};++export type CollectionPickerModalProps = Omit<+ EntityPickerModalProps,+ "models" | "onChange"+> & {+ entityType?: EntityType;+ onChange: (newItem: CollectionPickerValueItem) => void;+};++/**+ * A picker that only picks collections or dashboards+ */+export const CollectionPickerModal = ({+ title = t`Choose a collection`,+ entityType,+ isDisabledItem: isDisabledItemProp,+ isHiddenItem: isHiddenItemProp,+ isSelectableItem: isSelectableItemProp,+ onChange,+ ...props+}: CollectionPickerModalProps) => {+ const shouldDisableItem = useMemo(() => {+ const entityTypeCheck = entityType+ ? (item: OmniPickerItem) => {+ if (item.model === "collection") {+ return !canPlaceEntityInCollectionOrDescendants(+ entityType,+ getCollectionType(item),+ );+ }+ return false;+ }+ : undefined;++ if (isDisabledItemProp && entityTypeCheck) {+ return (item: OmniPickerItem) => {+ return isDisabledItemProp(item) || entityTypeCheck(item);+ };+ }++ return isDisabledItemProp || entityTypeCheck;+ }, [isDisabledItemProp, entityType]);++ // dashboards act as collections for cards+ const models: EntityPickerModalProps["models"] =+ entityType === "card" ? ["dashboard", "collection"] : ["collection"];++ // canSelectItem determines if the Confirm button should be enabled+ // Namespace roots can be navigated into but not selected as final destinations+ const canSelectItem = useCallback(+ (item: OmniPickerItem): item is CollectionPickerValueItem => {+ if (!baseCanSelectItem(item)) {+ return false;+ }++ if (isSelectableItemProp && !isSelectableItemProp(item)) {+ return false;+ }++ if (entityType && item.model === "collection") {+ const collectionType = getCollectionType(item);+ if (!canPlaceEntityInCollection(entityType, collectionType)) {+ return false;+ }+ }++ if (+ !PLUGIN_TENANTS.canPlaceEntityInCollection({+ entityType,+ collection: item,+ })+ ) {+ return false;+ }++ return true;+ },+ [entityType, isSelectableItemProp],+ );++ const handleChange = (newItem: OmniPickerItem) => {+ if (canSelectItem(newItem)) {+ onChange(newItem);+ }+ };++ return (+ <EntityPickerModal+ title={title}+ isDisabledItem={shouldDisableItem}+ isSelectableItem={canSelectItem}+ {...props}+ onChange={handleChange}+ models={models}+ />+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemList.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemList.tsxdeleted file mode 100644index 1fe997d50dc..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemList.tsx+++ /dev/null@@ -1,62 +0,0 @@-import { skipToken, useListCollectionItemsQuery } from "metabase/api";-import type { CollectionItemModel } from "metabase-types/api";--import { ItemList } from "../../../EntityPicker";-import type { CollectionItemListProps, CollectionPickerItem } from "../types";--const validModels: CollectionItemModel[] = [- "collection",- "dashboard",- "document",- "card",- "dataset",- "metric",- "table",-];--const getValidCollectionItemModels = (models?: CollectionItemModel[]) =>- models ? models.filter((model) => validModels.includes(model)) : undefined;--export const CollectionItemList = ({- query,- onClick,- selectedItem,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,-}: CollectionItemListProps) => {- const {- data: items,- error,- isLoading,- } = useListCollectionItemsQuery<{- data: {- data: CollectionPickerItem[];- };- error: any;- isLoading: boolean;- }>(- query- ? {- ...query,- models: getValidCollectionItemModels(query.models),- include_can_run_adhoc_query: true,- }- : skipToken,- );-- return (- <ItemList- items={items?.data}- isLoading={isLoading}- error={error}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- />- );-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemPickerResolver.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemPickerResolver.tsxdeleted file mode 100644index 4393a000fb1..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemPickerResolver.tsx+++ /dev/null@@ -1,129 +0,0 @@-import _ from "underscore";--import { TablePicker } from "metabase/common/components/Pickers/TablePicker";-import { PERSONAL_COLLECTIONS } from "metabase/entities/collections";-import { PLUGIN_TENANTS } from "metabase/plugins";--import type { CollectionItemListProps, CollectionPickerItem } from "../types";--import { CollectionItemList } from "./CollectionItemList";-import { DashboardItemList } from "./DashboardItemList";-import { PersonalCollectionsItemList } from "./PersonalCollectionItemList";-import { RootItemList } from "./RootItemList";--export const CollectionItemPickerResolver = ({- onClick,- selectedItem,- options,- query,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,- entity = "collection",- initialValue,- tablesPath,- onTablesPathChange,-}: CollectionItemListProps) => {- if (!query) {- return (- <RootItemList- options={options}- selectedItem={selectedItem}- onClick={onClick}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- />- );- }-- if (query.id === PERSONAL_COLLECTIONS.id) {- return (- <PersonalCollectionsItemList- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- options={options}- />- );- }-- if (query.id === PLUGIN_TENANTS.TENANT_SPECIFIC_COLLECTIONS?.id) {- return (- <PLUGIN_TENANTS.TenantSpecificCollectionsItemList- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- options={options}- />- );- }-- // Route to tenant collection list only for the root tenant collection- // (not for subcollections within the tenant namespace)- if (query.id === "tenant") {- return (- <PLUGIN_TENANTS.TenantCollectionItemList- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- options={options}- />- );- }-- if (entity === "dashboard") {- return (- <DashboardItemList- query={query}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- options={options}- />- );- }-- if (query?.id === "databases") {- return (- <TablePicker- value={initialValue}- onItemSelect={(i) => onClick(i as unknown as CollectionPickerItem)}- path={tablesPath}- onPathChange={onTablesPathChange || _.noop}- shouldDisableItem={(i) =>- shouldDisableItem?.(i as unknown as CollectionPickerItem) ||- !shouldShowItem?.(i as unknown as CollectionPickerItem) ||- false- }- />- );- }-- return (- <CollectionItemList- query={query}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- options={options}- />- );-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/CollectionPicker.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/CollectionPicker.tsxdeleted file mode 100644index c55eff849d2..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/CollectionPicker.tsx+++ /dev/null@@ -1,285 +0,0 @@-import type { Ref } from "react";-import { forwardRef, useCallback, useImperativeHandle, useMemo } from "react";-import { useDeepCompareEffect } from "react-use";--import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { useSelector } from "metabase/lib/redux";-import { getUserPersonalCollectionId } from "metabase/selectors/user";-import type { Collection, Dashboard } from "metabase-types/api";--import { LoadingSpinner, NestedItemPicker } from "../../../../EntityPicker";-import { handleNewDashboard as handleNewDashboardUtil } from "../../../DashboardPicker/utils";-import { useGetInitialContainer } from "../../../hooks";-import { getCollectionIdPath, getStateFromIdPath } from "../../../utils";-import { useEnsureCollectionSelected } from "../../hooks";-import type {- CollectionPickerItem,- CollectionPickerModel,- CollectionPickerOptions,- CollectionPickerStatePath,-} from "../../types";-import {- getParentCollectionId,- getPathLevelForItem,- isFolderFactory,-} from "../../utils";-import { CollectionItemPickerResolver } from "../CollectionItemPickerResolver";--const defaultOptions: CollectionPickerOptions = {- showPersonalCollections: true,- showRootCollection: true,- showLibrary: true,- showDatabases: true,-};--interface CollectionPickerProps {- initialValue?: Pick<CollectionPickerItem, "id" | "model">;- options?: CollectionPickerOptions;- path: CollectionPickerStatePath | undefined;- shouldDisableItem?: (item: CollectionPickerItem) => boolean;- onInit: (item: CollectionPickerItem) => void;- onItemSelect: (item: CollectionPickerItem) => void;- onPathChange: (path: CollectionPickerStatePath) => void;- models?: CollectionPickerModel[];-}--const DEFAULT_MODELS: CollectionPickerModel[] = ["collection"];--export const CollectionPickerInner = (- {- initialValue,- options = defaultOptions,- path: pathProp,- shouldDisableItem,- onInit,- onItemSelect,- onPathChange,- models = DEFAULT_MODELS,- }: CollectionPickerProps,- ref: Ref<unknown>,-) => {- const pathOptions = useMemo(- () => ({- models,- namespace: options.namespace,- }),- [models, options?.namespace],- );-- const defaultPath = useMemo(() => {- return getStateFromIdPath({- idPath: ["root"],- ...pathOptions,- });- }, [pathOptions]);- const path = pathProp ?? defaultPath;- const {- currentCollection,- currentDashboard,- error,- isLoading: loadingCurrentCollection,- } = useGetInitialContainer(initialValue);-- const userPersonalCollectionId = useSelector(getUserPersonalCollectionId);-- const onFolderSelect = useCallback(- ({ folder }: { folder: CollectionPickerItem }) => {- const newPath = getStateFromIdPath({- idPath: getCollectionIdPath(folder, userPersonalCollectionId),- ...pathOptions,- });- onItemSelect(folder);- onPathChange(newPath);- },- [onItemSelect, onPathChange, userPersonalCollectionId, pathOptions],- );-- const handleItemSelect = useCallback(- (item: CollectionPickerItem) => {- const pathLevel = getPathLevelForItem(- item,- path,- userPersonalCollectionId,- );-- const newPath = path.slice(0, pathLevel + 1);- newPath[newPath.length - 1].selectedItem = item;-- onItemSelect(item);- onPathChange(newPath);- },- [path, onItemSelect, onPathChange, userPersonalCollectionId],- );-- const handleNewCollection = useCallback(- (newCollection: Collection) => {- const parentCollectionId = getParentCollectionId(newCollection.location);-- const newCollectionItem: CollectionPickerItem = {- ...newCollection,- collection_id: parentCollectionId,- model: "collection",- };-- const selectedItem = path[path.length - 1]?.selectedItem;-- if (selectedItem && selectedItem.model === "collection") {- // if the currently selected item is not a folder, it will be once we create a new collection within it- // so we need to select it-- const newPath: CollectionPickerStatePath = [- ...path,- {- query: {- id: parentCollectionId,- models: ["collection"],- namespace: options.namespace,- },- selectedItem: newCollectionItem,- },- ];- onItemSelect(newCollectionItem);- onPathChange(newPath);- return;- }-- handleItemSelect(newCollectionItem);- },- [path, handleItemSelect, onItemSelect, onPathChange, options.namespace],- );-- const handleNewDashboard = useCallback(- (newDashboard: Dashboard) => {- handleNewDashboardUtil(- newDashboard,- path,- onItemSelect,- userPersonalCollectionId,- handleItemSelect,- onPathChange,- );- },- [- path,- onItemSelect,- userPersonalCollectionId,- handleItemSelect,- onPathChange,- ],- );-- // Exposing onNewCollection so that parent can select newly created- // folder- useImperativeHandle(- ref,- () => ({- onNewCollection: handleNewCollection,- onNewDashboard: handleNewDashboard,- }),- [handleNewCollection, handleNewDashboard],- );-- useDeepCompareEffect(- function setInitialPath() {- if (!pathProp && currentDashboard?.collection) {- const newPath = getStateFromIdPath({- idPath: getCollectionIdPath(- {- ...currentDashboard.collection,- location: currentDashboard.collection?.effective_location,- is_personal: currentDashboard.collection?.is_personal,- model: "collection",- },- userPersonalCollectionId,- ),- ...pathOptions,- });-- const newSelectedItem = {- id: currentDashboard.id,- model: "dashboard" as const,- name: currentDashboard.name,- };-- newPath[newPath.length - 1].selectedItem = newSelectedItem;-- onPathChange(newPath);-- if (currentDashboard.collection?.can_write) {- // start with the current item selected if we can- onItemSelect({- ...currentDashboard.collection,- model: "dashboard",- });- }- }- // do not overwrite the previously selected item when the user switches- // tabs; in this case the component is unmounted and this hook runs again- else if (!pathProp && currentCollection?.id) {- const newPath = getStateFromIdPath({- idPath: getCollectionIdPath(- {- ...currentCollection,- id: currentCollection.id,- location: currentCollection.effective_location,- is_personal: currentCollection.is_personal,- type: currentCollection.type,- model: "collection",- },- userPersonalCollectionId,- ),- ...pathOptions,- });- onPathChange(newPath);-- if (currentCollection.can_write) {- // start with the current item selected if we can- onItemSelect({- ...currentCollection,- model: "collection",- });- }- }- },- [- pathProp,- pathOptions,- currentCollection,- userPersonalCollectionId,- onPathChange,- ],- );-- useEnsureCollectionSelected({- currentCollection,- currentDashboard,- enabled: path === defaultPath,- options,- useRootCollection: initialValue?.id == null,- onInit,- });-- const isFolder = useMemo(() => isFolderFactory(models), [models]);-- if (error) {- return <LoadingAndErrorWrapper error={error} />;- }-- if (loadingCurrentCollection) {- return <LoadingSpinner />;- }-- return (- <NestedItemPicker- isFolder={isFolder}- shouldDisableItem={shouldDisableItem}- options={options}- onFolderSelect={onFolderSelect}- onItemSelect={handleItemSelect}- path={path}- listResolver={CollectionItemPickerResolver}- />- );-};--export const CollectionPicker = forwardRef(CollectionPickerInner);diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/index.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/index.tsdeleted file mode 100644index ac7145e8390..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./CollectionPicker";diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/common.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/common.unit.spec.tsxdeleted file mode 100644index 62513c1e705..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/common.unit.spec.tsx+++ /dev/null@@ -1,100 +0,0 @@-import userEvent from "@testing-library/user-event";--import { act, screen, waitFor, within } from "__support__/ui";--import { setup } from "./setup";--describe("CollectionPicker", () => {- afterEach(() => {- jest.restoreAllMocks();- });-- it("should select the root collection by default", async () => {- act(() => {- setup();- });-- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toBeInTheDocument();-- expect(- await screen.findByRole("link", { name: /Collection 2/ }),- ).toBeInTheDocument();- });-- it("should render the path to the value provided", async () => {- act(() => {- setup({ initialValue: { id: 3, model: "collection" } });- });- await screen.findByRole("link", { name: /Our Analytics/ });- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should render the path back to personal collection", async () => {- act(() => {- setup({ initialValue: { id: 5, model: "collection" } });- });- expect(- await screen.findByRole("link", { name: /My personal collection/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /personal sub_collection/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should allow selecting, but not navigating into collections without children", async () => {- act(() => {- setup({ initialValue: { id: 1, model: "collection" } });- });-- const personalSubCollectionButton = await screen.findByRole("link", {- name: /personal sub_collection/,- });- expect(personalSubCollectionButton).not.toHaveAttribute("data-active");-- expect(- within(personalSubCollectionButton).queryByLabelText("chevronright icon"),- ).not.toBeInTheDocument();-- await userEvent.click(personalSubCollectionButton);-- expect(personalSubCollectionButton).toHaveAttribute("data-active", "true");-- // selecting an empty collection should not show another column- await waitFor(() =>- expect(- screen.queryByTestId("item-picker-level-2"),- ).not.toBeInTheDocument(),- );- });-- it("should allow disabling certain items in the collection picker", async () => {- act(() => {- setup({- initialValue: { id: 1, model: "collection" },- shouldDisableItem: () => true,- });- });-- const links = await screen.findAllByRole("link");- for (const link of links) {- expect(link).toHaveAttribute("data-disabled", "true");- }- });-});diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/enterprise.unit.spec.tsxdeleted file mode 100644index 078acf4138d..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/enterprise.unit.spec.tsx+++ /dev/null@@ -1,119 +0,0 @@-import userEvent from "@testing-library/user-event";--import { screen, waitFor } from "__support__/ui";-import { PLUGIN_TENANTS } from "metabase/plugins";--import { type SetupOpts, setup as coreSetup } from "./setup";--const setup = (opts: SetupOpts = {}) => coreSetup({ ...opts, ee: true });--describe("tenant collections", () => {- it("should show tenant collections in the root panel and build a path", async () => {- setup();-- expect(- await screen.findByRole("link", { name: /Shared collections/ }),- ).toBeInTheDocument();-- await userEvent.click(- screen.getByRole("link", { name: /Shared collections/ }),- );-- expect(- await screen.findByRole("link", { name: /tcoll/ }),- ).toBeInTheDocument();-- await userEvent.click(screen.getByRole("link", { name: /tcol/ }));-- expect(- await screen.findByRole("link", { name: /tsubcol/ }),- ).toBeInTheDocument();- });-- it("should handle a tenant collection as an initial value", async () => {- setup({- initialValue: {- model: "collection",- id: 7,- },- });-- expect(- await screen.findByRole("link", { name: /Shared collections/ }),- ).toHaveAttribute("data-active", "true");-- expect(await screen.findByRole("link", { name: /tcol/ })).toHaveAttribute(- "data-active",- "true",- );-- expect(- await screen.findByRole("link", { name: /tsubcol/ }),- ).toHaveAttribute("data-active", "true");- });-});--describe("restrictToNamespace option", () => {- it("should only show tenant collections when restricted to shared-tenant-collection namespace", async () => {- setup({- options: {- restrictToNamespace:- PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE ?? undefined,- },- });-- // Tenant root should be visible- expect(- await screen.findByRole("link", { name: /Shared collections/ }),- ).toBeInTheDocument();-- // Regular collections should NOT be visible- await waitFor(() => {- expect(- screen.queryByRole("link", { name: /Our Analytics/ }),- ).not.toBeInTheDocument();- });- expect(- screen.queryByRole("link", { name: /My personal collection/ }),- ).not.toBeInTheDocument();- });-- it("should hide tenant collections when restricted to default namespace", async () => {- setup({- options: {- restrictToNamespace: "default",- showRootCollection: true,- showPersonalCollections: true,- },- });-- // Regular collections should be visible- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();-- // Tenant root should NOT be visible- await waitFor(() => {- expect(- screen.queryByRole("link", { name: /Shared collections/ }),- ).not.toBeInTheDocument();- });- });-- it("should show all collections when restrictToNamespace is not set", async () => {- setup({- options: {- showRootCollection: true,- showPersonalCollections: true,- },- });-- // Both regular and tenant collections should be visible- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();- expect(- await screen.findByRole("link", { name: /Shared collections/ }),- ).toBeInTheDocument();- });-});diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/setup.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/setup.tsxdeleted file mode 100644index 8e6610730bb..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/setup.tsx+++ /dev/null@@ -1,286 +0,0 @@-import fetchMock from "fetch-mock";-import { useState } from "react";--import { setupEnterprisePlugins } from "__support__/enterprise";-import {- setupCollectionItemsEndpoint,- setupDatabaseListEndpoint,- setupRootCollectionItemsEndpoint,- setupTenantCollectionItemsEndpoint,-} from "__support__/server-mocks";-import { mockSettings } from "__support__/settings";-import { mockGetBoundingClientRect, renderWithProviders } from "__support__/ui";-import type {- Collection,- CollectionId,- CollectionItem,-} from "metabase-types/api";-import {- createMockCollection,- createMockCollectionItem,- createMockSettings,- createMockTokenFeatures,-} from "metabase-types/api/mocks";-import { createMockState } from "metabase-types/store/mocks";--import type {- CollectionPickerItem,- CollectionPickerOptions,- CollectionPickerStatePath,-} from "../../../types";-import { CollectionPicker } from "../CollectionPicker";--type MockCollection = {- id: CollectionId;- name: string;- location: string | null;- effective_location: string | null;- is_personal: boolean;- is_shared_tenant_collection?: boolean;- collections: MockCollection[];- here: CollectionItem["here"];-};--const collectionTree: MockCollection[] = [- {- id: "root",- name: "Our Analytics",- location: null,- effective_location: null,- is_personal: false,- here: ["collection"],- collections: [- {- id: 4,- name: "Collection 4",- location: "/",- effective_location: "/",- is_personal: false,- here: ["collection"],- collections: [- {- id: 3,- name: "Collection 3",- collections: [],- location: "/4/",- effective_location: "/4/",- here: [],- is_personal: false,- },- ],- },- {- id: 2,- is_personal: false,- name: "Collection 2",- location: "/",- effective_location: "/",- here: [],- collections: [],- },- ],- },- {- name: "My personal collection",- id: 1,- location: "/",- effective_location: "/",- is_personal: true,- here: ["collection"],- collections: [- {- id: 5,- location: "/1/",- effective_location: "/1/",- name: "personal sub_collection",- is_personal: true,- here: [],- collections: [],- },- ],- },-];--const tenantCollectionsTree: MockCollection[] = [- {- name: "tcoll",- id: 6,- location: "/",- effective_location: "/",- is_personal: false,- is_shared_tenant_collection: true,- here: ["collection"],- collections: [- {- id: 7,- location: "/6/",- effective_location: "/6/",- name: "tsubcoll",- is_personal: false,- is_shared_tenant_collection: true,- collections: [],- here: [],- },- ],- },-];--const flattenCollectionTree = (- node: MockCollection[],-): Omit<MockCollection, "collections">[] => {- return [- ...node.map((n) => ({- name: n.name,- id: n.id,- is_personal: !!n.is_personal,- ...(n.is_shared_tenant_collection !== undefined && {- is_shared_tenant_collection: n.is_shared_tenant_collection,- }),- location: n.location,- effective_location: n.effective_location,- here: n.here,- })),- ].concat(...node.map((n) => flattenCollectionTree(n.collections)));-};--const mockCollectionToCollectionItem = (c: MockCollection) =>- createMockCollectionItem({- id: c.id as number,- name: c.name,- model: "collection",- location: c.location || "/",- effective_location: c.effective_location || "/",- here: c.here,- ...(c.is_shared_tenant_collection && {- namespace: "shared-tenant-collection",- }),- });--const setupCollectionTreeMocks = (node: MockCollection[]) => {- node.forEach((n) => {- const collectionItems = n.collections.map(mockCollectionToCollectionItem);-- // Skip root since it's handled separately (tenant-aware in EE mode)- if (n.id !== "root") {- setupCollectionItemsEndpoint({- collection: createMockCollection({ id: n.id }),- collectionItems,- models: ["collection"],- });- }-- if (collectionItems.length > 0) {- setupCollectionTreeMocks(n.collections);- }- });-};--const setupTenantCollectionTreeMocks = (node: MockCollection[]) => {- node.forEach((n) => {- const collectionItems = n.collections.map(mockCollectionToCollectionItem);-- setupTenantCollectionItemsEndpoint({- collection: createMockCollection({ id: n.id }),- collectionItems,- models: ["collection"],- });-- if (collectionItems.length > 0) {- setupTenantCollectionTreeMocks(n.collections);- }- });-};--export interface SetupOpts {- initialValue?: {- id: CollectionId;- model: "collection";- };- onItemSelect?: (item: CollectionPickerItem) => void;- shouldDisableItem?: (item: CollectionPickerItem) => boolean;- ee?: boolean;- options?: CollectionPickerOptions;-}--export const setup = ({- initialValue = { id: "root", model: "collection" },- onItemSelect = jest.fn<void, [CollectionPickerItem]>(),- shouldDisableItem,- ee = false,- options,-}: SetupOpts = {}) => {- mockGetBoundingClientRect();-- const allCollections = flattenCollectionTree(collectionTree).map((c) =>- createMockCollection(c as Collection),- );-- //Setup individual collection mocks- allCollections.forEach((collection) => {- fetchMock.get(`path:/api/collection/${collection.id}`, collection);- });-- setupCollectionTreeMocks(collectionTree);-- setupRootCollectionItemsEndpoint({- rootCollectionItems: collectionTree[0].collections.map(- mockCollectionToCollectionItem,- ),- tenantRootItems: ee- ? [mockCollectionToCollectionItem(tenantCollectionsTree[0])]- : [],- });-- setupDatabaseListEndpoint([]);-- const settings = mockSettings(- createMockSettings({- "token-features": createMockTokenFeatures({- tenants: ee ? true : false,- }),- "use-tenants": ee ? true : false,- }),- );-- // Update root mock to handle tenant namespace in EE mode- if (ee) {- setupEnterprisePlugins();- setupTenantCollectionTreeMocks(tenantCollectionsTree);-- const allTenantCollections = flattenCollectionTree(tenantCollectionsTree);-- //Setup individual collection mocks- allTenantCollections.forEach((collection) => {- fetchMock.get(`path:/api/collection/${collection.id}`, {- ...collection,- namespace: "shared-tenant-collection",- });- });- }-- function TestComponent() {- const [path, setPath] = useState<CollectionPickerStatePath>();-- const handlePathChange = (newPath: CollectionPickerStatePath) => {- setPath(newPath);- };-- return (- <CollectionPicker- initialValue={initialValue}- path={path}- onInit={jest.fn()}- onItemSelect={onItemSelect}- onPathChange={handlePathChange}- shouldDisableItem={shouldDisableItem}- options={options}- />- );- }-- return renderWithProviders(<TestComponent />, {- storeInitialState: createMockState({- settings,- }),- });-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPickerModal.tsxdeleted file mode 100644index 08ce9230be4..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPickerModal.tsx+++ /dev/null@@ -1,382 +0,0 @@-import { useCallback, useMemo, useRef, useState } from "react";-import { t } from "ttag";-import _ from "underscore";--import {- type EntityType,- canPlaceEntityInCollection,- canPlaceEntityInCollectionOrDescendants,-} from "metabase/collections/utils";-import { useToggle } from "metabase/common/hooks/use-toggle";-import { Button, Icon } from "metabase/ui";-import type { RecentItem, SearchResult } from "metabase-types/api";--import {- EntityPickerModal,- type EntityPickerTab,- defaultOptions,-} from "../../../EntityPicker";-import { useLogRecentItem } from "../../../EntityPicker/hooks/use-log-recent-item";-import { NewDashboardDialog } from "../../DashboardPicker/components/NewDashboardDialog";-import { getNamespaceForItem, isNamespaceRoot } from "../../utils";-import type {- CollectionPickerItem,- CollectionPickerModel,- CollectionPickerOptions,- CollectionPickerStatePath,- CollectionPickerValueItem,-} from "../types";-import { getCollectionType } from "../types";--import { CollectionPicker } from "./CollectionPicker/CollectionPicker";-import { NewCollectionDialog } from "./NewCollectionDialog";--export interface CollectionPickerModalProps {- title?: string;- onChange: (item: CollectionPickerValueItem) => void;- onClose: () => void;- options?: CollectionPickerOptions;- value?: Pick<CollectionPickerValueItem, "id" | "model" | "collection_id">;- shouldDisableItem?: (item: CollectionPickerItem) => boolean;- entityType?: EntityType;- searchResultFilter?: (searchResults: SearchResult[]) => SearchResult[];- recentFilter?: (recentItems: RecentItem[]) => RecentItem[];- models?: CollectionPickerModel[];- canSelectItem?: (item: CollectionPickerItem) => boolean;-}--const baseCanSelectItem = (- item: Pick<CollectionPickerItem, "can_write" | "model"> | null | undefined,-): item is CollectionPickerValueItem => {- return (- !!item &&- item.can_write !== false &&- (item.model === "collection" || item.model === "dashboard")- );-};--const searchFilter = (- searchResults: SearchResult[],- entityType?: EntityType,-): SearchResult[] => {- return searchResults.filter((result) => {- if (!result.can_write || result.collection.type === "trash") {- return false;- }-- if (result.model === "collection" && entityType) {- return canPlaceEntityInCollection(entityType, result.collection_type);- }-- return true;- });-};--const recentItemFilter = (- recentItems: RecentItem[],- entityType?: EntityType,-): RecentItem[] => {- if (!entityType) {- return recentItems;- }-- return recentItems.filter((item) => {- if (item.model === "collection") {- return canPlaceEntityInCollection(entityType, item.collection_type);- }- return true;- });-};--export const CollectionPickerModal = ({- title = t`Choose a collection`,- onChange,- onClose,- value,- options = defaultOptions,- shouldDisableItem: shouldDisableItemProp,- entityType,- searchResultFilter,- recentFilter,- models: modelsProp,- canSelectItem: _canSelectItem,-}: CollectionPickerModalProps) => {- options = { ...defaultOptions, ...options };-- const models = modelsProp || ["collection"];-- const shouldDisableItem = useMemo(() => {- const entityTypeCheck = entityType- ? (item: CollectionPickerItem) => {- if (item.model === "collection") {- return !canPlaceEntityInCollectionOrDescendants(- entityType,- getCollectionType(item),- );- }- return false;- }- : undefined;-- if (shouldDisableItemProp && entityTypeCheck) {- return (item: CollectionPickerItem) => {- return shouldDisableItemProp(item) || entityTypeCheck(item);- };- }-- return shouldDisableItemProp || entityTypeCheck;- }, [shouldDisableItemProp, entityType]);-- const [selectedItem, setSelectedItem] = useState<CollectionPickerItem | null>(- null,- );-- // canSelectItem determines if the Confirm button should be enabled- // Namespace roots can be navigated into but not selected as final destinations- const canSelectItem = useCallback(- (- item:- | Pick<CollectionPickerItem, "id" | "can_write" | "model">- | null- | undefined,- ): item is CollectionPickerValueItem => {- if (!baseCanSelectItem(item)) {- return false;- }-- if (_canSelectItem && !_canSelectItem(item)) {- return false;- }-- if (entityType && item.model === "collection") {- const collectionType = getCollectionType(item as CollectionPickerItem);- if (!canPlaceEntityInCollection(entityType, collectionType)) {- return false;- }- }-- // Check if namespace root is disallowed for this savingModel- if (- options.savingModel !== "collection" &&- isNamespaceRoot(item as CollectionPickerItem)- ) {- return false;- }-- return true;- },- [_canSelectItem, entityType, options.savingModel],- );-- const { tryLogRecentItem } = useLogRecentItem();-- const handleChange = useCallback(- async (item: CollectionPickerValueItem) => {- await onChange(item);- tryLogRecentItem(item);- },- [onChange, tryLogRecentItem],- );-- const [- isCreateCollectionDialogOpen,- {- turnOn: openCreateCollectionDialog,- turnOff: closeCreateCollectionDialog,- },- ] = useToggle(false);-- const [- isCreateDashboardDialogOpen,- { turnOn: openCreateDashboardDialog, turnOff: closeCreateDashboardDialog },- ] = useToggle(false);-- const pickerRef = useRef<{- onNewCollection: (item: CollectionPickerItem) => void;- onNewDashboard: (item: CollectionPickerItem) => void;- }>();-- const handleInit = useCallback((item: CollectionPickerItem) => {- setSelectedItem((current) => current ?? item);- }, []);-- const handleItemSelect = useCallback(- async (item: CollectionPickerItem) => {- if (options.hasConfirmButtons) {- setSelectedItem(item);- } else if (canSelectItem(item)) {- await handleChange(item);- }- },- [handleChange, options, canSelectItem],- );-- const handleConfirm = async () => {- if (selectedItem && canSelectItem(selectedItem)) {- await handleChange(selectedItem);- }- };-- const canCreateCollectionInSelected =- selectedItem?.can_write !== false &&- (selectedItem?.model !== "collection" ||- canPlaceEntityInCollection("collection", selectedItem.type));-- const modalActions = options.allowCreateNew- ? _.compact([- models.includes("dashboard") && (- <Button- key="dashboard-on-the-go"- miw="9.5rem"- onClick={openCreateDashboardDialog}- leftSection={<Icon name="add_to_dash" />}- disabled={Boolean(- selectedItem?.can_write === false ||- (selectedItem && isNamespaceRoot(selectedItem)),- )}- >- {t`New dashboard`}- </Button>- ),- <Button- key="collection-on-the-go"- miw="9.5rem"- onClick={openCreateCollectionDialog}- leftSection={<Icon name="collection" />}- disabled={!canCreateCollectionInSelected}- >- {t`New collection`}- </Button>,- ])- : [];-- const [collectionsPath, setCollectionsPath] =- useState<CollectionPickerStatePath>();-- const tabs: EntityPickerTab<- CollectionPickerItem["id"],- CollectionPickerItem["model"],- CollectionPickerItem- >[] = [- {- id: "collections-tab",- displayName: models.some((model) => model !== "collection")- ? t`Browse`- : t`Collections`,- models: models,- folderModels: ["collection"],- icon: "folder",- render: ({ onItemSelect }) => (- <CollectionPicker- initialValue={value}- options={options}- path={collectionsPath}- ref={pickerRef}- shouldDisableItem={shouldDisableItem}- onInit={handleInit}- onItemSelect={onItemSelect}- onPathChange={setCollectionsPath}- models={models}- />- ),- },- ];-- const handleNewCollectionCreate = (newCollection: CollectionPickerItem) => {- pickerRef.current?.onNewCollection(newCollection);- };-- const handleNewDashboardCreate = (newDashboard: CollectionPickerItem) => {- pickerRef.current?.onNewDashboard(newDashboard);- };-- const composedSearchResultFilter = useCallback(- (searchResults: SearchResult[]) => {- if (searchResultFilter) {- return searchFilter(searchResultFilter(searchResults), entityType);- }- return searchFilter(searchResults, entityType);- },- [searchResultFilter, entityType],- );-- const composedRecentFilter = useCallback(- (recentItems: RecentItem[]) => {- const filtered = recentItemFilter(recentItems, entityType);- if (recentFilter) {- return recentFilter(filtered);- }- return filtered;- },- [recentFilter, entityType],- );-- const parentCollectionId = useMemo(() => {- if (- selectedItem &&- isNamespaceRoot(selectedItem) &&- selectedItem.can_write- ) {- return selectedItem.id;- } else if (canSelectItem(selectedItem)) {- return selectedItem.model === "dashboard"- ? selectedItem.collection_id- : selectedItem.id;- } else if (canSelectItem(value)) {- return value.model === "dashboard" ? value.collection_id : value.id;- } else {- return "root";- }- }, [selectedItem, value, canSelectItem]);-- // Determine the effective namespace for creating new collections- // Priority: 1) options.namespace (explicit), 2) selectedItem namespace, 3) undefined- const effectiveNamespace = useMemo(() => {- // If explicitly set in options, use that- if (options.namespace) {- return options.namespace;- }-- // Get namespace from the currently selected item- return getNamespaceForItem(selectedItem);- }, [options.namespace, selectedItem]);-- return (- <>- <EntityPickerModal- title={title}- onItemSelect={handleItemSelect}- canSelectItem={- !isCreateCollectionDialogOpen &&- !isCreateDashboardDialogOpen &&- canSelectItem(selectedItem)- }- onConfirm={handleConfirm}- onClose={onClose}- selectedItem={selectedItem}- tabs={tabs}- options={options}- searchResultFilter={composedSearchResultFilter}- recentFilter={composedRecentFilter}- actionButtons={modalActions}- trapFocus={!isCreateCollectionDialogOpen}- disableCloseOnEscape={- isCreateCollectionDialogOpen || isCreateDashboardDialogOpen- }- />- <NewCollectionDialog- isOpen={isCreateCollectionDialogOpen}- onClose={closeCreateCollectionDialog}- parentCollectionId={parentCollectionId}- onNewCollection={handleNewCollectionCreate}- namespace={effectiveNamespace}- />- <NewDashboardDialog- isOpen={isCreateDashboardDialogOpen}- onClose={closeCreateDashboardDialog}- parentCollectionId={parentCollectionId}- onNewDashboard={handleNewDashboardCreate}- />- </>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/DashboardItemList.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/DashboardItemList.tsxdeleted file mode 100644index e79e6183527..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/DashboardItemList.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { skipToken, useListDashboardItemsQuery } from "metabase/api";--import { ItemList } from "../../../EntityPicker";-import type { CollectionItemListProps, CollectionPickerItem } from "../types";--export const DashboardItemList = ({- query,- onClick,- selectedItem,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,-}: CollectionItemListProps) => {- const {- data: dashboardItems,- error,- isLoading,- } = useListDashboardItemsQuery<{- data: {- data: CollectionPickerItem[];- };- error: any;- isLoading: boolean;- }>(query ? query : skipToken);-- return (- <ItemList- items={dashboardItems?.data}- isLoading={isLoading}- error={error}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- />- );-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.tsxdeleted file mode 100644index 3af1950e95e..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.tsx+++ /dev/null@@ -1,104 +0,0 @@-import { t } from "ttag";-import * as Yup from "yup";--import { useCreateCollectionMutation } from "metabase/api";-import { FormFooter } from "metabase/common/components/FormFooter";-import { useEscapeToCloseModal } from "metabase/common/hooks/use-escape-to-close-modal";-import {- Form,- FormErrorMessage,- FormProvider,- FormSubmitButton,- FormTextInput,-} from "metabase/forms";-import * as Errors from "metabase/lib/errors";-import { Button, Flex, Modal } from "metabase/ui";-import type { CollectionId, CollectionNamespace } from "metabase-types/api";--import type { CollectionPickerItem } from "../types";--const NEW_COLLECTION_SCHEMA = Yup.object({- name: Yup.string()- .required(Errors.required)- .max(100, Errors.maxLength)- .default(""),-});--interface NewCollectionDialogProps {- isOpen: boolean;- onClose: () => void;- parentCollectionId: CollectionId | null;- onNewCollection: (item: CollectionPickerItem) => void;- namespace?: CollectionNamespace;-}--export const NewCollectionDialog = ({- isOpen,- onClose,- parentCollectionId,- onNewCollection,- namespace,-}: NewCollectionDialogProps) => {- const [createCollection] = useCreateCollectionMutation();-- const onCreateNewCollection = async ({ name }: { name: string }) => {- // Virtual collection IDs like "root" and "tenant" should be converted to null- // These represent namespace roots which have no parent- const isVirtualRoot =- parentCollectionId === "root" || parentCollectionId === "tenant";-- const newCollection = await createCollection({- name,- parent_id: isVirtualRoot ? null : parentCollectionId,- namespace,- }).unwrap();-- onNewCollection({ ...newCollection, model: "collection" });- onClose();- };-- useEscapeToCloseModal(onClose, { capture: true });-- return (- <Modal- title={t`Create a new collection`}- opened={isOpen}- onClose={onClose}- data-testid="create-collection-on-the-go"- trapFocus={true}- withCloseButton={false}- closeOnEscape={false}- >- <FormProvider- initialValues={{ name: "" }}- validationSchema={NEW_COLLECTION_SCHEMA}- onSubmit={onCreateNewCollection}- >- {({ dirty }: { dirty: boolean }) => (- <Form>- <FormTextInput- name="name"- label={t`Give it a name`}- placeholder={t`My new collection`}- mb="1rem"- labelProps={{ my: "0.5rem" }}- data-autofocus- />- <FormFooter>- <FormErrorMessage inline />- <Flex style={{ flexShrink: 1 }} justify="flex-end" gap="sm">- <Button type="button" onClick={onClose}>{t`Cancel`}</Button>- <FormSubmitButton- type="submit"- label={t`Create`}- disabled={!dirty}- variant="filled"- />- </Flex>- </FormFooter>- </Form>- )}- </FormProvider>- </Modal>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.unit.spec.tsxdeleted file mode 100644index cf1d747c557..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.unit.spec.tsx+++ /dev/null@@ -1,97 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { renderWithProviders, screen } from "__support__/ui";-import type { CollectionId } from "metabase-types/api";--import { NewCollectionDialog } from "./NewCollectionDialog";--const setup = (- params: {- parentCollectionId: CollectionId | null;- } = {- parentCollectionId: "root",- },-) => {- const onClose = jest.fn();- const onNewCollection = jest.fn();- fetchMock.post("path:/api/collection", { id: 2 });- renderWithProviders(- <NewCollectionDialog- isOpen- onClose={onClose}- onNewCollection={onNewCollection}- {...params}- />,- );-};--describe("new collection dialog", () => {- it("should handle a parentCollectionId of root", async () => {- setup({- parentCollectionId: "root",- });- await userEvent.type(- screen.getByPlaceholderText("My new collection"),- "Test collection",- );- await userEvent.click(screen.getByRole("button", { name: "Create" }));-- const apiCalls = fetchMock.callHistory.calls("path:/api/collection");- expect(apiCalls).toHaveLength(1);-- const call = apiCalls[0];- const body = JSON.parse(call.options?.body as string);- expect(body.parent_id).toBe(null);- });-- it("should handle a normal parentCollectionId", async () => {- setup({ parentCollectionId: 12 });- await userEvent.type(- screen.getByPlaceholderText("My new collection"),- "Test collection",- );- await userEvent.click(screen.getByRole("button", { name: "Create" }));-- const apiCalls = fetchMock.callHistory.calls("path:/api/collection");- expect(apiCalls).toHaveLength(1);-- const call = apiCalls[0];- const body = JSON.parse(call.options?.body as string);- expect(body.parent_id).toBe(12);- });-- it("should handle a parentCollectionId of null", async () => {- setup({ parentCollectionId: null });- await userEvent.type(- screen.getByPlaceholderText("My new collection"),- "Test collection",- );- await userEvent.click(screen.getByRole("button", { name: "Create" }));-- const apiCalls = fetchMock.callHistory.calls("path:/api/collection");- expect(apiCalls).toHaveLength(1);-- const call = apiCalls[0];- const body = JSON.parse(call.options?.body as string);- expect(body.parent_id).toBe(null);- });-- it("should show validation error when name exceeds 100 characters", async () => {- setup({ parentCollectionId: "root" });- const longName = "a".repeat(101);- const input = screen.getByPlaceholderText("My new collection");- await userEvent.type(input, longName);- await userEvent.tab();-- expect(- await screen.findByText(/must be 100 characters or less/),- ).toBeInTheDocument();-- const createButton = screen.getByRole("button", { name: "Create" });- expect(createButton).toBeDisabled();-- const apiCalls = fetchMock.callHistory.calls("path:/api/collection");- expect(apiCalls).toHaveLength(0);- });-});diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/RootItemList.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/RootItemList.tsxdeleted file mode 100644index db874233692..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/RootItemList.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { ItemList } from "../../../EntityPicker";-import { useRootCollectionPickerItems } from "../hooks";-import type { CollectionItemListProps } from "../types";--export const RootItemList = ({- onClick,- selectedItem,- options,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,-}: CollectionItemListProps) => {- const { items, isLoading } = useRootCollectionPickerItems(options);-- return (- <ItemList- items={items}- isLoading={isLoading}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}- />- );-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/index.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/index.tsdeleted file mode 100644index 3784da5c5b8..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./CollectionPicker";-export * from "./CollectionPickerModal";diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.tsdeleted file mode 100644index a69971d6f0f..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts+++ /dev/null@@ -1,304 +0,0 @@-import { useEffect, useMemo, useState } from "react";-import { t } from "ttag";--import {- skipToken,- useGetCollectionQuery,- useListCollectionItemsQuery,- useListDatabasesQuery,-} from "metabase/api";-import { isRootCollection } from "metabase/collections/utils";-import { useGetPersonalCollection, useSetting } from "metabase/common/hooks";-import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";-import { useSelector } from "metabase/lib/redux";-import { PLUGIN_DATA_STUDIO, PLUGIN_TENANTS } from "metabase/plugins";-import { getUser, getUserIsAdmin } from "metabase/selectors/user";-import type { Collection, Dashboard } from "metabase-types/api";--import type { CollectionItemListProps, CollectionPickerItem } from "./types";--const personalCollectionsRoot: CollectionPickerItem = {- ...PERSONAL_COLLECTIONS,- can_write: false,- model: "collection",- location: "/",- description: "",- here: ["collection"],- below: ["collection"],-};--const getTenantSpecificCollectionsRoot = (): CollectionPickerItem | null => {- const base = PLUGIN_TENANTS.TENANT_SPECIFIC_COLLECTIONS;- if (!base) {- return null;- }- return {- ...base,- can_write: false,- model: "collection",- location: "/",- description: "",- here: ["collection", "card", "dashboard"],- below: ["collection"],- };-};--/**- * This is a special item list that exists "above" our analytics and might include:- * a) the highest-level collections the user can access (often "our analytics")- * b) the user's personal collection- * c) a top level folder including all personal collections (admin only)- */-export const useRootCollectionPickerItems = (- options: CollectionItemListProps["options"],-) => {- const isAdmin = useSelector(getUserIsAdmin);-- const { data: databaseData, isLoading: isLoadingDatabases } =- useListDatabasesQuery(undefined, { skip: !options.showDatabases });- const databases = databaseData?.data ?? [];- const tenantsEnabled = useSetting("use-tenants");- const currentUser = useSelector(getUser);-- const { data: personalCollection, isLoading: isLoadingPersonalCollection } =- useGetPersonalCollection();-- const { data: libraryCollection } =- PLUGIN_DATA_STUDIO.useGetLibraryCollection({- skip: !options.showLibrary,- });-- const {- data: personalCollectionItems,- isLoading: isLoadingPersonalCollectionItems,- } = useListCollectionItemsQuery(- personalCollection- ? {- id: personalCollection.id,- models: ["collection", "dashboard"],- limit: 0, // we only want total number of items- }- : skipToken,- );- const totalPersonalCollectionItems = personalCollectionItems?.total ?? 0;-- const {- data: rootCollection,- isLoading: isLoadingRootCollection,- error: rootCollectionError,- } = useGetCollectionQuery({ id: "root" });-- const items = useMemo(() => {- const collectionItems: CollectionPickerItem[] = [];-- if (- options?.restrictToNamespace === PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE- ) {- if (tenantsEnabled && currentUser) {- collectionItems.push({- name: t`Shared collections`,- id: "tenant",- namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,- here: ["collection", "card", "dashboard"],- description: null,- can_write: true,- model: "collection",- location: "/",- });- }- return collectionItems;- }-- if (- options.showLibrary &&- libraryCollection &&- options.namespace !== "snippets" &&- options.namespace !== "transforms"- ) {- collectionItems.push({- ...libraryCollection,- model: "collection",- moderated_status: null,- });- }-- if (options?.showDatabases && databases.length > 0) {- collectionItems.push({- id: "databases",- name: t`Databases`,- model: "collection",- can_write: true,- location: "/",- here: ["collection"],- below: ["table"],- });- }-- if (- options?.showRootCollection ||- options?.namespace === "snippets" ||- options?.namespace === "transforms"- ) {- if (rootCollection && !rootCollectionError) {- collectionItems.push({- ...rootCollection,- model: "collection",- here: ["collection"],- location: "/",- name:- options.namespace === "snippets"- ? t`SQL snippets`- : options.namespace === "transforms"- ? t`Transforms`- : rootCollection.name,- });- } else if (rootCollectionError) {- collectionItems.push({- name: t`Collections`,- id: "root",- here: ["collection"],- description: null,- can_write: false,- model: "collection",- location: "/",- });- }- }-- if (- options?.showPersonalCollections &&- options?.namespace !== "snippets" &&- options?.namespace !== "transforms" &&- currentUser &&- !!personalCollection- ) {- collectionItems.push({- ...personalCollection,- here: totalPersonalCollectionItems ? ["collection"] : [],- model: "collection",- can_write: true,- });-- if (isAdmin) {- collectionItems.push(personalCollectionsRoot);- }- }-- // Only show tenant collections if NOT restricted to a different namespace- // When restrictToNamespace is "default", we exclude tenant collections- const shouldShowTenantCollections =- tenantsEnabled &&- currentUser &&- options?.restrictToNamespace !== "default";-- if (shouldShowTenantCollections) {- collectionItems.push({- name: t`Shared collections`,- id: "tenant",- namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,- here: ["collection", "card", "dashboard"],- description: null,- can_write: true,- model: "collection",- location: "/",- });- }-- const userTenantCollectionId = currentUser?.tenant_collection_id;- if (shouldShowTenantCollections && userTenantCollectionId) {- collectionItems.push({- name: t`Our data`,- id: userTenantCollectionId,- here: ["collection", "card", "dashboard"],- description: null,- can_write: true,- model: "collection",- location: "/",- type: "tenant-specific-root-collection",- });- }-- if (shouldShowTenantCollections && isAdmin) {- const tenantSpecificRoot = getTenantSpecificCollectionsRoot();- if (tenantSpecificRoot) {- collectionItems.push(tenantSpecificRoot);- }- }-- return collectionItems;- }, [- personalCollection,- rootCollection,- isAdmin,- options,- databases.length,- rootCollectionError,- totalPersonalCollectionItems,- libraryCollection,- tenantsEnabled,- currentUser,- ]);-- const isLoading =- isLoadingDatabases ||- isLoadingRootCollection ||- isLoadingPersonalCollection ||- isLoadingPersonalCollectionItems;-- return { items, isLoading };-};--export const useEnsureCollectionSelected = ({- currentCollection,- currentDashboard,- enabled,- options,- useRootCollection,- onInit,-}: {- currentCollection: Collection | undefined;- currentDashboard: Dashboard | undefined;- enabled: boolean;- options: CollectionItemListProps["options"];- useRootCollection: boolean;- onInit: (item: CollectionPickerItem) => void;-}) => {- const [isEnabled, setIsEnabled] = useState(enabled);- // all this is done to acquire the name of the root collection, which getStateFromIdPath can't provide- const { items } = useRootCollectionPickerItems(options);-- const currentCollectionItem: CollectionPickerItem | undefined =- useMemo(() => {- if (!currentCollection && !currentDashboard) {- return undefined;- }-- if (currentDashboard) {- return {- ...currentDashboard,- model: "dashboard",- };- }-- if (currentCollection) {- return {- ...currentCollection,- model: "collection",- };- }-- // not possible, but typescript isn't smart enough to figure this out- // so the return types get messed up- }, [currentCollection, currentDashboard]);-- const defaultCollectionItem = useRootCollection- ? items.find(isRootCollection)- : currentCollectionItem;-- useEffect(() => {- if (isEnabled && defaultCollectionItem) {- onInit(defaultCollectionItem);- setIsEnabled(false); // ensure this effect runs only once- }- }, [isEnabled, defaultCollectionItem, onInit]);-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/index.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/index.tsindex 777db88cce3..71174678fef 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/index.ts+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/index.ts@@ -1,3 +1,2 @@-export * from "./components";-export * from "./hooks";export * from "./types";+export * from "./CollectionPickerModal";diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.tsindex ad083ac5fa2..c28ccdbb35c 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts@@ -1,114 +1,16 @@-import type {- CardId,- CollectionId,- CollectionItem,- CollectionItemModel,- CollectionNamespace,- CollectionType,- DashboardId,- ListCollectionItemsRequest,- SearchResult,-} from "metabase-types/api";+import type { CardId, CollectionId, DashboardId } from "metabase-types/api";-import type {- EntityPickerModalOptions,- ListProps,- PickerState,- TypeWithModel,-} from "../../EntityPicker";+import type { OmniPickerCollectionItem } from "../EntityPicker";export type CollectionItemId = CollectionId | CardId | DashboardId;-// internally, this picker supports all items that live in collections-// so that we can use its components for picking all of them-export type CollectionPickerModel = Extract<- CollectionItemModel,- "collection" | "card" | "dataset" | "metric" | "dashboard" | "table"->;--// we can enforce type safety at the boundary of a collection-only picker with this type-export type CollectionPickerValueModel = Extract<- CollectionPickerModel,- "collection" | "dashboard"->;--export type CollectionPickerItem = TypeWithModel<- CollectionItemId,- CollectionPickerModel-> &- Pick<- Partial<SearchResult>,- "description" | "can_write" | "database_id" | "collection_type"- > &- Partial<- Pick<- CollectionItem,- | "is_shared_tenant_collection"- | "is_tenant_dashboard"- | "collection_namespace"- >- > & {- location?: string | null;- effective_location?: string | null;- is_personal?: boolean;- collection_id?: CollectionId | null;- here?: CollectionItemModel[];- below?: CollectionItemModel[];- type?: CollectionType;- namespace?: CollectionNamespace;- };--/**- * Returns the collection type for an item.- * Recent items and search results use `collection_type` field,- * while regular collection picker items use `type` field.- */-export function getCollectionType(- item: CollectionPickerItem,-): CollectionType | null {- return item.collection_type ?? item.type ?? null;-}-export type CollectionPickerValueItem =- | (Omit<CollectionPickerItem, "model" | "id"> & {+ | (Omit<OmniPickerCollectionItem, "model" | "id"> & {id: CollectionId;model: "collection";})- | (Omit<CollectionPickerItem, "model" | "id"> & {+ | (Omit<OmniPickerCollectionItem, "model" | "id"> & {id: DashboardId;model: "dashboard";collection_id: CollectionId | null;});--export type CollectionPickerOptions = EntityPickerModalOptions & {- namespace?: CollectionNamespace;- allowCreateNew?: boolean;- showPersonalCollections?: boolean;- showRootCollection?: boolean;- showLibrary?: boolean;- /**- * When set to "collection", allows saving to namespace root collections- * (like tenant root). When null/undefined, namespace roots are disabled.- */- savingModel?: "collection" | null;- /**- * Restricts the picker to only show collections in a specific namespace.- * - When set to "shared-tenant-collection", only the tenant root is shown.- * - When set to "default", the tenant root is hidden and regular collections are shown.- * - When undefined, all roots are shown (default behavior).- */- restrictToNamespace?: string;-};--export type CollectionItemListProps = ListProps<- CollectionItemId,- CollectionPickerModel,- CollectionPickerItem,- ListCollectionItemsRequest,- CollectionPickerOptions->;--export type CollectionPickerStatePath = PickerState<- CollectionPickerItem,- ListCollectionItemsRequest->;diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.tsdeleted file mode 100644index 4dcbc2154dc..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.ts+++ /dev/null@@ -1,74 +0,0 @@-import type {- CollectionId,- CollectionItemModel,- CollectionNamespace,- ListCollectionItemsRequest,-} from "metabase-types/api";--import type { PickerState } from "../../EntityPicker";-import type { QuestionPickerItem } from "../QuestionPicker";--import type { CollectionPickerItem } from "./types";--export const isFolderFactory =- (models: CollectionItemModel[]) =>- (item: CollectionPickerItem): boolean => {- return Boolean(- item.model === "collection" &&- models.some((model) => item?.here?.includes(model)),- );- };--export const getParentCollectionId = (- location?: string | null,- namespace?: CollectionNamespace | null,- type?: string | null,-): CollectionId => {- const parentCollectionId = location?.split("/").filter(Boolean).reverse()[0];- if (parentCollectionId) {- return Number(parentCollectionId);- }-- if (namespace === "shared-tenant-collection") {- return "tenant";- }-- if (type === "tenant-specific-root-collection") {- return "tenant-specific";- }-- return "root";-};--export const getPathLevelForItem = (- item: CollectionPickerItem | QuestionPickerItem,- path: PickerState<- CollectionPickerItem | QuestionPickerItem,- ListCollectionItemsRequest- >,- userPersonalCollectionId?: CollectionId,-): number => {- if (item.model === "collection" && item.id === userPersonalCollectionId) {- return 0;- }-- if (item.model === "table") {- // we can ignore this, it's not actually in the collection hierarchy- return 0;- }-- const parentCollectionId =- item.collection_id ??- getParentCollectionId(- item?.effective_location ?? item?.location,- item?.namespace,- item?.type,- );-- // set selected item at the correct level- const pathLevel = path.findIndex(- (level) => String(level?.query?.id) === String(parentCollectionId),- );-- return pathLevel === -1 ? 0 : pathLevel;-};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.unit.spec.tsdeleted file mode 100644index 05ae241b25a..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.unit.spec.ts+++ /dev/null@@ -1,55 +0,0 @@-import { getParentCollectionId } from "./utils";--describe("CollectionPicker > utils", () => {- describe("getParentCollectionId", () => {- it("should get the root collection for null values", () => {- expect(getParentCollectionId(null)).toEqual("root");- expect(getParentCollectionId("")).toEqual("root");- expect(getParentCollectionId(undefined)).toEqual("root");- });-- it("should get the last item in a slash-separated list", () => {- expect(getParentCollectionId("/1/2/3/4/5/")).toEqual(5);- expect(getParentCollectionId("1/2/3/4/5")).toEqual(5);- expect(getParentCollectionId("/100/200/300/400/500/")).toEqual(500);- });-- it.each([- {- location: "/",- namespace: "shared-tenant-collection" as const,- type: null,- desc: "shared tenant",- expected: "tenant",- },- {- location: null,- namespace: "shared-tenant-collection" as const,- type: null,- desc: "shared tenant",- expected: "tenant",- },- {- location: "/",- namespace: null,- type: "tenant-specific-root-collection",- desc: "dedicated tenant",- expected: "tenant-specific",- },- {- location: null,- namespace: null,- type: "tenant-specific-root-collection",- desc: "dedicated tenant",- expected: "tenant-specific",- },- ])(- "should return $expected for top-level $desc collection at $location",- ({ location, namespace, type, expected }) => {- expect(getParentCollectionId(location, namespace, type)).toEqual(- expected,- );- },- );- });-});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/DashboardPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/DashboardPickerModal.tsxnew file mode 100644index 00000000000..a697b75fe0a--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/DashboardPickerModal.tsx@@ -0,0 +1,66 @@+import { useCallback } from "react";+import { match } from "ts-pattern";+import { t } from "ttag";++import {+ EntityPickerModal,+ type EntityPickerModalProps,+ type OmniPickerItem,+} from "../EntityPicker";++export const DashboardPickerModal = ({+ title = t`Choose a dashboard`,+ onChange,+ onClose,+ value = { model: "collection", id: "root" },+ options = {},+ isSelectableItem: isSelectableItemProp,+ ...rest+}: Omit<EntityPickerModalProps, "models">) => {+ const searchParams:+ | { filter_items_in_personal_collection?: "only" | "exclude" }+ | undefined = match(options)+ .with({ hasRootCollection: false }, () => ({+ filter_items_in_personal_collection: "only" as const,+ }))+ .with({ hasPersonalCollections: false }, () => ({+ filter_items_in_personal_collection: "exclude" as const,+ }))+ .otherwise(() => undefined);++ const canCreateDashboards = options.canCreateDashboards ?? true;++ const canSelectItem = useCallback(+ (item: OmniPickerItem) => {+ if (item.model !== "dashboard") {+ return false;+ }++ if (isSelectableItemProp && !isSelectableItemProp(item)) {+ return false;+ }++ return true;+ },+ [isSelectableItemProp],+ );++ return (+ <EntityPickerModal+ title={title}+ onChange={onChange}+ onClose={onClose}+ value={value}+ options={{+ canCreateDashboards,+ ...options,+ }}+ searchParams={searchParams}+ {...rest}+ // if the user can create a dashboard, they should be able to navigate the whole collection tree+ // so they can create a dashboard in any collection, not just those that already have dashboards+ models={canCreateDashboards ? ["dashboard", "collection"] : ["dashboard"]}+ isSelectableItem={canSelectItem}+ />+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/DashboardPicker.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/DashboardPicker.tsxdeleted file mode 100644index affc6d6da29..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/DashboardPicker.tsx+++ /dev/null@@ -1,187 +0,0 @@-import type { Ref } from "react";-import { forwardRef, useCallback, useImperativeHandle, useMemo } from "react";-import { useDeepCompareEffect } from "react-use";--import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { useSelector } from "metabase/lib/redux";-import { getUserPersonalCollectionId } from "metabase/selectors/user";-import type { CollectionItemModel, Dashboard } from "metabase-types/api";--import { LoadingSpinner, NestedItemPicker } from "../../../../EntityPicker";-import { CollectionItemPickerResolver } from "../../../CollectionPicker/components/CollectionItemPickerResolver";-import { getPathLevelForItem } from "../../../CollectionPicker/utils";-import { useGetInitialContainer } from "../../../hooks";-import { getCollectionIdPath, getStateFromIdPath } from "../../../utils";-import type {- DashboardPickerItem,- DashboardPickerOptions,- DashboardPickerStatePath,-} from "../../types";-import {- handleNewDashboard as handleNewDashboardUtil,- isFolder,-} from "../../utils";--export const defaultOptions: DashboardPickerOptions = {- showPersonalCollections: true,- showRootCollection: true,- allowCreateNew: true,-};--interface DashboardPickerProps {- initialValue?: Pick<DashboardPickerItem, "model" | "id">;- options: DashboardPickerOptions;- models?: CollectionItemModel[];- path: DashboardPickerStatePath | undefined;- shouldDisableItem?: (item: DashboardPickerItem) => boolean;- onItemSelect: (item: DashboardPickerItem) => void;- onPathChange: (path: DashboardPickerStatePath) => void;-}--const DashboardPickerInner = (- {- initialValue,- options,- models = ["dashboard"],- path: pathProp,- shouldDisableItem,- onItemSelect,- onPathChange,- }: DashboardPickerProps,- ref: Ref<unknown>,-) => {- const defaultPath = useMemo(() => {- return getStateFromIdPath({ idPath: ["root"], models });- }, [models]);- const path = pathProp ?? defaultPath;-- const {- currentCollection,- currentDashboard,- error,- isLoading: loadingCurrentCollection,- } = useGetInitialContainer(initialValue);-- const userPersonalCollectionId = useSelector(getUserPersonalCollectionId);-- const onFolderSelect = useCallback(- ({ folder }: { folder: DashboardPickerItem }) => {- const idPath = getCollectionIdPath(folder, userPersonalCollectionId);-- const newPath = getStateFromIdPath({- idPath,- models,- });- onPathChange(newPath);- onItemSelect(folder);- },- [onPathChange, onItemSelect, userPersonalCollectionId, models],- );-- const handleItemSelect = useCallback(- (item: DashboardPickerItem) => {- // set selected item at the correct level- const pathLevel = getPathLevelForItem(- item,- path,- userPersonalCollectionId,- );-- const newPath = path.slice(0, pathLevel + 1);- newPath[newPath.length - 1].selectedItem = item;- onPathChange(newPath);- onItemSelect(item);- },- [onPathChange, onItemSelect, path, userPersonalCollectionId],- );-- const handleNewDashboard = useCallback(- (newDashboard: Dashboard) => {- handleNewDashboardUtil(- newDashboard,- path,- onItemSelect,- userPersonalCollectionId,- handleItemSelect,- onPathChange,- );- },- [- path,- onItemSelect,- userPersonalCollectionId,- handleItemSelect,- onPathChange,- ],- );-- // Exposing onNewDashboard so that parent can select newly created- // folder- useImperativeHandle(- ref,- () => ({- onNewDashboard: handleNewDashboard,- }),- [handleNewDashboard],- );-- useDeepCompareEffect(- function setInitialPath() {- // This can really be driven from currentDashboard.collection, and we should not be looking at currentCollection at all.- if (currentCollection?.id) {- const idPath = getCollectionIdPath(- {- ...currentCollection,- model: "collection",- },- userPersonalCollectionId,- );-- const newPath = getStateFromIdPath({- idPath,- models,- });-- if (currentCollection.can_write) {- // start with the current item selected if we can- newPath[newPath.length - 1].selectedItem = currentDashboard- ? {- id: currentDashboard.id,- name: currentDashboard.name,- model: "dashboard",- }- : {- id: currentCollection.id,- name: currentCollection.name,- model: "collection",- };- }-- onPathChange(newPath);- }- },- [currentCollection, userPersonalCollectionId, onPathChange],- );-- if (error) {- return <LoadingAndErrorWrapper error={error} />;- }-- if (loadingCurrentCollection) {- return <LoadingSpinner />;- }-- return (- <NestedItemPicker- isFolder={isFolder}- options={options}- onFolderSelect={onFolderSelect}- onItemSelect={handleItemSelect}- path={path}- listResolver={CollectionItemPickerResolver}- shouldDisableItem={shouldDisableItem}- />- );-};--export const DashboardPicker = forwardRef(DashboardPickerInner);diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/index.ts b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/index.tsdeleted file mode 100644index 5df0b889dd5..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./DashboardPicker";diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/common.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/common.unit.spec.tsxdeleted file mode 100644index f408afc7f89..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/common.unit.spec.tsx+++ /dev/null@@ -1,142 +0,0 @@-import userEvent from "@testing-library/user-event";--import { screen } from "__support__/ui";--import { defaultOptions } from "../DashboardPicker";--import { setupModal, setupPicker } from "./setup";--describe("DashboardPicker", () => {- afterEach(() => {- jest.restoreAllMocks();- });-- it("should select the root collection by default", async () => {- await setupPicker();-- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toBeInTheDocument();-- expect(- await screen.findByRole("link", { name: /Collection 2/ }),- ).toBeInTheDocument();- });-- it("should render the path to the collection provided", async () => {- await setupPicker({ initialValue: { id: 3, model: "collection" } });- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should render the path to the dashboard provided", async () => {- await setupPicker({ initialValue: { id: 100, model: "dashboard" } });-- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");-- // dashboard itself should start selected- expect(- await screen.findByRole("link", { name: /My Dashboard 1/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /My Dashboard 2/ }),- ).not.toHaveAttribute("data-active", "true");- });-});--describe("DashboardPickerModal", () => {- afterEach(() => {- jest.restoreAllMocks();- });-- it("should render the modal", async () => {- await setupModal();-- expect(await screen.findByText(/choose a dashboard/i)).toBeInTheDocument();- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();-- expect(screen.getByRole("button", { name: /Select/ })).toBeInTheDocument();- });-- it("should render the modal with no select button", async () => {- await setupModal({- options: { ...defaultOptions, hasConfirmButtons: false },- });-- expect(await screen.findByText(/choose a dashboard/i)).toBeInTheDocument();- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: /Select/ }),- ).not.toBeInTheDocument();- });-- it("should render no tabs by default", async () => {- await setupModal();-- expect(screen.queryByRole("tab")).not.toBeInTheDocument();- });-- it("should automatically switch to the search tab when a search query is provided", async () => {- await setupModal();-- const searchInput = await screen.findByPlaceholderText(/search/i);-- await userEvent.type(searchInput, "sizzlipede");-- expect(- await screen.findByRole("tab", { name: /Dashboards/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(- "aria-selected",- "true",- );- });-- it("should switch back to not having tabs when the search query is cleared", async () => {- await setupModal();-- const searchInput = await screen.findByPlaceholderText(/search/i);-- await userEvent.type(searchInput, "sizzlipede");-- expect(- await screen.findByRole("tab", { name: /Dashboards/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(- "aria-selected",- "true",- );-- await userEvent.clear(searchInput);-- expect(screen.queryByRole("tab")).not.toBeInTheDocument();- });-});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/enterprise.unit.spec.tsxdeleted file mode 100644index 85b709596a6..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/enterprise.unit.spec.tsx+++ /dev/null@@ -1,53 +0,0 @@-import userEvent from "@testing-library/user-event";--import { screen } from "__support__/ui";--import { type SetupOpts, setupPicker } from "./setup";--const setup = (opts: SetupOpts = {}) => setupPicker({ ...opts, ee: true });--describe("tenant collections", () => {- it("should show tenant collections in the root panel and build a path to a dashboard", async () => {- await setup();-- await userEvent.click(- await screen.findByRole("link", { name: /Shared collections/ }),- );-- await userEvent.click(await screen.findByRole("link", { name: /tcoll/ }));-- await userEvent.click(- await screen.findByRole("link", { name: /tsubcoll/ }),- );-- expect(- await screen.findByRole("link", { name: /Shared Dashboard/ }),- ).toBeInTheDocument();- });-- it("should handle a tenant tenant as an initial value", async () => {- await setup({- initialValue: {- model: "dashboard",- id: 102,- },- });-- expect(- await screen.findByRole("link", { name: /Shared collections/ }),- ).toHaveAttribute("data-active", "true");-- expect(await screen.findByRole("link", { name: /tcoll/ })).toHaveAttribute(- "data-active",- "true",- );-- expect(- await screen.findByRole("link", { name: /tsubcoll/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Shared Dashboard/ }),- ).toHaveAttribute("data-active", "true");- });-});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/setup.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/setup.tsxdeleted file mode 100644index 674fa7aec27..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/setup.tsx+++ /dev/null@@ -1,353 +0,0 @@-import fetchMock from "fetch-mock";-import { useState } from "react";--import { setupEnterprisePlugins } from "__support__/enterprise";-import {- setupCollectionItemsEndpoint,- setupDatabasesEndpoints,- setupRecentViewsAndSelectionsEndpoints,- setupRootCollectionItemsEndpoint,- setupSearchEndpoints,- setupTenantCollectionItemsEndpoint,-} from "__support__/server-mocks";-import { mockSettings } from "__support__/settings";-import {- mockGetBoundingClientRect,- renderWithProviders,- waitForLoaderToBeRemoved,-} from "__support__/ui";-import type {- CollectionId,- CollectionItem,- DashboardId,-} from "metabase-types/api";-import {- createMockCollection,- createMockCollectionItem,- createMockDashboard,- createMockSettings,- createMockTokenFeatures,-} from "metabase-types/api/mocks";-import { createMockState } from "metabase-types/store/mocks";--import type {- DashboardPickerItem,- DashboardPickerStatePath,- DashboardPickerValueModel,-} from "../../../types";-import { DashboardPickerModal } from "../../DashboardPickerModal";-import { DashboardPicker, defaultOptions } from "../DashboardPicker";--type NestedCollectionItem = Partial<Omit<CollectionItem, "id">> & {- id: any;- is_personal?: boolean;- descendants: NestedCollectionItem[];-};--const myDashboard = createMockDashboard({- id: 100,- name: "My Dashboard 1",- collection_id: 3,-});--const myDashboard2 = createMockDashboard({- id: 101,- name: "My Dashboard 2",- collection_id: 3,-});--const sharedTenantDashboard = createMockDashboard({- id: 102,- name: "Shared Dashboard",- collection_id: 7,-});--const collectionTree: NestedCollectionItem[] = [- {- id: "root",- model: "collection",- name: "Our Analytics",- location: "",- can_write: true,- descendants: [- {- id: 4,- name: "Collection 4",- model: "collection",- location: "/",- effective_location: "/",- can_write: true,- descendants: [- {- id: 3,- name: "Collection 3",- model: "collection",- descendants: [- {- ...myDashboard,- model: "dashboard",- descendants: [],- },- {- ...myDashboard2,- model: "dashboard",- descendants: [],- },- ],- location: "/4/",- effective_location: "/4/",- can_write: true,- is_personal: false,- },- ],- },- {- id: 2,- model: "collection",- is_personal: false,- name: "Collection 2",- location: "/",- effective_location: "/",- can_write: true,- descendants: [],- },- ],- },- {- name: "My personal collection",- id: 1,- model: "collection",- location: "/",- effective_location: "/",- is_personal: true,- can_write: true,- descendants: [- {- id: 5,- model: "collection",- location: "/1/",- effective_location: "/1/",- name: "personal sub_collection",- is_personal: true,- can_write: true,- descendants: [],- },- ],- },-];--const tenantCollectionsTree: NestedCollectionItem[] = [- {- name: "tcoll",- id: 6,- location: "/",- effective_location: "/",- is_personal: false,- is_shared_tenant_collection: true,- model: "collection",- here: ["collection"],- below: ["dashboard"],- can_write: true,- descendants: [- {- id: 7,- location: "/6/",- effective_location: "/6/",- name: "tsubcoll",- model: "collection",- is_personal: false,- is_shared_tenant_collection: true,- can_write: true,- descendants: [- {- ...sharedTenantDashboard,- model: "dashboard",- is_tenant_dashboard: true,- descendants: [],- },- ],- here: ["dashboard"],- },- ],- },-];--const flattenCollectionTree = (- nodes: NestedCollectionItem[],-): Omit<NestedCollectionItem, "descendants">[] => {- if (!nodes) {- return [];- }- return nodes.flatMap(({ descendants, ...node }) => [- node,- ...flattenCollectionTree(descendants),- ]);-};--const mockCollectionToCollectionItem = (c: NestedCollectionItem) =>- createMockCollectionItem({- ...c,- ...(c.is_shared_tenant_collection && {- namespace: "shared-tenant-collection",- }),- });--const setupCollectionTreeMocks = (node: NestedCollectionItem[]) => {- node.forEach((node) => {- if (!node.descendants) {- return;- }- const collectionItems = node.descendants.map((c: NestedCollectionItem) =>- createMockCollectionItem(c),- );-- // Skip root since it's handled separately (tenant-aware)- if (node.id !== "root") {- setupCollectionItemsEndpoint({- collection: createMockCollection({ id: node.id }),- collectionItems,- models: ["collection", "dashboard"],- });- }-- if (collectionItems.length > 0) {- setupCollectionTreeMocks(node.descendants);- }- });-};--const setupTenantCollectionTreeMocks = (node: NestedCollectionItem[]): void => {- node.forEach((n) => {- const collectionItems = n.descendants.map((c: NestedCollectionItem) =>- mockCollectionToCollectionItem(c),- );-- setupTenantCollectionItemsEndpoint({- collection: createMockCollection({ id: n.id }),- collectionItems,- models: ["collection", "dashboard"],- });-- if (collectionItems.length > 0) {- setupTenantCollectionTreeMocks(n.descendants);- }- });-};--export interface SetupOpts {- initialValue?: {- id: CollectionId | DashboardId;- model: "collection" | "dashboard";- };- onChange?: (item: DashboardPickerItem) => void;- models?: [DashboardPickerValueModel, ...DashboardPickerValueModel[]];- options?: typeof defaultOptions;- ee?: boolean;-}--const commonSetup = ({ ee = false }: { ee?: boolean } = {}) => {- setupRecentViewsAndSelectionsEndpoints([]);- mockGetBoundingClientRect();- setupSearchEndpoints([]);- setupDatabasesEndpoints([]);-- const allItems = flattenCollectionTree(collectionTree).map(- createMockCollectionItem,- );-- allItems.forEach((item) => {- if (item.model !== "collection") {- fetchMock.get(`path:/api/dashboard/${item.id}`, item);- } else {- fetchMock.get(`path:/api/collection/${item.id}`, item);- }- });-- setupCollectionTreeMocks(collectionTree);-- // Setup root collection items endpoint (handles both regular and tenant requests)- setupRootCollectionItemsEndpoint({- rootCollectionItems: collectionTree[0].descendants.map(- createMockCollectionItem,- ),- tenantRootItems: ee- ? [mockCollectionToCollectionItem(tenantCollectionsTree[0])]- : [],- });-- if (ee) {- const allTenantItems = flattenCollectionTree(tenantCollectionsTree).map(- createMockCollectionItem,- );-- setupEnterprisePlugins();- setupTenantCollectionTreeMocks(tenantCollectionsTree);-- allTenantItems.forEach((item) => {- if (item.model !== "collection") {- fetchMock.get(`path:/api/dashboard/${item.id}`, item);- } else {- fetchMock.get(`path:/api/collection/${item.id}`, {- ...item,- namespace: "shared-tenant-collection",- });- }- });- }-};--export const setupPicker = async ({- initialValue = { id: "root", model: "collection" },- onChange = jest.fn<void, [DashboardPickerItem]>(),- ee = false,-}: SetupOpts = {}) => {- const settings = mockSettings(- createMockSettings({- "token-features": createMockTokenFeatures({- tenants: ee ? true : false,- }),- "use-tenants": ee,- }),- );-- commonSetup({ ee });-- function TestComponent() {- const [path, setPath] = useState<DashboardPickerStatePath>();-- return (- <DashboardPicker- initialValue={initialValue}- options={defaultOptions}- path={path}- onItemSelect={onChange}- onPathChange={setPath}- />- );- }-- renderWithProviders(<TestComponent />, {- storeInitialState: createMockState({ settings }),- });-- await waitForLoaderToBeRemoved();-};--export const setupModal = async ({- initialValue,- onChange = jest.fn<void, [DashboardPickerItem]>(),- options = defaultOptions,-}: SetupOpts = {}) => {- commonSetup();-- renderWithProviders(- <DashboardPickerModal- onChange={onChange}- value={initialValue}- onClose={jest.fn()}- options={options}- />,- );-- await waitForLoaderToBeRemoved();-};diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPickerModal.tsxdeleted file mode 100644index c2fe6951bdd..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPickerModal.tsx+++ /dev/null@@ -1,231 +0,0 @@-import { useCallback, useRef, useState } from "react";-import { match } from "ts-pattern";-import { t } from "ttag";--import { useToggle } from "metabase/common/hooks/use-toggle";-import { Button, Icon } from "metabase/ui";-import type { RecentItem, SearchResult } from "metabase-types/api";--import type { EntityPickerTab } from "../../../EntityPicker";-import {- EntityPickerModal,- defaultOptions as defaultEntityPickerOptions,-} from "../../../EntityPicker";-import { useLogRecentItem } from "../../../EntityPicker/hooks/use-log-recent-item";-import { isNamespaceRoot } from "../../utils";-import type {- DashboardPickerInitialValueItem,- DashboardPickerItem,- DashboardPickerOptions,- DashboardPickerStatePath,- DashboardPickerValueItem,-} from "../types";-import { getCollectionId } from "../utils";--import {- DashboardPicker,- defaultOptions as defaultDashboardPickerOptions,-} from "./DashboardPicker/DashboardPicker";-import { NewDashboardDialog } from "./NewDashboardDialog";--export interface DashboardPickerModalProps {- title?: string;- onChange: (item: DashboardPickerValueItem) => void;- onClose: () => void;- options?: DashboardPickerOptions;- value?: DashboardPickerInitialValueItem;- searchFilter?: (searchResults: SearchResult[]) => SearchResult[];- recentFilter?: (recents: RecentItem[]) => RecentItem[];- shouldDisableItem?: (- item: DashboardPickerItem,- isReadOnlyCollection?: boolean,- ) => boolean;- canSelectCollection?: boolean;-}--const canSelectItem = (- item: DashboardPickerItem | DashboardPickerInitialValueItem | null,- canSelectCollection: boolean,-): item is DashboardPickerValueItem => {- return (- item?.model === "dashboard" ||- (canSelectCollection && item?.model === "collection")- );-};--const defaultOptions: DashboardPickerOptions = {- ...defaultEntityPickerOptions,- ...defaultDashboardPickerOptions,-};--const mergeOptions = (- options: Partial<DashboardPickerOptions>,- canSelectCollection: boolean,- selectedModel: DashboardPickerItem["model"] | null | undefined,-) => ({- ...defaultOptions,- ...(canSelectCollection- ? {- confirmButtonText: match(selectedModel)- .with("dashboard", () => t`Save in this dashboard`)- .with("collection", () => t`Save in this collection`)- .otherwise(() => t`Save`),- }- : {}),- ...options,-});--export const DashboardPickerModal = ({- title = t`Choose a dashboard`,- onChange,- onClose,- value = { model: "collection", id: "root" },- options = defaultOptions,- shouldDisableItem,- searchFilter,- recentFilter,- canSelectCollection = false,-}: DashboardPickerModalProps) => {- const [selectedItem, setSelectedItem] = useState<DashboardPickerItem | null>(- canSelectItem(value, canSelectCollection) ? value : null,- );-- options = mergeOptions(options, canSelectCollection, selectedItem?.model);-- const [dashboardsPath, setDashboardsPath] =- useState<DashboardPickerStatePath>();-- const handleDashboardsPathChange = useCallback(- function (newPath: DashboardPickerStatePath) {- setDashboardsPath(newPath);- const last = newPath?.[newPath.length - 1];- if (- last &&- canSelectItem(last?.selectedItem ?? null, canSelectCollection)- ) {- setSelectedItem(last.selectedItem);- }- },- [canSelectCollection],- );-- const { tryLogRecentItem } = useLogRecentItem();-- const handleOnChange = useCallback(- (item: DashboardPickerValueItem) => {- onChange(item);- tryLogRecentItem(item);- },- [onChange, tryLogRecentItem],- );-- const [- isCreateDialogOpen,- { turnOn: openCreateDialog, turnOff: closeCreateDialog },- ] = useToggle(false);-- const pickerRef = useRef<{- onNewDashboard: (item: DashboardPickerItem) => void;- }>();-- const handleItemSelect = useCallback(- (item: DashboardPickerItem) => {- if (options.hasConfirmButtons) {- setSelectedItem(item);- } else if (canSelectItem(item, canSelectCollection)) {- handleOnChange(item);- }- },- [handleOnChange, options, canSelectCollection],- );-- const handleConfirm = () => {- if (selectedItem && canSelectItem(selectedItem, canSelectCollection)) {- handleOnChange(selectedItem);- }- };-- const modalActions = [- <Button- key="dashboard-on-the-go"- miw="9.5rem"- onClick={openCreateDialog}- leftSection={<Icon name="add_to_dash" />}- disabled={Boolean(- selectedItem?.can_write === false ||- (selectedItem && isNamespaceRoot(selectedItem)),- )}- >- {t`New dashboard`}- </Button>,- ];-- const tabs: EntityPickerTab<- DashboardPickerItem["id"],- DashboardPickerItem["model"],- DashboardPickerItem- >[] = [- {- id: "dashboards-tab",- displayName: t`Dashboards`,- models: ["dashboard" as const],- folderModels: ["collection" as const],- icon: "dashboard",- render: ({ onItemSelect }) => (- <DashboardPicker- initialValue={value}- models={["dashboard", "collection"]}- options={options}- path={dashboardsPath}- ref={pickerRef}- shouldDisableItem={shouldDisableItem}- onItemSelect={onItemSelect}- onPathChange={handleDashboardsPathChange}- />- ),- },- ];-- const handleNewDashboardCreate = (newDashboard: DashboardPickerItem) => {- pickerRef.current?.onNewDashboard(newDashboard);- };-- const parentCollectionId = getCollectionId(selectedItem || value);-- return (- <>- <EntityPickerModal- title={title}- onItemSelect={handleItemSelect}- canSelectItem={- !isCreateDialogOpen &&- canSelectItem(selectedItem, canSelectCollection)- }- onConfirm={handleConfirm}- onClose={onClose}- selectedItem={selectedItem}- initialValue={value}- tabs={tabs}- options={options}- searchResultFilter={searchFilter}- recentFilter={recentFilter}- actionButtons={modalActions}- searchParams={- options.showRootCollection === false- ? { filter_items_in_personal_collection: "only" }- : options.showPersonalCollections === false- ? { filter_items_in_personal_collection: "exclude" }- : undefined- }- trapFocus={!isCreateDialogOpen}- disableCloseOnEscape={isCreateDialogOpen}- />- <NewDashboardDialog- isOpen={isCreateDialogOpen}- onClose={closeCreateDialog}- parentCollectionId={parentCollectionId}- onNewDashboard={handleNewDashboardCreate}- />- </>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/NewDashboardDialog.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/NewDashboardDialog.tsxdeleted file mode 100644index 6e976376f79..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/NewDashboardDialog.tsx+++ /dev/null@@ -1,95 +0,0 @@-import { t } from "ttag";--import { useCreateDashboardMutation } from "metabase/api";-import { FormFooter } from "metabase/common/components/FormFooter";-import { useEscapeToCloseModal } from "metabase/common/hooks/use-escape-to-close-modal";-import {- Form,- FormErrorMessage,- FormProvider,- FormSubmitButton,- FormTextInput,-} from "metabase/forms";-import { Button, Flex, Modal } from "metabase/ui";-import type { CollectionId } from "metabase-types/api";--import type { DashboardPickerItem } from "../types";--interface NewDashboardDialogProps {- isOpen: boolean;- onClose: () => void;- parentCollectionId: CollectionId | null;- onNewDashboard: (item: DashboardPickerItem) => void;-}--export const NewDashboardDialog = ({- isOpen,- onClose,- parentCollectionId,- onNewDashboard,-}: NewDashboardDialogProps) => {- const [createDashboard] = useCreateDashboardMutation();-- const onCreateNewDashboard = async ({ name }: { name: string }) => {- const newDashboard = await createDashboard({- name,- collection_id: parentCollectionId === "root" ? null : parentCollectionId,- }).unwrap();-- onNewDashboard({- ...newDashboard,- collection_id: newDashboard.collection_id ?? "root",- model: "dashboard",- });- onClose();- };-- useEscapeToCloseModal(onClose, { capture: true });-- return (- <Modal- title={t`Create a new dashboard`}- opened={isOpen}- onClose={onClose}- data-testid="create-dashboard-on-the-go"- trapFocus={true}- withCloseButton={false}- closeOnEscape={false}- styles={{- content: {- padding: "1rem",- },- }}- >- <FormProvider- initialValues={{ name: "" }}- onSubmit={onCreateNewDashboard}- >- {({ dirty, isSubmitting }) => (- <Form>- <FormTextInput- name="name"- label={t`Give it a name`}- placeholder={t`My new dashboard`}- mb="1rem"- labelProps={{ my: "0.5rem" }}- data-autofocus- />- <FormFooter>- <FormErrorMessage inline />- <Flex style={{ flexShrink: 1 }} justify="flex-end" gap="sm">- <Button type="button" onClick={onClose}>{t`Cancel`}</Button>- <FormSubmitButton- type="submit"- label={t`Create`}- disabled={!dirty || isSubmitting}- variant="filled"- />- </Flex>- </FormFooter>- </Form>- )}- </FormProvider>- </Modal>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/NewDashboardDialog.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/NewDashboardDialog.unit.spec.tsxdeleted file mode 100644index 51417c848e6..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/NewDashboardDialog.unit.spec.tsx+++ /dev/null@@ -1,79 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { renderWithProviders, screen } from "__support__/ui";-import type { CollectionId } from "metabase-types/api";--import { NewDashboardDialog } from "./NewDashboardDialog";--const setup = (- params: {- parentCollectionId: CollectionId | null;- } = {- parentCollectionId: "root",- },-) => {- const onClose = jest.fn();- const onNewCollection = jest.fn();- fetchMock.post("path:/api/dashboard", { id: 2 });- renderWithProviders(- <NewDashboardDialog- isOpen- onClose={onClose}- onNewDashboard={onNewCollection}- {...params}- />,- );-};--describe("new collection dialog", () => {- it("should handle a parentCollectionId of root", async () => {- setup({- parentCollectionId: "root",- });- await userEvent.type(- screen.getByPlaceholderText("My new dashboard"),- "Test collection",- );- await userEvent.click(screen.getByRole("button", { name: "Create" }));-- const apiCalls = fetchMock.callHistory.calls("path:/api/dashboard");- expect(apiCalls).toHaveLength(1);-- const call = apiCalls[0];- const body = JSON.parse(call.options?.body as string);- expect(body.collection_id).toBe(null);- });-- it("should handle a normal parentCollectionId", async () => {- setup({ parentCollectionId: 12 });- await userEvent.type(- screen.getByPlaceholderText("My new dashboard"),- "Test collection",- );- await userEvent.click(screen.getByRole("button", { name: "Create" }));-- const apiCalls = fetchMock.callHistory.calls("path:/api/dashboard");- expect(apiCalls).toHaveLength(1);-- const call = apiCalls[0];- const body = JSON.parse(call.options?.body as string);- expect(body.collection_id).toBe(12);- });-- it("should handle a parentCollectionId of null", async () => {- setup({ parentCollectionId: null });- await userEvent.type(- screen.getByPlaceholderText("My new dashboard"),- "Test collection",- );- await userEvent.click(screen.getByRole("button", { name: "Create" }));-- const apiCalls = fetchMock.callHistory.calls("path:/api/dashboard");- expect(apiCalls).toHaveLength(1);-- const call = apiCalls[0];- const body = JSON.parse(call.options?.body as string);- expect(body.collection_id).toBe(null);- });-});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/index.ts b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/index.tsdeleted file mode 100644index a18c8b731a2..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./DashboardPicker";-export * from "./DashboardPickerModal";diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/index.ts b/frontend/src/metabase/common/components/Pickers/DashboardPicker/index.tsindex 9916d85ae79..1155693ea21 100644--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/index.ts+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/index.ts@@ -1,2 +1 @@-export * from "./components";-export * from "./types";+export * from "./DashboardPickerModal";diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/types.ts b/frontend/src/metabase/common/components/Pickers/DashboardPicker/types.tsdeleted file mode 100644index 81abebdb133..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/types.ts+++ /dev/null@@ -1,57 +0,0 @@-import type {- CollectionId,- DashboardId,- ListCollectionItemsRequest,- SearchModel,-} from "metabase-types/api";--import type {- EntityPickerModalOptions,- ListProps,- PickerState,-} from "../../EntityPicker";-import type {- CollectionItemId,- CollectionPickerItem,-} from "../CollectionPicker";--export type DashboardPickerModel = Extract<- CollectionPickerItem["model"],- "dashboard" | "collection"->;-export type DashboardPickerValueModel = Extract<- CollectionPickerItem["model"],- "dashboard"->;--export type DashboardPickerValueItem = CollectionPickerItem & {- id: DashboardId;- model: DashboardPickerValueModel;-};--export type DashboardPickerInitialValueItem = {- id: DashboardId | CollectionId;- model: DashboardPickerModel;-};--// we could tighten this up in the future, but there's relatively little value to it-export type DashboardPickerItem = CollectionPickerItem;--export type DashboardPickerOptions = EntityPickerModalOptions & {- allowCreateNew?: boolean;- showPersonalCollections?: boolean;- showRootCollection?: boolean;-};--export type DashboardItemListProps = ListProps<- CollectionItemId,- SearchModel,- DashboardPickerItem,- ListCollectionItemsRequest,- DashboardPickerOptions->;--export type DashboardPickerStatePath = PickerState<- DashboardPickerItem,- ListCollectionItemsRequest->;diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/DashboardPicker/utils.tsdeleted file mode 100644index f429c43d65a..00000000000--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/utils.ts+++ /dev/null@@ -1,91 +0,0 @@-import _ from "underscore";--import type { CollectionId, Dashboard } from "metabase-types/api";--import {- getParentCollectionId,- getPathLevelForItem,-} from "../CollectionPicker/utils";--import type {- DashboardPickerInitialValueItem,- DashboardPickerItem,- DashboardPickerStatePath,-} from "./types";--export const getCollectionId = (- item: DashboardPickerItem | DashboardPickerInitialValueItem | null,-): CollectionId => {- if (!item) {- return "root";- }-- if (- "collection_id" in item &&- item.model === "dashboard" &&- item.collection_id !== undefined- ) {- return item.collection_id ?? "root";- }-- if (item.model === "collection") {- return (item.id as CollectionId) ?? "root";- }-- if ("location" in item) {- return getParentCollectionId(item.effective_location ?? item.location);- }-- return "root";-};--export const isFolder = (item: DashboardPickerItem) => {- return (- item.is_personal ||- item.id === "root" ||- (item?.model === "collection" &&- _.intersection(- [...(item?.below ?? []), ...(item?.here ?? [])],- ["dashboard"],- ).length > 0)- );-};--export const handleNewDashboard = (- newDashboard: Dashboard,- path: DashboardPickerStatePath,- onItemSelect: (item: DashboardPickerItem) => void,- userPersonalCollectionId: CollectionId | undefined,- handleItemSelect: (item: DashboardPickerItem) => void,- onPathChange: (item: DashboardPickerStatePath) => void,-) => {- const newCollectionItem: DashboardPickerItem = {- id: newDashboard.id,- name: newDashboard.name,- collection_id: newDashboard.collection_id || "root",- model: "dashboard",- };-- // Needed to satisfy type between DashboardPickerItem and the query below.- const parentCollectionId = getCollectionId(newCollectionItem);-- //Is the parent collection already in the path?- const isParentCollectionInPath =- getPathLevelForItem(newCollectionItem, path, userPersonalCollectionId) > 0;-- if (!isParentCollectionInPath) {- onPathChange([- ...path,- {- query: {- id: parentCollectionId,- models: ["collection", "dashboard"],- },- selectedItem: newCollectionItem,- },- ]);- onItemSelect(newCollectionItem);- return;- }- handleItemSelect(newCollectionItem);-};diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/DataPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/DataPicker/DataPickerModal.tsxnew file mode 100644index 00000000000..83b230e6079--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/DataPicker/DataPickerModal.tsx@@ -0,0 +1,108 @@+import { useCallback, useMemo } from "react";++import { useSetting } from "metabase/common/hooks";+import { getQuestionVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";+import type { DatabaseId, RecentContexts, TableId } from "metabase-types/api";++import type {+ EntityPickerOptions,+ OmniPickerItem,+ OmniPickerValue,+} from "../EntityPicker";+import { EntityPickerModal } from "../EntityPicker";++import type { DataPickerValue } from "./types";+import { isDataPickerValue } from "./types";+import { shouldDisableItemNotInDb } from "./utils";++interface Props {+ title: string;+ value?: OmniPickerValue;+ models?: DataPickerValue["model"][];+ onChange: (value: TableId) => void;+ onClose: () => void;+ onlyDatabaseId?: DatabaseId;+ shouldDisableItem?: (item: OmniPickerItem) => boolean;+ options?: EntityPickerOptions;+}++const DATA_PICKER_MODELS: DataPickerValue["model"][] = [+ "card",+ "dataset",+ "metric",+ "table",+];++const RECENTS_CONTEXT: RecentContexts[] = ["selections"];++export const DataPickerModal = ({+ title,+ value,+ onChange,+ onClose,+ onlyDatabaseId,+ shouldDisableItem,+ options: passedOptions,+ models: passedModels = DATA_PICKER_MODELS,+}: Props) => {+ const hasNestedQueriesEnabled = useSetting("enable-nested-queries");++ const models: DataPickerValue["model"][] = useMemo(+ () => (hasNestedQueriesEnabled ? passedModels : ["table"]),+ [hasNestedQueriesEnabled, passedModels],+ );++ const searchParams = useMemo(() => {+ const tableParams = onlyDatabaseId+ ? { table_db_id: onlyDatabaseId }+ : undefined;+ return {+ include_dashboard_questions: true,+ ...tableParams,+ };+ }, [onlyDatabaseId]);++ const shouldDisable = useMemo(() => {+ const shouldDisableFn = shouldDisableItemNotInDb(onlyDatabaseId);++ return (i: OmniPickerItem) =>+ shouldDisableFn(i) || Boolean(shouldDisableItem && shouldDisableItem(i));+ }, [onlyDatabaseId, shouldDisableItem]);++ const handleItemSelect = useCallback(+ (item: OmniPickerItem) => {+ if (!isDataPickerValue(item)) {+ return;+ }++ const id =+ item.model === "table" ? item.id : getQuestionVirtualTableId(item.id);+ onChange(id);+ onClose();+ },+ [onChange, onClose],+ );++ return (+ <EntityPickerModal+ models={models}+ value={value}+ options={{+ hasSearch: true,+ hasRecents: true,+ hasLibrary: true,+ hasDatabases: true,+ hasRootCollection: true,+ hasConfirmButtons: false,+ hasPersonalCollections: true,+ ...passedOptions,+ }}+ recentsContext={RECENTS_CONTEXT}+ searchParams={searchParams}+ title={title}+ onClose={onClose}+ onChange={handleItemSelect}+ isDisabledItem={shouldDisable}+ />+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DataPicker/DataPickerModal.unit.spec.tsxsimilarity index 67%rename from frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.unit.spec.tsxrename to frontend/src/metabase/common/components/Pickers/DataPicker/DataPickerModal.unit.spec.tsxindex 12b7c54024c..57960b925c6 100644--- a/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.unit.spec.tsx+++ b/frontend/src/metabase/common/components/Pickers/DataPicker/DataPickerModal.unit.spec.tsx@@ -1,19 +1,29 @@+import userEvent from "@testing-library/user-event";+import {+ setupCollectionByIdEndpoint,+ setupDatabasesEndpoints,setupRecentViewsAndSelectionsEndpoints,setupSearchEndpoints,} from "__support__/server-mocks";-import { renderWithProviders, screen } from "__support__/ui";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitForLoaderToBeRemoved,+} from "__support__/ui";import type { DatabaseId, RecentItem, SearchResult } from "metabase-types/api";import {+ createMockCollection,+ createMockDatabase,createMockRecentCollectionItem,createMockRecentTableDatabaseInfo,createMockRecentTableItem,createMockSearchResult,} from "metabase-types/api/mocks";-import type { DataPickerValue } from "../types";-import { DataPickerModal } from "./DataPickerModal";+import type { DataPickerValue } from "./types";type SetupOpts = {title?: string;@@ -23,16 +33,24 @@ type SetupOpts = {searchItems?: SearchResult[];};-function setup({+async function setup({title = "Pick your starting data",value,databaseId,recentItems = [],searchItems = [],}: SetupOpts = {}) {+ mockGetBoundingClientRect();const onChange = jest.fn();const onClose = jest.fn();+ setupDatabasesEndpoints([createMockDatabase({ id: 1, name: "DB 1" })]);++ const collections = [+ createMockCollection({ id: 2, name: "Collection A" }),+ createMockCollection({ id: 3, name: "Collection B" }),+ ];+ setupCollectionByIdEndpoint({ collections });setupRecentViewsAndSelectionsEndpoints(recentItems, ["selections"]);setupSearchEndpoints(searchItems);@@ -40,12 +58,14 @@ function setup({<DataPickerModaltitle={title}value={value}- databaseId={databaseId}+ onlyDatabaseId={databaseId}onChange={onChange}onClose={onClose}/>,);+ await waitForLoaderToBeRemoved();+return { onChange, onClose };}@@ -100,30 +120,27 @@ describe("DataPickerModal", () => {];it("should show tables and cards for all databases in recent items if the database is not specified", async () => {- setup({+ await setup({recentItems,searchItems,});- expect(- await screen.findByRole("tab", { name: /Recents/ }),- ).toBeInTheDocument();- expect(await screen.findByText("DB 1 table")).toBeInTheDocument();- expect(screen.getByText("DB 1 question")).toBeInTheDocument();- expect(screen.getByText("DB 2 table")).toBeInTheDocument();- expect(screen.getByText("DB 2 question")).toBeInTheDocument();+ await userEvent.click(await screen.findByText(/Recent items/));+ await waitForLoaderToBeRemoved();+ expect(await screen.findByText(/DB 1 table/)).toBeInTheDocument();+ expect(await screen.findByText(/DB 1 question/)).toBeInTheDocument();+ expect(await screen.findByText(/DB 2 table/)).toBeInTheDocument();+ expect(await screen.findByText(/DB 2 question/)).toBeInTheDocument();});it("should show tables and cards for the selected database in recent items (metabase#52523)", async () => {- setup({+ await setup({databaseId: 1,recentItems,searchItems,});- expect(- await screen.findByRole("tab", { name: /Recents/ }),- ).toBeInTheDocument();+ await userEvent.click(await screen.findByText(/Recent items/));expect(await screen.findByText("DB 1 table")).toBeInTheDocument();- expect(screen.getByText("DB 1 question")).toBeInTheDocument();+ expect(await screen.findByText("DB 1 question")).toBeInTheDocument();expect(screen.queryByText("DB 2 table")).not.toBeInTheDocument();expect(screen.queryByText("DB 2 question")).not.toBeInTheDocument();});diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.tsxdeleted file mode 100644index 3bf5c15dede..00000000000--- a/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.tsx+++ /dev/null@@ -1,308 +0,0 @@-import { useCallback, useMemo, useState } from "react";-import { c, t } from "ttag";--import { useSetting } from "metabase/common/hooks";-import { Button, Checkbox, Icon, Popover } from "metabase/ui";-import { getQuestionVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";-import type {- DatabaseId,- RecentContexts,- RecentItem,- TableId,-} from "metabase-types/api";--import type { EntityPickerTab } from "../../../EntityPicker";-import { EntityPickerModal, defaultOptions } from "../../../EntityPicker";-import { useLogRecentItem } from "../../../EntityPicker/hooks/use-log-recent-item";-import type { CollectionPickerItem } from "../../CollectionPicker";-import {- QuestionPicker,- type QuestionPickerModel,- type QuestionPickerStatePath,-} from "../../QuestionPicker";-import { TablePicker } from "../../TablePicker";-import type { TablePickerStatePath } from "../../TablePicker/types";-import { useAvailableData } from "../hooks";-import type {- DataPickerItem,- DataPickerModalOptions,- DataPickerValue,-} from "../types";-import {- createQuestionPickerItemSelectHandler,- createShouldShowItem,- getRecentItemDatabaseId,- isTableItem,- isValueItem,-} from "../utils";--interface Props {- /**- * Limit selection to a particular database- */- databaseId?: DatabaseId;- title: string;- value: DataPickerValue | undefined;- models?: DataPickerValue["model"][];- onChange: (value: TableId) => void;- onClose: () => void;- shouldDisableItem?: (- item: DataPickerItem | CollectionPickerItem | RecentItem,- ) => boolean;- options?: DataPickerModalOptions;-}--type FilterOption = { label: string; value: QuestionPickerModel };--const QUESTION_PICKER_MODELS: QuestionPickerModel[] = [- "card",- "dataset",- "metric",- "dashboard",- "table",-];--const RECENTS_CONTEXT: RecentContexts[] = ["selections"];--const OPTIONS: DataPickerModalOptions = {- ...defaultOptions,- hasConfirmButtons: false,- showPersonalCollections: true,- showRootCollection: true,- showLibrary: true,- showDatabases: true,- hasRecents: true,-};--export const DataPickerModal = ({- databaseId,- title,- value,- onChange,- onClose,- shouldDisableItem,- options,- models = ["card", "dataset", "metric", "table"],-}: Props) => {- options = {- ...OPTIONS,- ...options,- };- const [modelFilter, setModelFilter] = useState<QuestionPickerModel[]>(- QUESTION_PICKER_MODELS,- );- const hasNestedQueriesEnabled = useSetting("enable-nested-queries");-- const {- hasQuestions,- hasModels,- hasMetrics,- hasTables,- isLoading: isLoadingAvailableData,- } = useAvailableData({- databaseId,- });-- const questionPickerModalFilterOptions = useMemo(() => {- const filterOptions: FilterOption[] = [];-- if (hasQuestions) {- filterOptions.push({- label: t`Saved questions`,- value: "card" as const,- });- }- if (hasModels) {- filterOptions.push({- label: t`Models`,- value: "dataset" as const,- });- }- if (hasMetrics) {- filterOptions.push({- label: t`Metrics`,- value: "metric" as const,- });- }- if (hasTables) {- filterOptions.push({- label: t`Tables`,- value: "table" as const,- });- }- return filterOptions;- }, [hasQuestions, hasModels, hasMetrics, hasTables]);-- const { tryLogRecentItem } = useLogRecentItem();-- const shouldShowItem = useMemo(() => {- return createShouldShowItem(modelFilter, databaseId);- }, [databaseId, modelFilter]);-- const recentFilter = useCallback(- (recentItems: RecentItem[]) => {- return recentItems.filter((item) => {- if (databaseId && getRecentItemDatabaseId(item) !== databaseId) {- return false;- }- if (shouldDisableItem) {- // Do not show items that are disabled in recents- return !shouldDisableItem(item);- }- return true;- });- },- [databaseId, shouldDisableItem],- );-- const searchParams = useMemo(() => {- const tableParams = databaseId ? { table_db_id: databaseId } : undefined;- return {- include_dashboard_questions: true,- ...tableParams,- };- }, [databaseId]);-- const handleItemSelect = useCallback(- (item: DataPickerItem) => {- if (!isValueItem(item)) {- return;- }-- const id =- item.model === "table" ? item.id : getQuestionVirtualTableId(item.id);- onChange(id);- tryLogRecentItem(item);- onClose();- },- [onChange, onClose, tryLogRecentItem],- );-- const [questionsPath, setQuestionsPath] = useState<QuestionPickerStatePath>();- const [tablesPath, setTablesPath] = useState<TablePickerStatePath>();- const filterButton = (- <FilterButton- value={modelFilter}- onChange={setModelFilter}- options={questionPickerModalFilterOptions}- />- );-- const tabs = (function getTabs() {- const computedTabs: EntityPickerTab<- DataPickerItem["id"],- DataPickerItem["model"],- DataPickerItem- >[] = [];-- const hasOnlyTableModels =- models != null && models.length === 1 && models[0] === "table";- if (hasOnlyTableModels || !hasNestedQueriesEnabled) {- computedTabs.push({- id: "tables-tab",- displayName: t`Tables`,- models: ["table" as const],- folderModels: ["database" as const, "schema" as const],- icon: "table",- render: ({ onItemSelect }) => (- <TablePicker- databaseId={databaseId}- path={tablesPath}- value={isTableItem(value) ? value : undefined}- onItemSelect={onItemSelect}- onPathChange={setTablesPath}- shouldDisableItem={shouldDisableItem}- />- ),- });- } else {- computedTabs.push({- id: "questions-tab",- displayName: t`Data`,- models,- folderModels: ["collection", "dashboard", "schema", "database"],- icon: "folder",- extraButtons: [filterButton],- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={value}- models={[- ...models,- ...(models.includes("card") ? ["dashboard" as const] : []),- ]}- options={options}- path={questionsPath}- shouldShowItem={shouldShowItem}- onInit={createQuestionPickerItemSelectHandler(onItemSelect)}- onItemSelect={createQuestionPickerItemSelectHandler(onItemSelect)}- onPathChange={setQuestionsPath}- shouldDisableItem={shouldDisableItem}- tablesPath={tablesPath}- onTablesPathChange={setTablesPath}- />- ),- });- }-- return computedTabs;- })();-- return (- <EntityPickerModal- canSelectItem- defaultToRecentTab={false}- initialValue={value}- options={options}- recentsContext={RECENTS_CONTEXT}- recentFilter={recentFilter}- searchParams={searchParams}- selectedItem={value ?? null}- tabs={tabs}- title={title}- onClose={onClose}- onItemSelect={handleItemSelect}- isLoadingTabs={isLoadingAvailableData}- searchExtraButtons={[filterButton]}- searchModels={models}- />- );-};--const FilterButton = ({- value,- onChange,- options,-}: {- value: QuestionPickerModel[];- onChange: (value: QuestionPickerModel[]) => void;- options: FilterOption[];-}) => {- return (- <Popover zIndex={450}>- <Popover.Target>- <Button leftSection={<Icon name="filter" />} variant="subtle">{c(- "A verb, not a noun",- ).t`Filter`}</Button>- </Popover.Target>- <Popover.Dropdown>- <Checkbox.Group- value={value}- onChange={(newValues: string[]) =>- onChange(newValues as QuestionPickerModel[])- }- px="1rem"- py="0.5rem"- >- {options.map((option) => (- <Checkbox- key={`filter-${option.value}`}- label={option.label}- value={option.value}- my="1rem"- />- ))}- </Checkbox.Group>- </Popover.Dropdown>- </Popover>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/components/index.ts b/frontend/src/metabase/common/components/Pickers/DataPicker/components/index.tsdeleted file mode 100644index 01bd5c5e86c..00000000000--- a/frontend/src/metabase/common/components/Pickers/DataPicker/components/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./DataPickerModal";diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/hooks/index.ts b/frontend/src/metabase/common/components/Pickers/DataPicker/hooks/index.tsdeleted file mode 100644index c523055f9a7..00000000000--- a/frontend/src/metabase/common/components/Pickers/DataPicker/hooks/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./useAvailableData";diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/hooks/useAvailableData.ts b/frontend/src/metabase/common/components/Pickers/DataPicker/hooks/useAvailableData.tsdeleted file mode 100644index 982ae1f3a77..00000000000--- a/frontend/src/metabase/common/components/Pickers/DataPicker/hooks/useAvailableData.ts+++ /dev/null@@ -1,34 +0,0 @@-import { useSearchQuery } from "metabase/api";-import type { DatabaseId } from "metabase-types/api";--interface Props {- databaseId?: DatabaseId;-}--export const useAvailableData = ({ databaseId }: Props = {}) => {- const { data, isLoading } = useSearchQuery(- {- limit: 0,- models: ["card"],- table_db_id: databaseId,- calculate_available_models: true,- include_dashboard_questions: true,- },- {- refetchOnMountOrArgChange: true,- },- );- const availableModels = data?.available_models ?? [];- const hasQuestions = availableModels.includes("card");- const hasModels = availableModels.includes("dataset");- const hasMetrics = availableModels.includes("metric");- const hasTables = availableModels.includes("table");-- return {- isLoading,- hasQuestions,- hasModels,- hasMetrics,- hasTables,- };-};diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/index.ts b/frontend/src/metabase/common/components/Pickers/DataPicker/index.tsindex b793f517ee6..19a12b5d08d 100644--- a/frontend/src/metabase/common/components/Pickers/DataPicker/index.ts+++ b/frontend/src/metabase/common/components/Pickers/DataPicker/index.ts@@ -1,3 +1,3 @@-export * from "./components";+export * from "./DataPickerModal";export * from "./types";export * from "./utils";diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/types.ts b/frontend/src/metabase/common/components/Pickers/DataPicker/types.tsindex 602680a81d1..dc0fd4cc655 100644--- a/frontend/src/metabase/common/components/Pickers/DataPicker/types.ts+++ b/frontend/src/metabase/common/components/Pickers/DataPicker/types.ts@@ -1,73 +1,45 @@import type {- CardId,- Collection,- DashboardId,- DatabaseId,-} from "metabase-types/api";--import type { EntityPickerModalOptions } from "../../EntityPicker";-import type { QuestionPickerOptions } from "../QuestionPicker";-import type {- DatabaseItem,- SchemaItem,- TableItem,- TablePickerValue,-} from "../TablePicker/types";--export type CollectionItem = {- id: Collection["id"];- name: Collection["name"];- model: "collection";-};--export type QuestionItem = {- id: CardId;- name: string;- model: "card";- database_id: DatabaseId;+ OmniPickerDatabaseItem,+ OmniPickerItem,+ OmniPickerQuestionItem,+ OmniPickerSchemaItem,+ OmniPickerTableItem,+} from "../EntityPicker";++export const isQuestionItem = (+ item: OmniPickerItem,+): item is OmniPickerQuestionItem => {+ if (+ item.model === "card" ||+ item.model === "dataset" ||+ item.model === "metric"+ ) {+ return true;+ }+ return false;};-export type DashboardItem = {- id: DashboardId;- name: string;- model: "dashboard";+export const isTableItem = (+ item: OmniPickerItem,+): item is OmniPickerTableItem => {+ return item.model === "table";};-export type ModelItem = {- id: CardId;- name: string;- model: "dataset";- database_id: DatabaseId;+export const isSchemaItem = (+ item: OmniPickerItem,+): item is OmniPickerSchemaItem => {+ return item.model === "schema";};-export type MetricItem = {- id: CardId;- name: string;- model: "metric";- database_id: DatabaseId;+export const isDataPickerValue = (+ item: OmniPickerItem,+): item is OmniPickerTableItem | OmniPickerQuestionItem => {+ return isTableItem(item) || isQuestionItem(item);};export type DataPickerValue =- | TablePickerValue- | QuestionItem- | ModelItem- | MetricItem;--export type DataPickerFolderItem =- | CollectionItem- | DatabaseItem- | SchemaItem- | DashboardItem;--export type DataPickerValueItem =- | TableItem- | QuestionItem- | ModelItem- | MetricItem;--export type DataPickerItem = DataPickerFolderItem | DataPickerValueItem;--export type DataPickerModalOptions = EntityPickerModalOptions &- QuestionPickerOptions & {- showDatabases?: boolean;- };+ | Pick<+ OmniPickerTableItem | OmniPickerQuestionItem,+ "model" | "id" | "database_id"+ >+ | Pick<OmniPickerDatabaseItem, "model" | "id">;diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/DataPicker/utils.tsindex a29a227dc2c..704431461ea 100644--- a/frontend/src/metabase/common/components/Pickers/DataPicker/utils.ts+++ b/frontend/src/metabase/common/components/Pickers/DataPicker/utils.ts@@ -1,33 +1,24 @@import { canCollectionCardBeUsed } from "metabase/common/components/Pickers/utils";-import { isNullOrUndefined } from "metabase/lib/types";import * as Lib from "metabase-lib";import { getSchemaName } from "metabase-lib/v1/metadata/utils/schema";-import type {- CollectionItem,- CollectionItemModel,- DatabaseId,- RecentItem,- Table,-} from "metabase-types/api";+import type { DatabaseId, SchemaName } from "metabase-types/api";-import type { QuestionPickerItem } from "../QuestionPicker";-import type { TablePickerItem, TablePickerValue } from "../TablePicker";+import type { OmniPickerItem } from "../EntityPicker";-import type {- DataPickerFolderItem,- DataPickerItem,- DataPickerValue,- DataPickerValueItem,- MetricItem,- ModelItem,- QuestionItem,+import {+ type DataPickerValue,+ isQuestionItem,+ isSchemaItem,+ isTableItem,} from "./types";export const getDataPickerValue = (query: Lib.Query,stageIndex: number,joinable: Lib.Joinable,-): DataPickerValue | undefined => {+):+ | (DataPickerValue & { db_id?: DatabaseId; schema?: SchemaName })+ | undefined => {const pickerInfo = Lib.pickerInfo(query, joinable);const displayInfo = Lib.displayInfo(query, stageIndex, joinable);@@ -38,150 +29,48 @@ export const getDataPickerValue = (if (pickerInfo.cardId != null) {return {id: pickerInfo.cardId,- name: displayInfo.displayName,+ // name: displayInfo.displayName,model: displayInfo.isModel? "dataset": displayInfo.isMetric? "metric": "card",database_id: pickerInfo.databaseId,+ schema: getSchemaName(displayInfo.schema), // for compatibility with MiniPicker for now};}return {id: pickerInfo.tableId,- name: displayInfo.displayName,model: "table",- db_id: pickerInfo.databaseId,- schema: getSchemaName(displayInfo.schema),+ database_id: pickerInfo.databaseId,+ db_id: pickerInfo.databaseId, // for compatibility with MiniPicker for now+ schema: getSchemaName(displayInfo.schema), // for compatibility with MiniPicker for now};};-export const isCollectionItem = (- value: DataPickerValue | undefined,-): value is QuestionItem | ModelItem | MetricItem => {- return isQuestionItem(value) || isModelItem(value) || isMetricItem(value);-};--export const isQuestionItem = (- value: DataPickerValue | undefined,-): value is QuestionItem => {- return value?.model === "card";-};--export const isModelItem = (- value: DataPickerValue | undefined,-): value is ModelItem => {- return value?.model === "dataset";-};--export const isMetricItem = (- value: DataPickerValue | undefined,-): value is MetricItem => {- return value?.model === "metric";-};--export const isTableItem = (- value: DataPickerValue | undefined,-): value is TablePickerValue => {- return value?.model === "table";-};--export const isValueItem = (- item: DataPickerItem,-): item is DataPickerValueItem => {- return ["table", "card", "dataset", "metric"].includes(item.model);-};--export const isFolderItem = (- item: DataPickerItem,-): item is DataPickerFolderItem => {- return ["collection", "database", "schema"].includes(item.model);-};--type OmniPickerModel = CollectionItemModel | TablePickerItem["model"];--export const createShouldShowItem = (- models: OmniPickerModel[],- databaseId?: DatabaseId,-) => {- return (- item: QuestionPickerItem | (TablePickerItem & { database_id?: DatabaseId }),- ) => {- if (item.model === "collection") {- if (item.id === "root" || item.is_personal) {- return true;- }-- const below = item.below ?? [];- const here = item.here ?? [];- const contents = [...below, ...here];- const hasCards = models.some((model: OmniPickerModel) =>- contents.includes(model as CollectionItemModel),- );-- return hasCards;- }-- if (!isNullOrUndefined(databaseId) && item.model === "database") {- return item.id === databaseId;- }-- if (item.model === "table") {- const itemDbId = item.database_id ?? (item as unknown as Table).db_id;- return isNullOrUndefined(databaseId) || itemDbId === databaseId;+/**+ * This is used to disable cards and tables that are not+ * in the specified database.+ */+export const shouldDisableItemNotInDb =+ (databaseId?: DatabaseId) =>+ (item: OmniPickerItem): boolean => {+ if (!databaseId) {+ return false;}- if (item.model === "schema") {- return isNullOrUndefined(databaseId) || item.dbId === databaseId;+ if (item.model === "database") {+ return item.id !== databaseId;}- const hasNoDb =- isNullOrUndefined(databaseId) ||- !hasDatabaseId(item) ||- isNullOrUndefined(item.database_id);-- if (item.model === "card" && models.includes(item.model)) {- return (- canCollectionCardBeUsed(item as CollectionItem) &&- (hasNoDb || item.database_id === databaseId)- );+ if (isTableItem(item) || isSchemaItem(item)) {+ return item.database_id !== databaseId;}- if (hasNoDb && models.includes(item.model)) {- return true;+ if (isQuestionItem(item)) {+ return canCollectionCardBeUsed(item) && item.database_id !== databaseId;}- return item.database_id === databaseId;- };-};--const hasDatabaseId = (- value: unknown,-): value is Pick<CollectionItem, "database_id"> => {- return typeof value === "object" && value != null && "database_id" in value;-};--export const castQuestionPickerItemToDataPickerItem = (- item: QuestionPickerItem,-): DataPickerItem => {- // see comment for QuestionPickerItem definition to see why we need this cast- return item as DataPickerItem;-};--export const createQuestionPickerItemSelectHandler = (- onItemSelect: (item: DataPickerItem) => void,-) => {- return (questionPickerItem: QuestionPickerItem) => {- const item = castQuestionPickerItemToDataPickerItem(questionPickerItem);- onItemSelect(item);+ return false;};-};--export function getRecentItemDatabaseId(item: RecentItem) {- if (item.model === "table") {- return item.database.id;- } else {- return item.database_id;- }-}diff --git a/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/AutoScrollBox.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/AutoScrollBox.tsxsimilarity index 84%rename from frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/AutoScrollBox.tsxrename to frontend/src/metabase/common/components/Pickers/EntityPicker/components/AutoScrollBox.tsxindex ed0cb3dbcc5..9484e730e78 100644--- a/frontend/src/metabase/common/components/EntityPicker/components/AutoScrollBox/AutoScrollBox.tsx+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/AutoScrollBox.tsx@@ -2,7 +2,9 @@ import type React from "react";import { useEffect, useRef } from "react";import { usePrevious } from "react-use";-import { HorizontalScrollBox } from "./AutoScrollBox.styled";+import { Box } from "metabase/ui";++import S from "./EntityPicker.module.css";const scrollRight = (container: HTMLDivElement | null,@@ -42,8 +44,13 @@ export const AutoScrollBox = ({}, [previousContentHash, contentHash, previousContainerRef]);return (- <HorizontalScrollBox h="100%" {...props} ref={containerRef}>+ <Box+ h="100%"+ className={S.HorizontalScrollBox}+ {...props}+ ref={containerRef}+ >{children}- </HorizontalScrollBox>+ </Box>);};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ButtonBar.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ButtonBar.tsxnew file mode 100644index 00000000000..b007e72ffc0--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ButtonBar.tsx@@ -0,0 +1,107 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import { t } from "ttag";++import { getErrorMessage } from "metabase/api/utils";+import { Button, Flex, Text } from "metabase/ui";++import { useOmniPickerContext } from "../context";+import type { EntityPickerOptions, EntityPickerProps } from "../types";++import { NewCollectionDialog } from "./NewCollectionDialog";+import { NewDashboardDialog } from "./NewDashboardDialog";++export type ButtonBarProps = {+ onConfirm: EntityPickerProps["onChange"];+ onCancel: () => void;+ confirmButtonText?: EntityPickerOptions["confirmButtonText"];+ cancelButtonText?: EntityPickerOptions["cancelButtonText"];+};++export const ButtonBar = ({+ onConfirm,+ onCancel,+ confirmButtonText,+ cancelButtonText,+}: ButtonBarProps) => {+ const { path, isSelectableItem } = useOmniPickerContext();+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const selectedItem = path[path.length - 1];++ const canConfirm = useMemo(() => {+ const selectedItem = path[path.length - 1];+ return isSelectableItem(selectedItem);+ }, [isSelectableItem, path]);++ const handleConfirm = useCallback(async () => {+ const selectedItem = path[path.length - 1];+ if (canConfirm) {+ await onConfirm(selectedItem);+ }+ }, [canConfirm, onConfirm, path]);++ useEffect(() => {+ const handleKeyPress = (e: KeyboardEvent) => {+ if (e.isComposing) {+ return;+ }+ if (canConfirm && e.key === "Enter") {+ handleConfirm();+ }+ };+ document.addEventListener("keydown", handleKeyPress);+ return () => {+ document.removeEventListener("keydown", handleKeyPress);+ };+ }, [handleConfirm, canConfirm]);++ const confirmText =+ typeof confirmButtonText === "function"+ ? confirmButtonText(selectedItem)+ : (confirmButtonText ?? t`Select`);++ return (+ <Flex+ justify="space-between"+ align="center"+ p="md"+ style={{+ borderTop: "1px solid var(--mb-color-border)",+ }}+ >+ <Flex gap="md">+ <NewCollectionDialog />+ <NewDashboardDialog />+ </Flex>+ {error && (+ <Text c="error" px="md" lh="1rem">+ {error}+ </Text>+ )}+ <Flex gap="md">+ <Button onClick={onCancel} type="button">+ {cancelButtonText ?? t`Cancel`}+ </Button>+ <Button+ ml={1}+ variant="filled"+ onClick={async () => {+ try {+ setError(null);+ setLoading(true);+ await handleConfirm();+ } catch (e: any) {+ console.error(e);+ setError(getErrorMessage(e));+ }+ setLoading(false);+ }}+ disabled={!canConfirm || loading}+ data-testid="entity-picker-select-button"+ >+ {confirmText}+ </Button>+ </Flex>+ </Flex>+ );+};diff --git a/frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntitityPickerModal.module.css b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntitityPickerModal.module.csssimilarity index 100%rename from frontend/src/metabase/common/components/EntityPicker/components/EntityPickerModal/EntitityPickerModal.module.cssrename to frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntitityPickerModal.module.cssdiff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPicker.module.css b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPicker.module.cssnew file mode 100644index 00000000000..941023d0072--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPicker.module.css@@ -0,0 +1,3 @@+.HorizontalScrollBox {+ overflow-x: auto;+}diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPicker.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPicker.tsxnew file mode 100644index 00000000000..07c18de1862--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPicker.tsx@@ -0,0 +1,25 @@+import ErrorBoundary from "metabase/ErrorBoundary";++import { EntityPickerProvider } from "../context";+import type { EntityPickerProps } from "../types";++import { ButtonBar } from "./ButtonBar";+import { NestedItemPicker } from "./NestedItemPicker";++export function EntityPicker(props: EntityPickerProps) {+ return (+ <EntityPickerProvider value={props}>+ <ErrorBoundary>+ <NestedItemPicker />+ </ErrorBoundary>+ {props.options.hasConfirmButtons && (+ <ButtonBar+ onConfirm={props.onChange}+ onCancel={props.onClose}+ confirmButtonText={props.options.confirmButtonText}+ cancelButtonText={props.options.cancelButtonText}+ />+ )}+ </EntityPickerProvider>+ );+}diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPickerModal.tsxnew file mode 100644index 00000000000..e231b7c5cff--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/EntityPickerModal.tsx@@ -0,0 +1,238 @@+import {+ useDebouncedCallback,+ useDisclosure,+ useWindowEvent,+} from "@mantine/hooks";+import { useCallback, useMemo, useRef, useState } from "react";+import { t } from "ttag";++import { useModalOpen } from "metabase/common/hooks/use-modal-open";+import { useUniqueId } from "metabase/common/hooks/use-unique-id";+import resizeObserver from "metabase/lib/resize-observer";+import { ActionIcon, Box, Icon, Modal, TextInput } from "metabase/ui";+import type { RecentContexts } from "metabase-types/api";++import { useLogRecentItem } from "../hooks";+import type {+ EntityPickerOptions,+ EntityPickerProps,+ OmniPickerItem,+ OmniPickerValue,+} from "../types";++import S from "./EntitityPickerModal.module.css";+import { EntityPicker } from "./EntityPicker";++export const DEFAULT_RECENTS_CONTEXT: RecentContexts[] = [+ "selections",+ "views",+];++const defaultOptions: EntityPickerOptions = {+ hasSearch: true,+ hasRecents: true,+ hasDatabases: false,+ hasLibrary: true,+ hasRootCollection: true,+ hasPersonalCollections: true,++ hasConfirmButtons: true,+ canCreateCollections: false,+ canCreateDashboards: false,+};++export type EntityPickerModalProps = {+ title?: string;+ value?: OmniPickerValue;+ onClose: () => void;+ recentsContext?: RecentContexts[];+ options?: EntityPickerOptions;+} & Omit<+ EntityPickerProps,+ | "options"+ | "isNewCollectionDialogOpen"+ | "openNewCollectionDialog"+ | "closeNewCollectionDialog"+ | "isNewDashboardDialogOpen"+ | "openNewDashboardDialog"+ | "closeNewDashboardDialog"+>;++export function EntityPickerModal({+ title = t`Choose an item`,+ options,+ onClose,+ onChange,+ ...rest+}: EntityPickerModalProps) {+ const [modalContentMinWidth, setModalContentMinWidth] = useState(920);+ const modalContentRef = useRef<HTMLDivElement | null>(null);+ const [searchQuery, setSearchQuery] = useState<string>("");+ const [+ isNewCollectionDialogOpen,+ { open: openNewCollectionDialog, close: closeNewCollectionDialog },+ ] = useDisclosure(false);+ const [+ isNewDashboardDialogOpen,+ { open: openNewDashboardDialog, close: closeNewDashboardDialog },+ ] = useDisclosure(false);++ const hydratedOptions: EntityPickerOptions = useMemo(+ () => ({ ...defaultOptions, ...options }),+ [options],+ );++ const { open } = useModalOpen();++ const { tryLogRecentItem } = useLogRecentItem();++ const isDialogOpen = isNewCollectionDialogOpen || isNewDashboardDialogOpen;++ const handleChange = useCallback(+ async (item: OmniPickerItem) => {+ if (isDialogOpen) {+ return;+ }+ await onChange(item);+ tryLogRecentItem(item);+ },+ [isDialogOpen, onChange, tryLogRecentItem],+ );++ useWindowEvent(+ "keydown",+ (event) => {+ if (event.key === "Escape") {+ event.stopPropagation();+ !isDialogOpen && onClose();+ }+ },+ { capture: true },+ );++ const titleId = useUniqueId("entity-picker-modal-title-");++ const modalContentResizeHandler = useCallback(+ (entry: ResizeObserverEntry) => {+ const width = entry.contentRect.width;+ setModalContentMinWidth((currentWidth) =>+ currentWidth < width ? width : currentWidth,+ );+ },+ [],+ );++ const modalContentCallbackRef = useCallback(+ (element: HTMLDivElement | null) => {+ if (element) {+ resizeObserver.subscribe(element, modalContentResizeHandler);+ modalContentRef.current = element;+ } else {+ if (modalContentRef.current) {+ resizeObserver.unsubscribe(+ modalContentRef.current,+ modalContentResizeHandler,+ );+ }+ }+ },+ [modalContentResizeHandler],+ );++ return (+ <Modal.Root+ opened={open}+ onClose={onClose}+ data-testid="entity-picker-modal"+ /**+ * Both children of this component have "position: fixed" so the element's height is 0 by default.+ * This makes the following assertion to fail in Cypress:+ * cy.findByTestId("entity-picker-modal").should("be.visible");+ * Height is specified here to make that assertion pass.+ */+ h="100vh"+ w="100vw"+ closeOnEscape={false} // we're doing this manually in useWindowEvent+ yOffset="10dvh"+ >+ <Modal.Overlay />+ <Modal.Content+ className={S.modalContent}+ aria-labelledby={titleId}+ miw={`min(${modalContentMinWidth}px, 80vw)`}+ w="fit-content"+ maw="80vw"+ ref={modalContentCallbackRef}+ >+ <Modal.Header px="1.5rem" pt="1rem" pb="1rem" bg="background-primary">+ <Modal.Title id={titleId} fz="lg">+ {title}+ </Modal.Title>+ <Modal.CloseButton size={21} pos="relative" top="1px" />+ </Modal.Header>+ <Modal.Body className={S.modalBody} p="0">+ {hydratedOptions.hasSearch && (+ <Box px="1.5rem" mb="1.5rem">+ <SearchInput value={searchQuery} onChange={setSearchQuery} />+ </Box>+ )}+ <EntityPicker+ searchQuery={searchQuery}+ onChange={handleChange}+ options={hydratedOptions}+ onClose={onClose}+ isNewCollectionDialogOpen={isNewCollectionDialogOpen}+ openNewCollectionDialog={openNewCollectionDialog}+ closeNewCollectionDialog={closeNewCollectionDialog}+ isNewDashboardDialogOpen={isNewDashboardDialogOpen}+ openNewDashboardDialog={openNewDashboardDialog}+ closeNewDashboardDialog={closeNewDashboardDialog}+ {...rest}+ />+ </Modal.Body>+ </Modal.Content>+ </Modal.Root>+ );+}++const SearchInput = ({+ value,+ onChange,+}: {+ value: string;+ onChange: (value: string) => void;+}) => {+ const [localValue, setLocalValue] = useState(value);+ const debouncedOnChange = useDebouncedCallback((newValue: string) => {+ onChange(newValue);+ }, 300);+ return (+ <TextInput+ classNames={{ input: S.textInput }}+ data-autofocus+ type="search"+ leftSection={<Icon name="search" size={16} />}+ miw={400}+ placeholder={t`Search…`}+ value={localValue}+ onChange={(e) => {+ const newValue = e.target.value ?? "";+ setLocalValue(newValue);+ debouncedOnChange(newValue);+ }}+ rightSection={+ value.length ? (+ <ActionIcon+ onClick={() => {+ setLocalValue("");+ onChange("");+ }}+ data-testid="clear-search"+ >+ <Icon name="close" size={16} />+ </ActionIcon>+ ) : null+ }+ />+ );+};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.tsxnew file mode 100644index 00000000000..25ae38044b1--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/CollectionItemList.tsx@@ -0,0 +1,39 @@+import { useListCollectionItemsQuery } from "metabase/api";++import { useOmniPickerContext } from "../../context";+import type { OmniPickerItem } from "../../types";+import { getCollectionItemsOptions } from "../../utils";++import { ItemList } from "./ItemList";++export const CollectionItemList = ({+ parentItem,+ pathIndex,+}: {+ parentItem: OmniPickerItem;+ pathIndex: number;+}) => {+ const { models } = useOmniPickerContext();++ const {+ data: collectionItems,+ error,+ isLoading,+ } = useListCollectionItemsQuery({+ id: !parentItem.id ? "root" : parentItem.id,+ namespace:+ "namespace" in parentItem && !!parentItem.namespace+ ? parentItem.namespace+ : undefined,+ ...getCollectionItemsOptions({ models }),+ });++ return (+ <ItemList+ items={collectionItems?.data}+ pathIndex={pathIndex}+ isLoading={isLoading}+ error={error}+ />+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/DashboardItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/DashboardItemList.tsxnew file mode 100644index 00000000000..d185c58792d--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/DashboardItemList.tsx@@ -0,0 +1,30 @@+import { skipToken, useListDashboardItemsQuery } from "metabase/api";++import type { OmniPickerItem } from "../../types";++import { ItemList } from "./ItemList";++export const DashboardItemList = ({+ parentItem,+ pathIndex,+}: {+ parentItem: OmniPickerItem;+ pathIndex: number;+}) => {+ const {+ data: dashboardItems,+ error,+ isLoading,+ } = useListDashboardItemsQuery(+ parentItem.id ? { id: parentItem.id } : skipToken,+ );++ return (+ <ItemList+ items={dashboardItems?.data}+ isLoading={isLoading}+ error={error}+ pathIndex={pathIndex}+ />+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/DbItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/DbItemList.tsxnew file mode 100644index 00000000000..747fdac02f1--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/DbItemList.tsx@@ -0,0 +1,115 @@+import { match } from "ts-pattern";++import {+ skipToken,+ useListDatabaseSchemaTablesQuery,+ useListDatabaseSchemasQuery,+ useListDatabasesQuery,+} from "metabase/api";+import type { Database, SchemaName, Table } from "metabase-types/api";++import {+ ItemList,+ type OmniPickerDatabaseItem,+ type OmniPickerItem,+ type OmniPickerSchemaItem,+ type OmniPickerTableItem,+} from "../..";++const createSchemaItem = (+ dbId: number,+ schema: SchemaName,+): OmniPickerSchemaItem => ({+ model: "schema",+ id: schema,+ name: schema,+ database_id: dbId,+});++const createDatabaseItem = (db: Database): OmniPickerDatabaseItem => ({+ ...db,+ model: "database",+});++const createTableItem = (table: Table): OmniPickerTableItem => ({+ ...table,+ name: table.display_name ?? table.name,+ database_id: table.db_id, // make the API consistent+ model: "table",+});++const useGetDbItemListData = (parentItem: OmniPickerItem) => {+ const {+ data: databases,+ isLoading: isLoadingDatabases,+ error: databasesError,+ } = useListDatabasesQuery(+ parentItem.id === "databases" ? undefined : skipToken,+ );++ const dbId = match(parentItem)+ .with({ model: "database" }, () => Number(parentItem.id))+ .with(+ { model: "schema" },+ () => (parentItem as OmniPickerSchemaItem).database_id,+ )+ .otherwise(() => undefined);++ const {+ data: schemas,+ isLoading: isLoadingSchemas,+ error: schemasError,+ } = useListDatabaseSchemasQuery(+ parentItem.model === "database" && !!dbId ? { id: dbId } : skipToken,+ );++ const schemaName: SchemaName | null =+ parentItem.model === "schema"+ ? String(parentItem.id)+ : schemas?.length === 1+ ? schemas[0] // if there's one schema, go straight to tables+ : null;++ const {+ data: tables,+ isLoading: isLoadingTables,+ error: tablesError,+ } = useListDatabaseSchemaTablesQuery(+ schemaName !== null && !!dbId+ ? {+ id: dbId,+ schema: schemaName,+ }+ : skipToken,+ );++ return {+ data:+ tables?.map(createTableItem) ??+ (dbId+ ? schemas?.map((schema) => createSchemaItem(dbId, schema))+ : undefined) ??+ databases?.data?.map(createDatabaseItem),+ isLoading: isLoadingTables || isLoadingSchemas || isLoadingDatabases,+ error: tablesError || schemasError || databasesError,+ };+};++export const DbItemList = ({+ parentItem,+ pathIndex,+}: {+ parentItem: OmniPickerItem;+ pathIndex: number;+}) => {+ const { data, error, isLoading } = useGetDbItemListData(parentItem);++ return (+ <ItemList+ items={data}+ pathIndex={pathIndex}+ isLoading={isLoading}+ error={error}+ />+ );+};diff --git a/frontend/src/metabase/common/components/EntityPicker/components/ItemList/ItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/ItemList.tsxsimilarity index 62%rename from frontend/src/metabase/common/components/EntityPicker/components/ItemList/ItemList.tsxrename to frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/ItemList.tsxindex a5af143177c..973cefb14ee 100644--- a/frontend/src/metabase/common/components/EntityPicker/components/ItemList/ItemList.tsx+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/ItemList.tsx@@ -1,6 +1,5 @@import type React from "react";import { useMemo } from "react";-import { t } from "ttag";import { VirtualizedList } from "metabase/common/components/VirtualizedList";import { useTranslateContent } from "metabase/i18n/hooks";@@ -11,61 +10,65 @@ import { getIsTenantUser } from "metabase/selectors/user";import {Box,type BoxProps,- Center,Flex,Icon,NavLink,type NavLinkProps,} from "metabase/ui";-import type { TypeWithModel } from "../../types";+import { useOmniPickerContext } from "../../context";+import type { OmniPickerItem } from "../../types";import { getEntityPickerIcon, isSelectedItem } from "../../utils";-import { DelayedLoadingSpinner } from "../LoadingSpinner";+import { ItemListLoader } from "../LoadingSpinner";-import { PickerColumn } from "./ItemList.styled";+const PickerColumn = ({+ children,+ ...props+}: {+ children: React.ReactNode;+}) => (+ <Box p="1rem" {...props}>+ {children}+ </Box>+);-interface ItemListProps<- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,-> {- items?: Item[] | null;+interface ItemListProps {+ pathIndex: number;+ items?: OmniPickerItem[];isLoading?: boolean;error?: unknown;- onClick: (item: Item) => void;- selectedItem: Item | null;- isFolder: (item: Item) => boolean;- isCurrentLevel: boolean;- shouldDisableItem?: (item: Item) => boolean;- shouldShowItem?: (item: Item) => boolean;navLinkProps?: (isSelected?: boolean) => NavLinkProps;containerProps?: BoxProps;}-export const ItemList = <- Id,- Model extends string,- Item extends TypeWithModel<Id, Model>,->({+export function ItemList({+ pathIndex,items,isLoading = false,error,- onClick,- selectedItem,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,navLinkProps,containerProps = { pb: "xs" },-}: ItemListProps<Id, Model, Item>) => {+}: ItemListProps) {const tc = useTranslateContent();-+ const {+ path,+ setPath,+ isHiddenItem,+ isDisabledItem,+ isFolderItem,+ isSelectableItem,+ onChange,+ options,+ } = useOmniPickerContext();+ const selectedItem = path?.[pathIndex + 1];+ const filteredItems = useMemo(() => {+ return items ? items.filter((i) => !isHiddenItem(i)) : items;+ }, [items, isHiddenItem]);+ const isCurrentLevel = path.length - 2 === pathIndex;const isTenantUser = useSelector(getIsTenantUser);- const filteredItems =- items && shouldShowItem ? items.filter(shouldShowItem) : items;+const activeItemIndex = useMemo(() => {- if (!filteredItems) {+ if (!filteredItems || !selectedItem) {return -1;}@@ -78,14 +81,8 @@ export const ItemList = <return <LoadingAndErrorWrapper error={error} />;}- if (isLoading && !filteredItems) {- return (- <Box miw={310} h="100%" aria-label={t`Loading...`}>- <Center p="lg" h="100%">- <DelayedLoadingSpinner delay={300} />- </Center>- </Box>- );+ if (isLoading) {+ return <ItemListLoader />;}if (!filteredItems || !filteredItems.length) {@@ -98,13 +95,13 @@ export const ItemList = <scrollTo={activeItemIndex}estimatedItemSize={37}>- {filteredItems.map((item: Item) => {- const isSelected = isSelectedItem(item, selectedItem);+ {filteredItems.map((item: OmniPickerItem, index) => {+ const isSelected = index === activeItemIndex;const icon = getEntityPickerIcon(item, {isSelected: isSelected && isCurrentLevel,isTenantUser,});- const isDisabled = shouldDisableItem?.(item);+ const isDisabled = isDisabledItem(item);return (<Box@@ -116,14 +113,16 @@ export const ItemList = <w={"auto"}disabled={isDisabled}rightSection={- isFolder(item) ? <Icon name="chevronright" size={10} /> : null+ isFolderItem(item) ? (+ <Icon name="chevronright" size={10} />+ ) : null}mb={0}label={<Flex align="center">{tc(item.name)}{" "}<PLUGIN_MODERATION.ModerationStatusIcon- status={item.moderated_status}+ status={"moderated_status" in item && item.moderated_status}filledsize={14}ml="0.5rem"@@ -135,7 +134,14 @@ export const ItemList = <onClick={(e: React.MouseEvent) => {e.preventDefault(); // prevent form submissione.stopPropagation(); // prevent parent onClick- onClick(item);+ setPath((prevPath) => [+ ...prevPath.slice(0, pathIndex + 1),+ item,+ ]);++ if (!options?.hasConfirmButtons && isSelectableItem(item)) {+ onChange(item);+ }}}variant={isCurrentLevel ? "default" : "mb-light"}{...navLinkProps?.(isSelected)}@@ -145,4 +151,4 @@ export const ItemList = <})}</VirtualizedList>);-};+}diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/ItemListRouter.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/ItemListRouter.tsxnew file mode 100644index 00000000000..5425f645aee--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/ItemListRouter.tsx@@ -0,0 +1,85 @@+import {+ ItemListLoader,+ type OmniPickerFolderItem,+ type OmniPickerItem,+} from "metabase/common/components/Pickers";+import { PERSONAL_COLLECTIONS } from "metabase/entities/collections";+import { PLUGIN_TENANTS } from "metabase/plugins";++import { CollectionItemList } from "./CollectionItemList";+import { DashboardItemList } from "./DashboardItemList";+import { DbItemList } from "./DbItemList";+import { PersonalCollectionsItemList } from "./PersonalCollectionItemList";+import { RecentsItemList } from "./RecentsItemList";+import { SearchResultsItemList } from "./SearchResultsItemList";++const isDbItem = (item: OmniPickerItem) => {+ return (+ (item.model === "collection" && item.id === "databases") ||+ item.model === "database" ||+ item.model === "schema"+ );+};++export const ItemListRouter = ({+ parentItem,+ pathIndex,+ isLoading,+}: {+ parentItem: OmniPickerFolderItem;+ pathIndex: number;+ isLoading?: boolean;+}) => {+ if (isLoading) {+ return <ItemListLoader />;+ }++ if (!parentItem) {+ console.error("No parent item");+ return null;+ }++ if (parentItem.model === "collection") {+ if (parentItem.id === PERSONAL_COLLECTIONS.id) {+ return <PersonalCollectionsItemList pathIndex={pathIndex} />;+ }++ if (parentItem.id === "search-results") {+ return <SearchResultsItemList />;+ }++ if (parentItem.id === "recents") {+ return <RecentsItemList />;+ }++ if (+ parentItem.id === "root" &&+ parentItem.namespace === PLUGIN_TENANTS.TENANT_SPECIFIC_NAMESPACE+ ) {+ return (+ <PLUGIN_TENANTS.TenantSpecificCollectionsItemList+ pathIndex={pathIndex}+ />+ );+ }++ // Route to tenant collection list only for the root tenant collection+ // (not for subcollections within the tenant namespace)+ if (+ parentItem.id === "root" &&+ parentItem.namespace === PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE+ ) {+ return <PLUGIN_TENANTS.TenantCollectionItemList pathIndex={pathIndex} />;+ }+ }++ if (parentItem.model === "dashboard") {+ return <DashboardItemList parentItem={parentItem} pathIndex={pathIndex} />;+ }++ if (isDbItem(parentItem)) {+ return <DbItemList parentItem={parentItem} pathIndex={pathIndex} />;+ }++ return <CollectionItemList parentItem={parentItem} pathIndex={pathIndex} />;+};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/PersonalCollectionItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/PersonalCollectionItemList.tsxsimilarity index 59%rename from frontend/src/metabase/common/components/Pickers/CollectionPicker/components/PersonalCollectionItemList.tsxrename to frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/PersonalCollectionItemList.tsxindex 283ae1e9c85..386bd254b1f 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/PersonalCollectionItemList.tsx+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/PersonalCollectionItemList.tsx@@ -3,17 +3,16 @@ import { useMemo } from "react";import { useListCollectionsQuery } from "metabase/api";import type { Collection } from "metabase-types/api";-import { ItemList } from "../../../EntityPicker";-import type { CollectionItemListProps, CollectionPickerItem } from "../types";+import type { OmniPickerItem } from "../../types";+import { allCollectionModels } from "../../utils";++import { ItemList } from "./ItemList";export const PersonalCollectionsItemList = ({- onClick,- selectedItem,- isFolder,- isCurrentLevel,- shouldDisableItem,- shouldShowItem,-}: CollectionItemListProps) => {+ pathIndex,+}: {+ pathIndex: number;+}) => {const {data: collections,error,@@ -32,29 +31,26 @@ export const PersonalCollectionsItemList = ({items={topLevelPersonalCollections}error={error}isLoading={isLoading}- onClick={onClick}- selectedItem={selectedItem}- isFolder={isFolder}- isCurrentLevel={isCurrentLevel}- shouldDisableItem={shouldDisableItem}- shouldShowItem={shouldShowItem}+ pathIndex={pathIndex}/>);};const getSortedTopLevelPersonalCollections = (personalCollections?: Collection[],-): CollectionPickerItem[] | null =>+): OmniPickerItem[] | undefined =>personalCollections?.filter(isRootPersonalCollection).map(- (collection: Collection): CollectionPickerItem => ({+ (collection: Collection): OmniPickerItem => ({...collection,- here: ["collection"], // until this endpoint gives this to us, pretend they all have content+ // until this endpoint gives this to us, pretend they all have content+ here: ["collection"],+ below: allCollectionModels,model: "collection",}),)- .sort((a, b) => a?.name.localeCompare(b.name)) ?? null;+ .sort((a, b) => a?.name.localeCompare(b.name)) ?? undefined;// the search api lacks `personal_owner_id` field, so we need this check to be different// than when checking this elsewherediff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/RecentsItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/RecentsItemList.tsxnew file mode 100644index 00000000000..968764c01d7--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/RecentsItemList.tsx@@ -0,0 +1,71 @@+import { useMemo } from "react";++import { useListRecentsQuery } from "metabase/api";+import { Box } from "metabase/ui";+import type { RecentItem } from "metabase-types/api";++import { useOmniPickerContext } from "../../context";+import type { OmniPickerItem } from "../../types";+import { DEFAULT_RECENTS_CONTEXT } from "../EntityPickerModal";++import { SearchResults } from "./SearchResults";++const MAX_RECENTS = 20;++const makeIntoPickerItem = (item: RecentItem): OmniPickerItem => {+ if (item.model !== "table") {+ return {+ ...item,+ collection: {+ ...item.parent_collection,+ id: item.parent_collection?.id ?? "root",+ },+ dashboard_id: item.dashboard?.id,+ };+ }+ return {+ ...item,+ name: item.display_name ?? item.name,+ database_name: item.database.name,+ database_id: item.database.id,+ schema: item.table_schema,+ };+};++export const RecentsItemList = () => {+ const { isHiddenItem, isDisabledItem, isSelectableItem, recentsContext } =+ useOmniPickerContext();++ const {+ data: results,+ error,+ isLoading,+ } = useListRecentsQuery({+ context: recentsContext ?? DEFAULT_RECENTS_CONTEXT,+ });++ const filteredResults = useMemo(() => {+ return (+ results+ ?.map(makeIntoPickerItem)+ .filter(+ // don't show something you can't pick at all+ (item) =>+ isSelectableItem(item) &&+ !isHiddenItem(item) &&+ !isDisabledItem(item),+ )+ .slice(0, MAX_RECENTS) ?? []+ );+ }, [results, isHiddenItem, isDisabledItem, isSelectableItem]);++ return (+ <Box h="100%" w="40rem">+ <SearchResults+ searchResults={filteredResults}+ isLoading={isLoading}+ error={error}+ />+ </Box>+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/RootItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/RootItemList.tsxnew file mode 100644index 00000000000..35d6ad87d54--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/RootItemList.tsx@@ -0,0 +1,18 @@+import { ItemList } from "../..";+import { useRootItems } from "../../hooks/use-get-root-items";++export const RootItemList = ({+ isLoading: isLoadingProp,+}: {+ isLoading: boolean;+}) => {+ const { items, isLoading } = useRootItems();++ return (+ <ItemList+ items={items}+ isLoading={isLoading || isLoadingProp}+ pathIndex={-1}+ />+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/SearchResults.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/SearchResults.tsxnew file mode 100644index 00000000000..c55ec71b135--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/SearchResults.tsx@@ -0,0 +1,239 @@+import { t } from "ttag";++import { Ellipsified } from "metabase/common/components/Ellipsified";+import { EmptyState } from "metabase/common/components/EmptyState";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { VirtualizedList } from "metabase/common/components/VirtualizedList";+import { NoObjectError } from "metabase/common/components/errors/NoObjectError";+import { getIcon } from "metabase/lib/icon";+import { PLUGIN_DATA_STUDIO, PLUGIN_MODERATION } from "metabase/plugins";+// import { trackSearchClick } from "metabase/search/analytics";+import { Box, Flex, Icon, NavLink, SegmentedControl, Text } from "metabase/ui";++import type { OmniPickerItem, OmniPickerTableItem, SearchScope } from "../..";+import { useOmniPickerContext } from "../../context";+import {+ useCurrentSearchScope,+ useGetLastCollection,+} from "../../hooks/use-current-search-scope";+import { getEntityPickerIcon, isSelectedItem } from "../../utils";++export const SearchResults = ({+ searchResults,+ isLoading,+ error,+ onClick,+}: {+ searchResults: OmniPickerItem[];+ isLoading?: boolean;+ error?: unknown;+ onClick?: (item: OmniPickerItem, index: number) => void;+}) => {+ const { path, setPath, isDisabledItem, isSelectableItem, options, onChange } =+ useOmniPickerContext();+ const selectedItem = path?.[path.length - 1];++ if (isLoading || error) {+ return (+ <Box h="100%" w="40rem">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />;+ </Box>+ );+ }++ if (searchResults.length === 0) {+ return (+ <EmptyState+ title={t`We didn't find anything`}+ illustrationElement={<NoObjectError mb="-1.5rem" />}+ />+ );+ }++ return (+ <VirtualizedList+ Wrapper={({ children, ...props }) => (+ <Box py="md" {...props}>+ {children}+ </Box>+ )}+ estimatedItemSize={66}+ >+ {searchResults?.map((item, index) => {+ const isSelected = isSelectedItem(item, selectedItem);+ const isSelectable = isSelectableItem(item);++ return (+ <Box+ key={`${item.model}-${item.id}`}+ pb="xs"+ px="sm"+ data-testid="result-item"+ data-model-type={item.model}+ >+ <NavLink+ w={"auto"}+ disabled={isDisabledItem(item) || !isSelectable}+ rightSection={+ <LocationInfo item={item} isSelected={isSelected} />+ }+ mb={0}+ label={+ <Flex align="center">+ <Ellipsified maw="21rem">{item.name} </Ellipsified>+ <PLUGIN_MODERATION.ModerationStatusIcon+ status={"moderated_status" in item && item.moderated_status}+ filled+ size={14}+ ml="0.5rem"+ />+ </Flex>+ }+ active={isSelected}+ leftSection={+ <Icon+ {...getEntityPickerIcon(item, { isSelected })}+ size={16}+ />+ }+ onClick={(e: React.MouseEvent) => {+ e.preventDefault(); // prevent form submission+ e.stopPropagation(); // prevent parent onClick++ if (onClick) {+ onClick(item, index);+ }++ if (isSelectable) {+ setPath((prevPath) => [...prevPath.slice(0, 1), item]);++ if (!options?.hasConfirmButtons) {+ onChange(item);+ }+ }+ }}+ variant="default"+ />+ </Box>+ );+ })}+ </VirtualizedList>+ );+};++const isTableInDb = (item: OmniPickerItem): item is OmniPickerTableItem => {+ return (+ item.model === "table" &&+ (!("collection" in item) || (!!item.collection && !item.collection.name))+ );+};++const getItemText = (item: OmniPickerItem) => {+ const isTable = isTableInDb(item);++ if (item.model === "schema") {+ return item.id;+ }++ if (item.model === "database") {+ return "";+ }++ return isTable+ ? `${item.database_name}${item.schema ? ` (${item.schema})` : ""}`+ : (item?.collection?.name ?? t`Our analytics`);+};++const getLocationIcon = (item: OmniPickerItem) => {+ if (+ item.model === "table" ||+ item.model === "schema" ||+ item.model === "database"+ ) {+ return null;+ }++ return getIcon({+ ...item,+ model: "collection",+ });+};++const LocationInfo = ({+ item,+ isSelected,+}: {+ item: OmniPickerItem;+ isSelected: boolean;+}) => {+ const itemText = getItemText(item);++ if (!itemText) {+ return null;+ }++ const iconProps = getLocationIcon(item);++ return (+ <Flex gap="xs" align="center">+ {iconProps && <Icon {...iconProps} size={12} />}+ <Text+ size="sm"+ c={isSelected ? "text-secondary-inverse" : "text-secondary"}+ >+ <Ellipsified maw="12rem" data-testid="picker-item-location">+ {itemText}+ </Ellipsified>+ </Text>+ </Flex>+ );+};++export function SearchScopeSelector() {+ const { setSearchScope } = useOmniPickerContext();+ const searchScope = useCurrentSearchScope();++ const { data: libraryCollection } =+ PLUGIN_DATA_STUDIO.useGetLibraryCollection();++ const lastCollection = useGetLastCollection();++ const options = [+ { label: t`Everywhere`, value: "all" },+ libraryCollection?.id+ ? { label: t`Library`, value: String(libraryCollection.id) }+ : null,+ lastCollection+ ? {+ label: truncateName(lastCollection.name, 20),+ value: String(lastCollection.id),+ }+ : null,+ ].filter((i) => i !== null);++ return (+ <Flex+ justify="space-between"+ align="center"+ px="md"+ py="sm"+ bg="background-secondary"+ mb="xs"+ data-testid="search-scope-selector"+ >+ <Text>{t`Where to search:`}</Text>+ <SegmentedControl+ value={searchScope ? String(searchScope) : "all"}+ onChange={(newValue) => setSearchScope(newValue as SearchScope)}+ data={options}+ />+ </Flex>+ );+}++const truncateName = (name: string, maxLength: number) => {+ if (name.length <= maxLength) {+ return name;+ }+ return name.slice(0, maxLength - 1) + "…";+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/SearchResultsItemList.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/SearchResultsItemList.tsxnew file mode 100644index 00000000000..11cbf4c2784--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/SearchResultsItemList.tsx@@ -0,0 +1,159 @@+import { useCallback, useMemo } from "react";+import { pick } from "underscore";++import { skipToken, useSearchQuery } from "metabase/api";+import { trackSearchClick } from "metabase/search/analytics";+import { Stack } from "metabase/ui";+import {+ SEARCH_MODELS,+ type SchemaName,+ type SearchModel,+ type SearchRequest,+ type SearchResult,+} from "metabase-types/api";++import { useOmniPickerContext } from "../../context";+import { useCurrentSearchScope } from "../../hooks/use-current-search-scope";+import type { OmniPickerItem } from "../../types";++import { SearchResults, SearchScopeSelector } from "./SearchResults";++const makeIntoPickerItem = (+ item: SearchResult,+ searchParams?: Partial<SearchRequest>,+): OmniPickerItem => {+ const isGuaranteedPersonal =+ searchParams?.filter_items_in_personal_collection === "only";+ const isGuaranteedNotPersonal =+ searchParams?.filter_items_in_personal_collection === "exclude";++ if (item.model === "table") {+ return {+ ...pick(item, ["id", "name", "collection", "database_id"]),+ model: "table",+ database_name: item.database_name ?? undefined,+ schema: item.table_schema as SchemaName,+ };+ }++ return {+ ...item,+ type: "type" in item ? item.type : item.collection_type,+ // search items don't have locations, so we can't tell from the item itself if it's in a personal collection+ // but if the searchParams are filtering to only personal collection items, we can assume it is+ is_personal:+ isGuaranteedPersonal || (isGuaranteedNotPersonal ? false : undefined),+ } as OmniPickerItem;+};++const useApiSearch = ({+ searchQuery,+ models,+ searchParams,+}: {+ models: OmniPickerItem["model"][];+ searchQuery?: string;+ searchParams?: Partial<SearchRequest>;+}) => {+ const searchScope = useCurrentSearchScope();++ const { searchCollection, searchModels } = useMemo(() => {+ if (searchScope === "databases") {+ // if we're searching the databases scope, only search for tables+ return {+ searchCollection: undefined,+ searchModels: ["table" as const],+ };+ }+ const searchModels = models.filter((model) =>+ SEARCH_MODELS.includes(model as SearchModel),+ ) as SearchModel[];+ if (searchScope === "all") {+ return {+ searchCollection: undefined,+ searchModels,+ };+ }+ return {+ searchCollection: searchScope || undefined,+ searchModels,+ };+ }, [searchScope, models]);++ const apiQuery: SearchRequest = useMemo(+ () => ({+ q: searchQuery || "",+ collection: searchCollection,+ models: searchModels,+ context: "entity-picker",+ limit: 50,+ calculate_available_models: true,+ ...(searchParams || {}),+ }),+ [searchQuery, searchCollection, searchModels, searchParams],+ );++ return useSearchQuery(apiQuery?.q?.length ? apiQuery : skipToken);+};++export const SearchResultsItemList = () => {+ const {+ models,+ searchQuery,+ isHiddenItem,+ isDisabledItem,+ isSelectableItem,+ searchParams,+ } = useOmniPickerContext();++ const {+ data: results,+ error,+ isFetching,+ } = useApiSearch({+ models,+ searchQuery,+ searchParams,+ });++ const filteredResults = useMemo(+ () =>+ results?.data+ ?.map((i) => makeIntoPickerItem(i, searchParams))+ .filter(+ // don't show something you can't pick at all+ (item) =>+ isSelectableItem(item) &&+ !isHiddenItem(item) &&+ !isDisabledItem(item),+ ) || [],+ [results, isHiddenItem, isDisabledItem, isSelectableItem, searchParams],+ );++ const onClick = useCallback(+ (item: OmniPickerItem, index: number) => {+ trackSearchClick({+ itemType: "item",+ position: index,+ context: "entity-picker",+ searchEngine: "unknown",+ entityModel: item.model,+ entityId: typeof item.id === "number" ? item.id : null,+ searchTerm: searchQuery,+ });+ },+ [searchQuery],+ );++ return (+ <Stack h="100%" w="40rem" gap={0}>+ <SearchScopeSelector />+ <SearchResults+ searchResults={filteredResults}+ isLoading={isFetching}+ error={error}+ onClick={onClick}+ />+ </Stack>+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/index.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/index.tsnew file mode 100644index 00000000000..edd16590608--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/ItemLists/index.ts@@ -0,0 +1,3 @@+export * from "./ItemList";+export * from "./RootItemList";+export * from "./ItemListRouter";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/LoadingSpinner/LoadingSpinner.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/LoadingSpinner.tsxsimilarity index 77%rename from frontend/src/metabase/common/components/EntityPicker/components/LoadingSpinner/LoadingSpinner.tsxrename to frontend/src/metabase/common/components/Pickers/EntityPicker/components/LoadingSpinner.tsxindex 78b80b70816..bd299ca709c 100644--- a/frontend/src/metabase/common/components/EntityPicker/components/LoadingSpinner/LoadingSpinner.tsx+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/LoadingSpinner.tsx@@ -1,7 +1,8 @@import { useState } from "react";import { useMount } from "react-use";+import { t } from "ttag";-import { Flex, Loader, Text } from "metabase/ui";+import { Box, Center, Flex, Loader, Text } from "metabase/ui";export const LoadingSpinner = ({ text }: { text?: string }) => (<Flex@@ -41,3 +42,11 @@ export const DelayedLoadingSpinner = ({return <LoadingSpinner text={text} />;};++export const ItemListLoader = () => (+ <Box w={365} h="100%" aria-label={t`Loading...`}>+ <Center p="lg" h="100%">+ <DelayedLoadingSpinner delay={300} />+ </Center>+ </Box>+);diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NestedItemPicker.module.css b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NestedItemPicker.module.cssnew file mode 100644index 00000000000..9af76dfdefd--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NestedItemPicker.module.css@@ -0,0 +1,16 @@+.ListBox {+ border-right: 1px solid var(--mb-color-border);+ height: 100%;+ min-width: 365px;+ background-color: var(--mb-color-background-secondary);++ &:last-child {+ background-color: var(--mb-color-background-primary);+ }+}++.singlePickerView {+ border-top: 1px solid var(--mb-color-border);+ flex-grow: 1;+ height: 0;+}diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NestedItemPicker.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NestedItemPicker.tsxnew file mode 100644index 00000000000..090edd4c243--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NestedItemPicker.tsx@@ -0,0 +1,49 @@+import ErrorBoundary from "metabase/ErrorBoundary";+import { Box, Flex } from "metabase/ui";++import { useOmniPickerContext } from "../context";+import { useSwitchToSearchFolder } from "../hooks/use-switch-to-search-folder";++import { AutoScrollBox } from "./AutoScrollBox";+import { ItemListRouter } from "./ItemLists/ItemListRouter";+import { RootItemList } from "./ItemLists/RootItemList";+import S from "./NestedItemPicker.module.css";+import { generateKey } from "./utils";++export function NestedItemPicker() {+ const { path, isLoadingPath, isFolderItem } = useOmniPickerContext();+ const folderPath = path.filter(isFolderItem);+ useSwitchToSearchFolder();++ return (+ <div className={S.singlePickerView} data-testid="single-picker-view">+ <AutoScrollBox+ data-testid="nested-item-picker"+ contentHash={generateKey(path?.[path.length - 1])}+ >+ <Flex h="100%" w="fit-content">+ <Box className={S.ListBox} data-testid={`item-picker-level-0`}>+ <RootItemList isLoading={isLoadingPath} />+ </Box>+ {folderPath.map((item, index) => {+ return (+ <Box+ className={S.ListBox}+ data-testid={`item-picker-level-${index + 1}`}+ key={generateKey(item)}+ >+ <ErrorBoundary>+ <ItemListRouter+ parentItem={item}+ pathIndex={index}+ isLoading={isLoadingPath}+ />+ </ErrorBoundary>+ </Box>+ );+ })}+ </Flex>+ </AutoScrollBox>+ </div>+ );+}diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewCollectionDialog/NewCollectionDialog.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewCollectionDialog/NewCollectionDialog.tsxnew file mode 100644index 00000000000..120880618f1--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewCollectionDialog/NewCollectionDialog.tsx@@ -0,0 +1,159 @@+import { useMemo } from "react";+import { t } from "ttag";+import * as Yup from "yup";++import { useCreateCollectionMutation } from "metabase/api";+import { canPlaceEntityInCollection } from "metabase/collections/utils";+import { FormFooter } from "metabase/common/components/FormFooter";+import { useEscapeToCloseModal } from "metabase/common/hooks/use-escape-to-close-modal";+import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSubmitButton,+ FormTextInput,+} from "metabase/forms";+import * as Errors from "metabase/lib/errors";+import { PLUGIN_TENANTS } from "metabase/plugins";+import { Button, Flex, Modal } from "metabase/ui";++import { useOmniPickerContext } from "../../context";+import type { OmniPickerCollectionItem } from "../../types";+import {+ getCollectionType,+ isCollection,+ isInRecentsOrSearch,+} from "../../utils";++const NEW_COLLECTION_SCHEMA = Yup.object({+ name: Yup.string()+ .required(Errors.required)+ .max(100, Errors.maxLength)+ .default(""),+});++export const NewCollectionDialog = () => {+ const [createCollection] = useCreateCollectionMutation();+ const {+ options,+ path,+ setPath,+ isNewCollectionDialogOpen: isOpen,+ openNewCollectionDialog: open,+ closeNewCollectionDialog: close,+ } = useOmniPickerContext();++ const { lastCollection, lastCollectionIdx } = useMemo(() => {+ const lastCollectionIndex = path.findLastIndex(isCollection);++ return {+ lastCollectionIdx: lastCollectionIndex,+ lastCollection:+ path[lastCollectionIndex] && isCollection(path[lastCollectionIndex])+ ? path[lastCollectionIndex]+ : undefined,+ };+ }, [path]);++ useEscapeToCloseModal(close, { capture: true });++ if (!options.canCreateCollections) {+ return null;+ }++ const canCreateHere =+ !isInRecentsOrSearch(path) &&+ lastCollection &&+ lastCollection.can_write &&+ canPlaceEntityInCollection(+ "collection",+ getCollectionType(lastCollection),+ ) &&+ PLUGIN_TENANTS.canPlaceEntityInCollection({+ entityType: "collection",+ collection: lastCollection,+ });++ const onCreateNewCollection = async ({ name }: { name: string }) => {+ if (!canCreateHere) {+ return;+ }+ // Virtual collection IDs like "root" and "tenant" should be converted to null+ // These represent namespace roots which have no parent+ const isVirtualRoot =+ lastCollection.id === "root" || lastCollection.id === "tenant";++ const newCollection = await createCollection({+ name,+ parent_id: isVirtualRoot ? null : lastCollection.id,+ namespace: lastCollection.namespace,+ }).unwrap();++ const parentCollection: OmniPickerCollectionItem = {+ ...lastCollection,+ // refresh last collection to show it has new child+ here: lastCollection.here+ ? lastCollection.here.concat(["collection"])+ : ["collection"],+ };++ setPath([+ ...path.slice(0, lastCollectionIdx),+ parentCollection,+ { ...newCollection, can_write: true, model: "collection" }, // select newly created collection+ ]);++ close();+ };++ return (+ <>+ <Button onClick={open} disabled={!canCreateHere}>+ {lastCollection?.namespace === "transforms" ||+ lastCollection?.namespace === "snippets"+ ? t`New folder`+ : t`New collection`}+ </Button>+ <Modal+ title={t`Create a new collection`}+ opened={isOpen}+ onClose={close}+ data-testid="create-collection-on-the-go"+ trapFocus={true}+ withCloseButton={false}+ closeOnEscape={false}+ >+ <FormProvider+ initialValues={{ name: "" }}+ validationSchema={NEW_COLLECTION_SCHEMA}+ onSubmit={onCreateNewCollection}+ >+ {({ dirty }: { dirty: boolean }) => (+ <Form>+ <FormTextInput+ name="name"+ label={t`Give it a name`}+ placeholder={t`My new collection`}+ mb="1rem"+ labelProps={{ my: "0.5rem" }}+ data-autofocus+ />+ <FormFooter>+ <FormErrorMessage inline />+ <Flex style={{ flexShrink: 1 }} justify="flex-end" gap="sm">+ <Button type="button" onClick={close}>{t`Cancel`}</Button>+ <FormSubmitButton+ type="submit"+ label={t`Create`}+ disabled={!dirty}+ variant="filled"+ />+ </Flex>+ </FormFooter>+ </Form>+ )}+ </FormProvider>+ </Modal>+ </>+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewCollectionDialog/index.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewCollectionDialog/index.tsnew file mode 100644index 00000000000..e8e35b6ffeb--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewCollectionDialog/index.ts@@ -0,0 +1 @@+export * from "./NewCollectionDialog";diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewDashboardDialog/NewDashboardDialog.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewDashboardDialog/NewDashboardDialog.tsxnew file mode 100644index 00000000000..82ce3e614bb--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewDashboardDialog/NewDashboardDialog.tsx@@ -0,0 +1,145 @@+import { useMemo } from "react";+import { t } from "ttag";++import { useCreateDashboardMutation } from "metabase/api";+import { FormFooter } from "metabase/common/components/FormFooter";+import { useEscapeToCloseModal } from "metabase/common/hooks/use-escape-to-close-modal";+import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSubmitButton,+ FormTextInput,+} from "metabase/forms";+import { PLUGIN_DATA_STUDIO, PLUGIN_TENANTS } from "metabase/plugins";+import { Button, Flex, Modal } from "metabase/ui";++import { useOmniPickerContext } from "../../context";+import type { OmniPickerCollectionItem } from "../../types";+import {+ getCollectionType,+ isCollection,+ isInRecentsOrSearch,+} from "../../utils";++export const NewDashboardDialog = () => {+ const [createDashboard] = useCreateDashboardMutation();+ const {+ options,+ path,+ setPath,+ isNewDashboardDialogOpen: isOpen,+ openNewDashboardDialog: open,+ closeNewDashboardDialog: close,+ } = useOmniPickerContext();++ const { lastCollection, lastCollectionIdx } = useMemo(() => {+ const lastCollectionIndex = path.findLastIndex(isCollection);++ return {+ lastCollectionIdx: lastCollectionIndex,+ lastCollection:+ path[lastCollectionIndex] && isCollection(path[lastCollectionIndex])+ ? path[lastCollectionIndex]+ : undefined,+ };+ }, [path]);++ useEscapeToCloseModal(close, { capture: true });++ if (!options.canCreateDashboards) {+ return null;+ }++ const canCreateHere =+ !isInRecentsOrSearch(path) &&+ lastCollection &&+ "can_write" in lastCollection &&+ lastCollection.can_write &&+ PLUGIN_TENANTS.canPlaceEntityInCollection({+ entityType: "dashboard",+ collection: lastCollection,+ }) &&+ PLUGIN_DATA_STUDIO.canPlaceEntityInCollection(+ "dashboard",+ getCollectionType(lastCollection),+ );++ const onCreateNewDashboard = async ({ name }: { name: string }) => {+ if (!canCreateHere) {+ return;+ }+ const newDashboard = await createDashboard({+ name,+ collection_id: lastCollection.id === "root" ? null : lastCollection.id,+ }).unwrap();++ const parentCollection: OmniPickerCollectionItem = {+ ...lastCollection,+ // refresh last collection to show it has new child+ here: lastCollection.here+ ? lastCollection.here.concat(["dashboard"])+ : ["dashboard"],+ };++ setPath([+ ...path.slice(0, lastCollectionIdx),+ parentCollection,+ { ...newDashboard, model: "dashboard" }, // select newly created dashboard+ ]);++ close();+ };++ return (+ <>+ <Button onClick={open} disabled={!canCreateHere}>+ {t`New dashboard`}+ </Button>+ <Modal+ title={t`Create a new dashboard`}+ opened={isOpen}+ onClose={close}+ data-testid="create-dashboard-on-the-go"+ trapFocus={true}+ withCloseButton={false}+ closeOnEscape={false}+ styles={{+ content: {+ padding: "1rem",+ },+ }}+ >+ <FormProvider+ initialValues={{ name: "" }}+ onSubmit={onCreateNewDashboard}+ >+ {({ dirty, isSubmitting }) => (+ <Form>+ <FormTextInput+ name="name"+ label={t`Give it a name`}+ placeholder={t`My new dashboard`}+ mb="1rem"+ labelProps={{ my: "0.5rem" }}+ data-autofocus+ />+ <FormFooter>+ <FormErrorMessage inline />+ <Flex style={{ flexShrink: 1 }} justify="flex-end" gap="sm">+ <Button type="button" onClick={close}>{t`Cancel`}</Button>+ <FormSubmitButton+ type="submit"+ label={t`Create`}+ disabled={!dirty || isSubmitting}+ variant="filled"+ />+ </Flex>+ </FormFooter>+ </Form>+ )}+ </FormProvider>+ </Modal>+ </>+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewDashboardDialog/index.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewDashboardDialog/index.tsnew file mode 100644index 00000000000..37f24cb3e68--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/NewDashboardDialog/index.ts@@ -0,0 +1 @@+export * from "./NewDashboardDialog";diff --git a/frontend/src/metabase/common/components/EntityPicker/components/index.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/index.tsxsimilarity index 82%rename from frontend/src/metabase/common/components/EntityPicker/components/index.tsrename to frontend/src/metabase/common/components/Pickers/EntityPicker/components/index.tsxindex 78916ff3b6c..243c500aeca 100644--- a/frontend/src/metabase/common/components/EntityPicker/components/index.ts+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/index.tsx@@ -1,5 +1,5 @@export * from "./AutoScrollBox";export * from "./EntityPickerModal";-export * from "./ItemList";+export * from "./ItemLists";export * from "./LoadingSpinner";export * from "./NestedItemPicker";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.tsxnew file mode 100644index 00000000000..b67f9659172--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/EntityPickerModal.unit.spec.tsx@@ -0,0 +1,769 @@+import userEvent from "@testing-library/user-event";++import { findRequests } from "__support__/server-mocks";+import { screen, waitFor, within } from "__support__/ui";++import { setup } from "./setup";++const expectActiveItem = async (itemName: string) =>+ waitFor(() =>+ expect(+ screen.getByRole("link", { name: new RegExp(itemName) }),+ ).toHaveAttribute("data-active", "true"),+ );++const expectInactiveItem = async (itemName: string) =>+ waitFor(() =>+ expect(+ screen.getByRole("link", { name: new RegExp(itemName) }),+ ).not.toHaveAttribute("data-active", "true"),+ );++const expectVisibleItem = async (itemName: string) =>+ waitFor(() =>+ expect(+ screen.getByRole("link", { name: new RegExp(itemName) }),+ ).toBeVisible(),+ );++describe("EntityPickerModal", () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ describe("Default Behavior", () => {+ it("should render a picker", async () => {+ await setup({ title: "Test picker 😁" });+ expect(await screen.findByText("Test picker 😁")).toBeInTheDocument();+ });++ it("should open databases if enabled", async () => {+ await setup({ options: { hasDatabases: true } });+ await expectActiveItem("Databases");+ });++ it("should not show databases if there are none", async () => {+ await setup({ options: { hasDatabases: true }, databases: [] });+ await expectVisibleItem("Recent items");+ expect(screen.queryByText("Databases")).not.toBeInTheDocument();+ });++ it("should display root items when there are no databases or recents", async () => {+ await setup({+ options: { hasDatabases: true, hasRecents: false },+ databases: [],+ });++ await expectInactiveItem("Our analytics");+ expect(screen.queryByText("Databases")).not.toBeInTheDocument();+ expect(screen.queryByText("Recent items")).not.toBeInTheDocument();+ });++ it("Should select recents by default without databases", async () => {+ await setup();+ await expectActiveItem("Recent items");+ });++ it("Should select our analytics by default without databases or recents", async () => {+ await setup({+ options: { hasRecents: false, hasDatabases: false },+ models: ["collection", "card", "dashboard"],+ });+ await expectActiveItem("Our analytics");+ });+ });++ describe("Collection Navigation", () => {+ it("should auto-select a collection path based on value item", async () => {+ await setup({ value: { id: 33, model: "collection" } });++ await expectActiveItem("Our analytics");+ await expectActiveItem("First Collection");+ await expectActiveItem("Nested Collection");+ await expectInactiveItem("Question in Nested Coll");+ });++ it("should only hit collection/items endpoint once for each collection (backparse cache hit)", async () => {+ await setup({ value: { id: 33, model: "collection" } });++ await expectActiveItem("Our analytics");+ await expectActiveItem("First Collection");+ await expectActiveItem("Nested Collection");+ await expectInactiveItem("Question in Nested Coll");+ const gets = await findRequests("GET");++ // if we get 2 hits on any of these, the api request in+ // use-get-path-from-value got desynced from the one in CollectionItemList+ const rootHits = gets.filter((req) =>+ req.url.includes("/api/collection/root/items"),+ );+ const firstCollectionHits = gets.filter((req) =>+ req.url.includes("/api/collection/11/items"),+ );+ const nestedCollectionHits = gets.filter((req) =>+ req.url.includes("/api/collection/33/items"),+ );+ expect(rootHits).toHaveLength(1);+ expect(firstCollectionHits).toHaveLength(1);+ expect(nestedCollectionHits).toHaveLength(1);+ });++ it("should navigate into collections when clicked", async () => {+ await setup({ value: { id: "root", model: "collection" } });+ await expectActiveItem("Our analytics"); // level 0+ await userEvent.click(await screen.findByText("First Collection")); // level 1+ await expectActiveItem("First Collection");++ expect(+ await screen.findByText("Question in Collection 1"), // level 2+ ).toBeInTheDocument();+ expect(+ await screen.findByText("Dashboard in Collection 1"),+ ).toBeInTheDocument();+ await expectInactiveItem("Nested Collection");+ await userEvent.click(await screen.findByText(/Nested Collection/));+ await expectActiveItem("Nested Collection");+ await expectInactiveItem("Question in Nested Coll"); // level 3+ });++ it("should navigate back", async () => {+ await setup({ value: { id: 33, model: "collection" } });++ await expectVisibleItem("Question in Nested Coll");+ await userEvent.click(await screen.findByText("First Collection"));+ await expectVisibleItem("Nested Collection");++ // nested item no longer visible+ expect(+ screen.queryByText(/Question in Nested Coll/),+ ).not.toBeInTheDocument();+ });++ it("should navigate sideways", async () => {+ await setup({ value: { id: "root", model: "collection" } });+ await expectActiveItem("Our analytics"); // level 0++ await userEvent.click(await screen.findByText("First Collection")); // level 1+ await expectActiveItem("First Collection");+ await expectVisibleItem("Question in Collection 1"); // level 2+ await expectVisibleItem("Dashboard in Collection 1");++ await userEvent.click(await screen.findByText("Second Collection")); // level 1+ await expectActiveItem("Second Collection");+ await expectInactiveItem("First Collection"); // level 2+ await expectVisibleItem("Question in Collection 2"); // level 2+ await expectVisibleItem("Model in Collection 2");+ expect(+ screen.queryByText("Question in Collection 1"),+ ).not.toBeInTheDocument();+ });+ });++ describe("Database Navigation", () => {+ it("should show databases item", async () => {+ await setup({ options: { hasDatabases: true } });+ await userEvent.click(await screen.findByText("Databases"));++ await expectActiveItem("Databases");+ });++ it("should hide databases item by default", async () => {+ await setup();+ await expectVisibleItem("Our analytics");+ expect(screen.queryByText("Databases")).not.toBeInTheDocument();+ });++ it("should auto-select a table path based on value item", async () => {+ await setup({+ options: { hasDatabases: true },+ value: { id: 32, model: "table" },+ });++ await expectActiveItem("Databases");+ await expectActiveItem("Database 3");+ await expectActiveItem("schema five");+ await expectActiveItem("Table 32");+ });++ it("hides schemas when there's only one in a db", async () => {+ await setup({+ options: { hasDatabases: true },+ value: { id: 20, model: "table" },+ });++ await expectActiveItem("Databases");+ await expectActiveItem("Database 2");+ await expectActiveItem("Table 20");+ expect(screen.queryByText(/schema/i)).not.toBeInTheDocument();+ });++ it("can disable databases based on isDisabledItem", async () => {+ await setup({+ options: { hasDatabases: true },+ value: { id: 2, model: "database" },+ isDisabledItem: (item) => item.model === "database" && item.id === 3,+ });+ await expectActiveItem("Database 2");+ await expectVisibleItem("Database 3");+ const db3Item = await screen.findByRole("link", { name: /Database 3/ });+ expect(db3Item).toHaveAttribute("data-disabled", "true");+ });++ it("can hide databases based on isDisabledItem", async () => {+ await setup({+ options: { hasDatabases: true },+ value: { id: 2, model: "database" },+ isHiddenItem: (item) => item.model === "database" && item.id === 3,+ });+ await expectActiveItem("Database 2");+ expect(screen.queryByText("Database 3")).not.toBeInTheDocument();+ });++ it("can disable table selection based on isSelectableItem", async () => {+ await setup({+ options: { hasDatabases: true },+ value: { id: 2, model: "database" },+ isSelectableItem: (item) => item.model === "table" && item.id !== 21,+ });+ await expectActiveItem("Database 2");+ await expectVisibleItem("Table 20");+ await expectVisibleItem("Table 21");+ await expectVisibleItem("Table 22");++ await userEvent.click(await screen.findByText("Table 20"));+ expect(+ await screen.findByRole("button", { name: "Select" }),+ ).toBeEnabled();++ await userEvent.click(await screen.findByText("Table 21"));+ expect(+ await screen.findByRole("button", { name: "Select" }),+ ).toBeDisabled();+ });+ });++ describe("Selection", () => {+ it("should show confirm button and text based on option", async () => {+ await setup({+ options: { hasConfirmButtons: true, confirmButtonText: "YES PLEASE" },+ });++ expect(+ await screen.findByRole("button", { name: "YES PLEASE" }),+ ).toBeInTheDocument();+ });++ it("should hide confirm button when option is false", async () => {+ await setup({+ options: { hasConfirmButtons: false, confirmButtonText: "Select" },+ });+ await expectVisibleItem("Our analytics");++ expect(+ screen.queryByRole("button", { name: /Select/i }),+ ).not.toBeInTheDocument();+ });++ it("should call onChange when selecting a collection item", async () => {+ const { onChange } = await setup();+ 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" }),+ );++ await waitFor(() => {+ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 100,+ model: "card",+ name: "Question in Collection 1",+ }),+ );+ });+ });++ it("should call onChange without a confirm button", async () => {+ const { onChange } = await setup({+ options: { hasConfirmButtons: 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"),+ );++ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 100,+ model: "card",+ name: "Question in Collection 1",+ }),+ );+ });++ it("should select a nested item", async () => {+ const { onChange } = await setup();+ await userEvent.click(await screen.findByText("Our analytics"));+ await userEvent.click(await screen.findByText("First Collection"));+ await userEvent.click(await screen.findByText("Nested Collection"));+ await userEvent.click(await screen.findByText("Metric in Nested Coll"));+ await userEvent.click(+ await screen.findByRole("button", { name: "Select" }),+ );++ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 301,+ model: "metric",+ name: "Metric in Nested Coll",+ }),+ );+ });++ it("should allow selecting a collection itself", async () => {+ const { onChange } = await setup({+ models: ["collection", "card", "dashboard"],+ });+ await userEvent.click(await screen.findByText("Our analytics"));+ await userEvent.click(await screen.findByText("First Collection"));+ await userEvent.click(+ await screen.findByRole("button", { name: "Select" }),+ );++ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 11,+ model: "collection",+ name: "First Collection",+ }),+ );+ });++ it("can disable selection based on provided models", async () => {+ const { onChange } = await setup({+ models: ["card"], // no collections+ });+ await userEvent.click(await screen.findByText("Our analytics"));+ await userEvent.click(await screen.findByText("First Collection"));+ await expectActiveItem("First Collection");+ const selectButton = await screen.findByRole("button", {+ name: "Select",+ });+ expect(selectButton).toBeDisabled();+ await userEvent.click(selectButton);++ expect(onChange).not.toHaveBeenCalled();+ });++ it("can disable selection based on isSelectableItem callback", async () => {+ const { onChange } = await setup({+ isSelectableItem: (item) => !item.name.includes("1"),+ });++ 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 expectActiveItem("Question in Collection 1");+ // can't ultimately select anything with 1 in the name+ const selectButton = await screen.findByRole("button", {+ name: "Select",+ });+ expect(selectButton).toBeDisabled();+ await userEvent.click(selectButton);++ expect(onChange).not.toHaveBeenCalled();++ await userEvent.click(await screen.findByText("Second Collection"));+ await userEvent.click(+ await screen.findByText("Question in Collection 2"),+ );+ await expectActiveItem("Question in Collection 2");+ // can select items without 1 in the name+ const selectButton2 = await screen.findByRole("button", {+ name: "Select",+ });+ expect(selectButton2).toBeEnabled();+ await userEvent.click(selectButton2);++ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 200,+ model: "card",+ name: "Question in Collection 2",+ }),+ );+ });+ });++ describe("Search", () => {+ const waitForSearchResults = async () => {+ // input debounce means we need to wait for a little longer+ return screen.findByText(/Search results/i, {}, { timeout: 600 });+ };++ it("should not show search nav item without a search query", async () => {+ await setup();+ await expectInactiveItem("Our analytics");+ expect(screen.getByPlaceholderText(/Search…/i)).toBeInTheDocument();+ expect(screen.queryByText(/Search results/i)).not.toBeInTheDocument();+ });++ it("should hide search based on option", async () => {+ await setup({ options: { hasSearch: false } });+ await expectInactiveItem("Our analytics");+ expect(screen.queryByPlaceholderText(/Search…/i)).not.toBeInTheDocument();+ });++ it("should show a search nav item with a search query", async () => {+ await setup();++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectActiveItem('Search results for "My"');+ });++ it("should return to previous location when clearing the search input", async () => {+ await setup();+ 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 expectActiveItem("Question in Collection 1");+ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ // search is open+ await expectActiveItem('Search results for "My"');+ // selected item is gone+ expect(+ screen.queryByText("Question in Collection 1"),+ ).not.toBeInTheDocument();+ await userEvent.click(await screen.findByTestId("clear-search"));+ // input is empty+ expect(await screen.findByPlaceholderText("Search…")).toHaveValue("");+ // previous item is active again+ await expectActiveItem("Question in Collection 1");+ });++ it("should show search results", async () => {+ await setup();++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectVisibleItem("Search Result Card 3");+ await expectVisibleItem("Search Result Dashboard 5");+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(11);+ });++ it("should hide search results based on isHiddenItem", async () => {+ await setup({+ isHiddenItem: (item) => item.name.includes("Dash"),+ });++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectVisibleItem("Search Result Card 3");+ expect(+ screen.queryByText("Search Result Dashboard 5"),+ ).not.toBeInTheDocument();+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(9);+ });++ it("should hide search results based on isDisabledItem", async () => {+ await setup({+ isDisabledItem: (item) => item.name.includes("Dash"),+ });++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectVisibleItem("Search Result Card 3");+ expect(+ screen.queryByText("Search Result Dashboard 5"),+ ).not.toBeInTheDocument();+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(9);+ });++ it("should hide search results based on isSelectableItem", async () => {+ await setup({+ isSelectableItem: (item) => !item.name.includes("Dash"),+ });++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectVisibleItem("Search Result Card 3");+ expect(+ screen.queryByText("Search Result Dashboard 5"),+ ).not.toBeInTheDocument();+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(9);+ });++ it("should hide search results based on provided models", async () => {+ await setup({+ models: ["table", "card"],+ });++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectVisibleItem("Search Result Card 3");+ await expectVisibleItem("Search Result Card 4");+ await expectVisibleItem("Search Result Table 9");+ await expectVisibleItem("Search Result Table 10");+ expect(screen.queryByText(/Search Result Dash/)).not.toBeInTheDocument();+ expect(+ screen.queryByText(/Search Result Metric/),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(/Search Result Collection/),+ ).not.toBeInTheDocument();+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(4);+ });++ describe("Search Scope", () => {+ it("should default to searching the current collection", async () => {+ await setup();+ await userEvent.click(await screen.findByText("Our analytics"));+ await userEvent.click(await screen.findByText("First Collection"));++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectActiveItem('Search results for "My"');+ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "First Collection" },+ ),+ ).toBeChecked();+ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "Everywhere" },+ ),+ ).not.toBeChecked();+ });++ it("does not narrow search scope in non-numeric collections", async () => {+ await setup();+ await userEvent.click(await screen.findByText("Our analytics"));++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectActiveItem('Search results for "My"');+ expect(+ within(+ await screen.findByTestId("search-scope-selector"),+ ).queryByText("Our analytics"),+ ).not.toBeInTheDocument();++ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "Everywhere" },+ ),+ ).toBeChecked();+ });++ it("can search only databases", async () => {+ await setup({ options: { hasDatabases: true } });+ await userEvent.click(await screen.findByText("Databases"));++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectActiveItem('Search results for "My"');+ expect(+ within(+ await screen.findByTestId("search-scope-selector"),+ ).queryByText("Our analytics"),+ ).not.toBeInTheDocument();++ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "Databases" },+ ),+ ).toBeChecked();+ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "Everywhere" },+ ),+ ).not.toBeChecked();+ });++ it("can switch search scopes", async () => {+ await setup();+ await userEvent.click(await screen.findByText("Our analytics"));+ await userEvent.click(await screen.findByText("First Collection"));++ await userEvent.type(+ await screen.findByPlaceholderText("Search…"),+ "My",+ { delay: 50 },+ );+ await waitForSearchResults();+ await expectActiveItem('Search results for "My"');+ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "First Collection" },+ ),+ ).toBeChecked();+ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "Everywhere" },+ ),+ ).not.toBeChecked();++ const gets = await findRequests("GET");+ const lastGet = gets.slice(-1)[0];+ expect(lastGet.url).toContain("collection=11");++ await userEvent.click(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "Everywhere" },+ ),+ );++ expect(+ within(await screen.findByTestId("search-scope-selector")).getByRole(+ "radio",+ { name: "Everywhere" },+ ),+ ).toBeChecked();++ const getsAfter = await findRequests("GET");+ const lastGetAfter = getsAfter.slice(-1)[0];+ expect(lastGetAfter.url).not.toContain("collection=11");+ });+ });+ });++ describe("Recents", () => {+ it("should show a recents menu item", async () => {+ await setup();+ await expectActiveItem("Recent items");+ });++ it("should hide recents based on option", async () => {+ await setup({ options: { hasRecents: false, hasDatabases: false } });+ await expectVisibleItem("Our analytics");+ expect(screen.queryByText("Recent items")).not.toBeInTheDocument();+ });++ it("should show recent items in recents", async () => {+ await setup();+ await userEvent.click(await screen.findByText("Recent items"));+ await expectVisibleItem("Recent Question 1");+ await expectVisibleItem("Recent Question 2");+ await expectVisibleItem("Recent Table");+ await expectVisibleItem("Recent Dashboard");+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(5);+ });++ it("should filter out irrelevant models", async () => {+ await setup({+ models: ["table", "card"],+ });++ expect(await screen.findByText("Recent Question 1")).toBeInTheDocument();+ expect(await screen.findByText("Recent Question 2")).toBeInTheDocument();+ expect(await screen.findByText("Recent Table")).toBeInTheDocument();+ expect(screen.queryByText("Recent Dashboard")).not.toBeInTheDocument();+ });++ it("should hide recents based on isHiddenItem", async () => {+ await setup({+ models: ["table", "card"],+ isHiddenItem: (item) => item.name.includes("2"),+ });++ await userEvent.click(await screen.findByText("Recent items"));+ await expectVisibleItem("Recent Question 1");+ await expectVisibleItem("Recent Table");+ expect(screen.queryByText("Recent Question 2")).not.toBeInTheDocument();+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(2);+ });++ it("should hide recents based on isDisabledItem", async () => {+ await setup({+ models: ["table", "card"],+ isDisabledItem: (item) => item.name.includes("2"),+ });++ await userEvent.click(await screen.findByText("Recent items"));+ await expectVisibleItem("Recent Question 1");+ await expectVisibleItem("Recent Table");+ expect(screen.queryByText("Recent Question 2")).not.toBeInTheDocument();+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(2);+ });++ it("should hide recents based on isSelectableItem", async () => {+ await setup({+ models: ["table", "card"],+ isSelectableItem: (item) => !item.name.includes("2"),+ });++ await userEvent.click(await screen.findByText("Recent items"));+ await expectVisibleItem("Recent Question 1");+ await expectVisibleItem("Recent Table");+ expect(screen.queryByText("Recent Question 2")).not.toBeInTheDocument();+ const searchList = await screen.findByTestId("item-picker-level-1");+ expect(within(searchList).getAllByRole("link")).toHaveLength(2);+ });+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/NewCollectionDialog.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/NewCollectionDialog.unit.spec.tsxnew file mode 100644index 00000000000..706c73dd067--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/NewCollectionDialog.unit.spec.tsx@@ -0,0 +1,127 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { screen, waitFor } from "__support__/ui";+import { createMockCollection } from "metabase-types/api/mocks";++import type { EntityPickerModalProps } from "../EntityPickerModal";++import { setup as baseSetup } from "./setup";++type SetupOpts = Partial<EntityPickerModalProps> & {+ click?: boolean;+};++async function setup({ click = true, ...props }: SetupOpts = {}) {+ await baseSetup({+ models: ["dashboard", "collection"],+ value: { id: 33, model: "collection" },+ ...props,+ options: {+ canCreateCollections: true,+ ...props.options,+ },+ });++ fetchMock.post("path:/api/collection", () => {+ return createMockCollection();+ });++ if (click) {+ const button = await screen.findByRole("button", {+ name: /new collection/i,+ });+ await waitFor(() => expect(button).toBeEnabled());+ await userEvent.click(button);+ }+}++describe("NewCollectionDialog", () => {+ it("should render", async () => {+ await setup();+ expect(+ await screen.findByText("Create a new collection"),+ ).toBeInTheDocument();+ });++ it("should not render the New collection button if canCreateCollections is false", async () => {+ await setup({ click: false, options: { canCreateCollections: false } });+ //wait for the initial render+ expect(await screen.findByText("Our analytics")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /new collection/i }),+ ).not.toBeInTheDocument();+ });++ it("should disable the New collection button if the user is in recents", async () => {+ await setup({+ click: false,+ value: { id: "recents", model: "collection" },+ });+ expect(+ await screen.findByRole("button", { name: /new collection/i }),+ ).toBeDisabled();+ });++ it("should disable the New collection button if the user is in search", async () => {+ await setup({+ click: false,+ });+ await userEvent.type(await screen.findByPlaceholderText("Search…"), "My", {+ delay: 50,+ });+ const button = await screen.findByRole("button", {+ name: /new collection/i,+ });+ await waitFor(() => expect(button).toBeDisabled());+ });++ it("should disable the New collection button if the user does not have write permissions to the collection", async () => {+ await setup({+ click: false,+ value: { id: 22, model: "collection" },+ });+ const button = await screen.findByRole("button", {+ name: /new collection/i,+ });+ await waitFor(() => expect(button).toBeDisabled());+ });++ it("should create a new collection", async () => {+ await setup();+ const button = await screen.findByRole("button", { name: "Create" });+ expect(button).toBeDisabled(); //can't create a collection without a name+ await userEvent.type(+ await screen.findByPlaceholderText("My new collection"),+ "My New Collection",+ );+ expect(button).toBeEnabled();+ await userEvent.click(button);++ const apiCalls = fetchMock.callHistory.calls("path:/api/collection");+ expect(apiCalls).toHaveLength(1);+ const call = apiCalls[0];+ const body = JSON.parse(call.options?.body as string);+ expect(body.name).toBe("My New Collection");+ expect(body.parent_id).toBe(33);+ });++ it("should handle a parent collection id of root", async () => {+ await setup({ value: { id: "root", model: "collection" } });+ const button = await screen.findByRole("button", { name: "Create" });+ expect(button).toBeDisabled(); //can't create a collection without a name+ await userEvent.type(+ await screen.findByPlaceholderText("My new collection"),+ "My New Collection",+ );+ expect(button).toBeEnabled();+ await userEvent.click(button);++ const apiCalls = fetchMock.callHistory.calls("path:/api/collection");+ expect(apiCalls).toHaveLength(1);+ const call = apiCalls[0];+ const body = JSON.parse(call.options?.body as string);+ expect(body.name).toBe("My New Collection");+ expect(body.parent_id).toBe(null);+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/NewDashboardDialog.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/NewDashboardDialog.unit.spec.tsxnew file mode 100644index 00000000000..545a0e6e747--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/NewDashboardDialog.unit.spec.tsx@@ -0,0 +1,125 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupDashboardCreateEndpoint } from "__support__/server-mocks";+import { screen, waitFor } from "__support__/ui";++import type { EntityPickerModalProps } from "../EntityPickerModal";++import { setup as baseSetup } from "./setup";++type SetupOpts = Partial<EntityPickerModalProps> & {+ click?: boolean;+};++async function setup({ click = true, ...props }: SetupOpts = {}) {+ await baseSetup({+ models: ["dashboard", "collection"],+ value: { id: 33, model: "collection" },+ ...props,+ options: {+ canCreateDashboards: true,+ ...props.options,+ },+ });++ setupDashboardCreateEndpoint({});++ if (click) {+ const button = await screen.findByRole("button", {+ name: /new dashboard/i,+ });+ await waitFor(() => expect(button).toBeEnabled());+ await userEvent.click(button);+ }+}++describe("NewDashboardDialog", () => {+ it("should render", async () => {+ await setup();+ expect(+ await screen.findByText("Create a new dashboard"),+ ).toBeInTheDocument();+ });++ it("should not render the New dashboard button if canCreateDashboards is false", async () => {+ await setup({ click: false, options: { canCreateDashboards: false } });+ //wait for the initial render+ expect(await screen.findByText("Our analytics")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /new dashboard/i }),+ ).not.toBeInTheDocument();+ });++ it("should disable the New dashboard button if the user is in recents", async () => {+ await setup({+ click: false,+ value: { id: "recents", model: "collection" },+ });+ expect(+ await screen.findByRole("button", { name: /new dashboard/i }),+ ).toBeDisabled();+ });++ it("should disable the New dashboard button if the user is in search", async () => {+ await setup({+ click: false,+ });+ await userEvent.type(await screen.findByPlaceholderText("Search…"), "My", {+ delay: 50,+ });+ const button = await screen.findByRole("button", {+ name: /new dashboard/i,+ });+ await waitFor(() => expect(button).toBeDisabled());+ });++ it("should disable the New dashboard button if the user does not have write permissions to the collection", async () => {+ await setup({+ click: false,+ value: { id: 22, model: "collection" },+ });+ const button = await screen.findByRole("button", {+ name: /new dashboard/i,+ });+ await waitFor(() => expect(button).toBeDisabled());+ });++ it("should create a new dashboard", async () => {+ await setup();+ const button = await screen.findByRole("button", { name: "Create" });+ expect(button).toBeDisabled(); //can't create a dashboard without a name+ await userEvent.type(+ await screen.findByPlaceholderText("My new dashboard"),+ "My New Dashboard",+ );+ expect(button).toBeEnabled();+ await userEvent.click(button);++ const apiCalls = fetchMock.callHistory.calls("path:/api/dashboard");+ expect(apiCalls).toHaveLength(1);+ const call = apiCalls[0];+ const body = JSON.parse(call.options?.body as string);+ expect(body.name).toBe("My New Dashboard");+ expect(body.collection_id).toBe(33);+ });++ it("should handle a parent collection id of root", async () => {+ await setup({ value: { id: "root", model: "collection" } });+ const button = await screen.findByRole("button", { name: "Create" });+ expect(button).toBeDisabled(); //can't create a dashboard without a name+ await userEvent.type(+ await screen.findByPlaceholderText("My new dashboard"),+ "My New Dashboard",+ );+ expect(button).toBeEnabled();+ await userEvent.click(button);++ const apiCalls = fetchMock.callHistory.calls("path:/api/dashboard");+ expect(apiCalls).toHaveLength(1);+ const call = apiCalls[0];+ const body = JSON.parse(call.options?.body as string);+ expect(body.name).toBe("My New Dashboard");+ expect(body.collection_id).toBe(null);+ });+});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.tsxnew file mode 100644index 00000000000..1d805cb4f4e--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/test/setup.tsx@@ -0,0 +1,391 @@+import fetchMock from "fetch-mock";++import {+ setupCollectionByIdEndpoint,+ setupCollectionItemsEndpoint,+ setupCollectionsEndpoints,+ setupDatabasesEndpoints,+ setupRecentViewsAndSelectionsEndpoints,+ setupRootCollectionItemsEndpoint,+} from "__support__/server-mocks";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ waitForLoaderToBeRemoved,+} from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/entities/collections";+import type { Database, RecentItem, SearchResult } from "metabase-types/api";+import {+ createMockCollection,+ createMockCollectionItem,+ createMockDatabase,+ createMockRecentCollectionItem,+ createMockRecentTableItem,+ createMockSearchResult,+ createMockSearchResults,+ createMockTable,+} from "metabase-types/api/mocks";++import {+ EntityPickerModal,+ type EntityPickerModalProps,+} from "../EntityPickerModal";++const mockSearchResults = createMockSearchResults({+ items: [+ createMockSearchResult({+ name: "Search Result Collection 0",+ model: "collection",+ can_write: true,+ id: 600,+ }),+ createMockSearchResult({+ name: "Search Result Collection 1",+ model: "collection",+ can_write: true,+ id: 601,+ }),+ createMockSearchResult({+ name: "Search Result Collection 2",+ model: "collection",+ can_write: true,+ id: 602,+ }),+ createMockSearchResult({+ name: "Search Result Card 3",+ database_id: 1,+ model: "card",+ id: 603,+ }),+ createMockSearchResult({+ name: "Search Result Card 4",+ database_id: 2,+ model: "card",+ id: 604,+ }),+ createMockSearchResult({+ name: "Search Result Dashboard 5",+ model: "dashboard",+ id: 605,+ }),+ createMockSearchResult({+ name: "Search Result Dashboard 6",+ model: "dashboard",+ id: 606,+ }),+ createMockSearchResult({+ name: "Search Result Metric 7",+ model: "metric",+ id: 607,+ }),+ createMockSearchResult({+ name: "Search Result Metric 8",+ model: "metric",+ id: 608,+ }),+ createMockSearchResult({+ name: "Search Result Table 9",+ model: "table",+ id: 609,+ }),+ createMockSearchResult({+ name: "Search Result Table 10",+ model: "table",+ database_id: 2,+ id: 610,+ }),+ ],+});+const mockRecentItems = [+ createMockRecentCollectionItem({+ id: 100,+ model: "card",+ name: "Recent Question 1",+ description: "A card",+ timestamp: "2025-11-01T00:00:00",+ }),+ createMockRecentCollectionItem({+ id: 200,+ model: "card",+ name: "Recent Question 2",+ description: "sometimes invisible",+ timestamp: "2025-11-01T00:00:00",+ }),+ createMockRecentCollectionItem({+ id: 101,+ model: "dashboard",+ name: "Recent Dashboard",+ description: "A board",+ timestamp: "2025-11-01T00:00:00",+ }),+ createMockRecentTableItem({+ id: 102,+ model: "table",+ name: "Recent_Table",+ display_name: "Recent Table",+ description: "A tableau",+ timestamp: "2025-11-01T00:00:00",+ }),+ createMockRecentCollectionItem({+ id: 300,+ model: "collection",+ name: "Recent_Collection",+ timestamp: "2025-11-01T00:00:00",+ }),+];++// Collection tree structure+const rootCollection = createMockCollection(ROOT_COLLECTION);++const collection1 = createMockCollection({+ id: 11,+ name: "First Collection",+ here: ["card", "metric"],+ below: ["card", "metric"],+ location: "/",+});++const collection2 = createMockCollection({+ id: 22,+ name: "Second Collection",+ here: ["card", "metric"],+ below: ["card", "metric"],+ location: "/",+ can_write: false,+});++const nestedCollection = createMockCollection({+ id: 33,+ name: "Nested Collection",+ location: "/11/",+ here: ["card", "metric"],+ below: ["card", "metric"],+});++// Collection items+const rootCollectionItems = [+ createMockCollectionItem({+ id: 11,+ model: "collection",+ name: collection1.name,+ here: ["collection"],+ below: ["collection", "card"],+ collection_id: null,+ can_write: true,+ }),+ createMockCollectionItem({+ id: 22,+ model: "collection",+ name: collection2.name,+ here: ["collection"],+ below: ["collection", "card"],+ collection_id: null,+ can_write: false,+ }),+];++const collection1Items = [+ createMockCollectionItem({+ id: 100,+ model: "card",+ name: "Question in Collection 1",+ collection_id: 1,+ }),+ createMockCollectionItem({+ id: 101,+ model: "dashboard",+ name: "Dashboard in Collection 1",+ collection_id: 1,+ }),+ createMockCollectionItem({+ id: 33,+ model: "collection",+ name: nestedCollection.name,+ collection_id: 1,+ here: ["collection"],+ below: ["collection", "card"],+ location: "/1/",+ can_write: true,+ }),+];++const collection2Items = [+ createMockCollectionItem({+ id: 200,+ model: "card",+ name: "Question in Collection 2",+ collection_id: 2,+ }),+ createMockCollectionItem({+ id: 201,+ model: "dataset",+ name: "Model in Collection 2",+ collection_id: 2,+ }),+];++const nestedCollectionItems = [+ createMockCollectionItem({+ id: 300,+ model: "card",+ name: "Question in Nested Coll",+ collection_id: 33,+ }),+ createMockCollectionItem({+ id: 301,+ model: "metric",+ name: "Metric in Nested Coll",+ collection_id: 33,+ }),+];++const mockDatabases = [+ createMockDatabase({+ id: 1,+ name: "Database 1",+ tables: [+ createMockTable({+ id: 10,+ db_id: 1,+ display_name: "Table 10",+ schema: "schema one",+ }),+ createMockTable({+ id: 11,+ db_id: 1,+ display_name: "Table 11",+ schema: "schema one",+ }),+ createMockTable({+ id: 12,+ db_id: 1,+ display_name: "Table 12",+ schema: "schema two",+ }),+ ],+ }),+ createMockDatabase({+ id: 2,+ name: "Database 2",+ tables: [+ createMockTable({+ id: 20,+ db_id: 2,+ display_name: "Table 20",+ schema: "schema three",+ }),+ createMockTable({+ id: 21,+ db_id: 2,+ display_name: "Table 21",+ schema: "schema three",+ }),+ createMockTable({+ id: 22,+ db_id: 2,+ display_name: "Table 22",+ schema: "schema three",+ }),+ ],+ }),+ createMockDatabase({+ id: 3,+ name: "Database 3",+ tables: [+ createMockTable({+ id: 30,+ db_id: 3,+ display_name: "Table 30",+ schema: "schema four",+ }),+ createMockTable({+ id: 31,+ db_id: 3,+ display_name: "Table 31",+ schema: "schema four",+ }),+ createMockTable({+ id: 32,+ db_id: 3,+ display_name: "Table 32",+ schema: "schema five",+ }),+ ],+ }),+];++export type SetupOpts = Partial<EntityPickerModalProps> & {+ recentItems?: RecentItem[];+ searchResults?: SearchResult[];+ databases?: Database[];+};++export const setup = async ({ databases, ...rest }: SetupOpts = {}) => {+ process.env.OVERSCAN = "20"; // for VirtualizedList overscan+ mockGetBoundingClientRect();+ setupRecentViewsAndSelectionsEndpoints(mockRecentItems, [+ "views",+ "selections",+ ]);++ setupDatabasesEndpoints(databases ?? mockDatabases);++ // Setup collections+ setupCollectionsEndpoints({+ collections: [collection1, collection2, nestedCollection],+ rootCollection,+ });++ // Setup collection by ID endpoints+ setupCollectionByIdEndpoint({+ collections: [collection1, collection2, nestedCollection],+ });++ // Setup collection items endpoints for the tree structure+ setupRootCollectionItemsEndpoint({+ rootCollectionItems,+ });++ setupCollectionItemsEndpoint({+ collection: collection1,+ collectionItems: collection1Items,+ });++ setupCollectionItemsEndpoint({+ collection: collection2,+ collectionItems: collection2Items,+ });++ setupCollectionItemsEndpoint({+ collection: nestedCollection,+ collectionItems: nestedCollectionItems,+ });++ fetchMock.get("path:/api/search", mockSearchResults);+ fetchMock.get("path:/api/user/recipients", { data: [] });+ const onChange = jest.fn();+ const onClose = jest.fn();++ renderWithProviders(+ <EntityPickerModal+ title={"Pick a thing"}+ onClose={onClose}+ onChange={onChange}+ models={[+ "table",+ "collection",+ "transform",+ "dashboard",+ "snippet",+ "card",+ "dataset",+ "metric",+ ]}+ {...rest}+ />,+ );++ await waitForLoaderToBeRemoved();++ return { onChange, onClose };+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/components/utils.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/utils.tsnew file mode 100644index 00000000000..dad4bea2651--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/components/utils.ts@@ -0,0 +1,2 @@+export const generateKey = <Query>(query?: Query) =>+ JSON.stringify(query ?? "root");diff --git a/frontend/src/metabase/common/components/EntityPicker/constants.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/constants.tssimilarity index 100%rename from frontend/src/metabase/common/components/EntityPicker/constants.tsrename to frontend/src/metabase/common/components/Pickers/EntityPicker/constants.tsdiff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/context.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/context.tsxnew file mode 100644index 00000000000..5092edc8bab--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/context.tsx@@ -0,0 +1,87 @@+import { createContext, useContext, useMemo, useState } from "react";++import { useGetPathFromValue } from "./hooks/use-get-path-from-value";+import type {+ EntityPickerProps,+ OmniPickerContextValue,+ OmniPickerItem,+ SearchScope,+} from "./types";+import {+ getItemFunctions,+ getNamespacesFromModels,+ getValidCollectionItemModels,+} from "./utils";++export const OmniPickerContext = createContext<+ OmniPickerContextValue | undefined+>(undefined);++export const EntityPickerProvider = ({+ children,+ value,+}: {+ children: React.ReactNode;+ value: EntityPickerProps;+}) => {+ const namespaces = useMemo(+ () => value.namespaces ?? getNamespacesFromModels(value.models),+ [value.namespaces, value.models],+ );++ const [path, setPath, { isLoadingPath }] = useGetPathFromValue({+ value: value.value,+ options: value.options,+ namespaces,+ models: getValidCollectionItemModels(value.models),+ });++ const [previousPath, setPreviousPath] = useState<OmniPickerItem[]>([]);+ const [searchScope, setSearchScope] = useState<SearchScope>(null);++ const { isFolderItem, isHiddenItem, isDisabledItem, isSelectableItem } =+ useMemo(+ () =>+ getItemFunctions({+ models: value.models,+ isFolderItem: value.isFolderItem,+ isHiddenItem: value.isHiddenItem,+ isDisabledItem: value.isDisabledItem,+ isSelectableItem: value.isSelectableItem,+ }),+ [value],+ );++ return (+ <OmniPickerContext.Provider+ value={{+ ...value,+ namespaces,+ path,+ isLoadingPath,+ setPath,+ previousPath,+ setPreviousPath,+ searchScope,+ setSearchScope,+ isFolderItem,+ isHiddenItem,+ isDisabledItem,+ isSelectableItem,+ }}+ >+ {children}+ </OmniPickerContext.Provider>+ );+};++export const useOmniPickerContext = () => {+ const context = useContext(OmniPickerContext);++ if (!context) {+ throw new Error(+ "useOmniPickerContext must be used within a OmniPickerProvider",+ );+ }+ return context;+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/index.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/index.tsnew file mode 100644index 00000000000..0c6691c14ed--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/index.ts@@ -0,0 +1 @@+export * from "./use-log-recent-item";diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-current-search-scope.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-current-search-scope.tsnew file mode 100644index 00000000000..92d2e6cc365--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-current-search-scope.ts@@ -0,0 +1,82 @@+import { useMemo } from "react";++import { PLUGIN_DATA_STUDIO } from "metabase/plugins/oss/data-studio";++import { useOmniPickerContext } from "../context";+import type { OmniPickerCollectionItem, SearchScope } from "../types";++type CollectionWithNumericId = OmniPickerCollectionItem & { id: number };++export const useGetLastCollection = ():+ | (CollectionWithNumericId & { id: number })+ | null => {+ const { previousPath } = useOmniPickerContext();++ const { data: libraryCollection } =+ PLUGIN_DATA_STUDIO.useGetLibraryCollection();++ const lastCollection = useMemo(() => {+ const lastCollectionIndex = previousPath.findLastIndex(+ (item) => item.model === "collection",+ );+ return lastCollectionIndex !== -1+ ? (previousPath[lastCollectionIndex] as OmniPickerCollectionItem)+ : null;+ }, [previousPath]);++ return isValidScope(lastCollection, libraryCollection)+ ? lastCollection+ : null;+};++/**+ * gets the narrowed search scope for the currently selected collection, if it is selectable */+export const useCurrentSearchScope = (): SearchScope => {+ const { searchScope } = useOmniPickerContext();+ const { data: libraryCollection } =+ PLUGIN_DATA_STUDIO.useGetLibraryCollection();++ const lastCollection = useGetLastCollection();++ if (searchScope || !lastCollection) {+ return searchScope;+ }++ if (lastCollection) {+ return lastCollection.id;+ }++ if (libraryCollection) {+ return libraryCollection.id;+ }++ return "all";+};++const isValidScope = (+ lastCollection: OmniPickerCollectionItem | null,+ libraryCollection?: OmniPickerCollectionItem,+): lastCollection is OmniPickerCollectionItem & { id: number } => {+ if (!lastCollection) {+ return false;+ }+ if (libraryCollection && lastCollection.id === libraryCollection.id) {+ // don't show library twice+ return false;+ }++ if (typeof lastCollection.id === "number") {+ return true;+ }++ if (lastCollection.id === "root" || lastCollection.id === null) {+ // scoped search doesn't work for our analytics+ return false;+ }++ if (lastCollection.id === "databases") {+ return true;+ }++ return false;+};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.tsnew file mode 100644index 00000000000..f7f71c603c4--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts@@ -0,0 +1,557 @@+import { useState } from "react";+import { useDeepCompareEffect } from "react-use";+import { t } from "ttag";++import {+ cardApi,+ collectionApi,+ dashboardApi,+ databaseApi,+ documentApi,+ snippetApi,+ tableApi,+} from "metabase/api";+import { useGetPersonalCollection } from "metabase/common/hooks/use-get-personal-collection";+import { type DispatchFn, useDispatch } from "metabase/lib/redux";+import { PLUGIN_DATA_STUDIO, PLUGIN_TRANSFORMS } from "metabase/plugins";+import type {+ Collection,+ CollectionNamespace,+ LibraryCollection,+ SchemaName,+} from "metabase-types/api";++import type {+ EntityPickerOptions,+ OmniPickerCollectionItem,+ OmniPickerCollectionItemValue,+ OmniPickerDbValue,+ OmniPickerItem,+ OmniPickerTableValue,+ OmniPickerValue,+} from "../types";+import { getCollectionItemsOptions, validCollectionModels } from "../utils";++import { getRootCollectionItem, personalCollectionsRoot } from "./utils";+const allCollectionModels = Array.from(validCollectionModels);++const getDefaultPath = async ({+ options,+ libraryCollection,+ namespaces,+ dispatch,+}: {+ options: EntityPickerOptions;+ libraryCollection?: LibraryCollection;+ namespaces: CollectionNamespace[];+ dispatch: DispatchFn;+}): Promise<OmniPickerItem[]> => {+ if (libraryCollection && options.hasLibrary) {+ const libraryChildrenResponse = await dispatch(+ collectionApi.endpoints.listCollectionItems.initiate({+ id: libraryCollection.id,+ }),+ ).unwrap();++ if (libraryChildrenResponse) {+ const firstChildCollection = libraryChildrenResponse.data.find(+ (item) => item.model === "collection",+ );+ // we might also want to check if this collection has any relevant models+ if (firstChildCollection) {+ return [libraryCollection, firstChildCollection];+ }+ }+ }+ if (options.hasDatabases) {+ const databases = await dispatch(+ databaseApi.endpoints.listDatabases.initiate(),+ ).unwrap();+ if (databases.data.length > 0) {+ return [getFakeDbCollection()];+ }+ }+ if (options.hasRecents) {+ return [getFakeRecentsCollection()];+ }+ if (options.hasRootCollection) {+ const namespace = namespaces[0];+ return [await getRootCollectionItem({ namespace, dispatch })];+ }+ return [];+};++export function useGetPathFromValue({+ value,+ options,+ namespaces,+ models,+}: {+ value?: OmniPickerValue;+ options: EntityPickerOptions;+ namespaces: CollectionNamespace[];+ models: OmniPickerCollectionItem["model"][];+}) {+ const [path, setPath] = useState<OmniPickerItem[]>([]);+ const [isLoadingPath, setIsLoadingPath] = useState(false);++ const dispatch = useDispatch();++ const { data: libraryCollection, isLoading: isLoadingLibraryCollection } =+ PLUGIN_DATA_STUDIO.useGetLibraryCollection();++ const { data: personalCollection, isLoading: isLoadingPersonalCollection } =+ useGetPersonalCollection();++ useDeepCompareEffect(() => {+ if (isLoadingLibraryCollection || isLoadingPersonalCollection) {+ return;+ }++ setIsLoadingPath(true);++ if (!value) {+ getDefaultPath({ options, libraryCollection, namespaces, dispatch }).then(+ (path) => {+ setPath(path);+ setIsLoadingPath(false);+ },+ );+ return;+ }++ getPathFromValue({+ value,+ dispatch,+ libraryCollection,+ personalCollection,+ models,+ }).then((newPath) => {+ setPath(newPath);+ setIsLoadingPath(false);+ });+ }, [+ value,+ dispatch,+ libraryCollection,+ isLoadingLibraryCollection,+ isLoadingPersonalCollection,+ ]);++ return [path, setPath, { isLoadingPath }] as const;+}++const isInDbPath = (item: OmniPickerValue): item is OmniPickerDbValue =>+ ["database", "schema", "table"].includes(item.model);++const isTableItem = (item: OmniPickerValue): item is OmniPickerTableValue =>+ item.model === "table" && !!item.id;++async function getPathFromValue({+ value,+ dispatch,+ libraryCollection,+ personalCollection,+ models,+}: {+ value: OmniPickerValue;+ dispatch: DispatchFn;+ libraryCollection?: LibraryCollection;+ personalCollection?: Collection;+ models: OmniPickerCollectionItem["model"][];+}): Promise<OmniPickerItem[]> {+ if (value.id === "databases") {+ return [getFakeDbCollection()];+ }++ if (value.id === "recents") {+ return [getFakeRecentsCollection()];+ }++ if (!isInDbPath(value)) {+ return getCollectionPathFromValue({+ value,+ dispatch,+ libraryCollection,+ personalCollection,+ models,+ });+ }++ if (!isTableItem(value)) {+ return getDbPathFromValue(value, dispatch);+ }++ // check if the table is in a collection+ const table = await dispatch(+ tableApi.endpoints.getTable.initiate({ id: value.id }),+ ).unwrap();++ return table.collection == null+ ? getDbPathFromValue(value, dispatch)+ : getCollectionPathFromValue({+ value,+ dispatch,+ libraryCollection,+ personalCollection,+ models,+ });+}++const getFakeDbCollection = (): OmniPickerItem => ({+ name: t`Databases`,+ id: "databases",+ model: "collection",+ here: ["table"],+ below: ["table"],+});++const getFakeRecentsCollection = (): OmniPickerItem => ({+ name: t`Recent items`,+ id: "recents",+ model: "collection",+ here: allCollectionModels,+ below: allCollectionModels,+});++// note: doesn't handle parsing a path from a schema only value since schemas don't have unique ids+async function getDbPathFromValue(+ value: OmniPickerValue,+ dispatch: DispatchFn,+): Promise<OmniPickerItem[]> {+ if (value.model === "database") {+ const dbReq = await dispatch(+ databaseApi.endpoints.listDatabases.initiate(),+ ).unwrap();+ const db = dbReq.data.find((db) => db.id === value.id);++ if (!db) {+ return [getFakeDbCollection()];+ }+ // by default, select the first schema+ const schemas = await dispatch(+ databaseApi.endpoints.listDatabaseSchemas.initiate({ id: db.id }),+ ).unwrap();++ const schema: SchemaName | undefined =+ schemas?.length > 1 ? schemas[0] : undefined;++ return db+ ? [+ getFakeDbCollection(),+ { id: db.id, name: db.name, model: "database" as const },+ // if there's only one schema, omit it+ ...(schema+ ? [+ {+ id: schema,+ name: schema,+ model: "schema" as const,+ database_id: db.id,+ },+ ]+ : []),+ ]+ : [getFakeDbCollection()];+ }++ if (!isTableItem(value)) {+ return [getFakeDbCollection()];+ }++ const table = await dispatch(+ tableApi.endpoints.getTable.initiate({ id: value.id }),+ ).unwrap();++ if (!table) {+ return [getFakeDbCollection()];+ }++ // need to get the list because we hide schemas if there's only one+ const schemas = await dispatch(+ databaseApi.endpoints.listDatabaseSchemas.initiate({ id: table.db_id }),+ ).unwrap();++ const schema: SchemaName | undefined =+ schemas?.length > 1+ ? schemas.find((sch) => sch === table.schema)+ : undefined;++ const schemaPathItem = schema+ ? [+ {+ id: schema,+ name: schema,+ model: "schema" as const,+ database_id: table.db_id,+ },+ ]+ : [];++ return [+ getFakeDbCollection(),+ { id: table.db_id, name: table.db?.name ?? t`Database`, model: "database" },+ ...schemaPathItem,+ { id: table.id, name: table.display_name, model: "table" },+ ];+}++const isCollection = (+ item: Collection | unknown,+ value: OmniPickerCollectionItemValue,+): item is Collection => {+ return (+ value.model === "collection" &&+ typeof item === "object" &&+ item !== null &&+ "id" in item &&+ // the payload for the root collection is totally different+ ("location" in item || item.id === "root")+ );+};++const getNamespace = (+ item: Awaited<ReturnType<typeof getItemByModel>>,+): CollectionNamespace | undefined => {+ if (!item || typeof item !== "object") {+ return undefined;+ }++ if ("namespace" in item) {+ return item.namespace as CollectionNamespace;+ }+ if (+ "collection" in item &&+ typeof item.collection === "object" &&+ !!item.collection &&+ "namespace" in item.collection+ ) {+ return item.collection?.namespace as CollectionNamespace;+ }++ if ("collection_namespace" in item) {+ return item.collection_namespace as CollectionNamespace;+ }+ return undefined;+};++async function getCollectionPathFromValue({+ value,+ dispatch,+ libraryCollection,+ personalCollection,+ models,+}: {+ value: OmniPickerCollectionItemValue;+ dispatch: DispatchFn;+ libraryCollection?: LibraryCollection;+ personalCollection?: Collection;+ models: OmniPickerCollectionItem["model"][];+}): Promise<OmniPickerItem[]> {+ if (value.id === null || value.id === "root") {+ // if a root was passed, just return the root collection item+ const rootCollectionItem = await getRootCollectionItem({+ namespace: value.namespace ?? null,+ dispatch,+ });+ return [rootCollectionItem];+ }++ const item = await getItemByModel(value, dispatch).catch(console.error);+ if (!item) {+ return [];+ }++ const isCollectionValue = isCollection(item, value);+ const parentCollectionId = isCollectionValue ? item.id : item?.collection_id;++ const itemNamespace = value.namespace ?? getNamespace(item);++ const rootCollectionItem = await getRootCollectionItem({+ namespace: itemNamespace ?? null,+ dispatch,+ });++ const collection = isCollectionValue+ ? item+ : await dispatch(+ collectionApi.endpoints.getCollection.initiate({+ id: parentCollectionId ?? "root",+ }),+ ).unwrap();++ const location = collection?.effective_location ?? collection?.location;++ const locationPath = [rootCollectionItem];++ if (!location) {+ if (item && !isCollectionValue) {+ locationPath.push({+ id: item.id,+ name: item.name,+ model: value.model,+ });+ }+ return locationPath;+ }++ const collectionIds = [+ "root",+ ...(location?.split("/") ?? []).map((id) => Number(id)),+ collection?.id,+ ].filter(Boolean);++ const isInLibrary =+ libraryCollection?.id && collectionIds.includes(libraryCollection.id);++ const isInPersonalCollection =+ personalCollection?.id && collectionIds.includes(personalCollection.id);++ const isInOtherUserPersonalCollection =+ collection.is_personal && !isInPersonalCollection;++ // pretend special collections are at the top level+ if (+ isInPersonalCollection ||+ isInOtherUserPersonalCollection ||+ isInLibrary+ ) {+ collectionIds.shift();+ locationPath.shift();++ if (isInLibrary && libraryCollection) {+ locationPath.push({+ id: libraryCollection.id,+ name: libraryCollection.name,+ model: "collection",+ below: allCollectionModels,+ });+ } else if (isInPersonalCollection && personalCollection) {+ locationPath.push({+ id: personalCollection.id,+ name: personalCollection.name,+ model: "collection",+ below: allCollectionModels,+ can_write: true,+ });+ } else if (isInOtherUserPersonalCollection) {+ // need to fetch all personal collections to find the right one+ locationPath.push(personalCollectionsRoot);+ const personalCollections = await dispatch(+ collectionApi.endpoints.listCollections.initiate({+ "personal-only": true,+ }),+ ).unwrap();++ const basePersonalCollectionId = collectionIds[0];+ const otherUserPersonalCollection = personalCollections.find(+ (col: Collection) => col.id === basePersonalCollectionId,+ );+ if (otherUserPersonalCollection) {+ locationPath.push({+ id: otherUserPersonalCollection.id,+ name: otherUserPersonalCollection.name,+ can_write: otherUserPersonalCollection.can_write,+ model: "collection",+ here: allCollectionModels,+ below: allCollectionModels,+ });+ }+ }+ }++ for (let i = 0; i < collectionIds.length; i++) {+ // for loop to get sequential requests+ const collectionId = collectionIds[i];++ if (!collectionId) {+ break;+ }++ // use items endpoint to warm the cache+ const collectionItems = await dispatch(+ collectionApi.endpoints.listCollectionItems.initiate({+ id: collectionId,+ namespace: itemNamespace ?? undefined,+ ...getCollectionItemsOptions({ models }),+ }),+ )+ .unwrap()+ .catch(console.error);++ if (!collectionItems?.data) {+ break;+ }++ const nextItem = collectionItems.data.find(+ (item) => item.model === "collection" && item.id === collectionIds[i + 1],+ );++ if (!nextItem) {+ break;+ }++ locationPath.push({+ id: nextItem.id,+ name: nextItem.name,+ model: "collection",+ namespace: nextItem.namespace,+ can_write: nextItem.can_write,+ here: nextItem.here,+ below: nextItem.below,+ });+ }++ if (item && !isCollectionValue) {+ locationPath.push({+ id: item.id,+ name: item.name,+ model: value.model,+ ...("can_write" in item ? { can_write: item.can_write } : {}),+ });+ }+ return locationPath;+}++function getItemByModel(value: OmniPickerValue, dispatch: DispatchFn) {+ switch (value.model) {+ case "table":+ return dispatch(+ tableApi.endpoints.getTable.initiate({ id: value.id }),+ ).unwrap();+ case "card":+ case "dataset":+ case "metric":+ return dispatch(+ cardApi.endpoints.getCard.initiate({ id: Number(value.id) }),+ ).unwrap();+ case "collection":+ return dispatch(+ collectionApi.endpoints.getCollection.initiate({+ id: value.id,+ namespace: value.namespace ?? undefined,+ }),+ ).unwrap();+ case "dashboard":+ return dispatch(+ dashboardApi.endpoints.getDashboard.initiate({ id: value.id }),+ ).unwrap();+ case "document":+ return dispatch(+ documentApi.endpoints.getDocument.initiate({ id: Number(value.id) }),+ ).unwrap();+ case "snippet":+ return dispatch(+ snippetApi.endpoints.getSnippet.initiate(Number(value.id)),+ ).unwrap();+ case "transform":+ return dispatch(+ // @ts-expect-error - FIXME: this is a nightmare to type, and it's moving to OSS anyway+ PLUGIN_TRANSFORMS.transformApi.endpoints.getTransform.initiate(+ Number(value.id),+ ),+ ).unwrap();+ default:+ return Promise.resolve(null);+ }+}diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.unit.spec.tsxnew file mode 100644index 00000000000..656cd6fdcd3--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.unit.spec.tsx@@ -0,0 +1,1208 @@+import fetchMock from "fetch-mock";++import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupCardEndpoints,+ setupCollectionByIdEndpoint,+ setupCollectionItemsEndpoint,+ setupCollectionsEndpoints,+ setupDatabasesEndpoints,+ setupLibraryEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderHookWithProviders, waitFor } from "__support__/ui";+import { reinitialize } from "metabase/plugins";+import type {+ Collection,+ CollectionItem,+ CollectionNamespace,+ Database,+} from "metabase-types/api";+import {+ createMockCard,+ createMockCollection,+ createMockCollectionItem,+ createMockDatabase,+ createMockTable,+ createMockTokenFeatures,+ createMockUser,+} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import type {+ EntityPickerOptions,+ OmniPickerCollectionItem,+ OmniPickerItem,+ OmniPickerValue,+} from "../types";++import { useGetPathFromValue } from "./use-get-path-from-value";++const personalCollection = createMockCollection({+ id: 1001,+ name: "Admin's Personal Collection",+ location: "/",+ is_personal: true,+ personal_owner_id: 1,+});++const defaultOptions: EntityPickerOptions = {+ hasSearch: true,+ hasRecents: false,+ hasDatabases: false,+ hasLibrary: false,+ hasRootCollection: true,+ hasPersonalCollections: true,+};++interface SetupOpts {+ value?: OmniPickerValue;+ options?: EntityPickerOptions;+ namespaces?: CollectionNamespace[];+ collections?: Collection[];+ models?: OmniPickerCollectionItem["model"][];+ databases?: Database[];+ enterprise?: boolean;+}++const setup = ({+ value,+ options = defaultOptions,+ namespaces = [null],+ models = ["collection", "card"],+ collections = [],+ databases = [],+ enterprise = false,+}: SetupOpts = {}) => {+ const rootCollection = createMockCollection({+ id: "root",+ name: "Our analytics",+ });++ setupCollectionsEndpoints({+ collections: [rootCollection, ...collections],+ rootCollection,+ });++ setupCollectionByIdEndpoint({+ collections: [rootCollection, personalCollection, ...collections],+ });+ setupDatabasesEndpoints(databases);++ const user = createMockUser({+ id: 1,+ first_name: "Admin",+ last_name: "McTesterson",+ personal_collection_id: personalCollection.id,+ });++ // Setup personal collection+ if (personalCollection) {+ fetchMock.get(+ `path:/api/collection/${personalCollection.id}`,+ personalCollection,+ );+ }++ const enterpriseTokenFeatures = {+ data_studio: true,+ transforms: true,+ tenants: true,+ };++ const storeInitialState = createMockState({+ settings: mockSettings({+ "token-features": createMockTokenFeatures(+ enterprise ? enterpriseTokenFeatures : {},+ ),+ }),+ currentUser: user,+ });++ if (enterprise) {+ setupEnterpriseOnlyPlugin("data-studio");+ setupEnterpriseOnlyPlugin("tenants");+ setupEnterpriseOnlyPlugin("transforms");+ } else {+ reinitialize();+ }++ return renderHookWithProviders(+ () => useGetPathFromValue({ value, options, namespaces, models }),+ {+ storeInitialState,+ },+ );+};++function expectPathToMatch(+ path: OmniPickerItem[],+ expectedPath: Partial<OmniPickerItem>[],+) {+ expect(path).toHaveLength(expectedPath.length);+ expectedPath.forEach((expectedItem, index) => {+ expect(path[index]).toMatchObject(expectedItem);+ });+}++async function waitForPathLength(+ result: ReturnType<typeof setup>["result"],+ length: number,+) {+ return waitFor(() => {+ const [path] = result.current;+ expect(path).toHaveLength(length);+ });+}++describe("useGetPathFromValue", () => {+ describe("default path (no value provided)", () => {+ it("should return database collection when hasDatabases is true", async () => {+ const libraryCollection = createMockCollection({+ id: 1,+ name: "Library",+ });++ const { result } = setup({+ options: {+ ...defaultOptions,+ hasDatabases: true,+ hasRecents: true,+ hasLibrary: false,+ },+ collections: [libraryCollection],+ databases: [+ createMockDatabase({ id: 1, name: "DB1" }),+ createMockDatabase({ id: 2, name: "DB2" }),+ ],+ });++ await waitForPathLength(result, 1);+ const [path] = result.current;++ expectPathToMatch(path, [{ id: "databases", name: "Databases" }]);+ });++ it("should return recents collection when hasRecents is true", async () => {+ const { result } = setup({+ options: {+ ...defaultOptions,+ hasRecents: true,+ hasDatabases: false, // only if databases is false+ },+ });++ await waitForPathLength(result, 1);++ const [path] = result.current;+ expectPathToMatch(path, [{ id: "recents", name: "Recent items" }]);+ });++ it("should return root collection when hasRootCollection is true", async () => {+ const { result } = setup({+ options: {+ ...defaultOptions,+ hasRootCollection: true,+ hasDatabases: false,+ hasRecents: false,+ },+ });++ await waitForPathLength(result, 1);++ const [path] = result.current;+ expectPathToMatch(path, [{ id: "root", name: "Our analytics" }]);+ });++ it("should return empty path when no default options are set", async () => {+ const { result } = setup({+ options: {+ hasRecents: false,+ hasDatabases: false,+ hasLibrary: false,+ hasRootCollection: false,+ },+ });++ await waitFor(() => {+ const [, , { isLoadingPath }] = result.current;+ expect(isLoadingPath).toBe(false);+ });++ const [path] = result.current;+ expect(path).toHaveLength(0);+ });+ });++ describe("collection item paths", () => {+ it("should return path for root collection (our analytics)", async () => {+ const value: OmniPickerValue = {+ model: "collection",+ id: "root",+ namespace: null,+ };++ const { result } = setup({ value });++ await waitForPathLength(result, 1);++ const [path] = result.current;+ expectPathToMatch(path, [{ id: "root" }]);+ });++ it("should return a path for a card in our analytics", async () => {+ const card = createMockCard({+ id: 132,+ name: "Test Card",+ collection_id: null,+ });+ const value: OmniPickerValue = {+ model: "card",+ id: 132,+ namespace: null,+ };++ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ id: card.id,+ model: "card",+ } as CollectionItem),+ ],+ });++ setupCardEndpoints(card);++ const { result } = setup({ value });++ await waitForPathLength(result, 2);++ const [path] = result.current;+ expectPathToMatch(path, [{ id: "root" }, { id: card.id, model: "card" }]);+ });++ it("should return path for root snippet collection", async () => {+ const value: OmniPickerValue = {+ model: "collection",+ id: "root",+ namespace: "snippets",+ };++ const { result } = setup({ value, namespaces: ["snippets"] });++ await waitForPathLength(result, 1);++ const [path] = result.current;+ expectPathToMatch(path, [{ id: "root", name: "SQL Snippets" }]);+ });++ it("should return path for a nested collection in normal namespace", async () => {+ const parentCollection = createMockCollection({+ id: 16,+ name: "Parent",+ location: "/",+ });++ const childCollection = createMockCollection({+ id: 26,+ name: "Child",+ location: "/16/",+ });++ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ ...parentCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: parentCollection,+ collectionItems: [+ createMockCollectionItem({+ ...childCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: childCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 123,+ name: "Grandchild card",+ model: "card",+ } as CollectionItem),+ createMockCollectionItem({+ id: 1234,+ name: "Grandchild collection",+ location: "/16/26/",+ model: "collection",+ } as CollectionItem),+ ],+ });++ const value: OmniPickerValue = {+ model: "collection",+ id: childCollection.id,+ namespace: null,+ };++ const { result } = setup({+ value,+ collections: [parentCollection, childCollection],+ });++ await waitForPathLength(result, 3);++ const [path] = result.current;+ expectPathToMatch(path, [+ {+ id: "root",+ name: "Our analytics",+ model: "collection",+ namespace: null,+ },+ { id: parentCollection.id, model: "collection" },+ { id: childCollection.id, model: "collection" },+ ]);+ });++ it("should use effective_location for collection path", async () => {+ const parentCollection = createMockCollection({+ id: 16,+ name: "Parent",+ location: "/",+ });++ const childCollection = createMockCollection({+ id: 26,+ name: "Child",+ location: "/16/",+ });++ const grandchildCollection = createMockCollection({+ id: 36,+ name: "Grandchild",+ location: "/16/26/",+ effective_location: "/16/",+ });++ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ ...parentCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: parentCollection,+ collectionItems: [+ createMockCollectionItem({+ ...childCollection,+ model: "collection",+ } as CollectionItem),+ createMockCollectionItem({+ id: grandchildCollection.id,+ name: grandchildCollection.name,+ location: "/16/26/",+ effective_location: "/16/",+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: childCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 123,+ name: "Grandchild card",+ model: "card",+ } as CollectionItem),+ createMockCollectionItem({+ id: grandchildCollection.id,+ name: grandchildCollection.name,+ location: "/16/26/",+ effective_location: "/16/",+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: grandchildCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 12333,+ name: "great Grandchild card",+ model: "card",+ } as CollectionItem),+ ],+ });++ const value: OmniPickerValue = {+ model: "collection",+ id: grandchildCollection.id,+ namespace: null,+ };++ const { result } = setup({+ value,+ collections: [parentCollection, childCollection, grandchildCollection],+ });++ await waitForPathLength(result, 3);++ const [path] = result.current;+ expectPathToMatch(path, [+ {+ id: "root",+ name: "Our analytics",+ model: "collection",+ namespace: null,+ },+ { id: parentCollection.id, model: "collection" },+ // should skip child collection due to effective_location+ { id: grandchildCollection.id, model: "collection" },+ ]);+ });++ it("should be able to start at the databases root", async () => {+ const value: OmniPickerValue = {+ model: "collection",+ id: "databases",+ };++ const { result } = setup({+ value,+ options: { hasDatabases: true, hasRecents: true },+ });++ await waitForPathLength(result, 1);++ const [path] = result.current;+ expectPathToMatch(path, [+ {+ id: "databases",+ name: "Databases",+ model: "collection",+ },+ ]);+ });++ it("should be able to start at the recents root", async () => {+ const value: OmniPickerValue = {+ model: "collection",+ id: "recents",+ };++ const { result } = setup({+ value,+ options: { hasDatabases: true, hasRecents: true },+ });++ await waitForPathLength(result, 1);++ const [path] = result.current;+ expectPathToMatch(path, [+ {+ id: "recents",+ name: "Recent items",+ model: "collection",+ },+ ]);+ });+ });++ describe("database paths", () => {+ const testDb = createMockDatabase({+ id: 1,+ name: "Test Database",+ tables: [+ createMockTable({ id: 10, name: "Table10", schema: "schema1" }),+ createMockTable({ id: 11, name: "Table11", schema: "schema2" }),+ createMockTable({ id: 12, name: "Table12", schema: "schema2" }),+ createMockTable({ id: 13, name: "Table13", schema: "schema2" }),+ ],+ });++ const testDbSingleSchema = createMockDatabase({+ id: 2,+ name: "Test Database",+ tables: [+ createMockTable({+ id: 21,+ db_id: 2,+ name: "Table21",+ schema: "schema1",+ }),+ createMockTable({+ id: 22,+ db_id: 2,+ name: "Table22",+ schema: "schema1",+ }),+ ],+ });++ it("should return path for a database with multiple schemas", async () => {+ const value: OmniPickerValue = {+ model: "database",+ id: testDb.id,+ };++ const { result } = setup({+ value,+ databases: [testDb, testDbSingleSchema],+ });++ await waitForPathLength(result, 3);++ const [path] = result.current;+ expectPathToMatch(path, [+ { id: "databases" },+ { id: testDb.id },+ { id: "schema1" }, // auto selects first schema+ ]);+ });++ it("should hide schema for a database with one schema", async () => {+ const value: OmniPickerValue = {+ model: "database",+ id: testDbSingleSchema.id,+ };++ const { result } = setup({+ value,+ databases: [testDb, testDbSingleSchema],+ });++ await waitForPathLength(result, 2);++ const [path] = result.current;+ expectPathToMatch(path, [+ { id: "databases" },+ { id: testDbSingleSchema.id, model: "database" },+ ]);+ });++ it("should return path for a table in database (multiple schemas)", async () => {+ const table = testDb.tables?.[0];+ const value: OmniPickerValue = {+ model: "table",+ id: table?.id as number,+ };++ const { result } = setup({+ value,+ databases: [testDb, testDbSingleSchema],+ });++ await waitForPathLength(result, 4);++ const [path] = result.current;+ expectPathToMatch(path, [+ { id: "databases", model: "collection" },+ { id: testDb.id, model: "database" },+ { id: "schema1", model: "schema" },+ { id: table?.id, model: "table", name: table?.display_name },+ ]);+ });++ it("should return path for a table in database (single schema)", async () => {+ const table = testDbSingleSchema.tables?.[0];++ const { result } = setup({+ value: {+ model: "table",+ id: table?.id as number,+ },+ databases: [testDb, testDbSingleSchema],+ });++ await waitForPathLength(result, 3);++ const [path] = result.current;+ expectPathToMatch(path, [+ { id: "databases", model: "collection" },+ { id: testDbSingleSchema.id, model: "database" },+ { id: table?.id, model: "table" },+ ]);+ });+ });++ describe("special collections", () => {+ it("should handle user personal collection path", async () => {+ const childCollection = createMockCollection({+ id: 2002,+ name: "Personal child collection",+ location: `/${personalCollection.id}/`,+ is_personal: true,+ });++ setupCollectionItemsEndpoint({+ collection: personalCollection,+ collectionItems: [+ createMockCollectionItem({+ id: childCollection.id as number,+ name: childCollection.name,+ model: "collection",+ }),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: childCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 222,+ name: "my card",+ model: "card",+ }),+ ],+ });++ const value: OmniPickerValue = {+ model: "collection",+ id: childCollection.id,+ namespace: null,+ };++ const { result } = setup({+ value,+ collections: [childCollection],+ });++ await waitForPathLength(result, 2);++ const [path] = result.current;+ expect(path.length).toBeGreaterThanOrEqual(2);+ expectPathToMatch(path, [+ { id: personalCollection.id, model: "collection" },+ { id: childCollection.id, model: "collection" },+ ]);+ });++ it("should handle other user personal collection root", async () => {+ const otherPersonal = createMockCollection({+ id: 2003,+ name: "Jane's personal collection",+ location: "/",+ is_personal: true,+ personal_owner_id: 2,+ });++ setupCollectionItemsEndpoint({+ collection: otherPersonal,+ collectionItems: [+ createMockCollectionItem({+ id: 222,+ name: "my card",+ model: "card",+ }),+ ],+ });++ const value: OmniPickerValue = {+ model: "collection",+ id: otherPersonal.id,+ namespace: null,+ };++ const { result } = setup({+ value,+ collections: [otherPersonal],+ });++ await waitForPathLength(result, 2);++ const [path] = result.current;+ expect(path.length).toBeGreaterThanOrEqual(2);+ expectPathToMatch(path, [+ { id: "personal", model: "collection" },+ { id: otherPersonal.id, model: "collection" },+ ]);+ });++ it("should handle nested other user personal collections", async () => {+ const otherPersonal = createMockCollection({+ id: 2002,+ name: "Jane's personal collection",+ location: "/",+ is_personal: true,+ personal_owner_id: 2,+ });++ const nestedPersonal = createMockCollection({+ id: 2003,+ name: "Jane's more personal collection",+ location: "/2002/",+ is_personal: true,+ });++ const moreNestedPersonal = createMockCollection({+ id: 2004,+ name: "Jane's extra nested personal collection",+ location: "/2002/2003/",+ is_personal: true,+ });++ setupCollectionItemsEndpoint({+ collection: otherPersonal,+ collectionItems: [+ createMockCollectionItem({+ ...nestedPersonal,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: nestedPersonal,+ collectionItems: [+ createMockCollectionItem({+ ...moreNestedPersonal,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: moreNestedPersonal,+ collectionItems: [+ createMockCollectionItem({+ id: 222,+ name: "my card",+ model: "card",+ }),+ ],+ });++ const value: OmniPickerValue = {+ model: "collection",+ id: moreNestedPersonal.id,+ namespace: null,+ };++ const { result } = setup({+ value,+ collections: [otherPersonal, nestedPersonal, moreNestedPersonal],+ });++ await waitForPathLength(result, 4);++ const [path] = result.current;+ expectPathToMatch(path, [+ { id: "personal", model: "collection" },+ { id: otherPersonal.id, model: "collection" },+ { id: nestedPersonal.id, model: "collection" },+ { id: moreNestedPersonal.id, model: "collection" },+ ]);+ });+ });++ describe("loading states", () => {+ it("should set isLoadingPath to true initially, and false when done loading", async () => {+ const parentCollection = createMockCollection({+ id: 16,+ name: "Parent",+ location: "/",+ });++ const childCollection = createMockCollection({+ id: 26,+ name: "Child",+ location: "/16/",+ });++ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ ...parentCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ // doing this manually here to get a delay+ fetchMock.get(+ `path:/api/collection/${parentCollection.id}/items`,+ () => {+ return {+ data: [+ createMockCollectionItem({+ ...childCollection,+ model: "collection",+ } as CollectionItem),+ ],+ };+ },+ { name: `collection-${parentCollection.id}-items`, delay: 50 },+ );++ setupCollectionItemsEndpoint({+ collection: childCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 123,+ name: "Grandchild card",+ model: "card",+ } as CollectionItem),+ createMockCollectionItem({+ id: 1234,+ name: "Grandchild collection",+ location: "/16/26/",+ model: "collection",+ } as CollectionItem),+ ],+ });++ const value: OmniPickerValue = {+ model: "collection",+ id: childCollection.id,+ namespace: null,+ };++ const { result } = setup({+ value,+ collections: [parentCollection, childCollection],+ });++ await waitFor(() => {+ const [, , { isLoadingPath }] = result.current;+ expect(isLoadingPath).toBe(true);+ });++ await waitFor(() => {+ const [, , { isLoadingPath }] = result.current;+ expect(isLoadingPath).toBe(false);+ });+ });+ });++ describe("setPath functionality", () => {+ it("should provide a setPath function", async () => {+ const { result } = setup();++ await waitFor(() => {+ expect(result.current[2].isLoadingPath).toBe(false);+ });++ const [, setPath] = result.current;+ expect(typeof setPath).toBe("function");+ });+ });++ describe("missing items", () => {+ it("should handle missing database gracefully", async () => {+ const value: OmniPickerValue = {+ model: "database",+ id: 999,+ };++ fetchMock.get("path:/api/database/999/schemas", 404);++ const { result } = setup({ value });++ await waitForPathLength(result, 1);++ const [path] = result.current;+ expectPathToMatch(path, [{ id: "databases" }]);+ });++ it("should handle missing collection gracefully", async () => {+ const missing_collection_id = 5555;++ fetchMock.get(`path:/api/collection/${missing_collection_id}`, 404);+ const { result } = setup({+ value: { model: "collection", id: missing_collection_id },+ collections: [],+ });++ await waitForPathLength(result, 0);++ const [path] = result.current;+ expectPathToMatch(path, []);+ });+ });++ describe("enterprise features", () => {+ beforeEach(() => {+ setupLibraryEndpoints(true);+ });++ it("warmup enterprise plugins", () => {+ // warm up enterprise plugins, without this, tests can time out in CI 😢+ setupLibraryEndpoints(true);+ const { result } = setup({+ enterprise: true,+ });+ expect(result).toBeDefined();+ }, 10_000);++ it("should return transform path with a provided transform collection", async () => {+ const parentCollection = createMockCollection({+ id: 6262,+ name: "My Transforms",+ location: "/",+ namespace: "transforms",+ model: "collection",+ here: ["table", "dataset"],+ } as unknown as Collection);++ const childCollection = createMockCollection({+ id: 6363,+ name: "More Transforms",+ location: "/6262/",+ namespace: "transforms",+ model: "collection",+ collection: parentCollection,+ here: ["table", "dataset"],+ } as unknown as Collection);++ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ ...parentCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: parentCollection,+ collectionItems: [+ createMockCollectionItem({+ ...childCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: childCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 12345,+ name: "Cool Transform",+ model: "transform",+ } as CollectionItem),+ ],+ });++ const { result } = setup({+ enterprise: true,+ value: { id: childCollection.id, model: "collection" },+ options: { ...defaultOptions },+ collections: [parentCollection, childCollection],+ namespaces: ["transforms"],+ });++ await waitForPathLength(result, 3);++ const [path] = result.current;+ expectPathToMatch(path, [+ { id: "root", namespace: "transforms", name: "Transforms" },+ { id: parentCollection.id },+ { id: childCollection.id },+ ]);+ });++ it("should return library collection path with no provided value", async () => {+ const libraryCollection = createMockCollection({+ id: 6464,+ name: "Library",+ here: ["collection"],+ below: ["collection"],+ } as unknown as Collection);++ const childCollection = createMockCollection({+ id: 6565,+ name: "Data",+ location: "/6464/",+ here: ["table", "dataset"],+ } as unknown as Collection);++ setupCollectionItemsEndpoint({+ collection: libraryCollection,+ collectionItems: [+ createMockCollectionItem({+ ...childCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ const { result } = setup({+ enterprise: true,+ options: { ...defaultOptions, hasLibrary: true },+ collections: [libraryCollection, childCollection],+ });++ await waitForPathLength(result, 2);++ const [path] = result.current;+ expectPathToMatch(path, [+ { id: libraryCollection.id },+ { id: childCollection.id },+ ]);+ });++ it("should return a shared tenant collection path", async () => {+ const parentCollection = createMockCollection({+ id: 6262,+ name: "shared stuff",+ location: "/",+ namespace: "shared-tenant-collection",+ model: "collection",+ here: ["table", "dataset", "collection"],+ } as unknown as Collection);++ const childCollection = createMockCollection({+ id: 6363,+ name: "More shared stuff",+ location: "/6262/",+ namespace: "shared-tenant-collection",+ model: "collection",+ collection: parentCollection,+ here: ["table", "dataset", "collection"],+ } as unknown as Collection);++ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ ...parentCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: parentCollection,+ collectionItems: [+ createMockCollectionItem({+ ...childCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: childCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 12345,+ name: "Cool Card",+ model: "card",+ } as CollectionItem),+ ],+ });++ const { result } = setup({+ enterprise: true,+ value: { id: childCollection.id, model: "collection" },+ options: { ...defaultOptions },+ collections: [parentCollection, childCollection],+ namespaces: ["transforms"],+ });++ await waitForPathLength(result, 3);++ const [path] = result.current;+ expectPathToMatch(path, [+ {+ id: "root",+ namespace: "shared-tenant-collection",+ name: "Shared collections",+ },+ { id: parentCollection.id },+ { id: childCollection.id },+ ]);+ });++ it("should return a tenant specific collection path", async () => {+ const parentCollection = createMockCollection({+ id: 6262,+ name: "specific stuff",+ location: "/",+ namespace: "tenant-specific",+ model: "collection",+ here: ["table", "dataset", "collection"],+ } as unknown as Collection);++ const childCollection = createMockCollection({+ id: 6363,+ name: "More specific stuff",+ location: "/6262/",+ namespace: "tenant-specific",+ model: "collection",+ collection: parentCollection,+ here: ["table", "dataset", "collection"],+ } as unknown as Collection);++ setupCollectionItemsEndpoint({+ collection: { id: "root" },+ collectionItems: [+ createMockCollectionItem({+ ...parentCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: parentCollection,+ collectionItems: [+ createMockCollectionItem({+ ...childCollection,+ model: "collection",+ } as CollectionItem),+ ],+ });++ setupCollectionItemsEndpoint({+ collection: childCollection,+ collectionItems: [+ createMockCollectionItem({+ id: 12345,+ name: "Cool Card",+ model: "card",+ } as CollectionItem),+ ],+ });++ const { result } = setup({+ enterprise: true,+ value: { id: childCollection.id, model: "collection" },+ options: { ...defaultOptions },+ collections: [parentCollection, childCollection],+ namespaces: ["transforms"],+ });++ await waitForPathLength(result, 3);++ const [path] = result.current;+ expectPathToMatch(path, [+ {+ id: "root",+ namespace: "tenant-specific",+ name: "Tenant collections",+ },+ { id: parentCollection.id },+ { id: childCollection.id },+ ]);+ });+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-root-items.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-root-items.tsnew file mode 100644index 00000000000..f47d408daf3--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-root-items.ts@@ -0,0 +1,317 @@+import { useState } from "react";+import { useDeepCompareEffect } from "react-use";+import { t } from "ttag";++import {+ skipToken,+ useListCollectionItemsQuery,+ useListDatabasesQuery,+} from "metabase/api";+import {+ useGetPersonalCollection,+ useHasTokenFeature,+ useSetting,+} from "metabase/common/hooks";+import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";+import { type DispatchFn, useDispatch, useSelector } from "metabase/lib/redux";+import { PLUGIN_DATA_STUDIO, PLUGIN_TENANTS } from "metabase/plugins";+import { getUser, getUserIsAdmin } from "metabase/selectors/user";+import type {+ Collection,+ CollectionNamespace,+ Database,+ User,+} from "metabase-types/api";++import { useOmniPickerContext } from "../context";+import type {+ EntityPickerOptions,+ OmniPickerCollectionItem,+ OmniPickerItem,+} from "../types";+import { getValidCollectionItemModels } from "../utils";++import { getRootCollectionItem } from "./utils";++const personalCollectionsRoot: OmniPickerCollectionItem = {+ ...PERSONAL_COLLECTIONS,+ can_write: false,+ model: "collection",+ location: "/",+ here: ["collection"],+ below: ["collection"],+};++/**+ * This will generate a list of the top level items for the entity picker+ */+export const useRootItems = () => {+ const { options, models, searchQuery, namespaces } = useOmniPickerContext();+ const isAdmin = useSelector(getUserIsAdmin);+ const hasTenants = useSetting("use-tenants");+ const transformsEnabled = useHasTokenFeature("transforms");+ const dispatch = useDispatch();++ const { data: databaseData, isLoading: isLoadingDatabases } =+ useListDatabasesQuery(undefined, { skip: !options.hasDatabases });+ const tenantsEnabled = useSetting("use-tenants");++ const currentUser = useSelector(getUser);+ const [isLoadingCollections, setIsLoadingCollections] = useState(false);+ const [rootItems, setRootItems] = useState<OmniPickerItem[]>([]);++ const { data: personalCollection, isLoading: isLoadingPersonalCollection } =+ useGetPersonalCollection();++ const { data: libraryCollection } =+ PLUGIN_DATA_STUDIO.useGetLibraryCollection({+ skip: !options.hasLibrary,+ });++ const {+ data: personalCollectionItems,+ isLoading: isLoadingPersonalCollectionItems,+ } = useListCollectionItemsQuery(+ personalCollection+ ? {+ id: personalCollection.id,+ limit: 0, // we only want total number of items+ }+ : skipToken,+ );+ const totalPersonalCollectionItems = personalCollectionItems?.total ?? 0;++ useDeepCompareEffect(() => {+ const databases = databaseData?.data ?? [];+ setIsLoadingCollections(true);+ getRootItems({+ searchQuery,+ personalCollection,+ isAdmin,+ options,+ databases,+ totalPersonalCollectionItems,+ libraryCollection,+ namespaces,+ models,+ tenantsEnabled,+ transformsEnabled,+ currentUser,+ hasTenants,+ dispatch,+ })+ .then((rootItems) => {+ setRootItems(rootItems);+ })+ .finally(() => {+ setIsLoadingCollections(false);+ });+ }, [+ searchQuery,+ personalCollection,+ isAdmin,+ options,+ databaseData?.data,+ totalPersonalCollectionItems,+ libraryCollection,+ namespaces,+ models,+ tenantsEnabled,+ transformsEnabled,+ currentUser,+ hasTenants,+ setIsLoadingCollections,+ dispatch,+ ]);++ const isLoading =+ isLoadingDatabases ||+ isLoadingCollections ||+ isLoadingPersonalCollection ||+ isLoadingPersonalCollectionItems;++ return { items: rootItems, isLoading };+};++async function getRootItems({+ searchQuery,+ personalCollection,+ isAdmin,+ options,+ databases,+ totalPersonalCollectionItems,+ libraryCollection,+ namespaces,+ models,+ tenantsEnabled,+ transformsEnabled,+ currentUser,+ hasTenants,+ dispatch,+}: {+ searchQuery?: string;+ personalCollection?: Collection;+ isAdmin: boolean;+ options: EntityPickerOptions;+ databases: Database[];+ totalPersonalCollectionItems: number;+ libraryCollection?: OmniPickerItem;+ namespaces: CollectionNamespace[];+ models: OmniPickerItem["model"][];+ tenantsEnabled: boolean;+ transformsEnabled: boolean;+ currentUser: User | null;+ hasTenants: boolean;+ dispatch: DispatchFn;+}): Promise<OmniPickerCollectionItem[]> {+ const collectionItems: OmniPickerCollectionItem[] = [];+ const validCollectionModels = getValidCollectionItemModels(models);++ if (searchQuery) {+ collectionItems.push({+ id: "search-results",+ can_write: false,+ model: "collection",+ name: t`Search results for "${searchQuery}"`,+ below: validCollectionModels,+ });+ }++ if (options.hasLibrary && libraryCollection && namespaces.includes(null)) {+ collectionItems.push({+ ...libraryCollection,+ model: "collection",+ can_write: false,+ location: "/",+ collection: undefined,+ });+ }++ if (options.hasRecents) {+ collectionItems.push({+ id: "recents",+ name: t`Recent items`,+ model: "collection",+ can_write: false,+ location: "/",+ below: validCollectionModels,+ here: validCollectionModels,+ });+ }++ if (options.hasDatabases && databases.length > 0) {+ collectionItems.push({+ id: "databases",+ name: t`Databases`,+ model: "collection",+ can_write: false,+ location: "/",+ here: ["collection"],+ below: ["table"],+ });+ }++ if (namespaces.includes("snippets")) {+ collectionItems.push({+ ...(await getRootCollectionItem({+ namespace: "snippets",+ dispatch,+ })),+ here: ["collection"],+ below: validCollectionModels,+ });+ }++ if (namespaces.includes("transforms") && transformsEnabled) {+ collectionItems.push({+ ...(await getRootCollectionItem({+ namespace: "transforms",+ dispatch,+ })),+ here: ["collection"],+ below: validCollectionModels,+ });+ }++ if (options?.hasRootCollection && namespaces.includes(null)) {+ collectionItems.push({+ ...(await getRootCollectionItem({+ namespace: null,+ dispatch,+ })),+ model: "collection",+ here: ["collection"],+ below: validCollectionModels,+ });+ }++ if (+ hasTenants &&+ namespaces.includes(PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE)+ ) {+ collectionItems.push({+ ...(await getRootCollectionItem({+ namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,+ dispatch,+ })),+ here: ["collection", "card", "dashboard"],+ can_write: true, // should check API for this+ });+ }++ if (+ hasTenants &&+ namespaces.includes(PLUGIN_TENANTS.TENANT_SPECIFIC_NAMESPACE)+ ) {+ const userTenantCollectionId = currentUser?.tenant_collection_id;++ if (userTenantCollectionId && tenantsEnabled) {+ // show user's tenant collection+ collectionItems.push({+ name: t`Our data`,+ id: userTenantCollectionId,+ here: ["collection", "card", "dashboard"],+ can_write: true,+ namespace: null,+ model: "collection",+ location: "/",+ type: "tenant-specific-root-collection",+ });+ }+ const tenantSpecificRoot = await getRootCollectionItem({+ namespace: PLUGIN_TENANTS.TENANT_SPECIFIC_NAMESPACE,+ dispatch,+ });+ if (tenantSpecificRoot && isAdmin) {+ // show all tenant collections to admins+ collectionItems.push(tenantSpecificRoot);+ }+ }++ if (+ options?.hasPersonalCollections &&+ namespaces.includes(null) &&+ !!personalCollection+ ) {+ collectionItems.push({+ ...personalCollection,+ namespace: null,+ here: totalPersonalCollectionItems ? ["collection"] : [],+ below: totalPersonalCollectionItems ? validCollectionModels : [],+ model: "collection",+ can_write: true,+ });++ if (isAdmin) {+ collectionItems.push({+ ...personalCollectionsRoot,+ model: "collection",+ namespace: null,+ here: ["collection"],+ below: validCollectionModels,+ location: "/",+ });+ }+ }+ return collectionItems;+}diff --git a/frontend/src/metabase/common/components/EntityPicker/hooks/use-log-recent-item.tsx b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-log-recent-item.tsxsimilarity index 61%rename from frontend/src/metabase/common/components/EntityPicker/hooks/use-log-recent-item.tsxrename to frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-log-recent-item.tsxindex c6ba350fcbf..c61ca230e49 100644--- a/frontend/src/metabase/common/components/EntityPicker/hooks/use-log-recent-item.tsx+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-log-recent-item.tsx@@ -1,19 +1,14 @@import { useCallback } from "react";import { useLogRecentItemMutation } from "metabase/api";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import { isLoggableActivityModel } from "metabase-types/api";-import type { CollectionPickerItem } from "../../Pickers/CollectionPicker";-import type { DataPickerValueItem } from "../../Pickers/DataPicker";-import type { MiniPickerPickableItem } from "../../Pickers/MiniPicker/types";-export const useLogRecentItem = () => {const [logRecentItem] = useLogRecentItemMutation();const tryLogRecentItem = useCallback(- (- item: CollectionPickerItem | DataPickerValueItem | MiniPickerPickableItem,- ) => {+ (item: OmniPickerItem) => {if (isLoggableActivityModel(item)) {logRecentItem({model_id: item.id,diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-switch-to-search-folder.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-switch-to-search-folder.tsnew file mode 100644index 00000000000..452f081b478--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-switch-to-search-folder.ts@@ -0,0 +1,53 @@+import { useEffect } from "react";+import { usePrevious } from "react-use";+import { t } from "ttag";++import { useOmniPickerContext } from "../context";+import { validCollectionModels } from "../utils";++export function useSwitchToSearchFolder() {+ const {+ path,+ setPath,+ searchQuery,+ setPreviousPath,+ previousPath,+ setSearchScope,+ } = useOmniPickerContext();+ const previousSearchQuery = usePrevious(searchQuery);++ useEffect(() => {+ if (searchQuery && searchQuery !== previousSearchQuery) {+ if (path[0]?.id !== "search-results") {+ setPreviousPath(path);+ setSearchScope(null);+ }+ setPath([+ {+ id: "search-results",+ model: "collection",+ name: t`Search results for "${searchQuery}"`,+ below: Array.from(validCollectionModels),+ },+ ]);+ } else if (+ !searchQuery &&+ previousSearchQuery &&+ path[0]?.id === "search-results"+ ) {+ // Restore previous path when clearing search+ if (previousPath.length > 0) {+ setPath(previousPath);+ setPreviousPath([]);+ }+ }+ }, [+ searchQuery,+ previousSearchQuery,+ setPath,+ path,+ previousPath,+ setPreviousPath,+ setSearchScope,+ ]);+}diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/utils.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/utils.tsnew file mode 100644index 00000000000..2cf1fff25f2--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/utils.ts@@ -0,0 +1,94 @@+import { t } from "ttag";++import { collectionApi } from "metabase/api";+import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";+import type { DispatchFn } from "metabase/lib/redux";+import { PLUGIN_TRANSFORMS } from "metabase/plugins";+import { PLUGIN_TENANTS } from "metabase/plugins/oss/tenants";+import type { CollectionNamespace } from "metabase-types/api";++import type { OmniPickerCollectionItem } from "../types";+import { allCollectionModels } from "../utils";++export const getOurAnalytics = (): OmniPickerCollectionItem => ({+ model: "collection",+ id: "root",+ name: t`Our analytics`,+ here: ["collection"],+ below: allCollectionModels,+ can_write: true,+ namespace: null,+});++export const personalCollectionsRoot: OmniPickerCollectionItem = {+ ...PERSONAL_COLLECTIONS,+ can_write: false,+ model: "collection",+ location: "/",+ here: ["collection"],+ below: allCollectionModels,+};++export const getRootCollectionItem = async ({+ namespace,+ dispatch,+}: {+ namespace: CollectionNamespace;+ dispatch: DispatchFn;+}): Promise<OmniPickerCollectionItem> => {+ const rootCollectionFromApi = await fetchRootCollection(namespace, dispatch);+ const canWrite = rootCollectionFromApi?.can_write ?? false;++ const tenantRootItem = PLUGIN_TENANTS.getRootCollectionItem({ namespace });+ if (tenantRootItem) {+ return {+ can_write: canWrite,+ ...tenantRootItem,+ };+ }++ const transformRootItem = PLUGIN_TRANSFORMS.getRootCollectionItem({+ namespace,+ });+ if (transformRootItem) {+ return {+ ...transformRootItem,+ can_write: canWrite,+ };+ }++ if (namespace === "snippets") {+ return {+ model: "collection",+ id: "root",+ namespace: "snippets",+ location: "/",+ can_write: canWrite,+ name: t`SQL Snippets`,+ here: ["collection", "snippet"],+ below: ["collection", "snippet"],+ };+ }++ return {+ ...getOurAnalytics(),+ // if we failed to fetch our analytics, the user doesn't have access to it+ // so we just call it "Collections"+ ...(!rootCollectionFromApi ? { name: t`Collections` } : {}),+ can_write: canWrite,+ };+};++export const fetchRootCollection = async (+ namespace: CollectionNamespace,+ dispatch: DispatchFn,+) => {+ return dispatch(+ collectionApi.endpoints.getCollection.initiate({+ id: "root",+ namespace: namespace ?? undefined,+ }),+ )+ .unwrap()+ .catch(console.warn);+};diff --git a/frontend/src/metabase/common/components/EntityPicker/index.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/index.tssimilarity index 100%rename from frontend/src/metabase/common/components/EntityPicker/index.tsrename to frontend/src/metabase/common/components/Pickers/EntityPicker/index.tsdiff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/types.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/types.tsnew file mode 100644index 00000000000..2382c441ad6--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/types.ts@@ -0,0 +1,208 @@+import type { Dispatch, SetStateAction } from "react";++import type {+ CardId,+ Collection,+ CollectionId,+ CollectionItem,+ CollectionNamespace,+ DashboardId,+ DatabaseId,+ NativeQuerySnippet,+ RecentContexts,+ RegularCollectionId,+ SchemaName,+ SearchRequest,+ TableId,+} from "metabase-types/api";++export type EntityPickerOptions = {+ // options to show/hide root items+ hasSearch?: boolean;+ hasRecents?: boolean;+ hasDatabases?: boolean;+ hasLibrary?: boolean;+ hasRootCollection?: boolean;+ hasPersonalCollections?: boolean; // other users personal collections++ // options to customize the button bar+ hasConfirmButtons?: boolean;+ canCreateCollections?: boolean;+ canCreateDashboards?: boolean;+ confirmButtonText?:+ | React.ReactNode+ | ((i?: OmniPickerItem) => React.ReactNode);+ cancelButtonText?: React.ReactNode;+};++export type PickerItemFunctions = {+ isFolderItem: (item: OmniPickerItem) => item is OmniPickerFolderItem;+ isHiddenItem: (item: OmniPickerItem) => boolean;+ isDisabledItem: (item: OmniPickerItem) => boolean;+ isSelectableItem: (item: OmniPickerItem) => boolean;+};++export type EntityPickerProps = {+ onChange: (value: OmniPickerItem) => void;+ onClose: () => void;+ models: OmniPickerItem["model"][];+ namespaces?: CollectionNamespace[];+ options: EntityPickerOptions;+ searchParams?: Partial<SearchRequest>;+ value?: OmniPickerValue;+ searchQuery?: string;+ recentsContext?: RecentContexts[];+ isNewCollectionDialogOpen: boolean;+ openNewCollectionDialog: () => void;+ closeNewCollectionDialog: () => void;+ isNewDashboardDialogOpen: boolean;+ openNewDashboardDialog: () => void;+ closeNewDashboardDialog: () => void;+} & Partial<PickerItemFunctions>; // picker functions are optional in props++export type OmniPickerContextValue = {+ path: OmniPickerItem[];+ setPath: Dispatch<SetStateAction<OmniPickerItem[]>>;+ isLoadingPath: boolean;+ previousPath: OmniPickerItem[];+ setPreviousPath: Dispatch<SetStateAction<OmniPickerItem[]>>;+ searchScope: SearchScope;+ setSearchScope: Dispatch<SetStateAction<SearchScope>>;+ searchParams?: Partial<SearchRequest>;+ namespaces: CollectionNamespace[]; // not optional in context+} & EntityPickerProps &+ PickerItemFunctions; // picker functions are required in context++export type OmniPickerCollectionItem = Pick<+ CollectionItem,+ | "name"+ | "model"+ | "here"+ | "below"+ | "moderated_status"+ | "display"+ | "can_write"+ | "location"+ | "type"+ | "database_id"+ | "location"+ | "effective_location"+> & {+ id: CollectionItem["id"] | CollectionId;+ collection?:+ | (Pick<Collection, "id" | "name" | "authority_level"> & {+ namespace?: CollectionNamespace;+ })+ | null;+ dashboard_id?: DashboardId;+ namespace?: CollectionNamespace;+ is_personal?: boolean;+};++export type OmniPickerDashboardItem = {+ model: "dashboard";+ id: CollectionItem["id"] | CollectionId;+ name: string;+ here?: CollectionItem["here"];+ below?: CollectionItem["below"];+};++export type OmniPickerPickableItem<+ PickableModels extends CollectionItem["model"],+> = OmniPickerItem & {+ model: PickableModels;+};++export type OmniPickerSchemaItem = {+ model: "schema";+ id: SchemaName;+ database_id: DatabaseId;+ name: SchemaName;+};++export type OmniPickerTableItem = {+ model: "table";+ id: TableId;+ database_id: DatabaseId; // the api returns db_id for tables 🙄+ database_name?: string;+ schema?: SchemaName;+ name: string;+ is_published?: boolean;+};++export type OmniPickerQuestionItem = Omit<+ OmniPickerCollectionItem,+ "id" | "model"+> & {+ model: "card" | "dataset" | "metric";+ id: CardId;+};++export type OmniPickerDatabaseItem = {+ model: "database";+ id: DatabaseId;+ name: string;+};++export type OmniPickerSnippetItem = Pick<NativeQuerySnippet, "id" | "name"> & {+ model: "snippet";+};++export enum OmniPickerFolderModel {+ Database = "database",+ Schema = "schema",+ Collection = "collection",+ Dashboard = "dashboard",+}++export type DbTreeItem =+ | OmniPickerDatabaseItem+ | OmniPickerSchemaItem+ | OmniPickerTableItem;++export const isInDbTree = (item: OmniPickerItem): item is DbTreeItem => {+ return (+ item.model === "database" ||+ item.model === "schema" ||+ item.model === "table"+ );+};++// this includes all possible item types that can be shown in the mini picker+export type OmniPickerItem =+ | OmniPickerCollectionItem+ | OmniPickerSchemaItem+ | OmniPickerTableItem+ | OmniPickerDatabaseItem;++export type OmniPickerDbValue = Pick<DbTreeItem, "model" | "id">;+export type OmniPickerTableValue = Pick<OmniPickerTableItem, "model" | "id">;+export type OmniPickerCollectionItemValue = Pick<+ OmniPickerCollectionItem,+ "model" | "id" | "namespace"+>;++export type OmniPickerValue = OmniPickerDbValue | OmniPickerCollectionItemValue;++// this is only the intermediate/folder types that cannot ultimately be picked+export type OmniPickerFolderItem =+ | OmniPickerDatabaseItem+ | OmniPickerSchemaItem+ | OmniPickerDashboardItem+ | (OmniPickerCollectionItem & { model: "collection" });++// can't get schemas in search results+export type SearchableOmniPickerItem =+ | OmniPickerCollectionItem+ | OmniPickerTableItem+ | OmniPickerDatabaseItem;++// used to find only or exclude items in personal collections, usually when adding items to a dashboard+// so that you don't end up with personal items in a public dashboard+export type FilterItemsInPersonalCollection = "only" | "exclude";++export type SearchScope =+ | Exclude<RegularCollectionId, string>+ | "databases"+ | "all"+ | null;diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.tsnew file mode 100644index 00000000000..f23a9ccf45a--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.ts@@ -0,0 +1,312 @@+import _ from "underscore";++import type { ColorName } from "metabase/lib/colors/types";+import { type IconData, getIcon } from "metabase/lib/icon";+import type {+ CollectionItemModel,+ CollectionNamespace,+ CollectionType,+} from "metabase-types/api";+import { isObject } from "metabase-types/guards";++import {+ type EntityPickerProps,+ type OmniPickerCollectionItem,+ type OmniPickerFolderItem,+ OmniPickerFolderModel,+ type OmniPickerItem,+ type PickerItemFunctions,+} from "./types";++export const getEntityPickerIcon = (+ item: OmniPickerItem,+ {+ isSelected,+ isTenantUser,+ }: {+ isSelected?: boolean;+ isTenantUser?: boolean;+ } = {},+): IconData & { c?: ColorName } => {+ const icon = getIcon(item, { isTenantUser });++ if (item.id === "search-results") {+ icon.name = "search";+ }++ if (isSelected && !icon.color) {+ icon.color = "text-primary-inverse";+ }++ if (icon.name === "folder" && isSelected) {+ icon.name = "folder_filled";+ }++ if (item.id === "recents") {+ icon.name = "clock";+ }++ return { ...icon, color: undefined, c: icon.color ?? "brand" };+};++const isSameNamespace = (+ item1: OmniPickerItem,+ item2: OmniPickerItem,+): boolean => {+ if (!("namespace" in item1) || !("namespace" in item2)) {+ return true;+ }++ return item1.namespace === item2.namespace;+};++export const isSelectedItem = (+ item: OmniPickerItem,+ selectedItem: OmniPickerItem | null,+): boolean => {+ return (+ !!selectedItem &&+ item.id === selectedItem.id &&+ item.model === selectedItem.model &&+ isSameNamespace(item, selectedItem)+ );+};++const isValidItem = (item: unknown): item is OmniPickerItem => {+ return (+ isObject(item) &&+ "model" in item &&+ typeof item.model === "string" &&+ !!item.id+ );+};++/**+ * Given a set of models and optional custom functions,+ * return a complete set of item functions for the EntityPicker to use.+ *+ * Custom functions can narrow the result set, but cannot expand it.+ */++export function getItemFunctions({+ models,+ isFolderItem,+ isHiddenItem,+ isDisabledItem,+ isSelectableItem,+}: {+ models: EntityPickerProps["models"];+} & Partial<PickerItemFunctions>): PickerItemFunctions {+ const modelSet = new Set(models);++ const isFolderBase = (item: OmniPickerItem | unknown) => {+ if (!isValidItem(item)) {+ return false;+ }++ if (+ item.model === OmniPickerFolderModel.Database ||+ item.model === OmniPickerFolderModel.Schema+ ) {+ return true;+ }++ if (item.model === OmniPickerFolderModel.Collection) {+ if (!("here" in item) && !("below" in item)) {+ return false;+ }++ const hereBelowSet = Array.from(+ new Set([+ ...("here" in item && Array.isArray(item.here) ? item.here : []),+ ...("below" in item && Array.isArray(item.below) ? item.below : []),+ ]),+ );++ if (hereBelowSet.some((hereBelowModel) => modelSet.has(hereBelowModel))) {+ return true;+ }+ }++ if (item.model === OmniPickerFolderModel.Dashboard) {+ const hereBelowSet = Array.from(+ new Set([+ ...("here" in item && Array.isArray(item.here) ? item.here : []),+ ...("below" in item && Array.isArray(item.below) ? item.below : []),+ ]),+ );++ if (hereBelowSet.some((hereBelowModel) => modelSet.has(hereBelowModel))) {+ return true;+ }+ }++ return false;+ };++ const isFolder = (item: OmniPickerItem): item is OmniPickerFolderItem =>+ isFolderBase(item) && (isFolderItem ? isFolderItem(item) : true);++ // selectable should be narrower than hidden or disabled because+ // intermediate items should not be disabled, but can't ultimately be selected+ const isSelectableBase = (item: OmniPickerItem) => {+ if (!isValidItem(item)) {+ return false;+ }++ return modelSet.has(item.model);+ };++ const isSelectable = (item: OmniPickerItem) =>+ isSelectableBase(item) &&+ (isSelectableItem ? isSelectableItem(item) : true);++ const isHiddenBase = (item: OmniPickerItem) => {+ if (!isValidItem(item)) {+ return true;+ }++ return !modelSet.has(item.model) && !isFolder(item);+ };++ const isHidden = (item: OmniPickerItem) =>+ isHiddenBase(item) || (isHiddenItem ? isHiddenItem(item) : false);++ const isDisabledBase = (item: OmniPickerItem) => {+ if (!isValidItem(item)) {+ return true;+ }++ return false;+ };++ const isDisabled = (item: OmniPickerItem) =>+ isDisabledBase(item) || (isDisabledItem ? isDisabledItem(item) : false);++ return {+ isFolderItem: isFolder,+ isHiddenItem: isHidden,+ isDisabledItem: isDisabled,+ isSelectableItem: isSelectable,+ };+}++export const validCollectionModels = new Set<CollectionItemModel>([+ "collection",+ "dashboard",+ "document",+ "card",+ "dataset",+ "metric",+ "table",+ "snippet",+ "transform",+]);++export const allCollectionModels = Array.from(validCollectionModels);++const isValidModel = (+ model: OmniPickerItem["model"],+): model is CollectionItemModel =>+ validCollectionModels.has(model as CollectionItemModel);++export const getValidCollectionItemModels = (+ models: OmniPickerItem["model"][],+): CollectionItemModel[] =>+ _.uniq(models.filter(isValidModel).concat(["collection"]));++// this ensures that we get cache hits by sending the same options for collection item requests+export const getCollectionItemsOptions = ({+ models,+}: {+ models: OmniPickerItem["model"][];+}) => {+ return {+ models: getValidCollectionItemModels(models),+ include_can_run_adhoc_query: models.includes("table"),+ };+};++export const isCollection = (+ item: OmniPickerItem,+): item is OmniPickerCollectionItem => item.model === "collection";++const isCollectionWithType = (+ item: OmniPickerCollectionItem,+): item is OmniPickerCollectionItem & {+ type: CollectionType;+ model: "collection";+} => {+ return item.model === "collection" && typeof item.type === "string";+};++/**+ * Returns the collection type for an item.+ * Recent items and search results use `collection_type` field,+ * while regular collection picker items use `type` field.+ *+ * The entity picker normalizes all of these onto the "type" field,+ * which overlaps with question types+ */+export function getCollectionType(+ item: OmniPickerCollectionItem,+): CollectionType | null {+ if (isCollectionWithType(item)) {+ return item.type;+ }+ return null;+}++const namespaceMap: Record<string, CollectionNamespace[]> = {+ normal: [null, "analytics", "shared-tenant-collection", "tenant-specific"],+ snippet: ["snippets"],+ transform: ["transforms"],+};++export const getNamespacesFromModels = (+ models: OmniPickerItem["model"][],+): CollectionNamespace[] => {+ const modelNamespaces: CollectionNamespace[] = [];+ if (models.includes("snippet")) {+ modelNamespaces.push(...namespaceMap.snippet);+ }++ if (models.includes("transform")) {+ modelNamespaces.push(...namespaceMap.transform);+ }++ if (models.some((model) => model !== "snippet" && model !== "transform")) {+ modelNamespaces.push(...namespaceMap.normal);+ }++ return modelNamespaces;+};++export const getValidNamespaces = (+ movingItem?: OmniPickerCollectionItem,+): CollectionNamespace[] => {+ if (!movingItem) {+ return namespaceMap.normal;+ }++ if (movingItem.model === "collection") {+ // collections cannot move between namespaces+ return [movingItem.namespace ?? null];+ }++ if (movingItem.namespace === "snippets") {+ return namespaceMap.snippet;+ }++ if (movingItem.namespace === "transforms") {+ return namespaceMap.transform;+ }++ return namespaceMap.normal;+};++export const isInRecentsOrSearch = (path: OmniPickerItem[]) => {+ return (+ path[0] && (path[0].id === "recents" || path[0].id === "search-results")+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.unit.spec.tsnew file mode 100644index 00000000000..16e9e2a1804--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.unit.spec.ts@@ -0,0 +1,410 @@+import { getIcon } from "metabase/lib/icon";+import type { CollectionItemModel } from "metabase-types/api";++import {+ type EntityPickerProps,+ type OmniPickerCollectionItem,+ OmniPickerFolderModel,+ type OmniPickerItem,+} from "./types";+import {+ getCollectionType,+ getEntityPickerIcon,+ getItemFunctions,+ getNamespacesFromModels,+ getValidCollectionItemModels,+ isSelectedItem,+} from "./utils";++jest.mock("metabase/lib/icon", () => ({+ getIcon: jest.fn(),+}));++describe("EntityPicker utils", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe("getEntityPickerIcon", () => {+ it("should return the icon from getIcon", () => {+ (getIcon as jest.Mock).mockReturnValue({+ name: "table",+ color: "text-dark",+ });+ const item = { id: 1, model: "table" } as OmniPickerItem;+ const result = getEntityPickerIcon(item);+ expect(result).toEqual({+ name: "table",+ c: "text-dark",+ color: undefined,+ });+ expect(getIcon).toHaveBeenCalledWith(item, { isTenantUser: undefined });+ });++ it("should set color to text-primary-inverse if selected and no color present", () => {+ (getIcon as jest.Mock).mockReturnValue({ name: "table" });+ const item = { id: 1, model: "table" } as OmniPickerItem;+ const result = getEntityPickerIcon(item, { isSelected: true });+ expect(result).toEqual({+ name: "table",+ c: "text-primary-inverse",+ color: undefined,+ });+ });++ it("should change folder icon to folder_filled if selected", () => {+ (getIcon as jest.Mock).mockReturnValue({+ name: "folder",+ color: "text-yellow",+ });+ const item = { id: 1, model: "collection" } as OmniPickerItem;+ const result = getEntityPickerIcon(item, { isSelected: true });+ expect(result).toEqual({+ name: "folder_filled",+ c: "text-yellow",+ color: undefined,+ });+ });+ });++ describe("isSelectedItem", () => {+ it("should return true if items match id and model", () => {+ const item1 = { id: 1, model: "table" } as OmniPickerItem;+ const item2 = { id: 1, model: "table" } as OmniPickerItem;+ expect(isSelectedItem(item1, item2)).toBe(true);+ });++ it("should return false if items have different id", () => {+ const item1 = { id: 1, model: "table" } as OmniPickerItem;+ const item2 = { id: 2, model: "table" } as OmniPickerItem;+ expect(isSelectedItem(item1, item2)).toBe(false);+ });++ it("should return false if items have different model", () => {+ const item1 = { id: 1, model: "table" } as OmniPickerItem;+ const item2 = { id: 1, model: "database" } as OmniPickerItem;+ expect(isSelectedItem(item1, item2)).toBe(false);+ });++ it("should return false if selectedItem is null", () => {+ const item1 = { id: 1, model: "table" } as OmniPickerItem;+ expect(isSelectedItem(item1, null)).toBe(false);+ });++ it("should check namespace if present", () => {+ const item1 = {+ id: 1,+ model: "collection",+ namespace: "snippets",+ } as OmniPickerItem;+ const item2 = {+ id: 1,+ model: "collection",+ namespace: "snippets",+ } as OmniPickerItem;+ const item3 = {+ id: 1,+ model: "collection",+ namespace: undefined,+ } as OmniPickerItem;++ expect(isSelectedItem(item1, item2)).toBe(true);+ expect(isSelectedItem(item1, item3)).toBe(false);+ });+ });++ describe("getItemFunctions", () => {+ const models = ["table", "card"] as EntityPickerProps["models"];++ describe("isFolderItem", () => {+ it("should return true for Database and Schema models", () => {+ const { isFolderItem } = getItemFunctions({ models });+ expect(+ isFolderItem({+ id: 1,+ model: OmniPickerFolderModel.Database,+ } as OmniPickerItem),+ ).toBe(true);+ expect(+ isFolderItem({+ id: 1,+ model: OmniPickerFolderModel.Schema,+ } as unknown as OmniPickerItem),+ ).toBe(true);+ });++ it("should return false for invalid items", () => {+ const { isFolderItem } = getItemFunctions({ models });+ expect(isFolderItem(null as any)).toBe(false);+ expect(isFolderItem({} as any)).toBe(false);+ });++ it("should use custom isFolderItem if provided", () => {+ const customIsFolderItem = jest.fn().mockReturnValue(true);+ const { isFolderItem } = getItemFunctions({+ models,+ isFolderItem: customIsFolderItem as any,+ });++ const cardItem = { id: 1, model: "card" } as OmniPickerItem;+ const dbItem = {+ id: 1,+ model: OmniPickerFolderModel.Database,+ } as OmniPickerItem;++ // base behavior doesn't expand with permissive custom function+ expect(isFolderItem(cardItem)).toBe(false);+ expect(isFolderItem(dbItem)).toBe(true);++ // If custom returns false, it should narrow (become false)+ customIsFolderItem.mockReturnValue(false);+ expect(isFolderItem(cardItem)).toBe(false);+ expect(isFolderItem(dbItem)).toBe(false);+ });++ it("should return true for Collection if it contains allowed models", () => {+ const { isFolderItem } = getItemFunctions({ models: ["card"] });+ const item = {+ id: 1,+ model: OmniPickerFolderModel.Collection,+ here: ["card"],+ } as any;+ expect(isFolderItem(item)).toBe(true);+ });++ it("should return false for Collection if it does not contain allowed models", () => {+ const { isFolderItem } = getItemFunctions({ models: ["card"] });+ const item = {+ id: 1,+ model: OmniPickerFolderModel.Collection,+ here: ["dataset"],+ } as any;+ expect(isFolderItem(item)).toBe(false);+ });++ it("should return false for Collection if it has neither 'here' nor 'below'", () => {+ const { isFolderItem } = getItemFunctions({ models: ["card"] });+ const item = {+ id: 1,+ model: OmniPickerFolderModel.Collection,+ } as any;+ expect(isFolderItem(item)).toBe(false);+ });+ });++ describe("isSelectableItem", () => {+ it("should return true if model is in allowed models", () => {+ const { isSelectableItem } = getItemFunctions({ models: ["table"] });+ expect(+ isSelectableItem({ id: 1, model: "table" } as OmniPickerItem),+ ).toBe(true);+ });++ it("should return false for invalid items", () => {+ const { isSelectableItem } = getItemFunctions({ models: ["table"] });+ // @ts-expect-error - testing invalid item+ expect(isSelectableItem({ idx: 444 })).toBe(false);+ });++ it("should return false if model is not in allowed models", () => {+ const { isSelectableItem } = getItemFunctions({ models: ["table"] });+ expect(+ isSelectableItem({ id: 1, model: "card" } as OmniPickerItem),+ ).toBe(false);+ });++ it("should use custom isSelectableItem if provided", () => {+ const customIsSelectableItem = jest.fn().mockReturnValue(true);+ const { isSelectableItem } = getItemFunctions({+ models: ["table"],+ isSelectableItem: customIsSelectableItem,+ });++ const dashboardItem = { id: 1, model: "dashboard" } as OmniPickerItem;+ const tableItem = { id: 1, model: "table" } as OmniPickerItem;++ // When the function is permissive, base behavior applies+ expect(isSelectableItem(dashboardItem)).toBe(false);+ expect(isSelectableItem(tableItem)).toBe(true);++ // If custom returns false, it should narrow, not expand+ customIsSelectableItem.mockReturnValue(false);+ expect(isSelectableItem(dashboardItem)).toBe(false);+ expect(isSelectableItem(tableItem)).toBe(false);+ });+ });++ describe("isHiddenItem", () => {+ it("should return true for invalid items", () => {+ const { isHiddenItem } = getItemFunctions({ models: [] });+ expect(isHiddenItem(null as any)).toBe(true);+ });++ it("should use custom isHiddenItem if provided", () => {+ const customIsHiddenItem = jest.fn().mockReturnValue(false);+ const { isHiddenItem } = getItemFunctions({+ models: ["table"],+ isHiddenItem: customIsHiddenItem,+ });++ const tableItem = { id: 1, model: "table" } as OmniPickerItem;+ const cardItem = { id: 1, model: "card" } as OmniPickerItem;++ // base behavior not modified by permissive custom function+ expect(isHiddenItem(tableItem)).toBe(false);+ expect(isHiddenItem(cardItem)).toBe(true);++ // If custom returns true, it narrow what is shown+ customIsHiddenItem.mockReturnValue(true);+ expect(isHiddenItem(tableItem)).toBe(true);+ expect(isHiddenItem(cardItem)).toBe(true);+ });++ it("should return true if item is neither selectable nor a folder", () => {+ const { isHiddenItem } = getItemFunctions({ models: ["table"] });+ // "card" is not in models, and not a folder model+ const item = { id: 1, model: "card" } as OmniPickerItem;+ expect(isHiddenItem(item)).toBe(true);+ });++ it("should return false if item is selectable", () => {+ const { isHiddenItem } = getItemFunctions({ models: ["table"] });+ const item = { id: 1, model: "table" } as OmniPickerItem;+ expect(isHiddenItem(item)).toBe(false);+ });++ it("should return false if item is a folder", () => {+ const { isHiddenItem } = getItemFunctions({ models: ["table"] });+ const item = {+ id: 1,+ model: OmniPickerFolderModel.Database,+ } as OmniPickerItem;+ expect(isHiddenItem(item)).toBe(false);+ });+ });++ describe("isDisabledItem", () => {+ it("should return true for invalid items", () => {+ const { isDisabledItem } = getItemFunctions({ models: [] });+ // @ts-expect-error: testing invalid item+ expect(isDisabledItem({ idx: 123, modelx: "foo" })).toBe(true);+ });++ it("should return false for valid items", () => {+ const { isDisabledItem } = getItemFunctions({ models: [] });+ const item = { id: 1, model: "card" } as OmniPickerItem;+ expect(isDisabledItem(item)).toBe(false);+ });++ it("should use custom isDisabledItem if provided", () => {+ const customIsDisabledItem = jest.fn().mockReturnValue(false);++ const { isDisabledItem } = getItemFunctions({+ models: ["card"],+ isDisabledItem: customIsDisabledItem,+ });++ // @ts-expect-error: testing invalid item+ const invalidItem = { idx: 1, model: "dashboard" } as OmniPickerItem;+ const validItem = { id: 1, model: "card" } as OmniPickerItem;++ // doesn't validate invalid item+ expect(isDisabledItem(invalidItem)).toBe(true);+ expect(isDisabledItem(validItem)).toBe(false);++ // change mock to return true+ customIsDisabledItem.mockReturnValue(true);++ // still rejects invalid item+ expect(isDisabledItem(invalidItem)).toBe(true);++ // now valid item is also disabled+ expect(isDisabledItem(validItem)).toBe(true);+ });+ });+ });++ describe("getValidCollectionItemModels", () => {+ it("should filter valid collection models and append 'collection'", () => {+ const input = [+ "card",+ "dashboard",+ "pikachu",+ "table",+ "transform",+ "snippet",+ "",+ ];+ const result = getValidCollectionItemModels(+ input as CollectionItemModel[],+ );+ expect(result).toEqual([+ "card",+ "dashboard",+ "table",+ "transform",+ "snippet",+ "collection",+ ]);+ });+ });++ describe("getCollectionType", () => {+ const baseCollection: OmniPickerCollectionItem = {+ id: 111,+ model: "collection",+ name: "Test Collection",+ };++ it("should return type if present", () => {+ const item: OmniPickerCollectionItem = {+ ...baseCollection,+ type: "trash",+ };+ expect(getCollectionType(item)).toBe("trash");+ });++ it("should return null if not present", () => {+ const item = {} as any;+ expect(getCollectionType(item)).toBeNull();+ });+ });++ describe("getNamespacesFromModels", () => {+ it("should return snippet namespace if snippet model is present", () => {+ expect(getNamespacesFromModels(["snippet"])).toContain("snippets");+ });++ it("should return transform namespace if transform model is present", () => {+ expect(getNamespacesFromModels(["transform"])).toContain("transforms");+ });++ it("should return normal namespaces for other models", () => {+ const namespaces = getNamespacesFromModels(["card"]);+ expect(namespaces).toContain(null);+ expect(namespaces).toContain("analytics");+ });++ it("should combine namespaces", () => {+ const namespaces = getNamespacesFromModels(["snippet", "card"]);+ expect(namespaces).toContain("snippets");+ expect(namespaces).toContain(null);+ });++ it("should combine all namespaces", () => {+ const namespaces = getNamespacesFromModels([+ "snippet",+ "transform",+ "card",+ ]);+ expect(namespaces).toEqual([+ "snippets",+ "transforms",+ null,+ "analytics",+ "shared-tenant-collection",+ "tenant-specific",+ ]);+ });+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/MiniPicker.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/MiniPicker.tsxindex 2d62df0fd38..41081d44153 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/MiniPicker.tsx+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/MiniPicker.tsx@@ -3,8 +3,8 @@ import { useCallback, useEffect, useMemo } from "react";import { PLUGIN_DATA_STUDIO } from "metabase/plugins";import { Box, Menu } from "metabase/ui";-import { useLogRecentItem } from "../../../../EntityPicker/hooks/use-log-recent-item";import type { DataPickerValue } from "../../../DataPicker";+import { useLogRecentItem } from "../../../EntityPicker/hooks/use-log-recent-item";import { MiniPickerContext } from "../../context";import type { MiniPickerItem, MiniPickerPickableItem } from "../../types";import {diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsxindex 9fe110e21f4..533e4870db1 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsx+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsx@@ -115,6 +115,7 @@ describe("MiniPicker", () => {value: {model: "table",id: 4,+ // @ts-expect-error - needed to make compatible with minipicker and entity pickerdb_id: 1,schema: "pokemon",name: "cards",@@ -194,7 +195,6 @@ describe("MiniPicker", () => {value: {id: 202,model: "card",- name: "Rosings",database_id: 1,},});diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsxindex cbd600ee364..7711bf178a2 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx@@ -303,6 +303,7 @@ function SearchItemList({ query }: { query: string }) {q: debouncedQuery,models: models as SearchModel[],limit: 50,+ // FIXME: optionally pass table_db_id so we filter on the backend to valid joins});const searchResults: MiniPickerPickableItem[] = (diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.tsindex 58f19283adc..bfe8def0133 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts@@ -8,7 +8,6 @@ import { useDispatch } from "metabase/lib/redux";import type { SchemaName } from "metabase-types/api";import type { DataPickerValue } from "../DataPicker";-import type { TablePickerValue } from "../TablePicker";import {type MiniPickerCollectionItem,@@ -16,6 +15,7 @@ import {MiniPickerFolderModel,type MiniPickerItem,type MiniPickerPickableItem,+ type MiniPickerTableItem,} from "./types";export const getOurAnalytics = (): MiniPickerFolderItem => ({@@ -66,13 +66,21 @@ async function getPathFromValue(const table = await dispatch(tableApi.endpoints.getTable.initiate({ id: value.id }),).unwrap();+return table.collection == null- ? getTablePathFromValue(value, dispatch)+ ? getTablePathFromValue(+ {+ ...table,+ model: "table",+ table_schema: table.schema,+ },+ dispatch,+ ): getCollectionPathFromValue(value, dispatch, libraryCollection);}async function getTablePathFromValue(- value: TablePickerValue,+ value: MiniPickerTableItem,dispatch: DispatchFn,): Promise<MiniPickerFolderItem[]> {// get the list endpoints instead of the single table endpoint@@ -89,7 +97,7 @@ async function getTablePathFromValue(const db = dbs.data.find((db) => db.id === value.db_id);const schema: SchemaName | undefined =schemas?.length > 1- ? schemas.find((sch) => sch === value.schema)+ ? schemas.find((sch) => sch === value.table_schema): undefined;return [...(db ? [{ id: db.id, name: db.name, model: "database" as const }] : []),@@ -113,7 +121,7 @@ async function getCollectionPathFromValue(const card =value.model !== "table"? await dispatch(- cardApi.endpoints.getCard.initiate({ id: value.id }),+ cardApi.endpoints.getCard.initiate({ id: Number(value.id) }),).unwrap(): null;diff --git a/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.tsx b/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.tsxnew file mode 100644index 00000000000..d91d442534c--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/MoveModal/MoveModal.tsx@@ -0,0 +1,367 @@+import { useCallback } from "react";+import { t } from "ttag";+import _ from "underscore";++import type {+ MoveCollectionDestination,+ MoveDestination,+ OnMoveWithOneItem,+} from "metabase/collections/types";+import {+ canPlaceEntityInCollection,+ canPlaceEntityInCollectionOrDescendants,+ isItemCollection,+} from "metabase/collections/utils";+import {+ EntityPickerModal,+ isInDbTree,+} from "metabase/common/components/Pickers";+import { isItemInCollectionOrItsDescendants } from "metabase/common/components/Pickers/utils";+import { PLUGIN_TENANTS } from "metabase/plugins";+import type { CollectionId, CollectionItem } from "metabase-types/api";++import type {+ EntityPickerModalProps,+ OmniPickerCollectionItem,+ OmniPickerItem,+} from "../EntityPicker";+import { getCollectionType, getValidNamespaces } from "../EntityPicker/utils";++interface BaseMoveModalProps {+ title: string;+ onClose: () => void;+ movingItem: OmniPickerCollectionItem;+ isDisabledItem?: (item: OmniPickerCollectionItem) => boolean;+}++type MoveModalProps =+ | (BaseMoveModalProps & {+ canMoveToDashboard?: true | undefined;+ onMove: OnMoveWithOneItem;+ })+ | (BaseMoveModalProps & {+ canMoveToDashboard?: false;+ onMove: OnMoveWithOneItem<MoveCollectionDestination>;+ });++export const MoveModal = ({+ title,+ onClose,+ onMove,+ movingItem,+ canMoveToDashboard,+ isDisabledItem,+}: MoveModalProps) => {+ const shouldDisableItem = useCallback(+ (item: OmniPickerItem): boolean => {+ if (!movingItem) {+ return false;+ }++ if (isInDbTree(item)) {+ return true;+ }++ if (movingItem.model === "collection") {+ // can't move a collection into itself or its descendants+ if (isItemInCollectionOrItsDescendants(item, movingItem.id)) {+ return true;+ }+ }++ if (item.model === "collection") {+ return !canPlaceEntityInCollectionOrDescendants(+ movingItem.model,+ getCollectionType(item),+ );+ }++ if (+ !isInDbTree(item) &&+ !isInDbTree(movingItem) &&+ item.namespace &&+ movingItem.namespace+ ) {+ // collections cannot move between namespaces+ return item.namespace !== movingItem.namespace;+ }++ if (isDisabledItem) {+ return isDisabledItem(item as OmniPickerCollectionItem);+ }++ return false;+ },+ [movingItem, isDisabledItem],+ );++ const canSelectItem = useCallback(+ (item: OmniPickerItem): boolean => {+ if (isInDbTree(item)) {+ return false;+ }++ if (shouldDisableItem(item)) {+ return false;+ }++ if (+ !PLUGIN_TENANTS.canPlaceEntityInCollection({+ entityType: movingItem.model,+ collection: item,+ })+ ) {+ return false;+ }++ if (isSameDestination(movingItem, item)) {+ return false;+ }++ return true;+ },+ [movingItem, shouldDisableItem],+ );++ const handleMove = useCallback(+ (destination: OmniPickerItem) => {+ // GROSS:+ // - CollectionPicker's `onChange` prop isn't generic to its `models` prop, so+ // `onChange`'s destination arg isn't narrowed based on the `models` passed in. This+ // requires we do additional type guarding / unneeded error handling below.+ // - To keep this same issue from bubbling up to consumers of MoveModal, we need+ // do some extra type casting so it has an external API where `canMoveToDashboard`+ // narrows the `destination` arg for its `onMove` prop.+ // - Making CollectionPicker properly generic is hard due to some internal typing+ // being used by components other than the CollectionPicker. One type+ // cast here avoids a large headache-inducing refactor there.++ if (+ destination.model !== "collection" &&+ destination.model !== "dashboard"+ ) {+ throw new Error("MoveModal can only move to collections or dashboards");+ }++ if (!canMoveToDashboard) {+ if (destination.model === "dashboard") {+ throw new Error(+ "MoveModal can't move to a dashboard with canMoveToDashboard=false",+ );+ }++ return onMove({ id: destination.id, model: destination.model });+ } else {+ return onMove({+ id: destination.id,+ model: destination.model,+ } as MoveDestination);+ }+ },+ [onMove, canMoveToDashboard],+ );++ const models: ("dashboard" | "collection")[] = canMoveToDashboard+ ? ["collection", "dashboard"]+ : ["collection"];++ return (+ <EntityPickerModal+ title={title}+ value={{+ id: movingItem?.collection?.id || "root", // start with the current parent+ model: "collection",+ namespace: movingItem?.collection?.namespace,+ }}+ onChange={handleMove}+ models={models}+ namespaces={getValidNamespaces(movingItem)}+ options={{+ hasSearch: true,+ hasRecents: true,+ hasLibrary: true,+ hasRootCollection: true,+ hasConfirmButtons: true,+ canCreateCollections: true,+ hasPersonalCollections: true,+ confirmButtonText: t`Move`,+ }}+ isDisabledItem={shouldDisableItem}+ isSelectableItem={canSelectItem}+ onClose={onClose}+ />+ );+};++interface BulkMoveModalProps {+ onClose: () => void;+ onMove: OnMoveWithOneItem<MoveDestination>;+ selectedItems: CollectionItem[];+ initialCollectionId: CollectionId;+ recentAndSearchFilter?: (item: OmniPickerItem) => boolean;+}++export const BulkMoveModal = ({+ onClose,+ onMove,+ selectedItems,+ initialCollectionId,+}: BulkMoveModalProps) => {+ const movingCollectionIds = selectedItems+ .filter((item: OmniPickerCollectionItem) => isItemCollection(item))+ .map((item: OmniPickerCollectionItem) => String(item.id));++ const shouldDisableItem = useCallback(+ (item: OmniPickerItem): boolean => {+ if (isInDbTree(item)) {+ return true;+ }++ if (movingCollectionIds.length > 0) {+ const collectionItemFullPath =+ (item?.effective_location ?? item?.location)+ ?.split("/")+ .map(String)+ .concat(String(item.id)) ?? [];+ if (+ _.intersection(collectionItemFullPath, movingCollectionIds).length > 0+ ) {+ return true;+ }+ }++ if (item.model === "collection") {+ const hasInvalidItem = selectedItems.some(+ (selectedItem) =>+ !canPlaceEntityInCollectionOrDescendants(+ selectedItem.model,+ getCollectionType(item),+ ),+ );+ if (hasInvalidItem) {+ return true;+ }+ }++ return false;+ },+ [selectedItems, movingCollectionIds],+ );++ const canSelectItem = useCallback(+ (item: OmniPickerItem): boolean => {+ if (isInDbTree(item)) {+ return false;+ }+ if (shouldDisableItem(item)) {+ return false;+ }++ if (+ !selectedItems.every((item) =>+ PLUGIN_TENANTS.canPlaceEntityInCollection({+ entityType: item.model,+ collection: item,+ }),+ )+ ) {+ return false;+ }++ if (isSameDestination(selectedItems[0], item)) {+ return false;+ }++ return true;+ },+ [selectedItems, shouldDisableItem],+ );++ const title =+ selectedItems.length > 1+ ? t`Move ${selectedItems.length} items?`+ : t`Move "${selectedItems[0].name}"?`;++ const canMoveToDashboard = selectedItems.every(+ (item) => item.model === "card",+ );++ const models: EntityPickerModalProps["models"] = canMoveToDashboard+ ? ["collection", "dashboard"]+ : ["collection"];++ const shouldHideItem = useCallback(+ (item: OmniPickerItem) => {+ if (item.model === "collection") {+ return !selectedItems.every((selectedItem) =>+ canPlaceEntityInCollection(+ selectedItem.model,+ getCollectionType(item),+ ),+ );+ }+ return false;+ },+ [selectedItems],+ );++ const handleMove = useCallback(+ async (destination: OmniPickerItem) => {+ return onMove({+ id: destination.id,+ model: destination.model,+ } as MoveDestination);+ },+ [onMove],+ );++ const namespaces = getValidNamespaces(selectedItems[0]);+ const initialNamespace =+ selectedItems[0].namespace ?? selectedItems[0].collection_namespace;++ return (+ <EntityPickerModal+ title={title}+ value={{+ id: initialCollectionId,+ model: "collection",+ namespace: initialNamespace,+ }}+ onChange={handleMove}+ models={models}+ namespaces={namespaces}+ options={{+ hasSearch: true,+ hasRecents: true,+ hasRootCollection: true,+ hasConfirmButtons: true,+ canCreateCollections: true,+ confirmButtonText: t`Move`,+ }}+ isDisabledItem={shouldDisableItem}+ isSelectableItem={canSelectItem}+ isHiddenItem={shouldHideItem}+ onClose={onClose}+ />+ );+};++const isSameDestination = (+ movingItem: OmniPickerCollectionItem,+ movingTarget: OmniPickerCollectionItem,+) => {+ if (+ movingTarget.model === "dashboard" &&+ movingItem.dashboard_id === movingTarget.id+ ) {+ return true;+ }++ if (+ movingTarget.model === "collection" &&+ movingItem.collection?.id === movingTarget.id+ ) {+ return true;+ }+ return false;+};diff --git a/frontend/src/metabase/common/components/Pickers/MoveModal/index.ts b/frontend/src/metabase/common/components/Pickers/MoveModal/index.tsnew file mode 100644index 00000000000..42a1822e1a8--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/MoveModal/index.ts@@ -0,0 +1 @@+export * from "./MoveModal";diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/QuestionPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/QuestionPickerModal.tsxnew file mode 100644index 00000000000..1216486d265--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/QuestionPickerModal.tsx@@ -0,0 +1,72 @@+import { useCallback } from "react";+import { t } from "ttag";++import {+ EntityPickerModal,+ type EntityPickerModalProps,+ type OmniPickerItem,+ type OmniPickerQuestionItem,+} from "../EntityPicker";++const canSelectItem = (+ item: OmniPickerItem | null,+): item is OmniPickerQuestionItem => {+ return !!(+ item != null &&+ item.id &&+ (item.model === "card" ||+ item.model === "dataset" ||+ item.model === "metric")+ );+};++export type QuestionPickerModalProps = Omit<+ EntityPickerModalProps,+ "models" | "onChange"+> & {+ // you can pass dashboard as a model to allow picking questions within dashboards+ // but dashboards will never be a finally pickable item+ models?: (OmniPickerQuestionItem["model"] | "dashboard")[];+ onChange: (item: OmniPickerQuestionItem) => void;+};++export const QuestionPickerModal = ({+ title = t`Choose a question or model`,+ onChange,+ value = { model: "collection", id: "root" },+ options = {},+ models = ["card", "dataset"],+ ...props+}: QuestionPickerModalProps) => {+ const handleChange = useCallback(+ (item: OmniPickerItem) => {+ if (canSelectItem(item)) {+ onChange(item);+ }+ },+ [onChange],+ );++ const isSelectableItem = (item: OmniPickerItem) => {+ return canSelectItem(item);+ };++ return (+ <EntityPickerModal+ title={title}+ onChange={handleChange}+ value={value}+ models={models}+ options={options}+ searchParams={+ options.hasRootCollection === false+ ? { filter_items_in_personal_collection: "only" }+ : options.hasPersonalCollections === false+ ? { filter_items_in_personal_collection: "exclude" }+ : undefined+ }+ isSelectableItem={isSelectableItem}+ {...props}+ />+ );+};diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/QuestionPicker.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/QuestionPicker.tsxdeleted file mode 100644index 87a524ee0ed..00000000000--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/QuestionPicker.tsx+++ /dev/null@@ -1,238 +0,0 @@-import { useCallback, useMemo } from "react";-import { useDeepCompareEffect } from "react-use";--import { useSelector } from "metabase/lib/redux";-import { PLUGIN_TENANTS } from "metabase/plugins";-import { getUserPersonalCollectionId } from "metabase/selectors/user";--import {- DelayedLoadingSpinner,- NestedItemPicker,-} from "../../../../EntityPicker";-import { useEnsureCollectionSelected } from "../../../CollectionPicker";-import { CollectionItemPickerResolver } from "../../../CollectionPicker/components/CollectionItemPickerResolver";-import { getPathLevelForItem } from "../../../CollectionPicker/utils";-import {- type TablePickerItem,- type TablePickerStatePath,- type TablePickerValue,- isTablePickerValue,-} from "../../../TablePicker";-import { useGetInitialContainer } from "../../../hooks";-import { getCollectionIdPath, getStateFromIdPath } from "../../../utils";-import type {- QuestionPickerItem,- QuestionPickerModel,- QuestionPickerOptions,- QuestionPickerStatePath,-} from "../../types";-import {- getQuestionPickerValueModel,- isFolder,- isTablePickerFolderOrQuestionPickerFolder,-} from "../../utils";--export const defaultOptions: QuestionPickerOptions = {- showPersonalCollections: true,- showRootCollection: true,- hasConfirmButtons: false,-};--interface QuestionPickerProps {- initialValue?: Pick<QuestionPickerItem, "model" | "id"> | TablePickerValue;- models?: QuestionPickerModel[];- options: QuestionPickerOptions;- path: QuestionPickerStatePath | undefined;- tablesPath?: TablePickerStatePath;- shouldShowItem?: (item: QuestionPickerItem) => boolean;- onInit: (item: QuestionPickerItem) => void;- onItemSelect: (item: QuestionPickerItem) => void;- onPathChange: (path: QuestionPickerStatePath) => void;- onTablesPathChange?: (path: TablePickerStatePath) => void;- shouldDisableItem?: (- item: QuestionPickerItem,- models?: QuestionPickerModel[],- ) => boolean;-}--export const QuestionPicker = ({- initialValue,- models = ["dataset", "card"],- options,- path: pathProp,- tablesPath,- shouldShowItem,- onInit,- onItemSelect,- onPathChange,- onTablesPathChange,- shouldDisableItem,-}: QuestionPickerProps) => {- const defaultPath = useMemo(() => {- return getStateFromIdPath({- idPath: ["root"],- models,- });- }, [models]);- const path = pathProp ?? defaultPath;-- const {- currentTable,- currentQuestion,- currentCollection,- currentDashboard,- isLoading,- } = useGetInitialContainer(initialValue);-- const userPersonalCollectionId = useSelector(getUserPersonalCollectionId);-- const onFolderSelect = useCallback(- ({ folder }: { folder: QuestionPickerItem }) => {- onItemSelect(folder);-- //if it's actually a folder- if (isFolder(folder, models)) {- const newPath = getStateFromIdPath({- idPath: getCollectionIdPath(folder, userPersonalCollectionId),- models: models,- });-- onPathChange(newPath);- }- },- [onItemSelect, onPathChange, userPersonalCollectionId, models],- );-- const handleItemSelect = useCallback(- (item: QuestionPickerItem) => {- // set selected item at the correct level- const pathLevel = getPathLevelForItem(- item,- path,- userPersonalCollectionId,- );-- const newPath = path.slice(0, pathLevel + 1);- newPath[newPath.length - 1].selectedItem = item;- onItemSelect(item);- onPathChange(newPath);- },- [onItemSelect, onPathChange, path, userPersonalCollectionId],- );-- useDeepCompareEffect(- function setInitialPath() {- if (currentDashboard?.id) {- const location =- currentDashboard.collection_id === null- ? "/"- : `${currentDashboard.collection?.location ?? ""}${currentDashboard.collection?.id ?? ""}/`;-- const idPath = getCollectionIdPath(- {- ...currentDashboard,- model: "dashboard",- location,- is_tenant_dashboard: PLUGIN_TENANTS.isTenantNamespace(- currentDashboard?.collection?.namespace,- ),- },- userPersonalCollectionId,- );-- const newPath = getStateFromIdPath({- idPath,- models,- });-- // start with the current item selected if we can- newPath[newPath.length - 1].selectedItem = currentQuestion- ? {- id: currentQuestion.id,- name: currentQuestion.name,- model: getQuestionPickerValueModel(currentQuestion.type),- }- : {- id: currentDashboard.id,- name: currentDashboard.name,- model: "dashboard",- };-- onPathChange(newPath);- } else if (currentCollection?.id) {- const newPath = getStateFromIdPath({- idPath: getCollectionIdPath(- { ...currentCollection, model: "collection" },- userPersonalCollectionId,- ),- models,- });-- // start with the current item selected if we can- const newSelectedItem: QuestionPickerItem = currentTable- ? {- id: currentTable.id,- name: currentTable.display_name,- model: "table",- }- : currentQuestion- ? {- id: currentQuestion.id,- name: currentQuestion.name,- model: getQuestionPickerValueModel(currentQuestion.type),- }- : {- id: currentCollection.id,- name: currentCollection.name,- model: "collection",- };-- newPath[newPath.length - 1].selectedItem = newSelectedItem;-- onPathChange(newPath);- }- },- [- currentDashboard,- currentCollection,- userPersonalCollectionId,- onPathChange,- models,- ],- );-- useEnsureCollectionSelected({- currentCollection,- currentDashboard,- enabled: path === defaultPath,- options,- useRootCollection: initialValue?.id == null,- onInit,- });-- if (isLoading) {- return <DelayedLoadingSpinner />;- }-- return (- <NestedItemPicker- initialValue={isTablePickerValue(initialValue) ? initialValue : undefined}- isFolder={(item: QuestionPickerItem | TablePickerItem) =>- isTablePickerFolderOrQuestionPickerFolder(item, models)- }- options={options}- onFolderSelect={onFolderSelect}- onItemSelect={handleItemSelect}- path={path}- listResolver={CollectionItemPickerResolver}- shouldShowItem={shouldShowItem}- shouldDisableItem={- shouldDisableItem- ? (item) => shouldDisableItem(item, models)- : undefined- }- tablesPath={tablesPath}- onTablesPathChange={onTablesPathChange}- />- );-};diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/index.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/index.tsdeleted file mode 100644index a438a409353..00000000000--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./QuestionPicker";diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/common.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/common.unit.spec.tsxdeleted file mode 100644index 43d70bc0ac3..00000000000--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/common.unit.spec.tsx+++ /dev/null@@ -1,323 +0,0 @@-import userEvent from "@testing-library/user-event";--import { setupSearchEndpoints } from "__support__/server-mocks";-import { screen } from "__support__/ui";--import { defaultOptions } from "../QuestionPicker";--import {- level,- myMetric,- myModel,- nestedDashboardQuestion,- nestedQuestion,- rootDashboardQuestion,- setupModal,- setupPicker,-} from "./setup";--describe("QuestionPicker", () => {- it("should select the root collection by default", async () => {- await setupPicker();-- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toBeInTheDocument();-- expect(- await screen.findByRole("link", { name: /Collection 2/ }),- ).toBeInTheDocument();- });-- it("should render the path to the collection provided", async () => {- await setupPicker({ initialValue: { id: 3, model: "collection" } });- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");- });-- describe("initial value", () => {- it("should render the path to a question in the root collection", async () => {- await setupPicker({ initialValue: { id: 104, model: "card" } });-- expect(- await (await level(0)).findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(1)).findByRole("link", { name: /Question in Root/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should render the path to a question nested in multiple collections", async () => {- await setupPicker({- initialValue: { id: 100, model: "card" },- });-- expect(- await (await level(0)).findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(1)).findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(2)).findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");-- // question itself should start selected- expect(- await (await level(3)).findByRole("link", { name: /Nested Question/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should render the path to a dashboard question where dashboard is in the root collection", async () => {- await setupPicker({- initialValue: { id: rootDashboardQuestion.id, model: "card" },- });-- expect(- await (await level(0)).findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(1)).findByRole("link", { name: /Root Dashboard/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(2)).findByRole("link", { name: /DQ in Root/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should render the path to a dashboard question in a nested collection", async () => {- await setupPicker({- initialValue: { id: nestedDashboardQuestion.id, model: "card" },- });-- expect(- await (await level(0)).findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(1)).findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(2)).findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(3)).findByRole("link", { name: /Nested Dashboard/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(4)).findByRole("link", { name: /Nested DQ/ }),- ).toHaveAttribute("data-active", "true");- });- });-});--describe("QuestionPickerModal", () => {- it("should render the modal", async () => {- await setupModal();-- expect(- await screen.findByText(/choose a question or model/i),- ).toBeInTheDocument();- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();-- expect(- screen.queryByRole("button", { name: /Select/ }),- ).not.toBeInTheDocument();- });-- it("should render the modal with a select button", async () => {- await setupModal({- options: { ...defaultOptions, hasConfirmButtons: true },- });-- expect(- await screen.findByText(/choose a question or model/i),- ).toBeInTheDocument();- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();- expect(- await screen.findByRole("button", { name: /Select/ }),- ).toBeInTheDocument();- });-- it("should render model and question tabs by default", async () => {- await setupModal();-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toBeInTheDocument();- expect(- await screen.findByRole("tab", { name: /Models/ }),- ).toBeInTheDocument();- });-- it("should render the metric tab if explicitly enabled", async () => {- await setupModal({ models: ["card", "dataset", "metric"] });-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toBeInTheDocument();- expect(- await screen.findByRole("tab", { name: /Models/ }),- ).toBeInTheDocument();- expect(- await screen.findByRole("tab", { name: /Metrics/ }),- ).toBeInTheDocument();- });-- it("can render a single tab (which hides the tab bar)", async () => {- await setupModal({ models: ["dataset"] });-- expect(- await screen.findByText(/choose a question or model/i),- ).toBeInTheDocument();- expect(screen.queryByRole("tablist")).not.toBeInTheDocument();- expect(screen.queryByRole("tab")).not.toBeInTheDocument();- });-- it("should auto-select the question tab when a question is selected", async () => {- await setupModal({- initialValue: { id: 100, model: "card" },- });-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "true");- expect(await screen.findByRole("tab", { name: /Models/ })).toHaveAttribute(- "aria-selected",- "false",- );-- expect(- await screen.findByRole("link", { name: /Nested Question/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should auto-select the model tab when a model is selected", async () => {- await setupModal({- initialValue: { id: 101, model: "dataset" },- });-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Models/ })).toHaveAttribute(- "aria-selected",- "true",- );-- expect(- await screen.findByRole("link", { name: /My Model/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should auto-select the metric tab when a metric is selected", async () => {- await setupModal({- initialValue: { id: 102, model: "metric" },- models: ["card", "dataset", "metric"],- });-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Metrics/ })).toHaveAttribute(- "aria-selected",- "true",- );-- expect(- await screen.findByRole("link", { name: /My Metric/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should automatically switch to the search tab when a search query is provided", async () => {- setupSearchEndpoints([]);- await setupModal();-- const searchInput = await screen.findByPlaceholderText(/search/i);-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "true");-- await userEvent.type(searchInput, "sizzlipede");-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(- "aria-selected",- "true",- );-- await screen.findByText(/Didn't find anything/i);- });-- it("should switch back to the default tab when the search query is cleared", async () => {- setupSearchEndpoints([]);- await setupModal();-- const searchInput = await screen.findByPlaceholderText(/search/i);-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "true");-- await userEvent.type(searchInput, "sizzlipede");-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(- "aria-selected",- "true",- );-- await screen.findByText(/Didn't find anything/i);-- await userEvent.clear(searchInput);-- expect(- await screen.findByRole("tab", { name: /Questions/ }),- ).toHaveAttribute("aria-selected", "true");- expect(- screen.queryByRole("tab", { name: /Search/ }),- ).not.toBeInTheDocument();- });-- it("should be able to search for metrics", async () => {- await setupSearchEndpoints([nestedQuestion, myModel, myMetric]);- await setupModal({ models: ["card", "dataset", "metric"] });- // Need to wait for the collections tab to render- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();- const searchInput = await screen.findByPlaceholderText(/search/i);- await userEvent.type(searchInput, myMetric.name);- await userEvent.click(await screen.findByText("Everywhere"));- expect(await screen.findByText(myMetric.name)).toBeInTheDocument();- expect(screen.queryByText(nestedQuestion.name)).not.toBeInTheDocument();- });-});diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/enterprise.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/enterprise.unit.spec.tsdeleted file mode 100644index d3654373ec9..00000000000--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/enterprise.unit.spec.ts+++ /dev/null@@ -1,111 +0,0 @@-import userEvent from "@testing-library/user-event";--import { screen, within } from "__support__/ui";--import { level, setupPicker } from "./setup";--describe("verified questions", () => {- it("should show a verified icon when showing verified cards", async () => {- await setupPicker({- initialValue: { id: 100, model: "card" },- isEE: true,- });-- expect(- await (await level(0)).findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(1)).findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await (await level(2)).findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");-- // question itself should start selected- expect(- await (await level(3)).findByRole("link", { name: /Nested Question/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await within(- await screen.findByRole("link", { name: /My Verified Question/ }),- ).findByRole("img", { name: /verified_filled/ }),- ).toBeInTheDocument();- });-});--describe("tenant collection", () => {- it("should show tenant collections in the root panel and build a path to a dashboard", async () => {- await setupPicker({ isEE: true });-- await userEvent.click(- await screen.findByRole("link", { name: /Shared collections/ }),- );-- await userEvent.click(await screen.findByRole("link", { name: /tcoll/ }));-- await userEvent.click(- await screen.findByRole("link", { name: /tsubcoll/ }),- );-- expect(- await screen.findByRole("link", { name: /Tenant Question/ }),- ).toBeInTheDocument();- });-- it("should handle a tenant question as an initial value", async () => {- await setupPicker({- initialValue: {- model: "card",- id: 110,- },- isEE: true,- });-- expect(- await screen.findByRole("link", { name: /Shared collections/ }),- ).toHaveAttribute("data-active", "true");-- expect(await screen.findByRole("link", { name: /tcoll/ })).toHaveAttribute(- "data-active",- "true",- );-- expect(- await screen.findByRole("link", { name: /tsubcoll/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Tenant Question/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should handle a tenant dashboard question as an initial value", async () => {- await setupPicker({- initialValue: {- model: "card",- id: 121,- },- isEE: true,- });-- expect(- await screen.findByRole("link", { name: /Shared collections/ }),- ).toHaveAttribute("data-active", "true");-- expect(await screen.findByRole("link", { name: /tcoll/ })).toHaveAttribute(- "data-active",- "true",- );-- expect(- await screen.findByRole("link", { name: /tsubcoll/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /DQ in TenantDashboard/ }),- ).toHaveAttribute("data-active", "true");- });-});diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/setup.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/setup.tsxdeleted file mode 100644index a6ee476d41f..00000000000--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/setup.tsx+++ /dev/null@@ -1,483 +0,0 @@-import fetchMock from "fetch-mock";-import { useState } from "react";--import { setupEnterprisePlugins } from "__support__/enterprise";-import {- setupCollectionItemsEndpoint,- setupDashboardItemsEndpoint,- setupRecentViewsAndSelectionsEndpoints,- setupRootCollectionItemsEndpoint,- setupTenantCollectionItemsEndpoint,-} from "__support__/server-mocks";-import { mockSettings } from "__support__/settings";-import {- mockGetBoundingClientRect,- renderWithProviders,- screen,- waitForLoaderToBeRemoved,- within,-} from "__support__/ui";-import type { CollectionId, CollectionItem } from "metabase-types/api";-import {- createMockCard,- createMockCollection,- createMockCollectionItem,- createMockDashboard,- createMockTokenFeatures,-} from "metabase-types/api/mocks";-import { createMockState } from "metabase-types/store/mocks";--import type {- QuestionPickerItem,- QuestionPickerStatePath,- QuestionPickerValueModel,-} from "../../../types";-import { QuestionPickerModal } from "../../QuestionPickerModal";-import { QuestionPicker, defaultOptions } from "../QuestionPicker";--type NestedCollectionItem = Partial<Omit<CollectionItem, "id">> & {- id: any;- is_personal?: boolean;- descendants?: NestedCollectionItem[];- dashboard_id?: number;-};--const rootQuestion = createMockCollectionItem({- ...createMockCard({- id: 104,- name: "Question in Root",- collection_id: null,- }),- model: "card",-});--const tenantQuestion = createMockCollectionItem({- ...createMockCard({- id: 110,- name: "Tenant Question",- collection_id: 7,- }),- model: "card",-});--export const rootDashboard = createMockCollectionItem({- ...createMockDashboard({- name: "Root Dashboard",- collection_id: null,- }),- id: 105,- location: "/",- model: "dashboard",-});--export const rootDashboardQuestion = createMockCollectionItem({- ...createMockCard({- id: 111,- name: "DQ in Root",- collection_id: null,- dashboard_id: rootDashboard.id,- }),- model: "card",-});--export const nestedQuestion = createMockCollectionItem({- ...createMockCard({- id: 100,- name: "Nested Question",- collection_id: 3,- }),- model: "card",-});--const nestedDashboard = createMockCollectionItem({- ...createMockDashboard({- name: "Nested Dashboard",- collection_id: 3,- collection: createMockCollection({- id: 3,- location: "/4/",- }),- }),- location: "/4/",- id: 106,- model: "dashboard",-});--const tenantDashboard = createMockCollectionItem({- ...createMockDashboard({- name: "Tenant Dashboard",- collection_id: 7,- collection: createMockCollection({- id: 7,- location: "/6/7/",- namespace: "shared-tenant-collection",- }),- }),- location: "/6/7/",- id: 120,- model: "dashboard",- is_tenant_dashboard: true,-});--const tenantDashboardQuestion = createMockCollectionItem({- ...createMockCard({- id: 121,- name: "DQ in TenantDashboard",- collection_id: 7,- dashboard_id: tenantDashboard.id,- dashboard: tenantDashboard,- }),- model: "card",-});--export const nestedDashboardQuestion = createMockCollectionItem({- ...createMockCard({- id: 108,- name: "Nested DQ",- collection_id: 3,- dashboard_id: nestedDashboard.id,- dashboard: nestedDashboard,- }),- model: "card",-});--const myVerifiedQuestion = createMockCollectionItem({- ...createMockCard({- id: 103,- name: "My Verified Question",- collection_id: 3,- }),- moderated_status: "verified",-});--export const myModel = createMockCollectionItem({- ...createMockCard({- id: 101,- name: "My Model",- collection_id: 3,- type: "model",- }),- model: "dataset",-});--export const myMetric = createMockCollectionItem({- ...createMockCard({- id: 102,- name: "My Metric",- collection_id: 3,- type: "metric",- }),- model: "metric",-});--const collectionTree: NestedCollectionItem[] = [- {- id: "root" as any,- model: "collection",- name: "Our Analytics",- location: "",- can_write: true,- descendants: [- {- id: 4,- name: "Collection 4",- model: "collection",- location: "/",- can_write: true,- descendants: [- {- id: 3,- name: "Collection 3",- model: "collection",- descendants: [- nestedQuestion,- nestedDashboard,- nestedDashboardQuestion,- myModel,- myMetric,- myVerifiedQuestion,- ],- location: "/4/",- can_write: true,- is_personal: false,- },- ],- },- {- id: 2,- model: "collection",- is_personal: false,- name: "Collection 2",- location: "/",- can_write: true,- descendants: [],- },- rootQuestion,- rootDashboard,- rootDashboardQuestion,- ],- },- {- name: "My personal collection",- id: 1,- model: "collection",- location: "/",- is_personal: true,- can_write: true,- descendants: [- {- id: 5,- model: "collection",- location: "/1/",- name: "personal sub_collection",- is_personal: true,- can_write: true,- descendants: [],- },- ],- },-];--const tenantCollectionsTree: NestedCollectionItem[] = [- {- name: "tcoll",- id: 6,- location: "/",- effective_location: "/",- is_personal: false,- is_shared_tenant_collection: true,- model: "collection",- here: ["collection"],- below: ["card", "dashboard"],- can_write: true,- descendants: [- {- id: 7,- location: "/6/",- effective_location: "/6/",- name: "tsubcoll",- model: "collection",- is_personal: false,- is_shared_tenant_collection: true,- can_write: true,- descendants: [tenantQuestion, tenantDashboard, tenantDashboardQuestion],- here: ["card", "dashboard"],- },- ],- },-];--const flattenCollectionTree = (- nodes: NestedCollectionItem[],-): Omit<NestedCollectionItem, "descendants">[] => {- if (!nodes) {- return [];- }- return nodes.flatMap(({ descendants = [], ...node }) => [- node,- ...flattenCollectionTree(descendants),- ]);-};--const mockCollectionToCollectionItem = (c: NestedCollectionItem) =>- createMockCollectionItem({- ...c,- ...(c.is_shared_tenant_collection && {- namespace: "shared-tenant-collection",- }),- });--const setupCollectionTreeMocks = (node: NestedCollectionItem[]) => {- node.forEach((node) => {- if (!node.descendants) {- return;- }- const collectionItems = node.descendants- .filter((item) => !item.dashboard_id) //We don't show dashboard items in collection item endpoints- .map((c: NestedCollectionItem) => createMockCollectionItem(c));-- // Skip root since it's handled separately (tenant-aware)- if (node.id !== "root") {- setupCollectionItemsEndpoint({- collection: createMockCollection({ id: node.id }),- collectionItems,- });- }-- if (collectionItems.length > 0) {- setupCollectionTreeMocks(node.descendants);- }- });-};--const setupTenantCollectionTreeMocks = (node: NestedCollectionItem[]): void => {- node.forEach((n) => {- if (!n.descendants) {- return;- }- const collectionItems = n.descendants- .filter((item) => !item.dashboard_id) //We don't show dashboard items in collection item endpoints- .map((c: NestedCollectionItem) => mockCollectionToCollectionItem(c));-- setupTenantCollectionItemsEndpoint({- collection: createMockCollection({ id: n.id }),- collectionItems,- });-- if (collectionItems.length > 0) {- setupTenantCollectionTreeMocks(n.descendants);- }- });-};--interface SetupOpts {- initialValue?: {- id: CollectionId;- model: "collection" | "card" | "dataset" | "metric";- };- onChange?: (item: QuestionPickerItem) => void;- models?: [QuestionPickerValueModel, ...QuestionPickerValueModel[]];- options?: typeof defaultOptions;- isEE?: boolean;-}--const commonSetup = ({ isEE = false }: { isEE?: boolean } = {}) => {- mockGetBoundingClientRect();- setupRecentViewsAndSelectionsEndpoints([]);-- const allItems = flattenCollectionTree(collectionTree).map(- createMockCollectionItem,- );-- allItems.forEach((item) => {- if (item.model === "collection") {- fetchMock.get(`path:/api/collection/${item.id}`, item);- } else if (item.model === "dashboard") {- fetchMock.get(`path:/api/dashboard/${item.id}`, item);-- const dashboardId = item.id;- const dashboardItems = allItems.filter(- (item: any) => item.dashboard_id === dashboardId,- );- setupDashboardItemsEndpoint({- dashboard: item as any,- dashboardItems,- });- } else {- fetchMock.get(`path:/api/card/${item.id}`, item);- }- });-- setupCollectionTreeMocks(collectionTree);-- setupRootCollectionItemsEndpoint({- rootCollectionItems:- collectionTree[0].descendants- ?.filter((item) => !item.dashboard_id)- .map(createMockCollectionItem) ?? [],- tenantRootItems: isEE- ? [mockCollectionToCollectionItem(tenantCollectionsTree[0])]- : [],- });-- if (isEE) {- const allTenantItems = flattenCollectionTree(tenantCollectionsTree).map(- createMockCollectionItem,- );-- setupTenantCollectionTreeMocks(tenantCollectionsTree);-- allTenantItems.forEach((item) => {- if (item.model === "collection") {- fetchMock.get(`path:/api/collection/${item.id}`, {- ...item,- namespace: "shared-tenant-collection",- });- } else if (item.model === "dashboard") {- fetchMock.get(`path:/api/dashboard/${item.id}`, item);-- const dashboardId = item.id;- const dashboardItems = allTenantItems.filter(- (item: any) => item.dashboard_id === dashboardId,- );- setupDashboardItemsEndpoint({- dashboard: item as any,- dashboardItems,- });- } else {- fetchMock.get(`path:/api/card/${item.id}`, item);- }- });- }-};--export const setupPicker = async ({- initialValue = { id: "root", model: "collection" },- onChange = jest.fn<void, [QuestionPickerItem]>(),- isEE = false,-}: SetupOpts = {}) => {- commonSetup({ isEE });-- const settings = mockSettings({- "token-features": createMockTokenFeatures({- content_verification: isEE,- official_collections: isEE,- tenants: isEE,- }),- "use-tenants": isEE,- });-- const storeInitialState = createMockState({- settings,- });-- if (isEE) {- setupEnterprisePlugins();- }-- function TestComponent() {- const [path, setPath] = useState<QuestionPickerStatePath>();-- return (- <QuestionPicker- initialValue={initialValue}- models={["card", "dashboard"]}- options={defaultOptions}- path={path}- onInit={jest.fn()}- onItemSelect={onChange}- onPathChange={setPath}- />- );- }-- renderWithProviders(<TestComponent />, { storeInitialState });-- await waitForLoaderToBeRemoved();-};--// zero indexed-export const level = async (index: number) => {- return within(await screen.findByTestId(`item-picker-level-${index}`));-};--export const setupModal = async ({- initialValue,- models = ["card", "dataset"],- onChange = jest.fn<void, [QuestionPickerItem]>(),- options = defaultOptions,-}: SetupOpts = {}) => {- commonSetup();-- renderWithProviders(- <QuestionPickerModal- onChange={onChange}- value={initialValue}- onClose={jest.fn()}- models={models}- options={options}- />,- );-- await waitForLoaderToBeRemoved();-};diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal.tsxdeleted file mode 100644index c4007c79f4d..00000000000--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal.tsx+++ /dev/null@@ -1,192 +0,0 @@-import { useCallback, useState } from "react";-import { t } from "ttag";--import type { RecentItem } from "metabase-types/api";--import type { EntityPickerTab } from "../../../EntityPicker";-import {- EntityPickerModal,- defaultOptions as defaultEntityPickerOptions,-} from "../../../EntityPicker";-import { useLogRecentItem } from "../../../EntityPicker/hooks/use-log-recent-item";-import type {- QuestionPickerItem,- QuestionPickerModel,- QuestionPickerOptions,- QuestionPickerStatePath,- QuestionPickerValue,- QuestionPickerValueItem,-} from "../types";--import {- QuestionPicker,- defaultOptions as defaultQuestionPickerOptions,-} from "./QuestionPicker";--interface QuestionPickerModalProps {- title?: string;- onChange: (item: QuestionPickerValueItem) => void;- onClose: () => void;- options?: QuestionPickerOptions;- value?: QuestionPickerValue;- models?: QuestionPickerModel[];- recentFilter?: (items: RecentItem[]) => RecentItem[];- shouldDisableItem?: (- item: QuestionPickerItem,- models?: QuestionPickerModel[],- ) => boolean;-}--const canSelectItem = (- item: QuestionPickerItem | null,-): item is QuestionPickerValueItem => {- return (- item != null &&- (item.model === "card" ||- item.model === "dataset" ||- item.model === "metric")- );-};--const defaultOptions: QuestionPickerOptions = {- ...defaultEntityPickerOptions,- ...defaultQuestionPickerOptions,-};--export const QuestionPickerModal = ({- title = t`Choose a question or model`,- onChange,- onClose,- value = { model: "collection", id: "root" },- options = defaultOptions,- models = ["card", "dataset"],- recentFilter,- shouldDisableItem,-}: QuestionPickerModalProps) => {- options = { ...defaultOptions, ...options };- const [selectedItem, setSelectedItem] = useState<QuestionPickerItem | null>(- null,- );- const { tryLogRecentItem } = useLogRecentItem();-- const handleOnChange = useCallback(- (item: QuestionPickerValueItem) => {- onChange(item);- tryLogRecentItem(item);- },- [onChange, tryLogRecentItem],- );-- const handleItemSelect = useCallback(- (item: QuestionPickerItem) => {- if (options.hasConfirmButtons) {- setSelectedItem(item);- } else if (canSelectItem(item)) {- handleOnChange(item);- }- },- [handleOnChange, options],- );-- const handleConfirm = () => {- if (selectedItem && canSelectItem(selectedItem)) {- handleOnChange(selectedItem);- }- };-- const [modelsPath, setModelsPath] = useState<QuestionPickerStatePath>();- const [metricsPath, setMetricsPath] = useState<QuestionPickerStatePath>();- const [questionsPath, setQuestionsPath] = useState<QuestionPickerStatePath>();-- const tabs: EntityPickerTab<- QuestionPickerItem["id"],- QuestionPickerItem["model"],- QuestionPickerItem- >[] = [- {- id: "questions-tab",- displayName: t`Questions`,- models: ["card" as const],- folderModels: ["collection" as const],- icon: "folder",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={value}- models={["card", "dashboard"]}- options={{ ...options, showLibrary: false }}- path={questionsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setQuestionsPath}- shouldDisableItem={shouldDisableItem}- />- ),- },- {- id: "models-tab",- displayName: t`Models`,- models: ["dataset" as const],- folderModels: ["collection" as const],- icon: "model",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={value}- models={["dataset"]}- options={options}- path={modelsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setModelsPath}- shouldDisableItem={shouldDisableItem}- />- ),- },- {- id: "metrics-tab",- displayName: t`Metrics`,- models: ["metric" as const],- folderModels: ["collection" as const],- icon: "metric",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={value}- models={["metric"]}- options={options}- path={metricsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setMetricsPath}- shouldDisableItem={shouldDisableItem}- />- ),- },- ];-- const filteredTabs = tabs.filter((tab) =>- tab.models.every((m) => models.includes(m as QuestionPickerModel)),- );-- return (- <EntityPickerModal- title={title}- onItemSelect={handleItemSelect}- canSelectItem={canSelectItem(selectedItem)}- onConfirm={handleConfirm}- onClose={onClose}- selectedItem={selectedItem}- initialValue={value}- tabs={filteredTabs}- options={options}- searchParams={- options.showRootCollection === false- ? { filter_items_in_personal_collection: "only" }- : options.showPersonalCollections === false- ? { filter_items_in_personal_collection: "exclude" }- : undefined- }- searchResultFilter={(results) => results}- actionButtons={[]}- recentFilter={recentFilter}- />- );-};diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/index.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/index.tsdeleted file mode 100644index 306b28d889f..00000000000--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./QuestionPicker";-export * from "./QuestionPickerModal";diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/index.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/index.tsindex bed34df1c98..a9124fb977b 100644--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/index.ts+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/index.ts@@ -1,3 +1,3 @@-export * from "./components";+export * from "./QuestionPickerModal";export * from "./types";export { getQuestionPickerValue } from "./utils";diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/types.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/types.tsindex bab73a131e6..a41b5970c5f 100644--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/types.ts+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/types.ts@@ -1,54 +1,13 @@-import type {- CardId,- ListCollectionItemsRequest,- SearchModel,-} from "metabase-types/api";+import type { CardId } from "metabase-types/api";-import type {- EntityPickerModalOptions,- ListProps,- PickerState,-} from "../../EntityPicker";-import type {- CollectionItemId,- CollectionPickerItem,-} from "../CollectionPicker";-import type { TablePickerValueItem } from "../TablePicker";+import type { OmniPickerItem } from "../EntityPicker";-export type QuestionPickerModel =- | Extract<- CollectionPickerItem["model"],- "card" | "dataset" | "metric" | "collection" | "dashboard"- >- | "table";export type QuestionPickerValueModel = Extract<- CollectionPickerItem["model"],+ OmniPickerItem["model"],"card" | "dataset" | "metric">;-export type QuestionPickerValueItem = CollectionPickerItem & {+export type QuestionPickerValueItem = Pick<OmniPickerItem, "id" | "model"> & {id: CardId;model: QuestionPickerValueModel;};--// we could tighten this up in the future, but there's relatively little value to it-export type QuestionPickerItem = CollectionPickerItem | TablePickerValueItem;-export type QuestionPickerValue = Pick<QuestionPickerItem, "id" | "model">;-export type QuestionPickerOptions = EntityPickerModalOptions & {- showPersonalCollections?: boolean;- showRootCollection?: boolean;- showLibrary?: boolean;-};--export type QuestionItemListProps = ListProps<- CollectionItemId,- SearchModel,- QuestionPickerItem,- ListCollectionItemsRequest,- QuestionPickerOptions->;--export type QuestionPickerStatePath = PickerState<- QuestionPickerItem,- ListCollectionItemsRequest->;diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.tsindex 68e6d734a54..cddee032436 100644--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.ts+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.ts@@ -1,49 +1,11 @@-import _ from "underscore";-import type { Card, CardType } from "metabase-types/api";-import type { CollectionPickerItem } from "../CollectionPicker";-import {- type TablePickerFolderItem,- type TablePickerItem,- isTablePickerFolder,-} from "../TablePicker";-import type {- QuestionPickerItem,- QuestionPickerModel,- QuestionPickerValue,+ QuestionPickerValueItem,QuestionPickerValueModel,} from "./types";-export const isFolder = (- item: QuestionPickerItem,- models: QuestionPickerModel[],-) => {- return (- item.id === "root" ||- (item as CollectionPickerItem).is_personal ||- ((item?.model === "collection" || item?.model === "dashboard") &&- _.intersection([...(item?.below ?? []), ...(item?.here ?? [])], models)- .length > 0)- );-};--export const isTablePickerFolderOrQuestionPickerFolder = (- item: QuestionPickerItem | TablePickerItem,- models: QuestionPickerModel[],-): item is TablePickerFolderItem | QuestionPickerItem => {- return isTablePickerFolder(item) || isFolder(item, models);-};--export const getQuestionPickerValue = ({- id,- type,-}: Pick<Card, "id" | "type">): QuestionPickerValue => {- return { id, model: getQuestionPickerValueModel(type) };-};--export const getQuestionPickerValueModel = (+const getQuestionPickerValueModel = (type: CardType,): QuestionPickerValueModel => {switch (type) {@@ -55,3 +17,10 @@ export const getQuestionPickerValueModel = (return "metric";}};++export const getQuestionPickerValue = ({+ id,+ type,+}: Pick<Card, "id" | "type">): QuestionPickerValueItem => {+ return { id, model: getQuestionPickerValueModel(type) };+};diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/DatabaseList.tsx b/frontend/src/metabase/common/components/Pickers/TablePicker/DatabaseList.tsxdeleted file mode 100644index d2c506a5c29..00000000000--- a/frontend/src/metabase/common/components/Pickers/TablePicker/DatabaseList.tsx+++ /dev/null@@ -1,59 +0,0 @@-import { useMemo } from "react";--import type { Database } from "metabase-types/api";--import { ItemList, ListBox } from "../../EntityPicker";--import type { TablePickerFolderItem } from "./types";--interface Props {- databases: Database[] | undefined;- error: unknown;- isCurrentLevel: boolean;- isLoading: boolean;- selectedItem: TablePickerFolderItem | null;- onClick: (item: TablePickerFolderItem) => void;- shouldDisableItem?: (item: TablePickerFolderItem) => boolean;-}--const isFolder = () => true;--export const DatabaseList = ({- databases,- error,- isCurrentLevel,- isLoading,- selectedItem,- onClick,- shouldDisableItem,-}: Props) => {- const items: TablePickerFolderItem[] | undefined = useMemo(() => {- return databases?.map((database) => ({- id: database.id,- model: "database",- name: database.name,- database,- }));- }, [databases]);-- const hasOnly1Item = items?.length === 1;-- if (!isLoading && !error && hasOnly1Item) {- return null;- }-- return (- <ListBox data-testid="item-picker-level-0">- <ItemList- error={error}- isCurrentLevel={isCurrentLevel}- isFolder={isFolder}- isLoading={isLoading}- items={items}- selectedItem={selectedItem}- onClick={onClick}- shouldDisableItem={(item) => shouldDisableItem?.(item) || false}- />- </ListBox>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/SchemaList.tsx b/frontend/src/metabase/common/components/Pickers/TablePicker/SchemaList.tsxdeleted file mode 100644index 99c2b4fadb0..00000000000--- a/frontend/src/metabase/common/components/Pickers/TablePicker/SchemaList.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { useMemo } from "react";--import type { DatabaseId, SchemaName } from "metabase-types/api";--import { ItemList, ListBox } from "../../EntityPicker";--import type { TablePickerFolderItem } from "./types";-import { getSchemaDisplayName } from "./utils";--interface Props {- dbId: DatabaseId;- dbName: string | undefined;- error: unknown;- isCurrentLevel: boolean;- isLoading: boolean;- schemas: SchemaName[] | undefined;- selectedItem: TablePickerFolderItem | null;- onClick: (item: TablePickerFolderItem) => void;-}--const isFolder = () => true;--export const SchemaList = ({- dbId,- dbName,- error,- isCurrentLevel,- isLoading,- schemas,- selectedItem,- onClick,-}: Props) => {- const items: TablePickerFolderItem[] | undefined = useMemo(() => {- return schemas?.map((schema) => ({- id: schema,- model: "schema",- name: getSchemaDisplayName(schema),- isOnlySchema: schemas.length === 1,- dbName,- dbId,- }));- }, [schemas, dbId, dbName]);-- const hasOnly1Item = items?.length === 1;-- if (!isLoading && !error && hasOnly1Item) {- return null;- }-- return (- <ListBox data-testid="item-picker-level-2">- <ItemList- error={error}- isCurrentLevel={isCurrentLevel}- isFolder={isFolder}- isLoading={isLoading}- items={items}- selectedItem={selectedItem}- onClick={onClick}- />- </ListBox>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/TableList.tsx b/frontend/src/metabase/common/components/Pickers/TablePicker/TableList.tsxdeleted file mode 100644index 0b7083df263..00000000000--- a/frontend/src/metabase/common/components/Pickers/TablePicker/TableList.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { useMemo } from "react";--import type { Table } from "metabase-types/api";--import { ItemList, ListBox } from "../../EntityPicker";--import type { TableItem } from "./types";--interface Props {- error: unknown;- isLoading: boolean;- isCurrentLevel: boolean;- selectedItem: TableItem | null;- tables: Table[] | undefined;- onClick: (item: TableItem) => void;- shouldDisableItem?: (item: TableItem) => boolean;-}--const isFolder = () => false;--export const TableList = ({- error,- isLoading,- isCurrentLevel,- selectedItem,- tables,- onClick,- shouldDisableItem,-}: Props) => {- const items: TableItem[] | undefined = useMemo(() => {- return tables?.map((table) => ({- id: table.id,- model: "table",- name: table.display_name,- database: { id: table.db_id },- database_id: table.db_id,- is_published: table.is_published,- }));- }, [tables]);-- return (- <ListBox data-testid="item-picker-level-3">- <ItemList- error={error}- isCurrentLevel={isCurrentLevel}- isFolder={isFolder}- isLoading={isLoading}- items={items}- selectedItem={selectedItem}- onClick={onClick}- shouldDisableItem={shouldDisableItem}- />- </ListBox>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/TablePicker.tsx b/frontend/src/metabase/common/components/Pickers/TablePicker/TablePicker.tsxdeleted file mode 100644index 19ff4ee8d57..00000000000--- a/frontend/src/metabase/common/components/Pickers/TablePicker/TablePicker.tsx+++ /dev/null@@ -1,292 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from "react";-import { useLatest } from "react-use";--import {- skipToken,- useListDatabaseSchemaTablesQuery,- useListDatabaseSchemasQuery,- useListDatabasesQuery,-} from "metabase/api";-import { isNotNull } from "metabase/lib/types";-import { Flex } from "metabase/ui";-import type { DatabaseId, SchemaName, TableId } from "metabase-types/api";--import { DatabaseList } from "./DatabaseList";-import { SchemaList } from "./SchemaList";-import { TableList } from "./TableList";-import type {- TableItem,- TablePickerFolderItem,- TablePickerItem,- TablePickerStatePath,- TablePickerValue,-} from "./types";-import { getDbItem, getSchemaItem, getTableItem } from "./utils";--interface Props {- /**- * Limit selection to a particular database- */- databaseId?: DatabaseId;- path?: TablePickerStatePath | undefined;- value: TablePickerValue | undefined;- onItemSelect: (value: TablePickerItem) => void;- onPathChange: (path: TablePickerStatePath) => void;- shouldDisableItem?: (item: TablePickerItem) => boolean;-}--export const TablePicker = ({- databaseId,- path,- value,- onItemSelect,- onPathChange,- shouldDisableItem,-}: Props) => {- const defaultPath = useMemo<TablePickerStatePath>(() => {- return [databaseId ?? value?.db_id, value?.schema, value?.id];- }, [databaseId, value]);- const [initialDbId, initialSchemaId, initialTableId] = path ?? defaultPath;- const [dbId, setDbId] = useState<DatabaseId | undefined>(initialDbId);- const [schemaName, setSchemaName] = useState<SchemaName | undefined>(- initialSchemaId,- );- const [tableId, setTableId] = useState<TableId | undefined>(initialTableId);-- const {- data: databasesResponse,- error: errorDatabases,- isFetching: isLoadingDatabases,- } = useListDatabasesQuery({ saved: false, "can-query": true });-- const databases = isLoadingDatabases ? undefined : databasesResponse?.data;-- const {- data: schemas,- error: errorSchemas,- isFetching: isLoadingSchemas,- } = useListDatabaseSchemasQuery(- isNotNull(dbId) ? { id: dbId, "can-query": true } : skipToken,- );-- const {- data: tables,- error: errorTables,- isFetching: isLoadingTables,- } = useListDatabaseSchemaTablesQuery(- isNotNull(dbId) && isNotNull(schemaName)- ? { id: dbId, schema: schemaName, "can-query": true }- : skipToken,- );-- const selectedDbItem = useMemo(- () => getDbItem(databases, dbId),- [databases, dbId],- );-- const selectedSchemaItem = useMemo(- () =>- getSchemaItem(- dbId,- selectedDbItem?.name,- schemaName,- schemas?.length === 1,- ),- [dbId, selectedDbItem, schemaName, schemas],- );-- const selectedTableItem = useMemo(- () => getTableItem(tables, tableId),- [tables, tableId],- );-- const handleFolderSelect = useCallback(- (folder: TablePickerFolderItem) => {- if (folder.model === "database") {- if (dbId === folder.id) {- const newSchemaName =- schemas != null && schemas.length > 0 ? schemas[0] : undefined;- const newSchemaItem = getSchemaItem(- dbId,- folder.name,- newSchemaName,- schemas?.length === 1,- );- const newPath: TablePickerStatePath = [- dbId,- newSchemaName,- undefined,- ];- setSchemaName(newSchemaName);- onPathChange(newPath);- onItemSelect(newSchemaItem ?? folder);- } else {- const newPath: TablePickerStatePath = [- folder.id,- undefined,- undefined,- ];- setDbId(folder.id);- setSchemaName(undefined);- onItemSelect(folder);- onPathChange(newPath);- }- }-- if (folder.model === "schema") {- const newPath: TablePickerStatePath = [dbId, folder.id, undefined];- setSchemaName(folder.id);- onItemSelect({- ...folder,- name:- // use database name if there is only 1 schema, as user won't even see the schema in the UI- selectedDbItem && schemas?.length === 1- ? selectedDbItem.name- : folder.name,- });- onPathChange(newPath);- }-- setTableId(undefined);- },- [dbId, selectedDbItem, schemas, onItemSelect, onPathChange],- );-- const handleTableSelect = useCallback(- (item: TableItem) => {- setTableId(item.id);- onItemSelect(item);- onPathChange([dbId, schemaName, item.id]);- },- [dbId, schemaName, setTableId, onItemSelect, onPathChange],- );-- const onItemSelectRef = useLatest(onItemSelect);- const handleFolderSelectRef = useLatest(handleFolderSelect);-- useEffect(- function ensureDbSelected() {- const hasDbs = !isLoadingDatabases && databases && databases.length > 0;-- if (hasDbs && !selectedDbItem) {- const firstDatabase = shouldDisableItem- ? databases.find(- (db) => !shouldDisableItem({ ...db, model: "database" }),- )- : databases[0];-- const item = firstDatabase- ? getDbItem(databases, firstDatabase.id)- : undefined;-- if (item) {- handleFolderSelectRef.current(item);- }- }- },- [- dbId,- isLoadingDatabases,- databases,- handleFolderSelectRef,- selectedDbItem,- shouldDisableItem,- ],- );-- useEffect(- function ensureSchemaSelected() {- const hasSchemas = !isLoadingSchemas && schemas && schemas.length > 0;-- if (hasSchemas && !selectedSchemaItem) {- const firstSchema = schemas[0];- const item = getSchemaItem(- dbId,- selectedDbItem?.name,- firstSchema,- schemas.length === 1,- );-- if (item) {- handleFolderSelectRef.current(item);- }- }- },- [- dbId,- selectedDbItem,- isLoadingSchemas,- schemas,- handleFolderSelectRef,- selectedSchemaItem,- ],- );-- useEffect(- function ensureFolderSelected() {- if (initialDbId != null) {- const item = getSchemaItem(- initialDbId,- selectedDbItem?.name,- initialSchemaId,- schemas?.length === 1,- );-- if (item) {- onItemSelectRef.current(item);- }- }- },- [- databases,- schemas,- selectedDbItem,- onItemSelectRef,- initialDbId,- initialSchemaId,- ],- );-- return (- <Flex h="100%" w="fit-content">- {!databaseId && (- <DatabaseList- databases={databases}- error={errorDatabases}- isCurrentLevel={- schemaName == null || (schemas?.length === 1 && !tableId)- }- isLoading={isLoadingDatabases}- selectedItem={selectedDbItem}- onClick={handleFolderSelect}- shouldDisableItem={shouldDisableItem}- />- )}-- {isNotNull(dbId) && (- <SchemaList- dbId={dbId}- dbName={selectedDbItem?.name}- error={errorSchemas}- isCurrentLevel={!tableId}- isLoading={isLoadingSchemas}- schemas={isLoadingSchemas ? undefined : schemas}- selectedItem={selectedSchemaItem}- onClick={handleFolderSelect}- />- )}-- {isNotNull(schemaName) && (- <TableList- error={errorTables}- isCurrentLevel- isLoading={isLoadingTables}- selectedItem={selectedTableItem}- tables={isLoadingTables ? undefined : tables}- onClick={handleTableSelect}- shouldDisableItem={shouldDisableItem}- />- )}- </Flex>- );-};diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/index.ts b/frontend/src/metabase/common/components/Pickers/TablePicker/index.tsdeleted file mode 100644index 21177136be3..00000000000--- a/frontend/src/metabase/common/components/Pickers/TablePicker/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./TablePicker";-export * from "./types";diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/types.ts b/frontend/src/metabase/common/components/Pickers/TablePicker/types.tsdeleted file mode 100644index b3d37e652cf..00000000000--- a/frontend/src/metabase/common/components/Pickers/TablePicker/types.ts+++ /dev/null@@ -1,56 +0,0 @@-import type { DatabaseId, SchemaName, TableId } from "metabase-types/api";--import type { CollectionPickerItem } from "../CollectionPicker";-import type { QuestionPickerItem } from "../QuestionPicker";--export type DatabaseItem = {- id: DatabaseId;- name: string;- model: "database";-};--export type SchemaItem = {- id: SchemaName;- dbId: DatabaseId;- dbName: string | undefined;- isOnlySchema: boolean;- name: string;- model: "schema";-};--export type TableItem = {- id: TableId;- name: string;- model: "table";- database_id?: DatabaseId;- is_published?: boolean;-};--export type TablePickerValue = {- id: TableId;- name: string;- model: "table";- db_id: DatabaseId;- schema: SchemaName;-};--export type TablePickerStatePath = [- DatabaseId | undefined,- SchemaName | undefined,- TableId | undefined,-];--export type TablePickerValueItem = TableItem;--export type TablePickerFolderItem = DatabaseItem | SchemaItem;--export type TablePickerItem = TablePickerValueItem | TablePickerFolderItem;--export const isTablePickerValue = (- input?: Pick<QuestionPickerItem, "model" | "id">,-): input is TablePickerValue => input?.model === "table";--export const isTablePickerFolder = (- input?: TablePickerItem | CollectionPickerItem,-): input is TablePickerFolderItem =>- input?.model === "database" || input?.model === "schema";diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/utils.ts b/frontend/src/metabase/common/components/Pickers/TablePicker/utils.tsdeleted file mode 100644index 095d26d7012..00000000000--- a/frontend/src/metabase/common/components/Pickers/TablePicker/utils.ts+++ /dev/null@@ -1,74 +0,0 @@-import { humanize, titleize } from "metabase/lib/formatting/strings";-import type {- Database,- DatabaseId,- SchemaName,- Table,- TableId,-} from "metabase-types/api";--import type { TableItem, TablePickerFolderItem } from "./types";--export const generateKey = (- dbItem: TablePickerFolderItem | null,- schemaItem: TablePickerFolderItem | null,- tableItem: TableItem | null,-) => {- return [dbItem?.id, schemaItem?.id, tableItem?.id].join("-");-};--export const getDbItem = (- databases: Database[] | undefined,- dbId: DatabaseId | undefined,-): TablePickerFolderItem | null => {- if (typeof dbId === "undefined") {- return null;- }-- const database = databases?.find((db) => db.id === dbId);- const name = database?.name ?? "";-- return { model: "database", id: dbId, name };-};--export const getSchemaItem = (- dbId: DatabaseId | undefined,- dbName: string | undefined,- schemaName: SchemaName | undefined,- isOnlySchema: boolean,-): TablePickerFolderItem | null => {- if (typeof schemaName === "undefined" || typeof dbId === "undefined") {- return null;- }-- const name = getSchemaDisplayName(schemaName);-- return { model: "schema", id: schemaName, name, dbId, dbName, isOnlySchema };-};--export const getTableItem = (- tables: Table[] | undefined,- tableId: TableId | undefined,-): TableItem | null => {- if (typeof tableId === "undefined") {- return null;- }-- const table = tables?.find((db) => db.id === tableId);- const name = table?.name ?? "";-- return {- model: "table",- id: tableId,- name,- database_id: table?.db_id,- };-};--export const getSchemaDisplayName = (schemaName: SchemaName | undefined) => {- if (typeof schemaName === "undefined") {- return "";- }-- return titleize(humanize(schemaName));-};diff --git a/frontend/src/metabase/common/components/Pickers/hooks.ts b/frontend/src/metabase/common/components/Pickers/hooks.tsdeleted file mode 100644index b0cd4d9fb87..00000000000--- a/frontend/src/metabase/common/components/Pickers/hooks.ts+++ /dev/null@@ -1,125 +0,0 @@-import {- skipToken,- useGetCardQuery,- useGetCollectionQuery,- useGetDashboardQuery,- useGetTableQuery,-} from "metabase/api";-import { isValidCollectionId } from "metabase/collections/utils";-import { DATABASES_COLLECTION } from "metabase/entities/collections";-import type { Collection } from "metabase-types/api";--import type { QuestionPickerItem } from "./QuestionPicker";-import type { TablePickerValue } from "./TablePicker";--export const useGetInitialContainer = (- initialValue?: Pick<QuestionPickerItem, "model" | "id"> | TablePickerValue,-) => {- // Figure out what we're working with- const isQuestion =- initialValue && ["card", "dataset", "metric"].includes(initialValue.model);- const isCollection = initialValue?.model === "collection";- const isDashboard = initialValue?.model === "dashboard";- const isTable = initialValue?.model === "table";-- // Determine the IDs of the things we care about- const cardId = isQuestion ? Number(initialValue.id) : undefined;- const dashboardId = isDashboard ? Number(initialValue.id) : undefined;- const collectionId = isCollection- ? isValidCollectionId(initialValue.id)- ? initialValue.id- : "root"- : undefined;-- // Fetch the initial value's entity- const {- data: currentCollection,- isLoading: isCollectionLoading,- error: currentCollectionError,- } = useGetCollectionQuery(collectionId ? { id: collectionId } : skipToken);-- const {- data: currentQuestion,- isLoading: isQuestionLoading,- error: currentQuestionError,- } = useGetCardQuery(cardId ? { id: cardId } : skipToken);-- const {- data: currentDashboard,- isLoading: isDashboardLoading,- error: currentDashboardError,- } = useGetDashboardQuery(dashboardId ? { id: dashboardId } : skipToken);-- // If the initial value was a card or dashboard, fetch it's container- const {- data: currentQuestionCollection,- isLoading: isCurrentQuestionCollectionLoading,- error: currentQuestionCollectionError,- } = useGetCollectionQuery(- currentQuestion- ? { id: currentQuestion.collection_id ?? "root" }- : skipToken,- );-- const {- data: currentQuestionDashboard,- isLoading: isCurrentQuestionDashboardLoading,- error: currentQuestionDashboardError,- } = useGetDashboardQuery(- currentQuestion?.dashboard_id- ? { id: currentQuestion.dashboard_id }- : skipToken,- );-- // This is bad, and should be fixed. This shouldn't really be required (collections come back with dashboards),- // And note how we swap the ID out for root- const {- data: currentDashboardCollection,- isLoading: isCurrentDashboardCollectionLoading,- error: CurrentDashboardCollectionError,- } = useGetCollectionQuery(- currentDashboard- ? { id: currentDashboard.collection_id ?? "root" }- : skipToken,- );-- const {- data: currentTable,- isLoading: isCurrentTableLoading,- error: currentTableError,- } = useGetTableQuery(- initialValue != null && isTable ? { id: initialValue.id } : skipToken,- );-- const currentTableCollection =- currentTable != null- ? (currentTable.collection ?? (DATABASES_COLLECTION as Collection))- : undefined;-- return {- currentTable,- currentQuestion,- currentCollection:- currentTableCollection ??- currentQuestionCollection ??- currentDashboardCollection ??- currentCollection,- currentDashboard: currentQuestionDashboard ?? currentDashboard,- isLoading:- isCollectionLoading ||- isQuestionLoading ||- isDashboardLoading ||- isCurrentTableLoading ||- isCurrentQuestionCollectionLoading ||- isCurrentQuestionDashboardLoading ||- isCurrentDashboardCollectionLoading,- error:- currentTableError ??- currentCollectionError ??- currentDashboardError ??- currentQuestionError ??- currentQuestionCollectionError ??- CurrentDashboardCollectionError ??- currentQuestionDashboardError,- };-};diff --git a/frontend/src/metabase/common/components/Pickers/index.ts b/frontend/src/metabase/common/components/Pickers/index.tsnew file mode 100644index 00000000000..98b14fcdc5c--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/index.ts@@ -0,0 +1,7 @@+export * from "./EntityPicker";+export { CollectionPickerModal } from "./CollectionPicker";+export { DashboardPickerModal } from "./DashboardPicker";+export { DataPickerModal } from "./DataPicker";+export { MiniPicker } from "./MiniPicker";+export { MoveModal } from "./MoveModal";+export { QuestionPickerModal } from "./QuestionPicker";diff --git a/frontend/src/metabase/common/components/Pickers/utils.ts b/frontend/src/metabase/common/components/Pickers/utils.tsindex 0fd9484298b..60af61a99d8 100644--- a/frontend/src/metabase/common/components/Pickers/utils.ts+++ b/frontend/src/metabase/common/components/Pickers/utils.ts@@ -1,238 +1,12 @@-import { t } from "ttag";+import type { CollectionId, CollectionItem } from "metabase-types/api";-import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";-import { isNullOrUndefined } from "metabase/lib/types";-import { PLUGIN_TENANTS } from "metabase/plugins";-import type {- Collection,- CollectionId,- CollectionItem,- CollectionItemModel,- CollectionNamespace,- ListCollectionItemsRequest,-} from "metabase-types/api";--import type { PickerState } from "../EntityPicker";--import type {- CollectionPickerItem,- CollectionPickerOptions,- CollectionPickerStatePath,-} from "./CollectionPicker";--export const getNamespaceForItem = (- item: Pick<CollectionPickerItem, "id" | "namespace"> | null | undefined,-): CollectionNamespace | undefined => {- if (!item) {- return undefined;- }-- const tenantNamespace = PLUGIN_TENANTS.getNamespaceForTenantId(item.id);- if (tenantNamespace) {- return tenantNamespace as CollectionNamespace;- }-- return item.namespace;-};--export const getCollectionIdPath = (- collection: Pick<- CollectionPickerItem,- | "id"- | "location"- | "is_personal"- | "effective_location"- | "model"- | "is_shared_tenant_collection"- | "is_tenant_dashboard"- | "type"- | "namespace"- | "collection_namespace"- | "collection_id"- > & {- type?: Collection["type"];- },- userPersonalCollectionId?: CollectionId,-): CollectionId[] => {- if (collection.id === null || collection.id === "root") {- return ["root"];- }-- if (collection.id === "databases") {- return ["databases"];- }-- const tenantPath = PLUGIN_TENANTS.getTenantCollectionPathPrefix(collection);- if (tenantPath) {- if (- PLUGIN_TENANTS.isTenantCollectionId(collection.id) ||- collection.type === "tenant-specific-root-collection"- ) {- return tenantPath;- }- const location = collection?.effective_location ?? collection?.location;- const pathFromRoot: CollectionId[] =- location?.split("/").filter(Boolean).map(Number) ?? [];- const id =- collection.model === "collection" ? collection.id : -collection.id;- return [...tenantPath, ...pathFromRoot, id];- }-- if (collection.type === "library") {- return [collection.id];- }-- if (collection.id === PERSONAL_COLLECTIONS.id) {- return ["personal"];- }-- if (typeof collection.id === "string") {- console.error("Invalid collection id", collection.id);- return [];- }-- const location = collection?.effective_location ?? collection?.location;- const pathFromRoot: CollectionId[] =- location?.split("/").filter(Boolean).map(Number) ?? [];-- const isInUserPersonalCollection =- userPersonalCollectionId &&- (collection.id === userPersonalCollectionId ||- pathFromRoot.includes(userPersonalCollectionId));-- const isInSemanticLayerCollection = collection?.type?.includes("library");-- const id = collection.model === "collection" ? collection.id : -collection.id;-- if (isInUserPersonalCollection) {- return [...pathFromRoot, id];- } else if (isInSemanticLayerCollection) {- return [...pathFromRoot, id];- } else if (collection.is_personal) {- return ["personal", ...pathFromRoot, id];- } else {- return ["root", ...pathFromRoot, id];- }-};--export const getStateFromIdPath = ({- idPath,- namespace,- models,-}: {- idPath: CollectionId[];- namespace?: CollectionNamespace;- models: CollectionItemModel[];-}): CollectionPickerStatePath => {- const effectiveNamespace =- PLUGIN_TENANTS.isTenantCollectionId(idPath[0]) &&- PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE- ? (PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE as CollectionNamespace)- : namespace;-- const statePath: PickerState<- CollectionPickerItem,- ListCollectionItemsRequest- > = [- {- selectedItem: {- name: "",- model: "collection",- id: idPath[0],- here: ["collection"],- below: ["collection"],- namespace: effectiveNamespace,- },- },- ];-- idPath.forEach((id, index) => {- const { entityId: nextLevelId, model: nextLevelModel } = resolveEntityId(- idPath[index + 1],- );-- const { entityId, model: entityModel, ...extra } = resolveEntityId(id);-- statePath.push({- query: {- id: entityId,- models: ["collection", ...models],- namespace: effectiveNamespace,- ...extra,- },- entity: entityModel,- selectedItem: nextLevelId- ? {- name: "",- model: nextLevelModel,- id: nextLevelId,- here: ["collection"],- below: ["collection"],- namespace: effectiveNamespace,- }- : null,- });- });-- return statePath;-};--const resolveEntityId = (- id: CollectionId,-): {- model: "collection" | "dashboard";- entityId: CollectionId;-} => {- if (typeof id === "string" || isNullOrUndefined(id)) {- return {- entityId: id,- model: "collection",- };- } else {- const isDashboard = id < 0;-- return {- entityId: Math.abs(id),- model: isDashboard ? "dashboard" : "collection",- };- }-};--export const isNamespaceRoot = (item: CollectionPickerItem): boolean => {- return PLUGIN_TENANTS.isTenantCollectionId(item.id);-};--export const shouldDisableItemForSavingModel = (- item: CollectionPickerItem,- savingModel?: CollectionPickerOptions["savingModel"],-): boolean => {- if (savingModel === "collection") {- return false;- }-- return isNamespaceRoot(item);-};--export const getDisabledReasonForSavingModel = (- item: CollectionPickerItem,- savingModel?: CollectionPickerOptions["savingModel"],-): string | undefined => {- if (!shouldDisableItemForSavingModel(item, savingModel)) {- return undefined;- }-- if (PLUGIN_TENANTS.isTenantCollectionId(item.id)) {- const tenantReason = PLUGIN_TENANTS.getTenantRootDisabledReason();- if (tenantReason) {- return tenantReason;- }- }-- return t`Items cannot be saved to this collection.`;-};+import type { OmniPickerCollectionItem, OmniPickerItem } from "./EntityPicker";+/**+ * check if a card can be used as the starting point for a new query+ */export const canCollectionCardBeUsed = (- item: CollectionItem | CollectionPickerItem,+ item: CollectionItem | OmniPickerItem,): boolean => {if (item.model === "card") {return "can_run_adhoc_query" in item ? !!item.can_run_adhoc_query : true;@@ -246,7 +20,10 @@ export const canCollectionCardBeUsed = (* Used to prevent circular references when moving or editing collections.*/export function isItemInCollectionOrItsDescendants(- item: Pick<CollectionPickerItem, "id" | "effective_location" | "location">,+ item: Pick<+ OmniPickerCollectionItem,+ "id" | "effective_location" | "location"+ >,collectionId: CollectionId | undefined,): boolean {if (collectionId === undefined) {diff --git a/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/utils.unit.spec.tsindex 234964439b3..da548ddee5e 100644--- a/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts+++ b/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts@@ -1,531 +1,4 @@-import { setupEnterpriseTest } from "__support__/enterprise";-import { PLUGIN_TENANTS } from "metabase/plugins";--import {- getCollectionIdPath,- getDisabledReasonForSavingModel,- getNamespaceForItem,- getStateFromIdPath,- isItemInCollectionOrItsDescendants,- isNamespaceRoot,- shouldDisableItemForSavingModel,-} from "./utils";--setupEnterpriseTest();--describe("getCollectionIdPath", () => {- it("should handle the current user's personal collection", () => {- const path = getCollectionIdPath(- {- id: 1337,- location: "/",- effective_location: "/",- is_personal: true,- model: "collection",- },- 1337,- );-- expect(path).toEqual([1337]);- });-- it("should handle the library collections", () => {- const path = getCollectionIdPath(- {- id: 5,- location: "/6/",- effective_location: "/6/",- is_personal: true,- model: "collection",- type: "library-metrics",- },- 1337,- );-- expect(path).toEqual([6, 5]);- });-- it("should handle subcollections of the current user's personal collection", () => {- const path = getCollectionIdPath(- {- id: 1339,- location: "/1337/",- effective_location: "/1337/",- is_personal: true,- model: "collection",- },- 1337,- );-- expect(path).toEqual([1337, 1339]);- });-- it("should handle all users' personal collections", () => {- const path = getCollectionIdPath(- {- id: "personal",- location: "/",- effective_location: "/",- model: "collection",- },- 1337,- );-- expect(path).toEqual(["personal"]);- });-- it("should handle subcollections of all users' personal collections", () => {- const path = getCollectionIdPath(- {- id: 8675309,- location: "/1400/",- effective_location: "/1400/",- is_personal: true,- model: "collection",- },- 1337,- );-- expect(path).toEqual(["personal", 1400, 8675309]);- });-- it("should handle the current user's personal collection within all users' personal collections", () => {- const path = getCollectionIdPath(- {- id: 1337,- location: "/",- effective_location: "/",- is_personal: true,- model: "collection",- },- 1337,- );-- expect(path).toEqual([1337]);- });-- it("should handle subcollections of the current user's personal collection within all users' personal collections 🥴", () => {- const path = getCollectionIdPath(- {- id: 1339,- location: "/1337/",- effective_location: "/1337/",- is_personal: true,- model: "collection",- },- 1337,- );-- expect(path).toEqual([1337, 1339]);- });-- it("should handle root collection", () => {- const path = getCollectionIdPath(- {- id: "root",- location: "/",- effective_location: "/",- model: "collection",- },- 1337,- );-- expect(path).toEqual(["root"]);- });-- it("should handle subcollections of the root collection", () => {- const path = getCollectionIdPath(- {- id: 9,- location: "/6/7/8/",- effective_location: "/6/7/8/",- model: "collection",- },- 1337,- );-- expect(path).toEqual(["root", 6, 7, 8, 9]);- });-- it("should use effective location", () => {- const path = getCollectionIdPath(- {- id: 9,- location: "/4/5/6/7/8/",- effective_location: "/6/7/8/",- model: "collection",- },- 1337,- );-- expect(path).toEqual(["root", 6, 7, 8, 9]);- });-- it("should use a negative id when the model is a dashboard", () => {- const path = getCollectionIdPath(- {- id: 9,- location: "/4/5/6/7/8/",- effective_location: "/6/7/8/",- model: "dashboard",- },- 1337,- );-- expect(path).toEqual(["root", 6, 7, 8, -9]);- });-- it("should detect tenant collections via namespace", () => {- const path = getCollectionIdPath(- {- id: 9,- location: "/4/5/6/7/8/",- effective_location: "/6/7/8/",- model: "collection",- namespace: "shared-tenant-collection" as const,- },- 1337,- );-- expect(path).toEqual(["tenant", 6, 7, 8, 9]);- });-- it("should detect tenant collection items via collection_namespace", () => {- const path = getCollectionIdPath(- {- id: 9,- location: "/4/5/6/7/8/",- effective_location: "/6/7/8/",- model: "collection",- collection_namespace: "shared-tenant-collection" as const,- },- 1337,- );-- expect(path).toEqual(["tenant", 6, 7, 8, 9]);- });-- it("should detect tenant collection items - collections (legacy boolean)", () => {- const path = getCollectionIdPath(- {- id: 9,- location: "/4/5/6/7/8/",- effective_location: "/6/7/8/",- model: "collection",- is_shared_tenant_collection: true,- },- 1337,- );-- expect(path).toEqual(["tenant", 6, 7, 8, 9]);- });-- it("should detect tenant collection items - dashboards (legacy boolean)", () => {- const path = getCollectionIdPath(- {- id: 9,- location: "/4/5/6/7/8/",- effective_location: "/6/7/8/",- model: "collection",- is_tenant_dashboard: true,- },- 1337,- );-- expect(path).toEqual(["tenant", 6, 7, 8, 9]);- });-- it("should treat tenant collection root as a root-level item", () => {- const path = getCollectionIdPath(- {- id: 1234,- location: "/",- effective_location: "/",- model: "collection",- type: "tenant-specific-root-collection",- },- 1337,- );-- expect(path).toEqual([1234]);- });-- it("should nest tenant collection under tenant-specific for admins", () => {- const rootPath = getCollectionIdPath(- {- id: "tenant-specific",- location: "/",- model: "collection",- },- 1337,- );-- expect(rootPath).toEqual(["tenant-specific"]);-- const childPath = getCollectionIdPath(- {- id: 1234,- location: "/",- effective_location: "/",- model: "collection",- type: "tenant-specific-root-collection",- collection_id: "tenant-specific",- },- 1337,- );-- expect(childPath).toEqual(["tenant-specific", 1234]);- });-});--describe("getStateFromIdPath", () => {- it("should propagate namespace through state path", () => {- const statePath = getStateFromIdPath({- idPath: ["root", 1, 2],- namespace: "snippets",- models: ["collection"],- });-- // First item has no query- expect(statePath[0].selectedItem?.namespace).toBe("snippets");-- // Subsequent items should have the namespace in their queries- expect(statePath[1].query?.namespace).toBe("snippets");- expect(statePath[2].query?.namespace).toBe("snippets");- });-- it("should use shared-tenant-collection namespace for tenant paths", () => {- const statePath = getStateFromIdPath({- idPath: ["tenant", 1, 2],- models: ["collection"],- });-- // Should automatically use shared-tenant-collection namespace- expect(statePath[0].selectedItem?.namespace).toBe(- "shared-tenant-collection",- );- expect(statePath[1].query?.namespace).toBe("shared-tenant-collection");- expect(statePath[2].query?.namespace).toBe("shared-tenant-collection");- });-- it("should propagate namespace to selected items", () => {- const statePath = getStateFromIdPath({- idPath: ["tenant", 1],- models: ["collection"],- });-- // Selected items should have namespace- expect(statePath[0].selectedItem?.namespace).toBe(- "shared-tenant-collection",- );- expect(statePath[1].selectedItem?.namespace).toBe(- "shared-tenant-collection",- );- });-- it("should handle root paths without explicit namespace", () => {- const statePath = getStateFromIdPath({- idPath: ["root", 1],- models: ["collection"],- });-- // Should have undefined namespace for root- expect(statePath[0].selectedItem?.namespace).toBeUndefined();- expect(statePath[1].query?.namespace).toBeUndefined();- });-});--describe("isNamespaceRoot", () => {- it("should return true for tenant root", () => {- const item = {- id: "tenant",- name: "Shared collections",- model: "collection" as const,- namespace: "shared-tenant-collection" as const,- };-- expect(isNamespaceRoot(item)).toBe(true);- });-- it("should return false for regular collections", () => {- const item = {- id: 1,- name: "My Collection",- model: "collection" as const,- location: "/",- };-- expect(isNamespaceRoot(item)).toBe(false);- });-- it("should return false for root collection", () => {- const item = {- id: "root",- name: "Our Analytics",- model: "collection" as const,- location: "/",- };-- expect(isNamespaceRoot(item)).toBe(false);- });-- it("should return false for tenant sub-collections", () => {- const item = {- id: 123,- name: "Tenant Sub-Collection",- model: "collection" as const,- namespace: "shared-tenant-collection" as const,- location: "/tenant/",- };-- expect(isNamespaceRoot(item)).toBe(false);- });-});--describe("shouldDisableItemForSavingModel", () => {- const tenantRoot = {- id: "tenant",- name: "Shared collections",- model: "collection" as const,- namespace: "shared-tenant-collection" as const,- };-- const regularCollection = {- id: 1,- name: "My Collection",- model: "collection" as const,- location: "/",- };-- const tenantSubCollection = {- id: 123,- name: "Tenant Sub-Collection",- model: "collection" as const,- namespace: "shared-tenant-collection" as const,- location: "/tenant/",- };-- it("should return true for tenant root when savingModel is not 'collection'", () => {- expect(shouldDisableItemForSavingModel(tenantRoot, undefined)).toBe(true);- expect(shouldDisableItemForSavingModel(tenantRoot, null)).toBe(true);- });-- it("should return false for tenant root when saving a collection", () => {- expect(shouldDisableItemForSavingModel(tenantRoot, "collection")).toBe(- false,- );- });-- it("should return false for regular collections regardless of savingModel", () => {- expect(shouldDisableItemForSavingModel(regularCollection, undefined)).toBe(- false,- );- expect(shouldDisableItemForSavingModel(regularCollection, null)).toBe(- false,- );- expect(- shouldDisableItemForSavingModel(regularCollection, "collection"),- ).toBe(false);- });-- it("should return false for tenant sub-collections regardless of savingModel", () => {- expect(- shouldDisableItemForSavingModel(tenantSubCollection, undefined),- ).toBe(false);- expect(shouldDisableItemForSavingModel(tenantSubCollection, null)).toBe(- false,- );- });-});--describe("getDisabledReasonForSavingModel", () => {- const tenantRoot = {- id: "tenant",- name: "Shared collections",- model: "collection" as const,- namespace: "shared-tenant-collection" as const,- };-- const regularCollection = {- id: 1,- name: "My Collection",- model: "collection" as const,- location: "/",- };-- it("should return reason for disabled tenant root when savingModel is not 'collection'", () => {- const reason = getDisabledReasonForSavingModel(tenantRoot, undefined);-- expect(reason).toBeDefined();- expect(reason).toContain("tenant root collection");- });-- it("should return undefined for enabled items", () => {- expect(- getDisabledReasonForSavingModel(regularCollection, undefined),- ).toBeUndefined();- expect(- getDisabledReasonForSavingModel(tenantRoot, "collection"),- ).toBeUndefined();- });-});--describe("getNamespaceForItem", () => {- it("should return shared tenant namespace for tenant root", () => {- const item = {- id: "tenant",- namespace: "shared-tenant-collection" as const,- };-- expect(getNamespaceForItem(item)).toBe(- PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,- );- });-- it("should return the item namespace for regular collections with namespace", () => {- const item = {- id: 123,- namespace: "shared-tenant-collection" as const,- };-- expect(getNamespaceForItem(item)).toBe("shared-tenant-collection");- });-- it("should return the item namespace for snippet collections", () => {- const item = {- id: 456,- namespace: "snippets" as const,- };-- expect(getNamespaceForItem(item)).toBe("snippets");- });-- it("should return undefined for regular collections without namespace", () => {- const item = {- id: 789,- namespace: undefined,- };-- expect(getNamespaceForItem(item)).toBeUndefined();- });-- it("should return undefined for null item", () => {- expect(getNamespaceForItem(null)).toBeUndefined();- });-- it("should return undefined for undefined item", () => {- expect(getNamespaceForItem(undefined)).toBeUndefined();- });-- it("should return undefined for root collection", () => {- const item = {- id: "root",- namespace: undefined,- };-- expect(getNamespaceForItem(item)).toBeUndefined();- });-});+import { isItemInCollectionOrItsDescendants } from "./utils";describe("isItemInCollectionOrItsDescendants", () => {it("returns false when collectionId is undefined", () => {diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsx b/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsxindex 2d73e28e6fc..a975de46a0b 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsx+++ b/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsx@@ -4,7 +4,6 @@ import { c, t } from "ttag";import { FormCollectionAndDashboardPicker } from "metabase/collections/containers/FormCollectionAndDashboardPicker";import { getEntityTypeFromCardType } from "metabase/collections/utils";import { FormFooter } from "metabase/common/components/FormFooter";-import type { CollectionPickerModel } from "metabase/common/components/Pickers/CollectionPicker";import { getPlaceholder } from "metabase/common/components/SaveQuestionForm/util";import { FormDashboardTabSelect } from "metabase/dashboard/components/FormDashboardTabSelect";import {@@ -17,6 +16,8 @@ import {} from "metabase/forms";import { Button, Radio, Stack, rem } from "metabase/ui";+import type { OmniPickerItem } from "../Pickers";+import S from "./SaveQuestionForm.module.css";import { useSaveQuestionContext } from "./context";@@ -53,7 +54,7 @@ export const SaveQuestionForm = ({? t`Save changes`: t`Replace original question, "${originalQuestion?.displayName()}"`;- const models: CollectionPickerModel[] =+ const models: OmniPickerItem["model"][] =question.type() === "question"? ["collection", "dashboard"]: ["collection"];@@ -127,12 +128,6 @@ export const SaveQuestionForm = ({entityType={getEntityTypeFromCardType(question.type())}collectionPickerModalProps={{models,- recentFilter: (items) =>- items.filter((item) => {- // narrow type and make sure it's a dashboard or- // collection that the user can write to- return item.model !== "table" && item.can_write;- }),}}/>)}diff --git a/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsx b/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsxindex 8f40f9c65a1..4fec6b9175f 100644--- a/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsx+++ b/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsx@@ -888,11 +888,6 @@ describe("SaveQuestionModal", () => {const questionModalTitle = () =>screen.getByRole("heading", { name: /new question/i });- const newDashBtn = () =>- screen.getByRole("button", {- name: /new dashboard/i,- });-const COLLECTION = {USER: BOBBY_TEST_COLLECTION,ROOT: createMockCollection({@@ -961,7 +956,7 @@ describe("SaveQuestionModal", () => {await userEvent.click(saveLocDropdown());await waitFor(() => expect(newCollBtn()).toBeInTheDocument());await userEvent.click(newCollBtn());- await screen.findByText("Give it a name");+ await screen.findByText(/Give it a name/);await userEvent.click(newCollCancelButton());await userEvent.click(selectCollCancelButton());await waitFor(() => expect(questionModalTitle()).toBeInTheDocument());@@ -1003,64 +998,5 @@ describe("SaveQuestionModal", () => {});});});-- describe("new dashboard modal", () => {- it("should have a new dashboard button in the collection picker", async () => {- await setup(getQuestion());- await userEvent.click(saveLocDropdown());- await waitFor(() => {- expect(newDashBtn()).toBeInTheDocument();- });- });-- it("should open new dashboard modal and return to dashboard modal when clicking close", async () => {- await setup(getQuestion());- await userEvent.click(saveLocDropdown());- await waitFor(() => expect(newDashBtn()).toBeInTheDocument());- await userEvent.click(newDashBtn());- await screen.findByText("Give it a name");- await within(- await screen.findByTestId("create-dashboard-on-the-go"),- ).findByRole("button", { name: /cancel/i });- await userEvent.click(selectCollCancelButton());- await waitFor(() => expect(questionModalTitle()).toBeInTheDocument());- });-- describe("new dashboard location", () => {- beforeEach(async () => {- await setup(getQuestion(), null, {- collectionEndpoints: {- collections: Object.values(COLLECTION),- rootCollection: COLLECTION.ROOT,- },- });- });-- it("should create dashboard inside nested folder", async () => {- await userEvent.click(saveLocDropdown());- await waitFor(() => expect(newDashBtn()).toBeInTheDocument());- await userEvent.click(- await screen.findByRole("link", {- name: new RegExp(BOBBY_TEST_COLLECTION.name),- }),- );- await userEvent.click(newDashBtn());- await screen.findByText("Give it a name");- });-- it("should create dashboard inside root folder", async () => {- await userEvent.click(saveLocDropdown());- await waitFor(() => expect(newDashBtn()).toBeInTheDocument());- await userEvent.click(newDashBtn());- await waitFor(async () => {- expect(- await screen.findByRole("heading", {- name: "Create a new dashboard",- }),- ).toBeInTheDocument();- });- });- });- });});});diff --git a/frontend/src/metabase/common/components/VirtualizedList/VariableHeightVirtualizedList.tsx b/frontend/src/metabase/common/components/VirtualizedList/VariableHeightVirtualizedList.tsxindex b4c3491ec67..d988a59b459 100644--- a/frontend/src/metabase/common/components/VirtualizedList/VariableHeightVirtualizedList.tsx+++ b/frontend/src/metabase/common/components/VirtualizedList/VariableHeightVirtualizedList.tsx@@ -32,7 +32,7 @@ export function VirtualizedList({count: children.length,getScrollElement: () => parentRef.current,estimateSize: () => estimatedItemSize,- overscan: 5, // makes unit testing easier+ overscan: Number(process.env.OVERSCAN) || 5, // makes unit testing easier});const items = virtualizer.getVirtualItems();diff --git a/frontend/src/metabase/common/hooks/use-get-personal-collection.ts b/frontend/src/metabase/common/hooks/use-get-personal-collection.tsnew file mode 100644index 00000000000..ae0af399957--- /dev/null+++ b/frontend/src/metabase/common/hooks/use-get-personal-collection.ts@@ -0,0 +1,19 @@+import { skipToken, useGetCollectionQuery } from "metabase/api";+import { useSelector } from "metabase/lib/redux";+import { getUserPersonalCollectionId } from "metabase/selectors/user";++/**+ * gets the personal collection for the current user+ */+export const useGetPersonalCollection = () => {+ const personalCollectionId = useSelector(getUserPersonalCollectionId);+ const response = useGetCollectionQuery(+ personalCollectionId+ ? {+ id: personalCollectionId,+ }+ : skipToken,+ );++ return response;+};diff --git a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsx b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsxindex e2127286feb..0bf62994250 100644--- a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsx+++ b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsx@@ -4,8 +4,10 @@ import { t } from "ttag";import { skipToken, useGetCardQuery, useGetDashboardQuery } from "metabase/api";import { isPublicCollection } from "metabase/collections/utils";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { DashboardPickerModal } from "metabase/common/components/Pickers/DashboardPicker";-import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker";+import {+ DashboardPickerModal,+ QuestionPickerModal,+} from "metabase/common/components/Pickers";import { useDashboardQuery } from "metabase/common/hooks";import CS from "metabase/css/core/index.css";import {@@ -36,6 +38,7 @@ import { SidebarItem } from "../../SidebarItem";import S from "../LinkOptions.module.css";const LINK_TARGETS = {+ // TODO: we can probably just have one picker to pick either a question or a dashboardquestion: {Entity: Questions,PickerComponent: QuestionPickerModal,@@ -309,8 +312,8 @@ export function LinkedEntityPicker({}}onClose={() => setIsPickerOpen(false)}options={{- showPersonalCollections: filterPersonalCollections !== "exclude",- showRootCollection: true,+ hasPersonalCollections: filterPersonalCollections !== "exclude",+ hasRootCollection: true,hasConfirmButtons: false,}}/>diff --git a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsxindex 236e4460bcc..2bc339a94f0 100644--- a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx@@ -61,6 +61,7 @@ const collectionInRootCollectionItem = createMockCollectionItem({id: PUBLIC_COLLECTION.id as number,name: PUBLIC_COLLECTION.name,model: "collection",+ here: ["card", "dashboard"],collection_id: PUBLIC_COLLECTION.id as number,});@@ -97,7 +98,20 @@ function setup({});setupCollectionItemsEndpoint({collection: PERSONAL_COLLECTION,- collectionItems: [],+ collectionItems: [+ createMockCollectionItem({+ id: 4545,+ name: "my card",+ model: "card",+ collection_id: PERSONAL_COLLECTION.id,+ }),+ createMockCollectionItem({+ id: 4546,+ name: "my dash",+ model: "dashboard",+ collection_id: PERSONAL_COLLECTION.id,+ }),+ ],});setupCollectionItemsEndpoint({collection: PUBLIC_COLLECTION,@@ -199,12 +213,13 @@ describe("LinkedEntityPicker", () => {const call = fetchMock.callHistory.lastCall("path:/api/search");const urlObject = new URL(checkNotNull(call?.request?.url));expect(urlObject.pathname).toEqual("/api/search");- expect(urlSearchParamsToObject(urlObject.searchParams)).toEqual({- context: "entity-picker",- models: "dashboard",- q: typedText,- filter_items_in_personal_collection: "exclude",- });+ expect(urlSearchParamsToObject(urlObject.searchParams)).toEqual(+ expect.objectContaining({+ context: "entity-picker",+ q: typedText,+ filter_items_in_personal_collection: "exclude",+ }),+ );});});});@@ -260,11 +275,12 @@ describe("LinkedEntityPicker", () => {const call = fetchMock.callHistory.lastCall("path:/api/search");const urlObject = new URL(checkNotNull(call?.request?.url));expect(urlObject.pathname).toEqual("/api/search");- expect(urlSearchParamsToObject(urlObject.searchParams)).toEqual({- context: "entity-picker",- models: "dashboard",- q: typedText,- });++ const params = Object.keys(+ urlSearchParamsToObject(urlObject.searchParams),+ );+ expect(params).toContain("q");+ expect(params).not.toContain("filter_items_in_personal_collection");});});});@@ -343,12 +359,13 @@ describe("LinkedEntityPicker", () => {"card","dataset",]);- expect(urlSearchParamsToObject(urlObject.searchParams)).toEqual({- context: "entity-picker",- models: ["card", "dataset"],- q: typedText,- filter_items_in_personal_collection: "exclude",- });+ expect(urlSearchParamsToObject(urlObject.searchParams)).toEqual(+ expect.objectContaining({+ context: "entity-picker",+ q: typedText,+ filter_items_in_personal_collection: "exclude",+ }),+ );});});});@@ -375,7 +392,9 @@ describe("LinkedEntityPicker", () => {expect(await screen.findByText(PUBLIC_COLLECTION.name),).toBeInTheDocument();- expect(screen.getByText(PERSONAL_COLLECTION.name)).toBeInTheDocument();+ expect(+ screen.getByText(new RegExp(PERSONAL_COLLECTION.name)),+ ).toBeInTheDocument();expect(await screen.findByText(questionCollectionItem.name),).toBeInTheDocument();@@ -393,7 +412,7 @@ describe("LinkedEntityPicker", () => {await screen.findByPlaceholderText(/search/i),typedText,);- await userEvent.click(screen.getByText("Everywhere"));+ await userEvent.click(await screen.findByText("Everywhere"));expect(await screen.findByText(questionSearchResult.name),@@ -401,12 +420,11 @@ describe("LinkedEntityPicker", () => {const call = fetchMock.callHistory.lastCall("path:/api/search");const urlObject = new URL(checkNotNull(call?.request?.url));- expect(urlObject.pathname).toEqual("/api/search");- expect(urlSearchParamsToObject(urlObject.searchParams)).toEqual({- context: "entity-picker",- models: ["card", "dataset"],- q: typedText,- });+ const params = Object.keys(+ urlSearchParamsToObject(urlObject.searchParams),+ );+ expect(params).toContain("q");+ expect(params).not.toContain("filter_items_in_personal_collection");});});});diff --git a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx b/frontend/src/metabase/dashboard/components/DashboardGrid.tsxindex 1176fc7bae7..fec686667d5 100644--- a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardGrid.tsx@@ -6,9 +6,13 @@ import { t } from "ttag";import _ from "underscore";import { ExplicitSize } from "metabase/common/components/ExplicitSize";+import {+ type OmniPickerItem,+ type OmniPickerQuestionItem,+ isInDbTree,+} from "metabase/common/components/Pickers";import {QuestionPickerModal,- type QuestionPickerValueItem,getQuestionPickerValue,} from "metabase/common/components/Pickers/QuestionPicker";import { ContentViewportContext } from "metabase/common/context/ContentViewportContext";@@ -41,10 +45,8 @@ import type {Dashboard,DashboardCard,DashboardTabId,- RecentItem,VisualizerVizDefinition,} from "metabase-types/api";-import { isRecentCollectionItem } from "metabase-types/api";import type { State } from "metabase-types/store";import type { SetDashCardAttributesOpts } from "../actions";@@ -386,9 +388,9 @@ class DashboardGridInner extends Component<!!replaceCardModalDashCard &&isQuestionDashCard(replaceCardModalDashCard);- const handleSelect = (nextCard: QuestionPickerValueItem) => {- if (!hasValidDashCard) {- return;+ const handleSelect = (nextCard: OmniPickerQuestionItem) => {+ if (!hasValidDashCard || typeof nextCard.id === "string") {+ throw new Error(t`Invalid card selected`);}replaceCard({@@ -408,15 +410,18 @@ class DashboardGridInner extends Component<handleClose();};- const replaceCardModalRecentFilter = (items: RecentItem[]) => {- return items.filter((item) => {- if (isRecentCollectionItem(item) && item.dashboard) {- if (item.dashboard.id !== dashboard.id) {- return false;- }+ const shouldDisableItem = (item: OmniPickerItem) => {+ // don't allow adding items that are already saved in a different dashboard+ // proably only applicable to search and recents+ if (!isInDbTree(item) && item.dashboard_id) {+ if (item.dashboard_id !== dashboard.id) {+ return true;}+ }+ if (item.model === "dashboard" && item.id !== dashboard.id) {return true;- });+ }+ return false;};const handleClose = () => {@@ -435,10 +440,11 @@ class DashboardGridInner extends Component<? getQuestionPickerValue(replaceCardModalDashCard.card): undefined}- models={["card", "dataset", "metric"]}+ models={["card", "dataset", "metric", "dashboard"]}+ options={{ hasConfirmButtons: false }}onChange={handleSelect}onClose={handleClose}- recentFilter={replaceCardModalRecentFilter}+ isDisabledItem={shouldDisableItem}/>);}diff --git a/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx b/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsxindex eb27cfc6653..f654674fcc7 100644--- a/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx@@ -3,8 +3,7 @@ import _ from "underscore";import { useGetCollectionQuery } from "metabase/api";import { Link } from "metabase/common/components/Link";-import { MoveModal } from "metabase/common/components/MoveModal";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import { MoveModal } from "metabase/common/components/Pickers/MoveModal/MoveModal";import { ROOT_COLLECTION } from "metabase/entities/collections";import { Dashboards } from "metabase/entities/dashboards";import { connect } from "metabase/lib/redux";@@ -33,16 +32,20 @@ function DashboardMoveModal({options: any,) => void;}) {- const recentsAndSearchFilter = (item: CollectionPickerItem) =>- item.model === "collection" && item.id === dashboard.collection_id;-return (<MoveModaltitle={t`Move dashboard to…`}onClose={onClose}- initialCollectionId={dashboard.collection_id ?? "root"}canMoveToDashboard={false}- entityType="dashboard"+ movingItem={{+ ...dashboard,+ collection: {+ id: dashboard.collection?.id || "root",+ name: dashboard.collection?.name || "",+ namespace: dashboard.collection?.namespace,+ }, // parent collection info+ model: "dashboard",+ }}onMove={async (destination) => {await setDashboardCollection({ id: dashboard.id }, destination, {notify: {@@ -55,7 +58,6 @@ function DashboardMoveModal({});onClose();}}- recentAndSearchFilter={recentsAndSearchFilter}/>);}diff --git a/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsx b/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsxindex 4c87fb33637..8d45ec73585 100644--- a/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsx+++ b/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsx@@ -6,8 +6,8 @@ import * as Yup from "yup";import { useGetDashboardQuery } from "metabase/api";import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker/FormCollectionPicker";import { Button } from "metabase/common/components/Button";-import type { FilterItemsInPersonalCollection } from "metabase/common/components/EntityPicker";import { FormFooter } from "metabase/common/components/FormFooter";+import type { FilterItemsInPersonalCollection } from "metabase/common/components/Pickers";import { Dashboards } from "metabase/entities/dashboards";import {Form,diff --git a/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx b/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsxindex 5a8cfb6fef8..8fbaa1a5510 100644--- a/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx+++ b/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx@@ -4,8 +4,8 @@ import * as Yup from "yup";import { useCreateDashboardMutation } from "metabase/api";import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker/FormCollectionPicker";-import type { FilterItemsInPersonalCollection } from "metabase/common/components/EntityPicker";import { FormFooter } from "metabase/common/components/FormFooter";+import type { FilterItemsInPersonalCollection } from "metabase/common/components/Pickers";import { Collections } from "metabase/entities/collections";import {Form,diff --git a/frontend/src/metabase/documents/components/DocumentPage.tsx b/frontend/src/metabase/documents/components/DocumentPage.tsxindex b55edab86ad..de2ddf5caae 100644--- a/frontend/src/metabase/documents/components/DocumentPage.tsx+++ b/frontend/src/metabase/documents/components/DocumentPage.tsx@@ -505,10 +505,6 @@ export const DocumentPage = ({<CollectionPickerModaltitle={t`Where should we save this document?`}onClose={() => setCollectionPickerMode(null)}- options={{- showPersonalCollections: true,- showRootCollection: true,- }}entityType="document"onChange={async (collection) => {if (collectionPickerMode === "save") {diff --git a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsxindex a46fdc58416..37ebf8cdb78 100644--- a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsx+++ b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHub.unit.spec.tsx@@ -10,7 +10,13 @@ import {setupSearchEndpoints,} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";-import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";import {createMockCollection,createMockRecentTableDatabaseInfo,@@ -31,6 +37,7 @@ import { EmbeddingHub } from "./EmbeddingHub";const mockPush = push as jest.MockedFunction<typeof push>;const setup = ({ isAdmin = true, checklist = {} } = {}) => {+ mockGetBoundingClientRect();const state = createMockState({currentUser: createMockUser({ is_superuser: isAdmin }),settings: mockSettings({@@ -101,7 +108,7 @@ describe("EmbeddingHub", () => {it("opens table picker when 'Create a dashboard' is clicked", async () => {setup();- await userEvent.click(screen.getByText("Create a dashboard"));+ await userEvent.click(await screen.findByText("Create a dashboard"));const dialog = await screen.findByTestId("entity-picker-modal");expect(dialog).toBeInTheDocument();@@ -110,7 +117,7 @@ describe("EmbeddingHub", () => {await within(dialog).findByText("Choose a table to generate a dashboard"),).toBeInTheDocument();- await userEvent.click(await screen.findByText("Recents"));+ await userEvent.click(await screen.findByText("Recent items"));expect(await within(dialog).findByText("Foo Bar Table"),diff --git a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubXrayPickerModal.tsx b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubXrayPickerModal.tsxindex 0a09d85037a..1cbc1638e1c 100644--- a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubXrayPickerModal.tsx+++ b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubXrayPickerModal.tsx@@ -2,7 +2,6 @@ import { push } from "react-router-redux";import { t } from "ttag";import { DataPickerModal } from "metabase/common/components/Pickers/DataPicker";-import type { TablePickerValue } from "metabase/common/components/Pickers/TablePicker";import { useDispatch } from "metabase/lib/redux";import type { TableId } from "metabase-types/api";@@ -28,14 +27,13 @@ export const EmbeddingHubXrayPickerModal = ({return (<DataPickerModaltitle={t`Choose a table to generate a dashboard`}- value={{ model: "table", id: null } as unknown as TablePickerValue}models={["table"]}onChange={handleTableSelect}onClose={onClose}options={{- showLibrary: false,- showRootCollection: false,- showPersonalCollections: false,+ hasLibrary: false,+ hasRootCollection: false,+ hasPersonalCollections: false,}}/>);diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsxindex 176c2bb9e71..096e9b74ac3 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedResourceStep.tsx@@ -2,9 +2,11 @@ import { useDisclosure } from "@mantine/hooks";import { match } from "ts-pattern";import { t } from "ttag";-import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";-import { DashboardPickerModal } from "metabase/common/components/Pickers/DashboardPicker";-import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker";+import {+ CollectionPickerModal,+ DashboardPickerModal,+ QuestionPickerModal,+} from "metabase/common/components/Pickers";import { ActionIcon, Card, Group, Icon, Stack, Text } from "metabase/ui";import type { CollectionId } from "metabase-types/api";@@ -183,7 +185,6 @@ export const SelectEmbedResourceStep = () => {value={{id: selectedItemId ?? "root",model: "collection",- collection_id: null,}}onChange={handlePickerModalResourceSelect}onClose={closePicker}diff --git a/frontend/src/metabase/entities/collections/constants.ts b/frontend/src/metabase/entities/collections/constants.tsindex 4c19b228965..598a60900ef 100644--- a/frontend/src/metabase/entities/collections/constants.ts+++ b/frontend/src/metabase/entities/collections/constants.ts@@ -1,9 +1,11 @@import { t } from "ttag";+import type { CollectionId } from "metabase-types/api";+export const DEFAULT_COLLECTION_COLOR_ALIAS = "brand";export const ROOT_COLLECTION = {- id: "root" as const,+ id: "root" as CollectionId,get name() {return t`Our analytics`;},@@ -25,7 +27,7 @@ export const PERSONAL_COLLECTION = {// fake collection for admins that contains all other user's collectionsexport const PERSONAL_COLLECTIONS = {- id: "personal" as const, // placeholder id+ id: "personal" as CollectionId,get name() {return t`All personal collections`;},diff --git a/frontend/src/metabase/nav/components/search/RecentsList/RecentsList.tsx b/frontend/src/metabase/nav/components/search/RecentsList/RecentsList.tsxindex 5337c4bcc31..1e02adc599e 100644--- a/frontend/src/metabase/nav/components/search/RecentsList/RecentsList.tsx+++ b/frontend/src/metabase/nav/components/search/RecentsList/RecentsList.tsx@@ -5,10 +5,16 @@ import { getName } from "metabase/lib/name";import { useDispatch } from "metabase/lib/redux";import { RecentsListContent } from "metabase/nav/components/search/RecentsList/RecentsListContent";import { Paper } from "metabase/ui";-import type { RecentItem, UnrestrictedLinkEntity } from "metabase-types/api";+import type {+ RecentContexts,+ RecentItem,+ UnrestrictedLinkEntity,+} from "metabase-types/api";import { getItemUrl, recentsFilter } from "./util";+const DEFAULT_RECENTS_CONTEXT: RecentContexts[] = ["selections", "views"];+type RecentsListProps = {onClick?: (elem: UnrestrictedLinkEntity) => void;className?: string;@@ -16,7 +22,7 @@ type RecentsListProps = {export const RecentsList = ({ onClick, className }: RecentsListProps) => {const { data = [], isLoading: isRecentsListLoading } = useListRecentsQuery(- undefined,+ { context: DEFAULT_RECENTS_CONTEXT },{ refetchOnMountOrArgChange: true },);diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVUpload.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVUpload.tsxindex d31939c1bb1..51b20f3e20f 100644--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVUpload.tsx+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVUpload.tsx@@ -15,9 +15,9 @@ import { getComposedDragProps } from "metabase/collections/components/Collectionimport { useGetDefaultCollectionId } from "metabase/collections/hooks";import { CollectionName } from "metabase/common/components/CollectionName";import {- type CollectionPickerItem,CollectionPickerModal,-} from "metabase/common/components/Pickers/CollectionPicker";+ type OmniPickerItem,+} from "metabase/common/components/Pickers";import { UploadInput } from "metabase/common/components/upload";import { useDispatch } from "metabase/lib/redux";import {@@ -66,7 +66,7 @@ export const CSVUpload = ({);const handleCollectionChange = useCallback(- (item: CollectionPickerItem) => {+ (item: OmniPickerItem) => {// The model should always be a collection since we explicitly set it in the CollectionPickerModal.// In case anything ever changes in the picker, we want to ignore it in this handler.if (item.model !== "collection") {@@ -294,18 +294,12 @@ export const CSVUpload = ({onChange={handleCollectionChange}onClose={() => closeCollectionPicker()}options={{- showPersonalCollections: true,- showRootCollection: true,- showSearch: true,+ hasPersonalCollections: true,+ hasRootCollection: true,+ hasSearch: true,confirmButtonText: t`Select this collection`,}}- models={["collection"]}entityType="dataset"- recentFilter={(items) =>- items.filter((item) => {- return item.model !== "table" && item.can_write;- })- }/>)}</>diff --git a/frontend/src/metabase/plugins/oss/data-studio.ts b/frontend/src/metabase/plugins/oss/data-studio.tsindex 0eae59e3801..d4517e524bc 100644--- a/frontend/src/metabase/plugins/oss/data-studio.ts+++ b/frontend/src/metabase/plugins/oss/data-studio.ts@@ -1,13 +1,13 @@import type { Store } from "@reduxjs/toolkit";import type { ComponentType, ReactNode } from "react";-import type { MiniPickerCollectionItem } from "metabase/common/components/Pickers/MiniPicker/types";import type Question from "metabase-lib/v1/Question";import type {Collection,CollectionItem,CollectionItemModel,CollectionType,+ LibraryCollection,} from "metabase-types/api";import type { State } from "metabase-types/store";@@ -55,11 +55,11 @@ type DataStudioPlugin = {type: CollectionType;}) => CollectionItem | undefined;useGetLibraryCollection: (props?: { skip?: boolean }) => {- data: undefined | MiniPickerCollectionItem;+ data: undefined | LibraryCollection;isLoading: boolean;};useGetResolvedLibraryCollection: (props?: { skip?: boolean }) => {- data: undefined | MiniPickerCollectionItem;+ data: undefined | LibraryCollection | CollectionItem;isLoading: boolean;};};diff --git a/frontend/src/metabase/plugins/oss/tenants.ts b/frontend/src/metabase/plugins/oss/tenants.tsindex af796b18934..f85899a2a4c 100644--- a/frontend/src/metabase/plugins/oss/tenants.ts+++ b/frontend/src/metabase/plugins/oss/tenants.ts@@ -1,10 +1,14 @@import type React from "react";-import type { CollectionItemListProps } from "metabase/common/components/Pickers/CollectionPicker/types";+import type {+ OmniPickerCollectionItem,+ OmniPickerItem,+} from "metabase/common/components/Pickers";import type { CollectionTreeItem } from "metabase/entities/collections/utils";import type {Collection,CollectionId,+ CollectionItemModel,CollectionNamespace,Group,User,@@ -42,9 +46,9 @@ const getDefaultPluginTenants = () => ({canCreateSharedCollection: boolean;sharedTenantCollections: Collection[] | undefined;}>,- TenantCollectionItemList: (_props: CollectionItemListProps) =>+ TenantCollectionItemList: (_props: { pathIndex: number }) =>null as React.ReactElement | null,- TenantSpecificCollectionsItemList: (_props: CollectionItemListProps) =>+ TenantSpecificCollectionsItemList: (_props: { pathIndex: number }) =>null as React.ReactElement | null,TenantCollectionList: PluginPlaceholder,TenantUsersList: PluginPlaceholder,@@ -56,22 +60,15 @@ const getDefaultPluginTenants = () => ({EditUserStrategyModal: PluginPlaceholder,getNewUserModalTitle: (_isExternal: boolean) => null as string | null,getFormGroupsTitle: (_isExternal: boolean) => null as string | null,- SHARED_TENANT_NAMESPACE: null as CollectionNamespace,- isTenantNamespace: (_namespace?: CollectionNamespace) => false,- isTenantCollectionId: (_id: CollectionId) => false,- getNamespaceForTenantId: (_id: CollectionId) => null as CollectionNamespace,- getTenantCollectionPathPrefix: (_collection: TenantCollectionPathItem) =>- null as CollectionId[] | null,+ // cannot be null, because that refers to the default namespace+ SHARED_TENANT_NAMESPACE: "none" as CollectionNamespace,+ // cannot be null, because that refers to the default namespace+ TENANT_SPECIFIC_NAMESPACE: "none" as CollectionNamespace,+ canPlaceEntityInCollection: () => true,+ getRootCollectionItem: () => null as OmniPickerCollectionItem | null,getTenantRootDisabledReason: () => null as string | null,getNamespaceDisplayName: (_namespace?: CollectionNamespace) =>null as string | null,- TENANT_SPECIFIC_COLLECTIONS: null as {- id: "tenant-specific";- name: string;- location: string;- path: CollectionId[];- can_write: boolean;- } | null,getFlattenedCollectionsForNavbar: () => [],useTenantMainNavbarData: () => ({canCreateSharedCollection: false,@@ -109,12 +106,12 @@ export const PLUGIN_TENANTS: {canCreateSharedCollection: boolean;sharedTenantCollections: Collection[] | undefined;}>;- TenantCollectionItemList: (- props: CollectionItemListProps,- ) => React.ReactElement | null;- TenantSpecificCollectionsItemList: (- props: CollectionItemListProps,- ) => React.ReactElement | null;+ TenantCollectionItemList: (props: {+ pathIndex: number;+ }) => React.ReactElement | null;+ TenantSpecificCollectionsItemList: (props: {+ pathIndex: number;+ }) => React.ReactElement | null;TenantCollectionList: React.ComponentType;TenantUsersList: React.ComponentType;TenantUsersPersonalCollectionList: React.ComponentType<{@@ -127,21 +124,19 @@ export const PLUGIN_TENANTS: {getNewUserModalTitle: (isExternal: boolean) => string | null;getFormGroupsTitle: (isExternal: boolean) => string | null;SHARED_TENANT_NAMESPACE: CollectionNamespace;- isTenantNamespace: (namespace?: CollectionNamespace) => boolean;- isTenantCollectionId: (id: CollectionId) => boolean;- getNamespaceForTenantId: (id: CollectionId) => CollectionNamespace;- getTenantCollectionPathPrefix: (- collection: TenantCollectionPathItem,- ) => CollectionId[] | null;+ TENANT_SPECIFIC_NAMESPACE: CollectionNamespace;+ canPlaceEntityInCollection: ({+ entityType,+ collection,+ }: {+ entityType?: CollectionItemModel;+ collection: OmniPickerItem;+ }) => boolean;+ getRootCollectionItem: (args: {+ namespace: CollectionNamespace;+ }) => OmniPickerCollectionItem | null;getTenantRootDisabledReason: () => string | null;getNamespaceDisplayName: (namespace?: CollectionNamespace) => string | null;- TENANT_SPECIFIC_COLLECTIONS: {- id: "tenant-specific";- name: string;- location: string;- path: CollectionId[];- can_write: boolean;- } | null;getFlattenedCollectionsForNavbar: (args: {currentUser: User | null;sharedTenantCollections: Collection[] | undefined;diff --git a/frontend/src/metabase/plugins/oss/transforms.ts b/frontend/src/metabase/plugins/oss/transforms.tsindex 09d43bafa68..56dbf6a558e 100644--- a/frontend/src/metabase/plugins/oss/transforms.ts+++ b/frontend/src/metabase/plugins/oss/transforms.ts@@ -3,6 +3,10 @@ import type { ComponentType, Context, ReactNode } from "react";import { createContext } from "react";import type { TagType } from "metabase/api/tags";+import type {+ OmniPickerCollectionItem,+ OmniPickerItem,+} from "metabase/common/components/Pickers";import type { UseQuery } from "metabase/entities/containers/rtk-query/types/rtk";import {NotFoundPlaceholder,@@ -11,6 +15,7 @@ import {import type Question from "metabase-lib/v1/Question";import type {CheckDependenciesResponse,+ CollectionNamespace,GetDependencyGraphRequest,PythonTransformSourceDraft,Transform,@@ -21,9 +26,7 @@ import type {import type { State } from "metabase-types/store";// Types-export type TransformPickerItem = {- id: TransformId;- name: string;+export type TransformPickerItem = OmniPickerItem & {model: "transform";};@@ -36,7 +39,9 @@ export type TransformsPlugin = {isEnabled: boolean;canAccessTransforms: (state: State) => boolean;getDataStudioTransformRoutes(): ReactNode;- TransformPicker: ComponentType<TransformPickerProps>;+ getRootCollectionItem: (args: {+ namespace: CollectionNamespace;+ }) => OmniPickerCollectionItem | null;useGetTransformQuery: UseQuery<QueryDefinition<TransformId, BaseQueryFn, TagType, Transform>>;@@ -146,7 +151,7 @@ const getDefaultPluginTransforms = (): TransformsPlugin => ({isEnabled: false,canAccessTransforms: () => false,getDataStudioTransformRoutes: () => null,- TransformPicker: PluginPlaceholder,+ getRootCollectionItem: () => null,useGetTransformQuery:(() => []) as unknown as TransformsPlugin["useGetTransformQuery"],});diff --git a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.tsx b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.tsxindex 23cd7b2a996..e716233da9e 100644--- a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.tsx+++ b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.tsx@@ -2,20 +2,21 @@ import { useCallback } from "react";import { t } from "ttag";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import {+ type OmniPickerItem,+ isInDbTree,+} from "metabase/common/components/Pickers";import { DashboardPickerModal } from "metabase/common/components/Pickers/DashboardPicker";+import { getCollectionType } from "metabase/common/components/Pickers/EntityPicker/utils";import { ROOT_COLLECTION } from "metabase/entities/collections";import { useSelector } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";+import { PLUGIN_DATA_STUDIO } from "metabase/plugins";import { getUserPersonalCollectionId } from "metabase/selectors/user";-import type { Card, Dashboard, RecentItem } from "metabase-types/api";+import type { Card, Dashboard } from "metabase-types/api";import { useMostRecentlyViewedDashboard } from "./hooks";-import {- filterPersonalRecents,- filterWritableDashboards,- filterWritableRecents,- shouldDisableItem,-} from "./utils";+import { isInPersonalCollection } from "./utils";const getTitle = ({ type }: Card) => {if (type === "model") {@@ -76,15 +77,41 @@ export const AddToDashSelectDashModal = ({mostRecentlyViewedDashboard?.id &&(!isQuestionInPersonalCollection || isRecentDashboardInPersonalCollection);- const recentsFilter = useCallback(- (items: RecentItem[]) => {- const writableRecents = filterWritableRecents(items);+ const shouldDisable = useCallback(+ (item: OmniPickerItem) => {+ if (isInDbTree(item)) {+ return true;+ }++ if (item.model === "dashboard" && !item.can_write) {+ return true;+ }- if (isQuestionInPersonalCollection && personalCollectionId) {- return filterPersonalRecents(writableRecents, personalCollectionId);- } else {- return writableRecents;+ if (+ isQuestionInPersonalCollection &&+ personalCollectionId &&+ item.model === "dashboard"+ ) {+ // if the question is in a personal collection, hide dashboards that aren't in the personal collection+ const isPersonalDash = isInPersonalCollection(+ item,+ personalCollectionId,+ );++ return !isPersonalDash;}++ // if there can't be dashboards in the collection, you can't add a question to one there+ if (+ !PLUGIN_DATA_STUDIO.canPlaceEntityInCollectionOrDescendants(+ "dashboard",+ getCollectionType(item),+ )+ ) {+ return true;+ }++ return false;},[isQuestionInPersonalCollection, personalCollectionId],);@@ -110,13 +137,16 @@ export const AddToDashSelectDashModal = ({}}options={{- allowCreateNew: true,- showPersonalCollections: true,- showRootCollection: !isQuestionInPersonalCollection,+ hasPersonalCollections: true,+ hasRootCollection: !isQuestionInPersonalCollection,+ }}+ searchParams={{+ filter_items_in_personal_collection: isQuestionInPersonalCollection+ ? "only"+ : undefined,}}- shouldDisableItem={shouldDisableItem}- searchFilter={filterWritableDashboards}- recentFilter={recentsFilter}+ namespaces={isQuestionInPersonalCollection ? [null] : undefined}+ isDisabledItem={shouldDisable}/>);};diff --git a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsxindex be5664c62fd..eff38acc6e5 100644--- a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx@@ -15,6 +15,7 @@ import {mockGetBoundingClientRect,renderWithProviders,screen,+ waitFor,waitForLoaderToBeRemoved,} from "__support__/ui";import { getNextId } from "__support__/utils";@@ -54,7 +55,6 @@ const DASHBOARD = createMockDashboard({const DASHBOARD_AT_ROOT = createMockDashboard({id: getNextId(),name: "Dashboard at root",- collection_id: null,model: "dashboard",});@@ -319,14 +319,7 @@ describe("AddToDashSelectDashModal", () => {mostRecentlyViewedDashboard: DASHBOARD,});- expect(screen.getByText("Loading...")).toBeInTheDocument();- });-- it("should show error", async () => {- const ERROR = "Server Error!";- await setup({ error: ERROR, mostRecentlyViewedDashboard: DASHBOARD });-- expect(await screen.findByText(ERROR)).toBeInTheDocument();+ expect(await screen.findByText("Loading...")).toBeInTheDocument();});it("should render dashboards when opening the root collection (public collection)", async () => {@@ -470,18 +463,9 @@ describe("AddToDashSelectDashModal", () => {card: CARD_IN_PUBLIC_SUBCOLLECTION,});- expect(await findPickerItem(ROOT_COLLECTION.name)).toHaveAttribute(- "data-active",- "true",- );- expect(await findPickerItem(COLLECTION.name)).toHaveAttribute(- "data-active",- "true",- );- expect(await findPickerItem(SUBCOLLECTION.name)).toHaveAttribute(- "data-active",- "true",- );+ await expectActiveItem(ROOT_COLLECTION.name);+ await expectActiveItem(COLLECTION.name);+ await expectActiveItem(SUBCOLLECTION.name);});it("should not render public collections when the question is in a personal collection", async () => {@@ -554,12 +538,13 @@ describe("AddToDashSelectDashModal", () => {const call = fetchMock.callHistory.lastCall("path:/api/search");const urlObject = new URL(checkNotNull(call?.request?.url));expect(urlObject.pathname).toEqual("/api/search");- expect(Object.fromEntries(urlObject.searchParams.entries())).toEqual({- context: "entity-picker",- models: "dashboard",- q: typedText,- filter_items_in_personal_collection: "only",- });+ expect(Object.fromEntries(urlObject.searchParams.entries())).toEqual(+ expect.objectContaining({+ context: "entity-picker",+ q: typedText,+ filter_items_in_personal_collection: "only",+ }),+ );});it("when adding a public question, should not send a personal-only query param", async () => {@@ -584,11 +569,9 @@ describe("AddToDashSelectDashModal", () => {const call = fetchMock.callHistory.lastCall("path:/api/search");const urlObject = new URL(checkNotNull(call?.request?.url));expect(urlObject.pathname).toEqual("/api/search");- expect(Object.fromEntries(urlObject.searchParams.entries())).toEqual({- context: "entity-picker",- models: "dashboard",- q: typedText,- });+ expect(+ Object.keys(Object.fromEntries(urlObject.searchParams.entries())),+ ).not.toContain("filter_items_in_personal_collection");});});@@ -632,11 +615,9 @@ describe("AddToDashSelectDashModal", () => {async function assertPath(collections: Collection[]) {await waitForLoaderToBeRemoved();- return Promise.all(- collections.map(async (collection) => {- return expect(await findPickerItem(collection.name)).toBeInTheDocument();- }),- );+ for (const collection of collections) {+ expect(await findPickerItem(collection.name)).toBeInTheDocument();+ }}const clickPickerItem = async (item: string) => {@@ -646,3 +627,10 @@ const clickPickerItem = async (item: string) => {const findPickerItem = async (item: string) => {return screen.findByRole("link", { name: new RegExp(item) });};++const expectActiveItem = async (itemName: string) =>+ waitFor(() =>+ expect(+ screen.getByRole("link", { name: new RegExp(itemName) }),+ ).toHaveAttribute("data-active", "true"),+ );diff --git a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/utils.ts b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/utils.tsindex 347e4455cc4..3e85138178c 100644--- a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/utils.ts+++ b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/utils.ts@@ -1,64 +1,15 @@-import {- coerceCollectionId,- isPublicCollection,-} from "metabase/collections/utils";-import type { DashboardPickerItem } from "metabase/common/components/Pickers/DashboardPicker";-import { ROOT_COLLECTION } from "metabase/entities/collections/constants";-import type {- CollectionId,- Dashboard,- RecentItem,- SearchResult,-} from "metabase-types/api";+import type { OmniPickerItem } from "metabase/common/components/Pickers";+import type { CollectionId } from "metabase-types/api";-interface GetInitialOpenCollectionIdProps {- isQuestionInPersonalCollection: boolean;- mostRecentlyViewedDashboard: Dashboard | undefined;-}--export const getInitialOpenCollectionId = ({- isQuestionInPersonalCollection,- mostRecentlyViewedDashboard,-}: GetInitialOpenCollectionIdProps): undefined | CollectionId => {- if (!mostRecentlyViewedDashboard) {- return undefined;- }-- if (- isQuestionInPersonalCollection &&- isInPublicCollection(mostRecentlyViewedDashboard)- ) {- return ROOT_COLLECTION.id;- }-- return coerceCollectionId(mostRecentlyViewedDashboard.collection_id);-};--export function isInPublicCollection(dashboard: Dashboard | undefined) {- return isPublicCollection(dashboard?.collection ?? ROOT_COLLECTION);-}--export const shouldDisableItem = (item: DashboardPickerItem) => {- return item.model === "dashboard" && item.can_write === false;-};--export const filterWritableDashboards = (- dashes: SearchResult[],-): SearchResult[] => {- return dashes.filter((dash) => dash.can_write);-};--export const filterWritableRecents = (dashes: RecentItem[]) => {- return dashes.filter((dash) => dash.model !== "table" && dash.can_write);-};--export const filterPersonalRecents = (- dashes: RecentItem[],+export const isInPersonalCollection = (+ dash: OmniPickerItem,personalCollectionId: CollectionId,) => {- return dashes.filter(- (dash) =>- dash.model !== "table" &&- dash.parent_collection.id === personalCollectionId,- );+ if ("is_personal" in dash && dash.is_personal != null) {+ return dash.is_personal;+ }+ if ("location" in dash && !!dash.location) {+ return dash.location.split("/")[1] === String(personalCollectionId);+ }+ return false;};diff --git a/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityList.tsx b/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityList.tsxindex 578aac07acf..6b59211403a 100644--- a/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityList.tsx+++ b/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityList.tsx@@ -83,7 +83,9 @@ export const SavedEntityList = ({size: 16,}}onSelect={() => onSelect(virtualTableId)}- rightIcon={PLUGIN_MODERATION.getStatusIcon(moderated_status)}+ rightIcon={PLUGIN_MODERATION.getStatusIcon(+ moderated_status ?? undefined,+ )}/>);})}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.tsxindex ee28dffe573..d2704faa68d 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@@ -102,7 +102,7 @@ function SnippetFormInner({<FormCollectionPickername="collection_id"title={t`Folder this should be in`}- type="snippet-collections"+ collectionPickerModalProps={{ namespaces: ["snippets"] }}/>)}<Flex align="center" justify="space-between">diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsxindex a3394a377f4..1f3ed40bf8d 100644--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx@@ -3,8 +3,7 @@ import { type ReactNode, useMemo, useState } from "react";import { ResizableBox } from "react-resizable";import { useWindowSize } from "react-use";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";-import type { DataPickerItem } from "metabase/common/components/Pickers/DataPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import { ResizeHandle } from "metabase/common/components/ResizeHandle";import { useSetting } from "metabase/common/hooks";import {@@ -54,9 +53,7 @@ type QueryEditorBodyProps = {isShowingDataReference: boolean;isShowingSnippetSidebar: boolean;shouldDisableDatabase?: (database: QueryEditorDatabasePickerItem) => boolean;- shouldDisableItem?: (- item: DataPickerItem | CollectionPickerItem | RecentCollectionItem,- ) => boolean;+ shouldDisableItem?: (item: OmniPickerItem | RecentCollectionItem) => boolean;shouldShowLibrary?: boolean;onBlur?: () => void;onChange: (newQuestion: Question) => void;diff --git a/frontend/src/metabase/querying/editor/types.ts b/frontend/src/metabase/querying/editor/types.tsindex b38db85b728..8c657b699fa 100644--- a/frontend/src/metabase/querying/editor/types.ts+++ b/frontend/src/metabase/querying/editor/types.ts@@ -1,5 +1,4 @@-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker/types";-import type { DataPickerItem } from "metabase/common/components/Pickers/DataPicker/types";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import type { MiniPickerTableItem } from "metabase/common/components/Pickers/MiniPicker/types";import type { SelectionRange } from "metabase/query_builder/components/NativeQueryEditor/types";import type {@@ -21,8 +20,7 @@ export type QueryEditorSidebarType =export type QueryEditorModalType = "preview-query";export type QueryEditorDataPickerItem =- | DataPickerItem- | CollectionPickerItem+ | OmniPickerItem| RecentCollectionItem| MiniPickerTableItem;diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsxindex aa870e3be31..0fe6c2637da 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx@@ -299,7 +299,6 @@ describe("Notebook Editor > Join Step", () => {);const modal = await screen.findByTestId("entity-picker-modal");- await userEvent.click(await within(modal).findByText("Databases"));expect(await within(modal).findByText("Products")).toBeInTheDocument();expect(await within(modal).findByText("People")).toBeInTheDocument();@@ -362,10 +361,7 @@ describe("Notebook Editor > Join Step", () => {const modal = await screen.findByTestId("entity-picker-modal");- expect(await within(modal).findByText("Recents")).toBeInTheDocument();- expect(- await within(modal).findByRole("tab", { name: /Recents/i }),- ).toHaveAttribute("aria-selected", "true");+ await userEvent.click(await within(modal).findByText(/Recent items/));expect(within(modal).queryByText(QUESTION.name)).not.toBeInTheDocument();expect(await within(modal).findByText(MODEL.name)).toBeInTheDocument();@@ -383,6 +379,7 @@ describe("Notebook Editor > Join Step", () => {);const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await within(modal).findByText(/sample database/i));await userEvent.click(await within(modal).findByText("Reviews"));const lhsColumnPicker = await screen.findByTestId("lhs-column-picker");@@ -498,6 +495,7 @@ describe("Notebook Editor > Join Step", () => {);const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));expect(await within(modal).findByText("Products")).toBeInTheDocument();expect(within(modal).getByText("People")).toBeInTheDocument();expect(within(modal).getByText("Reviews")).toBeInTheDocument();@@ -514,6 +512,7 @@ describe("Notebook Editor > Join Step", () => {);const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Products"));expect(await screen.findByLabelText("Left column")).toHaveTextContent(@@ -573,6 +572,7 @@ describe("Notebook Editor > Join Step", () => {);const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Reviews"));expect(screen.queryByLabelText("Remove condition")).not.toBeInTheDocument();@@ -637,6 +637,7 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await within(entityPickerModal).findByText("Databases"),);+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(entityPickerModal).findByText("Reviews"),);@@ -681,6 +682,7 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await within(lhsTableModal).findByText("Databases"),);+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(lhsTableModal).findByText("Reviews"));await userEvent.click(screen.getByLabelText("Change join type"));@@ -757,6 +759,7 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await within(lhsTableModal).findByText("Databases"),);+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(lhsTableModal).findByText("Reviews"));const lhsColumnPopover = await screen.findByTestId("lhs-column-picker");@@ -777,6 +780,7 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await screen.findByText("Browse all"));const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Products"));await waitFor(() => {@@ -791,6 +795,7 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await screen.findByText("Browse all"));const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Reviews"));await userEvent.click(await screen.findByLabelText("Pick columns"));@@ -841,6 +846,7 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await screen.findByText("Browse all"));const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Reviews"));await userEvent.click(await screen.findByLabelText("Pick columns"));const joinColumnsPicker = await screen.findByTestId(@@ -865,6 +871,7 @@ describe("Notebook Editor > Join Step", () => {const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Reviews"));await userEvent.click(await screen.findByLabelText("Pick columns"));@@ -987,7 +994,7 @@ describe("Notebook Editor > Join Step", () => {const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));-+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Reviews"));expect(screen.queryByLabelText("Add condition")).not.toBeInTheDocument();@@ -1160,11 +1167,12 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await screen.findByText("Browse all"));- const picketModal = await screen.findByTestId("entity-picker-modal");+ const pickerModal = await screen.findByTestId("entity-picker-modal");await userEvent.click(- await within(picketModal).findByText("Databases"),+ await within(pickerModal).findByText("Databases"),);- await userEvent.click(await within(picketModal).findByText("Reviews"));+ await userEvent.click(await screen.findByText(/Sample Database/));+ await userEvent.click(await within(pickerModal).findByText("Reviews"));await selectColumnWithBucket(lhsBucketName);await selectColumnWithBucket(rhsBucketName);@@ -1242,11 +1250,12 @@ describe("Notebook Editor > Join Step", () => {await userEvent.click(await screen.findByText("Browse all"));- const picketModal = await screen.findByTestId("entity-picker-modal");+ const pickerModal = await screen.findByTestId("entity-picker-modal");await userEvent.click(- await within(picketModal).findByText("Databases"),+ await within(pickerModal).findByText("Databases"),);- await userEvent.click(await within(picketModal).findByText("Reviews"));+ await userEvent.click(await screen.findByText(/Sample Database/));+ await userEvent.click(await within(pickerModal).findByText("Reviews"));await selectColumnWithBucket(oldBucketName);await selectColumnWithBucket(oldBucketName);@@ -1279,6 +1288,7 @@ describe("Notebook Editor > Join Step", () => {await waitForLoaderToBeRemoved();const modal = await screen.findByTestId("entity-picker-modal");await userEvent.click(await within(modal).findByText("Databases"));+ await userEvent.click(await screen.findByText(/Sample Database/));await userEvent.click(await within(modal).findByText("Reviews"));const lhsPicker = await screen.findByTestId("lhs-column-picker");diff --git a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsxindex 7165766796e..6dac74a3262 100644--- a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx@@ -12,6 +12,7 @@ import {mockGetBoundingClientRect,renderWithProviders,screen,+ waitFor,waitForLoaderToBeRemoved,within,} from "__support__/ui";@@ -27,7 +28,6 @@ import {} from "metabase/browse/models/test-utils";import type { DataPickerValue } from "metabase/common/components/Pickers/DataPicker";import { checkNotNull } from "metabase/lib/types";-import type { IconName } from "metabase/ui";import {SAMPLE_METADATA,createQueryWithClauses,@@ -85,18 +85,14 @@ const TEST_RECENT_CARD = createMockRecentCollectionItem({});const dataPickerValueMap: Record<- DataPickerValue["model"],+ Exclude<DataPickerValue["model"], "database">,{- tabIcon: IconName;- tabDisplayName: string;recentItem: RecentItem;itemPickerData: string[];pickerColIdx?: number;}> = {table: {- tabIcon: "folder",- tabDisplayName: "Data",recentItem: TEST_RECENT_TABLE,itemPickerData: checkNotNull(MOCK_DATABASE.tables).map((table) => table.display_name,@@ -104,31 +100,25 @@ const dataPickerValueMap: Record<pickerColIdx: 3, // tables are always level 3 in the data picker},card: {- tabIcon: "folder",- tabDisplayName: "Data",recentItem: TEST_RECENT_CARD,itemPickerData: ["card"],},dataset: {- tabIcon: "folder",- tabDisplayName: "Data",recentItem: TEST_RECENT_MODEL,itemPickerData: ["dataset"],},metric: {- tabIcon: "folder",- tabDisplayName: "Data",recentItem: TEST_RECENT_METRIC,itemPickerData: ["metric"],},};-const TEST_ENTITY_TYPES: DataPickerValue["model"][] = [+const TEST_ENTITY_TYPES: Exclude<DataPickerValue["model"], "database">[] = ["table","metric","card","dataset",-] as const;+];function setup({question,@@ -269,126 +259,40 @@ describe("Notebook", () => {});describe("when filtering with modelsFilterList", () => {- describe("tab behavior", () => {- it("should not show tabs if only no type is chosen and recents are populated", async () => {+ describe.each<Exclude<DataPickerValue["model"], "database">>([+ "metric",+ "card",+ "dataset",+ ])("when filtering with %s", (entityType) => {+ it(`should show the entity picker when modelsFilterList=[${entityType}]`, async () => {setup({question: createSummarizedQuestion("question"),- modelsFilterList: [],+ modelsFilterList: [entityType],});- await goToEntityModal();-- expect(- await screen.findByTestId("single-picker-view"),- ).toBeInTheDocument();- });-- it("should not show tabs if only one type is chosen and recents are not populated", async () => {- setup({- question: createSummarizedQuestion("question"),- modelsFilterList: ["table"],- hasRecents: false,- });-- await goToEntityModal();-- expect(- await screen.findByTestId("single-picker-view"),- ).toBeInTheDocument();-- assertDataInPickerColumn({- columnIndex: Number(dataPickerValueMap["table"].pickerColIdx),- data: dataPickerValueMap["table"].itemPickerData,- });- });-- it("should show tabs if more than one type is chosen", async () => {- const models: DataPickerValue["model"][] = ["dataset", "card"];-- setup({- question: createSummarizedQuestion("question"),- modelsFilterList: models,- hasRecents: false,- });+ const {+ pickerColIdx = 1,+ recentItem,+ itemPickerData,+ } = dataPickerValueMap[entityType];await goToEntityModal();+ await userEvent.click(await screen.findByText(/Our analytics/));- for (const model of models) {- const { pickerColIdx = 1, itemPickerData } =- dataPickerValueMap[model];-- await userEvent.click(await screen.findByText("Our analytics"));-- assertDataInPickerColumn({- columnIndex: pickerColIdx,- data: itemPickerData,- });- }- });-- it("should show all tabs if no filter is selected", async () => {- setup({- question: createSummarizedQuestion("question"),+ await assertDataInPickerColumn({+ columnIndex: pickerColIdx,+ data: itemPickerData,});- await goToEntityModal();-- expect(await screen.findByTestId("tabs-view")).toBeInTheDocument();+ await userEvent.click(await screen.findByText(/Recent items/));+ await waitForLoaderToBeRemoved();- await goToDataPickerTab({- name: "Data",- iconName: "folder",- });- await goToDataPickerTab({- name: "Recents",- iconName: "clock",+ await assertDataInPickerColumn({+ columnIndex: 1,+ data: [recentItem.name],});});});-- describe.each<DataPickerValue["model"]>(["metric", "card", "dataset"])(- "when filtering with %s",- (entityType) => {- it(`should show the Collection item picker when modelsFilterList=[${entityType}]`, async () => {- setup({- question: createSummarizedQuestion("question"),- modelsFilterList: [entityType],- });-- const {- pickerColIdx = 1,- tabDisplayName,- tabIcon,- recentItem,- itemPickerData,- } = dataPickerValueMap[entityType];-- await goToEntityModal();-- await goToDataPickerTab({ name: tabDisplayName, iconName: tabIcon });-- if (entityType !== "table") {- // nested items so we want to go to the next nesting- await userEvent.click(await screen.findByText("Our analytics"));- }-- assertDataInPickerColumn({- columnIndex: pickerColIdx,- data: itemPickerData,- });-- await goToDataPickerTab({ name: "Recents", iconName: "clock" });-- assertDataInRecents({- data: [- "display_name" in recentItem- ? recentItem.display_name- : recentItem.name,- ],- });- });- },- );});});@@ -401,51 +305,22 @@ const goToEntityModal = async () => {expect(screen.getByTestId("entity-picker-modal")).toBeInTheDocument();await waitForLoaderToBeRemoved();- await waitForLoaderToBeRemoved();-};--const goToDataPickerTab = async ({- name,- iconName,-}: {- name: string;- iconName: IconName;-}) => {- const tabsView = within(await screen.findByTestId("tabs-view"));-- const tabButton = tabsView.getByRole("tab", {- name: `${iconName} icon ${name}`,- });-- expect(- within(tabButton).getByLabelText(`${iconName} icon`),- ).toBeInTheDocument();-- await userEvent.click(tabsView.getByText(name));-- expect(tabButton).toHaveAttribute("data-active", "true");};-const assertDataInPickerColumn = ({+const assertDataInPickerColumn = async ({columnIndex,data,}: {columnIndex: number;data: string[];}) => {- data.forEach((d) => {- expect(- within(screen.getByTestId(`item-picker-level-${columnIndex}`)).getByText(- d,- ),- ).toBeInTheDocument();- });-};--const assertDataInRecents = ({ data }: { data: string[] }) => {- data.forEach((d) => {- expect(- within(screen.getByRole("tabpanel", { name: /Recents/ })).getByText(d),- ).toBeInTheDocument();- });+ for (const datum of data) {+ await waitFor(() => {+ expect(+ within(+ screen.getByTestId(`item-picker-level-${columnIndex}`),+ ).getByText(datum),+ ).toBeInTheDocument();+ });+ }};diff --git a/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/NotebookDataPicker.tsx b/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/NotebookDataPicker.tsxindex 172f6767620..b7ee9d73a9d 100644--- a/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/NotebookDataPicker.tsx+++ b/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/NotebookDataPicker.tsx@@ -2,12 +2,11 @@ import { useMemo, useState } from "react";import { useLatest } from "react-use";import { t } from "ttag";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import {- type DataPickerItem,DataPickerModal,- createShouldShowItem,getDataPickerValue,+ shouldDisableItemNotInDb,} from "metabase/common/components/Pickers/DataPicker";import { MiniPicker } from "metabase/common/components/Pickers/MiniPicker";import type {@@ -24,7 +23,7 @@ import { getIsTenantUser } from "metabase/selectors/user";import { Icon, TextInput } from "metabase/ui";import * as Lib from "metabase-lib";import { getQuestionVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";-import type { RecentCollectionItem, TableId } from "metabase-types/api";+import type { TableId } from "metabase-types/api";import {type NotebookContextType,@@ -50,9 +49,7 @@ export interface NotebookDataPickerProps {table: Lib.TableMetadata | Lib.CardMetadata,metadataProvider: Lib.MetadataProvider,) => void;- shouldDisableItem?: (- item: DataPickerItem | CollectionPickerItem | RecentCollectionItem,- ) => boolean;+ shouldDisableItem?: (item: OmniPickerItem) => boolean;shouldDisableDatabase?: (item: QueryEditorDatabasePickerItem) => boolean;columnPicker: React.ReactNode;shouldShowLibrary?: boolean;@@ -157,9 +154,7 @@ type ModernDataPickerProps = {hasMetrics: boolean;isDisabled: boolean;onChange: (tableId: TableId) => void;- shouldDisableItem?: (- item: DataPickerItem | CollectionPickerItem | RecentCollectionItem,- ) => boolean;+ shouldDisableItem?: (item: OmniPickerItem) => boolean;shouldDisableDatabase?: (database: QueryEditorDatabasePickerItem) => boolean;shouldShowLibrary?: boolean;};@@ -191,28 +186,35 @@ function ModernDataPicker({const [focusPicker, setFocusPicker] = useState(false);const shouldHide = useMemo(() => {- const shouldShow = !canChangeDatabase- ? createShouldShowItem(modelList, databaseId)- : () => true;+ const shouldDisableBasedOnDb = !canChangeDatabase+ ? shouldDisableItemNotInDb(databaseId)+ : () => false;++ return (item: MiniPickerItem | unknown): item is MiniPickerPickableItem => {+ // FIXME: eww gross need to normalize db ids in minipicker+ // @ts-expect-error - will fix when we align types with minipicker: UXW-2735+ const dbId = item?.db_id ?? item?.database_id ?? item?.dbId ?? undefined;- return (- item: MiniPickerItem | QueryEditorDatabasePickerItem | unknown,- ): item is MiniPickerPickableItem => {return Boolean(- !shouldShow(item as DataPickerItem) ||- shouldDisableItem?.(item as DataPickerItem) ||+ // @ts-expect-error - Please fix 🥺+ shouldDisableBasedOnDb({ ...item, database_id: dbId }) ||+ shouldDisableItem?.(item as OmniPickerItem) ||(isObjectWithModel(item) &&item.model === "database" &&shouldDisableDatabase?.(item as QueryEditorDatabasePickerItem)),);};- }, [- databaseId,- canChangeDatabase,- modelList,- shouldDisableItem,- shouldDisableDatabase,- ]);+ }, [databaseId, canChangeDatabase, shouldDisableItem, shouldDisableDatabase]);++ // when you can't change databases, let's default to+ // selecting that database in the picker+ const defaultDbValue =+ canChangeDatabase || !databaseId+ ? undefined+ : {+ id: databaseId,+ model: "database" as const,+ };return (<>@@ -220,7 +222,8 @@ function ModernDataPicker({value={tableValue}opened={isOpened && !isBrowsing}onClose={() => setIsOpened(false)}- models={modelList}+ // minipicker doesn't support picking a database+ models={modelList.filter((model) => model !== "database")}searchQuery={dataSourceSearchQuery}onBrowseAll={() => setIsBrowsing(true)}trapFocus={focusPicker}@@ -239,12 +242,10 @@ function ModernDataPicker({{isOpened && isBrowsing && (<DataPickerModaltitle={title}- value={tableValue}- databaseId={canChangeDatabase ? undefined : databaseId}+ value={tableValue ?? defaultDbValue}+ onlyDatabaseId={canChangeDatabase ? undefined : databaseId}models={modelList}- onChange={(i) => {- onChange(i);- }}+ onChange={onChange}onClose={() => {setIsBrowsing(false);setIsOpened(false);@@ -257,6 +258,7 @@ function ModernDataPicker({shouldDisableDatabase?.(i)),);}}+ // searchQuery={dataSourceSearchQuery} ?/>)}{isOpened || !table ? (diff --git a/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx b/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsxindex d15241f9e1b..8b90bd561d0 100644--- a/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx+++ b/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx@@ -2,7 +2,7 @@ import { useCallback } from "react";import { t } from "ttag";import { useGetNativeDatasetQuery } from "metabase/api";-import { DelayedLoadingSpinner } from "metabase/common/components/EntityPicker/components/LoadingSpinner";+import { DelayedLoadingSpinner } from "metabase/common/components/Pickers/EntityPicker/components/LoadingSpinner";import { getEngineNativeType } from "metabase/lib/engine";import { CodeMirrorEditor as Editor } from "metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor";import { Box, Button, Flex, Icon, rem } from "metabase/ui";diff --git a/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsx b/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsxindex a64c23dedb0..2aeed67c02a 100644--- a/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsx+++ b/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsx@@ -5,7 +5,6 @@ import {DataPickerModal,getDataPickerValue,} from "metabase/common/components/Pickers/DataPicker";-import type { TablePickerValue } from "metabase/common/components/Pickers/TablePicker";import { Tables } from "metabase/entities/tables";import { useDispatch, useStore } from "metabase/lib/redux";import { checkNotNull } from "metabase/lib/types";@@ -37,9 +36,7 @@ export function DataStep({const tableInfo =query && table ? Lib.displayInfo(query, stageIndex, table) : undefined;const tableValue =- query && table- ? getDataPickerValue(query, stageIndex, table)- : { model: "table", id: null };+ query && table ? getDataPickerValue(query, stageIndex, table) : undefined;const store = useStore();const dispatch = useDispatch();@@ -92,13 +89,13 @@ export function DataStep({<DataPickerModaltitle={t`Select a table`}models={["table"]}- value={tableValue as TablePickerValue}+ value={tableValue}onChange={handleChange}onClose={() => setIsOpened(false)}options={{- showLibrary: false,- showRootCollection: false,- showPersonalCollections: false,+ hasLibrary: false,+ hasRootCollection: false,+ hasPersonalCollections: false,}}/>)}diff --git a/frontend/src/metabase/questions/components/CopyCardForm/CopyCardForm.tsx b/frontend/src/metabase/questions/components/CopyCardForm/CopyCardForm.tsxindex a1817f298b0..175c6658ed0 100644--- a/frontend/src/metabase/questions/components/CopyCardForm/CopyCardForm.tsx+++ b/frontend/src/metabase/questions/components/CopyCardForm/CopyCardForm.tsx@@ -6,7 +6,7 @@ import * as Yup from "yup";import { FormCollectionAndDashboardPicker } from "metabase/collections/containers/FormCollectionAndDashboardPicker";import { getEntityTypeFromCardType } from "metabase/collections/utils";import { FormFooter } from "metabase/common/components/FormFooter";-import type { CollectionPickerModel } from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import { FormDashboardTabSelect } from "metabase/dashboard/components/FormDashboardTabSelect";import {Form,@@ -97,7 +97,7 @@ export const CopyCardForm = ({onSaved?.(newCard, { dashboardTabId });};- const models: CollectionPickerModel[] =+ const models: OmniPickerItem["model"][] =model === "question" ? ["collection", "dashboard"] : ["collection"];return (@@ -133,15 +133,7 @@ export const CopyCardForm = ({entityType={model ? getEntityTypeFromCardType(model) : undefined}- collectionPickerModalProps={{- models,- recentFilter: (items) =>- items.filter((item) => {- // narrow type and make sure it's a dashboard or- // collection that the user can write to- return item.model !== "table" && item.can_write;- }),- }}+ collectionPickerModalProps={{ models }}/><FormDashboardTabSelectname="dashboard_tab_id"diff --git a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsxindex 2085291ccbb..34994ae8a6f 100644--- a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx+++ b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx@@ -12,8 +12,8 @@ import {getEntityTypeFromCardType,} from "metabase/collections/utils";import { ConfirmModal } from "metabase/common/components/ConfirmModal";-import { MoveModal } from "metabase/common/components/MoveModal";-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerCollectionItem } from "metabase/common/components/Pickers";+import { MoveModal } from "metabase/common/components/Pickers";import { Dashboards } from "metabase/entities/dashboards";import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/entities/questions";import { useDispatch } from "metabase/lib/redux";@@ -250,25 +250,35 @@ export const MoveCardModal = ({ card, onClose }: MoveCardModalProps) => {);}- const recentAndSearchFilter = (item: CollectionPickerItem) => {+ const shouldDisable = (item: OmniPickerCollectionItem) => {const dashboardId = card.dashboard_id;if (dashboardId) {+ // it's already in the dashboardreturn item.model === "dashboard" && item.id === dashboardId;- } else {- return item.model === "collection" && item.id === card.collection_id;}++ return false;};return (<MoveModaltitle={t`Where do you want to save this?`}- initialCollectionId={card.collection_id ?? "root"}onClose={onClose}onMove={handleChooseMoveLocation}canMoveToDashboard={card.type === "question"}- entityType={getEntityTypeFromCardType(card.type)}- recentAndSearchFilter={recentAndSearchFilter}+ movingItem={{+ ...card,+ collection: {+ // parent collection info+ id: card.collection_id ?? "root",+ name: "",+ namespace: card.collection?.namespace,+ },+ model: getEntityTypeFromCardType(card.type),+ dashboard_id: card.dashboard_id ?? undefined,+ }}+ isDisabledItem={shouldDisable}/>);};diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsxindex a12bc90b303..78bd6713b7c 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx@@ -17,7 +17,7 @@ import { useListCommentsQuery } from "metabase/api";import { getTargetChildCommentThreads } from "metabase/comments/utils";import { Ellipsified } from "metabase/common/components/Ellipsified";import { ExplicitSizeRefreshModeContext } from "metabase/common/components/ExplicitSize/ExplicitSize";-import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal";+import { QuestionPickerModal } from "metabase/common/components/Pickers";import type { QuestionPickerValueItem } from "metabase/common/components/Pickers/QuestionPicker/types";import { navigateToCardFromDocument } from "metabase/documents/actions";import {diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/EntitySearchSection.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/EntitySearchSection.tsxindex b50ae0780a3..a6f86755cb6 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/EntitySearchSection.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/EntitySearchSection.tsx@@ -1,6 +1,6 @@import { t } from "ttag";-import { QuestionPickerModal } from "metabase/common/components/Pickers/QuestionPicker/components/QuestionPickerModal";+import { QuestionPickerModal } from "metabase/common/components/Pickers";import type { MenuItem } from "metabase/documents/components/Editor/shared/MenuComponents";import {CreateNewQuestionFooter,@@ -14,7 +14,7 @@ import type {import { Box, Divider, Text } from "metabase/ui";import type { SearchResult } from "metabase-types/api";-import { LinkedEntityPickerModalWithConfirm } from "./LinkedEntityPickerModal";+import { LinkedEntityPickerModal } from "./LinkedEntityPickerModal";import type { DocumentLinkedEntityPickerItemValue } from "./LinkedEntityPickerModal/types";import { getBrowseAllItemIndex } from "./suggestionUtils";@@ -121,8 +121,8 @@ export function EntitySearchSection({)}{modal === "question-picker" && viewMode === "linkTo" && (- <LinkedEntityPickerModalWithConfirm- onConfirm={onModalSelect}+ <LinkedEntityPickerModal+ onChange={onModalSelect}onClose={onModalClose}/>)}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/LinkedEntityPickerModal.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/LinkedEntityPickerModal.tsxindex d5ea9fc17a4..4b1923a860a 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/LinkedEntityPickerModal.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/LinkedEntityPickerModal.tsx@@ -1,230 +1,45 @@-import { useMemo, useState } from "react";import { t } from "ttag";-import { useSearchQuery } from "metabase/api";import {EntityPickerModal,type EntityPickerOptions,- type EntityPickerTab,-} from "metabase/common/components/EntityPicker";-import {- CollectionPicker,- type CollectionPickerStatePath,-} from "metabase/common/components/Pickers/CollectionPicker";-import {- DashboardPicker,- type DashboardPickerStatePath,-} from "metabase/common/components/Pickers/DashboardPicker";-import {- QuestionPicker,- type QuestionPickerStatePath,-} from "metabase/common/components/Pickers/QuestionPicker";-import {- TablePicker,- type TablePickerStatePath,-} from "metabase/common/components/Pickers/TablePicker";+} from "metabase/common/components/Pickers";import {- COLLECTION_PICKER_OPTIONS,- DASHBOARD_PICKER_OPTIONS,+ DOCUMENT_LINK_MODELS,ENTITY_PICKER_OPTIONS,- QUESTION_PICKER_OPTIONS,RECENTS_CONTEXT,} from "./constants";-import type {- DocumentLinkedEntityPickerItem,- DocumentLinkedEntityPickerItemId,- DocumentLinkedEntityPickerItemModel,-} from "./types";-import { getCanSelectItem, hasAvailableModels } from "./utils";+import type { DocumentLinkedEntityPickerItemValue } from "./types";+import { getCanSelectItem } from "./utils";interface LinkedEntityPickerModalProps {- value: DocumentLinkedEntityPickerItem | null;- options?: Partial<EntityPickerOptions>;- onChange: (value: DocumentLinkedEntityPickerItem) => void;+ value?: DocumentLinkedEntityPickerItemValue | null;+ options?: EntityPickerOptions;+ onChange: (value: DocumentLinkedEntityPickerItemValue) => void;onConfirm?: () => void;onClose: () => void;}export function LinkedEntityPickerModal({value,- options,+ options = {},onChange,onClose,- onConfirm,}: LinkedEntityPickerModalProps) {- const [tablesPath, setTablesPath] = useState<TablePickerStatePath>();- const [questionsPath, setQuestionsPath] = useState<QuestionPickerStatePath>();- const [modelsPath, setModelsPath] = useState<QuestionPickerStatePath>();- const [metricsPath, setMetricsPath] = useState<QuestionPickerStatePath>();- const [dashboardsPath, setDashboardsPath] =- useState<DashboardPickerStatePath>();- const [collectionsPath, setCollectionsPath] =- useState<CollectionPickerStatePath>();-- const { data: searchResponse, isLoading: isSearchLoading } = useSearchQuery({- models: ["card"],- limit: 0,- calculate_available_models: true,- });-- const computedOptions = useMemo(- () => ({- ...ENTITY_PICKER_OPTIONS,- ...(options || null),- }),- [options],- );-- const tabs = useMemo(() => {- const computedTabs: EntityPickerTab<- DocumentLinkedEntityPickerItemId,- DocumentLinkedEntityPickerItemModel,- DocumentLinkedEntityPickerItem- >[] = [];-- computedTabs.push({- id: "tables-tab",- displayName: t`Tables`,- models: ["table"],- folderModels: ["database", "schema"],- icon: "table",- render: ({ onItemSelect }) => (- <TablePicker- value={undefined}- path={tablesPath}- onItemSelect={onItemSelect}- onPathChange={setTablesPath}- />- ),- });-- if (hasAvailableModels(searchResponse, ["card"])) {- computedTabs.push({- id: "questions-tab",- displayName: t`Questions`,- models: ["card"],- folderModels: ["collection", "dashboard"],- icon: "table2",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={undefined}- models={["card", "dashboard"]}- options={QUESTION_PICKER_OPTIONS}- path={questionsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setQuestionsPath}- />- ),- });- }-- if (hasAvailableModels(searchResponse, ["dataset"])) {- computedTabs.push({- id: "models-tab",- displayName: t`Models`,- models: ["dataset"],- folderModels: ["collection"],- icon: "model",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={undefined}- models={["dataset"]}- options={QUESTION_PICKER_OPTIONS}- path={modelsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setModelsPath}- />- ),- });- }-- if (hasAvailableModels(searchResponse, ["metric"])) {- computedTabs.push({- id: "metrics-tab",- displayName: t`Metrics`,- models: ["metric"],- folderModels: ["collection"],- icon: "metric",- render: ({ onItemSelect }) => (- <QuestionPicker- initialValue={undefined}- models={["metric"]}- options={DASHBOARD_PICKER_OPTIONS}- path={metricsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setMetricsPath}- />- ),- });- }-- if (hasAvailableModels(searchResponse, ["dashboard"])) {- computedTabs.push({- id: "dashboards-tab",- displayName: t`Dashboards`,- models: ["dashboard"],- folderModels: ["collection"],- icon: "dashboard",- render: ({ onItemSelect }) => (- <DashboardPicker- initialValue={undefined}- models={["dashboard"]}- options={QUESTION_PICKER_OPTIONS}- path={dashboardsPath}- onItemSelect={onItemSelect}- onPathChange={setDashboardsPath}- />- ),- });- }-- computedTabs.push({- id: "collections-tab",- displayName: t`Collections`,- models: ["collection"],- folderModels: ["collection"],- icon: "collection",- render: ({ onItemSelect }) => (- <CollectionPicker- initialValue={undefined}- models={["collection"]}- options={COLLECTION_PICKER_OPTIONS}- path={collectionsPath}- onInit={onItemSelect}- onItemSelect={onItemSelect}- onPathChange={setCollectionsPath}- />- ),- });-- return computedTabs;- }, [- searchResponse,- tablesPath,- questionsPath,- modelsPath,- metricsPath,- dashboardsPath,- collectionsPath,- ]);-return (<EntityPickerModaltitle={t`Choose an item to link`}- tabs={tabs}- initialValue={value || undefined}- selectedItem={value ?? null}- options={computedOptions}+ models={DOCUMENT_LINK_MODELS}+ value={value || undefined}+ options={{+ ...ENTITY_PICKER_OPTIONS,+ ...options,+ }}recentsContext={RECENTS_CONTEXT}- isLoadingTabs={isSearchLoading}- canSelectItem={getCanSelectItem(value)}- onItemSelect={onChange}+ isSelectableItem={getCanSelectItem}+ onChange={onChange}onClose={onClose}- onConfirm={onConfirm}/>);}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/LinkedEntityPickerModalWithConfirm.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/LinkedEntityPickerModalWithConfirm.tsxdeleted file mode 100644index 142fe28c4cc..00000000000--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/LinkedEntityPickerModalWithConfirm.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { useCallback, useState } from "react";--import { LinkedEntityPickerModal } from "./LinkedEntityPickerModal";-import type {- DocumentLinkedEntityPickerItem,- DocumentLinkedEntityPickerItemValue,-} from "./types";-import { getCanSelectItem } from "./utils";--interface LinkedEntityPickerModalWithConfirmProps {- onConfirm: (value: DocumentLinkedEntityPickerItemValue) => void;- onClose: () => void;-}--const EXTRA_OPTIONS = {- hasConfirmButtons: true,-};--export const LinkedEntityPickerModalWithConfirm = ({- onConfirm,- onClose,-}: LinkedEntityPickerModalWithConfirmProps) => {- const [value, setValue] = useState<DocumentLinkedEntityPickerItem | null>(- null,- );-- const handleChange = useCallback((value: DocumentLinkedEntityPickerItem) => {- setValue(value);- }, []);-- const handleConfirm = useCallback(() => {- if (value && getCanSelectItem(value)) {- onConfirm(value);- }- onClose();- }, [onClose, onConfirm, value]);-- return (- <LinkedEntityPickerModal- value={value}- options={EXTRA_OPTIONS}- onChange={handleChange}- onClose={onClose}- onConfirm={handleConfirm}- />- );-};diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/constants.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/constants.tsindex 90337268dc6..df863d26228 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/constants.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/constants.ts@@ -1,13 +1,10 @@-import {- type EntityPickerModalOptions,- defaultOptions,-} from "metabase/common/components/EntityPicker";-import type { CollectionPickerOptions } from "metabase/common/components/Pickers/CollectionPicker";-import type { DashboardPickerOptions } from "metabase/common/components/Pickers/DashboardPicker";-import type { QuestionPickerOptions } from "metabase/common/components/Pickers/QuestionPicker";+import type {+ EntityPickerModalProps,+ EntityPickerOptions,+} from "metabase/common/components/Pickers";import type { RecentContexts } from "metabase-types/api";-export const DOCUMENT_LINK_MODELS = [+export const DOCUMENT_LINK_MODELS: EntityPickerModalProps["models"] = ["card","dataset","metric",@@ -17,29 +14,17 @@ export const DOCUMENT_LINK_MODELS = ["table","database","transform",-] as const;-export type DocumentLinkItemModel = (typeof DOCUMENT_LINK_MODELS)[number];+];export const RECENTS_CONTEXT: RecentContexts[] = ["selections"];-export const ENTITY_PICKER_OPTIONS: EntityPickerModalOptions = {- ...defaultOptions,- hasConfirmButtons: false,+export const ENTITY_PICKER_OPTIONS: EntityPickerOptions = {+ hasSearch: true,hasRecents: true,-};--export const QUESTION_PICKER_OPTIONS: QuestionPickerOptions = {- showRootCollection: true,- showPersonalCollections: true,-};--export const DASHBOARD_PICKER_OPTIONS: DashboardPickerOptions = {- showRootCollection: true,- showPersonalCollections: true,-};+ hasLibrary: true,+ hasDatabases: true,+ hasRootCollection: true,+ hasPersonalCollections: true,-export const COLLECTION_PICKER_OPTIONS: CollectionPickerOptions = {- showRootCollection: false,- showPersonalCollections: true,- showLibrary: false,+ hasConfirmButtons: true,};diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/index.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/index.tsindex bd43e41916c..8df20f613ca 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/index.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/index.ts@@ -1,2 +1 @@export * from "./LinkedEntityPickerModal";-export * from "./LinkedEntityPickerModalWithConfirm";diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/types.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/types.tsindex 94c96d04757..ba37bd1b03e 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/types.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/types.ts@@ -1,28 +1,6 @@-import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";-import type { DashboardPickerItem } from "metabase/common/components/Pickers/DashboardPicker";-import type { QuestionPickerItem } from "metabase/common/components/Pickers/QuestionPicker";-import type {- DatabaseItem,- TableItem,- TablePickerItem,-} from "metabase/common/components/Pickers/TablePicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";-export type DocumentLinkedEntityPickerItem =- | TablePickerItem- | QuestionPickerItem- | CollectionPickerItem- | DashboardPickerItem;--export type DocumentLinkedEntityPickerItemId =- DocumentLinkedEntityPickerItem["id"];--export type DocumentLinkedEntityPickerItemModel =- DocumentLinkedEntityPickerItem["model"];--export type DocumentLinkedEntityPickerItemValue =- // exclude "schema" item- | TableItem- | DatabaseItem- | QuestionPickerItem- | CollectionPickerItem- | DashboardPickerItem;+// can't link to schema+export type DocumentLinkedEntityPickerItemValue = OmniPickerItem & {+ model: Omit<OmniPickerItem["model"], "schema">;+};diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/utils.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/utils.tsindex 0d6b782922d..cbde0556447 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/utils.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/utils.ts@@ -1,28 +1,16 @@-import type { TypeWithModel } from "metabase/common/components/EntityPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import {PERSONAL_COLLECTIONS,ROOT_COLLECTION,} from "metabase/entities/collections";-import type { SearchModel, SearchResponse } from "metabase-types/api";-import { DOCUMENT_LINK_MODELS, type DocumentLinkItemModel } from "./constants";+import { DOCUMENT_LINK_MODELS } from "./constants";import type { DocumentLinkedEntityPickerItemValue } from "./types";-export function hasAvailableModels(- response: SearchResponse | undefined,- models: SearchModel[],-) {- const availableModels = response?.available_models ?? [];- return models.some((model) => availableModels.includes(model));-}-export const getCanSelectItem = (- item: TypeWithModel<string | number, string> | null,+ item: OmniPickerItem | null,): item is DocumentLinkedEntityPickerItemValue => {- if (- item &&- DOCUMENT_LINK_MODELS.includes(item.model as DocumentLinkItemModel)- ) {+ if (item && DOCUMENT_LINK_MODELS.includes(item.model)) {if (item.model === "collection" &&(!item.id ||diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.tsindex e6b04399da9..f9f710c89ff 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.ts@@ -1,6 +1,7 @@import type { Editor, Range } from "@tiptap/core";import { useCallback, useEffect, useMemo, useState } from "react";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import { getTranslatedEntityName } from "metabase/common/utils/model-names";import { modelToUrl } from "metabase/lib/urls/modelToUrl";import type { DocumentLinkedEntityPickerItemValue } from "metabase/rich_text_editing/tiptap/extensions/shared/LinkedEntityPickerModal/types";@@ -282,7 +283,11 @@ export function useEntitySuggestions({);const handleModalSelect = useCallback(- (item: DocumentLinkedEntityPickerItemValue) => {+ (item: OmniPickerItem) => {+ if (item.model === "snippet" || item.model === "schema") {+ console.error(`Cannot select ${item.model}`);+ return;+ }onSelectEntity({id: item.id,model: item.model,diff --git a/frontend/src/metabase/timelines/common/components/MoveTimelineModal/MoveTimelineModal.tsx b/frontend/src/metabase/timelines/common/components/MoveTimelineModal/MoveTimelineModal.tsxindex 198311d0546..df06524c068 100644--- a/frontend/src/metabase/timelines/common/components/MoveTimelineModal/MoveTimelineModal.tsx+++ b/frontend/src/metabase/timelines/common/components/MoveTimelineModal/MoveTimelineModal.tsx@@ -1,10 +1,8 @@import { useCallback } from "react";import { t } from "ttag";-import {- CollectionPickerModal,- type CollectionPickerValueItem,-} from "metabase/common/components/Pickers/CollectionPicker";+import type { OmniPickerItem } from "metabase/common/components/Pickers";+import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";import { getTimelineName } from "metabase/lib/timelines";import type { CollectionId, Timeline } from "metabase-types/api";@@ -22,7 +20,7 @@ const MoveTimelineModal = ({onClose,}: MoveTimelineModalProps): JSX.Element => {const handleSubmit = useCallback(- async (item: CollectionPickerValueItem) => {+ async (item: OmniPickerItem) => {if (item.model === "collection") {await onSubmit(timeline, item.id);onSubmitSuccess?.();@@ -42,8 +40,9 @@ const MoveTimelineModal = ({onChange={handleSubmit}options={{confirmButtonText: t`Move`,- showPersonalCollections: true,- showRootCollection: true,+ hasPersonalCollections: true,+ hasRootCollection: true,+ hasLibrary: false,}}/>);diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.tsindex 4960f57a4be..5cb0c96312d 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useTreeTableInstance.ts@@ -7,7 +7,7 @@ import {useReactTable,} from "@tanstack/react-table";import { useVirtualizer } from "@tanstack/react-virtual";-import { useCallback, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { DEFAULT_OVERSCAN, DEFAULT_ROW_HEIGHT } from "../constants";import type {@@ -99,6 +99,22 @@ export function useTreeTableInstance<TData extends TreeNodeData>([expanded, onExpandedChange],);+ useEffect(() => {+ // override expanded state if defaultExpanded changes+ setInternalExpanded((prevExpanded) => {+ if (defaultExpanded === true) {+ return true;+ }+ if (defaultExpanded) {+ return {+ ...(prevExpanded === true ? {} : prevExpanded),+ ...defaultExpanded,+ };+ }+ return prevExpanded;+ });+ }, [defaultExpanded]);+const handleRowSelectionChange = useCallback((updater:diff --git a/frontend/src/metabase/visualizations/visualizations/DashCardPlaceholder.tsx b/frontend/src/metabase/visualizations/visualizations/DashCardPlaceholder.tsxindex 89e35ca5a01..c60b8c42570 100644--- a/frontend/src/metabase/visualizations/visualizations/DashCardPlaceholder.tsx+++ b/frontend/src/metabase/visualizations/visualizations/DashCardPlaceholder.tsx@@ -1,10 +1,11 @@import { useState } from "react";import { t } from "ttag";+import type { OmniPickerItem } from "metabase/common/components/Pickers";import {QuestionPickerModal,- type QuestionPickerValueItem,-} from "metabase/common/components/Pickers/QuestionPicker";+ isInDbTree,+} from "metabase/common/components/Pickers";import { replaceCard } from "metabase/dashboard/actions";import { useDispatch } from "metabase/lib/redux";import { Button, Flex } from "metabase/ui";@@ -28,9 +29,13 @@ function DashCardPlaceholderInner({const [isQuestionPickerOpen, setQuestionPickerOpen] = useState(false);const dispatch = useDispatch();- const handleSelectQuestion = (nextCard: QuestionPickerValueItem) => {- dispatch(replaceCard({ dashcardId: dashcard.id, nextCardId: nextCard.id }));- setQuestionPickerOpen(false);+ const handleSelectQuestion = (nextCard: OmniPickerItem) => {+ if (typeof nextCard.id === "number") {+ dispatch(+ replaceCard({ dashcardId: dashcard.id, nextCardId: nextCard.id }),+ );+ setQuestionPickerOpen(false);+ }};if (!isDashboard) {@@ -39,6 +44,20 @@ function DashCardPlaceholderInner({const pointerEvents = isEditingParameter ? "none" : "all";+ const shouldDisableItem = (item: OmniPickerItem) => {+ // don't allow adding items that are already saved in a different dashboard+ // proably only applicable to search and recents+ if (!isInDbTree(item) && item.dashboard_id) {+ if (item.dashboard_id !== dashboard.id) {+ return true;+ }+ }+ if (item.model === "dashboard" && item.id !== dashboard.id) {+ return true;+ }+ return false;+ };+return (<><Flex@@ -73,9 +92,13 @@ function DashCardPlaceholderInner({}: undefined}- models={["card", "dataset", "metric"]}+ options={{ hasConfirmButtons: false }}+ // TODO: account for restrictions on adding personal+ // questions to public dashboards+ models={["card", "dataset", "metric", "dashboard"]}onChange={handleSelectQuestion}onClose={() => setQuestionPickerOpen(false)}+ isDisabledItem={shouldDisableItem}/>)}</>diff --git a/frontend/test/__support__/server-mocks/collection.ts b/frontend/test/__support__/server-mocks/collection.tsindex c841b9b443d..1e8b2c2b5d9 100644--- a/frontend/test/__support__/server-mocks/collection.ts+++ b/frontend/test/__support__/server-mocks/collection.ts@@ -340,11 +340,12 @@ export function setupCollectionByIdEndpoint({setupCollectionWithErrorById({ error });return;}-- fetchMock.get(/api\/collection\/(\d+|root)$/, (call) => {+ // https://regexr.com/8jbva+ const collectionPathRegex =+ /api\/collection\/(\d+|root)(\?namespace=[\w\-]+)*$/;+ fetchMock.get(collectionPathRegex, (call) => {const urlString = call.url;- const parts = urlString.split("/");- const collectionIdParam = parts[parts.length - 1];+ const collectionIdParam = collectionPathRegex.exec(urlString)?.[1];const collectionId =collectionIdParam === "root" ? "root" : Number(collectionIdParam);diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsxindex fbca4786697..ce220e66e36 100644--- a/frontend/test/__support__/ui.tsx+++ b/frontend/test/__support__/ui.tsx@@ -392,7 +392,8 @@ export const mockOffsetHeightAndWidth = (value = 50) => {};/**- * jsdom doesn't have getBoundingClientRect, so we need to mock it+ * jsdom doesn't have getBoundingClientRect, so we need to mock it for any components+ * with virtualization to work in tests, like the entity picker*/export const mockGetBoundingClientRect = (options: Partial<DOMRect> = {}) => {jest