"use client" import * as React from "react" import { cn } from "../../lib/utils" import { railTriggerProps } from "../ui/floating-sheet-panel" import { Checkbox } from "../ui/checkbox" import { RowReorderHandle, ROW_DRAG_COLUMN_KEY, type RowMove } from "./row-reorder-handle" import { getConditionalCellBackground } from "../../lib/conditional-rule-match" import type { ColumnDef, ConditionalRule } from "./types" import type { useTableState } from "./use-table-state" import { CELL_CLIP_FOCUS_INSET_CLASS, CONTROL_COLUMN_PADDING, SPLIT_MAX_VISIBLE, isControlColumn, stickyShadow } from "./table-helpers" export type RowDragState = { id: string | number overId: string | number | null pos: "before" | "after" } | null export interface DataTableGroupRowsProps> { /** The rows to draw — one group's worth, or the whole page when ungrouped. */ groupRows: TData[] state: ReturnType> columns: ColumnDef[] selectable: boolean onRowClick?: (row: TData) => void /** Whether rows open a rail on this hub (a defined `openRowId`). */ rowsOpenRail: boolean openRowId?: string | number | null conditionalRules?: ConditionalRule[] getRowIdProp?: (row: TData, index: number) => string | number getRowSelectionLabel?: (row: TData, index: number) => string | undefined onRowsReorder?: unknown rowReorderDisabledReason?: string rowDrag: RowDragState rowDragRef: React.MutableRefObject setRowDrag: (next: RowDragState) => void setRowDragBoth: (next: RowDragState) => void commitRowMove: (scope: TData[], from: number, to: number) => void moveRowBy: (scope: TData[], from: number, move: RowMove) => void cellStyle: (key: string) => React.CSSProperties splitCountFor: (row: TData) => number firstRightPinKey?: string lastLeftPinKey?: string } /** The ``s for one group of rows: selection, open-row marker, cells, and row drag. */ export function DataTableGroupRows>({ groupRows, state, columns, selectable, onRowClick, rowsOpenRail, openRowId, conditionalRules, getRowIdProp, getRowSelectionLabel, onRowsReorder, rowReorderDisabledReason, rowDrag, rowDragRef, setRowDrag, setRowDragBoth, commitRowMove, moveRowBy, cellStyle, splitCountFor, firstRightPinKey, lastLeftPinKey, }: DataTableGroupRowsProps) { const { colWrap, displayCols, effectivePins, getRowId, rowHeight, selected, setSelected, showGridlines, toggleRow } = state return ( <> {groupRows.map((row, rowIndex) => { const rowId = getRowId(row, rowIndex, getRowIdProp) const isSelected = selected.has(rowId) const isOpen = rowsOpenRail && rowId === openRowId const rowClickable = Boolean(onRowClick) || selectable function handleRowClick(e: React.MouseEvent) { if (!rowClickable) return const el = e.target as HTMLElement | null if (!el) return if (el.closest("button, a, input, textarea, select, label, [role='checkbox']")) return if (onRowClick) { onRowClick(row) return } if (selectable) { toggleRow(rowId) } } return ( ).isNew) || undefined} // Selection and openness are different facts about a row and // it can hold both, so they get different channels: the tint // stays selection's, the leading bar (drawn by the first // cell) is openness'. `aria-current` carries the same news to // a screen reader, which cannot see either. data-open={isOpen || undefined} aria-current={isOpen || undefined} data-row-drop={rowDrag?.overId === rowId ? rowDrag.pos : undefined} data-row-dragging={rowDrag?.id === rowId || undefined} onDragOver={onRowsReorder && !rowReorderDisabledReason ? e => { const drag = rowDragRef.current if (!drag) return e.preventDefault() e.dataTransfer.dropEffect = "move" const rect = e.currentTarget.getBoundingClientRect() const pos = e.clientY < rect.top + rect.height / 2 ? "before" : "after" if (drag.overId !== rowId || drag.pos !== pos) { setRowDragBoth({ ...drag, overId: rowId, pos }) } } : undefined} onDrop={onRowsReorder && !rowReorderDisabledReason ? e => { const drag = rowDragRef.current if (!drag) return e.preventDefault() const from = groupRows.findIndex((r, i) => getRowId(r, i, getRowIdProp) === drag.id) let to = rowIndex + (drag.pos === "after" ? 1 : 0) if (from < to) to -= 1 setRowDragBoth(null) commitRowMove(groupRows, from, to) } : undefined} {...(rowsOpenRail ? railTriggerProps() : {})} className={cn( "group/row transition-colors", "data-[row-dragging]:opacity-50", "hover:bg-dt-row-hover", isSelected && "bg-dt-row-selected text-dt-row-selected-fg", rowClickable && "cursor-pointer", Boolean((row as Record).isNew) && "bg-dt-new-row-bg", // Skip layout/paint for offscreen rows (MessageScroller pattern). "[contain-intrinsic-size:auto_2.75rem] [content-visibility:auto]", )} > {displayCols.map((col, colIndex) => { const isPinned = !!effectivePins[col.key] const wrap = colWrap[col.key] const isEdgePin = col.key === lastLeftPinKey || col.key === firstRightPinKey const rowPy = rowHeight === "compact" ? "py-1" : rowHeight === "comfortable" ? "py-4" : "py-2.5" const cs = cellStyle(col.key) const tdBase = cn( `${isControlColumn(col.key) ? CONTROL_COLUMN_PADDING : "px-3"} ${rowPy} align-middle max-w-0`, showGridlines && !isEdgePin && "border-e border-border last:border-e-0", "border-b border-border group-last/row:border-b-0", "group-data-[row-drop=before]/row:shadow-[inset_0_2px_0_0_var(--ring)]", "group-data-[row-drop=after]/row:shadow-[inset_0_-2px_0_0_var(--ring)]", // Open-row bar. A `` cannot carry a reliable border // under `border-collapse`, so the leading cell draws it. // A shape rather than a fill keeps it legible next to the // selection tint and survives forced-colors, where fills // are replaced by system colours. colIndex === 0 && [ "relative", "group-data-[open]/row:before:absolute group-data-[open]/row:before:inset-y-0", "group-data-[open]/row:before:start-0 group-data-[open]/row:before:w-0.5", "group-data-[open]/row:before:bg-dt-row-open-marker", ], isPinned && [ "z-20 pinned-cell relative", "bg-dt-row-bg", "group-data-[new]/row:bg-dt-new-row-bg", "group-data-[state=selected]/row:bg-dt-row-selected", "group-hover/row:bg-dt-row-hover", "group-data-[new]/row:group-hover/row:bg-dt-row-hover", isEdgePin && stickyShadow(effectivePins[col.key]), ] ) const conditionalBg = getConditionalCellBackground( row, col.key, conditionalRules, columns, ) const tdStyle = conditionalBg ? { ...cs, background: conditionalBg } : cs const rowHandle = onRowsReorder && col.key === ROW_DRAG_COLUMN_KEY ? ( 0} canMoveDown={rowIndex < groupRows.length - 1} onMove={move => moveRowBy(groupRows, rowIndex, move)} onDragStart={e => { e.dataTransfer.effectAllowed = "move" const tr = e.currentTarget.closest("tr") if (tr) e.dataTransfer.setDragImage(tr, 0, 0) rowDragRef.current = { id: rowId, overId: null, pos: "before" } // Re-rendering inside dragstart makes Chrome cancel the drag. window.setTimeout(() => setRowDrag(rowDragRef.current), 0) }} onDragEnd={() => setRowDragBoth(null)} /> ) : null // Special synthetic columns if (col.key === ROW_DRAG_COLUMN_KEY) { return ( {rowHandle} ) } if (col.key === "select") { const selectionLabel = getRowSelectionLabel?.(row, rowIndex) const ariaLabel = selectionLabel ? `Select row, ${selectionLabel}` : `Select row ${rowIndex + 1}` return ( {selectable && ( // inline-flex: inline elements inside are never // stretched by table-cell height in Chrome/Safari/Firefox. // Block-level flex/grid always inherits full cell height at zoom. e.stopPropagation()} > toggleRow(rowId)} aria-label={ariaLabel} onClick={e => e.stopPropagation()} /> )} ) } // When wrap is on, override every common truncation // pattern any cell renderer might use: // • `.truncate` → single-line + ellipsis // • `.line-clamp-N` → multi-line + ellipsis // • `.whitespace-nowrap` → forced single line // We also flip the inner wrapper from `overflow-hidden` // to `overflow-visible` so the cell can grow vertically. // `wrap-break-word` breaks long tokens (camelCase IDs, URLs) // that `whitespace-normal` alone would bleed into neighbors. const wrapCellContentClass = "min-w-0 break-words wrap-break-word" const wrapOverride = wrap && cn( wrapCellContentClass, "[&_.truncate]:!whitespace-normal [&_.truncate]:!overflow-visible [&_.truncate]:!text-clip", "[&_.truncate]:break-words [&_.truncate]:wrap-break-word", "[&_[class*=line-clamp-]]:!line-clamp-none", "[&_[class*=line-clamp-]]:break-words [&_[class*=line-clamp-]]:wrap-break-word", "[&_.whitespace-nowrap]:!whitespace-normal", ) const innerWrap = wrap ? wrapCellContentClass : cn("min-w-0 overflow-hidden", CELL_CLIP_FOCUS_INSET_CLASS) if (col.split) { const items = col.split.items(row) const subCount = splitCountFor(row) const max = col.split.maxVisible ?? SPLIT_MAX_VISIBLE const overflow = items.length > max ? items.length - (max - 1) : 0 const shown = overflow ? items.slice(0, max - 1) : items return (
    {Array.from({ length: subCount }, (_, si) => { const isMore = overflow > 0 && si === shown.length const filled = si < shown.length return (
  • {filled ? (
    {col.split!.cell ? col.split!.cell(row, items[si], si) : String(items[si] ?? "")}
    ) : isMore ? ( +{overflow} more ) : null}
  • ) })}
) } // Custom cell renderer if (col.cell) { return (
{col.cell(row, { rowIndex, selected: isSelected, onSelect: checked => checked ? setSelected(prev => new Set([...prev, rowId])) : toggleRow(rowId), })}
) } // Default: render string value with optional truncation const rawVal = String(row[col.key] ?? "") return (
{rawVal}
) })} ) })} ) }