From 704d0eb6657c029aa4d12de22921a15092b155c8 Mon Sep 17 00:00:00 2001 From: Thomasgsn Date: Wed, 28 Oct 2026 17:54:25 +0100 Subject: [PATCH 1/2] feat: add color picker component --- CHANGELOG.md | 2 + components/motion/color-picker.tsx | 212 ++++++++++++++++++ components/previews/index.tsx | 9 + .../previews/motion/color-picker.preview.tsx | 20 ++ .../motion/color-picker/controlled.tsx | 20 ++ .../previews/motion/color-picker/form.tsx | 25 +++ lib/component-dates.ts | 1 + lib/registry.ts | 29 +++ 8 files changed, 318 insertions(+) create mode 100644 components/motion/color-picker.tsx create mode 100644 components/previews/motion/color-picker.preview.tsx create mode 100644 components/previews/motion/color-picker/controlled.tsx create mode 100644 components/previews/motion/color-picker/form.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index ac2dc9a..75faa5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ changes to a component's API are marked **Breaking**. ### Added +- **Color Picker**. A draggable color field, native keyboard sliders, HEX editing, and preset swatches. Supports controlled and uncontrolled values, disabled controls, form submission and reset, and reduced motion. + - `CHANGELOG.md`, branch and release rules in `CONTRIBUTING.md`, a pull request template, and issue templates for bugs and component requests. - 21st.dev export scripts. `scripts/build-21st.ts` turns seven picks (Rating, Tag Input, Morphing Search, Hold to Confirm, Expandable Tabs, Stepper, Number Ticker) into self-contained files with the motion tokens inlined and colors mapped to the stock shadcn theme. - `scripts/build-21st-blocks.ts` bundles six blocks (Agent Run, Onboarding Flow, Revenue Dashboard, Account Settings, Sign In With Code, Mobile App Shell) into single files, inlining every free component each one uses. diff --git a/components/motion/color-picker.tsx b/components/motion/color-picker.tsx new file mode 100644 index 0000000..58814a9 --- /dev/null +++ b/components/motion/color-picker.tsx @@ -0,0 +1,212 @@ +"use client"; + +import { Check } from "lucide-react"; +import { motion, useReducedMotion } from "motion/react"; +import { type CSSProperties, type PointerEvent, useEffect, useId, useRef, useState } from "react"; +import { SPRING_PRESS } from "@/lib/ease"; +import { cn } from "@/lib/utils"; + +export interface ColorPickerProps { + /** Controlled opaque color as #RGB or #RRGGBB. Invalid values use #6366f1. */ + value?: string; + /** Initial opaque color when uncontrolled. Default "#6366f1". */ + defaultValue?: string; + /** Called with a lowercase #RRGGBB color as the selection changes. */ + onValueChange?: (value: string) => void; + /** Preset colors as #RGB or #RRGGBB. Pass [] to hide them. */ + swatches?: readonly string[]; + /** Accessible name for the picker. Default "Color". */ + label?: string; + /** Disables every control. Default false. */ + disabled?: boolean; + /** Form field name for the selected #RRGGBB value. */ + name?: string; + /** Additional classes for the panel. */ + className?: string; +} + +type HSV = { h: number; s: number; v: number }; +const DEFAULT = "#6366f1"; +const SWATCHES = ["#ef4444", "#eab308", "#22c55e", "#06b6d4", "#6366f1", "#ec4899"]; + +function normalize(value: string): string | null { + const hex = value.trim().replace(/^#/, ""); + if (/^[\da-f]{3}$/i.test(hex)) return `#${[...hex].map((c) => c + c).join("").toLowerCase()}`; + return /^[\da-f]{6}$/i.test(hex) ? `#${hex.toLowerCase()}` : null; +} + +function fromHex(hex: string): HSV { + const [r, g, b] = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16) / 255); + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const delta = max - min; + let h = 0; + if (delta) { + if (max === r) h = ((g - b) / delta) % 6; + else if (max === g) h = (b - r) / delta + 2; + else h = (r - g) / delta + 4; + } + return { h: (h * 60 + 360) % 360, s: max ? delta / max * 100 : 0, v: max * 100 }; +} + +function toHex({ h, s, v }: HSV): string { + const channel = (offset: number) => { + const k = (offset + h / 60) % 6; + return Math.round((v / 100 - v / 100 * s / 100 * Math.max(0, Math.min(k, 4 - k, 1))) * 255) + .toString(16).padStart(2, "0"); + }; + return `#${channel(5)}${channel(3)}${channel(1)}`; +} + +const RANGE = cn( + "h-11 w-full cursor-pointer appearance-none bg-transparent outline-none disabled:cursor-not-allowed", + "[&::-webkit-slider-runnable-track]:h-2.5 [&::-webkit-slider-runnable-track]:rounded-full [&::-webkit-slider-runnable-track]:bg-[image:var(--picker-track)]", + "[&::-moz-range-track]:h-2.5 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-[image:var(--picker-track)]", + "[&::-webkit-slider-thumb]:-mt-1.5 [&::-webkit-slider-thumb]:size-[22px] [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-white", + "[&::-moz-range-thumb]:size-[22px] [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-white", + "[&::-webkit-slider-thumb]:shadow-[0_0_0_1px_var(--border-strong),0_1px_3px_rgb(0_0_0/0.25)]", + "[&::-moz-range-thumb]:shadow-[0_0_0_1px_var(--border-strong),0_1px_3px_rgb(0_0_0/0.25)]", + "focus-visible:[&::-webkit-slider-thumb]:outline-2 focus-visible:[&::-webkit-slider-thumb]:outline-offset-2 focus-visible:[&::-webkit-slider-thumb]:outline-foreground", + "focus-visible:[&::-moz-range-thumb]:outline-2 focus-visible:[&::-moz-range-thumb]:outline-offset-2 focus-visible:[&::-moz-range-thumb]:outline-foreground", +); + +/** + * An inline opaque color picker. Drag the color field or use the three native + * sliders with arrow keys, Home and End. HEX edits commit on blur or Enter; + * invalid edits revert, and Escape cancels an edit. Color changes follow input + * immediately. Only pointer presses on presets animate, with reduced motion + * turning that feedback off. + */ +export function ColorPicker({ + value, defaultValue = DEFAULT, onValueChange, swatches = SWATCHES, + label = "Color", disabled = false, name, className, +}: ColorPickerProps) { + const id = useId(); + const reduce = useReducedMotion(); + const inputRef = useRef(null); + const initial = normalize(defaultValue) ?? DEFAULT; + const [model, setModel] = useState(() => ({ hex: initial, hsv: fromHex(initial) })); + const controlled = value === undefined ? null : normalize(value) ?? DEFAULT; + const current = controlled !== null && controlled !== model.hex + ? { hex: controlled, hsv: fromHex(controlled) } : model; + // Retain hue at zero saturation and black, where HEX cannot encode it. + if (current !== model) setModel(current); + const { hex, hsv } = current; + const [draft, setDraft] = useState(hex); + const [pointerPress, setPointerPress] = useState(false); + useEffect(() => setDraft(hex), [hex]); + + useEffect(() => { + const form = inputRef.current?.form; + if (!form || value !== undefined) return; + const reset = (event: Event) => { + queueMicrotask(() => { + if (event.defaultPrevented) return; + setModel({ hex: initial, hsv: fromHex(initial) }); + setDraft(initial); + }); + }; + form.addEventListener("reset", reset); + return () => form.removeEventListener("reset", reset); + }, [initial, value]); + + const update = (next: HSV) => { + if (disabled) return; + const nextHex = toHex(next); + setModel({ hex: nextHex, hsv: next }); + if (nextHex !== hex) onValueChange?.(nextHex); + }; + const commit = () => { + const next = normalize(draft); + if (next && next !== hex) update(fromHex(next)); + setDraft(value === undefined ? next ?? hex : hex); + }; + const move = (event: PointerEvent) => { + if (disabled) return; + const rect = event.currentTarget.getBoundingClientRect(); + if (!rect.width || !rect.height) return; + update({ + ...hsv, + s: Math.max(0, Math.min(100, (event.clientX - rect.left) / rect.width * 100)), + v: Math.max(0, Math.min(100, 100 - (event.clientY - rect.top) / rect.height * 100)), + }); + }; + const presets = [...new Set(swatches.map(normalize).filter((color): color is string => color !== null))]; + const invalid = normalize(draft) === null; + const tracks = [ + { key: "h", label: "Hue", max: 360, suffix: "degrees", track: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)" }, + { key: "s", label: "Saturation", max: 100, suffix: "percent", track: `linear-gradient(to right, ${toHex({ ...hsv, s: 0 })}, ${toHex({ ...hsv, s: 100 })})` }, + { key: "v", label: "Brightness", max: 100, suffix: "percent", track: `linear-gradient(to right, #000, ${toHex({ ...hsv, v: 100 })})` }, + ] as const; + + return ( +
+
+ {label} +
+ {/* Pointer shortcut. The sliders below provide the same controls to keyboards and assistive technology. */} + +
+ {tracks.map((track) => ( + + ))} +
+ + {invalid &&

Use 3 or 6 hex digits.

} + {presets.length > 0 && ( +
+ {presets.map((color) => ( + setPointerPress(true)} onKeyDown={() => setPointerPress(false)} + whileTap={reduce || !pointerPress ? undefined : { scale: 0.97 }} transition={SPRING_PRESS} + onClick={() => update(fromHex(color))} + className="flex size-11 items-center justify-center rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-foreground/40 disabled:cursor-not-allowed"> + + {hex === color && + + ))} +
+ )} + +
+ ); +} diff --git a/components/previews/index.tsx b/components/previews/index.tsx index 55664b7..a952ac8 100644 --- a/components/previews/index.tsx +++ b/components/previews/index.tsx @@ -4,6 +4,15 @@ import type { ComponentType } from "react"; // Every preview is a client component that pulls in its library code. // Lazy chunks keep a page's JS limited to the previews it actually renders. export const previews: Record = { + "motion/color-picker": dynamic(() => + import("./motion/color-picker.preview").then((m) => m.ColorPickerPreview), + ), + "motion/color-picker-controlled": dynamic(() => + import("./motion/color-picker/controlled").then((m) => m.ColorPickerControlledPreview), + ), + "motion/color-picker-form": dynamic(() => + import("./motion/color-picker/form").then((m) => m.ColorPickerFormPreview), + ), "motion/button": dynamic(() => import("./motion/button.preview").then((m) => m.ButtonPreview), ), diff --git a/components/previews/motion/color-picker.preview.tsx b/components/previews/motion/color-picker.preview.tsx new file mode 100644 index 0000000..1d1847a --- /dev/null +++ b/components/previews/motion/color-picker.preview.tsx @@ -0,0 +1,20 @@ +"use client"; + +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/motion/tabs"; +import { ColorPickerControlledPreview } from "./color-picker/controlled"; +import { ColorPickerFormPreview } from "./color-picker/form"; + +export function ColorPickerPreview() { + return ( + +
+ + Controlled + Form + +
+ + +
+ ); +} diff --git a/components/previews/motion/color-picker/controlled.tsx b/components/previews/motion/color-picker/controlled.tsx new file mode 100644 index 0000000..ddfaf9b --- /dev/null +++ b/components/previews/motion/color-picker/controlled.tsx @@ -0,0 +1,20 @@ +"use client"; + +import { useState } from "react"; +import { ColorPicker } from "@/components/motion/color-picker"; + +export function ColorPickerControlledPreview() { + const [color, setColor] = useState("#6366f1"); + + return ( +
+
+ + {color} +
+ +
+ ); +} diff --git a/components/previews/motion/color-picker/form.tsx b/components/previews/motion/color-picker/form.tsx new file mode 100644 index 0000000..0a4ad3c --- /dev/null +++ b/components/previews/motion/color-picker/form.tsx @@ -0,0 +1,25 @@ +"use client"; + +import { useState } from "react"; +import { ColorPicker } from "@/components/motion/color-picker"; +import { Button } from "@/components/motion/button"; + +export function ColorPickerFormPreview() { + const [saved, setSaved] = useState(""); + + return ( +
{ + event.preventDefault(); + setSaved(String(new FormData(event.currentTarget).get("accent"))); + }} onReset={() => setSaved("")}> + {/* No value prop is needed for an uncontrolled form field. Reset restores defaultValue. */} + +
+ + +
+

{saved ? `Saved ${saved}` : "Choose a color, then save it."}

+ + ); +} diff --git a/lib/component-dates.ts b/lib/component-dates.ts index d5c96fe..76b056f 100644 --- a/lib/component-dates.ts +++ b/lib/component-dates.ts @@ -9,6 +9,7 @@ export type ComponentDates = { }; const COMPONENT_DATES: Readonly> = { + "motion/color-picker": { publishedAt: "2026-10-28", updatedAt: "2026-10-28" }, "motion/button": { publishedAt: "2026-09-13", updatedAt: "2026-09-13" }, "motion/tabs": { publishedAt: "2026-09-13", updatedAt: "2026-09-13" }, "motion/select": { publishedAt: "2026-09-13", updatedAt: "2026-09-13" }, diff --git a/lib/registry.ts b/lib/registry.ts index 1bf6b5a..46cd61e 100644 --- a/lib/registry.ts +++ b/lib/registry.ts @@ -101,6 +101,35 @@ export const catalog: CategoryEntry[] = [ launchedAt: "2026-09-13", keywords: ["theme toggle", "dark mode toggle", "view transition"], }, + { + slug: "color-picker", + name: "Color Picker", + description: + "Opaque color picker with a draggable color field, native sliders, HEX input, and preset swatches. Supports controlled values and forms.", + file: "components/motion/color-picker.tsx", + usageFile: "components/previews/motion/color-picker/controlled.tsx", + badge: "new", + launchedAt: "2026-10-28", + keywords: ["react color picker", "hex color input", "color swatches", "accessible color picker"], + examples: [ + { + slug: "controlled", + name: "Controlled", + description: "Pass value and onValueChange to update a preview as the color changes. Use the color field with a pointer, or adjust Hue, Saturation and Brightness with arrow keys, Home and End. Only opaque #RGB and #RRGGBB colors are supported. HEX edits commit on Enter or blur, invalid edits revert, and Escape cancels an edit. Add disabled to disable every control, or pass swatches={[]} to hide presets. Repeated adjustments have no animation; preset presses respect reduced motion.", + file: "components/motion/color-picker.tsx", + previewKey: "motion/color-picker-controlled", + previewFile: "components/previews/motion/color-picker/controlled.tsx", + }, + { + slug: "form", + name: "Form", + description: "Use defaultValue and name for an uncontrolled form field. FormData receives a lowercase #RRGGBB value. Reset restores the default without calling onValueChange. Supply swatches to choose the presets; invalid colors and duplicates are ignored. Disabled pickers are excluded from form submission.", + file: "components/motion/color-picker.tsx", + previewKey: "motion/color-picker-form", + previewFile: "components/previews/motion/color-picker/form.tsx", + }, + ], + }, { slug: "range-slider", name: "Range Slider", From bd16885ff31b0701e33e39865dffe03a638a1447 Mon Sep 17 00:00:00 2001 From: Thomasgsn Date: Wed, 28 Oct 2026 18:47:41 +0100 Subject: [PATCH 2/2] fix(color-picker): keep only the live value preview --- components/motion/color-picker.tsx | 13 +++++++--- components/previews/index.tsx | 6 ----- .../previews/motion/color-picker.preview.tsx | 22 ++++++++-------- .../motion/color-picker/controlled.tsx | 20 --------------- .../previews/motion/color-picker/form.tsx | 25 ------------------- lib/registry.ts | 13 ++-------- 6 files changed, 21 insertions(+), 78 deletions(-) delete mode 100644 components/previews/motion/color-picker/controlled.tsx delete mode 100644 components/previews/motion/color-picker/form.tsx diff --git a/components/motion/color-picker.tsx b/components/motion/color-picker.tsx index 58814a9..9f59db1 100644 --- a/components/motion/color-picker.tsx +++ b/components/motion/color-picker.tsx @@ -89,12 +89,15 @@ export function ColorPicker({ const controlled = value === undefined ? null : normalize(value) ?? DEFAULT; const current = controlled !== null && controlled !== model.hex ? { hex: controlled, hsv: fromHex(controlled) } : model; - // Retain hue at zero saturation and black, where HEX cannot encode it. - if (current !== model) setModel(current); const { hex, hsv } = current; const [draft, setDraft] = useState(hex); const [pointerPress, setPointerPress] = useState(false); - useEffect(() => setDraft(hex), [hex]); + + // Retain hue at zero saturation and black, where HEX cannot encode it. + if (current !== model) { + setModel(current); + setDraft(hex); + } useEffect(() => { const form = inputRef.current?.form; @@ -114,12 +117,14 @@ export function ColorPicker({ if (disabled) return; const nextHex = toHex(next); setModel({ hex: nextHex, hsv: next }); + // Sync in the input event: a passive update on every drag can cascade. + setDraft(nextHex); if (nextHex !== hex) onValueChange?.(nextHex); }; const commit = () => { const next = normalize(draft); if (next && next !== hex) update(fromHex(next)); - setDraft(value === undefined ? next ?? hex : hex); + else setDraft(hex); }; const move = (event: PointerEvent) => { if (disabled) return; diff --git a/components/previews/index.tsx b/components/previews/index.tsx index a952ac8..0c3fbc3 100644 --- a/components/previews/index.tsx +++ b/components/previews/index.tsx @@ -7,12 +7,6 @@ export const previews: Record = { "motion/color-picker": dynamic(() => import("./motion/color-picker.preview").then((m) => m.ColorPickerPreview), ), - "motion/color-picker-controlled": dynamic(() => - import("./motion/color-picker/controlled").then((m) => m.ColorPickerControlledPreview), - ), - "motion/color-picker-form": dynamic(() => - import("./motion/color-picker/form").then((m) => m.ColorPickerFormPreview), - ), "motion/button": dynamic(() => import("./motion/button.preview").then((m) => m.ButtonPreview), ), diff --git a/components/previews/motion/color-picker.preview.tsx b/components/previews/motion/color-picker.preview.tsx index 1d1847a..d8b6f81 100644 --- a/components/previews/motion/color-picker.preview.tsx +++ b/components/previews/motion/color-picker.preview.tsx @@ -1,20 +1,18 @@ "use client"; -import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/motion/tabs"; -import { ColorPickerControlledPreview } from "./color-picker/controlled"; -import { ColorPickerFormPreview } from "./color-picker/form"; +import { useState } from "react"; +import { ColorPicker } from "@/components/motion/color-picker"; export function ColorPickerPreview() { + const [color, setColor] = useState("#6366f1"); + return ( - -
- - Controlled - Form - +
+
+ - - - + +
); } diff --git a/components/previews/motion/color-picker/controlled.tsx b/components/previews/motion/color-picker/controlled.tsx deleted file mode 100644 index ddfaf9b..0000000 --- a/components/previews/motion/color-picker/controlled.tsx +++ /dev/null @@ -1,20 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { ColorPicker } from "@/components/motion/color-picker"; - -export function ColorPickerControlledPreview() { - const [color, setColor] = useState("#6366f1"); - - return ( -
-
- - {color} -
- -
- ); -} diff --git a/components/previews/motion/color-picker/form.tsx b/components/previews/motion/color-picker/form.tsx deleted file mode 100644 index 0a4ad3c..0000000 --- a/components/previews/motion/color-picker/form.tsx +++ /dev/null @@ -1,25 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { ColorPicker } from "@/components/motion/color-picker"; -import { Button } from "@/components/motion/button"; - -export function ColorPickerFormPreview() { - const [saved, setSaved] = useState(""); - - return ( -
{ - event.preventDefault(); - setSaved(String(new FormData(event.currentTarget).get("accent"))); - }} onReset={() => setSaved("")}> - {/* No value prop is needed for an uncontrolled form field. Reset restores defaultValue. */} - -
- - -
-

{saved ? `Saved ${saved}` : "Choose a color, then save it."}

- - ); -} diff --git a/lib/registry.ts b/lib/registry.ts index 46cd61e..be94612 100644 --- a/lib/registry.ts +++ b/lib/registry.ts @@ -107,7 +107,6 @@ export const catalog: CategoryEntry[] = [ description: "Opaque color picker with a draggable color field, native sliders, HEX input, and preset swatches. Supports controlled values and forms.", file: "components/motion/color-picker.tsx", - usageFile: "components/previews/motion/color-picker/controlled.tsx", badge: "new", launchedAt: "2026-10-28", keywords: ["react color picker", "hex color input", "color swatches", "accessible color picker"], @@ -117,16 +116,8 @@ export const catalog: CategoryEntry[] = [ name: "Controlled", description: "Pass value and onValueChange to update a preview as the color changes. Use the color field with a pointer, or adjust Hue, Saturation and Brightness with arrow keys, Home and End. Only opaque #RGB and #RRGGBB colors are supported. HEX edits commit on Enter or blur, invalid edits revert, and Escape cancels an edit. Add disabled to disable every control, or pass swatches={[]} to hide presets. Repeated adjustments have no animation; preset presses respect reduced motion.", file: "components/motion/color-picker.tsx", - previewKey: "motion/color-picker-controlled", - previewFile: "components/previews/motion/color-picker/controlled.tsx", - }, - { - slug: "form", - name: "Form", - description: "Use defaultValue and name for an uncontrolled form field. FormData receives a lowercase #RRGGBB value. Reset restores the default without calling onValueChange. Supply swatches to choose the presets; invalid colors and duplicates are ignored. Disabled pickers are excluded from form submission.", - file: "components/motion/color-picker.tsx", - previewKey: "motion/color-picker-form", - previewFile: "components/previews/motion/color-picker/form.tsx", + previewKey: "motion/color-picker", + previewFile: "components/previews/motion/color-picker.preview.tsx", }, ], },