260724_01_ENH: KriAutoComplete 버그 수정 및 Datatable pined row 추가

This commit is contained in:
2026-07-24 15:45:24 +09:00
parent b3d0549f7f
commit 288734f378
4 changed files with 113 additions and 18 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "kri-ui-registry", "name": "kri-ui-registry",
"version": "0.9.1", "version": "0.9.2",
"private": true, "private": true,
"description": "KRI internal shadcn UI registry", "description": "KRI internal shadcn UI registry",
"scripts": { "scripts": {

View File

@@ -24,6 +24,7 @@ export interface KriAutoCompleteBaseProps<T> {
withInfo?: boolean withInfo?: boolean
disabled?: boolean disabled?: boolean
'aria-invalid'?: boolean 'aria-invalid'?: boolean
modalPopover?: boolean
} }
export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> { export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
@@ -73,6 +74,7 @@ export function KriMultiSelect<T = unknown>({
onOptionsChange, onOptionsChange,
disabled, disabled,
'aria-invalid': ariaInvalid, 'aria-invalid': ariaInvalid,
modalPopover = true,
}: KriMultiSelectProps<T>) { }: KriMultiSelectProps<T>) {
const options = React.useMemo( const options = React.useMemo(
() => toOptions(items, getValue, getLabel, withInfo), () => toOptions(items, getValue, getLabel, withInfo),
@@ -104,6 +106,7 @@ export function KriMultiSelect<T = unknown>({
deduplicateOptions deduplicateOptions
disabled={disabled} disabled={disabled}
aria-invalid={ariaInvalid} aria-invalid={ariaInvalid}
modalPopover={modalPopover}
/> />
</div> </div>
) )
@@ -149,6 +152,7 @@ function KriSingleSelectInner<T>({
clearValue = '__CLEAR__', clearValue = '__CLEAR__',
disabled, disabled,
'aria-invalid': ariaInvalid, 'aria-invalid': ariaInvalid,
modalPopover = true,
}: KriSingleSelectProps<T>, forwardedRef: React.ForwardedRef<MultiSelectRef>) { }: KriSingleSelectProps<T>, forwardedRef: React.ForwardedRef<MultiSelectRef>) {
const ref = React.useRef<MultiSelectRef>(null) const ref = React.useRef<MultiSelectRef>(null)
React.useImperativeHandle( React.useImperativeHandle(
@@ -217,6 +221,7 @@ function KriSingleSelectInner<T>({
disabled={disabled} disabled={disabled}
aria-invalid={ariaInvalid} aria-invalid={ariaInvalid}
title={showSelectedTooltip ? selectedLabel ?? value : undefined} title={showSelectedTooltip ? selectedLabel ?? value : undefined}
modalPopover={modalPopover}
/> />
</div> </div>
) )

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import { useCallback, useEffect, useMemo, useState } from 'react' import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import type { OnChangeFn, PaginationState, Row, RowSelectionState, SortingState } from '@tanstack/react-table' import type { OnChangeFn, PaginationState, Row, RowPinningState, RowSelectionState, SortingState } from '@tanstack/react-table'
import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table' import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table'
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react' import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@@ -12,6 +12,8 @@ import type { DataTableColumn, DataTableProps } from './DataTable.type'
import { DataTablePagination } from './DataTablePagination' import { DataTablePagination } from './DataTablePagination'
import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag' import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag'
const EMPTY_PINNED_ROWS: never[] = []
export function DataTable<TData, TValue = unknown>({ export function DataTable<TData, TValue = unknown>({
columns, columns,
data, data,
@@ -32,6 +34,9 @@ export function DataTable<TData, TValue = unknown>({
emptyText = '데이터가 없습니다.', emptyText = '데이터가 없습니다.',
className, className,
maxBodyHeight, maxBodyHeight,
disablePagination = false,
topPinnedRows = EMPTY_PINNED_ROWS,
bottomPinnedRows = EMPTY_PINNED_ROWS,
}: Readonly<DataTableProps<TData, TValue>>) { }: Readonly<DataTableProps<TData, TValue>>) {
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize }) const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
const [sorting, setSorting] = useState<SortingState>([]) const [sorting, setSorting] = useState<SortingState>([])
@@ -51,7 +56,7 @@ export function DataTable<TData, TValue = unknown>({
aria-label="전체 선택" aria-label="전체 선택"
/> />
) : null, ) : null,
cell: ({ row }) => ( cell: ({ row }) => row.getIsPinned() ? null : (
<Checkbox <Checkbox
checked={row.getIsSelected()} checked={row.getIsSelected()}
onCheckedChange={(value) => { onCheckedChange={(value) => {
@@ -92,22 +97,43 @@ export function DataTable<TData, TValue = unknown>({
[isClient, onServerPaginationChange], [isClient, onServerPaginationChange],
) )
const combinedData = useMemo(
() => [...topPinnedRows, ...data, ...bottomPinnedRows],
[topPinnedRows, data, bottomPinnedRows],
)
const internalGetRowId = useCallback((row: TData, index: number) => {
if (index < topPinnedRows.length) return `__top-pinned-${index}`
if (index >= topPinnedRows.length + data.length) {
return `__bottom-pinned-${index - topPinnedRows.length - data.length}`
}
const originalIndex = index - topPinnedRows.length
return getRowId ? getRowId(data[originalIndex], originalIndex) : String(originalIndex)
}, [topPinnedRows.length, data, getRowId])
const rowPinning = useMemo<RowPinningState>(() => ({
top: topPinnedRows.map((_, i) => `__top-pinned-${i}`),
bottom: bottomPinnedRows.map((_, i) => `__bottom-pinned-${i}`),
}), [topPinnedRows, bottomPinnedRows])
const table = useReactTable({ const table = useReactTable({
data, data: combinedData,
columns: enhancedColumns, columns: enhancedColumns,
pageCount: isClient ? undefined : serverPageCount, pageCount: isClient ? undefined : serverPageCount,
state: { sorting, pagination, rowSelection }, state: { sorting, pagination, rowSelection, rowPinning },
enableRowSelection: selectionEnabled, enableRowSelection: (row) => selectionEnabled && !row.getIsPinned(),
enableRowPinning: true,
keepPinnedRows: true,
onRowSelectionChange: setRowSelection, onRowSelectionChange: setRowSelection,
onSortingChange: setSorting, onSortingChange: setSorting,
onPaginationChange: handlePaginationChange, onPaginationChange: handlePaginationChange,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
getSortedRowModel: isClient ? getSortedRowModel() : undefined, getSortedRowModel: isClient ? getSortedRowModel() : undefined,
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined, getPaginationRowModel: isClient && !disablePagination ? getPaginationRowModel() : undefined,
manualPagination: !isClient, manualPagination: !isClient,
manualSorting: !isClient, manualSorting: !isClient,
enableSortingRemoval: false, enableSortingRemoval: false,
...(getRowId ? { getRowId } : {}), getRowId: internalGetRowId,
}) })
useEffect(() => { useEffect(() => {
@@ -135,15 +161,50 @@ export function DataTable<TData, TValue = unknown>({
const totalCount = isClient ? data.length : (serverTotalCount ?? 0) const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
const topRows = table.getTopRows()
const centerRows = table.getCenterRows()
const bottomRows = table.getBottomRows()
const scrollContainerRef = useRef<HTMLDivElement>(null)
const [topOffsets, setTopOffsets] = useState<number[]>([])
const [bottomOffsets, setBottomOffsets] = useState<number[]>([])
useLayoutEffect(() => {
if (!maxBodyHeight) return
const container = scrollContainerRef.current
if (!container) return
const headerHeight = container.querySelector('thead')?.getBoundingClientRect().height ?? 0
const bodyRows = Array.from(container.querySelectorAll('tbody > tr'))
const topRowEls = bodyRows.slice(0, topRows.length)
const bottomRowEls = bottomRows.length ? bodyRows.slice(-bottomRows.length) : []
let topAcc = headerHeight
setTopOffsets(topRowEls.map((element) => {
const offset = topAcc
topAcc += element.getBoundingClientRect().height
return offset
}))
let bottomAcc = 0
const offsets: number[] = []
for (let index = bottomRowEls.length - 1; index >= 0; index -= 1) {
offsets[index] = bottomAcc
bottomAcc += bottomRowEls[index].getBoundingClientRect().height
}
setBottomOffsets(offsets)
}, [maxBodyHeight, topRows.length, bottomRows.length, centerRows.length])
return ( return (
<div className={cn('w-full space-y-4', className)}> <div className={cn('w-full space-y-4', className)}>
<div className="rounded-md border"> <div className="rounded-md border">
<div <div
ref={scrollContainerRef}
className={cn('relative w-full overflow-x-auto', maxBodyHeight && 'overflow-y-auto')} className={cn('relative w-full overflow-x-auto', maxBodyHeight && 'overflow-y-auto')}
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined} style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
> >
<table className="w-full caption-bottom text-sm"> <table className="w-full caption-bottom text-sm">
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-10 bg-background')}> <TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-20 bg-background')}>
{table.getHeaderGroups().map((headerGroup) => ( {table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent"> <TableRow key={headerGroup.id} className="hover:bg-transparent">
{headerGroup.headers.map((header) => { {headerGroup.headers.map((header) => {
@@ -170,7 +231,19 @@ export function DataTable<TData, TValue = unknown>({
))} ))}
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{table.getRowModel().rows.length ? table.getRowModel().rows.map((row) => ( {topRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { top: topOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
{centerRows.length ? centerRows.map((row) => (
<TableRow <TableRow
key={row.id} key={row.id}
data-state={row.getIsSelected() ? 'selected' : undefined} data-state={row.getIsSelected() ? 'selected' : undefined}
@@ -191,18 +264,32 @@ export function DataTable<TData, TValue = unknown>({
)) : ( )) : (
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow> <TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
)} )}
{bottomRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { bottom: bottomOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
</TableBody> </TableBody>
</table> </table>
</div> </div>
</div> </div>
<DataTablePagination {!disablePagination && (
table={table} <DataTablePagination
isClient={isClient} table={table}
totalCount={totalCount} isClient={isClient}
pageSizeOptions={pageSizeOptions} totalCount={totalCount}
paginationItemsToDisplay={paginationItemsToDisplay} pageSizeOptions={pageSizeOptions}
/> paginationItemsToDisplay={paginationItemsToDisplay}
/>
)}
</div> </div>
) )
} }

View File

@@ -35,4 +35,7 @@ export interface DataTableProps<TData, TValue = unknown> {
emptyText?: string emptyText?: string
className?: string className?: string
maxBodyHeight?: string maxBodyHeight?: string
disablePagination?: boolean
topPinnedRows?: TData[]
bottomPinnedRows?: TData[]
} }