diff --git a/.agent/consumer.md b/.agent/consumer.md index 76d2d48..4d7a990 100644 --- a/.agent/consumer.md +++ b/.agent/consumer.md @@ -22,6 +22,13 @@ When implementing or changing frontend UI, use this order: - `kri-auto-complete` exposes `searchMatch?: 'fuzzy' | 'contains'` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `fuzzy` (cmdk's default subsequence scoring), preserving existing behavior. - `contains` keeps only options whose label or value contains the search text as a case-insensitive substring, in the original option order. It applies only when `searchMode` is `filter`. +### KriColorPalette + +- `kri-color-palette` provides `KriColorPalette` with `value: string | null` and `onChange(value: string | null)`. Values are uppercase `#RRGGBB`, or `#RRGGBBAA` when they carry transparency; `null` means no color. +- `allowAlpha?: boolean` defaults to `false`. When disabled, an incoming `#RRGGBBAA` value is still displayed and preserved until the user picks a new color, which produces an opaque `#RRGGBB`. When enabled, a transparency slider and `#RRGGBBAA` input are available. +- `colors`, `allowCustom`, `allowClear`, `disabled`, `placeholder`, `className`, and `aria-label` are optional. A disabled palette never opens. +- Color helpers (`parseHexColor`, `formatHexColor`, `normalizeHexColor`, `isLightHexColor`) ship in `color-palette/color.ts`. Render stored colors as solid backgrounds without extra opacity so they match the palette. + ### KriEditor SMS Preview - `changeSmsType` reports `SMS | LMS | MMS`. Update consumer callbacks to handle `MMS`; this widens the previous callback contract. diff --git a/AGENTS.md b/AGENTS.md index afac27a..3f5b93b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -229,6 +229,7 @@ When implementation is complete, report in Korean: - Treat the current React version, component style, state management, routing, styling, and test approach as authoritative. - Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations. - Keep components focused and follow the repository's established split between presentation, state, data access, and side effects. +- Do not use nested ternary expressions. Use clear `if`/`else` branches, early returns, or well-named intermediate variables instead; a single, non-nested ternary is acceptable only when it remains immediately readable. - Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable. - Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states. - Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved. diff --git a/README.md b/README.md index 3f087d8..f4cb56d 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ kri-loading-overlay kri-editor kri-layout kri-dialog +kri-color-palette ``` `kri-data-table`은 TanStack Table v8 API를 사용하며 `@tanstack/react-table@^8.21.3` 범위를 지원합니다. KriUiRegistry에서 별도의 마이그레이션 버전을 제공하기 전에는 v9으로 올리지 않습니다. @@ -59,6 +60,7 @@ npx shadcn@latest add https://ui-registry.kric.com/r/kri-loading-overlay.json npx shadcn@latest add https://ui-registry.kric.com/r/kri-editor.json npx shadcn@latest add https://ui-registry.kric.com/r/kri-layout.json npx shadcn@latest add https://ui-registry.kric.com/r/kri-dialog.json +npx shadcn@latest add https://ui-registry.kric.com/r/kri-color-palette.json ``` ## KriAutoComplete 검색 스크롤 @@ -274,6 +276,26 @@ import { KriScatterChart } from '@/components/chart' `footer={null}`을 전달해도 Footer가 표시되지 않습니다. +## KriColorPalette + +`kri-color-palette`는 팝오버형 색상 선택 컴포넌트입니다. 기본 색상 버튼, 색상 영역·색조 슬라이더, HEX 입력, 색상 제거를 제공하며 값은 대문자 `#RRGGBB`(투명도 포함 시 `#RRGGBBAA`) 또는 `null`입니다. + +```tsx + +``` + +- `colors?: readonly string[]`: 기본 색상 버튼 목록. 기본값은 `KRI_COLOR_PALETTE_DEFAULT_COLORS`(16색)입니다. +- `allowCustom?: boolean`(기본 `true`): 색상 영역·색조 슬라이더·HEX 입력 노출 여부입니다. +- `allowAlpha?: boolean`(기본 `false`): 투명도 슬라이더와 `#RRGGBBAA` 입력을 허용합니다. `false`여도 전달받은 `#RRGGBBAA` 값은 투명도까지 표시·보존하며, 사용자가 색을 바꾸면 불투명한 `#RRGGBB`로 바뀝니다. +- `allowClear?: boolean`(기본 `true`), `disabled`, `placeholder`, `className`, `aria-label`을 지원합니다. `disabled`이면 팝오버가 열리지 않습니다. +- 색상 해석·정규화와 밝기 판단 함수(`parseHexColor`, `formatHexColor`, `normalizeHexColor`, `isLightHexColor`)는 `color-palette/color.ts`에서 함께 제공합니다. + +색상 영역은 [Dice UI color-picker](https://www.diceui.com/docs/components/radix/color-picker)(Radix 버전, MIT License)를 `color-palette/` 아래에 포함한 것입니다. 별도 npm 패키지 없이 `radix-ui`, `class-variance-authority`, `lucide-react`와 shadcn `button`, `input`, `popover`, `select`에 의존합니다. + ## Editor 주요 옵션 ```tsx diff --git a/registry/components/KriColorPalette.tsx b/registry/components/KriColorPalette.tsx new file mode 100644 index 0000000..8cced0e --- /dev/null +++ b/registry/components/KriColorPalette.tsx @@ -0,0 +1,247 @@ +'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) => { + 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 + const checkColorClass = isLightHexColor(parsedColor.rgb) ? 'text-black' : 'text-white' + 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} + + + ) +} diff --git a/registry/components/color-palette/color-picker.tsx b/registry/components/color-palette/color-picker.tsx new file mode 100644 index 0000000..0df5d1c --- /dev/null +++ b/registry/components/color-palette/color-picker.tsx @@ -0,0 +1,1687 @@ +"use client"; + +// Adapted from Dice UI color-picker (Radix variant), https://www.diceui.com/docs/components/radix/color-picker (MIT License). +// 로컬 변경: import 경로, 아이콘(lucide PipetteIcon), 빈 interface lint 수정. + +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "@/lib/utils"; +import { + Direction as DirectionPrimitive, + Slider as SliderPrimitive, + Slot as SlotPrimitive, +} from "radix-ui"; +import { useComposedRefs, useLayoutEffect } from "radix-ui/internal"; +import * as React from "react"; + +import { VisuallyHiddenInput } from "./visually-hidden-input"; +import { useRefWithInit } from "./use-ref-with-init"; +import { useValueAsRef } from "./use-value-as-ref"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { PipetteIcon } from "lucide-react"; + +const ROOT_NAME = "ColorPicker"; +const ROOT_IMPL_NAME = "ColorPickerImpl"; +const TRIGGER_NAME = "ColorPickerTrigger"; +const CONTENT_NAME = "ColorPickerContent"; +const AREA_NAME = "ColorPickerArea"; +const HUE_SLIDER_NAME = "ColorPickerHueSlider"; +const ALPHA_SLIDER_NAME = "ColorPickerAlphaSlider"; +const SWATCH_NAME = "ColorPickerSwatch"; +const EYE_DROPPER_NAME = "ColorPickerEyeDropper"; +const FORMAT_SELECT_NAME = "ColorPickerFormatSelect"; +const INPUT_NAME = "ColorPickerInput"; + +const colorFormats = ["hex", "rgb", "hsl", "hsb"] as const; + +interface DivProps extends React.ComponentProps<"div"> { + asChild?: boolean; +} + +type RootElement = React.ComponentRef; +type AreaElement = React.ComponentRef; +type InputElement = React.ComponentRef; + +type ColorFormat = (typeof colorFormats)[number]; + +/** + * @see https://gist.github.com/bkrmendy/f4582173f50fab209ddfef1377ab31e3 + */ +interface EyeDropper { + open: (options?: { signal?: AbortSignal }) => Promise<{ sRGBHex: string }>; +} + +declare global { + interface Window { + EyeDropper?: { + new (): EyeDropper; + }; + } +} + +interface ColorValue { + r: number; + g: number; + b: number; + a: number; +} + +interface HSVColorValue { + h: number; + s: number; + v: number; + a: number; +} + +function hexToRgb(hex: string, alpha?: number): ColorValue { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result + ? { + r: Number.parseInt(result[1] ?? "0", 16), + g: Number.parseInt(result[2] ?? "0", 16), + b: Number.parseInt(result[3] ?? "0", 16), + a: alpha ?? 1, + } + : { r: 0, g: 0, b: 0, a: alpha ?? 1 }; +} + +function toHex(n: number) { + const hex = Math.round(n).toString(16); + return hex.length === 1 ? `0${hex}` : hex; +} + +function rgbToHex(color: ColorValue): string { + return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`; +} + +function rgbToHsv(color: ColorValue): HSVColorValue { + const r = color.r / 255; + const g = color.g / 255; + const b = color.b / 255; + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const diff = max - min; + + let h = 0; + if (diff !== 0) { + switch (max) { + case r: + h = ((g - b) / diff) % 6; + break; + case g: + h = (b - r) / diff + 2; + break; + case b: + h = (r - g) / diff + 4; + break; + } + } + h = Math.round(h * 60); + if (h < 0) h += 360; + + const s = max === 0 ? 0 : diff / max; + const v = max; + + return { + h, + s: Math.round(s * 100), + v: Math.round(v * 100), + a: color.a, + }; +} + +function hsvToRgb(hsv: HSVColorValue): ColorValue { + const h = hsv.h / 360; + const s = hsv.s / 100; + const v = hsv.v / 100; + + const i = Math.floor(h * 6); + const f = h * 6 - i; + const p = v * (1 - s); + const q = v * (1 - f * s); + const t = v * (1 - (1 - f) * s); + + let r: number; + let g: number; + let b: number; + + switch (i % 6) { + case 0: { + r = v; + g = t; + b = p; + break; + } + case 1: { + r = q; + g = v; + b = p; + break; + } + case 2: { + r = p; + g = v; + b = t; + break; + } + case 3: { + r = p; + g = q; + b = v; + break; + } + case 4: { + r = t; + g = p; + b = v; + break; + } + case 5: { + r = v; + g = p; + b = q; + break; + } + default: { + r = 0; + g = 0; + b = 0; + } + } + + return { + r: Math.round(r * 255), + g: Math.round(g * 255), + b: Math.round(b * 255), + a: hsv.a, + }; +} + +function colorToString(color: ColorValue, format: ColorFormat = "hex"): string { + switch (format) { + case "hex": + return rgbToHex(color); + case "rgb": + return color.a < 1 + ? `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})` + : `rgb(${color.r}, ${color.g}, ${color.b})`; + case "hsl": { + const hsl = rgbToHsl(color); + return color.a < 1 + ? `hsla(${hsl.h}, ${hsl.s}%, ${hsl.l}%, ${color.a})` + : `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`; + } + case "hsb": { + const hsv = rgbToHsv(color); + return color.a < 1 + ? `hsba(${hsv.h}, ${hsv.s}%, ${hsv.v}%, ${color.a})` + : `hsb(${hsv.h}, ${hsv.s}%, ${hsv.v}%)`; + } + default: + return rgbToHex(color); + } +} + +function rgbToHsl(color: ColorValue) { + const r = color.r / 255; + const g = color.g / 255; + const b = color.b / 255; + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const diff = max - min; + const sum = max + min; + + const l = sum / 2; + + let h = 0; + let s = 0; + + if (diff !== 0) { + s = l > 0.5 ? diff / (2 - sum) : diff / sum; + + if (max === r) { + h = (g - b) / diff + (g < b ? 6 : 0); + } else if (max === g) { + h = (b - r) / diff + 2; + } else if (max === b) { + h = (r - g) / diff + 4; + } + h /= 6; + } + + return { + h: Math.round(h * 360), + s: Math.round(s * 100), + l: Math.round(l * 100), + }; +} + +function hslToRgb( + hsl: { h: number; s: number; l: number }, + alpha = 1, +): ColorValue { + const h = hsl.h / 360; + const s = hsl.s / 100; + const l = hsl.l / 100; + + const c = (1 - Math.abs(2 * l - 1)) * s; + const x = c * (1 - Math.abs(((h * 6) % 2) - 1)); + const m = l - c / 2; + + let r = 0; + let g = 0; + let b = 0; + + if (h >= 0 && h < 1 / 6) { + r = c; + g = x; + b = 0; + } else if (h >= 1 / 6 && h < 2 / 6) { + r = x; + g = c; + b = 0; + } else if (h >= 2 / 6 && h < 3 / 6) { + r = 0; + g = c; + b = x; + } else if (h >= 3 / 6 && h < 4 / 6) { + r = 0; + g = x; + b = c; + } else if (h >= 4 / 6 && h < 5 / 6) { + r = x; + g = 0; + b = c; + } else if (h >= 5 / 6 && h < 1) { + r = c; + g = 0; + b = x; + } + + return { + r: Math.round((r + m) * 255), + g: Math.round((g + m) * 255), + b: Math.round((b + m) * 255), + a: alpha, + }; +} + +function parseColorString(value: string): ColorValue | null { + const trimmed = value.trim(); + + if (trimmed.startsWith("#")) { + const hexMatch = trimmed.match(/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/); + if (hexMatch) { + return hexToRgb(trimmed); + } + } + + const rgbMatch = trimmed.match( + /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/, + ); + if (rgbMatch) { + return { + r: Number.parseInt(rgbMatch[1] ?? "0", 10), + g: Number.parseInt(rgbMatch[2] ?? "0", 10), + b: Number.parseInt(rgbMatch[3] ?? "0", 10), + a: rgbMatch[4] ? Number.parseFloat(rgbMatch[4]) : 1, + }; + } + + const hslMatch = trimmed.match( + /^hsla?\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(?:,\s*([\d.]+))?\s*\)$/, + ); + if (hslMatch) { + const h = Number.parseInt(hslMatch[1] ?? "0", 10); + const s = Number.parseInt(hslMatch[2] ?? "0", 10) / 100; + const l = Number.parseInt(hslMatch[3] ?? "0", 10) / 100; + const a = hslMatch[4] ? Number.parseFloat(hslMatch[4]) : 1; + + const c = (1 - Math.abs(2 * l - 1)) * s; + const x = c * (1 - Math.abs(((h / 60) % 2) - 1)); + const m = l - c / 2; + + let r = 0; + let g = 0; + let b = 0; + + if (h >= 0 && h < 60) { + r = c; + g = x; + b = 0; + } else if (h >= 60 && h < 120) { + r = x; + g = c; + b = 0; + } else if (h >= 120 && h < 180) { + r = 0; + g = c; + b = x; + } else if (h >= 180 && h < 240) { + r = 0; + g = x; + b = c; + } else if (h >= 240 && h < 300) { + r = x; + g = 0; + b = c; + } else if (h >= 300 && h < 360) { + r = c; + g = 0; + b = x; + } + + return { + r: Math.round((r + m) * 255), + g: Math.round((g + m) * 255), + b: Math.round((b + m) * 255), + a, + }; + } + + const hsbMatch = trimmed.match( + /^hsba?\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(?:,\s*([\d.]+))?\s*\)$/, + ); + if (hsbMatch) { + const h = Number.parseInt(hsbMatch[1] ?? "0", 10); + const s = Number.parseInt(hsbMatch[2] ?? "0", 10); + const v = Number.parseInt(hsbMatch[3] ?? "0", 10); + const a = hsbMatch[4] ? Number.parseFloat(hsbMatch[4]) : 1; + + return hsvToRgb({ h, s, v, a }); + } + + return null; +} + +type Direction = "ltr" | "rtl"; + +interface StoreState { + color: ColorValue; + hsv: HSVColorValue; + open: boolean; + format: ColorFormat; +} + +interface Store { + subscribe: (cb: () => void) => () => void; + getState: () => StoreState; + setColor: (value: ColorValue) => void; + setHsv: (value: HSVColorValue) => void; + setOpen: (value: boolean) => void; + setFormat: (value: ColorFormat) => void; + notify: () => void; +} + +const StoreContext = React.createContext(null); + +function useStoreContext(consumerName: string) { + const context = React.useContext(StoreContext); + if (!context) { + throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``); + } + return context; +} + +function useStore(selector: (state: StoreState) => U): U { + const store = useStoreContext("useStore"); + + const getSnapshot = React.useCallback( + () => selector(store.getState()), + [store, selector], + ); + + return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot); +} + +interface ColorPickerContextValue { + dir: Direction; + disabled?: boolean; + inline?: boolean; + readOnly?: boolean; + required?: boolean; +} + +const ColorPickerContext = React.createContext( + null, +); + +function useColorPickerContext(consumerName: string) { + const context = React.useContext(ColorPickerContext); + if (!context) { + throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``); + } + return context; +} + +interface ColorPickerProps + extends + Omit, + Pick< + React.ComponentProps, + "defaultOpen" | "open" | "onOpenChange" | "modal" + > { + value?: string; + defaultValue?: string; + onValueChange?: (value: string) => void; + dir?: Direction; + format?: ColorFormat; + defaultFormat?: ColorFormat; + onFormatChange?: (format: ColorFormat) => void; + name?: string; + asChild?: boolean; + disabled?: boolean; + inline?: boolean; + readOnly?: boolean; + required?: boolean; +} + +function ColorPicker(props: ColorPickerProps) { + const { + value: valueProp, + defaultValue = "#000000", + onValueChange, + format: formatProp, + defaultFormat = "hex", + onFormatChange, + defaultOpen, + open: openProp, + onOpenChange, + name, + disabled, + inline, + readOnly, + required, + ...rootProps + } = props; + + const listenersRef = useRefWithInit(() => new Set<() => void>()); + const stateRef = useRefWithInit(() => { + const colorString = valueProp ?? defaultValue; + const color = hexToRgb(colorString); + + return { + color, + hsv: rgbToHsv(color), + open: openProp ?? defaultOpen ?? false, + format: formatProp ?? defaultFormat, + }; + }); + + const propsRef = useValueAsRef({ + onValueChange, + onOpenChange, + onFormatChange, + }); + + const store = React.useMemo(() => { + function notify() { + for (const cb of listenersRef.current) { + cb(); + } + } + + return { + subscribe: (cb) => { + listenersRef.current.add(cb); + return () => listenersRef.current.delete(cb); + }, + getState: () => stateRef.current, + setColor: (value: ColorValue) => { + if (Object.is(stateRef.current.color, value)) return; + + const prevState = { ...stateRef.current }; + stateRef.current.color = value; + + if (propsRef.current.onValueChange) { + const colorString = colorToString(value, prevState.format); + propsRef.current.onValueChange(colorString); + } + + notify(); + }, + setHsv: (value: HSVColorValue) => { + if (Object.is(stateRef.current.hsv, value)) return; + + const prevState = { ...stateRef.current }; + stateRef.current.hsv = value; + + if (propsRef.current.onValueChange) { + const colorValue = hsvToRgb(value); + const colorString = colorToString(colorValue, prevState.format); + propsRef.current.onValueChange(colorString); + } + + notify(); + }, + setOpen: (value: boolean) => { + if (Object.is(stateRef.current.open, value)) return; + + stateRef.current.open = value; + + if (propsRef.current.onOpenChange) { + propsRef.current.onOpenChange(value); + } + + notify(); + }, + setFormat: (value: ColorFormat) => { + if (Object.is(stateRef.current.format, value)) return; + + stateRef.current.format = value; + + if (propsRef.current.onFormatChange) { + propsRef.current.onFormatChange(value); + } + + notify(); + }, + notify, + }; + }, [listenersRef, stateRef, propsRef]); + + return ( + + + + ); +} + +type ColorPickerImplProps = Omit< + ColorPickerProps, + | "defaultValue" + | "onValueChange" + | "onOpenChange" + | "format" + | "defaultFormat" + | "onFormatChange" +>; + +function ColorPickerImpl(props: ColorPickerImplProps) { + const { + value: valueProp, + dir: dirProp, + defaultOpen, + open: openProp, + name, + ref, + asChild, + disabled, + inline, + modal, + readOnly, + required, + ...rootProps + } = props; + + const store = useStoreContext(ROOT_IMPL_NAME); + + const dir = DirectionPrimitive.useDirection(dirProp); + + const [formTrigger, setFormTrigger] = React.useState( + null, + ); + const composedRef = useComposedRefs(ref, (node) => setFormTrigger(node)); + const isFormControl = formTrigger ? !!formTrigger.closest("form") : true; + + useLayoutEffect(() => { + if (valueProp !== undefined) { + const currentState = store.getState(); + const color = hexToRgb(valueProp, currentState.color.a); + const hsv = rgbToHsv(color); + store.setColor(color); + store.setHsv(hsv); + } + }, [valueProp, store]); + + useLayoutEffect(() => { + if (openProp !== undefined) { + store.setOpen(openProp); + } + }, [openProp, store]); + + const contextValue = React.useMemo( + () => ({ + dir, + disabled, + inline, + readOnly, + required, + }), + [dir, disabled, inline, readOnly, required], + ); + + const value = useStore((state) => rgbToHex(state.color)); + const open = useStore((state) => state.open); + + const RootPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + if (inline) { + return ( + + + {isFormControl && ( + + )} + + ); + } + + return ( + + + + {isFormControl && ( + + )} + + + ); +} + +function ColorPickerTrigger( + props: React.ComponentProps, +) { + const { asChild, disabled, ...triggerProps } = props; + + const context = useColorPickerContext(TRIGGER_NAME); + + const isDisabled = disabled || context.disabled; + + const TriggerPrimitive = asChild ? SlotPrimitive.Slot : Button; + + return ( + + + + ); +} + +function ColorPickerContent( + props: React.ComponentProps, +) { + const { asChild, className, children, ...popoverContentProps } = props; + + const context = useColorPickerContext(CONTENT_NAME); + + if (context.inline) { + const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + return ( + + {children} + + ); + } + + return ( + + {children} + + ); +} + +function ColorPickerArea(props: DivProps) { + const { + asChild, + onPointerDown: onPointerDownProp, + onPointerMove: onPointerMoveProp, + onPointerUp: onPointerUpProp, + className, + ref, + ...areaProps + } = props; + + const propsRef = useValueAsRef({ + onPointerDown: onPointerDownProp, + onPointerMove: onPointerMoveProp, + onPointerUp: onPointerUpProp, + }); + + const context = useColorPickerContext(AREA_NAME); + const store = useStoreContext(AREA_NAME); + + const hsv = useStore((state) => state.hsv); + + const isDraggingRef = React.useRef(false); + const areaRef = React.useRef(null); + const composedRef = useComposedRefs(ref, areaRef); + + const updateColorFromPosition = React.useCallback( + (clientX: number, clientY: number) => { + if (!areaRef.current) return; + + const rect = areaRef.current.getBoundingClientRect(); + const x = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)); + const y = Math.max( + 0, + Math.min(1, 1 - (clientY - rect.top) / rect.height), + ); + + const newHsv: HSVColorValue = { + h: hsv?.h ?? 0, + s: Math.round(x * 100), + v: Math.round(y * 100), + a: hsv?.a ?? 1, + }; + + store.setHsv(newHsv); + store.setColor(hsvToRgb(newHsv)); + }, + [hsv, store], + ); + + const onPointerDown = React.useCallback( + (event: React.PointerEvent) => { + if (context.disabled) return; + propsRef.current.onPointerDown?.(event); + if (event.defaultPrevented) return; + + isDraggingRef.current = true; + areaRef.current?.setPointerCapture(event.pointerId); + updateColorFromPosition(event.clientX, event.clientY); + }, + [context.disabled, updateColorFromPosition, propsRef], + ); + + const onPointerMove = React.useCallback( + (event: React.PointerEvent) => { + propsRef.current.onPointerMove?.(event); + if (event.defaultPrevented) return; + + if (isDraggingRef.current) { + updateColorFromPosition(event.clientX, event.clientY); + } + }, + [updateColorFromPosition, propsRef], + ); + + const onPointerUp = React.useCallback( + (event: React.PointerEvent) => { + propsRef.current.onPointerUp?.(event); + if (event.defaultPrevented) return; + + isDraggingRef.current = false; + areaRef.current?.releasePointerCapture(event.pointerId); + }, + [propsRef], + ); + + const hue = hsv?.h ?? 0; + const backgroundHue = hsvToRgb({ h: hue, s: 100, v: 100, a: 1 }); + + const AreaPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + return ( + +
+
+
+
+
+
+ + ); +} + +function ColorPickerHueSlider( + props: React.ComponentProps, +) { + const { className, ...sliderProps } = props; + + const context = useColorPickerContext(HUE_SLIDER_NAME); + const store = useStoreContext(HUE_SLIDER_NAME); + + const hsv = useStore((state) => state.hsv); + + const onValueChange = React.useCallback( + (values: number[]) => { + const newHsv: HSVColorValue = { + h: values[0] ?? 0, + s: hsv?.s ?? 0, + v: hsv?.v ?? 0, + a: hsv?.a ?? 1, + }; + store.setHsv(newHsv); + store.setColor(hsvToRgb(newHsv)); + }, + [hsv, store], + ); + + return ( + + + + + + + ); +} + +function ColorPickerAlphaSlider( + props: React.ComponentProps, +) { + const { className, ...sliderProps } = props; + + const context = useColorPickerContext(ALPHA_SLIDER_NAME); + const store = useStoreContext(ALPHA_SLIDER_NAME); + + const color = useStore((state) => state.color); + const hsv = useStore((state) => state.hsv); + + const onValueChange = React.useCallback( + (values: number[]) => { + const alpha = (values[0] ?? 0) / 100; + const newColor = { ...color, a: alpha }; + const newHsv = { ...hsv, a: alpha }; + store.setColor(newColor); + store.setHsv(newHsv); + }, + [color, hsv, store], + ); + + const gradientColor = `rgb(${color?.r ?? 0}, ${color?.g ?? 0}, ${color?.b ?? 0})`; + + return ( + + +
+ + + + + ); +} + +function ColorPickerSwatch(props: DivProps) { + const { asChild, className, ...swatchProps } = props; + + const context = useColorPickerContext(SWATCH_NAME); + + const color = useStore((state) => state.color); + const format = useStore((state) => state.format); + + const backgroundStyle = React.useMemo(() => { + if (!color) { + return { + background: + "linear-gradient(to bottom right, transparent calc(50% - 1px), hsl(var(--destructive)) calc(50% - 1px) calc(50% + 1px), transparent calc(50% + 1px)) no-repeat", + }; + } + + const colorString = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`; + + if (color.a < 1) { + return { + background: `linear-gradient(${colorString}, ${colorString}), repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0% 50% / 8px 8px`, + }; + } + + return { + backgroundColor: colorString, + }; + }, [color]); + + const ariaLabel = !color + ? "No color selected" + : `Current color: ${colorToString(color, format)}`; + + const SwatchPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + return ( + + ); +} + +function subscribeToEyeDropper() { + return () => {}; +} + +function getEyeDropperSnapshot() { + return !!window.EyeDropper; +} + +function getEyeDropperServerSnapshot() { + return false; +} + +function ColorPickerEyeDropper(props: React.ComponentProps) { + const { size: sizeProp, children, disabled, ...buttonProps } = props; + + const context = useColorPickerContext(EYE_DROPPER_NAME); + const store = useStoreContext(EYE_DROPPER_NAME); + + const color = useStore((state) => state.color); + + const isDisabled = disabled || context.disabled; + + const onEyeDropper = React.useCallback(async () => { + if (!window.EyeDropper) return; + + try { + const eyeDropper = new window.EyeDropper(); + const result = await eyeDropper.open(); + + if (result.sRGBHex) { + const currentAlpha = color?.a ?? 1; + const newColor = hexToRgb(result.sRGBHex, currentAlpha); + const newHsv = rgbToHsv(newColor); + store.setColor(newColor); + store.setHsv(newHsv); + } + } catch (error) { + console.warn("EyeDropper error:", error); + } + }, [color, store]); + + const hasEyeDropper = React.useSyncExternalStore( + subscribeToEyeDropper, + getEyeDropperSnapshot, + getEyeDropperServerSnapshot, + ); + + if (!hasEyeDropper) return null; + + const size = sizeProp ?? (children ? "default" : "icon"); + + return ( + + ); +} + +interface ColorPickerFormatSelectProps + extends + Omit, "value" | "onValueChange">, + Pick, "size" | "className"> {} + +function ColorPickerFormatSelect(props: ColorPickerFormatSelectProps) { + const { size, disabled, className, ...selectProps } = props; + + const context = useColorPickerContext(FORMAT_SELECT_NAME); + const store = useStoreContext(FORMAT_SELECT_NAME); + const isDisabled = disabled || context.disabled; + + const format = useStore((state) => state.format); + + const onFormatChange = React.useCallback( + (value: ColorFormat) => { + store.setFormat(value); + }, + [store], + ); + + return ( + + ); +} + +interface ColorPickerInputProps extends Omit< + React.ComponentProps, + "value" | "onChange" | "color" +> { + withoutAlpha?: boolean; +} + +function ColorPickerInput(props: ColorPickerInputProps) { + const store = useStoreContext(INPUT_NAME); + const context = useColorPickerContext(INPUT_NAME); + + const color = useStore((state) => state.color); + const format = useStore((state) => state.format); + const hsv = useStore((state) => state.hsv); + + const onColorChange = React.useCallback( + (newColor: ColorValue) => { + const newHsv = rgbToHsv(newColor); + store.setColor(newColor); + store.setHsv(newHsv); + }, + [store], + ); + + if (format === "hex") { + return ( + + ); + } + + if (format === "rgb") { + return ( + + ); + } + + if (format === "hsl") { + return ( + + ); + } + + if (format === "hsb") { + return ( + + ); + } +} + +const inputGroupItemVariants = cva("h-8 [-moz-appearance:textfield] focus-visible:z-10 focus-visible:ring-1 [&::-webkit-inner-spin-button]:m-0 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:m-0 [&::-webkit-outer-spin-button]:appearance-none", { + variants: { + position: { + first: "rounded-r-none", + middle: "-ml-px rounded-none border-l-0", + last: "-ml-px rounded-l-none border-l-0", + isolated: "", + }, + }, + defaultVariants: { + position: "isolated", + }, +}); + +interface InputGroupItemProps + extends + React.ComponentProps, + VariantProps {} + +function InputGroupItem({ + className, + position, + ...props +}: InputGroupItemProps) { + return ( + + ); +} + +interface FormatInputProps extends ColorPickerInputProps { + color: ColorValue; + onColorChange: (color: ColorValue) => void; + context: ColorPickerContextValue; +} + +function HexInput(props: FormatInputProps) { + const { + color, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const hexValue = rgbToHex(color); + const alphaValue = Math.round((color?.a ?? 1) * 100); + + const onHexChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = event.target.value; + const parsedColor = parseColorString(value); + if (parsedColor) { + onColorChange({ ...parsedColor, a: color?.a ?? 1 }); + } + }, + [color, onColorChange], + ); + + const onAlphaChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= 100) { + onColorChange({ ...color, a: value / 100 }); + } + }, + [color, onColorChange], + ); + + if (withoutAlpha) { + return ( + + ); + } + + return ( +
+ + +
+ ); +} + +function RgbInput(props: FormatInputProps) { + const { + color, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const rValue = Math.round(color?.r ?? 0); + const gValue = Math.round(color?.g ?? 0); + const bValue = Math.round(color?.b ?? 0); + const alphaValue = Math.round((color?.a ?? 1) * 100); + + const onChannelChange = React.useCallback( + (channel: "r" | "g" | "b" | "a", max: number, isAlpha = false) => + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= max) { + const newValue = isAlpha ? value / 100 : value; + onColorChange({ ...color, [channel]: newValue }); + } + }, + [color, onColorChange], + ); + + return ( +
+ + + + {!withoutAlpha && ( + + )} +
+ ); +} + +function HslInput(props: FormatInputProps) { + const { + color, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const hsl = React.useMemo(() => rgbToHsl(color), [color]); + const alphaValue = Math.round((color?.a ?? 1) * 100); + + const onHslChannelChange = React.useCallback( + (channel: "h" | "s" | "l", max: number) => + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= max) { + const newHsl = { ...hsl, [channel]: value }; + const newColor = hslToRgb(newHsl, color?.a ?? 1); + onColorChange(newColor); + } + }, + [hsl, color, onColorChange], + ); + + const onAlphaChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= 100) { + onColorChange({ ...color, a: value / 100 }); + } + }, + [color, onColorChange], + ); + + return ( +
+ + + + {!withoutAlpha && ( + + )} +
+ ); +} + +interface HsbInputProps extends Omit { + hsv: HSVColorValue; +} + +function HsbInput(props: HsbInputProps) { + const { + hsv, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const alphaValue = Math.round((hsv?.a ?? 1) * 100); + + const onHsvChannelChange = React.useCallback( + (channel: "h" | "s" | "v", max: number) => + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= max) { + const newHsv = { ...hsv, [channel]: value }; + const newColor = hsvToRgb(newHsv); + onColorChange(newColor); + } + }, + [hsv, onColorChange], + ); + + const onAlphaChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= 100) { + const currentColor = hsvToRgb(hsv); + onColorChange({ ...currentColor, a: value / 100 }); + } + }, + [hsv, onColorChange], + ); + + return ( +
+ + + + {!withoutAlpha && ( + + )} +
+ ); +} + +export { + ColorPicker, + ColorPickerAlphaSlider, + ColorPickerArea, + ColorPickerContent, + ColorPickerEyeDropper, + ColorPickerFormatSelect, + ColorPickerHueSlider, + ColorPickerInput, + type ColorPickerProps, + ColorPickerSwatch, + ColorPickerTrigger, + useStore as useColorPicker, +}; diff --git a/registry/components/color-palette/color.ts b/registry/components/color-palette/color.ts new file mode 100644 index 0000000..2d3c133 --- /dev/null +++ b/registry/components/color-palette/color.ts @@ -0,0 +1,42 @@ +export type ParsedHexColor = { + /** `#RRGGBB` (대문자) */ + rgb: string + /** 0~255. 투명도가 없는 값은 255 */ + alpha: number +} + +const HEX_COLOR_PATTERN = /^#?([0-9A-F]{6})([0-9A-F]{2})?$/ + +/** `#RRGGBB` 또는 `#RRGGBBAA`(대소문자 무관, `#` 생략 가능)를 해석한다. 형식이 다르면 null. */ +export const parseHexColor = (value: string | null | undefined): ParsedHexColor | null => { + if (!value) return null + const match = HEX_COLOR_PATTERN.exec(value.trim().toUpperCase()) + if (!match) return null + return { + rgb: `#${match[1]}`, + alpha: match[2] ? Number.parseInt(match[2], 16) : 255, + } +} + +/** 투명도가 255이면 `#RRGGBB`, 아니면 `#RRGGBBAA`로 만든다. */ +export const formatHexColor = (rgb: string, alpha = 255): string => { + const clamped = Math.max(0, Math.min(255, Math.round(alpha))) + if (clamped === 255) return rgb.toUpperCase() + return `${rgb.toUpperCase()}${clamped.toString(16).padStart(2, '0').toUpperCase()}` +} + +/** 정규화된 hex 문자열. 형식이 다르면 null. */ +export const normalizeHexColor = (value: string | null | undefined): string | null => { + const parsed = parseHexColor(value) + return parsed ? formatHexColor(parsed.rgb, parsed.alpha) : null +} + +/** 흰 배경 위에 그렸을 때 밝은 색인지 판단한다(투명도 반영). 글자색 대비 결정에 쓴다. */ +export const isLightHexColor = (value: string): boolean => { + const parsed = parseHexColor(value) + if (!parsed) return true + const ratio = parsed.alpha / 255 + const channel = (offset: number) => Number.parseInt(parsed.rgb.slice(offset, offset + 2), 16) * ratio + 255 * (1 - ratio) + const luminance = (channel(1) * 299 + channel(3) * 587 + channel(5) * 114) / 1000 + return luminance > 150 +} diff --git a/registry/components/color-palette/use-ref-with-init.ts b/registry/components/color-palette/use-ref-with-init.ts new file mode 100644 index 0000000..01d2bcd --- /dev/null +++ b/registry/components/color-palette/use-ref-with-init.ts @@ -0,0 +1,8 @@ +import * as React from "react"; + +function useRefWithInit(init: () => T): React.RefObject { + const [ref] = React.useState(() => ({ current: init() })); + return ref; +} + +export { useRefWithInit }; diff --git a/registry/components/color-palette/use-value-as-ref.ts b/registry/components/color-palette/use-value-as-ref.ts new file mode 100644 index 0000000..9a0d10a --- /dev/null +++ b/registry/components/color-palette/use-value-as-ref.ts @@ -0,0 +1,14 @@ +import { useLayoutEffect } from "radix-ui/internal"; +import * as React from "react"; + +function useValueAsRef(value: T) { + const ref = React.useRef(value); + + useLayoutEffect(() => { + ref.current = value; + }); + + return ref; +} + +export { useValueAsRef }; diff --git a/registry/components/color-palette/visually-hidden-input.tsx b/registry/components/color-palette/visually-hidden-input.tsx new file mode 100644 index 0000000..cadd4fb --- /dev/null +++ b/registry/components/color-palette/visually-hidden-input.tsx @@ -0,0 +1,154 @@ +"use client"; + +import * as React from "react"; + +type InputValue = string[] | string; + +interface VisuallyHiddenInputProps extends Omit< + React.InputHTMLAttributes, + "value" | "checked" | "onReset" +> { + value?: T; + checked?: boolean; + control: HTMLElement | null; + bubbles?: boolean; +} + +function VisuallyHiddenInput( + props: VisuallyHiddenInputProps, +) { + const { + control, + value, + checked, + bubbles = true, + type = "hidden", + style, + ...inputProps + } = props; + + const isCheckInput = React.useMemo( + () => type === "checkbox" || type === "radio" || type === "switch", + [type], + ); + const inputRef = React.useRef(null); + + const prevValueRef = React.useRef( + isCheckInput ? checked : value, + ); + + const [measuredSize, setMeasuredSize] = React.useState<{ + control: HTMLElement; + width: number; + height: number; + } | null>(null); + + const controlSize = React.useMemo<{ + width?: number; + height?: number; + }>( + () => + control && measuredSize?.control === control + ? { width: measuredSize.width, height: measuredSize.height } + : {}, + [control, measuredSize], + ); + + React.useLayoutEffect(() => { + if (!control) return; + + if (typeof window === "undefined") return; + + const resizeObserver = new ResizeObserver((entries) => { + if (!Array.isArray(entries) || !entries.length) return; + + const entry = entries[0]; + if (!entry) return; + + let width: number; + let height: number; + + if ("borderBoxSize" in entry) { + const borderSizeEntry = entry.borderBoxSize; + const borderSize = Array.isArray(borderSizeEntry) + ? borderSizeEntry[0] + : borderSizeEntry; + width = borderSize.inlineSize; + height = borderSize.blockSize; + } else { + width = control.offsetWidth; + height = control.offsetHeight; + } + + setMeasuredSize({ control, width, height }); + }); + + resizeObserver.observe(control, { box: "border-box" }); + return () => { + resizeObserver.disconnect(); + }; + }, [control]); + + React.useEffect(() => { + const currentValue = isCheckInput ? checked : value; + const prevValue = prevValueRef.current; + prevValueRef.current = currentValue; + + const input = inputRef.current; + if (!input) return; + + const inputProto = window.HTMLInputElement.prototype; + const propertyKey = isCheckInput ? "checked" : "value"; + const eventType = isCheckInput ? "click" : "input"; + + let serializedCurrentValue: unknown = value; + if (isCheckInput) { + serializedCurrentValue = checked; + } else if (typeof value === "object" && value !== null) { + serializedCurrentValue = JSON.stringify(value); + } + + const descriptor = Object.getOwnPropertyDescriptor(inputProto, propertyKey); + + const setter = descriptor?.set; + + if (prevValue !== currentValue && setter) { + const event = new Event(eventType, { bubbles }); + setter.call(input, serializedCurrentValue); + input.dispatchEvent(event); + } + }, [value, checked, bubbles, isCheckInput]); + + const composedStyle = React.useMemo(() => { + return { + ...style, + ...(controlSize.width !== undefined && controlSize.height !== undefined + ? controlSize + : {}), + border: 0, + clip: "rect(0 0 0 0)", + clipPath: "inset(50%)", + height: "1px", + margin: "-1px", + overflow: "hidden", + padding: 0, + position: "absolute", + whiteSpace: "nowrap", + width: "1px", + }; + }, [style, controlSize]); + + return ( + + ); +} + +export { VisuallyHiddenInput }; diff --git a/registry/components/registry.json b/registry/components/registry.json index c06260d..cbef30e 100644 --- a/registry/components/registry.json +++ b/registry/components/registry.json @@ -517,6 +517,55 @@ "target": "@components/common/KriDialog.tsx" } ] + }, + { + "name": "kri-color-palette", + "type": "registry:component", + "title": "KRI Color Palette", + "description": "기본 색상 버튼, 색상 영역·색조 슬라이더, HEX 입력과 선택적 투명도를 지원하는 색상 선택 컴포넌트입니다.", + "registryDependencies": [ + "button", + "input", + "popover", + "select" + ], + "dependencies": [ + "class-variance-authority", + "lucide-react", + "radix-ui" + ], + "files": [ + { + "path": "KriColorPalette.tsx", + "type": "registry:component", + "target": "@components/common/KriColorPalette.tsx" + }, + { + "path": "color-palette/color.ts", + "type": "registry:component", + "target": "@components/common/color-palette/color.ts" + }, + { + "path": "color-palette/color-picker.tsx", + "type": "registry:component", + "target": "@components/common/color-palette/color-picker.tsx" + }, + { + "path": "color-palette/visually-hidden-input.tsx", + "type": "registry:component", + "target": "@components/common/color-palette/visually-hidden-input.tsx" + }, + { + "path": "color-palette/use-ref-with-init.ts", + "type": "registry:component", + "target": "@components/common/color-palette/use-ref-with-init.ts" + }, + { + "path": "color-palette/use-value-as-ref.ts", + "type": "registry:component", + "target": "@components/common/color-palette/use-value-as-ref.ts" + } + ] } ] }