260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋
This commit is contained in:
@@ -2,15 +2,17 @@
|
||||
|
||||
import * as React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {MultiSelect, MultiSelectRef} from '@/components/ui/multi-select'
|
||||
import type { MultiSelectOption } from '@/components/ui/multi-select'
|
||||
import { MultiSelect } from '@/components/common/multi-select'
|
||||
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
||||
|
||||
type BaseProps<T> = {
|
||||
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
||||
|
||||
export interface KriAutoCompleteBaseProps<T> {
|
||||
items: T[]
|
||||
searchable?: boolean
|
||||
searchMode?: "filter" | "inputOnly";
|
||||
defaultSearchValue?: string;
|
||||
onSearchValueChange?: (value: string) => void;
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
defaultSearchValue?: string
|
||||
onSearchValueChange?: (value: string) => void
|
||||
placeholder?: string
|
||||
widthClassName?: string
|
||||
heightClassName?: string
|
||||
@@ -19,219 +21,185 @@ type BaseProps<T> = {
|
||||
className?: string
|
||||
getValue?: (item: T) => string
|
||||
getLabel?: (item: T) => string
|
||||
|
||||
/** ✅ 옵션: 원본 item을 option.info에 실어둘지 */
|
||||
withInfo?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
type KriMultiSelectProps<T = unknown> = BaseProps<T> & {
|
||||
export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||
value: string[]
|
||||
onChange: (value: string[]) => void
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
hideSelectAll?: boolean
|
||||
|
||||
/** ✅ withInfo=true일 때만 의미 있게 쓰면 됨 */
|
||||
onItemsChange?: (items: T[]) => void
|
||||
onOptionsChange?: (options: MultiSelectOption<T>[]) => void
|
||||
}
|
||||
|
||||
function toOptions<T>(
|
||||
items: T[],
|
||||
getValue: ((item: T) => string) | undefined,
|
||||
getLabel: ((item: T) => string) | undefined,
|
||||
withInfo: boolean,
|
||||
): MultiSelectOption<T>[] {
|
||||
return items.map((item) => ({
|
||||
value: getValue ? getValue(item) : String(item),
|
||||
label: getLabel ? getLabel(item) : String(item),
|
||||
...(withInfo ? { info: item } : {}),
|
||||
}))
|
||||
}
|
||||
|
||||
export function KriMultiSelect<T = unknown>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
defaultSearchValue = "",
|
||||
onSearchValueChange,
|
||||
maxCount = 1,
|
||||
maxSelected,
|
||||
hideSelectAll = false,
|
||||
placeholder = 'Select options',
|
||||
widthClassName,
|
||||
heightClassName,
|
||||
spanClassName = "text-lg",
|
||||
badgeClassName = "text-lg",
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemsChange,
|
||||
onOptionsChange,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const msRef = React.useRef<MultiSelectRef>(null);
|
||||
|
||||
const extractValue = React.useCallback(
|
||||
(item: T) => (getValue ? getValue(item) : String(item)),
|
||||
[getValue]
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
maxCount = 1,
|
||||
maxSelected,
|
||||
hideSelectAll = false,
|
||||
placeholder = 'Select options',
|
||||
widthClassName,
|
||||
heightClassName,
|
||||
spanClassName = 'text-base',
|
||||
badgeClassName = 'text-base',
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemsChange,
|
||||
onOptionsChange,
|
||||
disabled,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const options = React.useMemo(
|
||||
() => toOptions(items, getValue, getLabel, withInfo),
|
||||
[getLabel, getValue, items, withInfo],
|
||||
)
|
||||
const extractLabel = React.useCallback(
|
||||
(item: T) => (getLabel ? getLabel(item) : String(item)),
|
||||
[getLabel]
|
||||
)
|
||||
|
||||
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
|
||||
return items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
...(withInfo ? { info: item } : {}), // ✅ 필요할 때만 info를 실음
|
||||
}))
|
||||
}, [items, extractValue, extractLabel, withInfo])
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect<T>
|
||||
ref={msRef}
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
onValueChange={onChange}
|
||||
onOptionChange={onOptionsChange}
|
||||
onInfoChange={onItemsChange}
|
||||
maxSelected={maxSelected}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white text-lg", className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
maxCount={maxCount}
|
||||
hideSelectAll={hideSelectAll}
|
||||
autoSize
|
||||
singleLine
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
onValueChange={onChange}
|
||||
onOptionChange={onOptionsChange}
|
||||
onInfoChange={onItemsChange}
|
||||
maxSelected={maxSelected}
|
||||
placeholder={placeholder}
|
||||
className={cn('bg-background text-base', !widthClassName && 'w-auto', className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
maxCount={maxCount}
|
||||
hideSelectAll={hideSelectAll}
|
||||
singleLine
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type KriSingleSelectProps<T = unknown> = BaseProps<T> & {
|
||||
export interface KriSingleSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onItemChange?: (item: T | null) => void
|
||||
onOptionChange?: (option: MultiSelectOption<T> | null) => void
|
||||
preventDeselect?: boolean;
|
||||
hideOptionCheck?: boolean;
|
||||
|
||||
preventDeselect?: boolean
|
||||
hideOptionCheck?: boolean
|
||||
useClear?: boolean
|
||||
clearLabel?: string
|
||||
clearValue?: string
|
||||
|
||||
showSelectedTooltip?: boolean
|
||||
}
|
||||
|
||||
export function KriSingleSelect<T = unknown>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
defaultSearchValue = "",
|
||||
onSearchValueChange,
|
||||
placeholder = 'Select an option',
|
||||
heightClassName,
|
||||
widthClassName,
|
||||
spanClassName = "text-lg",
|
||||
badgeClassName = "text-lg",
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemChange,
|
||||
onOptionChange,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
showSelectedTooltip = false,
|
||||
useClear = false,
|
||||
clearLabel = "선택 해제",
|
||||
clearValue = "__CLEAR__",
|
||||
}: KriSingleSelectProps<T>) {
|
||||
const msRef = React.useRef<MultiSelectRef>(null);
|
||||
|
||||
const extractValue = React.useCallback(
|
||||
(item: T) => (getValue ? getValue(item) : String(item)),
|
||||
[getValue]
|
||||
)
|
||||
const extractLabel = React.useCallback(
|
||||
(item: T) => (getLabel ? getLabel(item) : String(item)),
|
||||
[getLabel]
|
||||
)
|
||||
|
||||
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
|
||||
const special: MultiSelectOption<T>[] = [];
|
||||
|
||||
if (useClear) special.push({ value: clearValue, label: clearLabel });
|
||||
|
||||
const normal = items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
...(withInfo ? { info: item } : {}),
|
||||
}));
|
||||
|
||||
return [...special, ...normal]
|
||||
}, [items, extractValue, extractLabel, withInfo, useClear, clearLabel, clearValue])
|
||||
|
||||
const defaultValue = React.useMemo(() => (value ? [value] : []), [value])
|
||||
|
||||
const tooltipText = React.useMemo(() => {
|
||||
if (!showSelectedTooltip) return undefined;
|
||||
if (!value || !value) return undefined;
|
||||
if (useClear && value === clearValue) return undefined;
|
||||
|
||||
const label = options.find(o => o.value === value)?.label;
|
||||
return label ?? value; // options에 없으면 value라도 표시
|
||||
}, [showSelectedTooltip, value, options, useClear, clearValue]);
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
placeholder = 'Select an option',
|
||||
heightClassName,
|
||||
widthClassName,
|
||||
spanClassName = 'text-base',
|
||||
badgeClassName = 'text-base',
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemChange,
|
||||
onOptionChange,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
showSelectedTooltip = false,
|
||||
useClear = false,
|
||||
clearLabel = '선택 해제',
|
||||
clearValue = '__CLEAR__',
|
||||
disabled,
|
||||
}: KriSingleSelectProps<T>) {
|
||||
const ref = React.useRef<MultiSelectRef>(null)
|
||||
const options = React.useMemo(() => {
|
||||
const normal = toOptions(items, getValue, getLabel, withInfo)
|
||||
return useClear ? [{ value: clearValue, label: clearLabel }, ...normal] : normal
|
||||
}, [clearLabel, clearValue, getLabel, getValue, items, useClear, withInfo])
|
||||
const selectedLabel = options.find((option) => option.value === value)?.label
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect<T>
|
||||
ref={msRef}
|
||||
options={options}
|
||||
defaultValue={defaultValue}
|
||||
onValueChange={(next) => {
|
||||
const v = next[0] ?? ""
|
||||
|
||||
if (v === clearValue) {
|
||||
msRef.current?.clear();
|
||||
|
||||
onChange("")
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
onChange(v)
|
||||
}}
|
||||
onOptionChange={(opts) => {
|
||||
const opt = opts[0] ?? null
|
||||
const item = withInfo ? ((opt as any)?.info ?? null) : null
|
||||
|
||||
onOptionChange?.(opt)
|
||||
onItemChange?.(item)
|
||||
}}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white text-lg", className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
autoSize
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
ref={ref}
|
||||
options={options}
|
||||
defaultValue={value ? [value] : []}
|
||||
onValueChange={(next) => {
|
||||
const selected = next[0] ?? ''
|
||||
if (selected === clearValue) {
|
||||
ref.current?.clear()
|
||||
onChange('')
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onChange(selected)
|
||||
}}
|
||||
onOptionChange={(next) => {
|
||||
const option = next[0] ?? null
|
||||
if (option?.value === clearValue) {
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onOptionChange?.(option)
|
||||
onItemChange?.(option?.info ?? null)
|
||||
}}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn('bg-background text-base', !widthClassName && 'w-auto', className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
82
src/components/common/KriDatePicker.tsx
Normal file
82
src/components/common/KriDatePicker.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import { useRef } from 'react'
|
||||
import { CalendarDays, X } from 'lucide-react'
|
||||
import { CalendarIcon, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -13,7 +11,7 @@ export type KriDateRange = {
|
||||
to: string
|
||||
}
|
||||
|
||||
type KriDateRangePickerProps = {
|
||||
export type KriDateRangePickerProps = {
|
||||
value: KriDateRange
|
||||
onChange: (value: KriDateRange) => void
|
||||
placeholder?: string
|
||||
@@ -23,97 +21,101 @@ type KriDateRangePickerProps = {
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function KriDateRangePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '조회 기간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
}: KriDateRangePickerProps) {
|
||||
const toInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined
|
||||
|
||||
const displayText = value.from && value.to
|
||||
? `${value.from} ~ ${value.to}`
|
||||
: value.from
|
||||
? `${value.from} ~`
|
||||
: value.to
|
||||
? `~ ${value.to}`
|
||||
: placeholder
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
if (!year || !month || !day) return undefined
|
||||
|
||||
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()
|
||||
}
|
||||
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({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '조회 기간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
}: KriDateRangePickerProps) {
|
||||
const selected = {
|
||||
from: parseDate(value.from),
|
||||
to: parseDate(value.to),
|
||||
}
|
||||
const selectedRange = selected.from || selected.to ? selected : undefined
|
||||
|
||||
const displayText = value.from && value.to
|
||||
? `${value.from} ~ ${value.to}`
|
||||
: value.from
|
||||
? `${value.from} ~`
|
||||
: value.to
|
||||
? `~ ${value.to}`
|
||||
: placeholder
|
||||
|
||||
const hasValue = value.from.length > 0 || value.to.length > 0
|
||||
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2', className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn('justify-start min-w-[260px] font-normal', triggerClassName)}
|
||||
>
|
||||
<CalendarDays className="w-4 h-4" />
|
||||
<span className="truncate">{displayText}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className={cn('w-[360px] space-y-3', contentClassName)}>
|
||||
<Label className="font-semibold">조회 기간</Label>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="date"
|
||||
value={value.from}
|
||||
onChange={(e) => {
|
||||
const nextFrom = e.target.value
|
||||
onChange({ ...value, from: nextFrom })
|
||||
if (nextFrom) {
|
||||
requestAnimationFrame(() => {
|
||||
focusAndOpenToDate()
|
||||
<div className={cn('relative', className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||
!hasValue && 'text-muted-foreground',
|
||||
triggerClassName,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4" />
|
||||
<span className="truncate">{displayText}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||
<Calendar
|
||||
mode="range"
|
||||
selected={selectedRange}
|
||||
onSelect={(range) => {
|
||||
onChange({
|
||||
from: formatDate(range?.from),
|
||||
to: formatDate(range?.to),
|
||||
})
|
||||
}
|
||||
}}
|
||||
}}
|
||||
/>
|
||||
<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>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{invalidRange && (
|
||||
<p className="text-xs text-red-600">조회 시작일은 종료일보다 이후일 수 없습니다.</p>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => onChange({ from: '', to: '' })}
|
||||
disabled={disabled || !hasValue}
|
||||
aria-label="조회 기간 초기화"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{hasValue && !disabled ? (
|
||||
<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({ from: '', to: '' })
|
||||
}}
|
||||
aria-label="조회 기간 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
136
src/components/common/KriDateTimePicker.tsx
Normal file
136
src/components/common/KriDateTimePicker.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
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 { KriTimePicker } from '@/components/common/KriTimePicker'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriDateTimePickerProps = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
className?: string
|
||||
triggerClassName?: string
|
||||
contentClassName?: string
|
||||
disabled?: boolean
|
||||
modalPopover?: boolean
|
||||
}
|
||||
|
||||
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 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}`
|
||||
}
|
||||
|
||||
const toValue = (date: Date | undefined, time: string): string => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return ''
|
||||
|
||||
return `${dateText}T${time || '00:00'}`
|
||||
}
|
||||
|
||||
const toDisplayText = (date: Date | undefined, time: string, placeholder: string) => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return placeholder
|
||||
|
||||
return `${dateText} ${time || '00:00'}`
|
||||
}
|
||||
|
||||
export function KriDateTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '날짜/시간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
modalPopover = true,
|
||||
}: KriDateTimePickerProps) {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const { date, time } = parseDateTime(value)
|
||||
const hasValue = date !== undefined
|
||||
|
||||
const handleDateSelect = (nextDate: Date | undefined) => {
|
||||
if (!nextDate) return
|
||||
onChange(toValue(nextDate, time || '00:00'))
|
||||
}
|
||||
|
||||
const handleTimeChange = (nextTime: string) => {
|
||||
if (!date) return
|
||||
onChange(toValue(date, nextTime))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||
!hasValue && 'text-muted-foreground',
|
||||
triggerClassName,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
<span className="truncate">{toDisplayText(date, time, placeholder)}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||
<div className="sm:flex">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={date}
|
||||
onSelect={handleDateSelect}
|
||||
/>
|
||||
<KriTimePicker
|
||||
value={time || '00:00'}
|
||||
onChange={handleTimeChange}
|
||||
disabled={!date}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{hasValue && !disabled ? (
|
||||
<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>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriDateTimePicker
|
||||
76
src/components/common/KriDialog.tsx
Normal file
76
src/components/common/KriDialog.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface KriDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: ReactNode
|
||||
description?: ReactNode
|
||||
children?: ReactNode
|
||||
footer?: ReactNode
|
||||
showDefaultFooter?: boolean
|
||||
closeLabel?: string
|
||||
showCloseButton?: boolean
|
||||
contentClassName?: string
|
||||
bodyClassName?: string
|
||||
footerClassName?: string
|
||||
}
|
||||
|
||||
export function KriDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
footer,
|
||||
showDefaultFooter = true,
|
||||
closeLabel = '닫기',
|
||||
showCloseButton = true,
|
||||
contentClassName,
|
||||
bodyClassName,
|
||||
footerClassName,
|
||||
}: KriDialogProps) {
|
||||
const renderFooter = () => {
|
||||
if (footer !== undefined) {
|
||||
if (footer === null) return null
|
||||
return <DialogFooter className={footerClassName}>{footer}</DialogFooter>
|
||||
}
|
||||
|
||||
if (!showDefaultFooter) return null
|
||||
|
||||
return (
|
||||
<DialogFooter className={footerClassName}>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
{closeLabel}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className={contentClassName} showCloseButton={showCloseButton}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
{description ? <DialogDescription>{description}</DialogDescription> : null}
|
||||
</DialogHeader>
|
||||
<div className={cn('min-h-0', bodyClassName)}>{children}</div>
|
||||
{renderFooter()}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
26
src/components/common/KriLoadingOverlay.tsx
Normal file
26
src/components/common/KriLoadingOverlay.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface KriLoadingOverlayProps {
|
||||
open: boolean
|
||||
label?: string
|
||||
className?: string
|
||||
spinnerClassName?: string
|
||||
}
|
||||
|
||||
export function KriLoadingOverlay({ open, label = '로딩 중', className, spinnerClassName }: KriLoadingOverlayProps) {
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label={label}
|
||||
className={cn('fixed inset-0 z-[9999] flex items-center justify-center bg-black/70', className)}
|
||||
>
|
||||
<div className={cn('size-12 animate-spin rounded-full border-4 border-gray-400 border-t-white', spinnerClassName)} />
|
||||
<span className="sr-only">{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,32 +7,18 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// ✅ 화면에 보여줄 “허용 특수문자”
|
||||
export const ALLOWED_SPECIALS_TEXT =
|
||||
`! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
|
||||
// ✅ “허용 문자만” 체크(공백/한글/기타 특수문자 차단)
|
||||
export const ONLY_ALLOWED_REGEX =
|
||||
/^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]+$/
|
||||
|
||||
// ✅ 최종 비밀번호 규칙(특수문자 필수 아님)
|
||||
// - 8~20자
|
||||
// - 영문 1개 이상 + 숫자 1개 이상
|
||||
// - 구성 문자는 허용 문자만
|
||||
export const KRI_PW_REGEX =
|
||||
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]{8,20}$/
|
||||
export const ALLOWED_SPECIALS_TEXT = `! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
export const ONLY_ALLOWED_REGEX = /^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/
|
||||
export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{8,20}$/
|
||||
|
||||
const requirements = [
|
||||
{ regex: /[A-Za-z]/, text: '영문 1개 이상 (A–Z 또는 a–z)' },
|
||||
{ regex: /\d/, text: '숫자 1개 이상' },
|
||||
{ regex: /^.{10,}$/, text: '10자 이상' },
|
||||
{
|
||||
regex: /[!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]/,
|
||||
text: `특수문자 사용 (허용: ${ALLOWED_SPECIALS_TEXT})`,
|
||||
},
|
||||
{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' },
|
||||
{ test: (value: string) => /\d/.test(value), text: '숫자 1개 이상' },
|
||||
{ test: (value: string) => value.length >= 8 && value.length <= 20, text: '8~20자' },
|
||||
{ test: (value: string) => !value || ONLY_ALLOWED_REGEX.test(value), text: '허용 문자만 사용' },
|
||||
]
|
||||
|
||||
type KriPasswordProps = {
|
||||
export interface KriPasswordProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
id?: string
|
||||
@@ -40,156 +26,92 @@ type KriPasswordProps = {
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
showStrength?: boolean
|
||||
}
|
||||
|
||||
const KriPassword = ({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
label = '비밀번호',
|
||||
placeholder = '비밀번호를 입력하세요',
|
||||
disabled,
|
||||
className,
|
||||
}: KriPasswordProps) => {
|
||||
export function KriPassword({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
label = '비밀번호',
|
||||
placeholder = '비밀번호를 입력하세요',
|
||||
disabled,
|
||||
className,
|
||||
showStrength = true,
|
||||
}: KriPasswordProps) {
|
||||
const [isVisible, setIsVisible] = useState(false)
|
||||
|
||||
const autoId = useId()
|
||||
const inputId = id ?? autoId
|
||||
const toggleVisibility = () => setIsVisible((prev) => !prev)
|
||||
const isValid = useMemo(() => KRI_PW_REGEX.test(value), [value])
|
||||
const hasOnlyAllowedChars = useMemo(
|
||||
() => (value ? ONLY_ALLOWED_REGEX.test(value) : true),
|
||||
[value]
|
||||
)
|
||||
|
||||
const checks = useMemo(
|
||||
() =>
|
||||
requirements.map((req) => ({
|
||||
met: req.regex.test(value),
|
||||
text: req.text,
|
||||
})),
|
||||
[value]
|
||||
)
|
||||
const hasOnlyAllowedChars = useMemo(() => (value ? ONLY_ALLOWED_REGEX.test(value) : true), [value])
|
||||
const checks = useMemo(() => requirements.map((item) => ({ met: item.test(value), text: item.text })), [value])
|
||||
const score = checks.filter((item) => item.met).length
|
||||
|
||||
const statusText = useMemo(() => {
|
||||
if (!value) return '비밀번호를 입력하세요'
|
||||
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있어요'
|
||||
return isValid ? '사용 가능한 비밀번호입니다' : '비밀번호 규칙을 만족하지 않아요'
|
||||
}, [value, isValid, hasOnlyAllowedChars])
|
||||
return isValid ? '사용 가능한 비밀번호입니다' : '영문과 숫자를 포함한 8~20자로 입력하세요'
|
||||
}, [hasOnlyAllowedChars, isValid, value])
|
||||
|
||||
const score = useMemo(() => checks.filter((c) => c.met).length, [checks])
|
||||
|
||||
const getBarColor = (s: number) => {
|
||||
if (s === 0) return 'bg-border'
|
||||
if (s === 1) return 'bg-destructive'
|
||||
if (s === 2) return 'bg-orange-500'
|
||||
if (s === 3) return 'bg-yellow-400'
|
||||
return 'bg-green-500' // 4
|
||||
}
|
||||
|
||||
const getStrengthText = (s: number) => {
|
||||
if (s === 0) return '비밀번호를 입력하세요'
|
||||
if (s === 1) return '약함'
|
||||
if (s === 2) return '보통'
|
||||
if (s === 3) return '강함'
|
||||
return '매우 강함'
|
||||
}
|
||||
const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500'
|
||||
|
||||
return (
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
<Label htmlFor={inputId}>{label}</Label>
|
||||
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleVisibility}
|
||||
disabled={disabled}
|
||||
className="text-muted-foreground focus-visible:ring-ring/50 absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
|
||||
>
|
||||
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
|
||||
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Strength bars */}
|
||||
<div className="flex h-1 w-full gap-1">
|
||||
{Array.from({ length: requirements.length }).map((_, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className={cn(
|
||||
'h-full flex-1 rounded-full transition-all duration-300 ease-out',
|
||||
index < score ? getBarColor(score) : 'bg-border'
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
{value ? (
|
||||
isValid ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-destructive" />
|
||||
)
|
||||
) : (
|
||||
<span className="mt-0.5 size-4" />
|
||||
)}
|
||||
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs',
|
||||
!value
|
||||
? 'text-muted-foreground'
|
||||
: isValid
|
||||
? 'text-green-600 dark:text-green-400'
|
||||
: 'text-destructive'
|
||||
)}
|
||||
>
|
||||
{statusText}
|
||||
</p>
|
||||
</div>
|
||||
{
|
||||
/*
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
{getStrengthText(score)}.
|
||||
</p>
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
포함 조건:
|
||||
</p>
|
||||
<ul className="space-y-1.5">
|
||||
{checks.map((c, idx) => (
|
||||
<li key={idx} className="flex items-start gap-2">
|
||||
{c.met ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-muted-foreground" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs',
|
||||
c.met ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{c.text}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
*/
|
||||
}
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
{label ? <Label htmlFor={inputId}>{label}</Label> : null}
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setIsVisible((current) => !current)}
|
||||
disabled={disabled}
|
||||
className="text-muted-foreground absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
|
||||
>
|
||||
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
|
||||
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showStrength ? (
|
||||
<>
|
||||
<div className="flex h-1 w-full gap-1">
|
||||
{requirements.map((item, index) => (
|
||||
<span
|
||||
key={item.text}
|
||||
className={cn(
|
||||
'h-full flex-1 rounded-full transition-colors',
|
||||
index < score && value ? barClass : 'bg-border',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
{value ? (
|
||||
isValid ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600" />
|
||||
) : (
|
||||
<XIcon className="text-destructive mt-0.5 size-4" />
|
||||
)
|
||||
) : (
|
||||
<span className="mt-0.5 size-4" />
|
||||
)}
|
||||
<p className={cn('text-xs', !value ? 'text-muted-foreground' : isValid ? 'text-green-600' : 'text-destructive')}>
|
||||
{statusText}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export type KriSelectItem = {
|
||||
label: string
|
||||
}
|
||||
|
||||
type KriSelectProps<T> = {
|
||||
export type KriSelectProps<T> = {
|
||||
items: T[]
|
||||
value: string
|
||||
onChange?: (value: string) => void
|
||||
@@ -23,6 +23,7 @@ type KriSelectProps<T> = {
|
||||
getValue?: (item: T) => string
|
||||
getLabel?: (item: T) => string
|
||||
useAll?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
|
||||
@@ -41,12 +42,13 @@ export function KriSelect<T>({
|
||||
placeholder,
|
||||
className,
|
||||
heightClassName,
|
||||
triggerTextClassName = 'text-lg',
|
||||
triggerTextClassName,
|
||||
contentClassName,
|
||||
itemClassName,
|
||||
getValue,
|
||||
getLabel,
|
||||
useAll = true,
|
||||
disabled,
|
||||
}: KriSelectProps<T>) {
|
||||
const extractValue = (item: T) => (getValue ? getValue(item) : String(item))
|
||||
const extractLabel = (item: T) => (getLabel ? getLabel(item) : String(item))
|
||||
@@ -57,10 +59,11 @@ export function KriSelect<T>({
|
||||
return (
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={(v) => {
|
||||
onChange?.(v)
|
||||
disabled={disabled}
|
||||
onValueChange={(selectedValue) => {
|
||||
onChange?.(selectedValue)
|
||||
|
||||
const selected = items.find((item) => extractValue(item) === v)
|
||||
const selected = items.find((item) => extractValue(item) === selectedValue)
|
||||
if (selected) {
|
||||
onChangeOption?.(selected)
|
||||
}
|
||||
@@ -75,16 +78,16 @@ export function KriSelect<T>({
|
||||
</SelectTrigger>
|
||||
<SelectContent className={contentClassName}>
|
||||
{useAll ? (
|
||||
<SelectItem key="ALL" value="ALL" className={itemClassName}>
|
||||
<SelectItem value="ALL" className={itemClassName}>
|
||||
전체
|
||||
</SelectItem>
|
||||
) : null}
|
||||
{items.map((item, idx) => {
|
||||
const v = extractValue(item)
|
||||
{items.map((item, index) => {
|
||||
const itemValue = extractValue(item)
|
||||
const label = extractLabel(item)
|
||||
|
||||
return (
|
||||
<SelectItem key={v ?? idx} value={v} className={itemClassName}>
|
||||
<SelectItem key={itemValue || index} value={itemValue} className={itemClassName}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
)
|
||||
|
||||
99
src/components/common/KriTimePicker.tsx
Normal file
99
src/components/common/KriTimePicker.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriTimePickerProps = {
|
||||
value?: string
|
||||
onChange: (value: string) => void
|
||||
disabled?: boolean
|
||||
minuteStep?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
const parseTime = (value: string | undefined) => {
|
||||
if (!value) return { hour: undefined, minute: undefined }
|
||||
|
||||
const [hour, minute] = value.split(':').map(Number)
|
||||
|
||||
return {
|
||||
hour: Number.isInteger(hour) && hour >= 0 && hour < 24 ? hour : undefined,
|
||||
minute: Number.isInteger(minute) && minute >= 0 && minute < 60 ? minute : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
const formatTime = (hour: number, minute: number) => {
|
||||
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function KriTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
minuteStep = 5,
|
||||
className,
|
||||
}: KriTimePickerProps) {
|
||||
const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
|
||||
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
|
||||
? Math.min(Math.floor(minuteStep), 60)
|
||||
: 5
|
||||
const hours = Array.from({ length: 24 }, (_, index) => index)
|
||||
const minutes = Array.from(
|
||||
{ length: Math.ceil(60 / normalizedMinuteStep) },
|
||||
(_, index) => index * normalizedMinuteStep,
|
||||
).filter((minute) => minute < 60)
|
||||
|
||||
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
|
||||
if (disabled) return
|
||||
|
||||
const nextHour = type === 'hour' ? nextValue : selectedHour ?? 0
|
||||
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
|
||||
|
||||
onChange(formatTime(nextHour, nextMinute))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}>
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{hours.map((hour) => (
|
||||
<Button
|
||||
key={hour}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedHour === hour ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('hour', hour)}
|
||||
>
|
||||
{hour}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{minutes.map((minute) => (
|
||||
<Button
|
||||
key={minute}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedMinute === minute ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('minute', minute)}
|
||||
>
|
||||
{String(minute).padStart(2, '0')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriTimePicker
|
||||
@@ -1,17 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
const isLoading = useAtomValue(loadingAtom);
|
||||
|
||||
if (!force && !isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
|
||||
{/* 심플 로딩 인디케이터 */}
|
||||
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MultiSelectContent } from './MultiSelectContent'
|
||||
import { MultiSelectTrigger } from './MultiSelectTrigger'
|
||||
import type { MultiSelectOption, MultiSelectProps, MultiSelectRef } from './types'
|
||||
import { arraysEqual, deduplicateOptions, flattenOptions } from './utils'
|
||||
import { useResponsiveSettings } from './use-responsive-settings'
|
||||
|
||||
function MultiSelectInner<T>(
|
||||
{
|
||||
options: rawOptions,
|
||||
onValueChange,
|
||||
onOptionChange,
|
||||
onInfoChange,
|
||||
defaultValue = [],
|
||||
stickySelectedOptions = [],
|
||||
onStickySelectedOptionsChange,
|
||||
placeholder = 'Select options',
|
||||
maxCount = 3,
|
||||
maxSelected,
|
||||
selectionMode = 'multiple',
|
||||
modalPopover = false,
|
||||
variant = 'default',
|
||||
className,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
hideSelectAll = false,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
emptyIndicator = '검색 결과가 없습니다.',
|
||||
autoSize = false,
|
||||
singleLine = false,
|
||||
popoverClassName,
|
||||
disabled = false,
|
||||
responsive,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
deduplicateOptions: shouldDeduplicate = false,
|
||||
resetOnDefaultValueChange = true,
|
||||
closeOnSelect = false,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
style,
|
||||
...buttonProps
|
||||
}: MultiSelectProps<T>,
|
||||
ref: React.ForwardedRef<MultiSelectRef>,
|
||||
) {
|
||||
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue)
|
||||
const [searchValue, setSearchValue] = React.useState(defaultSearchValue)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const buttonRef = React.useRef<HTMLButtonElement>(null)
|
||||
const [triggerWidth, setTriggerWidth] = React.useState<number>()
|
||||
|
||||
const options = React.useMemo(
|
||||
() => (shouldDeduplicate ? deduplicateOptions(rawOptions) : rawOptions),
|
||||
[rawOptions, shouldDeduplicate],
|
||||
)
|
||||
const flatOptions = React.useMemo(() => flattenOptions(options), [options])
|
||||
const responsiveSettings = useResponsiveSettings(responsive, maxCount)
|
||||
|
||||
const optionMap = React.useMemo(() => {
|
||||
const map = new Map<string, MultiSelectOption<T>>()
|
||||
for (const option of stickySelectedOptions) map.set(option.value, option)
|
||||
for (const option of flatOptions) map.set(option.value, option)
|
||||
return map
|
||||
}, [flatOptions, stickySelectedOptions])
|
||||
|
||||
const selectedOptions = React.useMemo(
|
||||
() => selectedValues.map((value) => optionMap.get(value) ?? { value, label: value }),
|
||||
[optionMap, selectedValues],
|
||||
)
|
||||
|
||||
const emit = React.useCallback(
|
||||
(next: string[]) => {
|
||||
setSelectedValues(next)
|
||||
onValueChange(next)
|
||||
const nextOptions = next.map((value) => optionMap.get(value) ?? { value, label: value })
|
||||
onOptionChange?.(nextOptions)
|
||||
onInfoChange?.(
|
||||
nextOptions.flatMap((option) => (option.info === undefined ? [] : [option.info])),
|
||||
)
|
||||
},
|
||||
[onInfoChange, onOptionChange, onValueChange, optionMap],
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!resetOnDefaultValueChange || arraysEqual(defaultValue, selectedValues)) return
|
||||
setSelectedValues(defaultValue)
|
||||
}, [defaultValue, resetOnDefaultValueChange, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!onStickySelectedOptionsChange) return
|
||||
const refreshed = selectedValues
|
||||
.map((value) => optionMap.get(value))
|
||||
.filter((option): option is MultiSelectOption<T> => Boolean(option))
|
||||
onStickySelectedOptionsChange(refreshed)
|
||||
}, [onStickySelectedOptionsChange, optionMap, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
const element = buttonRef.current
|
||||
if (!element || !('ResizeObserver' in window)) return
|
||||
const update = () => setTriggerWidth(Math.round(element.getBoundingClientRect().width))
|
||||
update()
|
||||
const observer = new ResizeObserver(update)
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
React.useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
reset: () => {
|
||||
emit(defaultValue)
|
||||
setSearchValue(defaultSearchValue)
|
||||
setOpen(false)
|
||||
},
|
||||
getSelectedValues: () => selectedValues,
|
||||
setSelectedValues: emit,
|
||||
clear: () => emit([]),
|
||||
focus: () => buttonRef.current?.focus(),
|
||||
}),
|
||||
[defaultSearchValue, defaultValue, emit, selectedValues],
|
||||
)
|
||||
|
||||
const toggleOption = React.useCallback(
|
||||
(option: MultiSelectOption<T>) => {
|
||||
if (option.disabled) return
|
||||
const selected = selectedValues.includes(option.value)
|
||||
|
||||
if (selected) {
|
||||
if (preventDeselect) return
|
||||
emit(selectedValues.filter((value) => value !== option.value))
|
||||
return
|
||||
}
|
||||
|
||||
if (selectionMode === 'single') {
|
||||
emit([option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (maxSelected !== undefined && selectedValues.length >= maxSelected) return
|
||||
emit([...selectedValues, option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
},
|
||||
[closeOnSelect, emit, maxSelected, preventDeselect, selectedValues, selectionMode],
|
||||
)
|
||||
|
||||
const toggleAll = React.useCallback(() => {
|
||||
const values = flatOptions.filter((option) => !option.disabled).map((option) => option.value)
|
||||
const allSelected = values.length > 0 && values.every((value) => selectedValues.includes(value))
|
||||
if (allSelected) {
|
||||
if (!preventDeselect) emit([])
|
||||
return
|
||||
}
|
||||
emit(maxSelected === undefined ? values : values.slice(0, maxSelected))
|
||||
}, [emit, flatOptions, maxSelected, preventDeselect, selectedValues])
|
||||
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchValue(value)
|
||||
onSearchValueChange?.(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<MultiSelectTrigger
|
||||
ref={buttonRef}
|
||||
selectedOptions={selectedOptions}
|
||||
placeholder={placeholder}
|
||||
maxCount={responsiveSettings.maxCount}
|
||||
compactMode={responsiveSettings.compactMode}
|
||||
hideIcons={responsiveSettings.hideIcons}
|
||||
singleLine={singleLine}
|
||||
preventDeselect={preventDeselect}
|
||||
variant={variant}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
onRemove={(value) => emit(selectedValues.filter((selected) => selected !== value))}
|
||||
onClear={() => emit([])}
|
||||
className={cn(autoSize && 'w-auto', className)}
|
||||
disabled={disabled}
|
||||
style={{ minWidth, maxWidth, ...style }}
|
||||
{...buttonProps}
|
||||
/>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className={cn('w-[var(--radix-popover-trigger-width)] min-w-64 p-0', popoverClassName)}
|
||||
style={{ width: triggerWidth ? `${triggerWidth}px` : undefined }}
|
||||
>
|
||||
<MultiSelectContent
|
||||
options={options}
|
||||
selectedValues={selectedValues}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
searchValue={searchValue}
|
||||
onSearchValueChange={handleSearchChange}
|
||||
hideSelectAll={hideSelectAll}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
selectionMode={selectionMode}
|
||||
emptyIndicator={emptyIndicator}
|
||||
onToggleOption={toggleOption}
|
||||
onToggleAll={toggleAll}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
const ForwardedMultiSelect = React.forwardRef(MultiSelectInner) as <T = unknown>(
|
||||
props: MultiSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
|
||||
) => React.ReactElement
|
||||
|
||||
export const MultiSelect = ForwardedMultiSelect
|
||||
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
'use client'
|
||||
|
||||
import { CheckIcon } from 'lucide-react'
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from '@/components/ui/command'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
import { isGroupedOptions } from './utils'
|
||||
|
||||
interface MultiSelectContentProps<T> {
|
||||
options: MultiSelectOptions<T>
|
||||
selectedValues: string[]
|
||||
searchable: boolean
|
||||
searchMode: 'filter' | 'inputOnly'
|
||||
searchValue: string
|
||||
onSearchValueChange: (value: string) => void
|
||||
hideSelectAll: boolean
|
||||
hideOptionCheck: boolean
|
||||
selectionMode: 'single' | 'multiple'
|
||||
emptyIndicator: React.ReactNode
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
onToggleAll: () => void
|
||||
}
|
||||
|
||||
function OptionItem<T>({
|
||||
option,
|
||||
selected,
|
||||
hideOptionCheck,
|
||||
onToggle,
|
||||
}: {
|
||||
option: MultiSelectOption<T>
|
||||
selected: boolean
|
||||
hideOptionCheck: boolean
|
||||
onToggle: () => void
|
||||
}) {
|
||||
const Icon = option.icon
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={`${option.label} ${option.value}`}
|
||||
disabled={option.disabled}
|
||||
onSelect={onToggle}
|
||||
className="flex items-center cursor-pointer"
|
||||
>
|
||||
{!hideOptionCheck ? (
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
selected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
|
||||
<span className="truncate">{option.label}</span>
|
||||
</CommandItem>
|
||||
)
|
||||
}
|
||||
|
||||
function OptionsGroup<T>({
|
||||
group,
|
||||
selectedValues,
|
||||
hideOptionCheck,
|
||||
onToggleOption,
|
||||
}: {
|
||||
group: MultiSelectGroup<T>
|
||||
selectedValues: string[]
|
||||
hideOptionCheck: boolean
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
}) {
|
||||
return (
|
||||
<CommandGroup heading={group.heading}>
|
||||
{group.options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export function MultiSelectContent<T>({
|
||||
options,
|
||||
selectedValues,
|
||||
searchable,
|
||||
searchMode,
|
||||
searchValue,
|
||||
onSearchValueChange,
|
||||
hideSelectAll,
|
||||
hideOptionCheck,
|
||||
selectionMode,
|
||||
emptyIndicator,
|
||||
onToggleOption,
|
||||
onToggleAll,
|
||||
}: MultiSelectContentProps<T>) {
|
||||
const grouped = isGroupedOptions(options)
|
||||
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
|
||||
const selectableOptions = flatOptions.filter((option) => !option.disabled)
|
||||
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
||||
|
||||
return (
|
||||
<Command shouldFilter={searchMode === 'filter'}>
|
||||
{searchable ? (
|
||||
<CommandInput
|
||||
value={searchValue}
|
||||
onValueChange={onSearchValueChange}
|
||||
placeholder="검색..."
|
||||
/>
|
||||
) : null}
|
||||
<CommandList>
|
||||
<CommandEmpty>{emptyIndicator}</CommandEmpty>
|
||||
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
|
||||
<>
|
||||
<CommandGroup>
|
||||
<CommandItem className="cursor-pointer" value="__kri_select_all__" onSelect={onToggleAll}>
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
allSelected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
전체 선택
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandSeparator />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{grouped ? (
|
||||
options.map((group) => (
|
||||
<OptionsGroup
|
||||
key={group.heading}
|
||||
group={group}
|
||||
selectedValues={selectedValues}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggleOption={onToggleOption}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<CommandGroup>
|
||||
{options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
)
|
||||
}
|
||||
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { ChevronDown, XCircle, XIcon } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectOption, MultiSelectVariant } from './types'
|
||||
import { getVariantClass } from './utils'
|
||||
|
||||
interface MultiSelectTriggerProps<T> extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onChange'> {
|
||||
selectedOptions: MultiSelectOption<T>[]
|
||||
placeholder: string
|
||||
maxCount: number
|
||||
singleLine: boolean
|
||||
compactMode: boolean
|
||||
hideIcons: boolean
|
||||
preventDeselect: boolean
|
||||
variant: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
onRemove: (value: string) => void
|
||||
onClear: () => void
|
||||
}
|
||||
|
||||
export const MultiSelectTrigger = React.forwardRef(function MultiSelectTriggerInner<T>(
|
||||
{
|
||||
selectedOptions,
|
||||
placeholder,
|
||||
maxCount,
|
||||
singleLine,
|
||||
compactMode,
|
||||
hideIcons,
|
||||
preventDeselect,
|
||||
variant,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
className,
|
||||
disabled,
|
||||
onRemove,
|
||||
onClear,
|
||||
...buttonProps
|
||||
}: MultiSelectTriggerProps<T>,
|
||||
ref: React.ForwardedRef<HTMLButtonElement>,
|
||||
) {
|
||||
const visible = selectedOptions.slice(0, maxCount)
|
||||
const hiddenCount = Math.max(0, selectedOptions.length - visible.length)
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-haspopup="listbox"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-auto min-h-9 w-full justify-between gap-2 px-3 py-1.5 font-normal',
|
||||
getVariantClass(variant),
|
||||
className,
|
||||
)}
|
||||
{...buttonProps}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'flex min-w-0 flex-1 items-center gap-1 text-left',
|
||||
singleLine ? 'overflow-x-auto whitespace-nowrap' : 'flex-wrap',
|
||||
spanClassName,
|
||||
)}
|
||||
>
|
||||
{selectedOptions.length === 0 ? (
|
||||
<span className="text-muted-foreground truncate">{placeholder}</span>
|
||||
) : compactMode ? (
|
||||
<span>{selectedOptions.length}개 선택</span>
|
||||
) : (
|
||||
<>
|
||||
{visible.map((option) => {
|
||||
const Icon = option.icon
|
||||
return (
|
||||
<Badge
|
||||
key={option.value}
|
||||
variant="secondary"
|
||||
className={cn('max-w-full gap-1', badgeClassName)}
|
||||
style={{ background: option.style?.gradient ?? option.style?.badgeColor }}
|
||||
>
|
||||
{!hideIcons && Icon ? <Icon className="size-3.5" /> : null}
|
||||
<span className="max-w-48 truncate">{option.label}</span>
|
||||
{!preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`${option.label} 선택 해제`}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
</Badge>
|
||||
)
|
||||
})}
|
||||
{hiddenCount > 0 ? <Badge variant="secondary">+{hiddenCount}</Badge> : null}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<span className="flex shrink-0 items-center gap-1">
|
||||
{selectedOptions.length > 0 && !preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="전체 선택 해제"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XCircle className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
) : null}
|
||||
<ChevronDown className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
</Button>
|
||||
)
|
||||
}) as <T>(props: MultiSelectTriggerProps<T> & { ref?: React.ForwardedRef<HTMLButtonElement> }) => React.ReactElement
|
||||
13
src/components/common/multi-select/index.ts
Normal file
13
src/components/common/multi-select/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export { MultiSelect } from './MultiSelect'
|
||||
export type {
|
||||
AnimationConfig,
|
||||
MultiSelectGroup,
|
||||
MultiSelectOption,
|
||||
MultiSelectOptions,
|
||||
MultiSelectProps,
|
||||
MultiSelectRef,
|
||||
MultiSelectResponsiveConfig,
|
||||
MultiSelectResponsiveSettings,
|
||||
MultiSelectSelectionMode,
|
||||
MultiSelectVariant,
|
||||
} from './types'
|
||||
89
src/components/common/multi-select/types.ts
Normal file
89
src/components/common/multi-select/types.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import type * as React from 'react'
|
||||
|
||||
export interface AnimationConfig {
|
||||
badgeAnimation?: 'bounce' | 'pulse' | 'wiggle' | 'fade' | 'slide' | 'none'
|
||||
popoverAnimation?: 'scale' | 'slide' | 'fade' | 'flip' | 'none'
|
||||
optionHoverAnimation?: 'highlight' | 'scale' | 'glow' | 'none'
|
||||
duration?: number
|
||||
delay?: number
|
||||
}
|
||||
|
||||
export interface MultiSelectOption<T = unknown> {
|
||||
label: string
|
||||
value: string
|
||||
info?: T
|
||||
icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>
|
||||
disabled?: boolean
|
||||
style?: {
|
||||
badgeColor?: string
|
||||
iconColor?: string
|
||||
gradient?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface MultiSelectGroup<T = unknown> {
|
||||
heading: string
|
||||
options: MultiSelectOption<T>[]
|
||||
}
|
||||
|
||||
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
||||
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
||||
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
||||
|
||||
export interface MultiSelectResponsiveSettings {
|
||||
maxCount?: number
|
||||
hideIcons?: boolean
|
||||
compactMode?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectResponsiveConfig {
|
||||
mobile?: MultiSelectResponsiveSettings
|
||||
tablet?: MultiSelectResponsiveSettings
|
||||
desktop?: MultiSelectResponsiveSettings
|
||||
}
|
||||
|
||||
export interface MultiSelectProps<T = unknown>
|
||||
extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'defaultValue' | 'onChange'> {
|
||||
options: MultiSelectOptions<T>
|
||||
onValueChange: (value: string[]) => void
|
||||
onOptionChange?: (selectedOptions: MultiSelectOption<T>[]) => void
|
||||
onInfoChange?: (infos: T[]) => void
|
||||
defaultValue?: string[]
|
||||
stickySelectedOptions?: MultiSelectOption<T>[]
|
||||
onStickySelectedOptionsChange?: (options: MultiSelectOption<T>[]) => void
|
||||
placeholder?: string
|
||||
animation?: number
|
||||
animationConfig?: AnimationConfig
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
selectionMode?: MultiSelectSelectionMode
|
||||
modalPopover?: boolean
|
||||
variant?: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
hideSelectAll?: boolean
|
||||
searchable?: boolean
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
defaultSearchValue?: string
|
||||
onSearchValueChange?: (value: string) => void
|
||||
emptyIndicator?: React.ReactNode
|
||||
autoSize?: boolean
|
||||
singleLine?: boolean
|
||||
popoverClassName?: string
|
||||
responsive?: boolean | MultiSelectResponsiveConfig
|
||||
minWidth?: string
|
||||
maxWidth?: string
|
||||
deduplicateOptions?: boolean
|
||||
resetOnDefaultValueChange?: boolean
|
||||
closeOnSelect?: boolean
|
||||
preventDeselect?: boolean
|
||||
hideOptionCheck?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectRef {
|
||||
reset: () => void
|
||||
getSelectedValues: () => string[]
|
||||
setSelectedValues: (values: string[]) => void
|
||||
clear: () => void
|
||||
focus: () => void
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import type { MultiSelectProps, MultiSelectResponsiveSettings } from './types'
|
||||
|
||||
export function useResponsiveSettings(
|
||||
responsive: MultiSelectProps['responsive'],
|
||||
defaultMaxCount: number,
|
||||
): Required<MultiSelectResponsiveSettings> {
|
||||
const [screen, setScreen] = React.useState<'mobile' | 'tablet' | 'desktop'>('desktop')
|
||||
|
||||
React.useEffect(() => {
|
||||
const update = () => {
|
||||
if (window.innerWidth < 640) setScreen('mobile')
|
||||
else if (window.innerWidth < 1024) setScreen('tablet')
|
||||
else setScreen('desktop')
|
||||
}
|
||||
|
||||
update()
|
||||
window.addEventListener('resize', update)
|
||||
return () => window.removeEventListener('resize', update)
|
||||
}, [])
|
||||
|
||||
if (!responsive) {
|
||||
return { maxCount: defaultMaxCount, hideIcons: false, compactMode: false }
|
||||
}
|
||||
|
||||
if (responsive === true) {
|
||||
const defaults = {
|
||||
mobile: { maxCount: 2, hideIcons: false, compactMode: true },
|
||||
tablet: { maxCount: 4, hideIcons: false, compactMode: false },
|
||||
desktop: { maxCount: 6, hideIcons: false, compactMode: false },
|
||||
}
|
||||
return defaults[screen]
|
||||
}
|
||||
|
||||
const current = responsive[screen]
|
||||
return {
|
||||
maxCount: current?.maxCount ?? defaultMaxCount,
|
||||
hideIcons: current?.hideIcons ?? false,
|
||||
compactMode: current?.compactMode ?? false,
|
||||
}
|
||||
}
|
||||
48
src/components/common/multi-select/utils.ts
Normal file
48
src/components/common/multi-select/utils.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
|
||||
export function isGroupedOptions<T>(options: MultiSelectOptions<T>): options is MultiSelectGroup<T>[] {
|
||||
return options.length > 0 && 'heading' in options[0]
|
||||
}
|
||||
|
||||
export function flattenOptions<T>(options: MultiSelectOptions<T>): MultiSelectOption<T>[] {
|
||||
return isGroupedOptions(options) ? options.flatMap((group) => group.options) : options
|
||||
}
|
||||
|
||||
export function deduplicateOptions<T>(options: MultiSelectOptions<T>): MultiSelectOptions<T> {
|
||||
const seen = new Set<string>()
|
||||
|
||||
if (isGroupedOptions(options)) {
|
||||
return options.map((group) => ({
|
||||
...group,
|
||||
options: group.options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
return options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function arraysEqual(left: string[], right: string[]): boolean {
|
||||
if (left.length !== right.length) return false
|
||||
return left.every((value, index) => value === right[index])
|
||||
}
|
||||
|
||||
export function getVariantClass(variant: 'default' | 'secondary' | 'destructive' | 'inverted'): string {
|
||||
switch (variant) {
|
||||
case 'secondary':
|
||||
return 'bg-secondary text-secondary-foreground'
|
||||
case 'destructive':
|
||||
return 'bg-destructive text-destructive-foreground'
|
||||
case 'inverted':
|
||||
return 'bg-foreground text-background'
|
||||
default:
|
||||
return 'bg-background text-foreground'
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user