feat: attributes filter / refactor of user data table (#17014)

* WIP restored from .git cache

* fix exports

* sortable row model

* feat column visibility component

* wip filters with nuqs

* pull in unique values from table into filters

* correctly assign filters via v/f

* inital selection bar refactor

* data-table selection bar + optmistic update of delete

* dynamic link

* migrate member list table to new data-table

* total list shows filtered value > db valuie

* add filters for attributes

* type errors

* make content bigger on lg

* add mb-6 to teams user datatable to match spacing spec

* correctly render multi-badge

* fix: masss asignment optimistic UI

* fix type errors

* remove log

* fix toolbar type error

* chore: Remove debug artifact

* type errors

* Update apps/web/public/static/locales/en/common.json

* use max-w-fit

* chore: Remove unused translation now we don't specify 'mass' in assign

* perf: fix: use the onBlur event to prevent focus loss whilst the list is rerendering

* Move the data-table exports together in the main barrel, then import

* fix exports that were lost in a merge

* fix exports that were lost in a merge

* fix groupteammapping/availbilityslider

* fix overflow problems

* add scrollbar-thin class

* fix type error

* user serverside values for faceted filters

* pass filters to serverside

* filter serverside

* fix team server side filter

* add loaded x of y

* attributes icon change

* correct implementation for text/input attr optimistic

* type check fixes

* fix platform checks

* fix types again

* fix types again

* fix types again

* add use client

* add use client

* fix-types

* fix: Add missing translation in EN

* fix e2e tests via testid

* fix e2e tests via testid

* fix: Member invite popup not popping up

* Update copyInviteLink to new-member-button testid

* Hopefully fix test ids this time

* fix: Use the right buttons on the right pages

---------

Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-10-15 17:45:11 +00:00
1 parent 0b914bef79
commit 7e44e686e8
43 files changed
+1462 -1049

No files matched your search

@@ -1,4 +1,7 @@
"use client";
import type { Column } from "@tanstack/react-table";
import { useState } from "react";
import { classNames } from "@calcom/lib";
@@ -17,18 +20,68 @@ import {
} from "../command";
import { Popover, PopoverContent, PopoverTrigger } from "../popover";
interface FilterOption {
label: string;
value: string;
icon?: IconName;
options?: FilterOption[];
}
interface DataTableFilter<TData, TValue> {
column?: Column<TData, TValue>;
title?: string;
options: {
label: string;
value: string;
icon?: IconName;
}[];
options: FilterOption[];
}
export function DataTableFilter<TData, TValue>({ column, title, options }: DataTableFilter<TData, TValue>) {
const facets = column?.getFacetedUniqueValues();
const selectedValues = new Set(column?.getFilterValue() as string[]);
const [currentOptions, setCurrentOptions] = useState<FilterOption[]>(options);
const [navigationPath, setNavigationPath] = useState<string[]>([]);
const flattenOptions = (opts: FilterOption[]): FilterOption[] => {
return opts.reduce((acc, option) => {
acc.push(option);
if (option.options) {
acc.push(...flattenOptions(option.options));
}
return acc;
}, [] as FilterOption[]);
};
const allOptions = flattenOptions(options);
const handleSelect = (option: FilterOption) => {
if (option.options) {
setCurrentOptions(option.options);
setNavigationPath([...navigationPath, option.label]);
} else {
if (selectedValues.has(option.value)) {
selectedValues.delete(option.value);
} else {
selectedValues.add(option.value);
}
const filterValues = Array.from(selectedValues);
column?.setFilterValue(filterValues.length ? filterValues : undefined);
}
};
const handleBack = () => {
if (navigationPath.length > 0) {
const newPath = [...navigationPath];
newPath.pop();
setNavigationPath(newPath);
let newOptions = options;
for (const label of newPath) {
const found = newOptions.find((o) => o.label === label);
if (found && found.options) {
newOptions = found.options;
}
}
setCurrentOptions(newOptions);
}
};
return (
<Popover>
@@ -44,7 +97,7 @@ export function DataTableFilter<TData, TValue>({ column, title, options }: DataT
{selectedValues.size}
</Badge>
) : (
options
allOptions
.filter((option) => selectedValues.has(option.value))
.map((option) => (
<Badge color="gray" key={option.value} className="rounded-sm px-1 font-normal">
@@ -62,32 +115,32 @@ export function DataTableFilter<TData, TValue>({ column, title, options }: DataT
<CommandInput placeholder={title} />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
{navigationPath.length > 0 && (
<CommandGroup>
<CommandItem onSelect={handleBack}>
<Icon name="arrow-left" className="mr-2 h-4 w-4" />
Back
</CommandItem>
</CommandGroup>
)}
<CommandGroup>
{options.map((option) => {
// TODO: It would be nice to pull these from data instead of options
{currentOptions.map((option) => {
const isSelected = selectedValues.has(option.value);
return (
<CommandItem
key={option.value}
onSelect={() => {
if (isSelected) {
selectedValues.delete(option.value);
} else {
selectedValues.add(option.value);
}
const filterValues = Array.from(selectedValues);
column?.setFilterValue(filterValues.length ? filterValues : undefined);
}}>
<div
className={classNames(
"border-subtle mr-2 flex h-4 w-4 items-center justify-center rounded-sm border",
isSelected ? "text-emphasis" : "opacity-50 [&_svg]:invisible"
)}>
<Icon name="check" className={classNames("h-4 w-4")} />
</div>
<CommandItem key={option.value} onSelect={() => handleSelect(option)}>
{!option.options && (
<div
className={classNames(
"border-subtle mr-2 flex h-4 w-4 items-center justify-center rounded-sm border",
isSelected ? "text-emphasis" : "opacity-50 [&_svg]:invisible"
)}>
<Icon name="check" className={classNames("h-4 w-4")} />
</div>
)}
{option.icon && <Icon name={option.icon} className="text-muted mr-2 h-4 w-4" />}
<span>{option.label}</span>
{facets?.get(option.value) && (
{option.options && <Icon name="chevron-right" className="ml-auto h-4 w-4" />}
{!option.options && facets?.get(option.value) && (
<span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs">
{facets.get(option.value)}
</span>
@@ -1,59 +1,19 @@
import type { Table } from "@tanstack/react-table";
"use client";
import { Button } from "../button";
import type { Table } from "@tanstack/react-table";
interface DataTablePaginationProps<TData> {
table: Table<TData>;
totalDbDataCount: number;
}
export function DataTablePagination<TData>({ table }: DataTablePaginationProps<TData>) {
export function DataTablePagination<TData>({ table, totalDbDataCount }: DataTablePaginationProps<TData>) {
const loadedCount = table.getFilteredRowModel().rows.length;
return (
<div className="flex items-center justify-between px-2">
<div className="text-muted-foreground flex-1 text-sm">
{table.getFilteredSelectedRowModel().rows.length} of {table.getFilteredRowModel().rows.length} row(s)
selected.
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex} of {table.getPageCount() - 1}
</div>
<div className="flex items-center space-x-2">
<Button
color="secondary"
variant="icon"
StartIcon="chevrons-left"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}>
<span className="sr-only">Go to first page</span>
</Button>
<Button
color="secondary"
variant="icon"
className="h-8 w-8 p-0"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
StartIcon="chevron-left">
<span className="sr-only">Go to previous page</span>
</Button>
<Button
color="secondary"
variant="icon"
StartIcon="chevron-right"
className="h-8 w-8 p-0"
disabled={!table.getCanNextPage()}
onClick={() => table.nextPage()}>
<span className="sr-only">Go to next page</span>
</Button>
<Button
color="secondary"
variant="icon"
className="hidden h-8 w-8 p-0 lg:flex"
StartIcon="chevrons-right"
onClick={() => table.setPageIndex(table.getPageCount())}>
<span className="sr-only">Go to last page</span>
</Button>
</div>
</div>
</div>
<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>
);
}
@@ -1,10 +1,11 @@
"use client";
import type { Table } from "@tanstack/react-table";
import type { Table as TableType } from "@tanstack/table-core/build/lib/types";
import { AnimatePresence } from "framer-motion";
import { Fragment } from "react";
import { forwardRef } from "react";
import { classNames } from "@calcom/lib";
import type { IconName } from "../..";
import { Button } from "../button";
export type ActionItem<TData> =
| {
@@ -20,51 +21,26 @@ export type ActionItem<TData> =
needsXSelected?: number;
};
interface DataTableSelectionBarProps<TData> {
table: Table<TData>;
actions?: ActionItem<TData>[];
renderAboveSelection?: (table: TableType<TData>) => React.ReactNode;
}
export function DataTableSelectionBar<TData>({
table,
actions,
renderAboveSelection,
}: DataTableSelectionBarProps<TData>) {
const numberOfSelectedRows = table.getSelectedRowModel().rows.length;
const isVisible = numberOfSelectedRows > 0;
// Hacky left % to center
const actionsVisible = actions?.filter((a) => {
if (!a.needsXSelected) return true;
return a.needsXSelected <= numberOfSelectedRows;
});
const Root = forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & { showSelectionCount?: boolean }
>(({ children, ...props }, ref) => {
return (
<AnimatePresence>
{isVisible ? (
<div className="fade-in fixed bottom-6 left-1/2 hidden -translate-x-1/2 gap-1 md:flex md:flex-col">
{renderAboveSelection && renderAboveSelection(table)}
<div className="bg-brand-default text-brand hidden items-center justify-between rounded-lg p-2 md:flex">
<p className="text-brand-subtle w-full px-2 text-center leading-none">
{numberOfSelectedRows} selected
</p>
{actionsVisible?.map((action, index) => {
return (
<Fragment key={index}>
{action.type === "action" ? (
<Button aria-label={action.label} onClick={action.onClick} StartIcon={action.icon}>
{action.label}
</Button>
) : action.type === "render" ? (
action.render(table)
) : null}
</Fragment>
);
})}
</div>
</div>
) : null}
</AnimatePresence>
<div
ref={ref}
className={classNames(
"bg-brand-default text-brand fixed bottom-4 left-1/2 flex w-fit -translate-x-1/2 transform items-center space-x-3 rounded-lg px-4 py-2",
props.className
)}
style={{ ...props.style }}
{...props}>
{children}
</div>
);
}
});
Root.displayName = "Root";
export const DataTableSelectionBar = {
Root,
};
@@ -1,44 +1,45 @@
"use client";
import type { Table } from "@tanstack/react-table";
import { useEffect, useState } from "react";
import { useEffect, useState, forwardRef } from "react";
import type { ComponentPropsWithoutRef } from "react";
import { classNames } from "@calcom/lib";
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { ButtonProps } from "../button";
import { Button } from "../button";
import { Input } from "../form";
import type { IconName } from "../icon/icon-names";
import { DataTableFilter } from "./DataTableFilter";
export type FilterableItems = {
title: string;
tableAccessor: string;
options: {
label: string;
value: string;
icon?: IconName;
}[];
}[];
interface DataTableToolbarProps extends ComponentPropsWithoutRef<"div"> {
children: React.ReactNode;
}
interface DataTableToolbarProps<TData> {
const Root = forwardRef<HTMLDivElement, DataTableToolbarProps>(function DataTableToolbar(
{ children, className },
ref
) {
return (
<div
ref={ref}
className={classNames("grid w-full items-center gap-2 py-4", className)}
style={{ gridArea: "header" }}>
{children}
</div>
);
});
interface SearchBarProps<TData> {
table: Table<TData>;
filterableItems?: FilterableItems;
searchKey?: string;
tableCTA?: React.ReactNode;
onSearch?: (value: string) => void;
}
export function DataTableToolbar<TData>({
table,
filterableItems,
tableCTA,
searchKey,
onSearch,
}: DataTableToolbarProps<TData>) {
// TODO: Is there a better way to check if the table is filtered?
// If you select ALL filters for a column, the table is not filtered and we dont get a reset button
const isFiltered = table.getState().columnFilters.length > 0;
function SearchBarComponent<TData>(
{ table, searchKey, onSearch }: SearchBarProps<TData>,
ref: React.Ref<HTMLInputElement>
) {
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearchTerm = useDebounce(searchTerm, 500);
@@ -46,54 +47,80 @@ export function DataTableToolbar<TData>({
onSearch?.(debouncedSearchTerm);
}, [debouncedSearchTerm, onSearch]);
const { t } = useLocale();
if (onSearch) {
return (
<Input
ref={ref}
className="max-w-64 mb-0 mr-auto rounded-md"
placeholder="Search"
value={searchTerm}
onChange={(event) => setSearchTerm(event.target.value.trim())}
/>
);
}
if (!searchKey) {
console.error("searchKey is required if onSearch is not provided");
return null;
}
return (
<div className="flex items-center justify-end gap-2 py-4">
{searchKey && (
<Input
className="max-w-64 mb-0 mr-auto rounded-md"
placeholder="Search"
value={(table.getColumn(searchKey)?.getFilterValue() as string) ?? ""}
onChange={(event) => table.getColumn(searchKey)?.setFilterValue(event.target.value.trim())}
/>
)}
{onSearch && (
<Input
className="max-w-64 mb-0 mr-auto rounded-md"
placeholder="Search"
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value);
}}
/>
)}
{isFiltered && (
<Button
color="minimal"
EndIcon="x"
onClick={() => table.resetColumnFilters()}
className="h-8 px-2 lg:px-3">
{t("clear")}
</Button>
)}
{filterableItems &&
filterableItems?.map((item) => {
const foundColumn = table.getColumn(item.tableAccessor);
if (foundColumn?.getCanFilter()) {
return (
<DataTableFilter
column={foundColumn}
title={item.title}
options={item.options}
key={item.title}
/>
);
}
})}
{tableCTA ? tableCTA : null}
</div>
<Input
ref={ref}
className="max-w-64 mb-0 mr-auto rounded-md"
placeholder="Search"
value={(table.getColumn(searchKey)?.getFilterValue() as string) ?? ""}
onChange={(event) => {
return table.getColumn(searchKey)?.setFilterValue(event.target.value.trim());
}}
/>
);
}
const SearchBar = forwardRef(SearchBarComponent) as <TData>(
props: SearchBarProps<TData> & { ref?: React.Ref<HTMLInputElement> }
) => ReturnType<typeof SearchBarComponent>;
interface ClearFiltersButtonProps<TData> {
table: Table<TData>;
}
function ClearFiltersButtonComponent<TData>(
{ table }: ClearFiltersButtonProps<TData>,
ref: React.Ref<HTMLButtonElement>
) {
const { t } = useLocale();
const isFiltered = table.getState().columnFilters.length > 0;
if (!isFiltered) return null;
return (
<Button
ref={ref}
color="minimal"
EndIcon="x"
onClick={() => table.resetColumnFilters()}
className="h-8 px-2 lg:px-3">
{t("clear")}
</Button>
);
}
const ClearFiltersButton = forwardRef(ClearFiltersButtonComponent) as <TData>(
props: ClearFiltersButtonProps<TData> & { ref?: React.Ref<HTMLButtonElement> }
) => ReturnType<typeof ClearFiltersButtonComponent>;
function CTAComponent(
{ children, onClick, color = "primary", ...rest }: ButtonProps,
ref: React.Ref<HTMLButtonElement>
) {
return (
<Button ref={ref} color={color} onClick={onClick} {...rest}>
{children}
</Button>
);
}
const CTA = forwardRef(CTAComponent) as (
props: ButtonProps & { ref?: React.Ref<HTMLButtonElement> }
) => ReturnType<typeof CTAComponent>;
export const DataTableToolbar = { Root, SearchBar, ClearFiltersButton, CTA };
@@ -1,78 +0,0 @@
import type { ColumnDef } from "@tanstack/react-table";
import { Badge } from "../../badge";
import { Checkbox } from "../../form";
import type { FilterableItems } from "../DataTableToolbar";
import type { DataTableUserStorybook } from "./data";
export const columns: ColumnDef<DataTableUserStorybook>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
className="translate-y-[2px]"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
className="translate-y-[2px]"
/>
),
},
{
accessorKey: "username",
header: "Username",
},
{
accessorKey: "email",
header: "Email",
},
{
accessorKey: "role",
header: "Role",
cell: ({ row, table }) => {
const user = row.original;
const BadgeColor = user.role === "admin" ? "blue" : "gray";
return (
<Badge
color={BadgeColor}
onClick={() => {
table.getColumn("role")?.setFilterValue(user.role);
}}>
{user.role}
</Badge>
);
},
filterFn: (rows, id, filterValue) => {
return filterValue.includes(rows.getValue(id));
},
},
];
export const filterableItems: FilterableItems = [
{
title: "Role",
tableAccessor: "role",
options: [
{
label: "Admin",
value: "admin",
},
{
label: "User",
value: "user",
},
{
label: "Owner",
value: "owner",
},
],
},
];
@@ -1,98 +0,0 @@
export type DataTableUserStorybook = {
id: string;
username: string;
email: string;
role: "admin" | "user";
};
export const dataTableSelectionActions = [
{
label: "Add To Team",
onClick: () => {
console.log("Add To Team");
},
icon: "users",
},
{
label: "Delete",
onClick: () => {
console.log("Delete");
},
icon: "stop-circle",
},
];
export const dataTableDemousers: DataTableUserStorybook[] = [
{
id: "728ed52f",
email: "[email protected]",
username: "m",
role: "admin",
},
{
id: "489e1d42",
email: "[email protected]",
username: "e",
role: "user",
},
{
id: "7b8a6f1d-2d2d-4d29-9c1a-0a8b3f5f9d2f",
email: "[email protected]",
username: "Ava_Waelchi",
role: "user",
},
{
id: "f4d9e2a3-7e3c-4d6e-8e4c-8d0d7d1c2c9b",
email: "[email protected]",
username: "Kamren_Gerhold",
role: "admin",
},
{
id: "1b2a4b6e-5b2d-4c38-9c7e-9d5e8f9c0a6a",
email: "[email protected]",
username: "Lennie_Harber",
role: "user",
},
{
id: "d6f3e6e9-9c2a-4c8a-8f3c-0d63a0eaf5a5",
email: "[email protected]",
username: "Lorenzo_Will",
role: "admin",
},
{
id: "7c1e5d1d-8b9c-4b1c-9d1b-7d9f8b5a7e3e",
email: "[email protected]",
username: "Monserrat_Lang",
role: "user",
},
{
id: "f7d8b7a2-0a5c-4f8d-9f4f-8d1a2c3e4b3e",
email: "[email protected]",
username: "Eddie_Effertz",
role: "user",
},
{
id: "2f8b9c8d-1a5c-4e3d-9b7a-6c5d4e3f2b1a",
email: "[email protected]",
username: "Alyce_Olson",
role: "user",
},
{
id: "d8c7b6a5-4e3d-2b1a-9c8d-1f2e3d4c5b6a",
email: "[email protected]",
username: "Jovanny_Kiehn",
role: "admin",
},
{
id: "3c2b1a5d-4e3d-8c7b-9a6f-0d1e2f3g4h5i",
email: "[email protected]",
username: "Aurelia_Kemmer",
role: "user",
},
{
id: "e4d3c2b1-5e4d-3c2b-1a9f-8g7h6i5j4k3l",
email: "[email protected]",
username: "Waino_Lang",
role: "admin",
},
];
@@ -1,67 +0,0 @@
import { Canvas, Meta, Story, ArgsTable } from "@storybook/addon-docs";
import {
Examples,
Example,
Note,
Title,
CustomArgsTable,
VariantsTable,
VariantRow,
} from "@calcom/storybook/components";
import { DataTable } from "../";
import { columns, filterableItems } from "./columns";
import { dataTableDemousers, dataTableSelectionActions } from "./data";
<Meta title="UI/table/DataTable" component={DataTable} />
<Title title="DataTable" suffix="Brief" subtitle="Version 3.0 — Last Update: 28 Aug 2023" />
## Definition
The `DataTable` component facilitates tabular data display with configurable columns, virtual scrolling, filtering, and interactive features for seamless dynamic table creation.
## Structure
The `DataTable` setup for tabular data, with columns, virtual scroll, sticky headers, and interactive features like filtering and row selection.
<CustomArgsTable of={DataTable} />
## Dialog Story
<Canvas>
<Story
name="DataTable"
args={{
columns: columns,
data: dataTableDemousers,
isPending: false,
searchKey: "username",
filterableItems: filterableItems,
tableContainerRef: { current: null },
selectionOptions: dataTableSelectionActions,
}}
argTypes={{
tableContainerRef: { table: { disable: true } },
searchKey: {
control: {
type: "select",
options: ["username", "email"],
},
},
selectionOptions: { control: { type: "object" } },
onScroll: { table: { disable: true } },
tableOverlay: { table: { disable: true } },
CTA: { table: { disable: true } },
tableCTA: { table: { disable: true } },
}}>
{(args) => (
<VariantsTable titles={["Default"]} columnMinWidth={1000}>
<VariantRow>
<DataTable {...args} />
</VariantRow>
</VariantsTable>
)}
</Story>
</Canvas>
@@ -0,0 +1,269 @@
"use client";
import { type Table } from "@tanstack/react-table";
import { forwardRef, useState, useMemo } from "react";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { ButtonProps } from "@calcom/ui";
import {
Button,
buttonClasses,
Popover,
PopoverTrigger,
PopoverContent,
Command,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandSeparator,
Icon,
} from "@calcom/ui";
import { useFiltersSearchState } from "./utils";
interface ColumnVisiblityProps<TData> {
table: Table<TData>;
}
function ColumnVisibilityButtonComponent<TData>(
{
children,
color = "secondary",
EndIcon = "sliders-vertical",
table,
...rest
}: ColumnVisiblityProps<TData> & ButtonProps,
ref: React.Ref<HTMLButtonElement>
) {
const { t } = useLocale();
const allColumns = table.getAllLeafColumns();
const [open, setOpen] = useState(false);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button ref={ref} color={color} EndIcon={EndIcon} {...rest}>
{children ? children : t("View")}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0" align="start">
<Command>
<CommandInput placeholder={t("search")} />
<CommandList>
<CommandEmpty>{t("no_columns_found")}</CommandEmpty>
<CommandGroup heading={t("toggle_columns")}>
{allColumns.map((column) => {
const canHide = column.getCanHide();
if (!column.columnDef.header || typeof column.columnDef.header !== "string" || !canHide)
return null;
const isVisible = column.getIsVisible();
return (
<CommandItem key={column.id} onSelect={() => column.toggleVisibility(!isVisible)}>
<div
className={classNames(
"border-subtle mr-2 flex h-4 w-4 items-center justify-center rounded-sm border",
isVisible ? "text-emphasis" : "opacity-50 [&_svg]:invisible"
)}>
<Icon name="check" className={classNames("h-4 w-4")} />
</div>
{column.columnDef.header}
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
<CommandSeparator />
<CommandGroup>
<CommandItem
onSelect={() => allColumns.forEach((column) => column.toggleVisibility(true))}
className={classNames(
"w-full justify-center text-center",
buttonClasses({ color: "secondary" })
)}>
{t("show_all_columns")}
</CommandItem>
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
);
}
const ColumnVisibilityButton = forwardRef(ColumnVisibilityButtonComponent) as <TData>(
props: ColumnVisiblityProps<TData> & ButtonProps & { ref?: React.Ref<HTMLButtonElement> }
) => ReturnType<typeof ColumnVisibilityButtonComponent>;
// Filters
interface FilterButtonProps<TData> {
table: Table<TData>;
omit?: string[];
}
function FilterButtonComponent<TData>(
{ table, omit }: FilterButtonProps<TData>,
ref: React.Ref<HTMLButtonElement>
) {
const { t } = useLocale();
const [_state, _setState] = useFiltersSearchState();
const activeFilters = _state.activeFilters;
const columns = table
.getAllColumns()
.filter((column) => column.getCanFilter())
.filter((column) => !omit?.includes(column.id));
const filterableColumns = useMemo(() => {
return columns.map((column) => ({
id: column.id,
title: typeof column.columnDef.header === "string" ? column.columnDef.header : column.id,
options: column.getFacetedUniqueValues(),
}));
}, [columns]);
const handleAddFilter = (columnId: string) => {
if (!activeFilters?.some((filter) => filter.f === columnId)) {
_setState({ activeFilters: [...activeFilters, { f: columnId, v: [] }] });
}
};
return (
<div className="flex items-center space-x-2">
<Popover>
<PopoverTrigger asChild>
<Button ref={ref} color="secondary" className="border-dashed">
<Icon name="filter" className="mr-2 h-4 w-4" />
{t("add_filter")}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0" align="start">
<Command>
<CommandInput placeholder={t("search_columns")} />
<CommandList>
<CommandEmpty>{t("no_columns_found")}</CommandEmpty>
{filterableColumns.map((column) => {
if (activeFilters?.some((filter) => filter.f === column.id)) return null;
return (
<CommandItem key={column.id} onSelect={() => handleAddFilter(column.id)}>
{column.title}
</CommandItem>
);
})}
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
);
}
const FilterButton = forwardRef(FilterButtonComponent) as <TData>(
props: FilterButtonProps<TData> & { ref?: React.Ref<HTMLButtonElement>; omit?: string[] }
) => ReturnType<typeof FilterButtonComponent>;
// Add the new ActiveFilters component
interface ActiveFiltersProps<TData> {
table: Table<TData>;
}
function ActiveFilters<TData>({ table }: ActiveFiltersProps<TData>) {
const { t } = useLocale();
const [_state, _setState] = useFiltersSearchState();
const columns = table.getAllColumns().filter((column) => column.getCanFilter());
const filterableColumns = useMemo(() => {
return columns.map((column) => {
return {
id: column.id,
title: typeof column.columnDef.header === "string" ? column.columnDef.header : column.id,
options: column.getFacetedUniqueValues(),
};
});
}, [columns]);
const handleRemoveFilter = (columnId: string) => {
_setState({ activeFilters: (_state.activeFilters || []).filter((filter) => filter.f !== columnId) });
table.getColumn(columnId)?.setFilterValue(undefined);
};
return (
<>
{(_state.activeFilters || []).map((filter) => {
const column = filterableColumns.find((col) => col.id === filter.f);
if (!column) return null;
return (
<Popover key={column.id}>
<PopoverTrigger asChild>
<Button color="secondary">
{column.title}
<Icon name="chevron-down" className="ml-2 h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" align="start">
<Command>
<CommandInput placeholder={t("search_options")} />
<CommandList>
<CommandEmpty>{t("no_options_found")}</CommandEmpty>
{Array.from(column.options).map(([option]) => {
if (!option) return null;
return (
<CommandItem
key={option}
onSelect={() => {
const newFilterValue = filter.v?.includes(option)
? filter.v?.filter((value) => value !== option)
: [...(filter.v || []), option];
_setState({
activeFilters: _state.activeFilters.map((f) =>
f.f === filter.f ? { ...f, v: newFilterValue } : f
),
});
table
.getColumn(filter.f)
?.setFilterValue(newFilterValue.length ? newFilterValue : undefined);
}}>
<div
className={classNames(
"border-subtle mr-2 flex h-4 w-4 items-center justify-center rounded-sm border",
Array.isArray(table.getColumn(column.id)?.getFilterValue()) &&
(table.getColumn(column.id)?.getFilterValue() as string[])?.includes(option)
? "bg-primary"
: "opacity-50"
)}>
{Array.isArray(table.getColumn(column.id)?.getFilterValue()) &&
(table.getColumn(column.id)?.getFilterValue() as string[])?.includes(option) && (
<Icon name="check" className="text-primary-foreground h-4 w-4" />
)}
</div>
{option}
</CommandItem>
);
})}
</CommandList>
<CommandSeparator />
<CommandGroup>
<CommandItem
onSelect={() => {
handleRemoveFilter(column.id);
}}
className={classNames(
"w-full justify-center text-center",
buttonClasses({ color: "secondary" })
)}>
{t("clear")}
</CommandItem>
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
);
})}
</>
);
}
// Update the export to include ActiveFilters
export const DataTableFilters = { ColumnVisibilityButton, FilterButton, ActiveFilters };
@@ -0,0 +1,17 @@
"use client";
import { parseAsArrayOf, parseAsJson, useQueryStates } from "nuqs";
import { z } from "zod";
const filterSchema = z.object({
f: z.string(),
v: z.array(z.string()).optional(),
});
export const filtersSearchParams = {
activeFilters: parseAsArrayOf(parseAsJson(filterSchema.parse)).withDefault([]),
};
export function useFiltersSearchState() {
return useQueryStates(filtersSearchParams);
}
+100 -144
View File
@@ -1,98 +1,40 @@
"use client";
import type {
ColumnDef,
ColumnFiltersState,
Row,
SortingState,
VisibilityState,
Table as TableType,
} from "@tanstack/react-table";
import {
flexRender,
getCoreRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { useState } from "react";
import type { Row } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
import type { Table as ReactTableType } from "@tanstack/react-table";
import { useVirtual } from "react-virtual";
import classNames from "@calcom/lib/classNames";
import Icon from "../icon/Icon";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../table/TableNew";
import type { ActionItem } from "./DataTableSelectionBar";
import { DataTableSelectionBar } from "./DataTableSelectionBar";
import type { FilterableItems } from "./DataTableToolbar";
import { DataTableToolbar } from "./DataTableToolbar";
// Export DataTable components under a common namespace for better clarity
export { DataTableToolbar } from "./DataTableToolbar";
export { DataTableFilters } from "./filters";
export interface DataTableProps<TData, TValue> {
table: ReactTableType<TData>;
tableContainerRef: React.RefObject<HTMLDivElement>;
columns: ColumnDef<TData, TValue>[];
data: TData[];
searchKey?: string;
onSearch?: (value: string) => void;
filterableItems?: FilterableItems;
selectionOptions?: ActionItem<TData>[];
renderAboveSelection?: (table: TableType<TData>) => React.ReactNode;
tableCTA?: React.ReactNode;
isPending?: boolean;
onRowMouseclick?: (row: Row<TData>) => void;
onScroll?: (e: React.UIEvent<HTMLDivElement, UIEvent>) => void;
CTA?: React.ReactNode;
tableOverlay?: React.ReactNode;
variant?: "default" | "compact";
"data-testid"?: string;
children?: React.ReactNode;
}
export function DataTable<TData, TValue>({
columns,
data,
filterableItems,
tableCTA,
searchKey,
selectionOptions,
table,
tableContainerRef,
isPending,
tableOverlay,
variant,
renderAboveSelection,
/** This should only really be used if you dont have actions in a row. */
onSearch,
onRowMouseclick,
onScroll,
children,
...rest
}: DataTableProps<TData, TValue>) {
const [rowSelection, setRowSelection] = useState({});
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const [sorting, setSorting] = useState<SortingState>([]);
const table = useReactTable({
data,
columns,
state: {
sorting,
columnVisibility,
rowSelection,
columnFilters,
},
enableRowSelection: true,
debugTable: true,
manualPagination: true,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
onColumnVisibilityChange: setColumnVisibility,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
});
}: DataTableProps<TData, TValue> & React.ComponentPropsWithoutRef<"div">) {
const { rows } = table.getRowModel();
const rowVirtualizer = useVirtual({
@@ -106,81 +48,95 @@ export function DataTable<TData, TValue>({
virtualRows.length > 0 ? totalSize - (virtualRows?.[virtualRows.length - 1]?.end || 0) : 0;
return (
<div className="relative space-y-4">
<DataTableToolbar
table={table}
filterableItems={filterableItems}
searchKey={searchKey}
onSearch={onSearch}
tableCTA={tableCTA}
/>
<div ref={tableContainerRef} onScroll={onScroll} data-testid={rest["data-testid"] ?? "data-table"}>
<Table data-testid="">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{paddingTop > 0 && (
<tr>
<td style={{ height: `${paddingTop}px` }} />
</tr>
)}
{virtualRows && !isPending ? (
virtualRows.map((virtualRow) => {
const row = rows[virtualRow.index] as Row<TData>;
return (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
onClick={() => onRowMouseclick && onRowMouseclick(row)}
className={classNames(
onRowMouseclick && "hover:cursor-pointer",
variant === "compact" && "!border-0"
)}>
{row.getVisibleCells().map((cell) => {
return (
<TableCell key={cell.id} className={classNames(variant === "compact" && "p-1.5")}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
);
})}
<div
className={classNames(
"grid h-[75dvh]", // Set a fixed height for the container
rest.className
)}
style={{
gridTemplateRows: "auto 1fr auto",
gridTemplateAreas: "'header' 'body' 'footer'",
...rest.style,
}}
data-testid={rest["data-testid"] ?? "data-table"}>
<div className="overflow-hidden" style={{ gridArea: "body" }}>
<div ref={tableContainerRef} onScroll={onScroll} className="scrollbar-thin h-full overflow-y-auto">
<div className="inline-block min-w-full align-middle">
<Table>
<TableHeader className="sticky top-0 z-10">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead
key={header.id}
className={classNames(
header.column.getCanSort() ? "cursor-pointer select-none" : ""
)}>
<div className="flex items-center" onClick={header.column.getToggleSortingHandler()}>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
{header.column.getIsSorted() && (
<Icon
name="arrow-up"
className="ml-2 h-4 w-4"
style={{
transform:
header.column.getIsSorted() === "asc" ? "rotate(0deg)" : "rotate(180deg)",
transition: "transform 0.2s ease-in-out",
}}
/>
)}
</div>
</TableHead>
))}
</TableRow>
);
})
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
{paddingBottom > 0 && (
<tr>
<td style={{ height: `${paddingBottom}px` }} />
</tr>
)}
</TableBody>
{tableOverlay && tableOverlay}
</Table>
))}
</TableHeader>
<TableBody>
{paddingTop > 0 && (
<tr>
<td style={{ height: `${paddingTop}px` }} />
</tr>
)}
{virtualRows && !isPending ? (
virtualRows.map((virtualRow) => {
const row = rows[virtualRow.index] as Row<TData>;
return (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
onClick={() => onRowMouseclick && onRowMouseclick(row)}
className={classNames(
onRowMouseclick && "hover:cursor-pointer",
variant === "compact" && "!border-0"
)}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className={classNames(variant === "compact" && "p-1.5")}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
);
})
) : (
<TableRow>
<TableCell colSpan={table.getAllColumns().length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
{paddingBottom > 0 && (
<tr>
<td style={{ height: `${paddingBottom}px` }} />
</tr>
)}
</TableBody>
</Table>
</div>
</div>
</div>
{/* <DataTablePagination table={table} /> */}
<DataTableSelectionBar
table={table}
actions={selectionOptions}
renderAboveSelection={renderAboveSelection}
/>
{children}
</div>
);
}
@@ -0,0 +1,27 @@
import { useCallback, useEffect } from "react";
export const useFetchMoreOnBottomReached = (
tableContainerRef: React.RefObject<HTMLDivElement>,
fetchNextPage: () => void,
isFetching: boolean,
totalFetched: number,
totalDBRowCount: number
) => {
const fetchMoreOnBottomReached = useCallback(
(containerRefElement?: HTMLDivElement | null) => {
if (containerRefElement) {
const { scrollHeight, scrollTop, clientHeight } = containerRefElement;
if (scrollHeight - scrollTop - clientHeight < 300 && !isFetching && totalFetched < totalDBRowCount) {
fetchNextPage();
}
}
},
[fetchNextPage, isFetching, totalFetched, totalDBRowCount]
);
useEffect(() => {
fetchMoreOnBottomReached(tableContainerRef.current);
}, [fetchMoreOnBottomReached, tableContainerRef]);
return fetchMoreOnBottomReached;
};
+1 -1
View File
@@ -4,7 +4,7 @@ import { classNames } from "@calcom/lib";
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="w-full overflow-auto md:overflow-visible">
<div className="w-full overflow-y-auto">
<table
ref={ref}
className={classNames("border-subtle w-full caption-bottom border text-sm", className)}
+5
View File
@@ -207,3 +207,8 @@ export { StorybookTrpcProvider } from "./components/mocks/trpc";
export { default as Icon } from "./components/icon/Icon";
export type { IconName } from "./components/icon/icon-names";
export { IconSprites } from "./components/icon/IconSprites";
export { DataTableSelectionBar } from "./components/data-table/DataTableSelectionBar";
export { DataTableToolbar } from "./components/data-table/DataTableToolbar";
export { DataTableFilters } from "./components/data-table/filters";
export { DataTablePagination } from "./components/data-table/DataTablePagination";