Files
front-ui-registry/registry/components/KriColorPalette.tsx

248 lines
9.7 KiB
TypeScript

'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/common/color-palette/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 '@/components/common/color-palette/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<HTMLInputElement>) => {
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 (
<Popover open={resolvedOpen} onOpenChange={(nextOpen) => setOpen(nextOpen && !disabled)}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="sm"
disabled={disabled}
aria-label={`${ariaLabel}: ${normalizedValue ?? placeholder}`}
className={cn('w-full justify-start gap-2 px-2 font-normal', className)}
>
<span
aria-hidden
className={cn('size-4 shrink-0 rounded-sm border', !normalizedValue && 'bg-[linear-gradient(to_bottom_right,transparent_calc(50%-1px),var(--destructive)_calc(50%-1px)_calc(50%+1px),transparent_calc(50%+1px))]')}
style={normalizedValue ? swatchStyle(normalizedValue) : undefined}
/>
<span className={cn('truncate font-mono text-xs', !normalizedValue && 'text-muted-foreground font-sans')}>
{normalizedValue ?? placeholder}
</span>
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-64 space-y-3 p-3">
<div className="grid grid-cols-8 gap-1.5" role="group" aria-label="기본 색상">
{colors.map((color) => {
const parsedColor = parseHexColor(color)
if (!parsedColor) return null
const selected = parsedColor.rgb === parsedValue?.rgb
const checkColorClass = isLightHexColor(parsedColor.rgb) ? 'text-black' : 'text-white'
return (
<button
key={parsedColor.rgb}
type="button"
className="focus-visible:ring-ring flex size-6 items-center justify-center rounded-sm border focus-visible:ring-2 focus-visible:outline-none"
style={{ backgroundColor: parsedColor.rgb }}
aria-label={`색상 ${parsedColor.rgb}`}
aria-pressed={selected}
title={parsedColor.rgb}
onClick={() => selectDiscrete(withAlpha(parsedColor.rgb))}
>
{selected ? <Check className={cn('size-3.5', checkColorClass)} /> : null}
</button>
)
})}
</div>
{allowCustom ? (
<div className="space-y-3 border-t pt-3">
<ColorPicker
key={pickerKey}
inline
defaultValue={parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK}
onValueChange={handlePickerChange}
className="flex flex-col gap-3"
>
<ColorPickerArea className="h-32" />
<ColorPickerHueSlider aria-label="색조" />
</ColorPicker>
{allowAlpha ? (
<div className="flex items-center gap-2">
<SliderPrimitive.Root
className="relative flex w-full touch-none items-center select-none"
min={0}
max={100}
step={1}
value={[alphaPercent]}
onValueChange={handleAlphaChange}
aria-label="투명도"
>
<SliderPrimitive.Track
className="relative h-3 w-full grow overflow-hidden rounded-full"
style={{ background: CHECKERBOARD }}
>
<div
className="absolute inset-0 rounded-full"
style={{ background: `linear-gradient(to right, transparent, ${parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK})` }}
/>
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="border-primary/50 bg-background focus-visible:ring-ring block size-4 rounded-full border shadow focus-visible:ring-1 focus-visible:outline-none" />
</SliderPrimitive.Root>
<span className="text-muted-foreground w-10 shrink-0 text-right font-mono text-xs">{alphaPercent}%</span>
</div>
) : null}
<div className="space-y-1">
<Input
value={hexDraft}
onChange={(event) => {
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 ? <p className="text-destructive text-xs">{hexFormatLabel} 형식으로 입력해 주세요.</p> : null}
</div>
</div>
) : null}
{allowClear ? (
<div className="flex justify-end border-t pt-2">
<Button
type="button"
variant="ghost"
size="sm"
disabled={!normalizedValue}
onClick={() => selectDiscrete(null)}
>
색상 제거
</Button>
</div>
) : null}
</PopoverContent>
</Popover>
)
}