summaryrefslogtreecommitdiff
path: root/components/data-table/data-table-group-list.tsx
blob: c00fac420f95b42b7e6f408b003a0d0084ea97e9 (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
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
"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { useQueryState, parseAsArrayOf, parseAsString } from "nuqs"
import { Layers, Check, ChevronsUpDown, GripVertical, XCircle } from "lucide-react"

import { toSentenceCase, cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover"
import {
  Command,
  CommandList,
  CommandGroup,
  CommandItem,
  CommandInput,
  CommandEmpty,
} from "@/components/ui/command"
import {
  Sortable,
  SortableItem,
  SortableDragHandle,
} from "@/components/ui/sortable"
import { useTranslation } from '@/i18n/client'
import { useParams, usePathname } from "next/navigation";

interface DataTableGroupListProps<TData> {
  /** TanStack Table 인스턴스 (grouping을 이미 사용할 수 있어야 함) */
  table: Table<TData>
  /** 정렬과 동일하게 URL 쿼리에 grouping을 저장할 때 쓰는 debounce 시간 (ms) */
  debounceMs: number
  /** shallow 라우팅 여부 */
  shallow?: boolean
}

export function DataTableGroupList<TData>({
  table,
  debounceMs,
  shallow,
}: DataTableGroupListProps<TData>) {
  const id = React.useId()
  const params = useParams();
    const lng = params?.lng as string;
  const { t } = useTranslation(lng);

  // ------------------------------------------------------
  // 1) 초기 그룹핑 상태 + URL Query State 동기화
  // ------------------------------------------------------
  const initialGrouping = (table.initialState.grouping ?? []) as string[]

  // group 쿼리 파라미터를 string[]로 파싱
  // parseAsArrayOf(parseAsString, ',')를 이용
  const [grouping, setGrouping] = useQueryState(
    "group",
    parseAsArrayOf(parseAsString, ",")
      .withDefault(initialGrouping)
      .withOptions({
        clearOnDefault: true,
        shallow,
      })
  )

  // TanStack Table의 `table.setGrouping()`과 동기화
  // (정렬 모달 예시에서 setSorting()을 쓰듯이 여기서는 setGrouping() 호출)
  React.useEffect(() => {
    table.setGrouping(grouping)
  }, [grouping, table])

  // 이미 중복 추가된 그룹은 제거
  // (정렬 예시에서도 uniqueSorting 했듯이)
  const uniqueGrouping = React.useMemo(
    () => grouping.filter((id, i, self) => self.indexOf(id) === i),
    [grouping]
  )

  // ------------------------------------------------------
  // 2) 그룹핑 가능한 컬럼만 골라내기
  // ------------------------------------------------------
  const groupableColumns = React.useMemo(
    () =>
      table
        .getAllColumns()
        .flatMap((column) => {
          if (column.columns && column.columns.length > 0) {
            return column.columns.filter(c => c.getCanSort());
          }
          return column.getCanSort() ? [column] : [];
        })
        .filter((col) => col.getCanGroup?.() !== false)
        .map((col) => ({
          id: col.id,
          label: toSentenceCase(col.id),
        })),
    [table]
  )

  // 이미 그룹핑 중인 컬럼 제외하고 "추가 가능"한 컬럼들
  const ungroupedColumns = React.useMemo(() => {
    return groupableColumns.filter(
      (column) => !grouping.includes(column.id)
    )
  }, [groupableColumns, grouping])



  // ------------------------------------------------------
  // 3) 그룹 배열을 업데이트하는 함수들
  // ------------------------------------------------------

  // 드래그/드롭으로 순서 변경
  function onGroupOrderChange(newGroups: string[]) {
    setGrouping(newGroups)
  }

  // "Add group" : 아직 그룹핑되지 않은 첫 번째 컬럼 추가
  function addGroup() {
    const firstAvailable = ungroupedColumns[0]
    if (!firstAvailable) return
    setGrouping([...grouping, firstAvailable.id])
  }

  // 특정 아이템(그룹 컬럼 id) 제거
  function removeGroup(id: string) {
    setGrouping((prev) => prev.filter((g) => g !== id))
  }

  // 전체 그룹핑 초기화
  function resetGrouping() {
    setGrouping([])
  }

  // ------------------------------------------------------
  // 4) 렌더링
  // ------------------------------------------------------

  return (
    <Sortable
      // sorting 예시처럼 Sortable 컨테이너로 감싸기
      // 여기선 "grouping"을 바로 value로 넘길 수 없고,
      // Sortable는 { id: UniqueIdentifier }[] 형태를 요구하므로 변환 필요
      value={grouping.map((id) => ({ id }))}
      onValueChange={(items) => {
        // 드래그 완료 시 string[] 형태로 되돌림
        onGroupOrderChange(items.map((i) => i.id))
      }}
      // overlay : 드래그 중 placeholder UI
      overlay={
        <div className="flex items-center gap-2">
          <div className="h-8 w-[11.25rem] rounded-sm bg-primary/10" />
          <div className="h-8 w-24 rounded-sm bg-primary/10" />
          <div className="size-8 shrink-0 rounded-sm bg-primary/10" />
        </div>
      }
    >
      <Popover>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="gap-2"
            aria-label="Open grouping"
            aria-controls={`${id}-group-dialog`}
          >
            <Layers className="size-3" aria-hidden="true" />
            <span className="hidden sm:inline">{t("tableToolBar.group")}</span>
            {uniqueGrouping.length > 0 && (
              <Badge
                variant="secondary"
                className="h-[1.14rem] rounded-[0.2rem] px-[0.32rem] font-mono text-[0.65rem] font-normal"
              >
                {uniqueGrouping.length}
              </Badge>
            )}
          </Button>
        </PopoverTrigger>

        <PopoverContent
          id={`${id}-group-dialog`}
          align="start"
          collisionPadding={16}
          className={cn(
            "flex w-[calc(100vw-theme(spacing.20))] min-w-72 max-w-[25rem] origin-[var(--radix-popover-content-transform-origin)] flex-col p-4 sm:w-[25rem]",
            grouping.length > 0 ? "gap-3.5" : "gap-2"
          )}
        >
          {uniqueGrouping.length > 0 ? (
            <>
              <h4 className="font-medium leading-none">Group by</h4>
              <p className="text-sm text-muted-foreground">
                그룹핑은 불러온 데이터에 한해서 그룹핑이 됩니다.
              </p>
            </>

          ) : (
            <div className="flex flex-col gap-1">
              <h4 className="font-medium leading-none">No grouping applied</h4>
              <p className="text-sm text-muted-foreground">
                Add grouping to organize your results.
              </p>
            </div>
          )}

          {/* 그룹 목록 */}
          <div className="flex max-h-40 flex-col gap-2 overflow-y-auto p-0.5">
            <div className="flex w-full flex-col gap-2">
              {uniqueGrouping.map((colId) => {
                // SortableItem에 key로 colId
                return (
                  <SortableItem key={colId} value={colId} asChild>
                    <div className="flex items-center gap-2">
                      <Popover modal>
                        <PopoverTrigger asChild>
                          <Button
                            variant="outline"
                            size="sm"
                            role="combobox"
                            className="h-8 w-44 justify-between gap-2 rounded focus:outline-none focus:ring-1 focus:ring-ring"
                            aria-label={`Select column for group ${colId}`}
                          >
                            <span className="truncate">
                              {toSentenceCase(colId)}
                            </span>
                            <div className="ml-auto flex items-center gap-1">
                              <ChevronsUpDown
                                className="size-4 shrink-0 opacity-50"
                                aria-hidden="true"
                              />
                            </div>
                          </Button>
                        </PopoverTrigger>
                        <PopoverContent
                          className="w-[var(--radix-popover-trigger-width)] p-0"
                        >
                          <Command>
                            <CommandInput placeholder="Search columns..." />
                            <CommandList>
                              <CommandEmpty>No columns found.</CommandEmpty>
                              <CommandGroup>
                                {ungroupedColumns.map((column) => (
                                  <CommandItem
                                    key={column.id}
                                    value={column.id}
                                    onSelect={(value) => {
                                      // colId -> 새로 선택한 value로 교체
                                      setGrouping((prev) =>
                                        prev.map((g) =>
                                          g === colId ? value : g
                                        )
                                      )
                                    }}
                                  >
                                    <span className="mr-1.5 truncate">
                                      {column.label}
                                    </span>
                                    <Check
                                      className={cn(
                                        "ml-auto size-4 shrink-0",
                                        column.id === colId
                                          ? "opacity-100"
                                          : "opacity-0"
                                      )}
                                      aria-hidden="true"
                                    />
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>

                      {/* remove group */}
                      <Button
                        variant="outline"
                        size="icon"
                        aria-label={`Remove group ${colId}`}
                        className="size-8 shrink-0 rounded"
                        onClick={() => removeGroup(colId)}
                      >
                        <XCircle className="size-3.5" aria-hidden="true" />
                      </Button>

                      {/* drag handle */}
                      <SortableDragHandle
                        variant="outline"
                        size="icon"
                        className="size-8 shrink-0 rounded"
                      >
                        <GripVertical className="size-3.5" aria-hidden="true" />
                      </SortableDragHandle>
                    </div>
                  </SortableItem>
                )
              })}
            </div>
          </div>

          <div className="flex w-full items-center gap-2">
            {/* 새 그룹 추가 */}
            <Button
              size="sm"
              className="h-[1.85rem] rounded"
              onClick={addGroup}
              disabled={grouping.length >= groupableColumns.length}
            >
              Add group
            </Button>
            {grouping.length > 0 && (
              <Button
                size="sm"
                variant="outline"
                className="rounded"
                onClick={resetGrouping}
              >
                Reset grouping
              </Button>
            )}
          </div>
        </PopoverContent>
      </Popover>
    </Sortable>
  )
}