Skip to content

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

Add virtualized grid to collection list view for tenants (#67958)

Phoomparin Manoa46764dd85ac
diff --git a/e2e/test/scenarios/collections/tenant-collections-list.cy.spec.ts b/e2e/test/scenarios/collections/tenant-collections-list.cy.spec.ts
new file mode 100644
index 00000000000..d7fea023c0b
--- /dev/null
+++ b/e2e/test/scenarios/collections/tenant-collections-list.cy.spec.ts
@@ -0,0 +1,68 @@
+const { H } = cy;
+
+interface Tenant {
+ name: string;
+ slug: string;
+}
+
+describe("scenarios > collections > tenant collections list", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ cy.request("PUT", "/api/setting", { "use-tenants": true });
+ });
+
+ it("should display tenant collections", () => {
+ const tenants: Tenant[] = Array.from({ length: 3 }, (_, i) => ({
+ name: `Tenant ${String(i + 1).padStart(2, "0")}`,
+ slug: `tenant-${String(i + 1).padStart(2, "0")}`,
+ }));
+
+ cy.log("creating multiple tenants");
+ tenants.forEach((tenant) => cy.request("POST", "/api/ee/tenant", tenant));
+
+ cy.visit("/collection/tenant-specific");
+
+ cy.log("all tenant collections are displayed");
+ H.main().within(() => {
+ tenants.forEach((tenant) => {
+ cy.findByText(tenant.name).should("be.visible");
+ });
+ });
+
+ cy.log("all collections should be clickable links");
+ cy.findAllByRole("link").should("have.length.at.least", tenants.length);
+
+ cy.log("can navigate to tenant collection");
+ H.main().findByText("Tenant 01").click();
+ cy.url().should("include", "/collection/");
+ cy.url().should("not.include", "/collection/tenant-specific");
+ H.main().findByText("Tenant collection: Tenant 01").should("be.visible");
+ });
+
+ it("does not show deactivated tenants", () => {
+ cy.log("create active tenant");
+ cy.request("POST", "/api/ee/tenant", {
+ name: "Active Tenant",
+ slug: "active-tenant",
+ });
+
+ cy.log("create tenant to be deactivated");
+ cy.request("POST", "/api/ee/tenant", {
+ name: "Deactivated Tenant",
+ slug: "deactivated-tenant",
+ }).then(({ body: tenant }) => {
+ cy.log("deactivate the tenant");
+ cy.request("PUT", `/api/ee/tenant/${tenant.id}`, { is_active: false });
+ });
+
+ cy.visit("/collection/tenant-specific");
+
+ cy.log("active tenant should be visible");
+ H.main().findByText("Active Tenant").should("be.visible");
+
+ cy.log("deactivated tenant should not be visible");
+ H.main().findByText("Deactivated Tenant").should("not.exist");
+ });
+});
diff --git a/frontend/src/metabase/common/components/CollectionListView/CollectionListView.module.css b/frontend/src/metabase/common/components/CollectionListView/CollectionListView.module.css
index db967ca6702..fbe701928c9 100644
--- a/frontend/src/metabase/common/components/CollectionListView/CollectionListView.module.css
+++ b/frontend/src/metabase/common/components/CollectionListView/CollectionListView.module.css
@@ -4,6 +4,7 @@
.card {
color: var(--mb-color-text-secondary);
+ cursor: pointer;
}
.card:hover {
diff --git a/frontend/src/metabase/common/components/CollectionListView/CollectionListView.tsx b/frontend/src/metabase/common/components/CollectionListView/CollectionListView.tsx
index 020bb6942cb..dde0baeb367 100644
--- a/frontend/src/metabase/common/components/CollectionListView/CollectionListView.tsx
+++ b/frontend/src/metabase/common/components/CollectionListView/CollectionListView.tsx
@@ -1,9 +1,8 @@
import type { CSSProperties, ComponentProps, Key, ReactNode } from "react";
import { BrowserCrumbs } from "metabase/common/components/BrowserCrumbs";
-import { Grid, GridItem } from "metabase/common/components/Grid";
import Link from "metabase/common/components/Link";
-import { PaginationControls } from "metabase/common/components/PaginationControls";
+import { VirtualizedGrid } from "metabase/common/components/VirtualizedGrid";
import CS from "metabase/css/core/index.css";
import {
Box,
@@ -27,22 +26,12 @@ type CollectionListItem = {
link: string;
};
-type PaginationProps = {
- page: number;
- pageSize: number;
- total?: number;
- itemsLength: number;
- onNextPage: () => void;
- onPreviousPage: () => void;
-};
-
type CollectionListViewProps = {
crumbs: Crumb;
loading?: boolean;
items: CollectionListItem[];
containerStyle?: CSSProperties;
containerClassName?: string;
- pagination?: PaginationProps;
};
export const CollectionListView = ({
@@ -51,8 +40,21 @@ export const CollectionListView = ({
items,
containerStyle,
containerClassName,
- pagination,
}: CollectionListViewProps) => {
+ const renderItem = (item: CollectionListItem) => (
+ <Link to={item.link}>
+ <Card shadow="none" withBorder className={styles.card}>
+ <Group gap="xs">
+ <Icon name={item.icon} className={CS.mr1} size={18} />
+
+ <Title order={6} component="h3">
+ {item.name}
+ </Title>
+ </Group>
+ </Card>
+ </Link>
+ );
+
return (
<Flex
direction="column"
@@ -64,51 +66,21 @@ export const CollectionListView = ({
<Box py="1rem">
<BrowserCrumbs crumbs={crumbs} />
</Box>
- <Box style={{ flexGrow: 1, overflowY: "auto" }} pr="0.5rem">
+ <Box style={{ flexGrow: 1, overflowY: "hidden" }} pr="0.5rem">
{loading ? (
<Flex justify="center" align="center" h="100%">
<Loader size="lg" />
</Flex>
) : (
- <Grid>
- {items.map((item) => (
- <GridItem
- key={item.key}
- role="list-item"
- className={styles.listGridItem}
- >
- <Link to={item.link}>
- <Card
- shadow="none"
- withBorder
- className={styles.card}
- style={{ cursor: "pointer" }}
- >
- <Group gap="xs">
- <Icon name={item.icon} className={CS.mr1} size={18} />
- <Title order={6} component="h3">
- {item.name}
- </Title>
- </Group>
- </Card>
- </Link>
- </GridItem>
- ))}
- </Grid>
+ <VirtualizedGrid
+ items={items}
+ keyExtractor={(item) => item.key}
+ renderItem={renderItem}
+ columnsPerRow={{ xs: 1, sm: 2, md: 3, lg: 4, xl: 4 }}
+ estimatedRowHeight={80}
+ />
)}
</Box>
- {pagination && (
- <Flex justify="end" className={CS.syncStatusAwarePagination}>
- <PaginationControls
- page={pagination.page}
- pageSize={pagination.pageSize}
- total={pagination.total}
- itemsLength={pagination.itemsLength}
- onNextPage={pagination.onNextPage}
- onPreviousPage={pagination.onPreviousPage}
- />
- </Flex>
- )}
</Flex>
);
};
diff --git a/frontend/src/metabase/common/components/UserCollectionList.tsx b/frontend/src/metabase/common/components/UserCollectionList.tsx
index 40515f7680e..6316fc18842 100644
--- a/frontend/src/metabase/common/components/UserCollectionList.tsx
+++ b/frontend/src/metabase/common/components/UserCollectionList.tsx
@@ -1,9 +1,5 @@
-import {
- STANDARD_USER_LIST_PAGE_SIZE as PAGE_SIZE,
- useListUsersQuery,
-} from "metabase/api";
+import { useListUsersQuery } from "metabase/api";
import { CollectionListView } from "metabase/common/components/CollectionListView";
-import { usePagination } from "metabase/common/hooks/use-pagination";
import {
PERSONAL_COLLECTIONS,
ROOT_COLLECTION,
@@ -12,15 +8,9 @@ import * as Urls from "metabase/lib/urls";
import type { IconName } from "metabase/ui";
export const UserCollectionList = () => {
- const { page, handleNextPage, handlePreviousPage } = usePagination();
-
- const { data, isLoading } = useListUsersQuery({
- limit: PAGE_SIZE,
- offset: PAGE_SIZE * page,
- });
+ const { data, isLoading } = useListUsersQuery({});
const users = data?.data ?? [];
- const total = data?.total;
const crumbs = [
{
@@ -40,18 +30,6 @@ export const UserCollectionList = () => {
}));
return (
- <CollectionListView
- crumbs={crumbs}
- loading={isLoading}
- items={items}
- pagination={{
- page,
- pageSize: PAGE_SIZE,
- total,
- itemsLength: PAGE_SIZE,
- onNextPage: handleNextPage,
- onPreviousPage: handlePreviousPage,
- }}
- />
+ <CollectionListView crumbs={crumbs} loading={isLoading} items={items} />
);
};
diff --git a/frontend/src/metabase/common/components/UserCollectionList.unit.spec.tsx b/frontend/src/metabase/common/components/UserCollectionList.unit.spec.tsx
index a6853d6fa3e..e1470b592f7 100644
--- a/frontend/src/metabase/common/components/UserCollectionList.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/UserCollectionList.unit.spec.tsx
@@ -1,7 +1,10 @@
-import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
-import { renderWithProviders, screen } from "__support__/ui";
+import {
+ mockGetBoundingClientRect,
+ renderWithProviders,
+ screen,
+} from "__support__/ui";
import { createMockUser } from "metabase-types/api/mocks";
import { UserCollectionList } from "./UserCollectionList";
@@ -15,31 +18,29 @@ const MockUsers = new Array(100).fill(0).map((_, index) =>
);
const setup = () => {
- fetchMock.get("path:/api/user", (call) => {
- const params = new URL(call.url).searchParams;
- const limit = parseInt(params.get("limit") ?? "0");
- const offset = parseInt(params.get("offset") ?? "0");
- return { data: MockUsers.slice(offset, offset + limit) };
- });
+ fetchMock.get("path:/api/user", { data: MockUsers });
+
renderWithProviders(<UserCollectionList />);
};
describe("UserCollectionList", () => {
- it("should show pages of users", async () => {
- setup();
-
- expect(await screen.findByText("big boi 0")).toBeInTheDocument();
- expect(await screen.findAllByRole("list-item")).toHaveLength(27);
-
- expect(await screen.findByText("1 - 27")).toBeInTheDocument();
+ beforeEach(() => {
+ mockGetBoundingClientRect();
+ });
- expect(await screen.findByTestId("previous-page-btn")).toBeDisabled();
- await userEvent.click(await screen.findByTestId("next-page-btn"));
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
- expect(await screen.findByText("28 - 54")).toBeInTheDocument();
+ it("should show virtualized list of users", async () => {
+ setup();
- expect(await screen.findByTestId("previous-page-btn")).toBeEnabled();
+ // First items should be visible
+ expect(await screen.findByText("big boi 0")).toBeInTheDocument();
+ expect(await screen.findByText("big boi 1")).toBeInTheDocument();
- expect(await screen.findByText("big boi 29")).toBeInTheDocument();
+ // Items far down should not be rendered due to virtualization
+ expect(screen.queryByText("big boi 98")).not.toBeInTheDocument();
+ expect(screen.queryByText("big boi 99")).not.toBeInTheDocument();
});
});
diff --git a/frontend/src/metabase/common/components/VirtualizedGrid/VirtualizedGrid.tsx b/frontend/src/metabase/common/components/VirtualizedGrid/VirtualizedGrid.tsx
new file mode 100644
index 00000000000..ad8e699235f
--- /dev/null
+++ b/frontend/src/metabase/common/components/VirtualizedGrid/VirtualizedGrid.tsx
@@ -0,0 +1,87 @@
+import { useVirtualizer } from "@tanstack/react-virtual";
+import type { Key, ReactNode } from "react";
+import { useMemo, useRef } from "react";
+import _ from "underscore";
+
+import { Box, type BoxProps, Grid, useMatches } from "metabase/ui";
+import type { BreakpointName } from "metabase/ui/theme";
+
+type VirtualizedGridProps<T> = {
+ items: T[];
+ keyExtractor: (item: T) => Key;
+ renderItem: (item: T) => ReactNode;
+ columnsPerRow: Record<BreakpointName, number>;
+ estimatedRowHeight: number;
+ overscan?: number;
+} & Omit<BoxProps, "children">;
+
+export const VirtualizedGrid = <T,>({
+ items,
+ keyExtractor,
+ renderItem,
+ columnsPerRow,
+ estimatedRowHeight,
+ overscan = 5,
+ ...boxProps
+}: VirtualizedGridProps<T>) => {
+ const parentRef = useRef<HTMLDivElement>(null);
+
+ // Use Mantine's useMatches to get the current column count based on breakpoint
+ const currentColumns = useMatches(
+ {
+ base: columnsPerRow.xs,
+ sm: columnsPerRow.sm,
+ md: columnsPerRow.md,
+ lg: columnsPerRow.lg,
+ xl: columnsPerRow.xl,
+ },
+ { getInitialValueInEffect: false },
+ );
+
+ // Group items into rows based on current columns
+ const rows = useMemo(
+ () => _.chunk(items, currentColumns),
+ [items, currentColumns],
+ );
+
+ const virtualizer = useVirtualizer({
+ count: rows.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => estimatedRowHeight,
+ overscan,
+ });
+
+ const virtualRows = virtualizer.getVirtualItems();
+
+ // Calculate span for current breakpoint
+ const currentSpan = 12 / currentColumns;
+
+ return (
+ <Box ref={parentRef} h="100%" style={{ overflowY: "auto" }} {...boxProps}>
+ <Box h={virtualizer.getTotalSize()} pos="relative">
+ {virtualRows.map((virtualRow) => {
+ const rowItems = rows[virtualRow.index];
+
+ return (
+ <Box
+ key={virtualRow.key}
+ pos="absolute"
+ top={0}
+ left={0}
+ w="100%"
+ style={{ transform: `translateY(${virtualRow.start}px)` }}
+ >
+ <Grid gutter="md">
+ {rowItems.map((item) => (
+ <Grid.Col key={keyExtractor(item)} span={currentSpan}>
+ {renderItem(item)}
+ </Grid.Col>
+ ))}
+ </Grid>
+ </Box>
+ );
+ })}
+ </Box>
+ </Box>
+ );
+};
diff --git a/frontend/src/metabase/common/components/VirtualizedGrid/VirtualizedGrid.unit.spec.tsx b/frontend/src/metabase/common/components/VirtualizedGrid/VirtualizedGrid.unit.spec.tsx
new file mode 100644
index 00000000000..ce83b067160
--- /dev/null
+++ b/frontend/src/metabase/common/components/VirtualizedGrid/VirtualizedGrid.unit.spec.tsx
@@ -0,0 +1,62 @@
+import { mockGetBoundingClientRect, render, screen } from "__support__/ui";
+
+import { VirtualizedGrid } from "./VirtualizedGrid";
+
+describe("VirtualizedGrid", () => {
+ beforeEach(() => {
+ // Same pattern as metabase/common/components/VirtualizedList/VariableHeightVirtualizedList.unit.spec.tsx
+ mockGetBoundingClientRect();
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("should chunk items into grid rows based on columnsPerRow", () => {
+ const items = Array.from({ length: 10 }, (_, i) => ({ id: i }));
+
+ const { container } = render(
+ <VirtualizedGrid
+ items={items}
+ keyExtractor={(item) => item.id}
+ renderItem={(item) => <div>Item {item.id}</div>}
+ columnsPerRow={{ xs: 4, sm: 4, md: 4, lg: 4, xl: 4 }}
+ estimatedRowHeight={80}
+ />,
+ );
+
+ // Need to use container to test actual DOM structure/chunking behavior
+ // eslint-disable-next-line testing-library/no-container
+ const rows = container.querySelectorAll('[style*="translateY"]');
+
+ // With 10 items and 4 columns per row, we should have 3 rows
+ expect(rows.length).toBe(3);
+
+ // Each item should be wrapped in a Grid.Col (has class starting with m_)
+ // eslint-disable-next-line testing-library/no-container
+ const gridCols = container.querySelectorAll('[class*="m_"]');
+ expect(gridCols.length).toBe(16);
+ });
+
+ it("should not render children outside the bounding client rect", () => {
+ const items = Array.from({ length: 100 }, (_, i) => ({ id: i }));
+
+ render(
+ <VirtualizedGrid
+ items={items}
+ keyExtractor={(item) => item.id}
+ renderItem={(item) => <div>Item {item.id}</div>}
+ columnsPerRow={{ xs: 4, sm: 4, md: 4, lg: 4, xl: 4 }}
+ estimatedRowHeight={80}
+ />,
+ );
+
+ // First items should be visible
+ expect(screen.getByText("Item 0")).toBeInTheDocument();
+ expect(screen.getByText("Item 1")).toBeInTheDocument();
+
+ // Items far down should not be rendered due to virtualization
+ expect(screen.queryByText("Item 98")).not.toBeInTheDocument();
+ expect(screen.queryByText("Item 99")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/common/components/VirtualizedGrid/index.ts b/frontend/src/metabase/common/components/VirtualizedGrid/index.ts
new file mode 100644
index 00000000000..0146d2a4210
--- /dev/null
+++ b/frontend/src/metabase/common/components/VirtualizedGrid/index.ts
@@ -0,0 +1 @@
+export { VirtualizedGrid } from "./VirtualizedGrid";
diff --git a/frontend/src/metabase/ui/index.ts b/frontend/src/metabase/ui/index.ts
index e92a0dd538e..de179c5018d 100644
--- a/frontend/src/metabase/ui/index.ts
+++ b/frontend/src/metabase/ui/index.ts
@@ -1,4 +1,4 @@
-export { rem, useCombobox, useMantineTheme } from "@mantine/core";
+export { rem, useCombobox, useMantineTheme, useMatches } from "@mantine/core";
export type {
ComboboxStore,
FloatingPosition,