'use client' import { useState, type CSSProperties, type KeyboardEvent } from 'react' import { Check } from 'lucide-react' import { Slider as SliderPrimitive } from 'radix-ui' import { Button } from '@/components/ui/button' import { ColorPicker, ColorPickerArea, ColorPickerHueSlider } from '@/components/ui/color-picker' import { Input } from '@/components/ui/input' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { cn } from '@/lib/utils' import { formatHexColor, isLightHexColor, normalizeHexColor, parseHexColor } from '@/utils/color' export const KRI_COLOR_PALETTE_DEFAULT_COLORS = [ '#111827', '#4B5563', '#9CA3AF', '#E5E7EB', '#EF4444', '#F97316', '#F59E0B', '#EAB308', '#84CC16', '#22C55E', '#14B8A6', '#06B6D4', '#3B82F6', '#6366F1', '#A855F7', '#EC4899', ] as const const CUSTOM_PICKER_FALLBACK = '#3B82F6' const CHECKERBOARD = 'repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0% 50% / 8px 8px' export type KriColorPaletteProps = { /** `#RRGGBB` 또는 `#RRGGBBAA` 형식의 색상. 지정되지 않았으면 null */ value: string | null onChange: (value: string | null) => void colors?: readonly string[] /** 색상 영역·색조 슬라이더·HEX 입력 노출 여부 */ allowCustom?: boolean /** * 투명도 슬라이더 노출 및 `#RRGGBBAA` 입력 허용 여부. * false여도 전달받은 값의 투명도는 표시·보존하며, 사용자가 색을 바꾸면 불투명(`#RRGGBB`)으로 바뀐다. */ allowAlpha?: boolean allowClear?: boolean disabled?: boolean placeholder?: string className?: string 'aria-label'?: string } const swatchStyle = (color: string): CSSProperties => ({ background: `linear-gradient(${color}, ${color}), ${CHECKERBOARD}`, }) export function KriColorPalette({ value, onChange, colors = KRI_COLOR_PALETTE_DEFAULT_COLORS, allowCustom = true, allowAlpha = false, allowClear = true, disabled = false, placeholder = '색상 없음', className, 'aria-label': ariaLabel = '색상 선택', }: KriColorPaletteProps) { const normalizedValue = normalizeHexColor(value) const parsedValue = parseHexColor(normalizedValue) const currentAlpha = parsedValue?.alpha ?? 255 const [open, setOpen] = useState(false) // 프리셋·HEX 입력·제거로 값이 바뀌면 색상 영역을 새 값으로 다시 초기화한다. const [pickerKey, setPickerKey] = useState(0) const [hexDraft, setHexDraft] = useState(normalizedValue ?? '') const [hexDraftSource, setHexDraftSource] = useState(normalizedValue) const [hexInvalid, setHexInvalid] = useState(false) if (hexDraftSource !== normalizedValue) { setHexDraftSource(normalizedValue) setHexDraft(normalizedValue ?? '') setHexInvalid(false) } const withAlpha = (rgb: string) => formatHexColor(rgb, allowAlpha ? currentAlpha : 255) const selectDiscrete = (next: string | null) => { onChange(next) setPickerKey((key) => key + 1) } const handlePickerChange = (next: string) => { const parsed = parseHexColor(next) if (!parsed) return const nextValue = withAlpha(parsed.rgb) if (nextValue === normalizedValue) return onChange(nextValue) } const handleAlphaChange = (values: number[]) => { const percent = values[0] ?? 100 const nextValue = formatHexColor(parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK, (percent / 100) * 255) if (nextValue === normalizedValue) return onChange(nextValue) } const commitHexDraft = () => { if (hexDraft.trim() === '') { setHexDraft(normalizedValue ?? '') setHexInvalid(false) return } // 전달받은 값을 그대로 두고 포커스만 이동한 경우(투명도 포함 값 포함)는 변경으로 보지 않는다. if (normalizeHexColor(hexDraft) === normalizedValue) { setHexDraft(normalizedValue ?? '') setHexInvalid(false) return } const parsed = parseHexColor(hexDraft) if (!parsed || (!allowAlpha && parsed.alpha !== 255)) { setHexInvalid(true) return } const nextValue = formatHexColor(parsed.rgb, parsed.alpha) setHexInvalid(false) setHexDraft(nextValue) if (nextValue !== normalizedValue) selectDiscrete(nextValue) } const handleHexKeyDown = (event: KeyboardEvent) => { if (event.key !== 'Enter') return event.preventDefault() commitHexDraft() } const hexFormatLabel = allowAlpha ? '#RRGGBB 또는 #RRGGBBAA' : '#RRGGBB' const alphaPercent = Math.round((currentAlpha / 255) * 100) // disabled이면 트리거 상태와 무관하게 팝오버가 열리지 않도록 한다(이미 열린 상태에서 disabled로 바뀐 경우 포함). const resolvedOpen = open && !disabled return ( setOpen(nextOpen && !disabled)}>
{colors.map((color) => { const parsedColor = parseHexColor(color) if (!parsedColor) return null const selected = parsedColor.rgb === parsedValue?.rgb return ( ) })}
{allowCustom ? (
{allowAlpha ? (
{alphaPercent}%
) : null}
{ setHexDraft(event.target.value) setHexInvalid(false) }} onBlur={commitHexDraft} onKeyDown={handleHexKeyDown} placeholder={allowAlpha ? '#RRGGBBAA' : '#RRGGBB'} maxLength={allowAlpha ? 9 : 7} aria-label="HEX 색상 코드" aria-invalid={hexInvalid} className="h-8 font-mono text-sm" /> {hexInvalid ?

{hexFormatLabel} 형식으로 입력해 주세요.

: null}
) : null} {allowClear ? (
) : null} ) }