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
Library empty state: expand Data, Metrics and SQL snippets (#68241)
Gabriel Moreno3f1ff1ba609f
diff --git a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.tsindex bbe94f5c15f..c1080bb9277 100644--- a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts@@ -135,4 +135,91 @@ describe("scenarios > data studio > library", () => {);});});++ describe("empty state", () => {+ it("should show empty states with interactions when sections are empty", () => {+ H.createLibrary();+ H.DataStudio.Library.visit();++ cy.log("Verify all sections are expanded");+ H.DataStudio.Library.collectionItem("Data").should("be.visible");+ H.DataStudio.Library.collectionItem("Metrics").should("be.visible");+ H.DataStudio.Library.collectionItem("SQL snippets").should("be.visible");++ cy.log("Verify Data section empty state");+ H.DataStudio.Library.libraryPage()+ .findByText("Cleaned, pre-transformed data sources ready for exploring")+ .should("be.visible");+ H.DataStudio.Library.libraryPage()+ .findByRole("button", { name: "Publish a table" })+ .should("be.visible");++ cy.log("Verify Metrics section empty state");+ H.DataStudio.Library.libraryPage()+ .findByText("Standardized calculations with known dimensions")+ .should("be.visible");+ H.DataStudio.Library.libraryPage()+ .findByRole("link", { name: "New metric" })+ .should("be.visible");++ cy.log("Verify SQL snippets section empty state");+ H.DataStudio.Library.libraryPage()+ .findByText("Reusable bits of code that save your time")+ .should("be.visible");+ H.DataStudio.Library.libraryPage()+ .findByRole("link", { name: "New snippet" })+ .should("be.visible");++ cy.log("Click on 'Publish a table' button and verify modal opens");+ H.DataStudio.Library.libraryPage()+ .findByRole("button", { name: "Publish a table" })+ .click();+ H.entityPickerModal().should("be.visible");+ H.entityPickerModalItem(3, "Orders").should("exist");+ H.entityPickerModal().button("Close").click();++ cy.log("Search for text and verify empty states are excluded");+ H.DataStudio.Library.libraryPage()+ .findByPlaceholderText("Search...")+ .type("Publish");+ H.DataStudio.Library.libraryPage()+ .findByText("Cleaned, pre-transformed data sources ready for exploring")+ .should("not.exist");+ });++ it("should hide empty states when items are added and keep empty sections expanded on navigation", () => {+ H.createLibrary();+ H.DataStudio.Library.visit();++ cy.log("Verify Data empty state is visible initially");+ H.DataStudio.Library.libraryPage()+ .findByText("Cleaned, pre-transformed data sources ready for exploring")+ .should("be.visible");++ cy.log("Publish a table via the +New menu");+ H.DataStudio.Library.newButton().click();+ H.popover().findByText("Publish a table").click();+ H.entityPickerModalItem(3, "Orders").click();+ H.entityPickerModal().button("Publish").click();++ cy.log("Navigate back to Library via breadcrumbs");+ H.DataStudio.breadcrumbs().findByRole("link", { name: "Data" }).click();++ cy.log("Verify Data section shows the table (empty state hidden)");+ H.DataStudio.Library.tableItem("Orders").should("be.visible");+ H.DataStudio.Library.libraryPage()+ .findByText("Cleaned, pre-transformed data sources ready for exploring")+ .should("not.exist");++ cy.log(+ "Verify Metrics and SQL snippets still show empty states (always expanded behavior)",+ );+ H.DataStudio.Library.libraryPage()+ .findByText("Standardized calculations with known dimensions")+ .should("be.visible");+ H.DataStudio.Library.libraryPage()+ .findByText("Reusable bits of code that save your time")+ .should("be.visible");+ });+ });});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/LibrarySectionLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/LibrarySectionLayout.tsxindex cf61026aa59..87293853499 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/LibrarySectionLayout.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/LibrarySectionLayout.tsx@@ -6,6 +6,7 @@ import _ from "underscore";import { useListCollectionsTreeQuery } from "metabase/api";import { isLibraryCollection } from "metabase/collections/utils";import DateTime from "metabase/common/components/DateTime";+import { ForwardRefLink } from "metabase/common/components/Link";import { useSetting } from "metabase/common/hooks";import { usePageTitle } from "metabase/hooks/use-page-title";import { useDispatch } from "metabase/lib/redux";@@ -13,11 +14,13 @@ import * as Urls from "metabase/lib/urls";import { PLUGIN_SNIPPET_FOLDERS } from "metabase/plugins";import { useRouter } from "metabase/router";import {+ Anchor,Card,EntityNameCell,Flex,Icon,Stack,+ Text,TextInput,TreeTable,type TreeTableColumnDef,@@ -34,15 +37,59 @@ import type { Collection, CollectionId } from "metabase-types/api";import { SectionLayout } from "../../components/SectionLayout";import { CreateMenu } from "./CreateMenu";+import { PublishTableModal } from "./PublishTableModal";import { RootSnippetsCollectionMenu } from "./RootSnippetsCollectionMenu";import {useBuildSnippetTree,useBuildTreeForCollection,useErrorHandling,} from "./hooks";-import { type TreeItem, isCollection } from "./types";+import {+ type EmptyStateData,+ type TreeItem,+ isCollection,+ isEmptyStateData,+} from "./types";import { getAccessibleCollection } from "./utils";+interface EmptyStateActionProps {+ data: EmptyStateData;+ onPublishTable: () => void;+}++function EmptyStateAction({ data, onPublishTable }: EmptyStateActionProps) {+ if (data.sectionType === "data") {+ return (+ <Anchor+ component="button"+ type="button"+ fz="inherit"+ onClick={(e) => {+ e.stopPropagation();+ onPublishTable();+ }}+ >+ {data.actionLabel}+ </Anchor>+ );+ }++ if (data.actionUrl) {+ return (+ <Anchor+ component={ForwardRefLink}+ to={data.actionUrl}+ fz="inherit"+ onClick={(e) => e.stopPropagation()}+ >+ {data.actionLabel}+ </Anchor>+ );+ }++ return null;+}+export function LibrarySectionLayout() {usePageTitle(t`Library`);const dispatch = useDispatch();@@ -53,6 +100,7 @@ export function LibrarySectionLayout() {const [permissionsCollectionId, setPermissionsCollectionId] =useState<CollectionId | null>(null);const [searchQuery, setSearchQuery] = useState("");+ const [isPublishTableModalOpen, setIsPublishTableModalOpen] = useState(false);const expandedIdsFromUrl = useMemo(() => {const rawIds = location.query?.expandedId;@@ -106,6 +154,9 @@ export function LibrarySectionLayout() {const handleItemSelect = useCallback((item: TreeItem) => {+ if (item.model === "empty-state" || isEmptyStateData(item.data)) {+ return;+ }const entityId = item.data.id as number;if (item.model === "metric") {dispatch(push(Urls.dataStudioMetric(entityId)));@@ -121,12 +172,16 @@ export function LibrarySectionLayout() {tree: tablesTree,isLoading: loadingTables,error: tablesError,- } = useBuildTreeForCollection(tableCollection);+ } = useBuildTreeForCollection(tableCollection, "data");const {tree: metricsTree,isLoading: loadingMetrics,error: metricsError,- } = useBuildTreeForCollection(metricCollection);+ } = useBuildTreeForCollection(+ metricCollection,+ "metrics",+ metricCollection?.id,+ );const {tree: snippetTree,isLoading: loadingSnippets,@@ -141,9 +196,42 @@ export function LibrarySectionLayout() {const isLoading = loadingTables || loadingMetrics || loadingSnippets;useErrorHandling(tablesError || metricsError || snippetsError);+ // Collections with only empty-state children should always be expanded+ // (even when navigating back via breadcrumbs which may collapse other sections)+ const alwaysExpandedIds = useMemo(() => {+ const ids: Record<string, boolean> = {};+ combinedTree.forEach((node) => {+ if (node.model === "collection" && node.children) {+ const hasOnlyEmptyState = node.children.every(+ (child) => child.model === "empty-state",+ );+ if (hasOnlyEmptyState) {+ ids[node.id] = true;+ }+ }+ });+ return ids;+ }, [combinedTree]);++ // Merge URL-based expansion with always-expanded empty sections+ const effectiveExpandedState = useMemo(() => {+ if (!expandedIdsFromUrl) {+ return true; // Expand all by default+ }+ return {+ ...expandedIdsFromUrl,+ ...alwaysExpandedIds,+ };+ }, [expandedIdsFromUrl, alwaysExpandedIds]);+const libraryHasContent = useMemo(() =>- combinedTree.some((node) => node.children && node.children.length > 0),+ combinedTree.some(+ (node) =>+ node.children &&+ node.children.length > 0 &&+ node.children.some((child) => child.model !== "empty-state"),+ ),[combinedTree],);@@ -155,13 +243,31 @@ export function LibrarySectionLayout() {enableSorting: true,accessorKey: "name",minWidth: 200,- cell: ({ row }) => (- <EntityNameCell- data-testid={`${row.original.model}-name`}- icon={row.original.icon}- name={row.original.name}- />- ),+ cell: ({ row }) => {+ const { data } = row.original;++ if (isEmptyStateData(data)) {+ return (+ <Flex align="center" gap="0.25rem" data-testid="empty-state-row">+ <Text c="text-tertiary" fz="inherit">+ {data.description}+ </Text>+ <EmptyStateAction+ data={data}+ onPublishTable={() => setIsPublishTableModalOpen(true)}+ />+ </Flex>+ );+ }++ return (+ <EntityNameCell+ data-testid={`${row.original.model}-name`}+ icon={row.original.icon}+ name={row.original.name}+ />+ );+ },},{id: "updatedAt",@@ -171,7 +277,10 @@ export function LibrarySectionLayout() {sortingFn: "datetime",width: "auto",widthPadding: 20,- cell: ({ getValue }) => {+ cell: ({ row, getValue }) => {+ if (row.original.model === "empty-state") {+ return null;+ }const dateValue = getValue() as string | undefined;return dateValue ? <DateTime value={dateValue} /> : null;},@@ -181,6 +290,9 @@ export function LibrarySectionLayout() {width: 48,cell: ({ row }) => {const { data } = row.original;+ if (isEmptyStateData(data)) {+ return null;+ }if (isCollection(data) &&data.model === "collection" &&@@ -207,7 +319,7 @@ export function LibrarySectionLayout() {},},],- [],+ [setIsPublishTableModalOpen],);const handleRowActivate = useCallback(@@ -224,8 +336,9 @@ export function LibrarySectionLayout() {getNodeId: (node) => node.id,globalFilter: searchQuery,onGlobalFilterChange: setSearchQuery,- isFilterable: (node) => node.model !== "collection",- defaultExpanded: expandedIdsFromUrl ?? true,+ isFilterable: (node) =>+ node.model !== "collection" && node.model !== "empty-state",+ defaultExpanded: effectiveExpandedState,onRowActivate: handleRowActivate,});@@ -277,6 +390,9 @@ export function LibrarySectionLayout() {emptyMessage ? <ListEmptyState label={emptyMessage} /> : null}onRowClick={(row) => {+ if (row.original.model === "empty-state") {+ return;+ }if (row.getCanExpand()) {row.toggleExpanded();} else {@@ -307,6 +423,11 @@ export function LibrarySectionLayout() {dispatch(goBack());}}/>+ <PublishTableModal+ opened={isPublishTableModalOpen}+ onClose={() => setIsPublishTableModalOpen(false)}+ onPublished={() => setIsPublishTableModalOpen(false)}+ /></>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/hooks.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/hooks.tsindex 3f0a2eb1e77..165c498cdbd 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/hooks.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/hooks.ts@@ -11,13 +11,15 @@ import {import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";import { getIcon } from "metabase/lib/icon";import { useMetadataToasts } from "metabase/metadata/hooks";-import type { Collection } from "metabase-types/api";+import type { Collection, CollectionId } from "metabase-types/api";-import type { TreeItem } from "./types";-import { buildSnippetTree } from "./utils";+import type { LibrarySectionType, TreeItem } from "./types";+import { buildSnippetTree, createEmptyStateItem } from "./utils";export const useBuildTreeForCollection = (- collection?: Collection,+ collection: Collection | undefined,+ sectionType: LibrarySectionType,+ metricCollectionId?: CollectionId,): {isLoading: boolean;tree: TreeItem[];@@ -39,6 +41,19 @@ export const useBuildTreeForCollection = (error,};}++ const hasItems = items.data.length > 0;+ const children: TreeItem[] = hasItems+ ? items.data.map((item) => ({+ name: item.name,+ updatedAt: item["last-edit-info"]?.timestamp,+ icon: getIcon({ model: item.model }).name,+ data: item,+ id: `${item.model}:${item.id}`,+ model: item.model,+ }))+ : [createEmptyStateItem(sectionType, metricCollectionId)];+return {isLoading,error,@@ -49,18 +64,11 @@ export const useBuildTreeForCollection = (icon: getIcon({ ...collection, model: "collection" }).name,data: { ...collection, model: "collection" },model: "collection",- children: items.data.map((item) => ({- name: item.name,- updatedAt: item["last-edit-info"]?.timestamp,- icon: getIcon({ model: item.model }).name,- data: item,- id: `${item.model}:${item.id}`,- model: item.model,- })),+ children,},],};- }, [isLoading, items, collection, error]);+ }, [isLoading, items, collection, error, sectionType, metricCollectionId]);};export const useBuildSnippetTree = (): {diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/types.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/types.tsindex 31f85a4ddcf..f5d2d08fd3c 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/types.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/types.ts@@ -6,16 +6,30 @@ import type {CollectionNamespace,} from "metabase-types/api";+export type LibrarySectionType = "data" | "metrics" | "snippets";++export type EmptyStateData = {+ model: "empty-state";+ sectionType: LibrarySectionType;+ description: string;+ actionLabel: string;+ actionUrl?: string;+};++export type TreeItemModel = CollectionItemModel | "empty-state";+export type TreeItem = {id: string;name: string;icon: IconName;updatedAt?: string;- model: CollectionItemModel;- data: (Collection | Omit<CollectionItem, "getUrl">) & {- model: CollectionItem["model"];- namespace?: CollectionNamespace | null;- };+ model: TreeItemModel;+ data:+ | ((Collection | Omit<CollectionItem, "getUrl">) & {+ model: CollectionItem["model"];+ namespace?: CollectionNamespace | null;+ })+ | EmptyStateData;children?: TreeItem[];};@@ -24,3 +38,9 @@ export const isCollection = (): c is Collection => {return Object.keys(c).includes("namespace");};++export const isEmptyStateData = (+ data: TreeItem["data"],+): data is EmptyStateData => {+ return data.model === "empty-state";+};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/utils.tsindex 5c8ba4b0089..9019324d17c 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/LibrarySectionLayout/utils.ts@@ -1,13 +1,15 @@import { t } from "ttag";import { isRootCollection } from "metabase/collections/utils";+import * as Urls from "metabase/lib/urls";import type {Collection,+ CollectionId,CollectionType,NativeQuerySnippet,} from "metabase-types/api";-import type { TreeItem } from "./types";+import type { LibrarySectionType, TreeItem } from "./types";function createSnippetNode(snippet: NativeQuerySnippet): TreeItem {return {@@ -71,7 +73,13 @@ export function buildSnippetTree(activeSnippets,);- return [{ ...rootNode, name: t`SQL snippets` }];+ // If the root has no children (no snippets or subfolders), add an empty state+ const hasContent = activeSnippets.length > 0 || nonRootCollections.length > 0;+ const children = hasContent+ ? rootNode.children+ : [createEmptyStateItem("snippets")];++ return [{ ...rootNode, name: t`SQL snippets`, children }];}export function getWritableCollection(@@ -105,3 +113,63 @@ export function getAccessibleCollection(}return collection.can_write ? collection : undefined;}++type EmptyStateConfig = {+ sectionType: LibrarySectionType;+ description: string;+ actionLabel: string;+ actionUrl?: string;+};++function getEmptyStateConfig(+ sectionType: LibrarySectionType,+): Omit<EmptyStateConfig, "sectionType" | "actionUrl"> {+ const config: Record<+ LibrarySectionType,+ Omit<EmptyStateConfig, "sectionType" | "actionUrl">+ > = {+ data: {+ description: t`Cleaned, pre-transformed data sources ready for exploring`,+ actionLabel: t`Publish a table`,+ },+ metrics: {+ description: t`Standardized calculations with known dimensions`,+ actionLabel: t`New metric`,+ },+ snippets: {+ description: t`Reusable bits of code that save your time`,+ actionLabel: t`New snippet`,+ },+ };++ return config[sectionType];+}++export function createEmptyStateItem(+ sectionType: LibrarySectionType,+ metricCollectionId?: CollectionId,+): TreeItem {+ const config = getEmptyStateConfig(sectionType);++ let actionUrl: string | undefined;+ if (sectionType === "metrics" && metricCollectionId) {+ actionUrl = Urls.newDataStudioMetric({ collectionId: metricCollectionId });+ } else if (sectionType === "snippets") {+ actionUrl = Urls.newDataStudioSnippet();+ }+ // "data" section opens a modal, so no actionUrl++ return {+ id: `empty-state:${sectionType}`,+ name: "",+ icon: "empty",+ model: "empty-state",+ data: {+ model: "empty-state",+ sectionType,+ description: config.description,+ actionLabel: config.actionLabel,+ actionUrl,+ },+ };+}