260706_01_ENH: DataTable 버그 수정 및 Date 관련 컴포넌트 추가

This commit is contained in:
2026-07-06 15:22:51 +09:00
parent 88043ecc34
commit e77fe4368a
13 changed files with 476 additions and 244 deletions

View File

@@ -0,0 +1,27 @@
import type { HTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export type CalendarDateRange = {
from?: Date;
to?: Date;
};
type CalendarBaseProps = Omit<HTMLAttributes<HTMLDivElement>, "onSelect">;
type CalendarSingleProps = CalendarBaseProps & {
mode: "single";
selected?: Date;
onSelect?: (date: Date | undefined) => void;
};
type CalendarRangeProps = CalendarBaseProps & {
mode: "range";
selected?: CalendarDateRange;
onSelect?: (range: CalendarDateRange | undefined) => void;
};
export type CalendarProps = CalendarSingleProps | CalendarRangeProps;
export function Calendar({ className, ...props }: CalendarProps) {
return <div className={cn(className)} data-mode={props.mode} />;
}

View File

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

View File

@@ -78,7 +78,7 @@ export function KriMultiSelect<T = unknown>({
) )
return ( return (
<div className={cn('flex-none overflow-hidden', widthClassName, heightClassName)}> <div className={cn('flex-none', widthClassName, heightClassName)}>
<MultiSelect<T> <MultiSelect<T>
options={options} options={options}
defaultValue={value} defaultValue={value}
@@ -96,7 +96,7 @@ export function KriMultiSelect<T = unknown>({
onSearchValueChange={onSearchValueChange} onSearchValueChange={onSearchValueChange}
maxCount={maxCount} maxCount={maxCount}
hideSelectAll={hideSelectAll} hideSelectAll={hideSelectAll}
autoSize autoSize={!widthClassName}
singleLine singleLine
resetOnDefaultValueChange resetOnDefaultValueChange
deduplicateOptions deduplicateOptions
@@ -154,7 +154,7 @@ export function KriSingleSelect<T = unknown>({
const selectedLabel = options.find((option) => option.value === value)?.label const selectedLabel = options.find((option) => option.value === value)?.label
return ( return (
<div className={cn('flex-none overflow-hidden', widthClassName, heightClassName)}> <div className={cn('flex-none', widthClassName, heightClassName)}>
<MultiSelect<T> <MultiSelect<T>
ref={ref} ref={ref}
options={options} options={options}
@@ -194,7 +194,7 @@ export function KriSingleSelect<T = unknown>({
preventDeselect={preventDeselect} preventDeselect={preventDeselect}
hideOptionCheck={hideOptionCheck} hideOptionCheck={hideOptionCheck}
hideSelectAll hideSelectAll
autoSize autoSize={!widthClassName}
singleLine singleLine
closeOnSelect closeOnSelect
resetOnDefaultValueChange resetOnDefaultValueChange

View File

@@ -0,0 +1,82 @@
"use client";
import {CalendarIcon, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Calendar} from "@/components/ui/calendar";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
import {cn} from "@/lib/utils";
const parseDate = (value: string) => {
if (!value) return undefined
const [year, month, day] = value.split('-').map(Number)
if (!year || !month || !day) return undefined
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return undefined
}
return date
}
const formatDate = (date: Date | undefined) => {
if (!date) return ''
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
export function KriDatePicker({
value,
onChange,
placeholder = "날짜 선택",
className,
}: {
value: string;
onChange: (value: string) => void;
placeholder?: string;
className?: string;
}) {
const selected = parseDate(value);
return (
<div className={cn("relative", className)}>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
className={cn("h-9 w-full justify-start bg-white pr-8 text-left font-normal", !value && "text-muted-foreground")}
>
<CalendarIcon className="h-4 w-4" />
{selected ? formatDate(selected) : placeholder}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={selected}
onSelect={(date) => onChange(date ? formatDate(date) : "")}
/>
</PopoverContent>
</Popover>
{value && (
<button
type="button"
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
onClick={(event) => {
event.stopPropagation();
onChange("");
}}
aria-label="날짜 초기화"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
);
}

View File

@@ -1,10 +1,8 @@
'use client' 'use client'
import { useRef } from 'react' import { CalendarIcon, X } from 'lucide-react'
import { CalendarDays, X } from 'lucide-react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Calendar } from '@/components/ui/calendar'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
@@ -23,6 +21,30 @@ export type KriDateRangePickerProps = {
disabled?: boolean disabled?: boolean
} }
const parseDate = (value: string) => {
if (!value) return undefined
const [year, month, day] = value.split('-').map(Number)
if (!year || !month || !day) return undefined
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return undefined
}
return date
}
const formatDate = (date: Date | undefined) => {
if (!date) return ''
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
export function KriDateRangePicker({ export function KriDateRangePicker({
value, value,
onChange, onChange,
@@ -32,7 +54,11 @@ export function KriDateRangePicker({
contentClassName, contentClassName,
disabled = false, disabled = false,
}: KriDateRangePickerProps) { }: KriDateRangePickerProps) {
const toInputRef = useRef<HTMLInputElement | null>(null) const selected = {
from: parseDate(value.from),
to: parseDate(value.to),
}
const selectedRange = selected.from || selected.to ? selected : undefined
const displayText = value.from && value.to const displayText = value.from && value.to
? `${value.from} ~ ${value.to}` ? `${value.from} ~ ${value.to}`
@@ -43,76 +69,52 @@ export function KriDateRangePicker({
: placeholder : placeholder
const hasValue = value.from.length > 0 || value.to.length > 0 const hasValue = value.from.length > 0 || value.to.length > 0
const invalidRange = value.from.length > 0 && value.to.length > 0 && value.from > value.to
const focusAndOpenToDate = () => {
const input = toInputRef.current
if (!input) return
input.focus()
const inputWithPicker = input as HTMLInputElement & { showPicker?: () => void }
inputWithPicker.showPicker?.()
if (!inputWithPicker.showPicker) {
input.click()
}
}
return ( return (
<div className={cn('flex items-center gap-2', className)}> <div className={cn('relative', className)}>
<Popover> <Popover>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
disabled={disabled} disabled={disabled}
className={cn('justify-start min-w-[260px] font-normal', triggerClassName)} className={cn(
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
!hasValue && 'text-muted-foreground',
triggerClassName,
)}
> >
<CalendarDays className="w-4 h-4" /> <CalendarIcon className="h-4 w-4" />
<span className="truncate">{displayText}</span> <span className="truncate">{displayText}</span>
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent align="start" className={cn('w-[360px] space-y-3', contentClassName)}> <PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
<Label className="font-semibold">조회 기간</Label> <Calendar
mode="range"
<div className="flex items-center gap-2"> selected={selectedRange}
<Input onSelect={(range) => {
type="date" onChange({
value={value.from} from: formatDate(range?.from),
onChange={(e) => { to: formatDate(range?.to),
const nextFrom = e.target.value
onChange({ ...value, from: nextFrom })
if (nextFrom) {
requestAnimationFrame(() => {
focusAndOpenToDate()
}) })
}
}} }}
/> />
<span className="text-sm text-muted-foreground">~</span>
<Input
ref={toInputRef}
type="date"
value={value.to}
onChange={(e) => onChange({ ...value, to: e.target.value })}
/>
</div>
{invalidRange && (
<p className="text-xs text-red-600">조회 시작일은 종료일보다 이후일 수 없습니다.</p>
)}
</PopoverContent> </PopoverContent>
</Popover> </Popover>
<Button {hasValue && !disabled ? (
<button
type="button" type="button"
variant="ghost" className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
size="icon-sm" onClick={(event) => {
onClick={() => onChange({ from: '', to: '' })} event.stopPropagation()
disabled={disabled || !hasValue} onChange({ from: '', to: '' })
}}
aria-label="조회 기간 초기화" aria-label="조회 기간 초기화"
> >
<X className="w-4 h-4" /> <X className="h-3.5 w-3.5" />
</Button> </button>
) : null}
</div> </div>
) )
} }

View File

@@ -0,0 +1,103 @@
'use client'
import { CalendarIcon, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Calendar } from '@/components/ui/calendar'
import { Input } from '@/components/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
export type KriDateTimePickerProps = {
value: string
onChange: (value: string) => void
placeholder?: string
className?: string
triggerClassName?: string
contentClassName?: string
disabled?: boolean
}
// value는 <input type="datetime-local">과 동일한 'yyyy-MM-ddTHH:mm' 포맷을 쓴다
const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
if (!value) return { date: undefined, time: '' }
const [datePart, timePart = ''] = value.split('T')
const [year, month, day] = datePart.split('-').map(Number)
if (!year || !month || !day) return { date: undefined, time: timePart }
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return { date: undefined, time: timePart }
}
return { date, time: timePart }
}
const toValue = (date: Date | undefined, time: string): string => {
if (!date) return ''
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}T${time || '00:00'}`
}
export function KriDateTimePicker({
value,
onChange,
placeholder = '날짜/시간 선택',
className,
triggerClassName,
contentClassName,
disabled = false,
}: KriDateTimePickerProps) {
const { date, time } = parseDateTime(value)
const hasValue = date !== undefined
return (
<div className={cn('flex items-center gap-2', className)}>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className={cn(
'w-40 justify-start bg-white text-left font-normal',
!hasValue && 'text-muted-foreground',
triggerClassName,
)}
>
<CalendarIcon className="h-4 w-4" />
<span className="truncate">{hasValue ? value.split('T')[0] : placeholder}</span>
</Button>
</PopoverTrigger>
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
<Calendar mode="single" selected={date} onSelect={(nextDate) => onChange(toValue(nextDate, time || '00:00'))} />
</PopoverContent>
</Popover>
<Input
type="time"
className="w-32"
value={time}
disabled={disabled || !hasValue}
onChange={(event) => onChange(toValue(date, event.target.value))}
/>
{hasValue && !disabled ? (
<button
type="button"
className="inline-flex h-5 w-5 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
onClick={() => onChange('')}
aria-label="날짜/시간 초기화"
>
<X className="h-3.5 w-3.5" />
</button>
) : null}
</div>
)
}
export default KriDateTimePicker

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import { useEffect, useMemo, useState } from 'react' import { useCallback, useEffect, useMemo, useState } from 'react'
import type { PaginationState, Row, RowSelectionState, SortingState } from '@tanstack/react-table' import type { OnChangeFn, PaginationState, Row, 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'
@@ -20,6 +20,7 @@ export function DataTable<TData, TValue = unknown>({
isClient = true, isClient = true,
pageCount: serverPageCount, pageCount: serverPageCount,
totalCount: serverTotalCount, totalCount: serverTotalCount,
pagination: externalPagination,
onPaginationChange: onServerPaginationChange, onPaginationChange: onServerPaginationChange,
onSortingChange: onServerSortingChange, onSortingChange: onServerSortingChange,
selectMode = 'none', selectMode = 'none',
@@ -31,7 +32,7 @@ export function DataTable<TData, TValue = unknown>({
emptyText = '데이터가 없습니다.', emptyText = '데이터가 없습니다.',
className, className,
}: Readonly<DataTableProps<TData, TValue>>) { }: Readonly<DataTableProps<TData, TValue>>) {
const [pagination, setPagination] = 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>([])
const [rowSelection, setRowSelection] = useState<RowSelectionState>({}) const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const drag = usePreventClickOnDrag() const drag = usePreventClickOnDrag()
@@ -67,6 +68,25 @@ export function DataTable<TData, TValue = unknown>({
return [selectionColumn, ...columns] return [selectionColumn, ...columns]
}, [columns, selectMode, selectionEnabled]) }, [columns, selectMode, selectionEnabled])
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
(updater) => {
if (isClient) {
setInternalPagination(updater)
return
}
if (onServerPaginationChange) {
onServerPaginationChange(updater)
return
}
setInternalPagination(updater)
},
[isClient, onServerPaginationChange],
)
const table = useReactTable({ const table = useReactTable({
data, data,
columns: enhancedColumns, columns: enhancedColumns,
@@ -75,7 +95,7 @@ export function DataTable<TData, TValue = unknown>({
enableRowSelection: selectionEnabled, enableRowSelection: selectionEnabled,
onRowSelectionChange: setRowSelection, onRowSelectionChange: setRowSelection,
onSortingChange: setSorting, onSortingChange: setSorting,
onPaginationChange: setPagination, onPaginationChange: handlePaginationChange,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
getSortedRowModel: isClient ? getSortedRowModel() : undefined, getSortedRowModel: isClient ? getSortedRowModel() : undefined,
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined, getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
@@ -85,10 +105,6 @@ export function DataTable<TData, TValue = unknown>({
...(getRowId ? { getRowId } : {}), ...(getRowId ? { getRowId } : {}),
}) })
useEffect(() => {
if (!isClient) onServerPaginationChange?.(pagination)
}, [isClient, onServerPaginationChange, pagination])
useEffect(() => { useEffect(() => {
if (!isClient) onServerSortingChange?.(sorting) if (!isClient) onServerSortingChange?.(sorting)
}, [isClient, onServerSortingChange, sorting]) }, [isClient, onServerSortingChange, sorting])

View File

@@ -1,4 +1,4 @@
import type { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table' import type { ColumnDef, PaginationState, SortingState, Updater } from '@tanstack/react-table'
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi' export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue>
@@ -23,7 +23,8 @@ export interface DataTableProps<TData, TValue = unknown> {
isClient?: boolean isClient?: boolean
pageCount?: number pageCount?: number
totalCount?: number totalCount?: number
onPaginationChange?: (pagination: PaginationState) => void pagination?: PaginationState
onPaginationChange?: (updater: Updater<PaginationState>) => void
onSortingChange?: (sorting: SortingState) => void onSortingChange?: (sorting: SortingState) => void
selectMode?: SelectMode selectMode?: SelectMode
onRowClick?: (row: TData) => void onRowClick?: (row: TData) => void

View File

@@ -22,6 +22,8 @@ export function DataTablePagination<TData>({
pageSizeOptions, pageSizeOptions,
paginationItemsToDisplay, paginationItemsToDisplay,
}: DataTablePaginationProps<TData>) { }: DataTablePaginationProps<TData>) {
'use no memo'
const currentPage = table.getState().pagination.pageIndex + 1 const currentPage = table.getState().pagination.pageIndex + 1
const pageCount = table.getPageCount() const pageCount = table.getPageCount()
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({ const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({

View File

@@ -48,7 +48,7 @@ export function KriHeader({
) : null} ) : null}
{logo ? ( {logo ? (
<button type="button" className="flex shrink-0 items-center" onClick={() => onNavigate?.(homePath)}> <button type="button" className="flex shrink-0 items-center cursor-pointer" onClick={() => onNavigate?.(homePath)}>
{logo} {logo}
</button> </button>
) : null} ) : null}

View File

@@ -47,7 +47,7 @@ function OptionItem<T>({
value={`${option.label} ${option.value}`} value={`${option.label} ${option.value}`}
disabled={option.disabled} disabled={option.disabled}
onSelect={onToggle} onSelect={onToggle}
className="flex items-center" className="flex items-center cursor-pointer"
> >
{!hideOptionCheck ? ( {!hideOptionCheck ? (
<span <span
@@ -124,7 +124,7 @@ export function MultiSelectContent<T>({
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? ( {selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
<> <>
<CommandGroup> <CommandGroup>
<CommandItem value="__kri_select_all__" onSelect={onToggleAll}> <CommandItem className="cursor-pointer" value="__kri_select_all__" onSelect={onToggleAll}>
<span <span
className={cn( className={cn(
'border-primary flex size-4 items-center justify-center rounded-sm border', 'border-primary flex size-4 items-center justify-center rounded-sm border',

View File

@@ -24,8 +24,7 @@
"description": "시작일과 종료일을 선택하고 초기화할 수 있는 KRI 공통 날짜 범위 컴포넌트입니다.", "description": "시작일과 종료일을 선택하고 초기화할 수 있는 KRI 공통 날짜 범위 컴포넌트입니다.",
"registryDependencies": [ "registryDependencies": [
"button", "button",
"input", "calendar",
"label",
"popover" "popover"
], ],
"dependencies": [ "dependencies": [