feat: implement standard pagination for org member list (#19802)

* feat: implement standard pagination for org member list

* fix type error

* i18n for pagination

* add paginationMode

* apply the change to PlatformManagedUsersTable

* replace useInfiniteQuery with useQuery

* fix type error

* fix type error

* fix type error

* fix type error

* update comment

* remove optimistic update

* minor changes

* update usage on nuqs

---------

Co-authored-by: Benny Joo <[email protected]>
This commit is contained in:
Eunjae LeeandBenny Joo authored and GitHub committed 2025-03-11 09:55:41 +01:00
1 parent 861e3aa24f
commit 7eee2728a2
24 files changed
+403 -388

No files matched your search

@@ -2,12 +2,12 @@
import type { Row } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
import type { Table as ReactTableType, Header } from "@tanstack/react-table";
import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual";
import type { Table as ReactTableType, Header, HeaderGroup } from "@tanstack/react-table";
import { useVirtualizer, type Virtualizer, type VirtualItem } from "@tanstack/react-virtual";
// eslint-disable-next-line no-restricted-imports
import kebabCase from "lodash/kebabCase";
import { usePathname } from "next/navigation";
import { useEffect, useState, memo } from "react";
import { useEffect, useState, memo, useMemo } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import {
@@ -30,7 +30,7 @@ import classNames from "@calcom/ui/classNames";
import { useColumnSizingVars } from "../hooks";
import { usePersistentColumnResizing } from "../lib/resizing";
export type DataTableProps<TData, TValue> = {
export type DataTableProps<TData> = {
table: ReactTableType<TData>;
tableContainerRef: React.RefObject<HTMLDivElement>;
isPending?: boolean;
@@ -46,9 +46,10 @@ export type DataTableProps<TData, TValue> = {
enableColumnResizing?: boolean;
className?: string;
containerClassName?: string;
paginationMode?: "infinite" | "standard";
};
export function DataTable<TData, TValue>({
export function DataTable<TData>({
table,
tableContainerRef,
isPending,
@@ -63,19 +64,18 @@ export function DataTable<TData, TValue>({
bodyTestId,
className,
containerClassName,
paginationMode = "infinite",
...rest
}: DataTableProps<TData, TValue> & React.ComponentPropsWithoutRef<"div">) {
}: DataTableProps<TData> & React.ComponentPropsWithoutRef<"div">) {
const pathname = usePathname() as string | null;
const identifier = _identifier ?? pathname ?? undefined;
const { rows } = table.getRowModel();
// https://stackblitz.com/github/tanstack/table/tree/main/examples/react/virtualized-infinite-scrolling
const rowVirtualizer = useVirtualizer({
count: rows.length,
estimateSize: () => 100,
getScrollElement: () => tableContainerRef.current,
// measure dynamic row height, except in firefox because it measures table border height incorrectly
measureElement:
typeof window !== "undefined" && navigator.userAgent.indexOf("Firefox") === -1
? (element) => element?.getBoundingClientRect().height
@@ -83,8 +83,10 @@ export function DataTable<TData, TValue>({
overscan: 10,
});
const virtualItemsCount = rowVirtualizer.getVirtualItems().length;
useEffect(() => {
if (rowVirtualizer.getVirtualItems().length >= rows.length && tableContainerRef.current) {
if (paginationMode === "infinite" && virtualItemsCount >= rows.length && tableContainerRef.current) {
const target = tableContainerRef.current;
// Right after the last row is rendered, tableContainer's scrollHeight is
// temporarily larger than the actual height of the table, so we need to
@@ -94,7 +96,7 @@ export function DataTable<TData, TValue>({
onScroll?.({ target });
}, 100);
}
}, [rowVirtualizer.getVirtualItems().length, rows.length, tableContainerRef.current]);
}, [virtualItemsCount, rows.length, tableContainerRef.current, paginationMode, onScroll]);
const columnSizingVars = useColumnSizingVars({ table });
@@ -131,8 +133,9 @@ export function DataTable<TData, TValue>({
ref={tableContainerRef}
onScroll={onScroll}
className={classNames(
"relative h-[80dvh] overflow-auto", // Set a fixed height for the container
"relative overflow-auto",
"scrollbar-thin border-subtle relative rounded-md border",
paginationMode === "infinite" && "h-[80dvh]", // Set a fixed height for the container
containerClassName
)}
style={{ gridArea: "body" }}>
@@ -144,9 +147,9 @@ export function DataTable<TData, TValue>({
}}>
{!hideHeader && (
<TableHeader className="sticky top-0 z-10">
{table.getHeaderGroups().map((headerGroup) => (
{table.getHeaderGroups().map((headerGroup: HeaderGroup<TData>) => (
<TableRow key={headerGroup.id} className="hover:bg-subtle flex w-full">
{headerGroup.headers.map((header) => {
{headerGroup.headers.map((header: Header<TData, unknown>) => {
const { column } = header;
return (
<TableHead
@@ -190,6 +193,7 @@ export function DataTable<TData, TValue>({
variant={variant}
isPending={isPending}
onRowMouseclick={onRowMouseclick}
paginationMode={paginationMode}
/>
) : (
<DataTableBody
@@ -200,6 +204,7 @@ export function DataTable<TData, TValue>({
variant={variant}
isPending={isPending}
onRowMouseclick={onRowMouseclick}
paginationMode={paginationMode}
/>
)}
</TableNew>
@@ -218,7 +223,8 @@ const MemoizedTableBody = memo(
prev.testId === next.testId &&
prev.variant === next.variant &&
prev.isPending === next.isPending &&
prev.onRowMouseclick === next.onRowMouseclick
prev.onRowMouseclick === next.onRowMouseclick &&
prev.paginationMode === next.paginationMode
) as typeof DataTableBody;
type DataTableBodyProps<TData> = {
@@ -229,6 +235,12 @@ type DataTableBodyProps<TData> = {
variant?: "default" | "compact";
isPending?: boolean;
onRowMouseclick?: (row: Row<TData>) => void;
paginationMode?: "infinite" | "standard";
};
type RowToRender<TData> = {
row: Row<TData>;
virtualItem?: VirtualItem;
};
function DataTableBody<TData>({
@@ -239,60 +251,75 @@ function DataTableBody<TData>({
variant,
isPending,
onRowMouseclick,
}: DataTableBodyProps<TData>) {
const virtualRows = rowVirtualizer.getVirtualItems();
return (
<TableBody
className="relative grid"
data-testid={testId}
style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
{virtualRows && !isPending ? (
virtualRows.map((virtualRow) => {
const row = rows[virtualRow.index] as Row<TData>;
return (
<TableRow
ref={(node) => rowVirtualizer.measureElement(node)} //measure dynamic row height
key={row.id}
data-index={virtualRow.index} //needed for dynamic row height measurement
data-state={row.getIsSelected() && "selected"}
onClick={() => onRowMouseclick && onRowMouseclick(row)}
style={{
display: "flex",
position: "absolute",
transform: `translateY(${virtualRow.start}px)`, //this should always be a `style` as it changes on scroll
width: "100%",
}}
className={classNames(onRowMouseclick && "hover:cursor-pointer", "group")}>
{row.getVisibleCells().map((cell) => {
const column = cell.column;
return (
<TableCell
key={cell.id}
style={{
...(column.getIsPinned() === "left" && { left: `${column.getStart("left")}px` }),
...(column.getIsPinned() === "right" && { right: `${column.getStart("right")}px` }),
width: `var(--col-${kebabCase(cell.column.id)}-size)`,
}}
className={classNames(
"flex shrink-0 items-center overflow-hidden",
variant === "compact" && "p-0",
column.getIsPinned() &&
"bg-default group-hover:!bg-muted group-data-[state=selected]:bg-subtle sm:sticky"
)}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
);
})}
</TableRow>
);
})
) : (
paginationMode,
}: DataTableBodyProps<TData> & { paginationMode?: "infinite" | "standard" }) {
const { t } = useLocale();
const virtualItems = rowVirtualizer.getVirtualItems();
const tableHeight = paginationMode === "infinite" ? rowVirtualizer.getTotalSize() : "auto";
const rowsToRender = useMemo<RowToRender<TData>[]>(
() =>
paginationMode === "infinite"
? virtualItems.map((virtualItem) => ({
row: rows[virtualItem.index] as Row<TData>,
virtualItem,
}))
: rows.map((row) => ({ row })),
[paginationMode, virtualItems, rows]
);
if (!isPending && rowsToRender.length === 0) {
return (
<TableBody className="relative grid" data-testid={testId} style={{ height: tableHeight }}>
<TableRow>
<TableCell colSpan={table.getAllColumns().length} className="h-24 text-center">
No results.
{t("no_results")}
</TableCell>
</TableRow>
)}
</TableBody>
);
}
return (
<TableBody className="relative grid" data-testid={testId} style={{ height: tableHeight }}>
{rowsToRender.map(({ row, virtualItem }) => (
<TableRow
ref={virtualItem ? (node) => rowVirtualizer.measureElement(node) : undefined}
key={row.id}
data-index={virtualItem?.index} //needed for dynamic row height measurement
data-state={row.getIsSelected() && "selected"}
onClick={() => onRowMouseclick && onRowMouseclick(row)}
style={{
display: "flex",
...(virtualItem && {
position: "absolute",
transform: `translateY(${virtualItem.start}px)`,
width: "100%",
}),
}}
className={classNames(onRowMouseclick && "hover:cursor-pointer", "group")}>
{row.getVisibleCells().map((cell) => {
const column = cell.column;
return (
<TableCell
key={cell.id}
style={{
...(column.getIsPinned() === "left" && { left: `${column.getStart("left")}px` }),
...(column.getIsPinned() === "right" && { right: `${column.getStart("right")}px` }),
width: `var(--col-${kebabCase(cell.column.id)}-size)`,
}}
className={classNames(
"flex shrink-0 items-center overflow-hidden",
variant === "compact" && "p-0",
column.getIsPinned() &&
"bg-default group-hover:!bg-muted group-data-[state=selected]:bg-subtle sm:sticky"
)}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
);
})}
</TableRow>
))}
</TableBody>
);
}
@@ -1,19 +1,45 @@
"use client";
import type { Table } from "@tanstack/react-table";
import { type Table } from "@tanstack/react-table";
import { Pagination } from "@calcom/ui";
import { useDataTable } from "../hooks";
interface DataTablePaginationProps<TData> {
table: Table<TData>;
totalDbDataCount: number;
totalRowCount: number;
paginationMode?: "infinite" | "standard";
}
export function DataTablePagination<TData>({ table, totalDbDataCount }: DataTablePaginationProps<TData>) {
const loadedCount = table.getFilteredRowModel().rows.length;
export function DataTablePagination<TData>({
table,
totalRowCount,
paginationMode = "infinite",
}: DataTablePaginationProps<TData>) {
const { pageIndex, pageSize, setPageIndex, setPageSize } = useDataTable();
return (
<p className="text-subtle text-sm tabular-nums">
Loaded <span className="text-default font-medium">{`${loadedCount}`}</span> of
<span className="text-default font-medium"> {`${totalDbDataCount}`}</span>
</p>
);
if (paginationMode === "infinite") {
const loadedCount = table.getFilteredRowModel().rows.length;
return (
<p className="text-subtle text-sm tabular-nums">
Loaded <span className="text-default font-medium">{loadedCount}</span> of{" "}
<span className="text-default font-medium">{totalRowCount}</span>
</p>
);
} else if (paginationMode === "standard") {
return (
<Pagination
currentPage={pageIndex + 1}
pageSize={pageSize}
totalItems={totalRowCount}
onPageChange={(page) => setPageIndex(page - 1)}
onPageSizeChange={(newSize) => setPageSize(newSize)}
onNext={() => setPageIndex(pageIndex + 1)}
onPrevious={() => setPageIndex(pageIndex - 1)}
/>
);
} else {
return null;
}
}
@@ -1,6 +1,8 @@
"use client";
import type { Table as ReactTableType, VisibilityState } from "@tanstack/react-table";
// eslint-disable-next-line no-restricted-imports
import { noop } from "lodash";
import { useEffect, useRef } from "react";
import {
@@ -12,17 +14,14 @@ import {
} from "@calcom/features/data-table";
import classNames from "@calcom/ui/classNames";
export type DataTableWrapperProps<TData, TValue> = {
type BaseDataTableWrapperProps<TData> = {
testId?: string;
bodyTestId?: string;
table: ReactTableType<TData>;
isPending: boolean;
hasNextPage: boolean;
fetchNextPage: () => void;
isFetching: boolean;
hideHeader?: boolean;
variant?: "default" | "compact";
totalDBRowCount?: number;
totalRowCount?: number;
ToolbarLeft?: React.ReactNode;
ToolbarRight?: React.ReactNode;
EmptyView?: React.ReactNode;
@@ -33,7 +32,23 @@ export type DataTableWrapperProps<TData, TValue> = {
tableContainerRef?: React.RefObject<HTMLDivElement>;
};
export function DataTableWrapper<TData, TValue>({
type InfinitePaginationProps<TData> = BaseDataTableWrapperProps<TData> & {
paginationMode: "infinite";
hasNextPage: boolean;
fetchNextPage: () => void;
isFetching: boolean;
};
type StandardPaginationProps<TData> = BaseDataTableWrapperProps<TData> & {
paginationMode: "standard";
hasNextPage?: never;
fetchNextPage?: never;
isFetching?: never;
};
export type DataTableWrapperProps<TData> = InfinitePaginationProps<TData> | StandardPaginationProps<TData>;
export function DataTableWrapper<TData>({
testId,
bodyTestId,
table,
@@ -41,7 +56,7 @@ export function DataTableWrapper<TData, TValue>({
hasNextPage,
fetchNextPage,
isFetching,
totalDBRowCount,
totalRowCount,
variant,
hideHeader,
ToolbarLeft,
@@ -52,14 +67,16 @@ export function DataTableWrapper<TData, TValue>({
containerClassName,
children,
tableContainerRef: externalRef,
}: DataTableWrapperProps<TData, TValue>) {
paginationMode,
}: DataTableWrapperProps<TData>) {
const internalRef = useRef<HTMLDivElement>(null);
const tableContainerRef = externalRef || internalRef;
const fetchMoreOnBottomReached = useFetchMoreOnBottomReached({
tableContainerRef,
hasNextPage,
fetchNextPage,
isFetching,
hasNextPage: paginationMode === "infinite" ? hasNextPage : false,
fetchNextPage: paginationMode === "infinite" ? fetchNextPage : noop,
isFetching: paginationMode === "infinite" ? isFetching : false,
enabled: paginationMode === "infinite",
});
const { sorting, setSorting, columnVisibility, setColumnVisibility } = useDataTable();
const columnFilters = useColumnFilters();
@@ -81,7 +98,7 @@ export function DataTableWrapper<TData, TValue>({
onSortingChange: setSorting,
onColumnVisibilityChange: setColumnVisibility,
}));
}, [table, sorting, columnFilters, columnVisibility]);
}, [table, sorting, columnFilters, columnVisibility, setSorting, setColumnVisibility]);
let view: "loader" | "empty" | "table" = "table";
if (isPending && LoaderView) {
@@ -118,10 +135,20 @@ export function DataTableWrapper<TData, TValue>({
variant={variant}
className={className}
containerClassName={containerClassName}
onScroll={(e) => fetchMoreOnBottomReached(e.target as HTMLDivElement)}>
{totalDBRowCount && (
paginationMode={paginationMode}
onScroll={
paginationMode === "infinite"
? (e: Pick<React.UIEvent<HTMLDivElement, UIEvent>, "target">) =>
fetchMoreOnBottomReached(e.target as HTMLDivElement)
: undefined
}>
{totalRowCount && (
<div style={{ gridArea: "footer", marginTop: "1rem" }}>
<DataTablePagination table={table} totalDbDataCount={totalDBRowCount} />
<DataTablePagination<TData>
table={table}
totalRowCount={totalRowCount}
paginationMode={paginationMode}
/>
</div>
)}
</DataTable>
@@ -7,14 +7,17 @@ export const useFetchMoreOnBottomReached = ({
hasNextPage,
fetchNextPage,
isFetching,
enabled = true,
}: {
tableContainerRef: React.RefObject<HTMLDivElement>;
hasNextPage: boolean;
fetchNextPage: () => void;
isFetching: boolean;
enabled?: boolean;
}) => {
const fetchMoreOnBottomReached = useCallback(
(containerRefElement?: HTMLDivElement | null) => {
if (!enabled) return;
if (containerRefElement) {
const { scrollHeight, scrollTop, clientHeight } = containerRefElement;
if (scrollHeight - scrollTop - clientHeight < 300 && !isFetching && hasNextPage) {
@@ -22,12 +25,13 @@ export const useFetchMoreOnBottomReached = ({
}
}
},
[fetchNextPage, isFetching]
[fetchNextPage, isFetching, hasNextPage, enabled]
);
useEffect(() => {
if (!enabled) return;
fetchMoreOnBottomReached(tableContainerRef.current);
}, [fetchMoreOnBottomReached, tableContainerRef]);
}, [fetchMoreOnBottomReached, tableContainerRef, enabled]);
return fetchMoreOnBottomReached;
};
+33 -2
View File
@@ -1,7 +1,7 @@
"use client";
import type { SortingState, OnChangeFn, VisibilityState } from "@tanstack/react-table";
import { useQueryState, parseAsArrayOf, parseAsJson } from "nuqs";
import { useQueryState, parseAsArrayOf, parseAsJson, parseAsInteger } from "nuqs";
import { createContext, useCallback } from "react";
import { z } from "zod";
@@ -26,6 +26,14 @@ export type DataTableContextType = {
columnVisibility: VisibilityState;
setColumnVisibility: OnChangeFn<VisibilityState>;
pageIndex: number;
pageSize: number;
setPageIndex: (pageIndex: number) => void;
setPageSize: (pageSize: number) => void;
offset: number;
limit: number;
};
export const DataTableContext = createContext<DataTableContextType | null>(null);
@@ -33,8 +41,14 @@ export const DataTableContext = createContext<DataTableContextType | null>(null)
const DEFAULT_ACTIVE_FILTERS: ActiveFilter[] = [];
const DEFAULT_SORTING: SortingState = [];
const DEFAULT_COLUMN_VISIBILITY: VisibilityState = {};
const DEFAULT_PAGE_SIZE = 10;
export function DataTableProvider({ children }: { children: React.ReactNode }) {
interface DataTableProviderProps {
children: React.ReactNode;
defaultPageSize?: number;
}
export function DataTableProvider({ children, defaultPageSize = DEFAULT_PAGE_SIZE }: DataTableProviderProps) {
const [activeFilters, setActiveFilters] = useQueryState(
"activeFilters",
parseAsArrayOf(parseAsJson(ZActiveFilter.parse)).withDefault(DEFAULT_ACTIVE_FILTERS)
@@ -48,6 +62,9 @@ export function DataTableProvider({ children }: { children: React.ReactNode }) {
parseAsJson(ZColumnVisibility.parse).withDefault(DEFAULT_COLUMN_VISIBILITY)
);
const [pageIndex, setPageIndex] = useQueryState("page", parseAsInteger.withDefault(0));
const [pageSize, setPageSize] = useQueryState("size", parseAsInteger.withDefault(defaultPageSize));
const clearAll = useCallback(
(exclude?: string[]) => {
setActiveFilters((prev) => prev.filter((filter) => exclude?.includes(filter.f)));
@@ -82,6 +99,14 @@ export function DataTableProvider({ children }: { children: React.ReactNode }) {
[setActiveFilters]
);
const setPageSizeAndGoToFirstPage = useCallback(
(newPageSize: number) => {
setPageSize(newPageSize);
setPageIndex(0);
},
[setPageSize, setPageIndex]
);
return (
<DataTableContext.Provider
value={{
@@ -94,6 +119,12 @@ export function DataTableProvider({ children }: { children: React.ReactNode }) {
setSorting,
columnVisibility,
setColumnVisibility,
pageIndex,
pageSize,
setPageIndex,
setPageSize: setPageSizeAndGoToFirstPage,
limit: pageSize,
offset: pageIndex * pageSize,
}}>
{children}
</DataTableContext.Provider>