1 "use client"
2
3 import * as React from "react"
4
5 import { Table } from "@/components/table"
6 import { flexRender } from "@tanstack/react-table"
7 import {
8 DndContext,
9 closestCenter,
10 KeyboardSensor,
11 PointerSensor,
12 useSensor,
13 useSensors,
14 DragEndEvent,
15 } from "@dnd-kit/core"
16 import {
17 arrayMove,
18 SortableContext,
19 sortableKeyboardCoordinates,
20 horizontalListSortingStrategy,
21 } from "@dnd-kit/sortable"
22
23 import { useDataTableContext } from "@/blocks/data-table/context/use-data-table-context"
24 import { Skeleton } from "@/components/skeleton"
25 import { Text } from "@/components/text"
26 import { Tooltip } from "@/components/tooltip"
27 import { clx } from "@/utils/clx"
28 import {
29 DataTableEmptyState,
30 DataTableEmptyStateContent,
31 DataTableEmptyStateProps,
32 } from "../types"
33 import { DataTableSortingIcon } from "./data-table-sorting-icon"
34 import { DataTableSortableHeaderCell } from "./data-table-sortable-header-cell"
35 import { DataTableNonSortableHeaderCell } from "./data-table-non-sortable-header-cell"
36
37 interface DataTableTableProps {
38 /**
39 * The empty state to display when the table is empty.
40 */
41 emptyState?: DataTableEmptyStateProps
42 }
43
44 /**
45 * This component renders the table in a data table, supporting advanced features.
46 */
47 const DataTableTable = (props: DataTableTableProps) => {
48 const hoveredRowId = React.useRef<string | null>(null)
49 const isKeyDown = React.useRef(false)
50
51 const [showStickyBorder, setShowStickyBorder] = React.useState(false)
52 const scrollableRef = React.useRef<HTMLDivElement>(null)
53
54 const { instance } = useDataTableContext()
55
56 const pageIndex = instance.pageIndex
57
58 const columns = instance.getAllColumns()
59
60 const hasSelect = columns.find((c) => c.id === "select")
61 const hasActions = columns.find((c) => c.id === "action")
62
63 // Width strategy for data columns (excluding the pinned select/action
64 // columns): a column with an explicit `size` keeps it; the rest split the
65 // remaining width equally as a percentage, so the table always fills
66 // regardless of column count (auto-layout with equal px widths under-fills
67 // when there are few columns). Counts only the rendered/visible columns.
68 const visibleDataColumns = (instance.getHeaderGroups()[0]?.headers ?? [])
69 .map((h) => h.column)
70 .filter((c) => c.id !== "select" && c.id !== "action")
71 const autoFillCount = visibleDataColumns.filter(
72 (c) => c.columnDef.size == null
73 ).length
74 const colWidth = autoFillCount > 0 ? 100 / autoFillCount : undefined
75
76 // Create list of all column IDs for SortableContext
77 // Use current order if available, otherwise use default order
78 const sortableItems = React.useMemo(() => {
79 if (instance.columnOrder && instance.columnOrder.length > 0) {
80 return instance.columnOrder
81 }
82 return columns.map((col) => col.id)
83 }, [columns, instance.columnOrder])
84
85 // Setup drag-and-drop sensors
86 const sensors = useSensors(
87 useSensor(PointerSensor, {
88 activationConstraint: {
89 distance: 8,
90 },
91 }),
92 useSensor(KeyboardSensor, {
93 coordinateGetter: sortableKeyboardCoordinates,
94 })
95 )
96
97 const handleDragEnd = (event: DragEndEvent) => {
98 const { active, over } = event
99
100 if (active.id !== over?.id && over?.id) {
101 const activeId = active.id as string
102 const overId = over.id as string
103
104 // Don't allow dragging fixed columns
105 if (activeId === "select" || activeId === "action") {
106 return
107 }
108
109 // Don't allow dropping on fixed columns
110 if (overId === "select" || overId === "action") {
111 return
112 }
113
114 // Use the current column order from the instance
115 const currentOrder =
116 instance.columnOrder && instance.columnOrder.length > 0
117 ? instance.columnOrder
118 : columns.map((col) => col.id)
119
120 const oldIndex = currentOrder.indexOf(activeId)
121 const newIndex = currentOrder.indexOf(overId)
122
123 if (oldIndex !== -1 && newIndex !== -1) {
124 const newOrder = arrayMove(currentOrder, oldIndex, newIndex)
125 instance.setColumnOrderFromArray(newOrder)
126 }
127 }
128 }
129
130 React.useEffect(() => {
131 const onKeyDownHandler = (event: KeyboardEvent) => {
132 // If an editable element is focused, we don't want to select a row
133 const isEditableElementFocused = getIsEditableElementFocused()
134
135 if (
136 event.key.toLowerCase() === "x" &&
137 hoveredRowId &&
138 !isKeyDown.current &&
139 !isEditableElementFocused
140 ) {
141 isKeyDown.current = true
142
143 const row = instance
144 .getRowModel()
145 .rows.find((r) => r.id === hoveredRowId.current)
146
147 if (row && row.getCanSelect()) {
148 row.toggleSelected()
149 }
150 }
151 }
152
153 const onKeyUpHandler = (event: KeyboardEvent) => {
154 if (event.key.toLowerCase() === "x") {
155 isKeyDown.current = false
156 }
157 }
158
159 document.addEventListener("keydown", onKeyDownHandler)
160 document.addEventListener("keyup", onKeyUpHandler)
161 return () => {
162 document.removeEventListener("keydown", onKeyDownHandler)
163 document.removeEventListener("keyup", onKeyUpHandler)
164 }
165 }, [hoveredRowId, instance])
166
167 const handleHorizontalScroll = (e: React.UIEvent<HTMLDivElement>) => {
168 const scrollLeft = e.currentTarget.scrollLeft
169
170 if (scrollLeft > 0) {
171 setShowStickyBorder(true)
172 } else {
173 setShowStickyBorder(false)
174 }
175 }
176
177 React.useEffect(() => {
178 scrollableRef.current?.scroll({ top: 0, left: 0 })
179 }, [pageIndex])
180
181 if (instance.showSkeleton) {
182 return <DataTableTableSkeleton pageSize={instance.pageSize} />
183 }
184
185 return (
186 <div className="flex w-full flex-1 flex-col overflow-hidden">
187 {instance.emptyState === DataTableEmptyState.POPULATED &&
188 (instance.enableColumnOrder ? (
189 <DndContext
190 sensors={sensors}
191 collisionDetection={closestCenter}
192 onDragEnd={handleDragEnd}
193 >
194 <div
195 ref={scrollableRef}
196 onScroll={handleHorizontalScroll}
197 className="min-h-0 w-full flex-1 overflow-auto overscroll-auto border-y"
198 >
199 <Table className="relative isolate w-full table-fixed">
200 <Table.Header
201 className="shadow-ui-border-base sticky inset-x-0 top-0 z-[1] w-full border-b-0 border-t-0 shadow-[0_1px_1px_0]"
202 style={{ transform: "translate3d(0,0,0)" }}
203 >
204 {instance.getHeaderGroups().map((headerGroup) => (
205 <Table.Row
206 key={headerGroup.id}
207 className={clx("border-b-0", {
208 "[&_th:last-of-type]:whitespace-nowrap": hasActions,
209 "[&_th:first-of-type]:whitespace-nowrap": hasSelect,
210 })}
211 >
212 <SortableContext
213 items={sortableItems}
214 strategy={horizontalListSortingStrategy}
215 >
216 {headerGroup.headers.map((header, idx) => {
217 const canSort = header.column.getCanSort()
218 const sortDirection = header.column.getIsSorted()
219 const firstSortDirection =
220 header.column.getFirstSortDir()
221 const sortHandler =
222 header.column.getToggleSortingHandler()
223
224 const isActionHeader = header.id === "action"
225 const isSelectHeader = header.id === "select"
226 const isSpecialHeader =
227 isActionHeader || isSelectHeader
228 const isDraggable = !isSpecialHeader
229
230 const Wrapper = canSort ? "button" : "div"
231 const isFirstColumn = hasSelect
232 ? idx === 1
233 : idx === 0
234
235 // Get header alignment from column metadata.
236 // `align` drives both header and cell; `headerAlign`
237 // is the legacy header-only fallback.
238 const alignMeta = (
239 header.column.columnDef.meta as any
240 )?.___alignMetaData
241 const headerAlign =
242 alignMeta?.align ?? alignMeta?.headerAlign ?? "left"
243 const isRightAligned = headerAlign === "right"
244 const isCenterAligned = headerAlign === "center"
245
246 const HeaderCellComponent = isDraggable
247 ? DataTableSortableHeaderCell
248 : DataTableNonSortableHeaderCell
249
250 return (
251 <HeaderCellComponent
252 key={header.id}
253 id={header.id}
254 isFirstColumn={isFirstColumn}
255 className={clx("whitespace-nowrap", {
256 "w-[calc(20px+24px+24px)] min-w-[calc(20px+24px+24px)] max-w-[calc(20px+24px+24px)]":
257 isSelectHeader,
258 "w-[calc(28px+24px+4px)] min-w-[calc(28px+24px+4px)] max-w-[calc(28px+24px+4px)]":
259 isActionHeader,
260 "after:absolute after:inset-y-0 after:right-0 after:h-full after:w-px after:bg-transparent after:content-['']":
261 isFirstColumn,
262 "after:bg-ui-border-base":
263 showStickyBorder && isFirstColumn,
264 "bg-ui-bg-subtle sticky":
265 isFirstColumn || isSelectHeader,
266 "left-0":
267 isSelectHeader ||
268 (isFirstColumn && !hasSelect),
269 "left-[calc(20px+24px+24px)]":
270 isFirstColumn && hasSelect,
271 })}
272 style={
273 !isSpecialHeader
274 ? {
275 width:
276 header.column.columnDef.size != null
277 ? header.column.columnDef.size
278 : colWidth !== undefined
279 ? `${colWidth}%`
280 : undefined,
281 maxWidth: header.column.columnDef.maxSize,
282 minWidth: header.column.columnDef.minSize,
283 }
284 : undefined
285 }
286 >
287 <Wrapper
288 type={canSort ? "button" : undefined}
289 onClick={canSort ? sortHandler : undefined}
290 onMouseDown={
291 canSort
292 ? (e) => e.stopPropagation()
293 : undefined
294 }
295 className={clx(
296 "group flex cursor-default items-center gap-2",
297 {
298 "cursor-pointer": canSort,
299 "w-full": isRightAligned || isCenterAligned,
300 "w-fit":
301 !isRightAligned && !isCenterAligned,
302 "justify-end": isRightAligned,
303 "justify-center": isCenterAligned,
304 }
305 )}
306 >
307 {canSort && isRightAligned && (
308 <DataTableSortingIcon
309 direction={sortDirection}
310 firstDirection={firstSortDirection}
311 />
312 )}
313 {flexRender(
314 header.column.columnDef.header,
315 header.getContext()
316 )}
317 {canSort && !isRightAligned && (
318 <DataTableSortingIcon
319 direction={sortDirection}
320 firstDirection={firstSortDirection}
321 />
322 )}
323 </Wrapper>
324 </HeaderCellComponent>
325 )
326 })}
327 </SortableContext>
328 </Table.Row>
329 ))}
330 </Table.Header>
331 <Table.Body className="border-b-0 border-t-0">
332 {instance.getRowModel().rows.map((row) => {
333 return (
334 <Table.Row
335 key={row.id}
336 onMouseEnter={() => (hoveredRowId.current = row.id)}
337 onMouseLeave={() => (hoveredRowId.current = null)}
338 onClick={(e) => instance.onRowClick?.(e, row)}
339 className={clx("group/row last-of-type:border-b-0", {
340 "cursor-pointer": !!instance.onRowClick,
341 })}
342 >
343 {row.getVisibleCells().map((cell, idx) => {
344 const isSelectCell = cell.column.id === "select"
345 const isActionCell = cell.column.id === "action"
346 const isSpecialCell = isSelectCell || isActionCell
347
348 const isFirstColumn = hasSelect
349 ? idx === 1
350 : idx === 0
351
352 return (
353 <Table.Cell
354 key={cell.id}
355 className={clx(
356 "items-stretch truncate whitespace-nowrap",
357 {
358 "w-[calc(20px+24px+24px)] min-w-[calc(20px+24px+24px)] max-w-[calc(20px+24px+24px)]":
359 isSelectCell,
360 "w-[calc(28px+24px+4px)] min-w-[calc(28px+24px+4px)] max-w-[calc(28px+24px+4px)]":
361 isActionCell,
362 "bg-ui-bg-base group-hover/row:bg-ui-bg-base-hover transition-fg sticky":
363 isFirstColumn || isSelectCell,
364 "after:absolute after:inset-y-0 after:right-0 after:h-full after:w-px after:bg-transparent after:content-['']":
365 isFirstColumn,
366 "after:bg-ui-border-base":
367 showStickyBorder && isFirstColumn,
368 "left-0":
369 isSelectCell ||
370 (isFirstColumn && !hasSelect),
371 "left-[calc(20px+24px+24px)]":
372 isFirstColumn && hasSelect,
373 }
374 )}
375 style={
376 !isSpecialCell
377 ? {
378 width:
379 cell.column.columnDef.size != null
380 ? cell.column.columnDef.size
381 : colWidth !== undefined
382 ? `${colWidth}%`
383 : undefined,
384 maxWidth: cell.column.columnDef.maxSize,
385 minWidth: cell.column.columnDef.minSize,
386 }
387 : undefined
388 }
389 >
390 {renderAlignedCell(cell)}
391 </Table.Cell>
392 )
393 })}
394 </Table.Row>
395 )
396 })}
397 </Table.Body>
398 </Table>
399 </div>
400 </DndContext>
401 ) : (
402 <div
403 ref={scrollableRef}
404 onScroll={handleHorizontalScroll}
405 className="min-h-0 w-full flex-1 overflow-auto overscroll-auto border-y"
406 >
407 <Table className="relative isolate w-full">
408 <Table.Header
409 className="shadow-ui-border-base sticky inset-x-0 top-0 z-[1] w-full border-b-0 border-t-0 shadow-[0_1px_1px_0]"
410 style={{ transform: "translate3d(0,0,0)" }}
411 >
412 {instance.getHeaderGroups().map((headerGroup) => (
413 <Table.Row
414 key={headerGroup.id}
415 className={clx("border-b-0", {
416 "[&_th:last-of-type]:w-[1%] [&_th:last-of-type]:whitespace-nowrap":
417 hasActions,
418 "[&_th:first-of-type]:w-[1%] [&_th:first-of-type]:whitespace-nowrap":
419 hasSelect,
420 })}
421 >
422 {headerGroup.headers.map((header, idx) => {
423 const canSort = header.column.getCanSort()
424 const sortDirection = header.column.getIsSorted()
425 const firstSortDirection = header.column.getFirstSortDir()
426 const sortHandler =
427 header.column.getToggleSortingHandler()
428
429 const isActionHeader = header.id === "action"
430 const isSelectHeader = header.id === "select"
431 const isSpecialHeader = isActionHeader || isSelectHeader
432
433 const Wrapper = canSort ? "button" : "div"
434 const isFirstColumn = hasSelect ? idx === 1 : idx === 0
435
436 // Get header alignment from column metadata.
437 // `align` drives both header and cell; `headerAlign`
438 // is the legacy header-only fallback.
439 const alignMeta = (header.column.columnDef.meta as any)
440 ?.___alignMetaData
441 const headerAlign =
442 alignMeta?.align ?? alignMeta?.headerAlign ?? "left"
443 const isRightAligned = headerAlign === "right"
444 const isCenterAligned = headerAlign === "center"
445
446 return (
447 <Table.HeaderCell
448 key={header.id}
449 className={clx("whitespace-nowrap", {
450 "w-[calc(20px+24px+24px)] min-w-[calc(20px+24px+24px)] max-w-[calc(20px+24px+24px)]":
451 isSelectHeader,
452 "w-[calc(28px+24px+4px)] min-w-[calc(28px+24px+4px)] max-w-[calc(28px+24px+4px)]":
453 isActionHeader,
454 "after:absolute after:inset-y-0 after:right-0 after:h-full after:w-px after:bg-transparent after:content-['']":
455 isFirstColumn,
456 "after:bg-ui-border-base":
457 showStickyBorder && isFirstColumn,
458 "bg-ui-bg-subtle sticky":
459 isFirstColumn || isSelectHeader,
460 "left-0":
461 isSelectHeader || (isFirstColumn && !hasSelect),
462 "left-[calc(20px+24px+24px)]":
463 isFirstColumn && hasSelect,
464 })}
465 style={
466 !isSpecialHeader
467 ? {
468 width: header.column.columnDef.size,
469 maxWidth: header.column.columnDef.maxSize,
470 minWidth: header.column.columnDef.minSize,
471 }
472 : undefined
473 }
474 >
475 <Wrapper
476 type={canSort ? "button" : undefined}
477 onClick={canSort ? sortHandler : undefined}
478 onMouseDown={
479 canSort ? (e) => e.stopPropagation() : undefined
480 }
481 className={clx(
482 "group flex cursor-default items-center gap-2",
483 {
484 "cursor-pointer": canSort,
485 "w-full": isRightAligned || isCenterAligned,
486 "w-fit": !isRightAligned && !isCenterAligned,
487 "justify-end": isRightAligned,
488 "justify-center": isCenterAligned,
489 }
490 )}
491 >
492 {canSort && isRightAligned && (
493 <DataTableSortingIcon
494 direction={sortDirection}
495 firstDirection={firstSortDirection}
496 />
497 )}
498 {flexRender(
499 header.column.columnDef.header,
500 header.getContext()
501 )}
502 {canSort && !isRightAligned && (
503 <DataTableSortingIcon
504 direction={sortDirection}
505 firstDirection={firstSortDirection}
506 />
507 )}
508 </Wrapper>
509 </Table.HeaderCell>
510 )
511 })}
512 </Table.Row>
513 ))}
514 </Table.Header>
515 <Table.Body className="border-b-0 border-t-0">
516 {instance.getRowModel().rows.map((row) => {
517 return (
518 <Table.Row
519 key={row.id}
520 onMouseEnter={() => (hoveredRowId.current = row.id)}
521 onMouseLeave={() => (hoveredRowId.current = null)}
522 onClick={(e) => instance.onRowClick?.(e, row)}
523 className={clx("group/row last-of-type:border-b-0", {
524 "cursor-pointer": !!instance.onRowClick,
525 })}
526 >
527 {row.getVisibleCells().map((cell, idx) => {
528 const isSelectCell = cell.column.id === "select"
529 const isActionCell = cell.column.id === "action"
530 const isSpecialCell = isSelectCell || isActionCell
531
532 const isFirstColumn = hasSelect ? idx === 1 : idx === 0
533
534 return (
535 <Table.Cell
536 key={cell.id}
537 className={clx("items-stretch whitespace-nowrap", {
538 "w-[calc(20px+24px+24px)] min-w-[calc(20px+24px+24px)] max-w-[calc(20px+24px+24px)]":
539 isSelectCell,
540 "w-[calc(28px+24px+4px)] min-w-[calc(28px+24px+4px)] max-w-[calc(28px+24px+4px)]":
541 isActionCell,
542 "bg-ui-bg-base group-hover/row:bg-ui-bg-base-hover transition-fg sticky":
543 isFirstColumn || isSelectCell,
544 "after:absolute after:inset-y-0 after:right-0 after:h-full after:w-px after:bg-transparent after:content-['']":
545 isFirstColumn,
546 "after:bg-ui-border-base":
547 showStickyBorder && isFirstColumn,
548 "left-0":
549 isSelectCell || (isFirstColumn && !hasSelect),
550 "left-[calc(20px+24px+24px)]":
551 isFirstColumn && hasSelect,
552 })}
553 style={
554 !isSpecialCell
555 ? {
556 width: cell.column.columnDef.size,
557 maxWidth: cell.column.columnDef.maxSize,
558 minWidth: cell.column.columnDef.minSize,
559 }
560 : undefined
561 }
562 >
563 {renderAlignedCell(cell)}
564 </Table.Cell>
565 )
566 })}
567 </Table.Row>
568 )
569 })}
570 </Table.Body>
571 </Table>
572 </div>
573 ))}
574 <DataTableEmptyStateDisplay
575 state={instance.emptyState}
576 props={props.emptyState}
577 />
578 </div>
579 )
580 }
581 DataTableTable.displayName = "DataTable.Table"
582
583 interface DataTableEmptyStateDisplayProps {
584 state: DataTableEmptyState
585 props?: DataTableEmptyStateProps
586 }
587
588 const DefaultEmptyStateContent = ({
589 heading,
590 description,
591 }: DataTableEmptyStateContent) => (
592 <div className="flex size-full flex-col items-center justify-center gap-2">
593 <Text size="base" weight="plus">
594 {heading}
595 </Text>
596 <Text>{description}</Text>
597 </div>
598 )
599
600 const DataTableEmptyStateDisplay = ({
601 state,
602 props,
603 }: DataTableEmptyStateDisplayProps) => {
604 if (state === DataTableEmptyState.POPULATED) {
605 return null
606 }
607
608 const content =
609 state === DataTableEmptyState.EMPTY ? props?.empty : props?.filtered
610
611 return (
612 <div className="flex min-h-[250px] w-full flex-1 flex-col items-center justify-center border-y px-6 py-4">
613 {content?.custom ?? (
614 <DefaultEmptyStateContent
615 heading={content?.heading}
616 description={content?.description}
617 />
618 )}
619 </div>
620 )
621 }
622
623 interface DataTableTableSkeletonProps {
624 pageSize?: number
625 }
626
627 const DataTableTableSkeleton = ({
628 pageSize = 10,
629 }: DataTableTableSkeletonProps) => {
630 return (
631 <div className="flex w-full flex-1 flex-col overflow-hidden">
632 <div className="min-h-0 w-full flex-1 overscroll-auto border-y">
633 <div className="flex flex-col divide-y">
634 <Skeleton className="h-12 w-full" />
635 {Array.from({ length: pageSize }, (_, i) => i).map((row) => (
636 <Skeleton key={row} className="h-12 w-full rounded-none" />
637 ))}
638 </div>
639 </div>
640 </div>
641 )
642 }
643
644 // Renders a body cell's content, applying horizontal alignment from the
645 // column's `align` meta. Left-aligned (or unset) cells render bare; only
646 // center/right wrap in an alignment flex row. The content is clipped and (by
647 // default) tooltipped by TruncatedCell.
648 function renderAlignedCell(cell: any) {
649 const meta = cell.column.columnDef.meta as any
650 const align = meta?.___alignMetaData?.align
651 // Opt-out is explicit `false`; anything else (incl. unset) truncates+tooltips.
652 const wantTooltip = meta?.___truncateTooltip !== false
653
654 const rendered = flexRender(cell.column.columnDef.cell, cell.getContext())
655 const content = wantTooltip ? (
656 <TruncatedCell>{rendered}</TruncatedCell>
657 ) : (
658 rendered
659 )
660
661 if (!["right", "center"].includes(align)) {
662 return content
663 }
664
665 return (
666 <div
667 className={clx("flex min-w-0 items-center", {
668 "justify-end": align === "right",
669 "justify-center": align === "center",
670 })}
671 >
672 {content}
673 </div>
674 )
675 }
676
677 function TruncatedCell({ children }: { children: React.ReactNode }) {
678 const ref = React.useRef<HTMLDivElement>(null)
679 const [state, setState] = React.useState({ overflow: false, text: "" })
680
681 const check = () => {
682 const el = ref.current
683 if (el) {
684 setState({
685 overflow: el.scrollWidth > el.clientWidth,
686 text: el.textContent ?? "",
687 })
688 }
689 }
690
691 return (
692 // Cap the tooltip's width and break long unbroken strings so the text
693 // wraps inside the bubble instead of overflowing it.
694 <Tooltip
695 content={state.text}
696 hidden={!state.overflow}
697 className="max-w-[360px] break-words"
698 >
699 <div ref={ref} className="truncate" onMouseEnter={check}>
700 {children}
701 </div>
702 </Tooltip>
703 )
704 }
705
706 function getIsEditableElementFocused() {
707 const activeElement = !!document ? document.activeElement : null
708 const isEditableElementFocused =
709 activeElement instanceof HTMLInputElement ||
710 activeElement instanceof HTMLTextAreaElement ||
711 activeElement?.getAttribute("contenteditable") === "true"
712
713 return isEditableElementFocused
714 }
715
716 export { DataTableTable }
717 export type { DataTableEmptyStateProps, DataTableTableProps }