Theme
Version
GitHub PyPI Discord
On this page

Color Picker

CColorPicker combines a native color input with an enhanced spectrum, hue control, editable representation, and named swatches. Values are canonical lowercase #rrggbb strings.

Choose a brand color
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class ColorPickerAtAGlance(Component):
    template = '<c-CColorPicker label="Brand color" value="#7f56d9" />'


preview = ColorPickerAtAGlance()
preview  # noqa: B018

Switch representations

Set format to hex, rgb, or hsl. The format changes only the editable representation; the submitted and callback value remains canonical HEX.

Edit RGB and HSL colors
Show code
# ruff: noqa: E501 - embedded Citry templates remain readable as authored HTML

import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class ColorPickerFormats(Component):
    template = """<div class="color-format-grid"><c-CColorPicker label="RGB color" value="#12b76a" format="rgb" /><c-CColorPicker label="HSL color" value="#f79009" format="hsl" /></div>"""
    css = ":where(.color-format-grid){display:grid;grid-template-columns:repeat(auto-fit,minmax(15rem,1fr));gap:1rem}"


preview = ColorPickerFormats()
preview  # noqa: B018

Offer named swatches

Pass CColorSwatch records with validated color values and meaningful labels. Swatches are shortcuts, not a separate source of truth.

Choose from brand swatches
Show code
# ruff: noqa: ANN001, ANN201 - public snippets keep focus on component use

import citry_ui
from citry import Component, citry
from citry_ui import CColorSwatch

citry.register_library(citry_ui)


class ColorPickerSwatches(Component):
    def template_data(self, _kwargs, _slots):
        return {
            "swatches": [
                CColorSwatch("#7f56d9", "Violet"),
                CColorSwatch("#12b76a", "Green"),
                CColorSwatch("#f04438", "Red"),
                CColorSwatch("#f79009", "Orange"),
            ]
        }

    template = '<c-CColorPicker label="Accent" c-swatches="swatches" />'


preview = ColorPickerSwatches()
preview  # noqa: B018

Own value and popup state

Client value and open props are controlled. Change callbacks receive the requested value or state and details about the interaction.

Control the selected color
Show code
# ruff: noqa: E501 - Alpine expression remains readable in the public example

from citry import Component


class ControlledColorPicker(Component):
    template = """
      <section x-data="{color:'#7f56d9',open:false}">
        <c-CColorPicker label="Controlled accent" $c-props="{value:color,open,onValueChange:(next)=>color=next,onOpenChange:(next)=>open=next}" />
        <output x-text="color">#7f56d9</output>
      </section>
    """


preview = ControlledColorPicker()
preview  # noqa: B018

Submit with native forms

The native color input remains the successful form control. It also owns form reset behavior, so the no-script and enhanced paths agree.

Submit a profile color
Show code
# ruff: noqa: E501 - embedded Citry templates remain readable as authored HTML

import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class NativeColorForm(Component):
    template = """<form><c-CColorPicker label="Profile color" name="profile_color" value="#1570ef" /><button type="reset">Reset</button><button type="submit">Save</button></form>"""


preview = NativeColorForm()
preview  # noqa: B018

Keep the field understandable

Provide a concise visible field label and meaningful swatch labels. Readonly keeps the chosen value available while preventing color changes.

Present a readonly palette value
Show code
# ruff: noqa: ANN001, ANN201 - public snippets keep focus on component use

import citry_ui
from citry import Component, citry
from citry_ui import CColorSwatch

citry.register_library(citry_ui)


class AccessibleColorPicker(Component):
    def template_data(self, _kwargs, _slots):
        return {"swatches": [CColorSwatch("#005ea8", "Accessible blue"), CColorSwatch("#00703c", "Accessible green")]}

    template = '<c-CColorPicker label="Published theme color" value="#005ea8" c-swatches="swatches" readonly />'


preview = AccessibleColorPicker()
preview  # noqa: B018

Alpha, gradients, image sampling, EyeDropper permissions, and wide-gamut color spaces are outside this first solid-color contract.

API reference

Inputs

CColorPicker server inputs

Server inputs are passed in a template through <c-CColorPicker ... /> or in Python through CColorPicker(...).

InputTypeDefaultEffect
labelstrrequiredSupplies the visible field label.
valuestr"#7f56d9"Sets a '#rgb' or '#rrggbb' color normalized to lowercase six-digit HEX.
idstr | NonegeneratedSets the root ID and derived control IDs.
namestr | NoneNoneNames the native color form control.
formstr | NoneNoneAssociates the native input with an external form.
formatCColorPickerFormat (CColorPickerFormat)"hex"Chooses the editable HEX RGB or HSL representation.
swatchesSequence[CColorSwatch]"()"Adds unique named solid-color shortcuts.
openboolFalseSets initial popup visibility.
disabledboolFalseDisables focus mutation and form submission.
readonlyboolFalsePrevents color mutation while retaining the value.
sizeCColorPickerSize (CColorPickerSize)"md"Selects trigger height.
variantCColorPickerVariant (CColorPickerVariant)"outline"Selects outline soft or plain trigger styling.
open_labelstr"Open color picker"Overrides the catalog-backed trigger title.
area_labelstr"Saturation and brightness"Overrides the compound slider name.
hue_labelstr"Hue"Overrides the hue label.
format_labelstr"Color format"Overrides the format label.
value_labelstr"Color value"Overrides the text input label.
invalid_labelstr"Enter a valid color value"Overrides invalid edit announcements.
selected_labelstr containing '{color}'"Selected {color}"Overrides selection announcements.
class_CClassValue | None (CClassValue)NoneAdds root classes.
styleCStyleValue | None (CStyleValue)NoneAdds root styles.
attrsMapping[str, object] | NoneNoneAdds copied allowed root attributes.

CColorPicker client inputs

Client inputs are passed in the browser through the $c-props="{ ... }" attribute on <c-CColorPicker />.

InputTypeOmitted behaviorEffect
valuestringUses uncontrolled state.Controls the canonical HEX value.
openbooleanUses uncontrolled popup state.Controls popup visibility.
disabledbooleanUses the server value.Reactively disables the field.
readonlybooleanUses the server value.Reactively prevents mutation.
formatCColorPickerFormat (CColorPickerFormat)Uses the server value.Controls the editable representation.
onValueChangefunctionNo semantic callback runs.Receives valid color requests.
onOpenChangefunctionNo semantic callback runs.Receives popup visibility requests.

Slots

-

Events

Component events are callback inputs supplied through $c-props. Native browser events remain available through Alpine @... attributes.

CColorPicker events

EventSignatureTrigger and timingDetailControlled and cancellation behavior
onValueChange(value: string, detail: CColorPickerValueChangeDetail) => void (CColorPickerValueChangeDetail)A valid area hue text swatch native or reset request occurs.{value, previousValue, rgb, hsl, hsv, controlled, source, sourceEvent} (CColorPickerValueChangeDetail)Commits and dispatches native input and change only while uncontrolled.
onOpenChange(open: boolean, detail: CColorPickerOpenChangeDetail) => void (CColorPickerOpenChangeDetail)The popup requests a visibility change.{open, reason, sourceEvent} (CColorPickerOpenChangeDetail)Commits only while uncontrolled.

Methods

-

CSS

CSS variables to theme the components. Set them on an ancestor or the component itself.

CColorPicker CSS variables

Apply these variables to CColorPicker or one of its ancestors.

VariableTypePurposeDefault
--cui-color-picker-widthlengthTrigger and popup width.20rem
--cui-color-picker-area-heightlengthSaturation and brightness area height.12rem
--cui-color-picker-surfacecolorPopup and trigger surface.Canvas
--cui-color-picker-bordercomplete borderControl boundaries.Adaptive 1px neutral
--cui-color-picker-radiuslengthPopup radius.0.75rem
--cui-color-picker-shadowshadowPopup elevation.Adaptive shadow
--cui-color-picker-focuscolorFocus and selected-swatch indicator.Highlight

Attributes

HTML attributes defined on the components that you can refer to for CSS, inspection, and testing. Read-only.

CColorPicker attributes

AttributeElementTypeMeaning
data-openRootpresent | absentReflects popup visibility.
data-disabledRootpresent | absentReflects disabled state.
data-readonlyRootpresent | absentReflects readonly state.
data-formatRootCColorPickerFormat (CColorPickerFormat)Reflects the editable representation.
data-selectedSwatchpresent | absentMarks the current swatch.

Selectors

Selectors for the DOM nodes in the components that you can use for CSS, inspection, and testing.

CColorPicker selectors

SelectorElementPurpose
[data-citry-ui-part="color-picker"]RootState and root customization destination.
[data-citry-ui-part="native"]Native color inputProgressive fallback form and reset owner.
[data-citry-ui-part="trigger"]ButtonOpens the enhanced picker.
[data-citry-ui-part="popup"]DialogEnhanced control container.
[data-citry-ui-part="area"]Compound sliderChanges saturation and brightness.
[data-citry-ui-part="hue"]Label and rangeChanges hue.
[data-citry-ui-part="format"]SelectChooses editable representation.
[data-citry-ui-part="input"]Text inputCommits a parsed color.
[data-citry-ui-part="swatches"]ListGroups named shortcuts.
[data-citry-ui-part="swatch"]ButtonRequests a named color.
[data-citry-ui-part="status"]Polite statusAnnounces validation and selection.

Interfaces

Aliases and data shapes referenced above.

Input type aliases

InterfaceDefinition
CClassValuestr | Mapping[str, bool] | Sequence[CClassValue]
CStyleValuestr | Mapping[str, object] | Sequence[CStyleValue]
CColorPickerFormatLiteral["hex", "rgb", "hsl"]
CColorPickerSizeLiteral["sm", "md", "lg"]
CColorPickerVariantLiteral["outline", "soft", "plain"]
CColorPickerSourceLiteral["area", "hue", "text", "swatch", "native", "reset"]
CColorSwatchCColorSwatch(value: str, label: str)

CColorPickerValueChangeDetail

FieldTypeDefaultMeaning
valuestr-Requested canonical HEX value.
previousValuestr-Previous value.
rgbdict[str, int]-Requested integer RGB channels.
hsldict[str, float]-Requested HSL channels.
hsvdict[str, float]-Requested HSV channels.
controlledbool-Whether client value owns state.
sourceCColorPickerSource-Interaction source.
sourceEventobject-Native Event.

CColorPickerOpenChangeDetail

FieldTypeDefaultMeaning
openbool-Requested popup state.
reasonstr-Trigger outside escape or selection reason.
sourceEventobject-Native Event.

Translation keys

Catalog keys used by this family. An explicit component input or slot listed in Override takes precedence over the catalog for that instance.

CColorPicker translation keys

KeyPurposeVariablesOverrideBrowser updates
citry-ui-color-picker-openProvides the enhanced trigger title.noneopen_labelDeclarative $c-tr attribute binding.
citry-ui-color-picker-areaNames the compound saturation and brightness slider.nonearea_labelDeclarative $c-tr attribute binding.
citry-ui-color-picker-hueLabels the hue range.nonehue_labelDeclarative $c-tr text binding.
citry-ui-color-picker-formatLabels the format select.noneformat_labelDeclarative $c-tr text binding.
citry-ui-color-picker-valueLabels the editable value.nonevalue_labelDeclarative $c-tr text binding.
citry-ui-color-picker-invalidAnnounces an invalid text edit.noneinvalid_labelBrowser-created one-shot i18n.tr().
citry-ui-color-picker-selectedAnnounces an accepted color.color: strselected_label with {color}Browser-created one-shot i18n.tr().