summaryrefslogtreecommitdiff
path: root/components/data-table/data-table-view-options.tsx
blob: 422e3065b4eea1b9f01cfb99363ada5f21a37090 (plain)
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
"use client"

import * as React from "react"
import { RowData, type Table } from "@tanstack/react-table"
import {
  Check,
  ChevronsUpDown,
  GripVertical,
  Settings2,
} from "lucide-react"

import { cn, toSentenceCase } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

// Sortable
import {
  Sortable,
  SortableItem,
  SortableDragHandle,
} from "@/components/ui/sortable"
import { useTranslation } from '@/i18n/client'
import { useParams, usePathname } from "next/navigation";


/**
 * ViewOptionsProps:
 * - table: TanStack Table instance
 * - resetAutoSize: Function to reset autosize calculations (optional)
 */
interface DataTableViewOptionsProps<TData> {
  table: Table<TData>
  resetAutoSize?: () => void
}

declare module "@tanstack/table-core" {
  interface ColumnMeta<TData extends RowData, TValue> {
    excelHeader?: string
    group?: string
    type?: string
    // ...anything else you want
  }
}
/**
 * DataTableViewOptions:
 * - Renders a Popover with hideable columns
 * - Lets user reorder columns (drag & drop) + toggle visibility
 */
export function DataTableViewOptions<TData>({
  table,
  resetAutoSize,
}: DataTableViewOptionsProps<TData>) {
  const triggerRef = React.useRef<HTMLButtonElement>(null)

  const params = useParams();
    const lng = params?.lng as string;
  const { t } = useTranslation(lng);

  // 1) Identify columns that can be hidden
  const hideableCols = React.useMemo(() => {
    return table
      .getAllLeafColumns()
      .filter((col) =>  col.getCanHide())
  }, [table])


  // 2) local state for "columnOrder" (just the ID of hideable columns)
  //    We'll reorder these with drag & drop
  const [columnOrder, setColumnOrder] = React.useState<string[]>(() =>
    hideableCols.map((c) => c.id)
  )

  // 3) onMove: when user finishes drag
  //    - update local `columnOrder` only (no table.setColumnOrder yet)
  const handleMove = React.useCallback(
    ({ activeIndex, overIndex }: { activeIndex: number; overIndex: number }) => {
      setColumnOrder((prev) => {
        const newOrder = [...prev]
        const [removed] = newOrder.splice(activeIndex, 1)
        newOrder.splice(overIndex, 0, removed)
        return newOrder
      })
    },
    []
  )

  // 4) After local state changes, reflect in tanstack table
  //    - We do this in useEffect to avoid "update a different component" error
  React.useEffect(() => {
    // Also consider "non-hideable" columns, if any, to keep them in original positions
    const nonHideable = table
      .getAllColumns()
      .filter((col) => !hideableCols.some((hc) => hc.id === col.id))
      .map((c) => c.id)

    // e.g. place nonHideable at the front, then our local hideable order
    const finalOrder = [...nonHideable, ...columnOrder]

    // Now we set the table's official column order
    table.setColumnOrder(finalOrder)
    
    // Reset auto-size when column order changes
    resetAutoSize?.()
  }, [columnOrder, hideableCols, table, resetAutoSize])


  return (
    <Popover modal>
      <PopoverTrigger asChild>
        <Button
          ref={triggerRef}
          aria-label="Toggle columns"
          variant="outline"
          role="combobox"
          size="sm"
          className="gap-2"
        >
          <Settings2 className="size-4" />
          <span className="hidden sm:inline">{t("tableToolBar.view")}</span>
        </Button>
      </PopoverTrigger>

      <PopoverContent
        align="end"
        className="w-44 p-0"
        onCloseAutoFocus={() => triggerRef.current?.focus()}
      >
        <Command>
          <CommandInput placeholder="Search columns..." />
          <CommandList>
            <CommandEmpty>No columns found.</CommandEmpty>

            <CommandGroup>
              {/**
               * 5) Sortable: we pass an array of { id: string } from `columnOrder`,
               *    so we can reorder them with drag & drop
               */}
              <Sortable
                value={columnOrder.map((id) => ({ id }))}
                onMove={handleMove}
              >
                {columnOrder.map((colId) => {
                  // find column instance
                  const column = hideableCols.find((c) => c.id === colId)

                  if (!column) return null

                  const columnLabel = column?.columnDef?.meta?.excelHeader || column.id

                  return (
                    <SortableItem key={colId} value={colId} asChild>
                      <CommandItem
                        onSelect={() => {
                          column.toggleVisibility(!column.getIsVisible())
                          // Reset autosize calculations when toggling columns
                          resetAutoSize?.()
                        }}
                      >
                        {/* Drag handle on the left */}
                        <SortableDragHandle
                          variant="outline"
                          size="icon"
                          className="mr-2 size-5 shrink-0 rounded cursor-grab active:cursor-grabbing"
                        >
                          <GripVertical className="size-3.5" aria-hidden="true" />
                        </SortableDragHandle>

                        {/* label with tooltip for long names */}
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <span className="truncate">
                                {columnLabel}
                              </span>
                            </TooltipTrigger>
                            <TooltipContent>
                              {columnLabel}
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>

                        {/* check if visible */}
                        <Check
                          className={cn(
                            "ml-auto size-4 shrink-0",
                            column.getIsVisible() ? "opacity-100" : "opacity-0"
                          )}
                        />
                      </CommandItem>
                    </SortableItem>
                  )
                })}
              </Sortable>
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  )
}