refactor: add reusable select controls and enhance data table columns
This commit is contained in:
48
src/components/data-table/ColumnViewOptions.tsx
Normal file
48
src/components/data-table/ColumnViewOptions.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import type { Table } from '@tanstack/react-table';
|
||||
import { Columns3 } from 'lucide-react';
|
||||
|
||||
import { MultiSelectPopover } from '@/components/form';
|
||||
|
||||
function getColumnLabel(column: { id: string; columnDef: { header?: unknown } }) {
|
||||
const header = column.columnDef.header;
|
||||
return typeof header === 'string' ? header : column.id;
|
||||
}
|
||||
|
||||
export function ColumnViewOptions<TData>({ table }: { table: Table<TData> }) {
|
||||
const columns = useMemo(
|
||||
() =>
|
||||
table
|
||||
.getAllLeafColumns()
|
||||
.filter((column) => column.id !== 'select')
|
||||
.map((column) => ({
|
||||
column,
|
||||
value: column.id,
|
||||
label: getColumnLabel(column),
|
||||
disabled: !column.getCanHide(),
|
||||
})),
|
||||
[table],
|
||||
);
|
||||
const visibleColumnIds = columns
|
||||
.filter(({ column }) => column.getIsVisible())
|
||||
.map(({ value }) => value);
|
||||
|
||||
return (
|
||||
<MultiSelectPopover
|
||||
label="Columns"
|
||||
icon={<Columns3 />}
|
||||
options={columns}
|
||||
values={visibleColumnIds}
|
||||
searchPlaceholder="Search columns"
|
||||
emptyMessage="No columns found."
|
||||
onValuesChange={(nextValues) => {
|
||||
const visibleValues = new Set(nextValues);
|
||||
columns.forEach(({ column, value }) => {
|
||||
column.toggleVisibility(visibleValues.has(value));
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ interface TopHeaderProps {
|
||||
onAddNew?: () => void;
|
||||
addButtonText?: string;
|
||||
toolbar?: React.ReactNode;
|
||||
tableTools?: React.ReactNode;
|
||||
}
|
||||
|
||||
const TopHeader = ({
|
||||
@@ -17,6 +18,7 @@ const TopHeader = ({
|
||||
onAddNew,
|
||||
addButtonText = 'Add New',
|
||||
toolbar,
|
||||
tableTools,
|
||||
}: TopHeaderProps) => {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -34,7 +36,14 @@ const TopHeader = ({
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
{toolbar ? <div>{toolbar}</div> : null}
|
||||
{(toolbar || tableTools) && (
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
||||
<div className="min-w-0 flex-1">{toolbar}</div>
|
||||
{tableTools ? (
|
||||
<div className="flex shrink-0 justify-end">{tableTools}</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -12,14 +12,16 @@ import {
|
||||
ArrowUpNarrowWide,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { getPinnedColumnStyles } from './columnStyles';
|
||||
|
||||
const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
|
||||
return (
|
||||
<ShadTableHeader className="sticky top-0 z-10 bg-card">
|
||||
<ShadTableHeader className="sticky top-0 z-20 bg-card">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
const canSort = header.column.getCanSort();
|
||||
const canResize = header.column.getCanResize();
|
||||
const sortDirection = header.column.getIsSorted();
|
||||
const SortIcon =
|
||||
sortDirection === 'asc'
|
||||
@@ -31,17 +33,20 @@ const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
colSpan={header.colSpan}
|
||||
style={getPinnedColumnStyles(header.column, 'header')}
|
||||
onClick={
|
||||
canSort ? header.column.getToggleSortingHandler() : undefined
|
||||
}
|
||||
className={cn(
|
||||
'h-10 bg-card px-2 text-foreground transition-colors',
|
||||
'h-10 max-w-0 overflow-hidden bg-card px-2 text-foreground transition-colors',
|
||||
canSort && 'cursor-pointer select-none hover:bg-muted/60',
|
||||
sortDirection && 'bg-muted/70',
|
||||
header.column.getIsPinned() && 'shadow-sm',
|
||||
)}
|
||||
>
|
||||
{header.isPlaceholder ? null : (
|
||||
<div className="flex min-h-8 w-full items-center justify-between gap-2">
|
||||
<div className="relative flex min-h-8 w-full items-center justify-between gap-2">
|
||||
<span className="truncate">
|
||||
{flexRender(
|
||||
header.column.columnDef.header,
|
||||
@@ -56,6 +61,19 @@ const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground/60',
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
{canResize ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Resize column"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onMouseDown={header.getResizeHandler()}
|
||||
onTouchStart={header.getResizeHandler()}
|
||||
className={cn(
|
||||
'absolute -right-2 top-0 h-full w-1 cursor-col-resize touch-none select-none rounded bg-border opacity-0 transition-opacity hover:opacity-100',
|
||||
header.column.getIsResizing() && 'opacity-100',
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
19
src/components/data-table/columnStyles.ts
Normal file
19
src/components/data-table/columnStyles.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { Column } from '@tanstack/react-table';
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
export function getPinnedColumnStyles<TData>(
|
||||
column: Column<TData, unknown>,
|
||||
variant: 'header' | 'cell' = 'cell',
|
||||
): CSSProperties {
|
||||
const pinned = column.getIsPinned();
|
||||
|
||||
return {
|
||||
width: column.getSize(),
|
||||
minWidth: column.getSize(),
|
||||
left: pinned === 'left' ? `${column.getStart('left')}px` : undefined,
|
||||
right: pinned === 'right' ? `${column.getAfter('right')}px` : undefined,
|
||||
position: pinned ? 'sticky' : 'relative',
|
||||
// Header cells must sit above body cells when both are sticky (vertical + pin).
|
||||
zIndex: pinned ? (variant === 'header' ? 30 : 10) : undefined,
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,10 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
ColumnDef,
|
||||
ColumnPinningState,
|
||||
ColumnSizingState,
|
||||
SortingState,
|
||||
VisibilityState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
@@ -14,11 +17,23 @@ import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import type { PermissionInput } from '@/hooks/usePermissions';
|
||||
import { PermissionGuard } from '@/guards';
|
||||
|
||||
import TopHeader from './Header';
|
||||
import TableHeader from './TableHeader';
|
||||
import { TableFooter } from './Footer';
|
||||
import { TableActionButton } from './TableActionButton';
|
||||
import { ColumnViewOptions } from './ColumnViewOptions';
|
||||
import { getPinnedColumnStyles } from './columnStyles';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function shouldTruncateCell(column: { id: string; columnDef: { meta?: unknown } }) {
|
||||
if (column.id === 'actions') return false;
|
||||
const meta = column.columnDef.meta as { disableTruncate?: boolean } | undefined;
|
||||
return !meta?.disableTruncate;
|
||||
}
|
||||
|
||||
export type ColumnAlign = 'left' | 'right';
|
||||
|
||||
export interface DataTableAction<TData> {
|
||||
label: string | ((item: TData) => string);
|
||||
@@ -37,6 +52,9 @@ export interface DataTableProps<TData, TValue> {
|
||||
addButtonText?: string;
|
||||
isLoading?: boolean;
|
||||
actions?: DataTableAction<TData>[];
|
||||
/** Sticky-pin the actions column (use with actionsAlign). */
|
||||
actionsSticky?: boolean;
|
||||
actionsAlign?: ColumnAlign;
|
||||
toolbar?: React.ReactNode;
|
||||
emptyTitle?: string;
|
||||
emptyDescription?: string;
|
||||
@@ -49,9 +67,32 @@ export interface DataTableProps<TData, TValue> {
|
||||
};
|
||||
sorting?: SortingState;
|
||||
onSortingChange?: (sorting: SortingState) => void;
|
||||
enableColumnControls?: boolean;
|
||||
/** Minimum width (px) for every column unless overridden in the column def. */
|
||||
minColumnSize?: number;
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
export function DataTable<TData, TValue>(props: DataTableProps<TData, TValue>) {
|
||||
const { actions, ...rest } = props;
|
||||
|
||||
if (!actions?.length) {
|
||||
return <DataTableContent {...props} />;
|
||||
}
|
||||
|
||||
const actionPermissions = actions.map((action) => action.permission);
|
||||
|
||||
return (
|
||||
<PermissionGuard
|
||||
permissions={actionPermissions}
|
||||
match="any"
|
||||
fallback={<DataTableContent {...rest} actions={undefined} />}
|
||||
>
|
||||
<DataTableContent {...props} />
|
||||
</PermissionGuard>
|
||||
);
|
||||
}
|
||||
|
||||
function DataTableContent<TData, TValue>({
|
||||
columns: initialColumns,
|
||||
data,
|
||||
title,
|
||||
@@ -59,14 +100,21 @@ export function DataTable<TData, TValue>({
|
||||
addButtonText,
|
||||
isLoading = false,
|
||||
actions,
|
||||
actionsSticky = false,
|
||||
actionsAlign = 'right',
|
||||
toolbar,
|
||||
emptyTitle = 'No results found.',
|
||||
emptyDescription = 'Try adjusting your filters or search terms.',
|
||||
pagination,
|
||||
sorting: controlledSorting,
|
||||
onSortingChange,
|
||||
enableColumnControls = true,
|
||||
minColumnSize = 120,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [rowSelection, setRowSelection] = React.useState({});
|
||||
const [columnVisibility, setColumnVisibility] =
|
||||
React.useState<VisibilityState>({});
|
||||
const [columnSizing, setColumnSizing] = React.useState<ColumnSizingState>({});
|
||||
const [internalSorting, setInternalSorting] = React.useState<SortingState>(
|
||||
[],
|
||||
);
|
||||
@@ -91,11 +139,16 @@ export function DataTable<TData, TValue>({
|
||||
if (actions?.length) {
|
||||
cols.push({
|
||||
id: 'actions',
|
||||
size: 110,
|
||||
minSize: 90,
|
||||
enableHiding: false,
|
||||
enableSorting: false,
|
||||
enablePinning: false,
|
||||
header: () => <div className="text-right">Actions</div>,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original;
|
||||
return (
|
||||
<div className="flex justify-end gap-2">
|
||||
<div className="flex justify-start gap-2">
|
||||
{actions.map((action) => {
|
||||
const label =
|
||||
typeof action.label === 'function'
|
||||
@@ -126,14 +179,31 @@ export function DataTable<TData, TValue>({
|
||||
return cols;
|
||||
}, [actions, initialColumns]);
|
||||
|
||||
const columnPinning = React.useMemo<ColumnPinningState>(
|
||||
() =>
|
||||
actionsSticky && actions?.length
|
||||
? { [actionsAlign]: ['actions'] }
|
||||
: {},
|
||||
[actions, actionsAlign, actionsSticky],
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onColumnSizingChange: setColumnSizing,
|
||||
onSortingChange: handleSortingChange,
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
enableColumnResizing: true,
|
||||
enableColumnPinning: true,
|
||||
columnResizeMode: 'onChange',
|
||||
defaultColumn: {
|
||||
minSize: minColumnSize,
|
||||
size: minColumnSize,
|
||||
},
|
||||
manualPagination: !!pagination,
|
||||
manualSorting: isManualSorting,
|
||||
pageCount: pagination?.totalItems
|
||||
@@ -141,6 +211,9 @@ export function DataTable<TData, TValue>({
|
||||
: -1,
|
||||
state: {
|
||||
rowSelection,
|
||||
columnVisibility,
|
||||
columnPinning,
|
||||
columnSizing,
|
||||
sorting,
|
||||
pagination: pagination
|
||||
? {
|
||||
@@ -177,12 +250,16 @@ export function DataTable<TData, TValue>({
|
||||
onAddNew={onAddNew}
|
||||
addButtonText={addButtonText}
|
||||
toolbar={toolbar}
|
||||
tableTools={
|
||||
enableColumnControls ? <ColumnViewOptions table={table} /> : null
|
||||
}
|
||||
/>
|
||||
|
||||
<div>
|
||||
<Table
|
||||
containerClassName="max-h-[calc(100vh-350px)] overflow-y-auto"
|
||||
className="border-separate border-spacing-0"
|
||||
className="table-fixed border-separate border-spacing-0"
|
||||
style={{ width: '100%', minWidth: table.getTotalSize() }}
|
||||
>
|
||||
<TableHeader table={table} />
|
||||
<TableBody>
|
||||
@@ -202,14 +279,30 @@ export function DataTable<TData, TValue>({
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && 'selected'}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext(),
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
{row.getVisibleCells().map((cell) => {
|
||||
const truncate = shouldTruncateCell(cell.column);
|
||||
const content = flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext(),
|
||||
);
|
||||
|
||||
return (
|
||||
<TableCell
|
||||
key={cell.id}
|
||||
style={getPinnedColumnStyles(cell.column)}
|
||||
className={cn(
|
||||
'max-w-0 overflow-hidden',
|
||||
cell.column.getIsPinned() && 'bg-card',
|
||||
)}
|
||||
>
|
||||
{truncate ? (
|
||||
<div className="truncate">{content}</div>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
</TableCell>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
|
||||
154
src/components/form/MultiSelectPopover.tsx
Normal file
154
src/components/form/MultiSelectPopover.tsx
Normal file
@@ -0,0 +1,154 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Check, ChevronDown } from 'lucide-react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface MultiSelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
interface MultiSelectPopoverProps {
|
||||
label: string;
|
||||
icon?: React.ReactNode;
|
||||
options: MultiSelectOption[];
|
||||
values: string[];
|
||||
onValuesChange: (values: string[]) => void;
|
||||
searchPlaceholder?: string;
|
||||
emptyMessage?: string;
|
||||
align?: 'start' | 'center' | 'end';
|
||||
}
|
||||
|
||||
function checkboxClass(checked: boolean) {
|
||||
return cn(
|
||||
'flex size-4 shrink-0 items-center justify-center rounded border',
|
||||
checked && 'border-primary bg-primary text-primary-foreground',
|
||||
);
|
||||
}
|
||||
|
||||
export function MultiSelectPopover({
|
||||
label,
|
||||
icon,
|
||||
options,
|
||||
values,
|
||||
onValuesChange,
|
||||
searchPlaceholder = 'Search',
|
||||
emptyMessage = 'No options found.',
|
||||
align = 'end',
|
||||
}: MultiSelectPopoverProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
const selectedValues = useMemo(() => new Set(values), [values]);
|
||||
const selectableOptions = options.filter((option) => !option.disabled);
|
||||
const areAllSelected =
|
||||
selectableOptions.length > 0 &&
|
||||
selectableOptions.every((option) => selectedValues.has(option.value));
|
||||
const filteredOptions = useMemo(() => {
|
||||
const term = search.trim().toLowerCase();
|
||||
if (!term) return options;
|
||||
return options.filter((option) =>
|
||||
option.label.toLowerCase().includes(term),
|
||||
);
|
||||
}, [options, search]);
|
||||
|
||||
const toggleValue = (value: string) => {
|
||||
const nextValues = new Set(values);
|
||||
if (nextValues.has(value)) {
|
||||
nextValues.delete(value);
|
||||
} else {
|
||||
nextValues.add(value);
|
||||
}
|
||||
onValuesChange(Array.from(nextValues));
|
||||
};
|
||||
|
||||
const toggleAll = () => {
|
||||
const nextValues = new Set(values);
|
||||
|
||||
selectableOptions.forEach((option) => {
|
||||
if (areAllSelected) {
|
||||
nextValues.delete(option.value);
|
||||
} else {
|
||||
nextValues.add(option.value);
|
||||
}
|
||||
});
|
||||
|
||||
onValuesChange(Array.from(nextValues));
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button type="button" variant="outline" size="sm">
|
||||
{icon}
|
||||
{label}
|
||||
<Badge variant="secondary">{values.length}</Badge>
|
||||
<ChevronDown />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align={align} className="w-60 p-0">
|
||||
<div className="flex items-center gap-2 border-b p-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleAll}
|
||||
aria-label={`Toggle all ${label}`}
|
||||
className="shrink-0 rounded-md p-0.5 hover:bg-muted"
|
||||
>
|
||||
<span className={checkboxClass(areAllSelected)}>
|
||||
{areAllSelected ? <Check className="size-3" /> : null}
|
||||
</span>
|
||||
</button>
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder={searchPlaceholder}
|
||||
className="flex-1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="max-h-72 overflow-y-auto p-2">
|
||||
{filteredOptions.length ? (
|
||||
filteredOptions.map((option) => {
|
||||
const checked = selectedValues.has(option.value);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={option.value}
|
||||
className="flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
disabled={option.disabled}
|
||||
onClick={() => toggleValue(option.value)}
|
||||
className={cn(
|
||||
'flex min-w-0 flex-1 items-center gap-2 text-left',
|
||||
option.disabled && 'cursor-not-allowed opacity-60',
|
||||
)}
|
||||
>
|
||||
<span className={checkboxClass(checked)}>
|
||||
{checked ? <Check className="size-3" /> : null}
|
||||
</span>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div className="px-2 py-6 text-center text-muted-foreground">
|
||||
{emptyMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
export { FormField } from './FormField';
|
||||
export { MultiSelectPopover } from './MultiSelectPopover';
|
||||
export type { MultiSelectOption } from './MultiSelectPopover';
|
||||
export { PasswordField } from './PasswordField';
|
||||
|
||||
Reference in New Issue
Block a user