@allbluecn/admin-app 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/allblue-ui/package.json +6 -0
  2. package/allblue-ui/src/components/confirm-dialog.tsx +94 -0
  3. package/allblue-ui/src/components/infinite-scroll-sentinel.tsx +37 -0
  4. package/allblue-ui/src/components/notion-avatar.tsx +126 -0
  5. package/allblue-ui/src/components/user-avatar.tsx +82 -0
  6. package/allblue-ui/src/data-table/data-table-pagination.tsx +121 -0
  7. package/allblue-ui/src/data-table/data-table.tsx +218 -0
  8. package/allblue-ui/src/data-table/table-detail-layout.tsx +97 -0
  9. package/allblue-ui/src/hooks/use-load-more.ts +57 -0
  10. package/allblue-ui/src/hooks/use-mobile.ts +19 -0
  11. package/allblue-ui/src/index.ts +31 -0
  12. package/allblue-ui/src/lib/avatar.ts +41 -0
  13. package/allblue-ui/src/lib/datetime.ts +226 -0
  14. package/allblue-ui/src/lib/sanitize.ts +18 -0
  15. package/allblue-ui/src/lib/utils.ts +1 -0
  16. package/allblue-ui/src/ui/alert-dialog.tsx +185 -0
  17. package/allblue-ui/src/ui/alert.tsx +75 -0
  18. package/allblue-ui/src/ui/avatar.tsx +106 -0
  19. package/allblue-ui/src/ui/badge.tsx +51 -0
  20. package/allblue-ui/src/ui/button.tsx +57 -0
  21. package/allblue-ui/src/ui/card.tsx +102 -0
  22. package/allblue-ui/src/ui/checkbox.tsx +27 -0
  23. package/allblue-ui/src/ui/collapsible.tsx +19 -0
  24. package/allblue-ui/src/ui/dialog.tsx +155 -0
  25. package/allblue-ui/src/ui/dropdown-menu.tsx +265 -0
  26. package/allblue-ui/src/ui/field.tsx +236 -0
  27. package/allblue-ui/src/ui/input-group.tsx +157 -0
  28. package/allblue-ui/src/ui/input.tsx +19 -0
  29. package/allblue-ui/src/ui/label.tsx +17 -0
  30. package/allblue-ui/src/ui/pagination.tsx +130 -0
  31. package/allblue-ui/src/ui/select.tsx +232 -0
  32. package/allblue-ui/src/ui/separator.tsx +23 -0
  33. package/allblue-ui/src/ui/sheet.tsx +134 -0
  34. package/allblue-ui/src/ui/sidebar.tsx +721 -0
  35. package/allblue-ui/src/ui/skeleton.tsx +13 -0
  36. package/allblue-ui/src/ui/switch.tsx +30 -0
  37. package/allblue-ui/src/ui/table.tsx +113 -0
  38. package/allblue-ui/src/ui/textarea.tsx +17 -0
  39. package/allblue-ui/src/ui/toast.tsx +308 -0
  40. package/allblue-ui/src/ui/tooltip.tsx +64 -0
  41. package/package.json +3 -2
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "@allbluecn/ui-bundled",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module"
6
+ }
@@ -0,0 +1,94 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+
5
+ import type { ReactElement, ReactNode } from "react"
6
+ import {
7
+ AlertDialog,
8
+ AlertDialogAction,
9
+ AlertDialogCancel,
10
+ AlertDialogContent,
11
+ AlertDialogDescription,
12
+ AlertDialogFooter,
13
+ AlertDialogHeader,
14
+ AlertDialogTitle,
15
+ AlertDialogTrigger,
16
+ } from "../ui/alert-dialog"
17
+ import type { Button } from "../ui/button"
18
+
19
+ export interface ConfirmDialogProps {
20
+ /** 受控 open;不传则由 trigger 非受控驱动 */
21
+ open?: boolean
22
+ onOpenChange?: (open: boolean) => void
23
+ title: ReactNode
24
+ /** 传 null 渲染空描述(保持 aria-describedby 结构),缺省则不渲染 */
25
+ description?: ReactNode
26
+ cancelLabel: ReactNode
27
+ confirmLabel: ReactNode
28
+ /** 确认按钮点击回调;关闭时机由调用方自行控制(与既有内联实现一致,不自动关闭) */
29
+ onConfirm: () => void
30
+ confirmVariant?: React.ComponentProps<typeof Button>["variant"]
31
+ confirmClassName?: string
32
+ confirmDisabled?: boolean
33
+ cancelDisabled?: boolean
34
+ confirmTestId?: string
35
+ contentTestId?: string
36
+ contentClassName?: string
37
+ /** 可选触发器元素(作为 AlertDialogTrigger 的 render 元素) */
38
+ trigger?: ReactElement
39
+ }
40
+
41
+ /**
42
+ * 通用确认弹窗:收口各处内联的「双 state + 手写 AlertDialog」确认模式。
43
+ * 仅做骨架渲染,onConfirm 的异步/关闭时序完全由调用方决定,保证逐站点行为等价迁移。
44
+ */
45
+ export function ConfirmDialog({
46
+ open,
47
+ onOpenChange,
48
+ title,
49
+ description,
50
+ cancelLabel,
51
+ confirmLabel,
52
+ onConfirm,
53
+ confirmVariant,
54
+ confirmClassName,
55
+ confirmDisabled,
56
+ cancelDisabled,
57
+ confirmTestId,
58
+ contentTestId,
59
+ contentClassName,
60
+ trigger,
61
+ }: ConfirmDialogProps) {
62
+ const rootProps: { open?: boolean; onOpenChange?: (open: boolean) => void } = {}
63
+ if (open !== undefined) {
64
+ rootProps.open = open
65
+ rootProps.onOpenChange = onOpenChange
66
+ } else if (onOpenChange) {
67
+ rootProps.onOpenChange = onOpenChange
68
+ }
69
+ return (
70
+ <AlertDialog {...rootProps}>
71
+ {trigger ? <AlertDialogTrigger render={trigger} /> : null}
72
+ <AlertDialogContent data-testid={contentTestId} className={contentClassName}>
73
+ <AlertDialogHeader>
74
+ <AlertDialogTitle>{title}</AlertDialogTitle>
75
+ {description !== undefined ? (
76
+ <AlertDialogDescription>{description}</AlertDialogDescription>
77
+ ) : null}
78
+ </AlertDialogHeader>
79
+ <AlertDialogFooter>
80
+ <AlertDialogCancel disabled={cancelDisabled}>{cancelLabel}</AlertDialogCancel>
81
+ <AlertDialogAction
82
+ variant={confirmVariant}
83
+ className={confirmClassName}
84
+ disabled={confirmDisabled}
85
+ onClick={onConfirm}
86
+ data-testid={confirmTestId}
87
+ >
88
+ {confirmLabel}
89
+ </AlertDialogAction>
90
+ </AlertDialogFooter>
91
+ </AlertDialogContent>
92
+ </AlertDialog>
93
+ )
94
+ }
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+
5
+ import { useLoadMore } from "../hooks/use-load-more"
6
+
7
+ interface InfiniteScrollSentinelProps {
8
+ onLoadMore: () => void | Promise<void>
9
+ hasMore: boolean
10
+ rootRef?: React.RefObject<HTMLElement | null>
11
+ /** 全部加载完后的提示文案(调用方传入,组件内不做 i18n) */
12
+ loadedAllLabel: string
13
+ }
14
+
15
+ /**
16
+ * 无限滚动哨兵:滚动到底部附近触发 onLoadMore,展示三点脉冲 loading 与
17
+ * 「已全部加载」提示。加载状态机见 useLoadMore。
18
+ */
19
+ export function InfiniteScrollSentinel({ onLoadMore, hasMore, rootRef, loadedAllLabel }: InfiniteScrollSentinelProps) {
20
+ const { sentinelRef, loading } = useLoadMore(onLoadMore, hasMore, rootRef)
21
+
22
+ return (
23
+ <div className="flex h-7 items-center justify-center">
24
+ <div ref={sentinelRef} className="h-1" />
25
+ {loading && (
26
+ <div className="flex items-center gap-1">
27
+ <div className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary/60" />
28
+ <div className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary/60 delay-75" />
29
+ <div className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary/60 delay-150" />
30
+ </div>
31
+ )}
32
+ {!loading && !hasMore && (
33
+ <span className="text-xs text-muted-foreground">{loadedAllLabel}</span>
34
+ )}
35
+ </div>
36
+ )
37
+ }
@@ -0,0 +1,126 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+
19
+ import { useEffect, useState } from "react"
20
+ import type { AvatarConfig, AvatarPart, ShapeType } from "@allbluecn/kernel"
21
+ import { sanitizeSvg } from "../lib/sanitize"
22
+
23
+ const noneParts: AvatarPart[] = ["glasses", "hair", "accessories", "details", "beard"]
24
+
25
+ const partOrder: AvatarPart[] = [
26
+ "face",
27
+ "nose",
28
+ "mouth",
29
+ "eyes",
30
+ "eyebrows",
31
+ "glasses",
32
+ "hair",
33
+ "accessories",
34
+ "details",
35
+ "beard",
36
+ ]
37
+
38
+ function getPreviewImagePath(part: AvatarPart, index: number): string {
39
+ return `/avatar/preview/${part}/${index}.svg`
40
+ }
41
+
42
+ const SVGFilter = `<defs>
43
+ <filter id="notion-avatar-filter" x="-20%" y="-20%" width="140%" height="140%" filterUnits="objectBoundingBox" primitiveUnits="userSpaceOnUse" color-interpolation-filters="linearRGB">
44
+ <feMorphology operator="dilate" radius="20" in="SourceAlpha" result="morphology"/>
45
+ <feFlood flood-color="#ffffff" flood-opacity="1" result="flood"/>
46
+ <feComposite in="flood" in2="morphology" operator="in" result="composite"/>
47
+ <feMerge result="merge">
48
+ <feMergeNode in="composite" result="mergeNode"/>
49
+ <feMergeNode in="SourceGraphic" result="mergeNode1"/>
50
+ </feMerge>
51
+ </filter>
52
+ </defs>`
53
+
54
+ function extractInnerSvg(svgText: string): string {
55
+ return svgText.replace(/<svg[^>]*>/i, "").replace(/<\/svg>/i, "").trim()
56
+ }
57
+
58
+ const shapeStyle: Record<ShapeType, string> = {
59
+ circle: "rounded-full",
60
+ rounded: "rounded-lg",
61
+ square: "rounded-none",
62
+ }
63
+
64
+ type NotionAvatarProps = {
65
+ config: AvatarConfig
66
+ bgColor?: string
67
+ shape?: ShapeType
68
+ className?: string
69
+ style?: React.CSSProperties
70
+ flip?: boolean
71
+ }
72
+
73
+ export function NotionAvatar({
74
+ config,
75
+ bgColor = "transparent",
76
+ shape = "circle",
77
+ className,
78
+ style,
79
+ flip = false,
80
+ }: NotionAvatarProps) {
81
+ const [svgContent, setSvgContent] = useState<string>("")
82
+
83
+ useEffect(() => {
84
+ async function buildAvatar() {
85
+ const groups = await Promise.all(
86
+ partOrder.map(async (part) => {
87
+ const index = config[part]
88
+ if (noneParts.includes(part) && index === 0) return ""
89
+ try {
90
+ const res = await fetch(getPreviewImagePath(part, index))
91
+ const svgText = await res.text()
92
+ const inner = extractInnerSvg(svgText)
93
+ return `\n<g id="avatar-${part}"${part === "face" ? ' fill="#ffffff"' : ""}>${inner}</g>`
94
+ } catch {
95
+ return ""
96
+ }
97
+ }),
98
+ )
99
+ const flipAttr = flip ? ' transform="scale(-1,1) translate(-1080, 0)"' : ""
100
+ const avatarSvg = `<svg viewBox="0 0 1080 1080" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:100%;height:100%">${SVGFilter}<g id="avatar"${flipAttr}>${groups.join("")}</g></svg>`
101
+ setSvgContent(avatarSvg)
102
+ }
103
+ buildAvatar()
104
+ }, [config, flip])
105
+
106
+ if (!svgContent) {
107
+ return (
108
+ <div
109
+ className={`${shapeStyle[shape]} overflow-hidden bg-muted animate-pulse ${className ?? ""}`}
110
+ style={{ aspectRatio: "1 / 1", ...style }}
111
+ />
112
+ )
113
+ }
114
+
115
+ return (
116
+ <div
117
+ className={`${shapeStyle[shape]} ${className ?? ""}`}
118
+ style={{
119
+ backgroundColor: bgColor === "transparent" ? undefined : bgColor,
120
+ aspectRatio: "1 / 1",
121
+ ...style,
122
+ }}
123
+ dangerouslySetInnerHTML={{ __html: sanitizeSvg(svgContent) }}
124
+ />
125
+ )
126
+ }
@@ -0,0 +1,82 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+
19
+ import { NotionAvatar } from "./notion-avatar"
20
+ import type { AvatarConfig, ShapeType } from "@allbluecn/kernel"
21
+
22
+ type UserAvatarProps = {
23
+ avatarConfig?: AvatarConfig | null
24
+ bgShape?: ShapeType | null
25
+ bgColor?: string | null
26
+ name?: string | null
27
+ imageUrl?: string | null
28
+ className?: string
29
+ size?: "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl"
30
+ }
31
+
32
+ const sizeClasses: Record<string, string> = {
33
+ xs: "w-5 h-5",
34
+ sm: "w-6 h-6",
35
+ md: "w-8 h-8",
36
+ lg: "w-10 h-10",
37
+ xl: "w-12 h-12",
38
+ "2xl": "w-16 h-16",
39
+ "3xl": "w-20 h-20",
40
+ "4xl": "w-24 h-24",
41
+ }
42
+
43
+ export function UserAvatar({
44
+ avatarConfig,
45
+ bgShape,
46
+ bgColor,
47
+ name,
48
+ imageUrl,
49
+ className,
50
+ size = "md",
51
+ }: UserAvatarProps) {
52
+ const initial = (name || "U").charAt(0).toUpperCase()
53
+ const shapeClass =
54
+ bgShape === "circle" ? "rounded-full" : bgShape === "square" ? "rounded-none" : "rounded-lg"
55
+
56
+ if (avatarConfig) {
57
+ return (
58
+ <NotionAvatar
59
+ config={avatarConfig}
60
+ shape={bgShape ?? "square"}
61
+ bgColor={bgColor ?? "#fff"}
62
+ className={`${sizeClasses[size]} shrink-0 ${className ?? ""}`}
63
+ />
64
+ )
65
+ }
66
+
67
+ if (imageUrl) {
68
+ return (
69
+ <div className={`relative shrink-0 overflow-hidden ${shapeClass} ${sizeClasses[size]} ${className ?? ""}`}>
70
+ <img src={imageUrl} alt={name || ""} className="h-full w-full object-cover" />
71
+ </div>
72
+ )
73
+ }
74
+
75
+ return (
76
+ <div
77
+ className={`flex shrink-0 items-center justify-center ${shapeClass} bg-muted text-xs font-medium ${sizeClasses[size]} ${className ?? ""}`}
78
+ >
79
+ {initial}
80
+ </div>
81
+ )
82
+ }
@@ -0,0 +1,121 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ import {
19
+ Pagination,
20
+ PaginationContent,
21
+ PaginationEllipsis,
22
+ PaginationItem,
23
+ PaginationLink,
24
+ PaginationNext,
25
+ PaginationPrevious,
26
+ } from "../ui/pagination";
27
+
28
+ // i18n 由消费方注入(包内不依赖 @/paraglide),文案与原 admin 实现逐字对应
29
+ export interface DataTablePaginationLabels {
30
+ total: string;
31
+ previous: string;
32
+ next: string;
33
+ }
34
+
35
+ interface DataTablePaginationProps {
36
+ page: number;
37
+ totalPages: number;
38
+ total: number;
39
+ onPageChange: (page: number) => void;
40
+ labels: DataTablePaginationLabels;
41
+ }
42
+
43
+ function getPageNumbers(current: number, total: number): (number | "ellipsis")[] {
44
+ if (total <= 5) {
45
+ return Array.from({ length: total }, (_, i) => i + 1);
46
+ }
47
+
48
+ const pages: (number | "ellipsis")[] = [1];
49
+
50
+ if (current > 3) {
51
+ pages.push("ellipsis");
52
+ }
53
+
54
+ const start = Math.max(2, current - 1);
55
+ const end = Math.min(total - 1, current + 1);
56
+
57
+ for (let i = start; i <= end; i++) {
58
+ pages.push(i);
59
+ }
60
+
61
+ if (current < total - 2) {
62
+ pages.push("ellipsis");
63
+ }
64
+
65
+ pages.push(total);
66
+
67
+ return pages;
68
+ }
69
+
70
+ export function DataTablePagination({
71
+ page,
72
+ totalPages,
73
+ total,
74
+ onPageChange,
75
+ labels,
76
+ }: DataTablePaginationProps) {
77
+ const pages = getPageNumbers(page, totalPages);
78
+
79
+ return (
80
+ <div className="flex items-center justify-between gap-4 px-2 py-4">
81
+ <div className="text-sm text-muted-foreground whitespace-nowrap shrink-0">
82
+ {labels.total}
83
+ </div>
84
+ <Pagination className="justify-end">
85
+ <PaginationContent>
86
+ <PaginationItem>
87
+ <PaginationPrevious
88
+ text={labels.previous}
89
+ onClick={() => page > 1 && onPageChange(page - 1)}
90
+ className={page <= 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
91
+ />
92
+ </PaginationItem>
93
+ {pages.map((p, i) =>
94
+ p === "ellipsis" ? (
95
+ <PaginationItem key={`ellipsis-${i}`}>
96
+ <PaginationEllipsis />
97
+ </PaginationItem>
98
+ ) : (
99
+ <PaginationItem key={p}>
100
+ <PaginationLink
101
+ isActive={p === page}
102
+ onClick={() => onPageChange(p)}
103
+ className="cursor-pointer"
104
+ >
105
+ {p}
106
+ </PaginationLink>
107
+ </PaginationItem>
108
+ )
109
+ )}
110
+ <PaginationItem>
111
+ <PaginationNext
112
+ text={labels.next}
113
+ onClick={() => page < totalPages && onPageChange(page + 1)}
114
+ className={page >= totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
115
+ />
116
+ </PaginationItem>
117
+ </PaginationContent>
118
+ </Pagination>
119
+ </div>
120
+ );
121
+ }
@@ -0,0 +1,218 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ import type { CSSProperties } from 'react'
19
+ import { useRef } from 'react'
20
+ import {
21
+ type ColumnDef,
22
+ type RowData,
23
+ columnVisibilityFeature,
24
+ flexRender,
25
+ tableFeatures,
26
+ useTable,
27
+ } from '@tanstack/react-table'
28
+ import { useVirtualizer } from '@tanstack/react-virtual'
29
+ import {
30
+ Table,
31
+ TableBody,
32
+ TableCell,
33
+ TableHead,
34
+ TableHeader,
35
+ TableRow,
36
+ } from '../ui/table'
37
+ import { VIRTUALIZE_THRESHOLD } from '@allbluecn/kernel'
38
+
39
+ export const dataTableFeatures = tableFeatures({
40
+ columnVisibilityFeature,
41
+ })
42
+
43
+ export type AdminColumnDef<
44
+ TData extends RowData,
45
+ TValue = unknown,
46
+ > = ColumnDef<typeof dataTableFeatures, TData, TValue> & {
47
+ meta?: { style?: CSSProperties }
48
+ }
49
+
50
+ export interface DataTableProps<TData extends RowData> {
51
+ columns: AdminColumnDef<TData>[];
52
+ data: TData[];
53
+ onRowClick?: (row: TData) => void;
54
+ actions?: React.ReactNode;
55
+ }
56
+
57
+ const ROW_HEIGHT = 48
58
+
59
+ function ColGroup({ columns }: { columns: AdminColumnDef<any>[] }) {
60
+ return (
61
+ <colgroup>
62
+ {columns.map((col, i) => {
63
+ const style = (col.meta as { style?: CSSProperties } | undefined)?.style
64
+ const width = style?.width
65
+ return width != null ? <col key={i} style={{ width }} /> : null
66
+ })}
67
+ </colgroup>
68
+ )
69
+ }
70
+
71
+ export function DataTable<TData extends RowData>({
72
+ columns,
73
+ data,
74
+ onRowClick,
75
+ actions,
76
+ }: DataTableProps<TData>) {
77
+ const table = useTable({
78
+ features: dataTableFeatures,
79
+ data,
80
+ columns,
81
+ });
82
+
83
+ const { rows } = table.getRowModel();
84
+ const parentRef = useRef<HTMLDivElement>(null);
85
+
86
+ const shouldVirtualize = rows.length > VIRTUALIZE_THRESHOLD;
87
+
88
+ const rowVirtualizer = useVirtualizer({
89
+ count: shouldVirtualize ? rows.length : 0,
90
+ getScrollElement: () => parentRef.current,
91
+ estimateSize: () => ROW_HEIGHT,
92
+ overscan: 10,
93
+ enabled: shouldVirtualize,
94
+ });
95
+
96
+ const virtualRows = shouldVirtualize ? rowVirtualizer.getVirtualItems() : [];
97
+ const totalHeight = shouldVirtualize ? rowVirtualizer.getTotalSize() : 0;
98
+ const paddingTop = virtualRows.length > 0 ? virtualRows[0].start : 0;
99
+ const paddingBottom =
100
+ virtualRows.length > 0
101
+ ? totalHeight - virtualRows[virtualRows.length - 1].end
102
+ : 0;
103
+
104
+ const headerGroups = table.getHeaderGroups();
105
+
106
+ const renderRows = () => {
107
+ if (!shouldVirtualize) {
108
+ return rows.map((row) => (
109
+ <TableRow
110
+ key={row.id}
111
+ className={onRowClick ? 'cursor-pointer' : undefined}
112
+ onClick={() => onRowClick?.(row.original)}
113
+ >
114
+ {row.getVisibleCells().map((cell) => {
115
+ const style = (cell.column.columnDef.meta as
116
+ | { style?: CSSProperties }
117
+ | undefined)?.style
118
+ const alignClass =
119
+ style?.textAlign === 'right' ? 'text-right' : undefined
120
+ return (
121
+ <TableCell
122
+ key={cell.id}
123
+ className={alignClass}
124
+ style={{ width: style?.width }}
125
+ >
126
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
127
+ </TableCell>
128
+ )
129
+ })}
130
+ </TableRow>
131
+ ))
132
+ }
133
+
134
+ return (
135
+ <>
136
+ {paddingTop > 0 && <tr style={{ height: paddingTop }} />}
137
+ {virtualRows.map((virtualRow) => {
138
+ const row = rows[virtualRow.index]
139
+ return (
140
+ <TableRow
141
+ key={row.id}
142
+ style={{
143
+ position: 'absolute',
144
+ transform: `translateY(${virtualRow.start}px)`,
145
+ height: ROW_HEIGHT,
146
+ }}
147
+ className={onRowClick ? 'cursor-pointer' : undefined}
148
+ onClick={() => onRowClick?.(row.original)}
149
+ >
150
+ {row.getVisibleCells().map((cell) => {
151
+ const style = (cell.column.columnDef.meta as
152
+ | { style?: CSSProperties }
153
+ | undefined)?.style
154
+ const alignClass =
155
+ style?.textAlign === 'right' ? 'text-right' : undefined
156
+ return (
157
+ <TableCell
158
+ key={cell.id}
159
+ className={alignClass}
160
+ style={{ width: style?.width }}
161
+ >
162
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
163
+ </TableCell>
164
+ )
165
+ })}
166
+ </TableRow>
167
+ )
168
+ })}
169
+ {paddingBottom > 0 && <tr style={{ height: paddingBottom }} />}
170
+ </>
171
+ );
172
+ };
173
+
174
+ return (
175
+ <div className="rounded-md border flex flex-col min-h-0 flex-1 overflow-x-hidden">
176
+ <div className="shrink-0">
177
+ <Table className="table-fixed">
178
+ <ColGroup columns={columns} />
179
+ <TableHeader>
180
+ {headerGroups.map((headerGroup) => (
181
+ <TableRow key={headerGroup.id}>
182
+ {headerGroup.headers.map((header) => {
183
+ const style = (
184
+ header.column.columnDef.meta as
185
+ | { style?: CSSProperties }
186
+ | undefined
187
+ )?.style
188
+ const alignClass =
189
+ style?.textAlign === 'right' ? 'text-right' : undefined
190
+ return (
191
+ <TableHead
192
+ key={header.id}
193
+ className={alignClass}
194
+ style={{ width: style?.width }}
195
+ >
196
+ {header.isPlaceholder
197
+ ? null
198
+ : flexRender(header.column.columnDef.header, header.getContext())}
199
+ </TableHead>
200
+ )
201
+ })}
202
+ </TableRow>
203
+ ))}
204
+ </TableHeader>
205
+ </Table>
206
+ </div>
207
+ <div ref={parentRef} className="overflow-y-auto flex-1 min-h-0">
208
+ <div style={{ position: "relative", height: shouldVirtualize ? totalHeight : undefined }}>
209
+ <Table className="table-fixed">
210
+ <ColGroup columns={columns} />
211
+ <TableBody>{renderRows()}</TableBody>
212
+ </Table>
213
+ </div>
214
+ </div>
215
+ {actions && <div className="shrink-0 border-t">{actions}</div>}
216
+ </div>
217
+ );
218
+ }