Ordo UI
组件Controls

ColorPicker

@mox-hub/ui 组件 · Controls · canonical

color-picker@mox-hub/uiControlscanonicalsrc/components/color-picker.tsx
变体演示color-picker

Props API

Prop类型默认值说明
value*string——
onValueChange*(color: string) => void——
swatches*readonly string[]DEFAULT_SWATCHES—
allowCustom*booleantrue—
closeOnSwatch*booleantrue—
placeholder*string——
disabled*boolean——
triggerClassName*string——
className*string——
popoverAlign*"center" | "start" | "end""start"—

源码

packages/ui/src/components/color-picker.tsx
"use client"

import * as React from "react"
import { HexColorPicker } from "react-colorful"
import { CheckIcon, ChevronDownIcon } from "lucide-react"

import { useMessages } from "../i18n"
import { cn } from "../lib/utils"
import { Button } from "./button"
import { Input } from "./input"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "./popover"

/*
 * Color Picker —— 照 coss DatePicker 组合范式自建(Popover + react-colorful + 预设色板),
 * 收敛原生 <input type="color">(系统色板)与各处手绘 swatch 网格。
 * `swatches` 缺省用 DEFAULT_SWATCHES;`allowCustom=false` 退化为纯预设选择(标签色等受约束场景)。
 */

/**
 * 项目预设色板(Tailwind 500 阶,原 core-config TAG_COLORS 收编为全局缺省)。
 * 16 色 = 8 列 × 2 整行(色相连续补 yellow-500,灰收尾);用户新增须保持 8 的倍数。
 * 用户自选色板:存库的用户数据色值,非 UI 语义色(宪法 §5 豁免,见 PRINCIPLES 附录登记)。
 */
export const DEFAULT_SWATCHES = [
  "#ef4444",
  "#f97316",
  "#f59e0b",
  "#eab308",
  "#84cc16",
  "#22c55e",
  "#14b8a6",
  "#06b6d4",
  "#3b82f6",
  "#6366f1",
  "#8b5cf6",
  "#a855f7",
  "#d946ef",
  "#ec4899",
  "#f43f5e",
  "#6b7280",
] as const

const HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i

/** 预设色亮度判定:浅色底用深色对勾,避免白对勾在黄/绿上低于 3:1。 */
function isLightSwatch(hex: string): boolean {
  const raw = hex.replace("#", "")
  const full =
    raw.length === 3
      ? raw
          .split("")
          .map((char) => char + char)
          .join("")
      : raw
  const [r, g, b] = [0, 2, 4].map((offset) => {
    const channel = Number.parseInt(full.slice(offset, offset + 2), 16) / 255
    return channel <= 0.04045
      ? channel / 12.92
      : Math.pow((channel + 0.055) / 1.055, 2.4)
  })
  // 0.3 是实测阈值:橙/黄/绿/青系(含 #f97316 0.32、#14b8a6 0.37)在 0.4 下
  // 会误判为深色而使用白对勾,白对橙仅 2.8:1;0.3 下这些色全部走深色对勾。
  return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.3
}

export interface ColorPickerProps {
  /** 受控色值(hex,#rgb 或 #rrggbb) */
  value?: string
  onValueChange?: (color: string) => void
  /** 预设色板,缺省 DEFAULT_SWATCHES;传空数组隐藏色板区 */
  swatches?: readonly string[]
  /** 是否提供色域/明度调节与 hex 输入,默认 true;false 时为纯预设选择 */
  allowCustom?: boolean
  /** 选择预设后关闭弹层,默认 true */
  closeOnSwatch?: boolean
  placeholder?: string
  disabled?: boolean
  /** 触发按钮宽度等覆写 */
  triggerClassName?: string
  /** 弹层内容区覆写 */
  className?: string
  popoverAlign?: "start" | "center" | "end"
}

export function ColorPicker({
  value,
  onValueChange,
  swatches = DEFAULT_SWATCHES,
  allowCustom = true,
  closeOnSwatch = true,
  placeholder,
  disabled,
  triggerClassName,
  className,
  popoverAlign = "start",
}: ColorPickerProps) {
  const M = useMessages()
  const resolvedPlaceholder = placeholder ?? M.colorPicker.placeholder
  const [open, setOpen] = React.useState(false)
  const [hexDraft, setHexDraft] = React.useState(value ?? "")

  React.useEffect(() => {
    setHexDraft(value ?? "")
  }, [value])

  const handleSwatch = (color: string) => {
    onValueChange?.(color.toLowerCase())
    if (closeOnSwatch) {
      setOpen(false)
    }
  }

  const commitHex = () => {
    const hex = hexDraft.trim()
    if (HEX_RE.test(hex)) {
      onValueChange?.(hex.toLowerCase())
    } else {
      setHexDraft(value ?? "")
    }
  }

  return (
    <Popover
      open={disabled ? false : open}
      onOpenChange={(next) => {
        if (!disabled) setOpen(next)
      }}
    >
      <PopoverTrigger
        render={
          <Button
            variant="outline"
            disabled={disabled}
            data-slot="color-picker-trigger"
            className={cn("w-36 justify-start px-3 font-normal", triggerClassName)}
          />
        }
      >
        {value ? (
          <span
            aria-hidden
            className="size-4 shrink-0 rounded-full ring-1 ring-foreground/15"
            style={{ backgroundColor: value }}
          />
        ) : null}
        <span className={cn("truncate", !value && "text-muted-foreground")}>
          {value || resolvedPlaceholder}
        </span>
        <ChevronDownIcon className="ms-auto size-4 shrink-0 text-muted-foreground" />
      </PopoverTrigger>
      <PopoverContent align={popoverAlign} sideOffset={4} className={cn("w-auto gap-3 p-3", className)}>
        {swatches.length > 0 ? (
          <div data-slot="color-picker-swatches" className="grid grid-cols-8 gap-1.5">
            {swatches.map((color) => {
              const selected = value?.toLowerCase() === color.toLowerCase()
              return (
                <button
                  key={color}
                  type="button"
                  data-slot="color-picker-swatch"
                  aria-label={color}
                  aria-pressed={selected}
                  disabled={disabled}
                  onClick={() => handleSwatch(color)}
                  className={cn(
                    "flex size-control-xs items-center justify-center rounded-full transition-[transform,box-shadow] duration-fast",
                    "hover:scale-110",
                    selected
                      ? "ring-2 ring-ring ring-offset-2 ring-offset-background"
                      : "ring-1 ring-foreground/10",
                    disabled && "pointer-events-none opacity-50",
                  )}
                  style={{ backgroundColor: color }}
                >
                  {selected ? (
                    <CheckIcon
                      className={cn(
                        "size-3.5 drop-shadow-sm",
                        isLightSwatch(color) ? "text-foreground" : "text-white",
                      )}
                    />
                  ) : null}
                </button>
              )
            })}
          </div>
        ) : null}
        {allowCustom ? (
          <>
            <div
              data-slot="color-picker-custom"
              aria-hidden={disabled}
              inert={disabled || undefined}
              className={cn(disabled && "pointer-events-none opacity-50")}
            >
              <HexColorPicker
                color={value ?? "#6b7280"}
                onChange={(color) => onValueChange?.(color)}
                // react-colorful 挂载时向 head 注入 .react-colorful{width:200px;height:200px},
                // 晚于 Tailwind 样式表且同特异性,宽高 Tailwind 类会被吞——几何必须内联钉住。
                // 234 = 8 列色板网格自然宽(8×24 + 7×6),弹层内色板/色域/色条三段同宽。
                style={{ width: 234, height: 200 }}
              />
            </div>
            <Input
              data-slot="color-picker-hex"
              value={hexDraft}
              onChange={(e) => setHexDraft(e.target.value)}
              onBlur={commitHex}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault()
                  commitHex()
                }
              }}
              placeholder="#5E6AD2"
              disabled={disabled}
              spellCheck={false}
              className="h-control-sm font-mono text-xs uppercase"
            />
          </>
        ) : null}
      </PopoverContent>
    </Popover>
  )
}

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

颜色选择器,支持预设与自定义 hex;输出为 #rrggbb(无 alpha 通道),受控用 value 与 onValueChange。