261116_01_ENH: 색상 선택 컴포넌트(kri-color-palette) 추가 및 선택적 투명도 지원

This commit is contained in:
2026-11-16 16:54:13 +09:00
parent bffd953343
commit 8625593ac9
10 changed files with 2231 additions and 0 deletions

View File

@@ -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.

View File

@@ -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.

View File

@@ -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
<KriColorPalette
value={color}
onChange={setColor}
aria-label="헤더 색상"
/>
```
- `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

View File

@@ -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<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>
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -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
}

View File

@@ -0,0 +1,8 @@
import * as React from "react";
function useRefWithInit<T>(init: () => T): React.RefObject<T> {
const [ref] = React.useState(() => ({ current: init() }));
return ref;
}
export { useRefWithInit };

View File

@@ -0,0 +1,14 @@
import { useLayoutEffect } from "radix-ui/internal";
import * as React from "react";
function useValueAsRef<T>(value: T) {
const ref = React.useRef<T>(value);
useLayoutEffect(() => {
ref.current = value;
});
return ref;
}
export { useValueAsRef };

View File

@@ -0,0 +1,154 @@
"use client";
import * as React from "react";
type InputValue = string[] | string;
interface VisuallyHiddenInputProps<T = InputValue> extends Omit<
React.InputHTMLAttributes<HTMLInputElement>,
"value" | "checked" | "onReset"
> {
value?: T;
checked?: boolean;
control: HTMLElement | null;
bubbles?: boolean;
}
function VisuallyHiddenInput<T = InputValue>(
props: VisuallyHiddenInputProps<T>,
) {
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<HTMLInputElement>(null);
const prevValueRef = React.useRef<T | boolean | undefined>(
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<React.CSSProperties>(() => {
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 (
<input
type={type}
{...inputProps}
ref={inputRef}
aria-hidden={isCheckInput}
tabIndex={-1}
defaultChecked={isCheckInput ? checked : undefined}
style={composedStyle}
/>
);
}
export { VisuallyHiddenInput };

View File

@@ -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"
}
]
}
]
}