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
Add a Dashboards section to the Library (#83793)
Alexander Polyankin83223dea63d0
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 18adc0caa9e..6ad0af3238f 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -3928,7 +3928,12 @@premium-featuresutilwarehouse-schema-overlay}- :model-imports #{:model/Card :model/Collection :model/Table}}+ :model-imports #{:model/Card+ :model/Collection+ :model/Dashboard+ :model/Pulse+ :model/Table+ :model/Timeline}}enterprise/mcp{:team "Metabot"diff --git a/e2e/support/helpers/e2e-data-studio-helpers.ts b/e2e/support/helpers/e2e-data-studio-helpers.tsindex 06ee45ce369..ed6ffd9d9dc 100644--- a/e2e/support/helpers/e2e-data-studio-helpers.ts+++ b/e2e/support/helpers/e2e-data-studio-helpers.ts@@ -164,10 +164,17 @@ export const DataStudio = {DataStudio.Library.libraryPage().should("be.visible");DataStudio.Library.collectionItem("Data").should("be.visible");DataStudio.Library.collectionItem("Metrics").should("be.visible");- DataStudio.Library.collectionItem("SQL snippets").should("be.visible");+ DataStudio.Library.collectionItem("Dashboards")+ .scrollIntoView()+ .should("be.visible");+ DataStudio.Library.collectionItem("SQL snippets")+ .scrollIntoView()+ .should("be.visible");},noResults: () =>- libraryPage().findByText("No tables, metrics, or snippets yet"),+ libraryPage().findByText(+ "No tables, metrics, dashboards, or snippets yet",+ ),libraryPage,allTableItems: () => libraryPage().findAllByTestId("table-name"),tableItem: (name: string) =>diff --git a/enterprise/backend/src/metabase_enterprise/library/api.clj b/enterprise/backend/src/metabase_enterprise/library/api.cljindex eeada506fa2..bd96534a775 100644--- a/enterprise/backend/src/metabase_enterprise/library/api.clj+++ b/enterprise/backend/src/metabase_enterprise/library/api.clj@@ -28,8 +28,10 @@(defn- add-here-and-below [collection](let [descendent-ids (map :id (collection/descendants-flat collection))- below-card-types (library.db/card-types-in-collections descendent-ids)- below-tables? (library.db/published-table-in-collections? descendent-ids)]+ ;; Library questions are only ever dashboard questions, which aren't collection items+ below-card-types (disj (library.db/card-types-in-collections descendent-ids) :question)+ below-tables? (library.db/published-table-in-collections? descendent-ids)+ below-dashboards? (library.db/dashboard-in-collections? descendent-ids)];; This function is only used on the root Library which cannot have items directly in it;; So can assume :here is only collection, and all descendants are :below(assoc collection :here #{"collection"}@@ -37,6 +39,7 @@(contains? below-card-types :model)(-> (disj :model) (conj :dataset))below-tables? (conj :table)+ below-dashboards? (conj :dashboard)true sorttrue ((partial map name))))))diff --git a/enterprise/backend/src/metabase_enterprise/library/db.clj b/enterprise/backend/src/metabase_enterprise/library/db.cljindex 3504f4c6706..9697de137e4 100644--- a/enterprise/backend/src/metabase_enterprise/library/db.clj+++ b/enterprise/backend/src/metabase_enterprise/library/db.clj@@ -18,14 +18,17 @@[collection-ids :- [:sequential ::lib.schema.id/collection]](t2/exists? :model/Table :is_published true :collection_id [:in collection-ids] {:from [(warehouse-schema-overlay/table-query)]}))+(mu/defn dashboard-in-collections?+ "Whether a Dashboard exists in the Collections with `collection-ids`."+ [collection-ids :- [:sequential ::lib.schema.id/collection]]+ (t2/exists? :model/Dashboard :collection_id [:in collection-ids]))+(mu/defn library-collections- "The readable Library, Library-data, and Library-metrics Collections, ordered by name."+ "The readable Library Collections, ordered by name."[](t2/select :model/Collection{:where [:and- [:in :type [collection/library-collection-type- collection/library-data-collection-type- collection/library-metrics-collection-type]]+ [:in :type (vec collection/library-collection-types)](collection/visible-collection-filter-clause:id{:include-archived-items :excludediff --git a/enterprise/backend/src/metabase_enterprise/library/validation.clj b/enterprise/backend/src/metabase_enterprise/library/validation.cljindex 9aaa9322fd0..2fd0a98e460 100644--- a/enterprise/backend/src/metabase_enterprise/library/validation.clj+++ b/enterprise/backend/src/metabase_enterprise/library/validation.clj@@ -10,7 +10,8 @@"A map from the `:type` of the parent collection to a spec for what contents it permits."{collection/library-collection-type{:allowed-content-types #{collection/library-data-collection-type- collection/library-metrics-collection-type}+ collection/library-metrics-collection-type+ collection/library-dashboards-collection-type}:error-message "Cannot add anything to the semantic layer"}collection/library-data-collection-type@@ -19,7 +20,15 @@collection/library-metrics-collection-type{:allowed-content-types #{:metric collection/library-metrics-collection-type}- :error-message "Can only add metrics to the 'Metrics' collection"}})+ :error-message "Can only add metrics to the 'Metrics' collection"}++ collection/library-dashboards-collection-type+ {:allowed-content-types #{:model/Dashboard+ :dashboard-question+ :model/Pulse+ :model/Timeline+ collection/library-dashboards-collection-type}+ :error-message "Can only add dashboards to the 'Dashboards' collection"}})(defenterprise check-allowed-content"Check if the collection's content matches the allowed content.diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex ef2c83c5803..39e2d5175b2 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -57,6 +57,13 @@(spec/transforms-namespace-collection? entity))))serdes-paths))))+(defn- keep-library-dashboards+ "Adds the Library's Dashboards collection to `imported-data` when it has the Library, since repos may predate it."+ [imported-data]+ (cond-> imported-data+ (contains? (get-in imported-data [:by-entity-id "Collection"]) collection/library-entity-id)+ (update-in [:by-entity-id "Collection"] conj collection/library-dashboards-entity-id)))+(defn- remove-unsynced!"Deletes any remote sync content that was NOT part of the import.@@ -402,7 +409,7 @@(report 0.75 {:force? true})(t2/with-transaction [_conn](let [synced-collection-ids (spec/all-syncable-collection-ids)- _ (remove-unsynced! synced-collection-ids imported-data)+ _ (remove-unsynced! synced-collection-ids (keep-library-dashboards imported-data))settings-table-ids (remove-unsynced-user-settings! synced-collection-ids base-ingestable seen-paths)];; Replace the RemoteSyncObject table, folding each entity's repo file_path (so later renames/deletes;; resolve the real file) and serialized-content hash (so a post-pull no-op edit stays synced) into the@@ -411,6 +418,7 @@(insert-with-metadata! (spec/sync-all-entities! sync-timestamp imported-data)(source.ingestable/cached-file-paths base-ingestable))(track-user-settings! settings-table-ids sync-timestamp)+ (collection/ensure-library-dashboards-collection!)(when finalize! (finalize!))))(report 0.9 {:force? true})(when (and (not has-transforms?)diff --git a/enterprise/backend/test/metabase_enterprise/library/api_test.clj b/enterprise/backend/test/metabase_enterprise/library/api_test.cljindex d469837fed2..03ce74139e5 100644--- a/enterprise/backend/test/metabase_enterprise/library/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/library/api_test.clj@@ -49,7 +49,14 @@(let [response (mt/user-http-request :crowberto :get 200 "ee/library")](is (= "Library" (:name response)))(is (= ["metric" "table"] (:below response)))- (is (= ["collection"] (:here response)))))))))))+ (is (= ["collection"] (:here response))))))+ (testing "Dashboards and their questions show up as dashboards"+ (let [dashboards-id (t2/select-one-pk :model/Collection :type collection/library-dashboards-collection-type)]+ (mt/with-temp [:model/Dashboard dashboard {:collection_id dashboards-id}+ :model/Card _ {:collection_id dashboards-id+ :dashboard_id (:id dashboard)+ :type :question}]+ (is (= ["dashboard"] (:below (mt/user-http-request :crowberto :get 200 "ee/library"))))))))))))(deftest disallow-cross-type-collection-move-via-api-test(mt/with-premium-features #{:library}diff --git a/enterprise/backend/test/metabase_enterprise/library/validation_test.clj b/enterprise/backend/test/metabase_enterprise/library/validation_test.cljindex 9ada652f908..ede7f39ff66 100644--- a/enterprise/backend/test/metabase_enterprise/library/validation_test.clj+++ b/enterprise/backend/test/metabase_enterprise/library/validation_test.clj@@ -2,6 +2,10 @@(:require[clojure.test :refer :all][metabase.collections.models.collection :as collection]+ [metabase.dashboards.write :as dashboards.write]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.models.interface :as mi][metabase.test :as mt][toucan2.core :as t2]))@@ -69,6 +73,96 @@(is (= 1 (t2/insert! :model/Collection (assoc new-coll :type collection/library-metrics-collection-type)))"new collection with :type set is allowed"))))))+(deftest check-allowed-content-dashboards+ (mt/with-premium-features #{:library}+ (mt/with-temp [:model/Collection allow-dashboards {:name "Test Base Library" :type collection/library-dashboards-collection-type}+ :model/Dashboard dashboard {:collection_id (:id allow-dashboards)}+ :model/Card dashboard-card {:collection_id (:id allow-dashboards)+ :dashboard_id (:id dashboard)+ :type :question}]+ (testing "Can add dashboards and their questions"+ (is (some? dashboard))+ (is (some? dashboard-card)))+ (testing "Cannot add standalone questions, models, or metrics"+ (doseq [card-type [:question :model :metric]]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add dashboards to the 'Dashboards' collection"+ (t2/insert! :model/Card (merge (mt/with-temp-defaults :model/Card) {:type card-type :collection_id (:id allow-dashboards)}))))))+ (testing "Cannot turn a dashboard question into a standalone question"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add dashboards to the 'Dashboards' collection"+ (t2/update! :model/Card (:id dashboard-card) {:dashboard_id nil}))))+ (testing "Can add collections iff they have the same :type"+ (let [new-coll (merge (mt/with-temp-defaults :model/Collection)+ {:location (str "/" (:id allow-dashboards) "/")})]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add dashboards to the 'Dashboards' collection"+ (t2/insert! :model/Collection new-coll))+ "basic new collection is rejected")+ (is (= 1 (t2/insert! :model/Collection (assoc new-coll :type collection/library-dashboards-collection-type)))+ "new collection with :type set is allowed"))))))++(deftest library-dashboards-allow-dashboard-companions-test+ (mt/with-premium-features #{:library}+ (mt/with-temp [:model/Collection allow-dashboards {:name "Test Base Library" :type collection/library-dashboards-collection-type}+ :model/Dashboard dashboard {:collection_id (:id allow-dashboards)}]+ (testing "Dashboards can have subscriptions"+ (mt/with-temp [:model/Pulse pulse {:dashboard_id (:id dashboard) :collection_id (:id allow-dashboards)}]+ (is (some? pulse))))+ (testing "Dashboard questions can have timelines"+ (mt/with-temp [:model/Timeline timeline {:collection_id (:id allow-dashboards)}]+ (is (some? timeline)))))))++(deftest library-dashboards-dashboard-questions-are-questions-test+ (mt/with-premium-features #{:library}+ (mt/with-temp [:model/Collection allow-dashboards {:name "Test Base Library" :type collection/library-dashboards-collection-type}+ :model/Collection allow-metrics {:name "Test Metrics" :type collection/library-metrics-collection-type}+ :model/Dashboard dashboard {:collection_id (:id allow-dashboards)}+ :model/Card metric {:collection_id (:id allow-metrics) :type :metric}]+ (testing "A metric can't be moved into the Dashboards collection by giving it a dashboard"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add dashboards to the 'Dashboards' collection"+ (t2/update! :model/Card (:id metric) {:dashboard_id (:id dashboard)}))))+ (testing "Serdes loads dashboard questions before their dashboard"+ (binding [mi/*deserializing?* true]+ (is (some? (t2/insert! :model/Card (merge (mt/with-temp-defaults :model/Card)+ {:type :question :collection_id (:id allow-dashboards)}))))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Can only add dashboards to the 'Dashboards' collection"+ (t2/insert! :model/Card (merge (mt/with-temp-defaults :model/Card)+ {:type :metric :collection_id (:id allow-dashboards)})))))))))++(deftest deep-copy-dashboard-into-library-dashboards-test+ (mt/with-premium-features #{:library}+ (let [mp (mt/metadata-provider)+ query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]+ (mt/with-temp [:model/Collection allow-dashboards {:name "Test Base Library" :type collection/library-dashboards-collection-type}+ :model/Collection regular {:name "Regular Collection"}+ :model/Card question {:collection_id (:id regular)+ :collection_position 1+ :type :question+ :dataset_query query}+ :model/Card metric {:collection_id (:id regular) :type :metric :dataset_query query}+ :model/Dashboard dashboard {:collection_id (:id regular)}+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :card_id (:id question)}+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :card_id (:id metric)}]+ (doseq [[path copy!] {"API" #(:id (mt/user-http-request :crowberto :post 200 (str "dashboard/" (:id dashboard) "/copy") %))+ "write" #(mt/with-current-user (mt/user->id :crowberto)+ (:id (dashboards.write/copy-dashboard! (:id dashboard) %)))}]+ (testing (str path ": copied pinned questions become unpinned dashboard questions and metrics stay referenced")+ (let [copy-id (copy! {:collection_id (:id allow-dashboards) :is_deep_copy true})+ cards (t2/select :model/Card :id [:in (t2/select-fn-set :card_id :model/DashboardCard :dashboard_id copy-id)])]+ (is (=? [{:type :metric :id (:id metric) :dashboard_id nil}+ {:type :question :dashboard_id copy-id :collection_id (:id allow-dashboards) :collection_position nil}]+ (sort-by (comp name :type) cards))))))))))++(deftest move-dashboard-into-library-dashboards-test+ (mt/with-premium-features #{:library}+ (mt/with-temp [:model/Collection allow-dashboards {:name "Test Base Library" :type collection/library-dashboards-collection-type}+ :model/Collection regular {:name "Regular Collection" :type nil}+ :model/Dashboard dashboard {:collection_id (:id regular)}+ :model/Card dashboard-card {:collection_id (:id regular)+ :dashboard_id (:id dashboard)+ :type :question}]+ (testing "Moving a dashboard moves its questions along"+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" (:id dashboard)) {:collection_id (:id allow-dashboards)})+ (is (= (:id allow-dashboards) (t2/select-one-fn :collection_id :model/Card :id (:id dashboard-card))))))))+(deftest tables-cannot-be-moved-to-non-library-data-collections(mt/with-premium-features #{:library}(mt/with-temp [:model/Collection library-data {:name "Library Data" :type collection/library-data-collection-type}@@ -90,9 +184,10 @@(mt/with-premium-features #{:library}(mt/with-temp [:model/Collection library {:name "Test Library" :type collection/library-collection-type}:model/Collection models {:name "Test Semantic Model Layer" :type collection/library-data-collection-type}- :model/Collection metrics {:name "Test Semantic Metrics Layer" :type collection/library-metrics-collection-type}]+ :model/Collection metrics {:name "Test Semantic Metrics Layer" :type collection/library-metrics-collection-type}+ :model/Collection dashboards {:name "Test Semantic Dashboards Layer" :type collection/library-dashboards-collection-type}](mt/with-dynamic-fn-redefs [collection/library-root-collection? (constantly true)]- (doseq [col [library models metrics]]+ (doseq [col [library models metrics dashboards]](testing (str "Checking type " (:type col))(is (thrown-with-msg? clojure.lang.ExceptionInfo#"Cannot update properties on a semantic layer collection"diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.cljindex 012a88453bb..3782885db4e 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj@@ -2455,3 +2455,13 @@ serdes/meta:(is (= "main" (remote-sync.settings/remote-sync-branch)))(impl/run-task-body! (new-task-id) "feature" (fn [_] {:status :success}))(is (= "feature" (remote-sync.settings/remote-sync-branch))))))++(deftest keep-library-dashboards-test+ (testing "An import with the Library keeps its Dashboards collection, even from a repo that predates it"+ (is (= #{collection/library-entity-id collection/library-dashboards-entity-id "other-collection-xxxxx"}+ (get-in (#'impl/keep-library-dashboards+ {:by-entity-id {"Collection" #{collection/library-entity-id "other-collection-xxxxx"}}})+ [:by-entity-id "Collection"]))))+ (testing "An import without the Library leaves it to be removed with the Library"+ (is (= {:by-entity-id {"Collection" #{"other-collection-xxxxx"}}}+ (#'impl/keep-library-dashboards {:by-entity-id {"Collection" #{"other-collection-xxxxx"}}})))))diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.cljindex 0701c986f3f..3e3764282e2 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj@@ -52,7 +52,7 @@(reifyserdes.ingest/Ingestable(ingest-list [_]- (keys mapped))+ (map (comp no-labels serdes/path) extractions))(ingest-one [_ path](get mapped (no-labels path)))(ingest-errors [_]@@ -2185,7 +2185,7 @@(ts/with-db source-db(let [coll (ts/create! :model/Collection :name "coll")dash (ts/create! :model/Dashboard :name "dash" :collection_id (:id coll))- card (ts/create! :model/Card :name "dq card" :dashboard_id (:id dash))+ card (ts/create! :model/Card :name "dq card" :type :question :dashboard_id (:id dash))_ (ts/create! :model/DashboardCard :dashboard_id (:id dash) :card_id (:id card))_ (t2/update! :model/Dashboard (:id dash){:parameters [(card-sourced-param (:id card))]})@@ -2206,6 +2206,40 @@(is (= (:id new-dash)(:dashboard_id new-card)))))))))))+(deftest library-dashboards-questions-test+ (mt/with-premium-features #{:library}+ (ts/with-dbs [source-db dest-db]+ (ts/with-db source-db+ (let [coll (ts/create! :model/Collection :name "dashboards" :type collection/library-dashboards-collection-type)+ regular (ts/create! :model/Collection :name "regular")+ dash (ts/create! :model/Dashboard :name "dash" :collection_id (:id coll))+ dq (ts/create! :model/Card :name "dq card" :type :question :dashboard_id (:id dash))+ _ (ts/create! :model/DashboardCard :dashboard_id (:id dash) :card_id (:id dq))+ standalone (ts/create! :model/Card :name "standalone" :type :question :collection_id (:id regular))+ ser (vec (serdes.extract/extract {:no-settings true+ :no-data-model true+ :no-transforms true}))+ card-ser (fn [card] (first (filter #(and (= "Card" (:model (last (serdes/path %))))+ (= (:entity_id card) (:entity_id %)))+ ser)))+ messages (fn [e] (map ex-message (take-while some? (iterate ex-cause e))))]+ (ts/with-db dest-db+ (testing "A dashboard question loads into Library Dashboards before its dashboard"+ (is (serdes.load/load-metabase! (ingestion-in-memory (cons (card-ser dq) (remove #{(card-ser standalone)} ser)))))+ (is (= (t2/select-one-pk :model/Dashboard :entity_id (:entity_id dash))+ (t2/select-one-fn :dashboard_id :model/Card :entity_id (:entity_id dq)))))+ (testing "A standalone question can't load into Library Dashboards"+ (let [e (is (thrown? clojure.lang.ExceptionInfo+ (serdes.load/load-metabase!+ (ingestion-in-memory [(assoc (card-ser standalone) :collection_id (:entity_id coll))]))))]+ (is (some #(re-find #"Can only add dashboards to the 'Dashboards' collection" %) (messages e)))+ (is (not (t2/exists? :model/Card :entity_id (:entity_id standalone))))))+ (testing "A dashboard question can't become a standalone question in Library Dashboards"+ (let [e (is (thrown? clojure.lang.ExceptionInfo+ (serdes.load/load-metabase!+ (ingestion-in-memory [(assoc (card-ser dq) :dashboard_id nil)]))))]+ (is (some #(re-find #"Can only add dashboards to the 'Dashboards' collection" %) (messages e)))))))))))+(deftest continue-on-error-test(let [change-ser (fn [ser changes] ;; kind of like left-join, but right side is indexed(vec (for [entity ser]diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsxindex b569dbccfe4..57e32744b97 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/LibraryPage.tsx@@ -25,6 +25,7 @@ import type { CollectionId } from "metabase-types/api";import { LibraryEmptyState } from "../components/LibraryEmptyState";+import { CreateLibraryDashboardModal } from "./components/CreateLibraryDashboardModal";import { CreateMenu } from "./components/CreateMenu";import { LibraryBulkActions } from "./components/LibraryBulkActions";import { PublishTableModal } from "./components/PublishTableModal";@@ -50,6 +51,10 @@ function LibraryPageContent() {showPublishTableModal,{ open: openPublishTableModal, close: closePublishTableModal },] = useDisclosure(false);+ const [+ showCreateDashboardModal,+ { open: openCreateDashboardModal, close: closeCreateDashboardModal },+ ] = useDisclosure(false);const { data: collections = [], isLoading: isLoadingCollections } =useListCollectionsTreeQuery({"exclude-other-user-collections": true,@@ -62,17 +67,21 @@ function LibraryPageContent() {isChildrenLoading,isLoading,emptyMessage,- refreshTableCollections,- refreshMetricCollections,+ refreshSection,} = useLibraryTreeTableInstance({collections,isLoadingCollections,searchQuery,onPublishTableClick: openPublishTableModal,+ onNewDashboardClick: openCreateDashboardModal,});- const { libraryCollection, tableCollection, metricCollection } =- useLibraryCollections(collections);+ const {+ libraryCollection,+ tableCollection,+ metricCollection,+ dashboardCollection,+ } = useLibraryCollections(collections);const writableMetricCollection = useMemo(() =>libraryCollection &&@@ -99,19 +108,16 @@ function LibraryPageContent() {const moveDefaultCollectionId = match(selectionSection).with("data", () => tableCollection?.id).with("metrics", () => metricCollection?.id)+ .with("dashboards", () => dashboardCollection?.id).otherwise(() => undefined);const handleActionComplete = useCallback((section: LibrarySection, affectedCollectionIds: CollectionId[]) => {- if (section === "data") {- refreshTableCollections(affectedCollectionIds);- } else if (section === "metrics") {- refreshMetricCollections(affectedCollectionIds);- }+ refreshSection(section, affectedCollectionIds);// Snippet sections refetch via RTK tag invalidation.clearSelection();},- [refreshTableCollections, refreshMetricCollections, clearSelection],+ [refreshSection, clearSelection],);return (@@ -149,6 +155,11 @@ function LibraryPageContent() {canWriteToMetricCollection={!!writableMetricCollection}dataCollectionId={tableCollection?.id}canWriteToDataCollection={!!tableCollection?.can_write}+ dashboardCollectionId={dashboardCollection?.id}+ canWriteToDashboardCollection={+ !!dashboardCollection?.can_write+ }+ onNewDashboardClick={openCreateDashboardModal}/></Flex><Card withBorder p={0}>@@ -188,6 +199,13 @@ function LibraryPageContent() {onClose={closePublishTableModal}onPublished={closePublishTableModal}/>+ {dashboardCollection && (+ <CreateLibraryDashboardModal+ opened={showCreateDashboardModal}+ collectionId={dashboardCollection.id}+ onClose={closeCreateDashboardModal}+ />+ )}{!isRemoteSyncReadOnly && (<LibraryBulkActionsselectedItems={selectedItems}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/ActionCell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/ActionCell.tsxindex dbc0feaef02..ab09292b91e 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/ActionCell.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/ActionCell.tsx@@ -9,17 +9,23 @@ import { PLUGIN_LIBRARY } from "metabase/plugins";import { TableMoreMenu } from "metabase-enterprise/data-studio/library/tables/components/TableHeader/TableMoreMenu";import type { CollectionId } from "metabase-types/api";+import {+ type LibrarySection,+ getItemSection,+} from "../hooks/library-bulk-selection.utils";+import { LibraryCollectionRowMenu } from "./LibraryCollectionRowMenu";import { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";type ActionCellProps = {treeItem: TreeItem;- refreshTableCollections: (collectionIds: CollectionId[]) => void;- refreshMetricCollections: (collectionIds: CollectionId[]) => void;+ refreshSection: (+ section: LibrarySection,+ collectionIds: CollectionId[],+ ) => void;};-export function ActionCell(props: ActionCellProps) {- const { treeItem, refreshTableCollections, refreshMetricCollections } = props;+export function ActionCell({ treeItem, refreshSection }: ActionCellProps) {const { data, children } = treeItem;if (isEmptyStateData(data)) {@@ -27,7 +33,12 @@ export function ActionCell(props: ActionCellProps) {}if (isTableData(data)) {- return <TableMoreMenu table={data} onMoved={refreshTableCollections} />;+ return (+ <TableMoreMenu+ table={data}+ onMoved={(collectionIds) => refreshSection("data", collectionIds)}+ />+ );}if (!isCollectionData(data) || data.model !== "collection") {@@ -48,13 +59,16 @@ export function ActionCell(props: ActionCellProps) {PLUGIN_LIBRARY.isLibrarySubCollectionType(data.type) &&!data.is_library_root;- if (isLibraryCollection) {+ const section = getItemSection(treeItem);++ if (isLibraryCollection && section != null) {return (<LibraryCollectionRowMenuchildCount={children?.length ?? 0}collection={data}- refreshMetricCollections={refreshMetricCollections}- refreshTableCollections={refreshTableCollections}+ refreshCollections={(collectionIds) =>+ refreshSection(section, collectionIds)+ }/>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateLibraryDashboardModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateLibraryDashboardModal.tsxnew file mode 100644index 00000000000..1d42eafaafc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateLibraryDashboardModal.tsx@@ -0,0 +1,124 @@+import { useMemo } from "react";+import { t } from "ttag";+import * as Yup from "yup";++import { useCreateDashboardMutation } from "metabase/api";+import FormCollectionPicker from "metabase/common/collections/containers/FormCollectionPicker/FormCollectionPicker";+import { FormFooter } from "metabase/common/components/FormFooter";+import type { EntityPickerOptions } from "metabase/common/components/Pickers";+import {+ DASHBOARD_DESCRIPTION_MAX_LENGTH,+ DASHBOARD_NAME_MAX_LENGTH,+} from "metabase/common/utils/dashboard";+import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSubmitButton,+ FormTextInput,+ FormTextarea,+} from "metabase/forms";+import { useNavigate } from "metabase/router";+import { Button, Modal, Stack } from "metabase/ui";+import * as Urls from "metabase/urls";+import * as Errors from "metabase/utils/errors";+import type { CollectionId } from "metabase-types/api";++const DASHBOARD_SCHEMA = Yup.object({+ name: Yup.string()+ .required(Errors.required)+ .max(DASHBOARD_NAME_MAX_LENGTH, Errors.maxLength)+ .default(""),+ description: Yup.string()+ .nullable()+ .max(DASHBOARD_DESCRIPTION_MAX_LENGTH, Errors.maxLength)+ .default(null),+ collection_id: Yup.number().required(Errors.required),+});++type CreateLibraryDashboardValues = {+ name: string;+ description: string | null;+ collection_id: CollectionId;+};++const LIBRARY_DASHBOARD_PICKER_OPTIONS: EntityPickerOptions = {+ hasLibrary: true,+ hasRootCollection: false,+ hasPersonalCollections: false,+ hasRecents: false,+ hasSearch: false,+ hasConfirmButtons: true,+ canCreateCollections: false,+};++type CreateLibraryDashboardModalProps = {+ opened: boolean;+ collectionId: CollectionId;+ onClose: () => void;+};++export function CreateLibraryDashboardModal({+ opened,+ collectionId,+ onClose,+}: CreateLibraryDashboardModalProps) {+ const navigate = useNavigate();+ const [createDashboard] = useCreateDashboardMutation();++ const initialValues = useMemo(+ () => ({ ...DASHBOARD_SCHEMA.getDefault(), collection_id: collectionId }),+ [collectionId],+ );++ const handleSubmit = async (values: CreateLibraryDashboardValues) => {+ const dashboard = await createDashboard(values).unwrap();+ navigate(Urls.dashboard(dashboard, { editMode: true }));+ };++ return (+ <Modal opened={opened} title={t`New dashboard`} size="lg" onClose={onClose}>+ <FormProvider+ initialValues={initialValues}+ enableReinitialize+ validationSchema={DASHBOARD_SCHEMA}+ onSubmit={handleSubmit}+ >+ <Form as={Stack} gap={0}>+ <FormTextInput+ labelProps={{ mb: "xxs" }}+ name="name"+ label={t`Name`}+ placeholder={t`What is the name of your dashboard?`}+ data-autofocus+ mt="lg"+ />+ <FormTextarea+ labelProps={{ mb: "xxs" }}+ name="description"+ label={t`Description`}+ placeholder={t`It's optional but oh, so helpful`}+ nullable+ autosize={false}+ minRows={5}+ maxRows={5}+ my="lg"+ />+ <FormCollectionPicker+ name="collection_id"+ title={t`Collection`}+ entityType="dashboard"+ collectionPickerModalProps={{+ options: LIBRARY_DASHBOARD_PICKER_OPTIONS,+ }}+ />+ <FormFooter mt="lg">+ <FormErrorMessage inline />+ <Button type="button" onClick={onClose}>{t`Cancel`}</Button>+ <FormSubmitButton label={t`Create`} variant="filled" />+ </FormFooter>+ </Form>+ </FormProvider>+ </Modal>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateLibraryDashboardModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateLibraryDashboardModal.unit.spec.tsxnew file mode 100644index 00000000000..01f715e1d7b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateLibraryDashboardModal.unit.spec.tsx@@ -0,0 +1,84 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ createMockCollection,+ createMockDashboard,+} from "metabase-types/api/mocks";++import { CreateLibraryDashboardModal } from "./CreateLibraryDashboardModal";++const DASHBOARDS_COLLECTION = createMockCollection({+ id: 3,+ name: "Dashboards",+ type: "library-dashboards",+ is_library_root: true,+ can_write: true,+});++function setup() {+ const onClose = jest.fn();+ fetchMock.get(+ `path:/api/collection/${DASHBOARDS_COLLECTION.id}`,+ DASHBOARDS_COLLECTION,+ );+ fetchMock.get("path:/api/collection/root", createMockCollection());+ fetchMock.post("path:/api/dashboard", (call) =>+ createMockDashboard({+ ...JSON.parse(String(call.options.body)),+ id: 42,+ }),+ );++ const { router } = renderWithProviders(+ <CreateLibraryDashboardModal+ opened+ collectionId={DASHBOARDS_COLLECTION.id}+ onClose={onClose}+ />,+ { withRouter: true },+ );++ return { onClose, router };+}++describe("CreateLibraryDashboardModal", () => {+ it("preselects the Dashboards collection", async () => {+ setup();++ expect(await screen.findByText("Dashboards")).toBeInTheDocument();+ });++ it("creates the dashboard in the Library and opens it in the main app", async () => {+ const { router } = setup();++ await userEvent.type(screen.getByLabelText("Name"), "Sales");+ await userEvent.type(screen.getByLabelText("Description"), "Revenue");+ await userEvent.click(screen.getByRole("button", { name: "Create" }));++ await waitFor(() =>+ expect(router?.location).toMatchObject({+ pathname: "/dashboard/42-sales",+ hash: "#edit",+ }),+ );+ expect(+ await fetchMock.callHistory+ .lastCall("path:/api/dashboard")+ ?.request?.json(),+ ).toEqual({+ name: "Sales",+ description: "Revenue",+ collection_id: DASHBOARDS_COLLECTION.id,+ });+ });++ it("calls onClose when Cancel is clicked", async () => {+ const { onClose } = setup();++ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));++ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.tsxindex 357ddf76f75..5329b9b2eb3 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.tsx@@ -23,11 +23,17 @@ export const CreateMenu = ({canWriteToMetricCollection,dataCollectionId,canWriteToDataCollection,+ dashboardCollectionId,+ canWriteToDashboardCollection,+ onNewDashboardClick,}: {metricCollectionId?: CollectionId;canWriteToMetricCollection?: boolean;dataCollectionId?: CollectionId;canWriteToDataCollection?: boolean;+ dashboardCollectionId?: CollectionId;+ canWriteToDashboardCollection?: boolean;+ onNewDashboardClick: () => void;}) => {const dispatch = useDispatch();const navigate = useNavigate();@@ -47,17 +53,21 @@ export const CreateMenu = ({const canCreateMetric =hasDataAccess && metricCollectionId && canWriteToMetricCollection;- const canCreateCollection =+ const canCreateDashboard =+ dashboardCollectionId && canWriteToDashboardCollection;++ const canCreateLibraryCollection =(dataCollectionId && canWriteToDataCollection) ||(metricCollectionId && canWriteToMetricCollection) ||+ canCreateDashboard;++ const canCreateCollection =+ canCreateLibraryCollection ||(hasNativeWrite && PLUGIN_SNIPPET_FOLDERS.isEnabled);const collectionNamespaces: CollectionNamespace[] = [];- if (- (dataCollectionId && canWriteToDataCollection) ||- (metricCollectionId && canWriteToMetricCollection)- ) {+ if (canCreateLibraryCollection) {collectionNamespaces.push(null);}@@ -68,6 +78,7 @@ export const CreateMenu = ({const initialCollectionId =(dataCollectionId && canWriteToDataCollection && dataCollectionId) ||(metricCollectionId && canWriteToMetricCollection && metricCollectionId) ||+ (canCreateDashboard && dashboardCollectionId) ||null;const menuItems = [@@ -91,6 +102,15 @@ export const CreateMenu = ({{t`Metric`}</Menu.Item>),+ canCreateDashboard && (+ <Menu.Item+ key="dashboard"+ leftSection={<FixedSizeIcon name="dashboard" />}+ onClick={onNewDashboardClick}+ >+ {t`Dashboard`}+ </Menu.Item>+ ),hasNativeWrite && (<Menu.Itemkey="snippet"diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.unit.spec.tsxindex b26ce966f76..180e6f92558 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateMenu.unit.spec.tsx@@ -18,6 +18,7 @@ interface SetupOptions {dataCollectionId?: number;canWriteToDataCollection?: boolean;canWriteToMetricCollection?: boolean;+ canWriteToDashboardCollection?: boolean;remoteSyncType?: EnterpriseSettings["remote-sync-type"];}@@ -34,8 +35,10 @@ const setup = ({dataCollectionId = 2,canWriteToDataCollection = true,canWriteToMetricCollection = true,+ canWriteToDashboardCollection = false,remoteSyncType,}: SetupOptions = {}) => {+ const onNewDashboardClick = jest.fn();const state = createMockState({settings: mockSettings({"token-features": createMockTokenFeatures({@@ -54,13 +57,16 @@ const setup = ({dataCollectionId={dataCollectionId}canWriteToDataCollection={canWriteToDataCollection}canWriteToMetricCollection={canWriteToMetricCollection}+ dashboardCollectionId={3}+ canWriteToDashboardCollection={canWriteToDashboardCollection}+ onNewDashboardClick={onNewDashboardClick}/>,{storeInitialState: state,},);- return utils;+ return { ...utils, onNewDashboardClick };};describe("CreateMenu", () => {@@ -186,6 +192,44 @@ describe("CreateMenu", () => {});});+ it("renders the Dashboard option when the Dashboards collection is writable", async () => {+ const { onNewDashboardClick } = setup({+ user: fullPermissionsUser,+ canWriteToDashboardCollection: true,+ });++ await userEvent.click(screen.getByRole("button", { name: /New/ }));+ expect(+ screen.getAllByRole("menuitem").map((item) => item.textContent),+ ).toEqual([+ "Published table",+ "Metric",+ "Dashboard",+ "Snippet",+ "Collection",+ ]);++ await userEvent.click(screen.getByRole("menuitem", { name: /Dashboard/ }));+ expect(onNewDashboardClick).toHaveBeenCalled();+ });++ it("renders the Collection option when only the Dashboards collection is writable", async () => {+ const { store } = setup({+ user: {},+ canWriteToDataCollection: false,+ canWriteToMetricCollection: false,+ canWriteToDashboardCollection: true,+ });++ await userEvent.click(screen.getByRole("button", { name: /New/ }));+ await userEvent.click(screen.getByRole("menuitem", { name: /Collection/ }));++ expect(store.getState().modal.props).toMatchObject({+ initialCollectionId: 3,+ namespaces: [null],+ });+ });+it("renders nothing if remote sync is set to read-only", () => {setup({ user: fullPermissionsUser, remoteSyncType: "read-only" });expect(diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/EmptyStateAction.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/EmptyStateAction.tsxindex f0c20842a86..0bf9267294f 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/EmptyStateAction.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/EmptyStateAction.tsx@@ -5,13 +5,17 @@ import { Anchor } from "metabase/ui";interface EmptyStateActionProps {data: EmptyStateData;onPublishTableClick: () => void;+ onNewDashboardClick: () => void;}export function EmptyStateAction({data,onPublishTableClick,+ onNewDashboardClick,}: EmptyStateActionProps) {- if (data.sectionType === "data") {+ if (data.sectionType === "data" || data.sectionType === "dashboards") {+ const onClick =+ data.sectionType === "data" ? onPublishTableClick : onNewDashboardClick;return (<Anchorcomponent="button"@@ -19,7 +23,7 @@ export function EmptyStateAction({fz="inherit"onClick={(e) => {e.stopPropagation();- onPublishTableClick();+ onClick();}}>{data.actionLabel}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.tsxindex 1153653ac14..4929fb661f6 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryBulkActions.tsx@@ -1,4 +1,5 @@import { useCallback, useMemo, useState } from "react";+import { match } from "ts-pattern";import { msgid, ngettext, t } from "ttag";import { useSetArchive } from "metabase/archive/hooks";@@ -272,7 +273,11 @@ function LibraryMoveModal({hasConfirmButtons: true,confirmButtonText: t`Move`,}}- entityType={section === "data" ? "table" : "metric"}+ entityType={match(section)+ .with("data", () => "table" as const)+ .with("metrics", () => "metric" as const)+ .with("dashboards", () => "dashboard" as const)+ .exhaustive()}/>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsxindex a711ce76ebe..f7e5c3e5708 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.tsx@@ -9,31 +9,13 @@ import { getArchiveLibraryCollectionsMessage } from "../utils";type LibraryCollectionRowMenuProps = {childCount: number;collection: Collection;- refreshMetricCollections: (collectionIds: CollectionId[]) => void;- refreshTableCollections: (collectionIds: CollectionId[]) => void;+ refreshCollections: (collectionIds: CollectionId[]) => void;};export function LibraryCollectionRowMenu(props: LibraryCollectionRowMenuProps) {- const {- childCount,- collection,- refreshMetricCollections,- refreshTableCollections,- } = props;+ const { childCount, collection, refreshCollections } = props;const isLibraryDataCollection =collection.type === "library-data" && !collection.is_library_root;- const refreshCollections = useCallback(- (collectionIds: CollectionId[]) => {- if (collection.type === "library-metrics") {- refreshMetricCollections(collectionIds);- }-- if (collection.type === "library-data") {- refreshTableCollections(collectionIds);- }- },- [refreshMetricCollections, refreshTableCollections, collection.type],- );const onArchiveSuccess = useCallback(() => {const parentId = getParentCollectionId(collection);diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsxindex 2e1d656c036..339a7aab87a 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/LibraryCollectionRowMenu.unit.spec.tsx@@ -25,8 +25,7 @@ function setup({}),childCount = 0,}: Partial<Parameters<typeof LibraryCollectionRowMenu>[0]> = {}) {- const refreshMetricCollections = jest.fn();- const refreshTableCollections = jest.fn();+ const refreshCollections = jest.fn();const parentCollection = createMockCollection({id: 22,name: "Data",@@ -42,8 +41,7 @@ function setup({<LibraryCollectionRowMenuchildCount={childCount}collection={collection}- refreshMetricCollections={refreshMetricCollections}- refreshTableCollections={refreshTableCollections}+ refreshCollections={refreshCollections}/>,{storeInitialState: createMockState({@@ -58,12 +56,12 @@ function setup({},);- return { refreshMetricCollections, refreshTableCollections };+ return { refreshCollections };}describe("LibraryCollectionRowMenu", () => {- it("refreshes table collections after saving a Library Data collection", async () => {- const { refreshMetricCollections, refreshTableCollections } = setup();+ it("refreshes the parent collection after saving", async () => {+ const { refreshCollections } = setup();await userEvent.click(screen.getByRole("button", { name: "Collection options" }),@@ -75,34 +73,8 @@ describe("LibraryCollectionRowMenu", () => {await userEvent.click(screen.getByRole("button", { name: "Save" }));await waitFor(() => {- expect(refreshTableCollections).toHaveBeenCalledWith([22]);+ expect(refreshCollections).toHaveBeenCalledWith([22]);});- expect(refreshMetricCollections).not.toHaveBeenCalled();- });-- it("refreshes metric collections after saving a Library Metrics collection", async () => {- const { refreshMetricCollections, refreshTableCollections } = setup({- collection: createMockCollection({- id: 2,- name: "Library Metrics Collection",- type: "library-metrics",- parent_id: 22,- }),- });-- await userEvent.click(- screen.getByRole("button", { name: "Collection options" }),- );- await userEvent.click(- screen.getByRole("menuitem", { name: /Edit collection details/ }),- );- await userEvent.type(screen.getByLabelText("Name"), " Updated");- await userEvent.click(screen.getByRole("button", { name: "Save" }));-- await waitFor(() => {- expect(refreshMetricCollections).toHaveBeenCalledWith([22]);- });- expect(refreshTableCollections).not.toHaveBeenCalled();});it("shows a table unpublish warning when archiving a non-empty Library Data collection", async () => {diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.tsindex 79e7dfa67f2..bc060093092 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.ts@@ -13,9 +13,14 @@ import type {DatabaseId,} from "metabase-types/api";-export type LibrarySection = "data" | "metrics" | "snippets";+export type LibrarySection = "data" | "metrics" | "dashboards" | "snippets";-export type SelectableModel = "table" | "metric" | "snippet" | "collection";+export type SelectableModel =+ | "table"+ | "metric"+ | "dashboard"+ | "snippet"+ | "collection";export type SelectedItem = {key: string;@@ -34,10 +39,13 @@ const isCollectionRow = (const isLeafRow = (item: TreeItem,): item is TreeItem & {- model: "table" | "metric" | "snippet";+ model: "table" | "metric" | "dashboard" | "snippet";data: CollectionItem;} =>- item.model === "table" || item.model === "metric" || item.model === "snippet";+ item.model === "table" ||+ item.model === "metric" ||+ item.model === "dashboard" ||+ item.model === "snippet";const keyOf = (item: TreeItem): string => item.id;@@ -52,6 +60,9 @@ export function getItemSection(item: TreeItem): LibrarySection | null {if (item.model === "metric") {return "metrics";}+ if (item.model === "dashboard") {+ return "dashboards";+ }if (item.model === "snippet") {return "snippets";}@@ -66,6 +77,9 @@ export function getItemSection(item: TreeItem): LibrarySection | null {if (data.type === "library-data") {return "data";}+ if (data.type === "library-dashboards") {+ return "dashboards";+ }}return null;}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.unit.spec.tsindex 01e7051b1d5..353b0ee60e7 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-bulk-selection.utils.unit.spec.ts@@ -24,6 +24,7 @@ import {const SECTION_TYPE: Record<LibrarySection, CollectionType | null> = {data: "library-data",metrics: "library-metrics",+ dashboards: "library-dashboards",snippets: null,};@@ -64,6 +65,24 @@ function metricItem(};}+function dashboardItem(+ id: number,+ opts: { collectionId?: number | null } = {},+): TreeItem {+ return {+ id: `dashboard:${id}`,+ name: `Dashboard ${id}`,+ icon: "dashboard",+ model: "dashboard",+ data: createMockCollectionItem({+ id,+ model: "dashboard",+ collection_id: opts.collectionId ?? null,+ can_write: true,+ }),+ };+}+function snippetItem(id: number,opts: { collectionId?: number | null } = {},@@ -154,9 +173,11 @@ describe("library-bulk-selection.utils", () => {it("derives the section from model and collection type/namespace", () => {expect(getItemSection(tableItem(1))).toBe("data");expect(getItemSection(metricItem(1))).toBe("metrics");+ expect(getItemSection(dashboardItem(1))).toBe("dashboards");expect(getItemSection(snippetItem(1))).toBe("snippets");expect(getItemSection(subCollection(2, "data"))).toBe("data");expect(getItemSection(subCollection(3, "metrics"))).toBe("metrics");+ expect(getItemSection(subCollection(5, "dashboards"))).toBe("dashboards");expect(getItemSection(subCollection(4, "snippets"))).toBe("snippets");expect(getItemSection(emptyState())).toBeNull();});@@ -270,6 +291,21 @@ describe("library-bulk-selection.utils", () => {},]);});++ it("reads dashboard rows into the dashboards section", () => {+ expect(+ deriveSelectedItems([dashboardItem(7, { collectionId: 12 })]),+ ).toEqual([+ {+ key: "dashboard:7",+ model: "dashboard",+ section: "dashboards",+ entityId: 7,+ sourceCollectionId: 12,+ canWrite: true,+ },+ ]);+ });});describe("getSelectionSection", () => {diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.tsindex 176f711510d..6cc46b9ab22 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.ts@@ -17,6 +17,7 @@ export function selectedItemToMovable(item: SelectedItem): MovableItem {return match<SelectedItem, MovableItem>(item).with({ model: "table" }, () => ({ model: "table", id })).with({ model: "metric" }, () => ({ model: "metric", id }))+ .with({ model: "dashboard" }, () => ({ model: "dashboard", id })).with({ model: "snippet" }, () => ({ model: "snippet", id })).with({ model: "collection", section: "snippets" }, () => ({model: "snippet-collection",@@ -34,6 +35,11 @@ export function selectedItemToArchivable(item: SelectedItem): ArchivableItem {id,can_write: canWrite,}))+ .with({ model: "dashboard" }, () => ({+ model: "dashboard",+ id,+ can_write: canWrite,+ })).with({ model: "snippet" }, () => ({model: "snippet",id,diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.unit.spec.tsindex b9de015d9c9..3402748332c 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/library-item-updates.unit.spec.ts@@ -55,6 +55,9 @@ describe("selectedItemToMovable", () => {model: "snippet",id: 3,});+ expect(+ selectedItemToMovable(item("dashboard", 6, 10, "dashboards")),+ ).toEqual({ model: "dashboard", id: 6 });});it("distinguishes snippet folders from data/metrics collections", () => {@@ -80,6 +83,9 @@ describe("selectedItemToArchivable", () => {id: 3,can_write: true,});+ expect(+ selectedItemToArchivable(item("dashboard", 6, 10, "dashboards")),+ ).toEqual({ model: "dashboard", id: 6, can_write: true });expect(selectedItemToArchivable(item("collection", 4, 10, "metrics")),).toEqual({ model: "collection", id: 4, can_write: true });diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollectionTree.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollectionTree.tsindex 752db6495e6..842f60f3cb6 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollectionTree.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollectionTree.ts@@ -21,8 +21,16 @@ import type {Collection,CollectionId,CollectionItem,+ CollectionItemModel,} from "metabase-types/api";+const SECTION_ITEM_MODELS: Record<LibrarySectionType, CollectionItemModel[]> = {+ data: ["table", "collection"],+ metrics: ["metric", "collection"],+ dashboards: ["dashboard", "collection"],+ snippets: ["snippet", "collection"],+};+export function useLibraryCollectionTree(collection: Collection | undefined,sectionType: LibrarySectionType,@@ -30,6 +38,7 @@ export function useLibraryCollectionTree() {const dispatch = useDispatch();const getIcon = useGetIcon();+ const models = SECTION_ITEM_MODELS[sectionType];// 1. Fetch top-level itemsconst {@@ -40,7 +49,7 @@ export function useLibraryCollectionTree(collection? {id: collection.id,- models: ["metric", "table", "collection"],+ models,archived: false,}: skipToken,@@ -71,7 +80,7 @@ export function useLibraryCollectionTree(collectionApi.endpoints.listCollectionItems.initiate({id: collectionId,- models: ["metric", "table", "collection"],+ models,archived: false,},{ forceRefetch: true },@@ -80,7 +89,7 @@ export function useLibraryCollectionTree(const items = (result.data?.data ?? []).filter((item) => !item.archived);setLoadedCollections((prev) => new Map([...prev, [collectionId, items]]));},- [dispatch],+ [dispatch, models],);const refreshCollections = useCallback(diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollections.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollections.tsindex e87032da922..496d39aef8d 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollections.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryCollections.ts@@ -25,5 +25,17 @@ export const useLibraryCollections = (collections: Collection[]) => {[libraryCollection],);- return { libraryCollection, tableCollection, metricCollection };+ const dashboardCollection = useMemo(+ () =>+ libraryCollection &&+ getAccessibleCollection(libraryCollection, "library-dashboards"),+ [libraryCollection],+ );++ return {+ libraryCollection,+ tableCollection,+ metricCollection,+ dashboardCollection,+ };};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibrarySearch.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibrarySearch.tsindex 4efe33587ae..d58b08cb335 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibrarySearch.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibrarySearch.ts@@ -28,7 +28,7 @@ export function useLibrarySearch(? {q: debouncedQuery,collection: libraryCollectionId,- models: ["table", "metric"],+ models: ["table", "metric", "dashboard"],context: "library",}: skipToken,@@ -44,9 +44,14 @@ export function useLibrarySearch(if (searchResponse) {const dataItems: TreeItem[] = [];const metricItems: TreeItem[] = [];+ const dashboardItems: TreeItem[] = [];for (const result of searchResponse.data) {- if (result.model !== "table" && result.model !== "metric") {+ if (+ result.model !== "table" &&+ result.model !== "metric" &&+ result.model !== "dashboard"+ ) {continue;}@@ -73,6 +78,8 @@ export function useLibrarySearch(dataItems.push(item);} else if (result.model === "metric") {metricItems.push(item);+ } else {+ dashboardItems.push(item);}}@@ -103,6 +110,20 @@ export function useLibrarySearch(children: metricItems,});}++ if (dashboardItems.length > 0) {+ sections.push({+ id: "search-section:dashboards",+ name: t`Dashboards`,+ icon: "dashboard",+ model: "collection",+ data: {+ model: "collection",+ name: t`Dashboards`,+ },+ children: dashboardItems,+ });+ }}// Client-side filter snippetsdiff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsxindex 97713a307ec..da6b5fa455d 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx@@ -20,12 +20,13 @@ import {useTreeTableInstance,} from "metabase/ui";import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";-import type { Collection } from "metabase-types/api";+import type { Collection, CollectionId } from "metabase-types/api";import { ActionCell } from "../components/ActionCell";import { EmptyStateAction } from "../components/EmptyStateAction";import { getTreeRowHref } from "../utils";+import type { LibrarySection } from "./library-bulk-selection.utils";import { useErrorHandling } from "./useErrorHandling";import { useLibraryCollectionTree } from "./useLibraryCollectionTree";import { useLibraryCollections } from "./useLibraryCollections";@@ -36,6 +37,7 @@ type Params = {isLoadingCollections: boolean;searchQuery: string;onPublishTableClick: VoidFunction;+ onNewDashboardClick: VoidFunction;};export function useLibraryTreeTableInstance({@@ -43,6 +45,7 @@ export function useLibraryTreeTableInstance({isLoadingCollections,searchQuery,onPublishTableClick,+ onNewDashboardClick,}: Params) {const [searchParams] = useSearchParams();const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);@@ -58,8 +61,12 @@ export function useLibraryTreeTableInstance({ids.map((id) => [`collection:${id}`, true]),) as ExpandedState;}, [searchParams]);- const { libraryCollection, tableCollection, metricCollection } =- useLibraryCollections(collections);+ const {+ libraryCollection,+ tableCollection,+ metricCollection,+ dashboardCollection,+ } = useLibraryCollections(collections);const {tree: tablesTree,@@ -81,13 +88,38 @@ export function useLibraryTreeTableInstance({"metrics",metricCollection?.id,);+ const {+ tree: dashboardsTree,+ isLoading: loadingDashboards,+ error: dashboardsError,+ watchRows: watchDashboardRows,+ isChildrenLoading: isDashboardChildrenLoading,+ refreshCollections: refreshDashboardCollections,+ } = useLibraryCollectionTree(dashboardCollection, "dashboards");const {tree: snippetTree,isLoading: loadingSnippets,error: snippetsError,} = useBuildSnippetTree();- // Server-side search for tables and metrics, client-side for snippets+ const refreshSection = useCallback(+ (section: LibrarySection, collectionIds: CollectionId[]) => {+ const refreshCollections = {+ data: refreshTableCollections,+ metrics: refreshMetricCollections,+ dashboards: refreshDashboardCollections,+ snippets: undefined,+ }[section];+ refreshCollections?.(collectionIds);+ },+ [+ refreshTableCollections,+ refreshMetricCollections,+ refreshDashboardCollections,+ ],+ );++ // Server-side search for tables, metrics, and dashboards, client-side for snippetsconst {tree: searchTree,isActive: isSearchActive,@@ -98,17 +130,27 @@ export function useLibraryTreeTableInstance({() =>isSearchActive? searchTree- : [...tablesTree, ...metricsTree, ...snippetTree],- [isSearchActive, searchTree, tablesTree, metricsTree, snippetTree],+ : [...tablesTree, ...metricsTree, ...dashboardsTree, ...snippetTree],+ [+ isSearchActive,+ searchTree,+ tablesTree,+ metricsTree,+ dashboardsTree,+ snippetTree,+ ],);const isLoading =isLoadingCollections ||loadingTables ||loadingMetrics ||+ loadingDashboards ||loadingSnippets ||isSearchLoading;- useErrorHandling(tablesError || metricsError || snippetsError);+ useErrorHandling(+ tablesError || metricsError || dashboardsError || snippetsError,+ );const libraryHasContent = useMemo(() =>@@ -142,6 +184,7 @@ export function useLibraryTreeTableInstance({<EmptyStateActiondata={data}onPublishTableClick={onPublishTableClick}+ onNewDashboardClick={onNewDashboardClick}/>)}</Flex>@@ -211,26 +254,22 @@ export function useLibraryTreeTableInstance({id: "actions",width: 48,cell: ({ row }) => (- <ActionCell- treeItem={row.original}- refreshMetricCollections={refreshMetricCollections}- refreshTableCollections={refreshTableCollections}- />+ <ActionCell treeItem={row.original} refreshSection={refreshSection} />),},],[isRemoteSyncReadOnly,onPublishTableClick,- refreshMetricCollections,- refreshTableCollections,+ onNewDashboardClick,+ refreshSection,],);const snippetRootId = snippetTree[0]?.id;// Controlled expansion: expand all during search, preserve user state when browsing.- // Default any IDs from the URL. If none are provided, default to Data, Metrics and SQL Snippets expanded+ // Default any IDs from the URL. If none are provided, default to Data, Metrics, Dashboards and SQL Snippets expandedconst defaultExpanded = useMemo<ExpandedState>(() => {if (expandedIdsFromUrl) {return expandedIdsFromUrl;@@ -242,13 +281,22 @@ export function useLibraryTreeTableInstance({if (metricCollection) {ids[`collection:${metricCollection.id}`] = true;}+ if (dashboardCollection) {+ ids[`collection:${dashboardCollection.id}`] = true;+ }if (snippetRootId) {ids[snippetRootId] = true;}return ids;- }, [expandedIdsFromUrl, tableCollection, metricCollection, snippetRootId]);+ }, [+ expandedIdsFromUrl,+ tableCollection,+ metricCollection,+ dashboardCollection,+ snippetRootId,+ ]);const [browseExpanded, setBrowseExpanded] = useState<ExpandedState | null>(null,@@ -317,17 +365,29 @@ export function useLibraryTreeTableInstance({useEffect(() => {watchTableRows(treeTableInstance.rows);watchMetricRows(treeTableInstance.rows);- }, [treeTableInstance.rows, watchTableRows, watchMetricRows]);+ watchDashboardRows(treeTableInstance.rows);+ }, [+ treeTableInstance.rows,+ watchTableRows,+ watchMetricRows,+ watchDashboardRows,+ ]);const isChildrenLoading = useCallback((row: Parameters<typeof isTableChildrenLoading>[0]) =>- isTableChildrenLoading(row) || isMetricChildrenLoading(row),- [isTableChildrenLoading, isMetricChildrenLoading],+ isTableChildrenLoading(row) ||+ isMetricChildrenLoading(row) ||+ isDashboardChildrenLoading(row),+ [+ isTableChildrenLoading,+ isMetricChildrenLoading,+ isDashboardChildrenLoading,+ ],);let emptyMessage = null;if (!libraryHasContent) {- emptyMessage = t`No tables, metrics, or snippets yet`;+ emptyMessage = t`No tables, metrics, dashboards, or snippets yet`;} else if (searchQuery) {emptyMessage = t`No results for "${searchQuery}"`;}@@ -340,7 +400,6 @@ export function useLibraryTreeTableInstance({isChildrenLoading,isLoading,emptyMessage,- refreshTableCollections,- refreshMetricCollections,+ refreshSection,};}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.tsindex f4bca9d8b2e..81324b1a47e 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.ts@@ -47,5 +47,8 @@ export const getTreeRowHref = (row: { original: TreeItem }): string | null => {if (treeItem.model === "table") {return Urls.dataStudioTable(entityId);}+ if (treeItem.model === "dashboard") {+ return Urls.dashboard({ id: entityId, name: treeItem.name });+ }return null;};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.unit.spec.tsindex f933f20f59f..9c21ce25e2f 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/utils.unit.spec.ts@@ -1,6 +1,13 @@-import { createMockCollection } from "metabase-types/api/mocks";+import {+ createMockCollection,+ createMockCollectionItem,+} from "metabase-types/api/mocks";-import { getAccessibleCollection, getWritableCollection } from "./utils";+import {+ getAccessibleCollection,+ getTreeRowHref,+ getWritableCollection,+} from "./utils";describe("getWritableCollection", () => {it("returns collection when can_write is true", () => {@@ -112,3 +119,19 @@ describe("getAccessibleCollection", () => {expect(result).toBeUndefined();});});++describe("getTreeRowHref", () => {+ it("links dashboards to the main app's dashboard page", () => {+ const href = getTreeRowHref({+ original: {+ id: "dashboard:7",+ name: "Sales",+ icon: "dashboard",+ model: "dashboard",+ data: createMockCollectionItem({ id: 7, model: "dashboard" }),+ },+ });++ expect(href).toBe("/dashboard/7-sales");+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.tsindex 0c9719ebeac..91d525f8bec 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts@@ -84,10 +84,12 @@ export const useGetResolvedLibraryCollection = ({libraryCollection && hasStuff ? { id: libraryCollection.id } : skipToken,);+ // The Dashboards section never holds data sourcesconst subcollectionsWithStuff =libraryItems?.data.filter((item) =>item.model === "collection" &&+ item.type !== "library-dashboards" &&(item.here?.length || item.below?.length),) ?? [];@@ -97,7 +99,10 @@ export const useGetResolvedLibraryCollection = ({({ subcollectionsWithStuff }) => subcollectionsWithStuff?.length === 1,() => subcollectionsWithStuff[0],)- .with({ hasStuff: true }, () => libraryCollection)+ .when(+ ({ subcollectionsWithStuff }) => subcollectionsWithStuff.length > 1,+ () => libraryCollection,+ ).otherwise(() => undefined);return {@@ -118,6 +123,8 @@ function getLibrarySectionName(type: LibrarySubCollectionType) {return t`Data`;case "library-metrics":return t`Metrics`;+ case "library-dashboards":+ return t`Dashboards`;}}@@ -135,6 +142,7 @@ export function getCollectionPickerItems({const librarySubCollectionType: LibrarySubCollectionType[] = ["library-data","library-metrics",+ "library-dashboards",];return librarySubCollectionType.flatMap((type) => {@@ -193,6 +201,13 @@ export const getLibraryCollectionEmptyStateMessages = (};}+ if (type === "library-dashboards") {+ return {+ title: t`No dashboards yet`,+ description: t`Put dashboards in the semantic layer to see them here.`,+ };+ }+return {title: t`No metrics yet`,description: t`Put metrics in the semantic layer to see them here.`,@@ -202,7 +217,11 @@ export const getLibraryCollectionEmptyStateMessages = (export const isLibrarySubCollectionType = (type?: string | null,): type is LibrarySubCollectionType => {- return type === "library-data" || type === "library-metrics";+ return (+ type === "library-data" ||+ type === "library-metrics" ||+ type === "library-dashboards"+ );};export const isLibraryDataCollectionType = (diff --git a/frontend/lint/side-effect-files.json b/frontend/lint/side-effect-files.jsonindex 5a39a89cb71..7c33c339ead 100644--- a/frontend/lint/side-effect-files.json+++ b/frontend/lint/side-effect-files.json@@ -50,6 +50,7 @@"enterprise/frontend/src/metabase-enterprise/auth/index.ts": "global","enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/utils.ts": "self","enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizPage.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/components/CreateLibraryDashboardModal.tsx": "self","enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx": "entry","enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts": "entry","enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationForm.tsx": "self",diff --git a/frontend/src/embedding-sdk-bundle/types/collection.ts b/frontend/src/embedding-sdk-bundle/types/collection.tsindex 575a68f240e..29e381edcd5 100644--- a/frontend/src/embedding-sdk-bundle/types/collection.ts+++ b/frontend/src/embedding-sdk-bundle/types/collection.ts@@ -47,6 +47,7 @@ export type MetabaseCollectionItem = {| "library"| "library-data"| "library-metrics"+ | "library-dashboards"| "shared-tenant-collection"| "tenant-specific-root-collection"| "model"diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.tsindex 02cc9bad744..2bce2f0b6e6 100644--- a/frontend/src/metabase-types/api/collection.ts+++ b/frontend/src/metabase-types/api/collection.ts@@ -42,6 +42,7 @@ export type CollectionType =| "library"| "library-data"| "library-metrics"+ | "library-dashboards"| "shared-tenant-collection"| "tenant-specific-root-collection"| null;diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx b/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsxindex 1e24a8f5cb9..b441341f6f8 100644--- a/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx+++ b/frontend/src/metabase/common/collections/components/CollectionRowMenu/EditCollectionModal/EditCollectionModal.tsx@@ -155,6 +155,10 @@ function getPickerEntityType(return "metric";}+ if (collectionType === "library-dashboards") {+ return "dashboard";+ }+return undefined;}diff --git a/frontend/src/metabase/common/collections/utils.ts b/frontend/src/metabase/common/collections/utils.tsindex 0e48b8b363a..8daced02786 100644--- a/frontend/src/metabase/common/collections/utils.ts+++ b/frontend/src/metabase/common/collections/utils.ts@@ -426,6 +426,8 @@ export function getCollectionIcon(return { name: "table" };case "library-metrics":return { name: "metric" };+ case "library-dashboards":+ return { name: "dashboard" };}}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.tsindex 2e2815b9e10..9d87aa98a73 100644--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts@@ -42,11 +42,13 @@ const getDefaultPath = async ({options,libraryCollection,namespaces,+ models,dispatch,}: {options: EntityPickerOptions;libraryCollection?: LibraryCollection;namespaces: CollectionNamespace[];+ models: OmniPickerCollectionItem["model"][];dispatch: DispatchFn;}): Promise<OmniPickerItem[]> => {if (libraryCollection && options.hasLibrary) {@@ -57,8 +59,11 @@ const getDefaultPath = async ({).unwrap();if (libraryChildrenResponse) {+ // The Dashboards section only holds dashboards, so skip it unless we're picking themconst firstChildCollection = libraryChildrenResponse.data.find(- (item) => item.model === "collection",+ (item) =>+ item.model === "collection" &&+ (item.type !== "library-dashboards" || models.includes("dashboard")),);// we might also want to check if this collection has any relevant modelsif (firstChildCollection) {@@ -114,12 +119,16 @@ export function useGetPathFromValue({setIsLoadingPath(true);if (!value) {- getDefaultPath({ options, libraryCollection, namespaces, dispatch }).then(- (path) => {- setPath(path);- setIsLoadingPath(false);- },- );+ getDefaultPath({+ options,+ libraryCollection,+ namespaces,+ models,+ dispatch,+ }).then((path) => {+ setPath(path);+ setIsLoadingPath(false);+ });return;}diff --git a/frontend/src/metabase/common/data-studio/collection-utils.ts b/frontend/src/metabase/common/data-studio/collection-utils.tsindex a0df27e6841..3ee95e61c8e 100644--- a/frontend/src/metabase/common/data-studio/collection-utils.ts+++ b/frontend/src/metabase/common/data-studio/collection-utils.ts@@ -22,6 +22,10 @@ export function canPlaceEntityInCollection(return entityType === "metric" || entityType === "collection";}+ if (collectionType === "library-dashboards") {+ return entityType === "dashboard" || entityType === "collection";+ }+return false;}@@ -33,10 +37,16 @@ export function canPlaceEntityInCollectionOrDescendants(return true;}+ // Questions can be saved into the dashboards inside the Dashboards section+ if (collectionType === "library-dashboards") {+ return entityType === "card";+ }+if (collectionType === "library") {return (canPlaceEntityInCollection(entityType, "library-data") ||- canPlaceEntityInCollection(entityType, "library-metrics")+ canPlaceEntityInCollection(entityType, "library-metrics") ||+ canPlaceEntityInCollectionOrDescendants(entityType, "library-dashboards"));}diff --git a/frontend/src/metabase/common/data-studio/collection-utils.unit.spec.ts b/frontend/src/metabase/common/data-studio/collection-utils.unit.spec.tsindex 7e32dbd1a17..555ca453866 100644--- a/frontend/src/metabase/common/data-studio/collection-utils.unit.spec.ts+++ b/frontend/src/metabase/common/data-studio/collection-utils.unit.spec.ts@@ -2,7 +2,10 @@ import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import { mockSettings } from "__support__/settings";import { createMockTokenFeatures } from "metabase-types/api/mocks";-import { canPlaceEntityInCollection } from "./collection-utils";+import {+ canPlaceEntityInCollection,+ canPlaceEntityInCollectionOrDescendants,+} from "./collection-utils";describe("canPlaceEntityInCollection", () => {beforeEach(() => {@@ -32,9 +35,54 @@ describe("canPlaceEntityInCollection", () => {expect(canPlaceEntityInCollection("table", "library-metrics")).toBe(false);});+ it("should only allow dashboards and collections in Library Dashboards collections", () => {+ expect(canPlaceEntityInCollection("dashboard", "library-dashboards")).toBe(+ true,+ );+ expect(canPlaceEntityInCollection("collection", "library-dashboards")).toBe(+ true,+ );+ expect(canPlaceEntityInCollection("card", "library-dashboards")).toBe(+ false,+ );+ expect(canPlaceEntityInCollection("metric", "library-dashboards")).toBe(+ false,+ );+ });+it("should allow entities in non-Library collections", () => {expect(canPlaceEntityInCollection("table", null)).toBe(true);expect(canPlaceEntityInCollection("metric", undefined)).toBe(true);expect(canPlaceEntityInCollection("collection", null)).toBe(true);});});++describe("canPlaceEntityInCollectionOrDescendants", () => {+ beforeEach(() => {+ mockSettings({+ "token-features": createMockTokenFeatures({ library: true }),+ });+ setupEnterpriseOnlyPlugin("library");+ });++ it("should let questions reach the dashboards inside the Library", () => {+ expect(canPlaceEntityInCollectionOrDescendants("card", "library")).toBe(+ true,+ );+ expect(+ canPlaceEntityInCollectionOrDescendants("card", "library-dashboards"),+ ).toBe(true);+ expect(+ canPlaceEntityInCollectionOrDescendants("card", "library-data"),+ ).toBe(false);+ });++ it("should let dashboards reach the Library's Dashboards collection", () => {+ expect(+ canPlaceEntityInCollectionOrDescendants("dashboard", "library"),+ ).toBe(true);+ expect(+ canPlaceEntityInCollectionOrDescendants("dashboard", "library-metrics"),+ ).toBe(false);+ });+});diff --git a/frontend/src/metabase/data-studio/common/types.ts b/frontend/src/metabase/data-studio/common/types.tsindex c0c25f88853..605db899848 100644--- a/frontend/src/metabase/data-studio/common/types.ts+++ b/frontend/src/metabase/data-studio/common/types.ts@@ -6,7 +6,7 @@ import type {Table,} from "metabase-types/api";-export type LibrarySectionType = "data" | "metrics" | "snippets";+export type LibrarySectionType = "data" | "metrics" | "dashboards" | "snippets";export type EmptyStateData = {model: "empty-state";diff --git a/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.ts b/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.tsindex 3c802915305..fa30ff7fd54 100644--- a/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.ts+++ b/frontend/src/metabase/data-studio/common/utils/create-empty-space-item.ts@@ -27,6 +27,10 @@ const getEmptyStateConfig = (description: t`Standardized calculations with known dimensions`,actionLabel: t`New metric`,},+ dashboards: {+ description: t`Curated dashboards built on the semantic layer`,+ actionLabel: t`Create a dashboard`,+ },snippets: {description: t`Reusable bits of code that save your time`,actionLabel: t`New snippet`,@@ -49,7 +53,7 @@ export const createEmptyStateItem = (} else if (sectionType === "snippets" && !hideAction) {actionUrl = Urls.newDataStudioSnippet();}- // "data" section opens a modal, so no actionUrl+ // "data" and "dashboards" sections open a modal, so no actionUrlreturn {id: `empty-state:${sectionType}`,diff --git a/frontend/src/metabase/hooks/use-icon.ts b/frontend/src/metabase/hooks/use-icon.tsindex c38466c4093..d523854c563 100644--- a/frontend/src/metabase/hooks/use-icon.ts+++ b/frontend/src/metabase/hooks/use-icon.ts@@ -61,6 +61,8 @@ export const useGetIconBase = () => {return { name: "table" };case "library-metrics":return { name: "metric" };+ case "library-dashboards":+ return { name: "dashboard" };}}diff --git a/frontend/src/metabase/nav/containers/MainNavbar/NavbarLibrarySection/NavbarLibrarySection.tsx b/frontend/src/metabase/nav/containers/MainNavbar/NavbarLibrarySection/NavbarLibrarySection.tsxindex b65e5b8c74e..48d833fac96 100644--- a/frontend/src/metabase/nav/containers/MainNavbar/NavbarLibrarySection/NavbarLibrarySection.tsx+++ b/frontend/src/metabase/nav/containers/MainNavbar/NavbarLibrarySection/NavbarLibrarySection.tsx@@ -25,7 +25,7 @@ type LibraryCollectionSectionProps = {onItemSelect: () => void;};-/** Build the tree for a single library section (Data or Metrics).+/** Build the tree for a single library section (Data, Metrics, or Dashboards).* If the user has access to the root collection, use it directly.* If not, create a synthetic container for any promoted children. */function buildSectionTree(@@ -116,8 +116,14 @@ export function NavbarLibrarySection({"library-metrics",t`Metrics`,);+ const dashboardsTree = buildSectionTree(+ libraryCollection,+ collections,+ "library-dashboards",+ t`Dashboards`,+ );- return [dataTree, metricsTree].filter(+ return [dataTree, metricsTree, dashboardsTree].filter((node): node is CollectionTreeItem => node != null,);}, [collections]);diff --git a/frontend/src/metabase/plugins/oss/library.ts b/frontend/src/metabase/plugins/oss/library.tsindex 44bc188683d..ccd79023618 100644--- a/frontend/src/metabase/plugins/oss/library.ts+++ b/frontend/src/metabase/plugins/oss/library.ts@@ -59,9 +59,13 @@ export type CollectionPermissionsModalProps = {export type LibraryCollectionType =| "library"| "library-data"- | "library-metrics";+ | "library-metrics"+ | "library-dashboards";-export type LibrarySubCollectionType = "library-data" | "library-metrics";+export type LibrarySubCollectionType =+ | "library-data"+ | "library-metrics"+ | "library-dashboards";export type GetEntityPickerSyntheticLibraryItemFunction = {(params: {diff --git a/resources/migrations/065/20261006_library_dashboards.yaml b/resources/migrations/065/20261006_library_dashboards.yamlnew file mode 100644index 00000000000..3188867568e--- /dev/null+++ b/resources/migrations/065/20261006_library_dashboards.yaml@@ -0,0 +1,59 @@+## The Library gets a Dashboards section next to Data and Metrics. New Libraries create it with the other sections;+## existing Libraries get it here, with the Library's own collection permissions and Data Analysts' read-write access.++databaseChangeLog:+ - changeSet:+ id: v65.2026-10-06T16:00:00+ author: ranquild+ comment: Add the Dashboards section to an existing Library+ changes:+ - sql:+ sql: >-+ INSERT INTO collection (name, slug, type, location, entity_id, is_remote_synced)+ SELECT 'Dashboards', 'dashboards', 'library-dashboards', CONCAT('/', lib.id, '/'),+ 'librarylibrarydashbrd', lib.is_remote_synced+ FROM collection lib+ WHERE lib.entity_id = 'librarylibrarylibrary'+ AND NOT EXISTS (SELECT 1 FROM collection d WHERE d.entity_id = 'librarylibrarydashbrd')+ rollback:+ - empty: {}++ - changeSet:+ id: v65.2026-10-06T16:00:01+ author: ranquild+ comment: Copy the Library's collection permissions to its Dashboards section+ changes:+ - sql:+ sql: >-+ INSERT INTO permissions (object, group_id, perm_type, perm_value, collection_id)+ SELECT CASE WHEN p.perm_value = 'read'+ THEN CONCAT('/collection/', d.id, '/read/')+ ELSE CONCAT('/collection/', d.id, '/')+ END,+ p.group_id, p.perm_type, p.perm_value, d.id+ FROM permissions p+ JOIN collection lib ON lib.id = p.collection_id+ JOIN collection d ON d.entity_id = 'librarylibrarydashbrd'+ JOIN permissions_group pg ON pg.id = p.group_id+ WHERE lib.entity_id = 'librarylibrarylibrary'+ AND p.perm_type = 'perms/collection-access'+ AND (pg.magic_group_type IS NULL OR pg.magic_group_type <> 'data-analyst')+ AND NOT EXISTS (SELECT 1 FROM permissions x WHERE x.group_id = p.group_id AND x.collection_id = d.id)+ rollback:+ - empty: {}++ - changeSet:+ id: v65.2026-10-06T16:00:02+ author: ranquild+ comment: Give Data Analysts read-write access to the Library's Dashboards section+ changes:+ - sql:+ sql: >-+ INSERT INTO permissions (object, group_id, perm_type, perm_value, collection_id)+ SELECT CONCAT('/collection/', d.id, '/'), pg.id, 'perms/collection-access', 'read-and-write', d.id+ FROM permissions_group pg+ JOIN collection d ON d.entity_id = 'librarylibrarydashbrd'+ WHERE pg.magic_group_type = 'data-analyst'+ AND NOT EXISTS (SELECT 1 FROM permissions x WHERE x.group_id = pg.id AND x.collection_id = d.id)+ rollback:+ - empty: {}diff --git a/src/metabase/collections/children.clj b/src/metabase/collections/children.cljindex 8129b065b31..50339f5fca8 100644--- a/src/metabase/collections/children.clj+++ b/src/metabase/collections/children.clj@@ -98,9 +98,7 @@[:or [:= :personal_owner_id nil] [:= :personal_owner_id api/*current-user-id*]])(when-not include-library?[:or [:= nil :type]- [:not-in :type [collection/library-collection-type- collection/library-data-collection-type- collection/library-metrics-collection-type]]])+ [:not-in :type (vec collection/library-collection-types)]])[:or(when (contains? namespaces nil)[:= :namespace nil])@@ -706,9 +704,7 @@[:= :type collection-type]))(when-not include-library?[:or [:= nil :type]- [:not [:in :type [collection/library-collection-type- collection/library-metrics-collection-type- collection/library-data-collection-type]]]])+ [:not [:in :type (vec collection/library-collection-types)]]])(if archived?[:or[:= :archived true]diff --git a/src/metabase/collections/core.clj b/src/metabase/collections/core.cljindex 11557024160..fdce5467241 100644--- a/src/metabase/collections/core.clj+++ b/src/metabase/collections/core.clj@@ -25,11 +25,14 @@check-non-remote-synced-dependenciescheck-remote-synced-dependentscreate-library-collection!+ ensure-library-dashboards-collection!descendant-idsineligible-dependenciesinstance-analytics-collection-typelibrary-collectionlibrary-collection-type+ library-dashboards-collection-type+ library-dashboards-collection?library-data-collection-typelibrary-metrics-collection-typelocation-pathdiff --git a/src/metabase/collections/create.clj b/src/metabase/collections/create.cljindex f41c4ac3983..4c52b0cdb7c 100644--- a/src/metabase/collections/create.clj+++ b/src/metabase/collections/create.clj@@ -56,7 +56,7 @@(malli.util/assoc :location [:maybe ms/NonBlankString])(malli.util/assoc :namespace [:maybe [:or :keyword ms/NonBlankString]])(malli.util/assoc :is_remote_synced [:maybe :boolean])- (malli.util/assoc :type [:enum "trash" "library" "library-data" "library-metrics"])+ (malli.util/assoc :type [:enum "trash" "library" "library-data" "library-metrics" "library-dashboards"])(malli.util/optional-keys [:location :type])(malli.util/closed-schema)))diff --git a/src/metabase/collections/db.clj b/src/metabase/collections/db.cljindex 221c000d285..2d1e7ee1021 100644--- a/src/metabase/collections/db.clj+++ b/src/metabase/collections/db.clj@@ -39,6 +39,11 @@[type :- :string](t2/select-one :model/Collection :type type))+(mu/defn collection-with-entity-id+ "The ::collections.schema/collection with `entity-id`, or nil."+ [entity-id :- :string]+ (t2/select-one :model/Collection :entity_id entity-id))+(mu/defn root-remote-synced-collection"The top-level remote-synced ::collections.schema/collection, or nil."[]diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex f17096de338..0a5e1563008 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -75,12 +75,17 @@"The value of the `:type` field for collections that only allow metrics.""library-metrics")+(def ^:constant library-dashboards-collection-type+ "The value of the `:type` field for collections that only allow dashboards and their questions."+ "library-dashboards")+(def library-collection-types"All library `:type` values — collections users curate as the canonical place to find content.Kept as a set so callers (e.g. search ranking) can enumerate them without hard-coding strings."#{library-collection-typelibrary-data-collection-type- library-metrics-collection-type})+ library-metrics-collection-type+ library-dashboards-collection-type})(def ^:constant tenant-specific-root-collection-type"The value of the `:type` field for root collections that belong to a single tenant"@@ -166,6 +171,11 @@[collection](= (:type collection) library-metrics-collection-type))+(defn- is-library-dashboards-collection?+ "Is this the Dashboards collection?"+ [collection]+ (= (:type collection) library-dashboards-collection-type))+(defn remote-synced-collection"Get the remote-synced collection if it exists."[]@@ -241,11 +251,40 @@(def ^:private library-metrics-entity-id"librarylibrarymetrics")+(def library-dashboards-entity-id+ "The entity_id for the Library's Dashboards collection."+ "librarylibrarydashbrd")+(def ^:private library-entity-id?"Returns true if the given entity ID is one of the hard-coded Library keys."#{library-entity-idlibrary-data-entity-id- library-metrics-entity-id})+ library-metrics-entity-id+ library-dashboards-entity-id})++(defn- grant-library-collection-permissions!+ "Gives All Users read and Data Analysts read-write access to the Library `collection`."+ [collection]+ (collections.db/delete-permissions-for-collection! (:id collection))+ (perms/grant-collection-read-permissions! (perms/all-users-group) collection)+ (perms/grant-collection-readwrite-permissions! (perms/data-analyst-group) collection))++(defn- insert-library-dashboards-collection!+ "Inserts the Dashboards collection under `library` and returns it."+ [library]+ (u/prog1 (collections.db/insert-collection! {:name "Dashboards"+ :type library-dashboards-collection-type+ :location (str "/" (:id library) "/")+ :entity_id library-dashboards-entity-id+ :is_remote_synced (boolean (:is_remote_synced library))})+ (grant-library-collection-permissions! <>)))++(defn ensure-library-dashboards-collection!+ "Creates the Library's Dashboards collection when the Library exists without one, returning the created collection."+ []+ (when-let [library (collections.db/collection-with-entity-id library-entity-id)]+ (when-not (collections.db/collection-with-entity-id library-dashboards-entity-id)+ (insert-library-dashboards-collection! library))))(defn create-library-collection!"Create the Library collection. Returns Created collection. Throws if it already exists."@@ -265,10 +304,8 @@:type library-metrics-collection-type:location base-location:entity_id library-metrics-entity-id})]- (doseq [col [library data metrics]]- (collections.db/delete-permissions-for-collection! (:id col))- (perms/grant-collection-read-permissions! (perms/all-users-group) col)- (perms/grant-collection-readwrite-permissions! (perms/data-analyst-group) col))+ (run! grant-library-collection-permissions! [library data metrics])+ (insert-library-dashboards-collection! library)library))(methodical/defmethod t2/table-name :model/Collection [_model] :collection)@@ -282,13 +319,13 @@:authority_level mi/transform-keyword})(defn library-root-collection?- "Is this one of the immutable system-created Library collections (root, data, or metrics)?+ "Is this one of the immutable system-created Library collections (root, data, metrics, or dashboards)?Returns false for user-created subcollections that inherit a library type."[collection](library-entity-id? (:entity_id collection)))(defn maybe-localize-system-collection-name- "If the collection is a system-defined collection (Trash, Library, Data, or Metrics), translate the `name`.+ "If the collection is a system-defined collection (Trash, Library, Data, Metrics, or Dashboards), translate the `name`.Only overrides names for the system-created library collections, not user-created subcollections.This is a public function because we can't rely on `define-after-select` in all circumstances, e.g. when searchingor listing collection items (where we do a direct DB query without `:model/Collection`)."@@ -304,7 +341,10 @@(assoc :name (tru "Data"))(and (is-library-metrics-collection? collection) (library-root-collection? collection))- (assoc :name (tru "Metrics"))))+ (assoc :name (tru "Metrics"))++ (and (is-library-dashboards-collection? collection) (library-root-collection? collection))+ (assoc :name (tru "Dashboards"))))(t2/define-after-select :model/Collection [collection](maybe-localize-system-collection-name collection))@@ -2507,9 +2547,13 @@"Return true if the given collection ID corresponds to a collection in the library."[collection-id](when collection-id- (pos-int? (collections.db/collection-count-of-types collection-id [library-collection-type- library-data-collection-type- library-metrics-collection-type]))))+ (pos-int? (collections.db/collection-count-of-types collection-id (vec library-collection-types)))))++(defn library-dashboards-collection?+ "Return true if the collection with `collection-id` only holds dashboards and their questions."+ [collection-id]+ (when collection-id+ (pos-int? (collections.db/collection-count-of-types collection-id [library-dashboards-collection-type]))))(defn collections-in-namespace"Return all collections in the given namespace."diff --git a/src/metabase/collections/schema.clj b/src/metabase/collections/schema.cljindex 43638984d68..7b0c6b43e51 100644--- a/src/metabase/collections/schema.clj+++ b/src/metabase/collections/schema.clj@@ -16,7 +16,8 @@"remote-synced""library""library-models"- "library-metrics"])+ "library-metrics"+ "library-dashboards"])(mr/def ::CardType [:enum "model" "question" "metric"])diff --git a/src/metabase/dashboards/write.clj b/src/metabase/dashboards/write.cljindex 53e2e32a204..029ace96757 100644--- a/src/metabase/dashboards/write.clj+++ b/src/metabase/dashboards/write.clj@@ -452,6 +452,14 @@:discard []}(filter :card_id dashcards))))+(defn- reference-metrics+ "Moves the metrics in `cards`' `:copy` to `:reference`, since a dashboards-only collection can't hold copies of them."+ [{:keys [copy] :as cards}]+ (let [metric? (fn [[_ card]] (= :metric (keyword (:type card))))]+ (-> cards+ (assoc :copy (into {} (remove metric?) copy))+ (update :reference merge (into {} (filter metric?) copy)))))+(defn- maybe-duplicate-cards"Takes a dashboard id, and duplicates the cards both on the dashboard's cards and dashcardseries as necessary.@@ -461,13 +469,17 @@If `deep-copy?` is `false`, doesn't copy any cards *except* for Dashboard Questions, which must be copied."[deep-copy? new-dashboard old-dashboard dest-coll-id](let [same-collection? (= (:collection_id old-dashboard) dest-coll-id)- {:keys [copy discard reference]} (cards-to-copy deep-copy? (:dashcards old-dashboard))]+ dashboards-only? (collections/library-dashboards-collection? dest-coll-id)+ {:keys [copy discard reference]} (cond-> (cards-to-copy deep-copy? (:dashcards old-dashboard))+ dashboards-only? reference-metrics)]{:copied (into {} (for [[id to-copy] copy][id (queries/create-card!(cond-> to-copytrue (assoc :collection_id dest-coll-id)same-collection? (update :name #(str % " - " (tru "Duplicate")))- (:dashboard_id to-copy) (assoc :dashboard_id (u/the-id new-dashboard)))+ (or (:dashboard_id to-copy)+ dashboards-only?) (-> (assoc :dashboard_id (u/the-id new-dashboard))+ (dissoc :collection_position)))@api/*current-user*;; creating cards from a transaction. wait until tx complete to signal eventtruediff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.cljindex 6b29b7a54f2..753e7ea6af2 100644--- a/src/metabase/dashboards_rest/api.clj+++ b/src/metabase/dashboards_rest/api.clj@@ -458,6 +458,14 @@:discard []}(filter :card_id dashcards))))+(defn- reference-metrics+ "Moves the metrics in `cards`' `:copy` to `:reference`, since a dashboards-only collection can't hold copies of them."+ [{:keys [copy] :as cards}]+ (let [metric? (fn [[_ card]] (= :metric (keyword (:type card))))]+ (-> cards+ (assoc :copy (into {} (remove metric?) copy))+ (update :reference merge (into {} (filter metric?) copy)))))+(defn- maybe-duplicate-cards"Takes a dashboard id, and duplicates the cards both on the dashboard's cards and dashcardseries as necessary.@@ -466,13 +474,17 @@If `deep-copy?` is `false`, doesn't copy any cards *except* for Dashboard Questions, which must be copied."[deep-copy? new-dashboard old-dashboard dest-coll-id](let [same-collection? (= (:collection_id old-dashboard) dest-coll-id)- {:keys [copy discard reference]} (cards-to-copy deep-copy? (:dashcards old-dashboard))]+ dashboards-only? (collections/library-dashboards-collection? dest-coll-id)+ {:keys [copy discard reference]} (cond-> (cards-to-copy deep-copy? (:dashcards old-dashboard))+ dashboards-only? reference-metrics)]{:copied (into {} (for [[id to-copy] copy][id (queries/create-card!(cond-> to-copytrue (assoc :collection_id dest-coll-id)same-collection? (update :name #(str % " - " (tru "Duplicate")))- (:dashboard_id to-copy) (assoc :dashboard_id (u/the-id new-dashboard)))+ (or (:dashboard_id to-copy)+ dashboards-only?) (-> (assoc :dashboard_id (u/the-id new-dashboard))+ (dissoc :collection_position)))@api/*current-user*;; creating cards from a transaction. wait until tx complete to signal eventtruediff --git a/src/metabase/permissions/db.clj b/src/metabase/permissions/db.cljindex 9b0d2312f26..432e8da7cda 100644--- a/src/metabase/permissions/db.clj+++ b/src/metabase/permissions/db.clj@@ -568,7 +568,7 @@(mu/defn library-collection-ids"The IDs of the library Collections."[]- (t2/select-pks-set :model/Collection :type [:in ["library" "library-data" "library-metrics"]]))+ (t2/select-pks-set :model/Collection :type [:in ["library" "library-data" "library-metrics" "library-dashboards"]]))(mu/defn namespace-clause"Honey SQL clause to filter `namespace-keyword` by `namespace-val`, also matching the audit-app and tenantdiff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 6265def27a5..8cdb2f357b1 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -861,6 +861,14 @@(cond->> (lib/normalize ::queries.schema/card card)(mu.fn/instrument-ns? *ns*) (mu.fn/validate-output {:fn-name `normalize-card} [:maybe ::queries.schema/card])))+(defn- library-content-type+ "The content type a Library collection checks `card` against, counting a question as a dashboard question when `dashboard-pending?`."+ [card dashboard-pending?]+ (if (and (= :question (keyword (:type card)))+ (or (:dashboard_id card) dashboard-pending?))+ :dashboard-question+ (:type card)))+(t2/define-before-insert :model/Card[card](u/prog1@@ -875,7 +883,7 @@pre-insertpopulate-query-fieldspublic-sharing/add-public-uuid-prefix)- (collection/check-allowed-content (:type <>) (:collection_id <>))))+ (collection/check-allowed-content (library-content-type <> mi/*deserializing?*) (:collection_id <>))))(t2/define-after-insert :model/Card[card]@@ -897,6 +905,13 @@(assoc card :collection_id (queries.db/dashboard-collection-id dashboard-id))card))+(defn- check-allowed-content+ "Checks that the Collection `card` ends up in allows it when `changes` touch its collection or dashboard."+ [card changes]+ (when (some #(contains? changes %) [:collection_id :dashboard_id])+ (let [card (apply-dashboard-question-updates card changes)]+ (collection/check-allowed-content (library-content-type card mi/*deserializing?*) (:collection_id card)))))+(mu/defn- populate-result-metadata :- [:map[:result_metadata {:optional true} [:maybe[:sequential@@ -934,7 +949,7 @@;; normalization preserving the instance's original.original (t2/original card)card (normalize-card card)]- (collection/check-allowed-content (:type card) (:collection_id changes))+ (check-allowed-content card changes)(-> card(dissoc :verified-result-metadata?)(migrate-schema-governed-columns original changes)@@ -1482,6 +1497,13 @@:else base)))+(defmethod serdes/load-one! "Card" [ingested maybe-local]+ (u/prog1 (serdes/default-load-one! ingested maybe-local)+ (collection/check-allowed-content+ (library-content-type <> (and (some? (:dashboard_id ingested))+ (contains? (::serdes/strip ingested) :dashboard_id)))+ (:collection_id <>))))+;; A data app's resource collection holds the saved questions and metric copies the app runs.(defmethod collection/allowed-namespaces :model/Card[_]diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.cljindex e049912c45b..92193978507 100644--- a/test/metabase/app_db/schema_migrations_test.clj+++ b/test/metabase/app_db/schema_migrations_test.clj@@ -3649,3 +3649,41 @@(migrate!)(is (= #{implicit-id} (t2/select-pks-set :action)))(is (= #{other-button} (t2/select-pks-set :report_dashboardcard :id [:in [http-button other-button]])))))))++(deftest add-library-dashboards-section-test+ (testing "v65.2026-10-06T16:00:00 through v65.2026-10-06T16:00:02: an existing Library gets a Dashboards section with its permissions"+ (impl/test-migrations ["v65.2026-10-06T16:00:00" "v65.2026-10-06T16:00:02"] [migrate!]+ (let [library-id (insert-legacy-library-collection! {:name "Library"+ :slug "library"+ :type "library"+ :entity_id "librarylibrarylibrary"})+ read-group (t2/insert-returning-pk! :permissions_group {:name (mt/random-name) :entity_id (u/generate-nano-id)})+ write-group (t2/insert-returning-pk! :permissions_group {:name (mt/random-name) :entity_id (u/generate-nano-id)})+ analyst-group (t2/select-one-pk :permissions_group :magic_group_type "data-analyst")+ library-perms (fn [group-id object perm-value]+ {:group_id group-id+ :object object+ :perm_type "perms/collection-access"+ :perm_value perm-value+ :collection_id library-id})]+ (t2/insert! :permissions [(library-perms read-group (format "/collection/%d/read/" library-id) "read")+ (library-perms write-group (format "/collection/%d/" library-id) "read-and-write")+ (library-perms analyst-group (format "/collection/%d/read/" library-id) "read")])+ (migrate!)+ (let [{dashboards-id :id :as dashboards} (t2/select-one :collection :entity_id "librarylibrarydashbrd")]+ (is (=? {:name "Dashboards"+ :type "library-dashboards"+ :location (str "/" library-id "/")}+ dashboards))+ (is (= #{[read-group (format "/collection/%d/read/" dashboards-id) "read"]+ [write-group (format "/collection/%d/" dashboards-id) "read-and-write"]+ [analyst-group (format "/collection/%d/" dashboards-id) "read-and-write"]}+ (into #{}+ (map (juxt :group_id :object :perm_value))+ (t2/select :permissions :collection_id dashboards-id)))))))))++(deftest add-library-dashboards-section-without-library-test+ (testing "v65.2026-10-06T16:00:00: no Dashboards section is created without a Library"+ (impl/test-migrations ["v65.2026-10-06T16:00:00" "v65.2026-10-06T16:00:02"] [migrate!]+ (migrate!)+ (is (not (t2/exists? :collection :entity_id "librarylibrarydashbrd"))))))diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.cljindex ecdac524430..c6c0945b83f 100644--- a/test/metabase/collections/models/collection_test.clj+++ b/test/metabase/collections/models/collection_test.clj@@ -3309,12 +3309,31 @@non-archived-dashnon-archived-card]))))))))+(deftest ensure-library-dashboards-collection-test+ (mt/with-empty-h2-app-db!+ (testing "Without a Library there is nothing to restore"+ (is (nil? (collection/ensure-library-dashboards-collection!))))+ (let [library (collection/create-library-collection!)]+ (testing "An existing Dashboards collection is kept"+ (is (nil? (collection/ensure-library-dashboards-collection!))))+ (testing "A missing Dashboards collection is recreated with the Library's permissions"+ (t2/delete! :model/Collection :type collection/library-dashboards-collection-type)+ (let [dashboards (collection/ensure-library-dashboards-collection!)]+ (is (=? {:name "Dashboards"+ :type collection/library-dashboards-collection-type+ :location (str "/" (:id library) "/")}+ dashboards))+ (binding [api/*current-user* (mt/user->id :rasta)+ api/*current-user-permissions-set* (-> :rasta mt/user->id perms/user-permissions-set atom)]+ (is (true? (mi/can-read? dashboards)))+ (is (false? (mi/can-write? dashboards)))))))))+(deftest create-library(mt/with-empty-h2-app-db!(testing "Can create a library if none exist"(let [library (collection/create-library-collection!)](is (= "Library" (:name library)))- (is (= ["Data" "Metrics"] (sort (map :name (collection/descendants library)))))+ (is (= ["Dashboards" "Data" "Metrics"] (sort (map :name (collection/descendants library)))))(testing "Only admins can write to the library, all users can read"(binding [api/*current-user* (mt/user->id :rasta)api/*current-user-permissions-set* (-> :rasta mt/user->id perms/user-permissions-set atom)]diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex 3d524948dc3..d2495060eff 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -635,15 +635,11 @@:entity_id @#'collection/library-metrics-entity-id))})lib-items (:data (mt/user-http-request :crowberto :get 200(str "collection/" (:id library) "/items")))]- (testing "System library children (Data, Metrics) have is_library_root true"- (doseq [item (filter :is_library_root lib-items)]- (is (contains? #{collection/library-data-collection-type- collection/library-metrics-collection-type}- (:type item)))))- (testing "Data and Metrics collections both marked as is_library_root"+ (testing "Data, Metrics, and Dashboards collections are all marked as is_library_root"(let [roots (filter :is_library_root lib-items)](is (= #{collection/library-data-collection-type- collection/library-metrics-collection-type}+ collection/library-metrics-collection-type+ collection/library-dashboards-collection-type}(set (map :type roots))))))(testing "User-created subcollections inside Data do NOT have is_library_root"(let [data-items (:data (mt/user-http-request :crowberto :get 200