'use client' import React, { useState, useRef, useEffect, useCallback, useMemo, type RefObject } from 'react' import { useRouter } from 'next/navigation' import { EllipsisVertical, ChevronDown } from 'lucide-react' import type { Column, Density, TableVariant, MenuAnchor, TableShellProps } from './types' import { HIGHLIGHT, DENSITY_TD, VARIANT_TBODY, VARIANT_ROW_HOVER, VARIANT_ROW_STRIPED, VARIANT_ROW_BORDER } from './constants' import { formatValue } from './format' import { resolveId } from './utils' import Menu from './menu' function useClickOutside(ref: RefObject, cb: () => void, enabled: boolean) { useEffect(() => { if (!enabled) return function handler(e: MouseEvent) { if (ref.current && !ref.current.contains(e.target as Node)) cb() } document.addEventListener('mousedown', handler) return () => document.removeEventListener('mousedown', handler) }, [ref, cb, enabled]) } function resolveRedirectUrl( redirectPath: TableShellProps>['redirectPath'], row: Record, id: string ): string | null { if (!redirectPath) return null const cfg = typeof redirectPath === 'string' ? { path: redirectPath, key: undefined } : redirectPath if (!cfg.path) return null const rid = cfg.key ? String(row[cfg.key] ?? id) : id return cfg.path.includes('?') ? `${cfg.path}${rid}` : `${cfg.path}/${rid}` } function Cell>({ col, row, density, variant, }: { col: Column row: T density: Density variant: TableVariant }) { const value = row[col.key] const shouldTruncate = col.truncate === true const align = col.align ?? 'left' const wrapperAlign = align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : '' let content: React.ReactNode if (col.render) { content = col.render(value, row) } else if (col.highlight) { const colorName = col.highlight[String(value)] ?? col.highlight['default'] const formatted = String(formatValue(col.key, value)) if (colorName) { content = ( {formatted} ) } else { content = ( {formatted} ) } } else { const formatted = formatValue(col.key, value) content = ( {formatted === null || formatted === undefined ? '-' : String(formatted)} ) } return ( {content} ) } type BodyProps> = Pick< TableShellProps, 'data' | 'columns' | 'idKey' | 'variant' | 'density' | 'striped' | 'redirectPath' | 'onRowClick' | 'renderExpandedRow' | 'selectable' | 'selectedIds' | 'onSelectionChange' | 'menuItems' > export default function Body>({ data, columns, idKey, variant, density, striped, redirectPath, onRowClick, renderExpandedRow, selectable, selectedIds, onSelectionChange, menuItems, }: BodyProps) { const router = useRouter() const [openMenuId, setOpenMenuId] = useState(null) const [anchor, setAnchor] = useState(null) const [expandedId, setExpandedId] = useState(null) const menuRef = useRef(null) const menuWasOpenOnMouseDown = useRef(false) const closeMenu = useCallback(() => setOpenMenuId(null), []) useClickOutside(menuRef as RefObject, closeMenu, openMenuId !== null) useEffect(() => { if (openMenuId === null) return document.addEventListener('scroll', closeMenu, true) return () => document.removeEventListener('scroll', closeMenu, true) }, [closeMenu, openMenuId]) function openMenu(id: string, coords: MenuAnchor) { setAnchor(coords) setOpenMenuId(id) } const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds]) function toggleSelect(id: string) { const next = selectedSet.has(id) ? selectedIds.filter(s => s !== id) : [...selectedIds, id] onSelectionChange(next) } const hasMenu = Boolean(menuItems) const hasExpand = Boolean(renderExpandedRow) return ( {data.map((row, rowIdx) => { const id = resolveId( row as Record, idKey as string | undefined, columns as Column>[], ) const url = resolveRedirectUrl(redirectPath, row as Record, id) const isClickable = Boolean(url || onRowClick || hasExpand) const isMenuOpen = openMenuId === id const isExpanded = expandedId === id const isSelected = selectable && selectedSet.has(id) const expandedContent = renderExpandedRow?.(row) const rowClass = [ 'transition-colors duration-100', isClickable ? 'cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-login' : '', VARIANT_ROW_HOVER[variant], striped ? VARIANT_ROW_STRIPED[variant] : '', isSelected ? 'bg-login/5' : '', ].filter(Boolean).join(' ') return ( { if (url) router.prefetch(url) }} onMouseDown={() => { menuWasOpenOnMouseDown.current = openMenuId !== null }} onClick={() => { if (menuWasOpenOnMouseDown.current) { menuWasOpenOnMouseDown.current = false return } if (hasExpand) { setExpandedId(isExpanded ? null : id) return } if (onRowClick) { onRowClick(row, id); return } if (url) router.push(url) }} tabIndex={isClickable ? 0 : undefined} onKeyDown={(e) => { if (e.key === 'Enter' && e.target === e.currentTarget) e.currentTarget.click() }} onContextMenu={(e) => { if (!hasMenu) return e.preventDefault() openMenu(id, { top: e.clientY, right: window.innerWidth - e.clientX }) }} > {selectable && (
)} {columns.map((col) => ( ))} {hasExpand && (
)} {hasMenu && (
{isMenuOpen && anchor && ( {menuItems!(row, id)} )}
)} {hasExpand && isExpanded && ( e.stopPropagation()} > {expandedContent} )}
) })} ) }