@passui/tanstack 0.0.0-stage → 0.1.2

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 (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/package.json +65 -5
  4. package/src/auth-shell/auth-shell.tsx +26 -0
  5. package/src/auth-shell/index.ts +1 -0
  6. package/src/document/compose-viewport.tsx +96 -0
  7. package/src/document/index.ts +1 -0
  8. package/src/form-fields/fields.tsx +192 -0
  9. package/src/form-fields/index.ts +2 -0
  10. package/src/form-fields/selection.tsx +149 -0
  11. package/src/form-fields/submit.tsx +40 -0
  12. package/src/forms/contexts.ts +8 -0
  13. package/src/forms/elements/form-alert.tsx +30 -0
  14. package/src/forms/elements/submit.tsx +1 -0
  15. package/src/forms/fields/avatar-picker.tsx +399 -0
  16. package/src/forms/fields/avatar.tsx +299 -0
  17. package/src/forms/fields/checkbox.tsx +1 -0
  18. package/src/forms/fields/index.ts +32 -0
  19. package/src/forms/fields/input.tsx +1 -0
  20. package/src/forms/fields/multiselect.tsx +1 -0
  21. package/src/forms/fields/otp.tsx +1 -0
  22. package/src/forms/fields/radio-card.tsx +1 -0
  23. package/src/forms/fields/switch.tsx +1 -0
  24. package/src/forms/fields/textarea.tsx +1 -0
  25. package/src/forms/index.ts +30 -0
  26. package/src/mutation/index.ts +1 -0
  27. package/src/mutation/use-app-mutation.ts +160 -0
  28. package/src/route-boundary/default-boundary.tsx +61 -0
  29. package/src/route-boundary/default-loader.tsx +19 -0
  30. package/src/route-boundary/index.ts +3 -0
  31. package/src/route-boundary/not-founder.tsx +50 -0
  32. package/src/settings/index.ts +1 -0
  33. package/src/settings/setting-list.tsx +252 -0
  34. package/src/styles.css +12 -0
  35. package/src/tables/columns.tsx +39 -0
  36. package/src/tables/data-table.tsx +617 -0
  37. package/src/tables/filter-row.tsx +260 -0
  38. package/src/tables/index.ts +3 -0
  39. package/src/tables/pagination.tsx +93 -0
  40. package/src/tables/utils.ts +35 -0
@@ -0,0 +1,617 @@
1
+ import { HugeiconsIcon } from "@hugeicons/react"
2
+ import {
3
+ Cancel01Icon,
4
+ ChevronDownIcon,
5
+ ChevronUpIcon,
6
+ Loading03Icon,
7
+ } from "@hugeicons/core-free-icons"
8
+ import type {
9
+ ColumnDef,
10
+ ColumnFiltersState,
11
+ ColumnVisibilityState,
12
+ RowData,
13
+ RowSelectionState,
14
+ SortingState,
15
+ } from "@tanstack/react-table"
16
+ import {
17
+ columnFilteringFeature,
18
+ columnVisibilityFeature,
19
+ createFilteredRowModel,
20
+ createPaginatedRowModel,
21
+ createSortedRowModel,
22
+ filterFn_arrIncludes,
23
+ filterFn_arrIncludesSome,
24
+ filterFn_equals,
25
+ filterFn_inDateRange,
26
+ filterFn_inNumberRange,
27
+ filterFn_includesString,
28
+ flexRender,
29
+ globalFilteringFeature,
30
+ rowPaginationFeature,
31
+ rowSelectionFeature,
32
+ rowSortingFeature,
33
+ sortFn_alphanumeric,
34
+ sortFn_datetime,
35
+ sortFn_text,
36
+ tableFeatures,
37
+ useTable,
38
+ } from "@tanstack/react-table"
39
+ import type { ReactNode } from "react"
40
+ import { useEffect, useMemo, useState } from "react"
41
+ import { Button } from "@passui/react/button"
42
+ import { Toggle } from "@passui/react/toggle"
43
+ import { SearchField } from "@passui/react"
44
+ import {
45
+ Table,
46
+ TableBody,
47
+ TableCell,
48
+ TableFooter,
49
+ TableHead,
50
+ TableHeader,
51
+ TableRow,
52
+ } from "@passui/react/table"
53
+ import { cn } from "@passui/react/cn"
54
+ import { FilterRow } from "./filter-row"
55
+ import { DataTablePagination } from "./pagination"
56
+ import {
57
+ columnIdOf,
58
+ getColumnLabel,
59
+ isArrayValuedColumn,
60
+ } from "./utils"
61
+
62
+ export const baseTableFeatures = tableFeatures({
63
+ globalFilteringFeature,
64
+ columnFilteringFeature,
65
+ rowSortingFeature,
66
+ rowPaginationFeature,
67
+ columnVisibilityFeature,
68
+ rowSelectionFeature,
69
+ filteredRowModel: createFilteredRowModel(),
70
+ sortedRowModel: createSortedRowModel(),
71
+ paginatedRowModel: createPaginatedRowModel(),
72
+ filterFns: {
73
+ includesString: filterFn_includesString,
74
+ inNumberRange: filterFn_inNumberRange,
75
+ equals: filterFn_equals,
76
+ arrIncludes: filterFn_arrIncludes,
77
+ arrIncludesSome: filterFn_arrIncludesSome,
78
+ inDateRange: filterFn_inDateRange,
79
+ },
80
+ sortFns: {
81
+ text: sortFn_text,
82
+ alphanumeric: sortFn_alphanumeric,
83
+ datetime: sortFn_datetime,
84
+ },
85
+ })
86
+
87
+ export type DataTableFeatures = typeof baseTableFeatures
88
+
89
+ /**
90
+ * `filterVariant: 'date'` is the one thing a caller has to opt into
91
+ * explicitly (`updatedAt`/`createdAt`, or a custom `type: 'date'` column):
92
+ * unlike an array-valued column (detected automatically below, from the
93
+ * actual data), a date is just a string or number at runtime, nothing to
94
+ * sniff it from safely.
95
+ */
96
+ export type DataTableColumnMeta = {
97
+ filterVariant?: "date"
98
+ }
99
+
100
+ export type DataTableColumnDef<
101
+ TData extends RowData,
102
+ TValue = unknown,
103
+ > = ColumnDef<DataTableFeatures, TData, TValue> & {
104
+ meta?: DataTableColumnMeta
105
+ }
106
+
107
+ type DataTableProps<TData extends RowData> = {
108
+ data: TData[]
109
+ // biome-ignore lint/suspicious/noExplicitAny: a column array mixes columns with different value types per accessor, same escape hatch tanstack-table's own ColumnDef[] typings use
110
+ columns: DataTableColumnDef<TData, any>[]
111
+ /**
112
+ * A stable id per row, used as the React key and by react-table's row
113
+ * model. Without this, react-table falls back to the row's array index,
114
+ * so deleting a row shifts every id below it onto a different row's
115
+ * data, reusing DOM nodes (and any open dropdown/overlay state) across
116
+ * what are now different rows. Required, not defaulted, so this can't
117
+ * silently regress.
118
+ */
119
+ getRowId: (row: TData) => string
120
+ "aria-label": string
121
+ emptyMessage?: ReactNode
122
+ searchPlaceholder?: string
123
+ bulkActions?: (
124
+ selectedRows: TData[],
125
+ clearSelection: () => void
126
+ ) => ReactNode
127
+ /** Set false to render just the table. Default true. */
128
+ pagination?: boolean
129
+ pageSizeOptions?: number[]
130
+ onSelectedRowsChange?: (rows: TData[]) => void
131
+ /** Opens a row, e.g. its detail drawer. Ignored while rows are selectable. */
132
+ onRowClick?: (row: TData) => void
133
+ /** A summary row rendered inside the table's own <tfoot>, below the data rows — e.g. a totals line. Gets the visible column count for its colSpan. */
134
+ footer?: (columnCount: number) => ReactNode
135
+ /** True while a background refetch is in flight (e.g. after a mutation invalidates the query). Dims the existing rows and shows a small spinner rather than rendering nothing, since `data` still holds the last good result. */
136
+ isLoading?: boolean
137
+ /** Columns hidden until someone turns them on from the Columns menu, keyed by column id. */
138
+ initialColumnVisibility?: ColumnVisibilityState
139
+ }
140
+
141
+ /** A pill that opens the Columns or Filters panel, with a quiet count when something is hidden or applied. */
142
+ function ToolbarToggle({
143
+ label,
144
+ count,
145
+ open,
146
+ onClick,
147
+ }: {
148
+ label: string
149
+ count: number
150
+ open: boolean
151
+ onClick: () => void
152
+ }) {
153
+ const engaged = open || count > 0
154
+ return (
155
+ <button
156
+ type="button"
157
+ aria-expanded={open}
158
+ onClick={onClick}
159
+ className={cn(
160
+ "flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-border/40 px-3 text-xs transition-colors",
161
+ engaged
162
+ ? "bg-foreground/[0.07] text-foreground"
163
+ : "text-muted-foreground hover:bg-foreground/[0.04] hover:text-foreground"
164
+ )}
165
+ >
166
+ {label}
167
+ {count > 0 && (
168
+ <span className="rounded-full bg-foreground/10 px-1.5 tabular-nums">
169
+ {count}
170
+ </span>
171
+ )}
172
+ <HugeiconsIcon
173
+ icon={ChevronDownIcon}
174
+ className={cn(
175
+ "size-3 transition-transform duration-150",
176
+ open && "rotate-180"
177
+ )}
178
+ />
179
+ </button>
180
+ )
181
+ }
182
+
183
+ /**
184
+ * Self-contained table: pass `data` + `columns`, get sorting, pagination,
185
+ * search, column visibility, per-column filters, and row selection for
186
+ * free. There's no `useTable` state to wire up on the caller's side.
187
+ */
188
+ export function DataTable<TData extends RowData>({
189
+ data,
190
+ columns,
191
+ getRowId,
192
+ emptyMessage = "No results.",
193
+ searchPlaceholder = "Search…",
194
+ bulkActions,
195
+ pagination = true,
196
+ pageSizeOptions,
197
+ onSelectedRowsChange,
198
+ onRowClick,
199
+ footer,
200
+ isLoading = false,
201
+ initialColumnVisibility = {},
202
+ "aria-label": ariaLabel,
203
+ }: DataTableProps<TData>) {
204
+ const [searchInput, setSearchInput] = useState("")
205
+ const [globalFilter, setGlobalFilter] = useState("")
206
+ // Debounced: typing updates searchInput (the input stays responsive),
207
+ // globalFilter (the actual re-filter trigger, synchronous across the
208
+ // whole dataset) only updates 200ms after the last keystroke.
209
+ useEffect(() => {
210
+ const timeout = setTimeout(
211
+ () => setGlobalFilter(searchInput),
212
+ 200
213
+ )
214
+ return () => clearTimeout(timeout)
215
+ }, [searchInput])
216
+ const [sorting, setSorting] = useState<SortingState>([])
217
+ const [columnFilters, setColumnFilters] =
218
+ useState<ColumnFiltersState>([])
219
+ const [columnVisibility, setColumnVisibility] =
220
+ useState<ColumnVisibilityState>(
221
+ initialColumnVisibility
222
+ )
223
+ const [rowSelection, setRowSelection] =
224
+ useState<RowSelectionState>({})
225
+ const [columnsOpen, setColumnsOpen] = useState(false)
226
+ const [filtersOpen, setFiltersOpen] = useState(false)
227
+ const augmentedColumns = useMemo(
228
+ () =>
229
+ columns.map((col) => {
230
+ if (col.filterFn) return col
231
+ const colId = columnIdOf(col)
232
+ if (!colId) return col
233
+ if (col.meta?.filterVariant === "date") {
234
+ return {
235
+ ...col,
236
+ filterFn: filterFn_inDateRange,
237
+ }
238
+ }
239
+ if (isArrayValuedColumn(data, colId)) {
240
+ return {
241
+ ...col,
242
+ filterFn: filterFn_arrIncludesSome,
243
+ }
244
+ }
245
+ return col
246
+ }),
247
+ [columns, data]
248
+ )
249
+
250
+ const table = useTable({
251
+ features: baseTableFeatures,
252
+ data,
253
+ columns: augmentedColumns,
254
+ getRowId,
255
+ enableRowSelection: true,
256
+ state: {
257
+ globalFilter,
258
+ sorting,
259
+ columnFilters,
260
+ columnVisibility,
261
+ rowSelection,
262
+ },
263
+ onGlobalFilterChange: setGlobalFilter,
264
+ onSortingChange: setSorting,
265
+ onColumnFiltersChange: setColumnFilters,
266
+ onColumnVisibilityChange: setColumnVisibility,
267
+ onRowSelectionChange: setRowSelection,
268
+ globalFilterFn: "auto",
269
+ })
270
+
271
+ const toggleableColumns = table
272
+ .getAllColumns()
273
+ .filter((c) => c.getCanHide())
274
+ const hiddenCount = toggleableColumns.filter(
275
+ (c) => !c.getIsVisible()
276
+ ).length
277
+
278
+ const skip = ["select", "actions"]
279
+ const filterableColumns = table
280
+ .getAllColumns()
281
+ .filter(
282
+ (c) =>
283
+ c.getCanFilter() &&
284
+ !skip.includes(c.id) &&
285
+ c.accessorFn !== undefined
286
+ )
287
+
288
+ const activeFilterCount = columnFilters.length
289
+ const selectedCount =
290
+ Object.values(rowSelection).filter(Boolean).length
291
+ const selectedRows = table
292
+ .getSelectedRowModel()
293
+ .rows.map((r) => r.original)
294
+ const clearSelection = () => setRowSelection({})
295
+
296
+ const rows = table.getRowModel().rows
297
+ const columnCount = table.getVisibleLeafColumns().length
298
+
299
+ return (
300
+ <div className="flex flex-col gap-3 [&_div]:no-scrollbar [&_tr]:border-none!">
301
+ <div className="flex flex-wrap items-center gap-3">
302
+ <SearchField
303
+ className="w-full min-w-0 sm:max-w-sm"
304
+ aria-label={searchPlaceholder}
305
+ placeholder={searchPlaceholder}
306
+ autoComplete="off"
307
+ value={searchInput}
308
+ onChange={(event) =>
309
+ setSearchInput(event.target.value)
310
+ }
311
+ />
312
+ {isLoading && (
313
+ <HugeiconsIcon
314
+ icon={Loading03Icon}
315
+ className="size-4 shrink-0 animate-spin"
316
+ aria-label="Loading"
317
+ />
318
+ )}
319
+ <div className="flex shrink-0 items-center gap-1.5 sm:ml-auto">
320
+ <ToolbarToggle
321
+ label="Columns"
322
+ count={hiddenCount}
323
+ open={columnsOpen}
324
+ onClick={() => {
325
+ setColumnsOpen((o) => !o)
326
+ setFiltersOpen(false)
327
+ }}
328
+ />
329
+ <ToolbarToggle
330
+ label="Filters"
331
+ count={activeFilterCount}
332
+ open={filtersOpen}
333
+ onClick={() => {
334
+ setFiltersOpen((o) => !o)
335
+ setColumnsOpen(false)
336
+ }}
337
+ />
338
+ </div>
339
+ </div>
340
+
341
+ {columnsOpen && (
342
+ <div className="flex flex-col gap-2 rounded-2xl border border-border/40 bg-foreground/[0.025] p-4">
343
+ <div className="flex items-center justify-between">
344
+ <h3 className="text-xs">Columns</h3>
345
+ {hiddenCount > 0 && (
346
+ <Button
347
+ type="button"
348
+ variant="ghost"
349
+ size="sm"
350
+ onClick={() =>
351
+ table.resetColumnVisibility()
352
+ }
353
+ className="text-muted-foreground hover:text-foreground"
354
+ >
355
+ Show all
356
+ </Button>
357
+ )}
358
+ </div>
359
+ <div className="flex flex-wrap items-center gap-4">
360
+ {toggleableColumns.map((column) => {
361
+ const visible =
362
+ column.getIsVisible()
363
+ return (
364
+ <div
365
+ key={column.id}
366
+ className="flex cursor-pointer items-center gap-2"
367
+ onClick={() =>
368
+ column.toggleVisibility()
369
+ }
370
+ >
371
+ <Toggle
372
+ style="checkbox"
373
+ labelHidden
374
+ label={getColumnLabel(
375
+ column
376
+ )}
377
+ checked={visible}
378
+ onChange={() =>
379
+ column.toggleVisibility()
380
+ }
381
+ />
382
+ <span className="text-xs">
383
+ {getColumnLabel(
384
+ column
385
+ )}
386
+ </span>
387
+ </div>
388
+ )
389
+ })}
390
+ </div>
391
+ </div>
392
+ )}
393
+
394
+ {filtersOpen && (
395
+ <div className="flex flex-col gap-2 rounded-2xl border border-border/40 bg-foreground/[0.025] p-4">
396
+ <div className="flex items-center justify-between">
397
+ <h3 className="text-xs">Filters</h3>
398
+ {activeFilterCount > 0 && (
399
+ <Button
400
+ type="button"
401
+ variant="ghost"
402
+ size="sm"
403
+ onClick={() =>
404
+ setColumnFilters([])
405
+ }
406
+ className="text-muted-foreground hover:text-foreground"
407
+ >
408
+ <HugeiconsIcon
409
+ icon={Cancel01Icon}
410
+ className="size-3"
411
+ />
412
+ Clear all
413
+ </Button>
414
+ )}
415
+ </div>
416
+ {filterableColumns.length === 0 ? (
417
+ <p className="text-xs text-muted-foreground/60">
418
+ No filterable columns.
419
+ </p>
420
+ ) : (
421
+ <div className="flex flex-col gap-3">
422
+ {filterableColumns.map(
423
+ (column) => (
424
+ <FilterRow
425
+ key={column.id}
426
+ column={column}
427
+ data={data}
428
+ skip={skip}
429
+ isArrayColumn={isArrayValuedColumn(
430
+ data,
431
+ column.id
432
+ )}
433
+ isDateColumn={
434
+ (
435
+ column.columnDef as {
436
+ meta?: DataTableColumnMeta
437
+ }
438
+ ).meta
439
+ ?.filterVariant ===
440
+ "date"
441
+ }
442
+ />
443
+ )
444
+ )}
445
+ </div>
446
+ )}
447
+ </div>
448
+ )}
449
+
450
+ {bulkActions && selectedCount > 0 && (
451
+ <div className="flex items-center gap-3 rounded-full border border-border/40 bg-foreground/[0.035] py-1.5 pr-1.5 pl-4">
452
+ <span className="text-xs font-medium">
453
+ {selectedCount} selected
454
+ </span>
455
+ <div className="h-4 w-px bg-input/40" />
456
+ {bulkActions(
457
+ selectedRows,
458
+ clearSelection
459
+ )}
460
+ <Button
461
+ type="button"
462
+ variant="ghost"
463
+ size="sm"
464
+ onClick={clearSelection}
465
+ className="ml-auto text-muted-foreground hover:text-foreground"
466
+ >
467
+ Clear
468
+ </Button>
469
+ </div>
470
+ )}
471
+
472
+ <Table
473
+ aria-label={ariaLabel}
474
+ className={cn(
475
+ "divide-none!",
476
+ isLoading &&
477
+ "opacity-60 transition-opacity"
478
+ )}
479
+ >
480
+ <TableHeader>
481
+ {table
482
+ .getHeaderGroups()
483
+ .map((headerGroup) => (
484
+ <TableRow
485
+ key={headerGroup.id}
486
+ className="border-b border-border/40 hover:bg-transparent"
487
+ >
488
+ {headerGroup.headers.map(
489
+ (header) => (
490
+ <TableHead
491
+ key={header.id}
492
+ >
493
+ {header.isPlaceholder ? null : header.column.getCanSort() ? (
494
+ <div
495
+ className="flex w-fit cursor-pointer items-center gap-1 text-muted-foreground hover:text-foreground"
496
+ onClick={header.column.getToggleSortingHandler()}
497
+ >
498
+ {flexRender(
499
+ header
500
+ .column
501
+ .columnDef
502
+ .header,
503
+ header.getContext()
504
+ )}
505
+ <div className="flex flex-col">
506
+ <HugeiconsIcon
507
+ icon={
508
+ ChevronUpIcon
509
+ }
510
+ className={cn(
511
+ "size-3 opacity-20",
512
+ header.column.getIsSorted() ===
513
+ "asc" &&
514
+ "opacity-100"
515
+ )}
516
+ />
517
+ <HugeiconsIcon
518
+ icon={
519
+ ChevronDownIcon
520
+ }
521
+ className={cn(
522
+ "-mt-1.5 size-3 opacity-20",
523
+ header.column.getIsSorted() ===
524
+ "desc" &&
525
+ "opacity-100"
526
+ )}
527
+ />
528
+ </div>
529
+ </div>
530
+ ) : (
531
+ flexRender(
532
+ header
533
+ .column
534
+ .columnDef
535
+ .header,
536
+ header.getContext()
537
+ )
538
+ )}
539
+ </TableHead>
540
+ )
541
+ )}
542
+ </TableRow>
543
+ ))}
544
+ </TableHeader>
545
+ <TableBody>
546
+ {rows.length ? (
547
+ rows.map((row) => (
548
+ <TableRow
549
+ key={row.id}
550
+ className={cn(
551
+ "border-b border-border/25 transition-colors last:border-b-0 hover:bg-foreground/[0.025]",
552
+ onRowClick &&
553
+ "cursor-pointer"
554
+ )}
555
+ data-state={
556
+ row.getIsSelected()
557
+ ? "selected"
558
+ : undefined
559
+ }
560
+ onClick={() => {
561
+ if (
562
+ !onSelectedRowsChange
563
+ ) {
564
+ onRowClick?.(
565
+ row.original
566
+ )
567
+ return
568
+ }
569
+ row.toggleSelected()
570
+ onSelectedRowsChange(
571
+ selectedRows
572
+ )
573
+ }}
574
+ >
575
+ {row
576
+ .getVisibleCells()
577
+ .map((cell) => (
578
+ <TableCell
579
+ key={cell.id}
580
+ >
581
+ {flexRender(
582
+ cell.column
583
+ .columnDef
584
+ .cell,
585
+ cell.getContext()
586
+ )}
587
+ </TableCell>
588
+ ))}
589
+ </TableRow>
590
+ ))
591
+ ) : (
592
+ <TableRow>
593
+ <TableCell
594
+ colSpan={columnCount}
595
+ className="h-24 text-center"
596
+ >
597
+ {emptyMessage}
598
+ </TableCell>
599
+ </TableRow>
600
+ )}
601
+ </TableBody>
602
+ {footer && (
603
+ <TableFooter>
604
+ {footer(columnCount)}
605
+ </TableFooter>
606
+ )}
607
+ </Table>
608
+
609
+ {pagination && (
610
+ <DataTablePagination
611
+ table={table}
612
+ pageSizeOptions={pageSizeOptions}
613
+ />
614
+ )}
615
+ </div>
616
+ )
617
+ }