跳至正文
获取 Pro
动效组件M.14

色相选择器

FreeRegistry
components/linyi/color-selector.tsx
motionlucide-react
"use client";
 
import * as React from "react";
import { motion } from "motion/react";
import { Check, Copy } from "lucide-react";
import { cn } from "@/lib/cn";
import { SPRING_SNAPPY } from "@/lib/motion";
 
export interface ColorSwatch {
hex: string;
name?: string;
}
 
// verify-registry: allow-hex-start(可通过 swatches 属性覆盖的默认色板数据)
const DEFAULT_SWATCHES: ColorSwatch[] = [
{ hex: "#C23B26", name: "朱砂印泥" },
{ hex: "#2C6B5E", name: "松石黛绿" },
{ hex: "#233B5D", name: "霁蓝官窑" },
{ hex: "#B08D4F", name: "错金赤铜" },
{ hex: "#1F1C18", name: "端砚松墨" },
];
// verify-registry: allow-hex-end
 
/**
* Convert a 3- or 6-digit hex color string to an `rgb(r, g, b)` token.
*/
export function hexToRgb(hex: string): string {
const clean = hex.replace("#", "").trim();
const full =
clean.length === 3
? clean
.split("")
.map((c) => c + c)
.join("")
: clean.padEnd(6, "0").slice(0, 6);
 
const num = Number.parseInt(full, 16);
if (Number.isNaN(num)) return "rgb(0, 0, 0)";
const r = (num >> 16) & 255;
const g = (num >> 8) & 255;
const b = num & 255;
return `rgb(${r}, ${g}, ${b})`;
}
 
export interface ColorSelectorProps {
swatches?: (string | ColorSwatch)[];
value?: string;
defaultValue?: string;
onChange?: (hex: string, rgb: string) => void;
showTokens?: boolean;
copyable?: boolean;
size?: "sm" | "md";
ariaLabel?: string;
className?: string;
}
 
export function ColorSelector({
swatches = DEFAULT_SWATCHES,
value,
defaultValue,
onChange,
showTokens = true,
copyable = false,
size = "md",
ariaLabel = "色相选择",
className,
}: ColorSelectorProps) {
const normalized: ColorSwatch[] = React.useMemo(
() => swatches.map((s) => (typeof s === "string" ? { hex: s } : s)),
[swatches]
);
 
const [internalHex, setInternalHex] = React.useState(
defaultValue ?? normalized[0]?.hex ?? DEFAULT_SWATCHES[0].hex
);
const [copiedField, setCopiedField] = React.useState<"hex" | "rgb" | null>(null);
const uid = React.useId();
const buttonRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
const copyTimerRef = React.useRef<number | null>(null);
 
const selectedHex = value ?? internalHex;
const selectedIndex = Math.max(
0,
normalized.findIndex((s) => s.hex.toUpperCase() === selectedHex.toUpperCase())
);
const current = normalized[selectedIndex] ?? normalized[0];
const hexDisplay = (current?.hex ?? selectedHex).toUpperCase();
const rgbDisplay = hexToRgb(hexDisplay);
 
React.useEffect(() => {
return () => {
if (copyTimerRef.current) window.clearTimeout(copyTimerRef.current);
};
}, []);
 
const selectByIndex = (idx: number, focus = false) => {
const next = normalized[idx];
if (!next) return;
if (value === undefined) {
setInternalHex(next.hex);
}
onChange?.(next.hex.toUpperCase(), hexToRgb(next.hex));
if (focus) {
buttonRefs.current[idx]?.focus();
}
};
 
const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>, idx: number) => {
const count = normalized.length;
if (count === 0) return;
 
if (e.key === "ArrowRight" || e.key === "ArrowDown") {
e.preventDefault();
selectByIndex((idx + 1) % count, true);
} else if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
e.preventDefault();
selectByIndex((idx - 1 + count) % count, true);
} else if (e.key === "Home") {
e.preventDefault();
selectByIndex(0, true);
} else if (e.key === "End") {
e.preventDefault();
selectByIndex(count - 1, true);
}
};
 
const handleCopy = async (field: "hex" | "rgb", text: string) => {
try {
await navigator.clipboard?.writeText(text);
} catch {
// Fallback silently if clipboard permission is unavailable
}
setCopiedField(field);
if (copyTimerRef.current) window.clearTimeout(copyTimerRef.current);
copyTimerRef.current = window.setTimeout(() => setCopiedField(null), 1400);
};
 
const ringSize = size === "sm" ? "h-7 w-7" : "h-8 w-8";
const dotSize = size === "sm" ? "h-4.5 w-4.5" : "h-5 w-5";
 
return (
<div className={cn("inline-flex flex-col items-center gap-3", className)}>
<div
role="radiogroup"
aria-label={ariaLabel}
className="flex items-center gap-2"
>
{normalized.map((swatch, idx) => {
const active = idx === selectedIndex;
const label = swatch.name ? `${swatch.name} ${swatch.hex}` : swatch.hex;
return (
<button
key={swatch.hex}
ref={(el) => {
buttonRefs.current[idx] = el;
}}
type="button"
role="radio"
aria-checked={active}
aria-label={label}
tabIndex={active ? 0 : -1}
onClick={() => selectByIndex(idx)}
onKeyDown={(e) => handleKeyDown(e, idx)}
className={cn(
"relative flex items-center justify-center rounded-full cursor-pointer",
ringSize
)}
>
{active && (
<motion.span
layoutId={`color-ring-${uid}`}
transition={SPRING_SNAPPY}
aria-hidden="true"
className="pointer-events-none absolute inset-0 rounded-full border-2 border-fg"
/>
)}
<span
aria-hidden="true"
className={cn(
"pointer-events-none block rounded-full border border-black/10 dark:border-white/15 transition-transform duration-150 active:scale-90",
dotSize
)}
style={{ backgroundColor: swatch.hex }}
/>
</button>
);
})}
</div>
 
{showTokens && (
<div className="flex flex-wrap items-center justify-center gap-1.5 font-mono-num text-[11px]">
{copyable ? (
<>
<button
type="button"
onClick={() => handleCopy("hex", hexDisplay)}
className="inline-flex items-center gap-1.5 rounded-control border border-line bg-surface px-2.5 py-1 text-fg transition-colors hover:border-line-strong cursor-pointer"
aria-label={`复制 Hex ${hexDisplay}`}
>
<span
className="h-2 w-2 rounded-full"
style={{ backgroundColor: hexDisplay }}
/>
<span>{hexDisplay}</span>
{copiedField === "hex" ? (
<Check className="h-3 w-3 text-success" />
) : (
<Copy className="h-3 w-3 text-fg-muted" />
)}
</button>
<button
type="button"
onClick={() => handleCopy("rgb", rgbDisplay)}
className="inline-flex items-center gap-1.5 rounded-control border border-line bg-surface px-2.5 py-1 text-fg-secondary transition-colors hover:border-line-strong hover:text-fg cursor-pointer"
aria-label={`复制 RGB ${rgbDisplay}`}
>
<span>{rgbDisplay}</span>
{copiedField === "rgb" ? (
<Check className="h-3 w-3 text-success" />
) : (
<Copy className="h-3 w-3 text-fg-muted" />
)}
</button>
</>
) : (
<div className="flex items-center gap-1.5 text-fg-secondary">
<span className="font-medium text-fg">{hexDisplay}</span>
<span className="text-fg-muted" aria-hidden="true">
·
</span>
<span className="text-fg-muted">{rgbDisplay}</span>
</div>
)}
</div>
)}
</div>
);
}