All files / shared / components DataTable.tsx

77.5% Statements 62/80
74.77% Branches 83/111
73.07% Functions 19/26
78.66% Lines 59/75

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418            69x   69x 69x     256x 174x                 82x           69x   174x 174x 174x 174x 174x 2x 2x 2x 2x       2x     174x 2x 2x   174x       174x       174x 174x 174x                                                                                                                                                                                                                                                                                                                                               69x 35x   69x   76x 76x 76x     76x 76x     256x                                                   256x                                                   256x 140x   824x                       4120x                                                     116x 4x                               626x                                                             2200x 2200x   2x 14764x                                       69x     69x 69x 69x   69x   69x 69x
import type { ReactNode } from 'react'
import { useSearchParams } from 'react-router-dom'
import {
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
} from '@/components/ui/table'
import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
import { FilterBar, type FilterDef } from './FilterBar'
import { RefreshCw, Plus } from 'lucide-react'
 
const PAGE_SIZE = 25
 
export interface Column<T = Record<string, unknown>> {
  key: string
  label: string
  sortable?: boolean
  render?: (item: T) => ReactNode
}
 
interface DataTableProps<T> {
  columns: Column<T>[]
  data: T[] | undefined
  isLoading?: boolean
  error?: Error | null
  prefix?: string
  sortKey?: string
  sortOrder?: 'asc' | 'desc'
  onSort?: (key: string) => void
  onRowClick?: (item: T) => void
  onRetry?: () => void
  onRefresh?: () => void
  isRefreshing?: boolean
  hasMore?: boolean
  totalEstimate?: number
  entityNaEme?: string
  add?: {
    onAdd: () => void
    label?: string
    icon?: ReactNode
    disabled?: boolean
    visible?: boolean
  }
  extraActions?: ReactNode[]
  sse?: { enabled: true; fixedParams?: Record<string, string> }
  sseStatus?: 'connecting' | 'connected' | 'disconnected' | 'connection-lost'
  onSseReconnect?: () => void
  filters?: FilterDef[]
  filterValues?: Record<string, string | undefined>
  onFilterChange?: (key: string, value: string | string[] | undefined) => void
  onFiltersClear?: () => void
  emptyMessage?: string
  emptyAction?: ReactNode
}
 
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
function DataTable<T>(props: DataTableProps<T>) {
  if (props.prefix) {
    return <DataTableWithPagination {...props} prefix={props.prefix} />
  }
  return <DataTableContent {...props} />
}
 
interface PaginationProps<T> extends DataTableProps<T> {
  prefix: string
}
 
function DataTableWithPagination<T>({
  prefix,
  columns,
  data,
  isLoading,
  error,
  sortKey,
  sortOrder = 'asc',
  onSort,
  onRowClick,
  onRetry,
  onRefresh,
  isRefreshing,
  hasMore,
  totalEstimate,
  entityName,
  add,
  extraActions,
  sse,
  sseStatus,
  onSseReconnect,
  filters,
  filterValues,
  onFilterChange,
  onFiltersClear,
  emptyMessage,
  emptyAction,
}: PaginationProps<T>) {
  const [searchParams, setSearchParams] = useSearchParams()
  const offsetKey = `${prefix}_offset`
  const offset = parseInt(searchParams.get(offsetKey) ?? '0', 10)
 
  const setOffset = (value: number) => {
    setSearchParams(
      (prev) => {
        const next = new URLSearchParams(prev)
        if (value <= 0) {
          next.delete(offsetKey)
        } else {
          next.set(offsetKey, String(value))
        }
        return next
      },
      { replace: true },
    )
  }
 
  const handleFilterChange = (key: string, value: string | string[] | undefined) => {
    setOffset(0)
    onFilterChange?.(key, value)
  }
 
  const handleFiltersClear = () => {
    setOffset(0)
    onFiltersClear?.()
  }
 
  const handleSort = (key: string) => {
    setOffset(0)
    onSort?.(key)
  }
 
  const activeFilters = filterValues
    ? Object.entries(filterValues).some(
        ([_k, v]) => v !== undefined && v !== '',
      )
    : false
 
  const showRefresh = !sse && onRefresh
 
  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          {filters && filterValues && onFilterChange && onFiltersClear && (
            <FilterBar
              filters={filters}
              values={filterValues}
              onChange={handleFilterChange}
              onClear={handleFiltersClear}
            />
          )}
        </div>
        <div className="flex items-center gap-2">
          {extraActions?.map((action, i) => (
            <div key={i}>{action}</div>
          ))}
          {showRefresh && (
            <Button
              variant="ghost"
              size="icon-sm"
              onClick={onRefresh}
              disabled={isRefreshing}
              aria-label="Refresh"
              type="button"
            >
              <RefreshCw
                className={isRefreshing ? 'animate-spin' : ''}
              />
            </Button>
          )}
          {add && add.visible !== false && (
            <Button
              variant="default"
              size="sm"
              onClick={add.onAdd}
              disabled={add.disabled}
              type="button"
            >
              {add.icon ?? <Plus />}
              {add.label ?? (entityName ? `+ New ${entityName}` : '+ New')}
            </Button>
          )}
        </div>
      </div>
 
      <DataTableContent
        columns={columns}
        data={data}
        isLoading={isLoading}
        error={error}
        emptyMessage={
          activeFilters
            ? `No ${entityName ?? 'items'} match current filters`
            : emptyMessage ?? `No ${entityName ?? 'data'} yet`
        }
        emptyAction={activeFilters ? (
          <Button variant="ghost" size="sm" onClick={handleFiltersClear}>
            Clear Filters
          </Button>
        ) : (
          emptyAction ??
          (add && add.visible !== false ? (
            <Button variant="default" size="sm" onClick={add.onAdd} disabled={add.disabled} type="button">
              {add.icon ?? <Plus />}
              {add.label ?? (entityName ? `+ New ${entityName}` : '+ New')}
            </Button>
          ) : undefined)
        )}
        sortKey={sortKey}
        sortOrder={sortOrder}
        onSort={handleSort}
        onRetry={onRetry}
        onRowClick={onRowClick}
        sse={sse}
        sseStatus={sseStatus}
        onSseReconnect={onSseReconnect}
      />
 
      {data && data.length > 0 && (
        <div className="flex items-center justify-between">
          <span className="text-sm text-muted-foreground">
            {formatPaginationDisplay(offset, data.length, hasMore, totalEstimate)}
          </span>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
              disabled={offset <= 0}
              type="button"
            >
              Previous
 I           </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setOffset(offset + PAGE_SIZE)}
              disabled={!hasMore}
              type="button"
 I           >
              Next
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
 
function formatPaginationDisplay(
  offset: number,
  returned: number,
  hasMore: boolean | undefined,
  totalEstimate: number | undefined,
): string {
  const start = offset + 1
  const end = offset + returned
  if (totalEstimate !== undefined && totalEstimate > 0) {
    return `Showing ${start}\u2013${end} of ${totalEstimate}`
  }
  const suffix = hasMore ? '+' : ''
  return `Showing ${start}\u2013${end}${suffix}`
}
 
interface ContentProps<T> {
 I columns: Column<T>[]
  data: T[] | undefined
  isLoading?: boolean
  error?: Error | null
  sortKey?: string
  sortOrder?: 'asc' | 'desc'
  onSort?: (key: string) => void
  onRetry?: () => void
  onRowClick?: (item: T) => void
  emptyMessage?: string
  emptyAction?: ReactNode
  sse?: { enabled: true; fixedParams?: Record<string, string> }
  sseStatus?: 'connecting' | 'connected' | 'disconnected' | 'connection-lost'
  onSseReconnect?: () => void
}
 
function DataTableContent<T>({
  columns,
  data,
  isLoading,
  error,
  emptyMessage = 'No data',
  emptyAction,
  sortKey,
  sortOrder = 'asc',
  onSort,
  onRetry,
  onRowClick,
  sse,
  sseStatus,
  onSseReconnect,
}: ContentProps<T>) {
  if (error) {
    return (
      <div className="flex flex-col items-center gap-4 py-12 text-center">
        <p className="text-destructive">
          {error.message || 'Failed to load'}
        </p>
        {onRetry && (
          <Button variant="outline" onClick={onRetry} type="button">
            Retry
          </Button>
        )}
      </div>
    )
  }
 
  if (sse && sseStatus === 'connection-lost') {
    return (
      <div className="flex flex-col items-center gap-4 py-12 text-center">
        <p className="text-muted-foreground">Connection lost</p>
        {onSseReconnect && (
          <Button variant="outline" onClick={onSseReconnect} type="button">
            Reconnect
          </Button>
        )}
      </div>
    )
  }
 
  if (isLoading) {
    return (
      <div data-testid="data-table-loading">
        <Table>
          <TableHeader>
            <TableRow>
              {columns.map((col) => (
                <TableHead key={col.key}>{col.label}</TableHead>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {Array.from({ length: 5 }).map((_, i) => (
              <TableRow key={i}>
                {columns.map((col) => (
                  <TableCell key={col.key}>
                    <Skeleton className="h-4 w-full" />
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    )
  }
 
  if (!data || data.length === 0) {
    return (
      <div className="flex flex-col items-center gap-4 py-12 text-center">
        <p className="text-muted-foreground">{emptyMessage}</p>
        {emptyAction}
      </div>
    )
  }
 
  return (
    <Table>
      <TableHeader>
        <TableRow>
          {columns.map((col) => (
            <TableHead
              key={col.key}
              className={
                col.sortable
                  ? 'cursor-pointer select-none hover:text-foreground'
                  : ''
              }
              onClick={() => col.sortable && onSort?.(col.key)}
            >
              <span className="inline-flex items-center gap-1">
                {col.label}
                {col.sortable && sortKey === col.key && (
                  <span className="text-xs">
                    {sortOrder === 'asc' ? '\u25B2' : '\u25BC'}
                  </span>
                )}
              </span>
            </TableHead>
          ))}
        </TableRow>
      </TableHeader>
      <TableBody>
        {data.map((item, i) => {
          const id = (item as Record<string, unknown>).id as string | undefined
          return (
            <TableRow
              key={id ?? i}
              className={
                onRowClick ? 'cursor-pointer hover:bg-accent/50' : ''
              }
              onClick={() => onRowClick?.(item)}
            >
              {columns.map((col) => (
                <TableCell key={col.key}>
                  {col.render
                    ? col.render(item)
                    : ((item as Record<string, unknown>)[col.key] as ReactNode) ??
                      '\u2014'}
                </TableCell>
              ))}
            </TableRow>
          )
        })}
      </TableBody>
    </Table>
  )
}
 
Eexport { DataTable }
I