-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTable.tsx
More file actions
402 lines (365 loc) · 12.4 KB
/
Table.tsx
File metadata and controls
402 lines (365 loc) · 12.4 KB
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
import {
ColumnDef,
FilterFn,
flexRender,
getCoreRowModel,
getSortedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
useReactTable,
getPaginationRowModel,
getFacetedMinMaxValues,
} from "@tanstack/react-table"
import React from "react"
import { ChevronUpIcon, ChevronDownIcon, ChevronUpDownIcon } from "@heroicons/react/24/outline"
import Filter from "src/core/components/Filter"
import { buildSearchableString } from "src/core/utils/tableFilters"
import TooltipWrapper from "./TooltipWrapper"
const specialSearchTokens = new Set([
"read",
"unread",
"completed",
"complete",
"not completed",
"approved",
"not approved",
"pending",
])
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
const containsWholeWord = (text: string, word: string) => {
const escapedWord = escapeRegExp(word)
const regex = new RegExp(`\\b${escapedWord}\\b`)
return regex.test(text)
}
const matchesSpecialTokenInText = (text: string, token: string) => {
if (!text) {
return false
}
const normalized = text.toLowerCase()
if (token === "completed") {
return /(?<!not\s)\bcompleted\b/.test(normalized)
}
if (token === "complete") {
return /(?<!not\s)(?<!in)\bcomplete\b/.test(normalized)
}
if (token === "not completed") {
return /\bnot\s+completed\b/.test(normalized)
}
return containsWholeWord(normalized, token)
}
const matchesBooleanToken = (token: string, value: boolean | null, keyPath: string): boolean => {
const normalizedKey = keyPath.toLowerCase()
const isReadKey = normalizedKey.includes("read")
const isCompletionKey = normalizedKey.includes("status") || normalizedKey.includes("complete")
const isApprovalKey = normalizedKey.includes("approve")
if (token === "read") {
return isReadKey && value === true
}
if (token === "unread") {
return isReadKey && value === false
}
if (token === "completed" || token === "complete") {
return isCompletionKey && value === true
}
if (token === "not completed") {
return isCompletionKey && value === false
}
if (token === "approved") {
return isApprovalKey && value === true
}
if (token === "not approved") {
return isApprovalKey && value === false
}
if (token === "pending") {
return isApprovalKey && (value === null || value === undefined)
}
return false
}
const matchesSpecialToken = (data: unknown, token: string, keyPath = ""): boolean => {
if (data === null || data === undefined) {
return matchesBooleanToken(token, data as null, keyPath)
}
if (typeof data === "boolean") {
return matchesBooleanToken(token, data, keyPath)
}
if (Array.isArray(data)) {
return data.some((item) => matchesSpecialToken(item, token, keyPath))
}
if (data instanceof Date) {
return false
}
if (typeof data === "object") {
return Object.entries(data as Record<string, unknown>).some(([key, value]) => {
const nextPath = keyPath ? `${keyPath}.${key}` : key
return matchesSpecialToken(value, token, nextPath)
})
}
return false
}
type TableProps<TData> = {
columns: ColumnDef<TData, any>[]
data: TData[]
filters?: {} //pass object with the type of filter for a given colunm based on colunm id
enableSorting?: boolean
enableFilters?: boolean
enableGlobalSearch?: boolean
globalSearchPlaceholder?: string
addPagination?: boolean
classNames?: {
table?: string
thead?: string
tbody?: string
tfoot?: string
th?: string
td?: string
paginationButton?: string
pageInfo?: string
goToPageInput?: string
pageSizeSelect?: string
searchContainer?: string
searchInput?: string
}
}
const defaultGlobalFilterFn: FilterFn<any> = (row, _columnId, filterValue) => {
const searchValue = String(filterValue ?? "")
.toLowerCase()
.trim()
if (!searchValue) {
return true
}
try {
const rowValue = buildSearchableString(row.original ?? {})
if (specialSearchTokens.has(searchValue)) {
if (matchesSpecialToken(row.original, searchValue)) {
return true
}
return matchesSpecialTokenInText(rowValue, searchValue)
}
return rowValue.includes(searchValue)
} catch (error) {
return false
}
}
const Table = <TData,>({
columns,
data,
classNames,
enableSorting = true,
enableFilters = true,
enableGlobalSearch = true,
globalSearchPlaceholder = "Search...",
addPagination = false,
}: TableProps<TData>) => {
const [sorting, setSorting] = React.useState([])
const [globalFilter, setGlobalFilter] = React.useState("")
const table = useReactTable({
data,
columns,
enableSorting: enableSorting,
enableFilters: enableFilters,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
getPaginationRowModel: getPaginationRowModel(),
getFacetedMinMaxValues: getFacetedMinMaxValues(),
state: {
sorting: sorting,
globalFilter: globalFilter,
},
initialState: {
pagination: {
pageSize: 5,
},
},
onSortingChange: setSorting,
onGlobalFilterChange: setGlobalFilter,
globalFilterFn: defaultGlobalFilterFn,
autoResetPageIndex: false,
})
const currentPage = table.getState().pagination.pageIndex + 1
const pageCount = table.getPageCount()
const pageIndex = table.getState().pagination.pageIndex
const globalSearchTooltipId = React.useId()
React.useEffect(() => {
if (!addPagination) {
return
}
if (pageCount > 0 && pageIndex >= pageCount) {
table.setPageIndex(0)
}
}, [addPagination, pageCount, pageIndex, table])
return (
<>
{enableGlobalSearch && (
<div className={`mb-2 mt-2 mr-2 flex justify-end ${classNames?.searchContainer || ""}`}>
<input
type="text"
value={globalFilter ?? ""}
onChange={(event) => setGlobalFilter(event.target.value)}
placeholder={globalSearchPlaceholder}
aria-label="Search table data"
data-tooltip-id={globalSearchTooltipId}
data-tooltip-content="Searches all data in table (including comments, log dates, and more)."
className={`input input-primary input-bordered border-2 bg-base-300 rounded input-sm w-full max-w-xs focus:outline-secondary ${
classNames?.searchInput || ""
}`}
/>
<TooltipWrapper
id={globalSearchTooltipId}
content="Global search scans all table data, including hidden columns and filters."
className="z-[1099] ourtooltips"
/>
</div>
)}
<table className={classNames?.table || "table"}>
<thead className={classNames?.thead || "text-xl text-base-content"}>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id} className={classNames?.th}>
{header.isPlaceholder ? null : (
<>
<div
className={
header.column.getCanSort()
? "cursor-pointer select-none flex flex-row gap-2"
: "flex flex-row gap-2"
}
onClick={header.column.getToggleSortingHandler()}
>
{flexRender(header.column.columnDef.header, header.getContext())}
{{
asc: <ChevronUpIcon className="w-5 h-5" />,
desc: <ChevronDownIcon className="w-5 h-5" />,
}[header.column.getIsSorted() as string] ?? null}
{header.column.getCanSort() && !header.column.getIsSorted() ? (
<ChevronUpDownIcon className="w-5 h-5" />
) : null}
</div>
{header.column.getCanFilter() ? (
<div>
<Filter column={header.column} />
</div>
) : null}
</>
)}
</th>
))}
</tr>
))}
</thead>
<tbody className={classNames?.tbody || "text-lg"}>
{table.getRowModel().rows.length === 0 ? (
<tr>
<td colSpan={columns.length} className="text-center p-3">
No data found
</td>
</tr>
) : (
table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className={classNames?.td}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))
)}
</tbody>
<tfoot className={classNames?.tfoot}>
{table.getFooterGroups().map((footerGroup) => (
<tr key={footerGroup.id}>
{footerGroup.headers.map((header) => (
<th key={header.id}>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.footer, header.getContext())}
</th>
))}
</tr>
))}
</tfoot>
</table>
{addPagination && table.getRowModel().rows.length > 0 && pageCount > 1 && (
<>
{/* Pagination buttons */}
<div className="flex items-center gap-2">
<button
className={`btn btn-secondary ${classNames?.paginationButton || ""}`}
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
type="button"
>
{"<<"}
</button>
<button
className={`btn btn-secondary ${classNames?.paginationButton || ""}`}
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
type="button"
>
{"<"}
</button>
<button
className={`btn btn-secondary ${classNames?.paginationButton || ""}`}
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
type="button"
>
{">"}
</button>
<button
className={`btn btn-secondary ${classNames?.paginationButton || ""}`}
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
type="button"
>
{">>"}
</button>
{/* Curent page info */}
<span className={`flex items-center gap-1 ${classNames?.pageInfo || ""}`}>
<div>Page</div>
<strong>
{currentPage} of {pageCount}
</strong>
</span>
{/* Go to page input */}
<span className={`flex items-center gap-1 ${classNames?.goToPageInput || ""}`}>
| Go to:
<input
type="number"
defaultValue={table.getState().pagination.pageIndex + 1}
onChange={(e) => {
const page = e.target.value ? Number(e.target.value) - 1 : 0
table.setPageIndex(page)
}}
className="text-secondary input-secondary input-bordered border-2 bg-base-300 rounded input-sm w-20 mt-0"
min={1}
max={table.getPageCount()}
/>
</span>
{/* Select page size input */}
<select
value={table.getState().pagination.pageSize}
onChange={(e) => {
table.setPageSize(Number(e.target.value))
}}
className={`text-secondary input-secondary input-bordered border-2 bg-base-300 rounded input-sm leading-normal mt-0 ${
classNames?.pageSizeSelect || ""
}`}
>
{[5, 10, 20, 30, 40, 50].map((pageSize) => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
</>
)}
</>
)
}
export default Table