UIPackage React Native
Search
Menu

Color Picker

HSL colour picker with swatches, gradient-backed hue/saturation/lightness/opacity sliders, and a validated hex field. Hue survives achromatic colours.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add color-picker

Source files

Expand a file to read the source the installer copies into your app.

components/ui/color-picker/ColorPicker.tsx
import * as React from 'react'
import { Platform, Pressable, View, type ViewProps } from 'react-native'
import Svg, { Defs, LinearGradient, Rect, Stop } from 'react-native-svg'
import { Input } from '@/components/ui/input'
import { Slider } from '@/components/ui/slider'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'
import { hexToHsl, hslToHex, normalizeHex, type Hsla } from './color'

export type ColorSwatch = string | { value: string; label: string }

export interface ColorPickerLabels {
  hue: string
  saturation: string
  lightness: string
  alpha: string
  hex: string
  invalidHex: string
  /** Prefix for the preview's spoken value, e.g. "Current color #1E90FF". */
  current: string
}

export interface ColorPickerProps extends Omit<ViewProps, 'children'> {
  /** Controlled hex colour: `#RRGGBB`, or `#RRGGBBAA` when `alpha` is on. Any parseable hex is accepted. */
  value?: string
  defaultValue?: string
  /** Called with the uppercase hex on every change. A controlled owner may refuse it. */
  onValueChange?: (value: string) => void
  /** Called once a slider drag ends, a swatch is chosen, or a hex entry is committed. */
  onValueChangeComplete?: (value: string) => void
  swatches?: ColorSwatch[]
  /** Adds an opacity slider and emits `#RRGGBBAA`. */
  alpha?: boolean
  disabled?: boolean
  labels?: Partial<ColorPickerLabels>
  className?: string
}

const DEFAULT_LABELS: ColorPickerLabels = {
  hue: 'Hue',
  saturation: 'Saturation',
  lightness: 'Lightness',
  alpha: 'Opacity',
  hex: 'Hex color',
  invalidHex: 'Enter a hex color such as #1E90FF.',
  current: 'Current color',
}
const FALLBACK = '#000000'
// The slider announces percentages by default; hue reads in degrees instead.
const HUE_STEPS = Array.from({ length: 361 }, (_, i) => String(i))

interface GradientStop {
  offset: number
  color: string
  opacity?: number
}

/** Gradient drawn under a transparent native slider track. Android's SeekBar insets its track by 16dp. */
function Track({ id, stops }: { id: string; stops: GradientStop[] }) {
  return (
    <View
      pointerEvents="none"
      className={cn(
        'absolute top-[20px] h-[8px] overflow-hidden rounded-full',
        Platform.OS === 'android' ? 'inset-x-[16px]' : 'inset-x-0',
      )}
    >
      <Svg width="100%" height="100%">
        <Defs>
          <LinearGradient id={id} x1="0" y1="0" x2="1" y2="0">
            {stops.map((stop) => (
              <Stop key={stop.offset} offset={stop.offset} stopColor={stop.color} stopOpacity={stop.opacity ?? 1} />
            ))}
          </LinearGradient>
        </Defs>
        <Rect width="100%" height="100%" fill={`url(#${id})`} />
      </Svg>
    </View>
  )
}

export const ColorPicker = React.forwardRef<React.ComponentRef<typeof View>, ColorPickerProps>(
  (
    {
      value,
      defaultValue,
      onValueChange,
      onValueChangeComplete,
      swatches = [],
      alpha = false,
      disabled = false,
      labels: labelOverrides,
      className,
      ...props
    },
    ref,
  ) => {
    const labels = { ...DEFAULT_LABELS, ...labelOverrides }
    const gradientId = React.useId().replace(/[^a-zA-Z0-9]/g, '')
    const [internal, setInternal] = React.useState(defaultValue)
    const hex = normalizeHex(value ?? internal ?? FALLBACK, alpha) ?? normalizeHex(FALLBACK, alpha)!

    // HSL is the editing state; hex is the value. HSL is only re-derived when the hex it maps to
    // changes, so integer slider positions never round-trip through hex and drift.
    const [state, setState] = React.useState(() => ({ hex, hsl: hexToHsl(hex)! }))
    if (state.hex !== hex) setState({ hex, hsl: hexToHsl(hex, state.hsl)! })
    const { h, s, l, a } = state.hex === hex ? state.hsl : hexToHsl(hex, state.hsl)!

    const [draft, setDraft] = React.useState({ for: hex, text: hex, invalid: false })
    if (draft.for !== hex) setDraft({ for: hex, text: hex, invalid: false })

    function emit(next: string) {
      if (next === hex) return
      if (value === undefined) setInternal(next)
      onValueChange?.(next)
    }
    function setHsl(next: Hsla) {
      const nextHex = hslToHex(next, alpha)
      setState({ hex: nextHex, hsl: next })
      emit(nextHex)
    }

    function choose(next: string) {
      setState({ hex: next, hsl: hexToHsl(next, { h, s, l, a })! })
      emit(next)
      onValueChangeComplete?.(next)
    }
    function commitDraft() {
      const next = normalizeHex(draft.text, alpha)
      if (!next) return setDraft({ ...draft, invalid: true })
      if (next !== hex) choose(next)
      // An accepted value resyncs on the next render; a refused one shows the owner's value again.
      setDraft({ for: hex, text: hex, invalid: false })
    }

    const rows: {
      key: string
      label: string
      max: number
      current: number
      text: string
      set: (n: number) => Hsla
      stops: GradientStop[]
    }[] = [
      {
        key: 'hue',
        label: labels.hue,
        max: 360,
        current: h,
        text: `${Math.round(h)}°`,
        set: (n) => ({ h: n, s, l, a }),
        stops: [0, 60, 120, 180, 240, 300, 360].map((deg) => ({
          offset: deg / 360,
          color: hslToHex({ h: deg, s: 100, l: 50, a: 1 }),
        })),
      },
      {
        key: 'saturation',
        label: labels.saturation,
        max: 100,
        current: s,
        text: `${Math.round(s)}%`,
        set: (n) => ({ h, s: n, l, a }),
        stops: [0, 1].map((offset) => ({ offset, color: hslToHex({ h, s: offset * 100, l, a: 1 }) })),
      },
      {
        key: 'lightness',
        label: labels.lightness,
        max: 100,
        current: l,
        text: `${Math.round(l)}%`,
        set: (n) => ({ h, s, l: n, a }),
        stops: [0, 0.5, 1].map((offset) => ({ offset, color: hslToHex({ h, s, l: offset * 100, a: 1 }) })),
      },
    ]
    if (alpha)
      rows.push({
        key: 'alpha',
        label: labels.alpha,
        max: 100,
        current: a * 100,
        text: `${Math.round(a * 100)}%`,
        set: (n) => ({ h, s, l, a: n / 100 }),
        stops: [0, 1].map((offset) => ({ offset, color: hslToHex({ h, s, l, a: 1 }), opacity: offset })),
      })

    return (
      <View ref={ref} className={cn('gap-4', disabled && 'opacity-50', className)} {...props}>
        <View className="flex-row items-center gap-3">
          <View
            accessible
            accessibilityRole="image"
            accessibilityLabel={`${labels.current} ${hex}`}
            className="h-[48px] w-[48px] rounded-md border border-border"
            style={{ backgroundColor: hex }}
          />
          <View className="flex-1">
            <Input
              value={draft.text}
              onChangeText={(text) => setDraft({ for: hex, text, invalid: false })}
              onSubmitEditing={commitDraft}
              onBlur={commitDraft}
              invalid={draft.invalid}
              editable={!disabled}
              autoCapitalize="characters"
              autoCorrect={false}
              maxLength={9}
              returnKeyType="done"
              accessibilityLabel={labels.hex}
              accessibilityHint={draft.invalid ? labels.invalidHex : undefined}
            />
          </View>
        </View>
        {draft.invalid ? (
          <Text size="sm" className="text-destructive" accessibilityLiveRegion="polite">
            {labels.invalidHex}
          </Text>
        ) : null}

        {swatches.length ? (
          <View className="flex-row flex-wrap gap-1">
            {swatches.map((swatch, index) => {
              const raw = typeof swatch === 'string' ? swatch : swatch.value
              const swatchHex = normalizeHex(raw, alpha)
              if (!swatchHex) return null
              const selected = swatchHex === hex
              return (
                <Pressable
                  key={`${swatchHex}-${index}`}
                  disabled={disabled}
                  onPress={() => choose(swatchHex)}
                  accessibilityRole="button"
                  accessibilityLabel={typeof swatch === 'string' ? swatchHex : swatch.label}
                  accessibilityState={{ selected, disabled }}
                  className={cn(
                    'h-[48px] w-[48px] items-center justify-center rounded-full border-2',
                    selected ? 'border-ring' : 'border-transparent',
                  )}
                >
                  <View
                    className="h-[36px] w-[36px] rounded-full border border-border"
                    style={{ backgroundColor: swatchHex }}
                  />
                </Pressable>
              )
            })}
          </View>
        ) : null}

        {rows.map((row) => (
          <View key={row.key}>
            <View className="flex-row justify-between">
              <Text size="sm">{row.label}</Text>
              <Text size="sm" variant="muted">
                {row.text}
              </Text>
            </View>
            <View className="relative">
              <Track id={`${gradientId}${row.key}`} stops={row.stops} />
              <Slider
                minimumValue={0}
                maximumValue={row.max}
                step={1}
                value={row.current}
                disabled={disabled}
                minimumTrackTintColor="transparent"
                maximumTrackTintColor="transparent"
                onValueChange={(n) => {
                  if (!Number.isFinite(n)) return
                  setHsl(row.set(Math.min(row.max, Math.max(0, n))))
                }}
                onSlidingComplete={(n) => {
                  if (!Number.isFinite(n)) return
                  onValueChangeComplete?.(hslToHex(row.set(Math.min(row.max, Math.max(0, n))), alpha))
                }}
                accessibilityLabel={row.label}
                {...(row.key === 'hue' ? { accessibilityUnits: 'degrees', accessibilityIncrements: HUE_STEPS } : null)}
              />
            </View>
          </View>
        ))}
      </View>
    )
  },
)
ColorPicker.displayName = 'ColorPicker'
components/ui/color-picker/color.ts
/** Channels 0–255, alpha 0–1. */
export interface Rgba {
  r: number
  g: number
  b: number
  a: number
}
/** Hue 0–360, saturation and lightness 0–100, alpha 0–1. Kept as floats so hex → hsl → hex is lossless. */
export interface Hsla {
  h: number
  s: number
  l: number
  a: number
}

const HEX = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i

/** Parses `#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA` (leading `#` optional, any case). Anything else is `null`. */
export function parseHex(input: string): Rgba | null {
  const match = HEX.exec(input.trim())
  if (!match) return null
  let digits = match[1]
  if (digits.length <= 4) digits = [...digits].map((d) => d + d).join('')
  const byte = (i: number) => parseInt(digits.slice(i * 2, i * 2 + 2), 16)
  return { r: byte(0), g: byte(1), b: byte(2), a: digits.length === 8 ? byte(3) / 255 : 1 }
}

const clamp = (n: number, min: number, max: number, fallback = min) =>
  Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback

const pair = (n: number) =>
  Math.round(clamp(n, 0, 255))
    .toString(16)
    .padStart(2, '0')

/** Uppercase `#RRGGBB`, or `#RRGGBBAA` when `alpha` is true. */
export function formatHex({ r, g, b, a }: Rgba, alpha = false): string {
  return `#${pair(r)}${pair(g)}${pair(b)}${alpha ? pair(clamp(a, 0, 1, 1) * 255) : ''}`.toUpperCase()
}

/** Canonical form of any accepted hex, or `null` when it does not parse. */
export function normalizeHex(input: string, alpha = false): string | null {
  const rgba = parseHex(input)
  return rgba ? formatHex(rgba, alpha) : null
}

export function rgbToHsl({ r, g, b, a }: Rgba): Hsla {
  const [rn, gn, bn] = [clamp(r, 0, 255) / 255, clamp(g, 0, 255) / 255, clamp(b, 0, 255) / 255]
  const an = clamp(a, 0, 1, 1)
  const max = Math.max(rn, gn, bn)
  const min = Math.min(rn, gn, bn)
  const l = (max + min) / 2
  const d = max - min
  if (d === 0) return { h: 0, s: 0, l: l * 100, a: an }
  const s = d / (1 - Math.abs(2 * l - 1))
  let h = max === rn ? ((gn - bn) / d) % 6 : max === gn ? (bn - rn) / d + 2 : (rn - gn) / d + 4
  h *= 60
  if (h < 0) h += 360
  return { h, s: s * 100, l: l * 100, a: an }
}

export function hslToRgb({ h, s, l, a }: Hsla): Rgba {
  const hn = Number.isFinite(h) ? ((h % 360) + 360) % 360 : 0
  const sn = clamp(s, 0, 100) / 100
  const ln = clamp(l, 0, 100) / 100
  const an = clamp(a, 0, 1, 1)
  const k = (n: number) => (n + hn / 30) % 12
  const m = sn * Math.min(ln, 1 - ln)
  const f = (n: number) => ln - m * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))
  return { r: f(0) * 255, g: f(8) * 255, b: f(4) * 255, a: an }
}

export const hslToHex = (hsl: Hsla, alpha = false) => formatHex(hslToRgb(hsl), alpha)

/**
 * HSL for `hex`, keeping `previous` hue (and saturation at black/white) where the colour has none,
 * so dragging lightness to 0 and back, or saturation to 0 and back, returns to the same hue.
 */
export function hexToHsl(hex: string, previous?: Hsla): Hsla | null {
  const rgba = parseHex(hex)
  if (!rgba) return null
  const next = rgbToHsl(rgba)
  if (!previous) return next
  if (next.l === 0 || next.l === 100) return { ...next, h: previous.h, s: previous.s }
  if (next.s === 0) return { ...next, h: previous.h }
  return next
}
components/ui/color-picker/index.ts
export { ColorPicker, type ColorPickerLabels, type ColorPickerProps, type ColorSwatch } from './ColorPicker'
export * from './color'

Dependencies

Registry items

npm packages

  • react-native-svg
Browse controls and interactions