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
support `targetCollection` in `CreateDashboardModal` (#69359)
Mahatthana (Kelvin) Nomsawadid7607ccf8a48
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.schema.tsindex 556e2cddd1c..644d7cfe93a 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.schema.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.schema.ts@@ -6,6 +6,7 @@ import type { CreateDashboardModalProps } from "./CreateDashboardModal";const propsSchema: Yup.SchemaOf<CreateDashboardModalProps> = Yup.object({initialCollectionId: Yup.mixed().optional(),+ targetCollection: Yup.mixed().optional(),isOpen: Yup.mixed().optional(),onClose: Yup.mixed().optional(),onCreate: Yup.object().required(),diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsxindex 58b5f93b2d9..bf14ac066c4 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx@@ -23,6 +23,11 @@ export interface CreateDashboardModalProps {*/initialCollectionId?: SdkCollectionId;+ /**+ * The collection to save the dashboard to. This will hide the collection picker from the save modal.+ */+ targetCollection?: SdkCollectionId;+/*** Whether the modal is open or not.*/@@ -41,6 +46,7 @@ export interface CreateDashboardModalProps {const CreateDashboardModalInner = ({initialCollectionId = "personal",+ targetCollection,isOpen = true,onCreate,onClose,@@ -55,6 +61,12 @@ const CreateDashboardModalInner = ({getCollectionIdSlugFromReference(state, initialCollectionId),);+ const resolvedTargetCollection = useSelector((state) =>+ targetCollection+ ? getCollectionIdValueFromReference(state, targetCollection)+ : undefined,+ );+const { isLoading: isCollectionQueryLoading } = useCollectionQuery({id: collectionIdSlug,});@@ -69,6 +81,7 @@ const CreateDashboardModalInner = ({onCreate={onCreate}onClose={() => onClose?.()}collectionId={collectionId}+ targetCollection={resolvedTargetCollection}/>);};diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.unit.spec.tsxindex e7687e7f26a..f9b7868baad 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.unit.spec.tsx@@ -11,6 +11,7 @@ import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/uiimport { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";import { useLocale } from "metabase/common/hooks/use-locale";import { ROOT_COLLECTION as ROOT } from "metabase/entities/collections";+import type { Collection, Dashboard } from "metabase-types/api";import {createMockCollection,createMockDashboard,@@ -125,7 +126,7 @@ describe("CreateDashboardModal", () => {expect(onCreate).toHaveBeenLastCalledWith(mockResponseDashboard);});- it('should support "isOpen" prop', async () => {+ it("should support `isOpen` prop", async () => {const { rerender } = setup({props: {isOpen: false,@@ -140,20 +141,146 @@ describe("CreateDashboardModal", () => {expect(screen.getByText("New dashboard")).toBeInTheDocument();});});++ it("should set the starting collection to the user's personal collection when not passing `initialCollectionId`", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByText("New dashboard")).toBeInTheDocument();+ });++ expect(screen.getByTestId("collection-picker-button")).toHaveTextContent(+ PERSONAL_COLLECTION.name,+ );+ });++ it("should set the starting collection from `initialCollectionId` prop", async () => {+ const anotherCollection = createMockCollection({+ id: getNextId(),+ name: "Another collection",+ can_write: true,+ });++ setup({+ props: {+ initialCollectionId: anotherCollection.id,+ },+ collections: [...COLLECTIONS, anotherCollection],+ });++ await waitFor(() => {+ expect(screen.getByText("New dashboard")).toBeInTheDocument();+ });++ expect(screen.getByTestId("collection-picker-button")).toHaveTextContent(+ anotherCollection.name,+ );+ });++ it("should hide the collection picker when passing `targetCollection`", async () => {+ const anotherCollection = createMockCollection({+ id: getNextId(),+ name: "Another collection",+ can_write: true,+ });++ const expectedDashboard = {+ name: "My awesome dashboard title",+ } satisfies Partial<Dashboard>;+ setupDashboardCreateEndpoint(expectedDashboard);++ setup({+ props: {+ // Should prioritize `targetCollection` over `initialCollectionId`+ initialCollectionId: PERSONAL_COLLECTION.id,+ targetCollection: anotherCollection.id,+ },+ collections: [...COLLECTIONS, anotherCollection],+ });++ await waitFor(() => {+ expect(screen.getByText("New dashboard")).toBeInTheDocument();+ });++ expect(+ screen.queryByTestId("collection-picker-button"),+ ).not.toBeInTheDocument();++ await userEvent.type(+ screen.getByPlaceholderText("What is the name of your dashboard?"),+ expectedDashboard.name,+ );++ await userEvent.click(screen.getByText("Create"));++ // api called with typed form input+ const createDashboardCall = fetchMock.callHistory.lastCall(+ `path:/api/dashboard`,+ {+ method: "POST",+ },+ );+ expect(await createDashboardCall?.request?.json()).toMatchObject({+ name: expectedDashboard.name,+ collection_id: anotherCollection.id,+ });+ });++ it("should resolve special collection name like `root` when passing `targetCollection`", async () => {+ const expectedDashboard = {+ name: "My awesome dashboard title",+ } satisfies Partial<Dashboard>;+ setupDashboardCreateEndpoint(expectedDashboard);++ setup({+ props: {+ targetCollection: "root",+ },+ });++ await waitFor(() => {+ expect(screen.getByText("New dashboard")).toBeInTheDocument();+ });++ expect(+ screen.queryByTestId("collection-picker-button"),+ ).not.toBeInTheDocument();++ await userEvent.type(+ screen.getByPlaceholderText("What is the name of your dashboard?"),+ expectedDashboard.name,+ );++ await userEvent.click(screen.getByText("Create"));++ // api called with typed form input+ const createDashboardCall = fetchMock.callHistory.lastCall(+ `path:/api/dashboard`,+ {+ method: "POST",+ },+ );+ expect(await createDashboardCall?.request?.json()).toMatchObject({+ name: expectedDashboard.name,+ collection_id: null,+ });+ });});-function setup(- {- isLocaleLoading,- props,- }: {- isLocaleLoading?: boolean;- props?: Partial<CreateDashboardModalProps>;- } = { isLocaleLoading: false, props: {} },-) {+interface SetupOpts {+ isLocaleLoading?: boolean;+ props?: Partial<CreateDashboardModalProps>;+ collections?: Collection[];+}++function setup({+ isLocaleLoading = false,+ props = {},+ collections = COLLECTIONS,+}: SetupOpts = {}) {useLocaleMock.mockReturnValue({ isLocaleLoading });- setupCollectionByIdEndpoint({ collections: COLLECTIONS });+ setupCollectionByIdEndpoint({ collections });// Mock the "personal" collection endpoint since the component now passes string IDs directlyfetchMock.get("path:/api/collection/personal", PERSONAL_COLLECTION);diff --git a/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx b/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsxindex 8fbaa1a5510..5fc09a5c3d6 100644--- a/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx+++ b/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx@@ -2,10 +2,10 @@ import { useCallback, useMemo } from "react";import { t } from "ttag";import * as Yup from "yup";+import type { SdkCollectionId } from "embedding-sdk-bundle/types";import { useCreateDashboardMutation } from "metabase/api";import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker/FormCollectionPicker";import { FormFooter } from "metabase/common/components/FormFooter";-import type { FilterItemsInPersonalCollection } from "metabase/common/components/Pickers";import { Collections } from "metabase/entities/collections";import {Form,@@ -56,32 +56,33 @@ export interface CreateDashboardProperties {export interface CreateDashboardFormOwnProps {collectionId?: CollectionId | null; // can be used by `getInitialCollectionId`+ targetCollection?: SdkCollectionId | null;onCreate?: (dashboard: Dashboard) => void;onCancel?: () => void;- initialValues?: CreateDashboardProperties | null;- filterPersonalCollections?: FilterItemsInPersonalCollection;}export function CreateDashboardForm({+ collectionId,+ targetCollection,onCreate,onCancel,- initialValues,- filterPersonalCollections,- collectionId,}: CreateDashboardFormOwnProps) {const initialCollectionId = useSelector((state) =>Collections.selectors.getInitialCollectionId(state, { collectionId }),);+ // When passing `"root"` it will be resolved to `null`+ const hasTargetCollection = targetCollection !== undefined;+const [handleCreateDashboard] = useCreateDashboardMutation();- const computedInitialValues = useMemo(- () => ({+ const computedInitialValues = useMemo(() => {+ return {...DASHBOARD_SCHEMA.getDefault(),- collection_id: initialCollectionId,- ...initialValues,- }),- [initialCollectionId, initialValues],- );+ collection_id: hasTargetCollection+ ? targetCollection+ : initialCollectionId,+ };+ }, [hasTargetCollection, initialCollectionId, targetCollection]);const handleCreate = useCallback(async (values: CreateDashboardProperties) => {@@ -121,12 +122,13 @@ export function CreateDashboardForm({maxRows={5}my="md"/>- <FormCollectionPicker- name="collection_id"- title={t`Which collection should this go in?`}- filterPersonalCollections={filterPersonalCollections}- entityType="dashboard"- />+ {!hasTargetCollection && (+ <FormCollectionPicker+ name="collection_id"+ title={t`Which collection should this go in?`}+ entityType="dashboard"+ />+ )}<FormFooter><FormErrorMessage inline />{!!onCancel && (diff --git a/frontend/src/metabase/dashboard/containers/CreateDashboardModal.tsx b/frontend/src/metabase/dashboard/containers/CreateDashboardModal.tsxindex 2f973aa07cc..2223405cfb8 100644--- a/frontend/src/metabase/dashboard/containers/CreateDashboardModal.tsx+++ b/frontend/src/metabase/dashboard/containers/CreateDashboardModal.tsx@@ -2,27 +2,29 @@ import { useCallback } from "react";import { push } from "react-router-redux";import { t } from "ttag";+import type { SdkCollectionId } from "embedding-sdk-bundle/types";import { useEscapeToCloseModal } from "metabase/common/hooks/use-escape-to-close-modal";import { useDispatch } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";import { Modal, type ModalProps } from "metabase/ui";-import type { Dashboard } from "metabase-types/api";+import type { CollectionId, Dashboard } from "metabase-types/api";-import type { CreateDashboardFormOwnProps } from "./CreateDashboardForm";import { CreateDashboardForm } from "./CreateDashboardForm";-export interface CreateDashboardModalProps- extends Omit<CreateDashboardFormOwnProps, "onCancel"> {+export interface CreateDashboardModalProps {+ opened: boolean;+ collectionId?: CollectionId | null; // can be used by `getInitialCollectionId`+ targetCollection?: SdkCollectionId | null;+ onCreate?: (dashboard: Dashboard) => void;onClose: () => void;}export const CreateDashboardModal = ({+ opened,+ collectionId,+ targetCollection,onCreate,onClose,- initialValues,- filterPersonalCollections,- collectionId,- ...modalProps}: CreateDashboardModalProps & Omit<ModalProps, "onClose">) => {const dispatch = useDispatch();const handleCreate = useCallback(@@ -46,14 +48,13 @@ export const CreateDashboardModal = ({data-testid="new-dashboard-modal"size="lg"closeOnEscape={false}- {...modalProps}+ opened={opened}><CreateDashboardFormonCreate={handleCreate}onCancel={onClose}- initialValues={initialValues}- filterPersonalCollections={filterPersonalCollections}collectionId={collectionId}+ targetCollection={targetCollection}/></Modal>);