use std::{cell::RefCell, rc::Rc};
use arc_motion::{is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, ClipboardItem, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce,
Rgba as GpuiRgba, Role, SharedString, Styled, TestSupportExt as _, Window,
base::{Button as BaseButton, StyledExt as _},
canvas, div, fill, point,
prelude::*,
px, size,
};
use crate::text::text_morph::TextMorph;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ColorFormat {
#[default]
Hex,
Rgb,
Hsl,
Oklch,
}
impl ColorFormat {
pub const ALL: [ColorFormat; 4] = [
ColorFormat::Hex,
ColorFormat::Rgb,
ColorFormat::Hsl,
ColorFormat::Oklch,
];
pub const fn label(self) -> &'static str {
match self {
Self::Hex => "Hex",
Self::Rgb => "RGB",
Self::Hsl => "HSL",
Self::Oklch => "OKLCH",
}
}
pub const fn next(self) -> Self {
match self {
Self::Hex => Self::Rgb,
Self::Rgb => Self::Hsl,
Self::Hsl => Self::Oklch,
Self::Oklch => Self::Hex,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ColorSwatch {
pub id: SharedString,
pub color: SharedString,
}
impl ColorSwatch {
pub fn new(id: impl Into<SharedString>, color: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
color: color.into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Hsva {
pub h: f32,
pub s: f32,
pub v: f32,
pub a: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RgbaColor {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContrastGrade {
Aaa,
Aa,
AaLarge,
Fails,
}
impl ContrastGrade {
pub const fn label(self) -> &'static str {
match self {
Self::Aaa => "AAA",
Self::Aa => "AA",
Self::AaLarge => "AA large",
Self::Fails => "Fails",
}
}
}
#[inline]
fn clamp01(v: f32) -> f32 {
v.clamp(0.0, 1.0)
}
#[inline]
fn round_digits(v: f32, digits: i32) -> f32 {
let f = 10_f32.powi(digits);
(v * f).round() / f
}
pub fn hsv_to_rgb(c: Hsva) -> RgbaColor {
let f = |n: f32| {
let k = (n + c.h / 60.0).rem_euclid(6.0);
c.v - c.v * c.s * k.min(4.0 - k).clamp(0.0, 1.0)
};
RgbaColor {
r: clamp01(f(5.0)),
g: clamp01(f(3.0)),
b: clamp01(f(1.0)),
a: clamp01(c.a),
}
}
pub fn rgb_to_hsv(c: RgbaColor, fallback_hue: f32) -> Hsva {
let max = c.r.max(c.g).max(c.b);
let min = c.r.min(c.g).min(c.b);
let d = max - min;
let mut h = fallback_hue;
if d > 1e-6 {
if (max - c.r).abs() < 1e-6 {
h = 60.0 * (((c.g - c.b) / d) % 6.0);
} else if (max - c.g).abs() < 1e-6 {
h = 60.0 * ((c.b - c.r) / d + 2.0);
} else {
h = 60.0 * ((c.r - c.g) / d + 4.0);
}
if h < 0.0 {
h += 360.0;
}
}
Hsva {
h: h.rem_euclid(360.0),
s: if max <= 1e-6 { 0.0 } else { d / max },
v: max,
a: clamp01(c.a),
}
}
pub fn hsl_to_rgb(h: f32, s: f32, l: f32, a: f32) -> RgbaColor {
let c = s * l.min(1.0 - l);
let f = |n: f32| {
let k = (n + h / 30.0).rem_euclid(12.0);
l - c * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
};
RgbaColor {
r: clamp01(f(0.0)),
g: clamp01(f(8.0)),
b: clamp01(f(4.0)),
a: clamp01(a),
}
}
pub fn rgb_to_hsl(c: RgbaColor, fallback_hue: f32) -> (f32, f32, f32) {
let max = c.r.max(c.g).max(c.b);
let min = c.r.min(c.g).min(c.b);
let l = (max + min) * 0.5;
let d = max - min;
let s = if d < 1e-6 {
0.0
} else {
d / (1.0 - (2.0 * l - 1.0).abs())
};
let h = if d < 1e-6 {
fallback_hue
} else {
rgb_to_hsv(c, fallback_hue).h
};
(h, clamp01(s), clamp01(l))
}
#[inline]
fn srgb_to_linear(c: f32) -> f32 {
if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
}
#[inline]
fn linear_to_srgb(c: f32) -> f32 {
if c <= 0.0031308 {
12.92 * c
} else {
1.055 * c.max(0.0).powf(1.0 / 2.4) - 0.055
}
}
pub fn rgb_to_oklch(c: RgbaColor, fallback_hue: f32) -> (f32, f32, f32) {
let lr = srgb_to_linear(c.r);
let lg = srgb_to_linear(c.g);
let lb = srgb_to_linear(c.b);
let l = (0.412_221_47 * lr + 0.536_332_55 * lg + 0.051_445_995 * lb).cbrt();
let m = (0.211_903_5 * lr + 0.680_699_5 * lg + 0.107_396_96 * lb).cbrt();
let s = (0.088_302_46 * lr + 0.281_718_85 * lg + 0.629_978_7 * lb).cbrt();
let big_l = 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s;
let a = 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s;
let b = 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s;
let chroma = a.hypot(b);
let mut hue = b.atan2(a).to_degrees();
if hue < 0.0 {
hue += 360.0;
}
(
clamp01(big_l),
chroma.max(0.0),
if chroma < 0.0005 { fallback_hue } else { hue },
)
}
pub fn oklch_to_rgb(big_l: f32, chroma: f32, hue_deg: f32, a: f32) -> RgbaColor {
let rad = hue_deg.to_radians();
let aa = chroma * rad.cos();
let bb = chroma * rad.sin();
let l = (big_l + 0.396_337_78 * aa + 0.215_803_76 * bb).powi(3);
let m = (big_l - 0.105_561_346 * aa - 0.063_854_17 * bb).powi(3);
let s = (big_l - 0.089_484_18 * aa - 1.291_485_5 * bb).powi(3);
RgbaColor {
r: clamp01(linear_to_srgb(
4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
)),
g: clamp01(linear_to_srgb(
-1.268_438 * l + 2.609_757_4 * m - 0.341_319_4 * s,
)),
b: clamp01(linear_to_srgb(
-0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
)),
a: clamp01(a),
}
}
#[inline]
fn channel_byte(c: f32) -> u8 {
(clamp01(c) * 255.0).round() as u8
}
pub fn color_to_hex(hsva: Hsva) -> String {
let rgb = hsv_to_rgb(hsva);
let r = channel_byte(rgb.r);
let g = channel_byte(rgb.g);
let b = channel_byte(rgb.b);
if rgb.a < 0.999 {
let a = channel_byte(rgb.a);
format!("#{r:02X}{g:02X}{b:02X}{a:02X}")
} else {
format!("#{r:02X}{g:02X}{b:02X}")
}
}
pub fn format_color(hsva: Hsva, kind: ColorFormat) -> String {
let rgb = hsv_to_rgb(hsva);
let alpha = if hsva.a < 0.999 {
format!(" / {}%", (hsva.a * 100.0).round() as i32)
} else {
String::new()
};
match kind {
ColorFormat::Hex => color_to_hex(hsva),
ColorFormat::Rgb => format!(
"rgb({} {} {}{alpha})",
channel_byte(rgb.r),
channel_byte(rgb.g),
channel_byte(rgb.b)
),
ColorFormat::Hsl => {
let (h, s, l) = rgb_to_hsl(rgb, hsva.h);
format!(
"hsl({} {}% {}%{alpha})",
(h.round() as i32).rem_euclid(360),
(s * 100.0).round() as i32,
(l * 100.0).round() as i32
)
}
ColorFormat::Oklch => {
let (l, c, h) = rgb_to_oklch(rgb, hsva.h);
let h_disp = round_digits(h, 1) % 360.0;
format!(
"oklch({:.1}% {:.3} {:.1}{alpha})",
round_digits(l * 100.0, 1),
round_digits(c, 3),
h_disp
)
}
}
}
fn parse_alpha_token(token: Option<&str>) -> Option<f32> {
let Some(raw) = token else {
return Some(1.0);
};
let s = raw.trim();
if let Some(pct) = s.strip_suffix('%') {
pct.parse::<f32>().ok().map(|v| clamp01(v / 100.0))
} else {
s.parse::<f32>().ok().map(clamp01)
}
}
fn split_func_args(inner: &str) -> (Vec<&str>, Option<&str>) {
if let Some((head, tail)) = inner.split_once('/') {
let parts: Vec<&str> = head
.split(|c: char| c.is_whitespace() || c == ',')
.filter(|t| !t.is_empty())
.collect();
(parts, Some(tail.trim()))
} else {
let parts: Vec<&str> = inner
.split(|c: char| c.is_whitespace() || c == ',')
.filter(|t| !t.is_empty())
.collect();
if parts.len() == 4 {
(parts[..3].to_vec(), Some(parts[3]))
} else {
(parts, None)
}
}
}
pub fn parse_color(input: &str, fallback_hue: f32) -> Option<Hsva> {
let text = input.trim().to_ascii_lowercase();
if text.is_empty() {
return None;
}
let hex_body = text.strip_prefix('#').unwrap_or(&text);
if matches!(hex_body.len(), 3 | 4 | 6 | 8) && hex_body.bytes().all(|b| b.is_ascii_hexdigit()) {
let expanded: String = if hex_body.len() <= 4 {
hex_body.chars().flat_map(|ch| [ch, ch]).collect()
} else {
hex_body.to_string()
};
let byte_at = |i: usize| {
u8::from_str_radix(&expanded[i..i + 2], 16)
.ok()
.map(|v| v as f32 / 255.0)
};
let r = byte_at(0)?;
let g = byte_at(2)?;
let b = byte_at(4)?;
let a = if expanded.len() == 8 {
byte_at(6)?
} else {
1.0
};
return Some(rgb_to_hsv(RgbaColor { r, g, b, a }, fallback_hue));
}
let (func, rest) = text.split_once('(')?;
let inner = rest.strip_suffix(')')?.trim();
let (parts, alpha_tok) = split_func_args(inner);
if parts.len() != 3 {
return None;
}
let a = parse_alpha_token(alpha_tok)?;
match func.trim() {
"rgb" | "rgba" => {
let r = clamp01(parts[0].parse::<f32>().ok()? / 255.0);
let g = clamp01(parts[1].parse::<f32>().ok()? / 255.0);
let b = clamp01(parts[2].parse::<f32>().ok()? / 255.0);
Some(rgb_to_hsv(RgbaColor { r, g, b, a }, fallback_hue))
}
"hsl" | "hsla" => {
let h = parts[0]
.strip_suffix("deg")
.unwrap_or(parts[0])
.parse::<f32>()
.ok()?
.rem_euclid(360.0);
let s = clamp01(
parts[1]
.strip_suffix('%')
.unwrap_or(parts[1])
.parse::<f32>()
.ok()?
/ 100.0,
);
let l = clamp01(
parts[2]
.strip_suffix('%')
.unwrap_or(parts[2])
.parse::<f32>()
.ok()?
/ 100.0,
);
let mut hsv = rgb_to_hsv(hsl_to_rgb(h, s, l, a), h);
hsv.h = h;
Some(hsv)
}
"oklch" => {
let l_raw = parts[0];
let l = if let Some(pct) = l_raw.strip_suffix('%') {
clamp01(pct.parse::<f32>().ok()? / 100.0)
} else {
clamp01(l_raw.parse::<f32>().ok()?)
};
let c = parts[1].parse::<f32>().ok()?.max(0.0);
let h = parts[2]
.strip_suffix("deg")
.unwrap_or(parts[2])
.parse::<f32>()
.ok()?
.rem_euclid(360.0);
Some(rgb_to_hsv(oklch_to_rgb(l, c, h, a), fallback_hue))
}
_ => None,
}
}
pub fn contrast_ratio(fg: Hsva, bg: RgbaColor) -> f32 {
let f = hsv_to_rgb(fg);
let mix = |c: f32, b: f32| c * f.a + b * (1.0 - f.a);
let lum = |r: f32, g: f32, b: f32| {
0.2126 * srgb_to_linear(r) + 0.7152 * srgb_to_linear(g) + 0.0722 * srgb_to_linear(b)
};
let la = lum(mix(f.r, bg.r), mix(f.g, bg.g), mix(f.b, bg.b));
let lb = lum(bg.r, bg.g, bg.b);
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}
pub const fn contrast_grade(ratio: f32) -> ContrastGrade {
if ratio >= 7.0 {
ContrastGrade::Aaa
} else if ratio >= 4.5 {
ContrastGrade::Aa
} else if ratio >= 3.0 {
ContrastGrade::AaLarge
} else {
ContrastGrade::Fails
}
}
pub fn rgba_to_hsla(c: RgbaColor) -> Hsla {
GpuiRgba {
r: clamp01(c.r),
g: clamp01(c.g),
b: clamp01(c.b),
a: clamp01(c.a),
}
.into()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ActiveDrag {
Area,
Hue,
Alpha,
}
#[derive(Clone)]
struct ColorPickerInternal {
hsva: Hsva,
synced_value: Option<SharedString>,
open: bool,
format: ColorFormat,
swatches: Vec<ColorSwatch>,
next_swatch_id: usize,
active_drag: Option<ActiveDrag>,
copied_until_ms: Option<f64>,
area_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
hue_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
alpha_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
area_focus: FocusHandle,
hue_focus: FocusHandle,
alpha_focus: FocusHandle,
}
impl ColorPickerInternal {
fn new(
initial_hsva: Hsva,
synced_value: Option<SharedString>,
open: bool,
format: ColorFormat,
swatches: Vec<ColorSwatch>,
cx: &mut App,
) -> Self {
Self {
hsva: initial_hsva,
synced_value,
open,
format,
next_swatch_id: swatches.len() + 1,
swatches,
active_drag: None,
copied_until_ms: None,
area_bounds: Rc::new(RefCell::new(None)),
hue_bounds: Rc::new(RefCell::new(None)),
alpha_bounds: Rc::new(RefCell::new(None)),
area_focus: cx.focus_handle(),
hue_focus: cx.focus_handle(),
alpha_focus: cx.focus_handle(),
}
}
}
#[derive(IntoElement)]
pub struct ColorPicker {
id: ElementId,
label: SharedString,
value: Option<SharedString>,
default_value: SharedString,
background: SharedString,
default_format: ColorFormat,
default_open: bool,
swatches: Vec<ColorSwatch>,
max_swatches: usize,
disabled: bool,
#[allow(clippy::type_complexity)]
on_value_change: Option<Rc<dyn Fn(&SharedString, &mut Window, &mut App)>>,
#[allow(clippy::type_complexity)]
on_swatches_change: Option<Rc<dyn Fn(&[ColorSwatch], &mut Window, &mut App)>>,
}
impl ColorPicker {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
label: "Color".into(),
value: None,
default_value: "#2F6BFF".into(),
background: "#FFFFFF".into(),
default_format: ColorFormat::Hex,
default_open: false,
swatches: Vec::new(),
max_swatches: 7,
disabled: false,
on_value_change: None,
on_swatches_change: None,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_value = value.into();
self
}
pub fn background(mut self, background: impl Into<SharedString>) -> Self {
self.background = background.into();
self
}
pub fn default_format(mut self, format: ColorFormat) -> Self {
self.default_format = format;
self
}
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
}
pub fn swatches(mut self, swatches: Vec<ColorSwatch>) -> Self {
self.swatches = swatches;
self
}
pub fn max_swatches(mut self, max: usize) -> Self {
self.max_swatches = max.max(1);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
pub fn on_swatches_change(
mut self,
handler: impl Fn(&[ColorSwatch], &mut Window, &mut App) + 'static,
) -> Self {
self.on_swatches_change = Some(Rc::new(handler));
self
}
}
fn frac_in_bounds(bounds: Bounds<Pixels>, pos: gpui_kit::Point<Pixels>) -> (f32, f32) {
let w = f32::from(bounds.size.width).max(1.0);
let h = f32::from(bounds.size.height).max(1.0);
let fx = ((f32::from(pos.x) - f32::from(bounds.origin.x)) / w).clamp(0.0, 1.0);
let fy = ((f32::from(pos.y) - f32::from(bounds.origin.y)) / h).clamp(0.0, 1.0);
(fx, fy)
}
fn paint_checkerboard(bounds: Bounds<Pixels>, is_dark: bool, window: &mut Window) {
let cell = 5.0_f32;
let c0 = if is_dark {
rgba_to_hsla(RgbaColor {
r: 0.30,
g: 0.30,
b: 0.32,
a: 1.0,
})
} else {
rgba_to_hsla(RgbaColor {
r: 0.88,
g: 0.88,
b: 0.90,
a: 1.0,
})
};
let c1 = if is_dark {
rgba_to_hsla(RgbaColor {
r: 0.22,
g: 0.22,
b: 0.24,
a: 1.0,
})
} else {
rgba_to_hsla(RgbaColor {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
})
};
let w = f32::from(bounds.size.width);
let h = f32::from(bounds.size.height);
let cols = (w / cell).ceil() as usize;
let rows = (h / cell).ceil() as usize;
for r in 0..rows {
for c in 0..cols {
let x = f32::from(bounds.origin.x) + c as f32 * cell;
let y = f32::from(bounds.origin.y) + r as f32 * cell;
let cw = cell.min(f32::from(bounds.origin.x) + w - x).max(0.0);
let ch = cell.min(f32::from(bounds.origin.y) + h - y).max(0.0);
if cw > 0.0 && ch > 0.0 {
let color = if (r + c) % 2 == 0 { c0 } else { c1 };
window.paint_quad(fill(
Bounds {
origin: point(px(x), px(y)),
size: size(px(cw), px(ch)),
},
color,
));
}
}
}
}
impl RenderOnce for ColorPicker {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let is_dark = theme.mode.is_dark();
let now_ms = motion_now(cx) * 1000.0;
let _reduced = is_reduced_motion(cx);
let initial_str = self.value.as_deref().unwrap_or(self.default_value.as_ref());
let initial_hsva = parse_color(initial_str, 220.0).unwrap_or(Hsva {
h: 220.0,
s: 0.8,
v: 1.0,
a: 1.0,
});
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-color-picker-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
ColorPickerInternal::new(
initial_hsva,
self.value.clone(),
self.default_open,
self.default_format,
self.swatches.clone(),
cx,
)
});
let mut needs_frame = false;
let controlled = self.value.clone();
internal.update(cx, |s, _| {
if let Some(ref val) = controlled
&& s.synced_value.as_ref() != Some(val)
{
s.synced_value = Some(val.clone());
if val.to_ascii_uppercase() != color_to_hex(s.hsva)
&& let Some(next) = parse_color(val.as_ref(), s.hsva.h)
{
s.hsva = next;
}
}
if let Some(until) = s.copied_until_ms {
if now_ms >= until {
s.copied_until_ms = None;
} else {
needs_frame = true;
}
}
});
if needs_frame {
window.request_animation_frame();
}
let snap = internal.read(cx).clone();
let hsva = snap.hsva;
let open = snap.open;
let format = snap.format;
let swatches = snap.swatches.clone();
let copied = snap.copied_until_ms.is_some();
let hex = SharedString::from(color_to_hex(hsva));
let formatted = SharedString::from(format_color(hsva, format));
let current_rgba = hsv_to_rgb(hsva);
let current_hsla = rgba_to_hsla(current_rgba);
let opaque_hsla = rgba_to_hsla(RgbaColor {
a: 1.0,
..current_rgba
});
let pure_hsla = rgba_to_hsla(hsv_to_rgb(Hsva {
h: hsva.h,
s: 1.0,
v: 1.0,
a: 1.0,
}));
let bg_rgba = parse_color(self.background.as_ref(), 0.0)
.map(hsv_to_rgb)
.unwrap_or(RgbaColor {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
});
let bg_hsla = rgba_to_hsla(bg_rgba);
let ratio = contrast_ratio(hsva, bg_rgba);
let grade = contrast_grade(ratio);
let grade_bg = match grade {
ContrastGrade::Aaa | ContrastGrade::Aa => {
oklab_mix(colors.success, colors.surface, 0.16)
}
ContrastGrade::AaLarge => oklab_mix(colors.warning, colors.surface, 0.18),
ContrastGrade::Fails => oklab_mix(colors.danger, colors.surface, 0.16),
};
let grade_fg = match grade {
ContrastGrade::Aaa | ContrastGrade::Aa => colors.success,
ContrastGrade::AaLarge => colors.warning,
ContrastGrade::Fails => colors.danger,
};
let render_chip = |chip_color: Hsla, px_size: f32| {
div()
.relative()
.w(px(px_size))
.h(px(px_size))
.flex_none()
.rounded_full()
.border_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.child(div().size_full().rounded_full().bg(chip_color))
};
let st_toggle = internal.clone();
let disabled = self.disabled;
let trigger = BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"trigger".into(),
))
.accessibility_label(SharedString::from(format!("{} {}", self.label, hex)))
.disabled(disabled)
.on_click(move |_, window, cx| {
st_toggle.update(cx, |s, _| {
s.open = !s.open;
});
window.refresh();
})
.h(ControlHeights::MD)
.pl(px(6.0))
.pr(px(12.0))
.flex()
.items_center()
.gap(px(10.0))
.rounded_full()
.border_1()
.border_color(if open {
colors.control_fill
} else {
colors.border
})
.bg(colors.surface)
.when(!disabled, |b| b.cursor_pointer())
.child(render_chip(current_hsla, 32.0))
.child(
div()
.flex()
.flex_col()
.items_start()
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(self.label.clone()),
)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(hex.clone()),
),
);
let panel = if open {
let commit_helper = {
let cb = self.on_value_change.clone();
move |next: Hsva,
state: &gpui_kit::Entity<ColorPickerInternal>,
window: &mut Window,
cx: &mut App| {
let prev_hex = color_to_hex(state.read(cx).hsva);
let next_hex = SharedString::from(color_to_hex(next));
state.update(cx, |s, _| {
s.hsva = next;
});
if next_hex.as_ref() != prev_hex
&& let Some(ref handler) = cb
{
handler(&next_hex, window, cx);
}
window.refresh();
}
};
let area_bounds_cell = snap.area_bounds.clone();
let area_h = hsva.h;
let area_canvas = canvas(
move |bounds, _, _| {
*area_bounds_cell.borrow_mut() = Some(bounds);
bounds
},
move |bounds, _, window, _| {
let cols = 28usize;
let rows = 18usize;
let w = f32::from(bounds.size.width);
let h = f32::from(bounds.size.height);
let cw = w / cols as f32;
let ch = h / rows as f32;
for r in 0..rows {
let v = 1.0 - (r as f32 + 0.5) / rows as f32;
for c in 0..cols {
let s = (c as f32 + 0.5) / cols as f32;
let col = rgba_to_hsla(hsv_to_rgb(Hsva {
h: area_h,
s,
v,
a: 1.0,
}));
window.paint_quad(fill(
Bounds {
origin: point(
px(f32::from(bounds.origin.x) + c as f32 * cw),
px(f32::from(bounds.origin.y) + r as f32 * ch),
),
size: size(px(cw + 0.75), px(ch + 0.75)),
},
col,
));
}
}
},
)
.size_full();
let st_area_down = internal.clone();
let st_area_move = internal.clone();
let st_area_up = internal.clone();
let st_area_key = internal.clone();
let area_focus = snap.area_focus.clone();
let commit_area_down = commit_helper.clone();
let commit_area_move = commit_helper.clone();
let commit_area_key = commit_helper.clone();
let thumb_x_px = (hsva.s * 276.0).clamp(0.0, 276.0);
let thumb_y_px = ((1.0 - hsva.v) * 164.0).clamp(0.0, 164.0);
let area = div()
.id(ElementId::NamedChild(self.id.clone().into(), "area".into()))
.test_support()
.track_focus(&area_focus)
.role(Role::Slider)
.aria_label("Saturation and brightness")
.relative()
.w(px(276.0))
.h(px(164.0))
.overflow_hidden()
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.cursor_crosshair()
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
let b = *st_area_down.read(cx).area_bounds.borrow();
if let Some(bounds) = b {
let (fx, fy) = frac_in_bounds(bounds, event.position);
let cur = st_area_down.read(cx).hsva;
st_area_down.update(cx, |s, _| s.active_drag = Some(ActiveDrag::Area));
area_focus.focus(window, cx);
commit_area_down(
Hsva {
s: fx,
v: 1.0 - fy,
..cur
},
&st_area_down,
window,
cx,
);
}
},
)
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
if st_area_move.read(cx).active_drag != Some(ActiveDrag::Area) {
return;
}
let b = *st_area_move.read(cx).area_bounds.borrow();
if let Some(bounds) = b {
let (fx, fy) = frac_in_bounds(bounds, event.position);
let cur = st_area_move.read(cx).hsva;
commit_area_move(
Hsva {
s: fx,
v: 1.0 - fy,
..cur
},
&st_area_move,
window,
cx,
);
}
})
.on_mouse_up(MouseButton::Left, move |_: &MouseUpEvent, window, cx| {
st_area_up.update(cx, |s, _| {
if s.active_drag == Some(ActiveDrag::Area) {
s.active_drag = None;
}
});
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
let step = if event.keystroke.modifiers.shift {
0.10
} else {
0.01
};
let cur = st_area_key.read(cx).hsva;
let next = match event.keystroke.key.as_str() {
"right" => Some(Hsva {
s: clamp01(cur.s + step),
..cur
}),
"left" => Some(Hsva {
s: clamp01(cur.s - step),
..cur
}),
"up" => Some(Hsva {
v: clamp01(cur.v + step),
..cur
}),
"down" => Some(Hsva {
v: clamp01(cur.v - step),
..cur
}),
"escape" => {
st_area_key.update(cx, |s, _| s.open = false);
window.refresh();
None
}
_ => None,
};
if let Some(n) = next {
commit_area_key(n, &st_area_key, window, cx);
}
})
.child(area_canvas)
.child(
div()
.absolute()
.left(px(thumb_x_px - 9.0))
.top(px(thumb_y_px - 9.0))
.w(px(18.0))
.h(px(18.0))
.rounded_full()
.border_2()
.border_color(rgba_to_hsla(RgbaColor {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
}))
.bg(opaque_hsla),
);
let hue_bounds_cell = snap.hue_bounds.clone();
let hue_canvas = canvas(
move |bounds, _, _| {
*hue_bounds_cell.borrow_mut() = Some(bounds);
bounds
},
move |bounds, _, window, _| {
let steps = 48usize;
let w = f32::from(bounds.size.width);
let cw = w / steps as f32;
for i in 0..steps {
let hue = (i as f32 + 0.5) / steps as f32 * 360.0;
let col = rgba_to_hsla(hsv_to_rgb(Hsva {
h: hue,
s: 1.0,
v: 1.0,
a: 1.0,
}));
window.paint_quad(fill(
Bounds {
origin: point(
px(f32::from(bounds.origin.x) + i as f32 * cw),
bounds.origin.y,
),
size: size(px(cw + 0.75), bounds.size.height),
},
col,
));
}
},
)
.size_full();
let st_hue_down = internal.clone();
let st_hue_move = internal.clone();
let st_hue_up = internal.clone();
let st_hue_key = internal.clone();
let hue_focus = snap.hue_focus.clone();
let commit_hue_down = commit_helper.clone();
let commit_hue_move = commit_helper.clone();
let commit_hue_key = commit_helper.clone();
let hue_thumb_x = (hsva.h / 360.0 * 276.0).clamp(9.0, 267.0);
let hue_slider = div()
.id(ElementId::NamedChild(self.id.clone().into(), "hue".into()))
.test_support()
.track_focus(&hue_focus)
.role(Role::Slider)
.aria_label("Hue")
.relative()
.w(px(276.0))
.h(px(16.0))
.rounded_full()
.cursor_pointer()
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
let b = *st_hue_down.read(cx).hue_bounds.borrow();
if let Some(bounds) = b {
let (fx, _) = frac_in_bounds(bounds, event.position);
let cur = st_hue_down.read(cx).hsva;
st_hue_down.update(cx, |s, _| s.active_drag = Some(ActiveDrag::Hue));
hue_focus.focus(window, cx);
commit_hue_down(
Hsva {
h: (fx * 359.9).clamp(0.0, 359.9),
..cur
},
&st_hue_down,
window,
cx,
);
}
},
)
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
if st_hue_move.read(cx).active_drag != Some(ActiveDrag::Hue) {
return;
}
let b = *st_hue_move.read(cx).hue_bounds.borrow();
if let Some(bounds) = b {
let (fx, _) = frac_in_bounds(bounds, event.position);
let cur = st_hue_move.read(cx).hsva;
commit_hue_move(
Hsva {
h: (fx * 359.9).clamp(0.0, 359.9),
..cur
},
&st_hue_move,
window,
cx,
);
}
})
.on_mouse_up(MouseButton::Left, move |_: &MouseUpEvent, window, cx| {
st_hue_up.update(cx, |s, _| {
if s.active_drag == Some(ActiveDrag::Hue) {
s.active_drag = None;
}
});
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
let step = if event.keystroke.modifiers.shift {
10.0
} else {
1.0
};
let cur = st_hue_key.read(cx).hsva;
let next_h = match event.keystroke.key.as_str() {
"right" | "up" => Some((cur.h + step).clamp(0.0, 359.9)),
"left" | "down" => Some((cur.h - step).clamp(0.0, 359.9)),
"home" => Some(0.0),
"end" => Some(359.9),
_ => None,
};
if let Some(h) = next_h {
commit_hue_key(Hsva { h, ..cur }, &st_hue_key, window, cx);
}
})
.child(
div()
.size_full()
.overflow_hidden()
.rounded_full()
.border_1()
.border_color(colors.border)
.child(hue_canvas),
)
.child(
div()
.absolute()
.left(px(hue_thumb_x - 9.0))
.top(px(-1.0))
.w(px(18.0))
.h(px(18.0))
.rounded_full()
.border_2()
.border_color(rgba_to_hsla(RgbaColor {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
}))
.bg(pure_hsla),
);
let alpha_bounds_cell = snap.alpha_bounds.clone();
let alpha_canvas = canvas(
move |bounds, _, _| {
*alpha_bounds_cell.borrow_mut() = Some(bounds);
bounds
},
move |bounds, _, window, _| {
paint_checkerboard(bounds, is_dark, window);
let steps = 32usize;
let w = f32::from(bounds.size.width);
let cw = w / steps as f32;
for i in 0..steps {
let a = (i as f32 + 0.5) / steps as f32;
let col = rgba_to_hsla(RgbaColor { a, ..current_rgba });
window.paint_quad(fill(
Bounds {
origin: point(
px(f32::from(bounds.origin.x) + i as f32 * cw),
bounds.origin.y,
),
size: size(px(cw + 0.75), bounds.size.height),
},
col,
));
}
},
)
.size_full();
let st_alpha_down = internal.clone();
let st_alpha_move = internal.clone();
let st_alpha_up = internal.clone();
let st_alpha_key = internal.clone();
let alpha_focus = snap.alpha_focus.clone();
let commit_alpha_down = commit_helper.clone();
let commit_alpha_move = commit_helper.clone();
let commit_alpha_key = commit_helper.clone();
let alpha_thumb_x = (hsva.a * 276.0).clamp(9.0, 267.0);
let alpha_slider = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"alpha".into(),
))
.test_support()
.track_focus(&alpha_focus)
.role(Role::Slider)
.aria_label("Opacity")
.relative()
.w(px(276.0))
.h(px(16.0))
.rounded_full()
.cursor_pointer()
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
let b = *st_alpha_down.read(cx).alpha_bounds.borrow();
if let Some(bounds) = b {
let (fx, _) = frac_in_bounds(bounds, event.position);
let cur = st_alpha_down.read(cx).hsva;
st_alpha_down
.update(cx, |s, _| s.active_drag = Some(ActiveDrag::Alpha));
alpha_focus.focus(window, cx);
commit_alpha_down(Hsva { a: fx, ..cur }, &st_alpha_down, window, cx);
}
},
)
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
if st_alpha_move.read(cx).active_drag != Some(ActiveDrag::Alpha) {
return;
}
let b = *st_alpha_move.read(cx).alpha_bounds.borrow();
if let Some(bounds) = b {
let (fx, _) = frac_in_bounds(bounds, event.position);
let cur = st_alpha_move.read(cx).hsva;
commit_alpha_move(Hsva { a: fx, ..cur }, &st_alpha_move, window, cx);
}
})
.on_mouse_up(MouseButton::Left, move |_: &MouseUpEvent, window, cx| {
st_alpha_up.update(cx, |s, _| {
if s.active_drag == Some(ActiveDrag::Alpha) {
s.active_drag = None;
}
});
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
let step = if event.keystroke.modifiers.shift {
0.10
} else {
0.01
};
let cur = st_alpha_key.read(cx).hsva;
let next_a = match event.keystroke.key.as_str() {
"right" | "up" => Some(clamp01(cur.a + step)),
"left" | "down" => Some(clamp01(cur.a - step)),
"home" => Some(0.0),
"end" => Some(1.0),
_ => None,
};
if let Some(a) = next_a {
commit_alpha_key(Hsva { a, ..cur }, &st_alpha_key, window, cx);
}
})
.child(
div()
.size_full()
.overflow_hidden()
.rounded_full()
.border_1()
.border_color(colors.border)
.child(alpha_canvas),
)
.child(
div()
.absolute()
.left(px(alpha_thumb_x - 9.0))
.top(px(-1.0))
.w(px(18.0))
.h(px(18.0))
.rounded_full()
.border_2()
.border_color(rgba_to_hsla(RgbaColor {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
}))
.bg(current_hsla),
);
let st_fmt = internal.clone();
let st_copy = internal.clone();
let formatted_for_copy = formatted.clone();
let format_row =
div()
.w_full()
.h(px(38.0))
.flex()
.items_center()
.overflow_hidden()
.rounded(px(6.0))
.border_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"format".into(),
))
.accessibility_label(SharedString::from(format!(
"Format: {}. Switch format",
format.label()
)))
.on_click(move |_, window, cx| {
st_fmt.update(cx, |s, _| {
s.format = s.format.next();
});
window.refresh();
})
.h_full()
.min_w(px(58.0))
.px(px(10.0))
.flex()
.items_center()
.justify_center()
.border_r_1()
.border_color(colors.border)
.cursor_pointer()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.foreground)
.child(TextMorph::new(
ElementId::NamedChild(self.id.clone().into(), "fmt-label".into()),
format.label(),
)),
)
.child(
div()
.flex_1()
.min_w_0()
.h_full()
.px(px(10.0))
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(colors.foreground)
.child(TextMorph::new(
ElementId::NamedChild(self.id.clone().into(), "fmt-val".into()),
formatted.clone(),
)),
)
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"copy-color".into(),
))
.accessibility_label("Copy color value")
.on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(
formatted_for_copy.to_string(),
));
let until = motion_now(cx) * 1000.0 + 1600.0;
st_copy.update(cx, |s, _| s.copied_until_ms = Some(until));
window.refresh();
})
.h_full()
.px(px(10.0))
.flex()
.items_center()
.border_l_1()
.border_color(colors.border)
.cursor_pointer()
.text_size(Typography::TEXT_XS)
.text_color(if copied {
colors.success
} else {
colors.text_secondary
})
.child(SharedString::from(if copied { "Copied" } else { "Copy" })),
);
let contrast_row = div()
.w_full()
.flex()
.items_center()
.gap(px(10.0))
.child(
div()
.w(px(36.0))
.h(px(28.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(px(9.0))
.border_1()
.border_color(colors.border)
.bg(bg_hsla)
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(current_hsla)
.child("Aa"),
)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(SharedString::from(format!("{ratio:.2}:1"))),
)
.child(
div()
.flex_1()
.min_w_0()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.truncate()
.child("against background"),
)
.child(
div()
.h(px(22.0))
.px(px(8.0))
.flex()
.items_center()
.rounded_full()
.bg(grade_bg)
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(grade_fg)
.child(SharedString::from(grade.label())),
);
let st_save = internal.clone();
let cb_sw_save = self.on_swatches_change.clone();
let max_sw = self.max_swatches;
let hex_for_save = hex.clone();
let swatch_buttons = swatches.iter().enumerate().map(|(idx, entry)| {
let is_current = entry.color.to_ascii_uppercase() == hex.as_ref();
let parsed = parse_color(entry.color.as_ref(), hsva.h)
.map(|c| rgba_to_hsla(hsv_to_rgb(c)))
.unwrap_or(current_hsla);
let st_apply = internal.clone();
let st_key = internal.clone();
let cb_sw_key = self.on_swatches_change.clone();
let commit_sw = commit_helper.clone();
let entry_color = entry.color.clone();
let entry_id = entry.id.clone();
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("swatch-{}", entry.id)),
))
.accessibility_label(SharedString::from(format!(
"{}. Delete to remove",
entry.color
)))
.on_click(move |_, window, cx| {
let cur_h = st_apply.read(cx).hsva.h;
if let Some(next) = parse_color(entry_color.as_ref(), cur_h) {
commit_sw(next, &st_apply, window, cx);
}
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
let key = event.keystroke.key.as_str();
let alt = event.keystroke.modifiers.alt;
let mut updated: Option<Vec<ColorSwatch>> = None;
st_key.update(cx, |s, _| {
if key == "delete" || key == "backspace" {
s.swatches.retain(|item| item.id != entry_id);
updated = Some(s.swatches.clone());
} else if alt && (key == "left" || key == "right") {
let to = if key == "left" {
idx.saturating_sub(1)
} else {
(idx + 1).min(s.swatches.len().saturating_sub(1))
};
if to != idx && idx < s.swatches.len() {
let item = s.swatches.remove(idx);
s.swatches.insert(to, item);
updated = Some(s.swatches.clone());
}
}
});
if let Some(list) = updated {
if let Some(ref handler) = cb_sw_key {
handler(&list, window, cx);
}
window.refresh();
}
})
.w(px(28.0))
.h(px(28.0))
.flex()
.items_center()
.justify_center()
.rounded_full()
.border_2()
.border_color(if is_current {
colors.foreground
} else {
Hsla::transparent_black()
})
.cursor_pointer()
.child(render_chip(parsed, if is_current { 20.0 } else { 24.0 }))
});
let swatches_row = div()
.w_full()
.flex()
.items_center()
.gap(px(6.0))
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"save-swatch".into(),
))
.accessibility_label(SharedString::from(format!("Save {hex_for_save}")))
.on_click(move |_, window, cx| {
let mut updated = Vec::new();
st_save.update(cx, |s, _| {
let id = SharedString::from(format!("swatch-{}", s.next_swatch_id));
s.next_swatch_id += 1;
s.swatches
.insert(0, ColorSwatch::new(id, color_to_hex(s.hsva)));
s.swatches.truncate(max_sw);
updated = s.swatches.clone();
});
if let Some(ref handler) = cb_sw_save {
handler(&updated, window, cx);
}
window.refresh();
})
.w(px(28.0))
.h(px(28.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded_full()
.border_1()
.border_color(colors.border)
.cursor_pointer()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child("+"),
)
.child(
div()
.flex_1()
.flex()
.flex_wrap()
.items_center()
.gap(px(4.0))
.children(swatch_buttons),
);
let st_done = internal.clone();
Some(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"panel".into(),
))
.test_support()
.role(Role::Dialog)
.aria_label(SharedString::from(format!("{} color", self.label)))
.w(px(306.0))
.p(px(14.0))
.flex()
.flex_col()
.gap(px(12.0))
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.child(
div()
.w_full()
.flex()
.items_center()
.justify_between()
.child(
div()
.flex()
.items_center()
.gap(px(10.0))
.child(render_chip(current_hsla, 28.0))
.child(
div()
.flex()
.flex_col()
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(self.label.clone()),
)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(hex.clone()),
),
),
)
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"done".into(),
))
.accessibility_label("Done")
.on_click(move |_, window, cx| {
st_done.update(cx, |s, _| s.open = false);
window.refresh();
})
.h(px(28.0))
.px(px(10.0))
.flex()
.items_center()
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.cursor_pointer()
.text_size(Typography::TEXT_XS)
.text_color(colors.foreground)
.child("Done"),
),
)
.child(area)
.child(hue_slider)
.child(alpha_slider)
.child(format_row)
.child(contrast_row)
.child(swatches_row),
)
} else {
None
};
div()
.id(self.id.clone())
.test_support()
.flex()
.flex_col()
.items_start()
.gap(Spacing::S2)
.when(!open, |this| this.child(trigger))
.when_some(panel, |this, p| this.child(p))
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
use super::*;
#[test]
fn parse_and_format_all_color_models() {
let blue = parse_color("#2F6BFF", 0.0).expect("hex parses");
assert_eq!(color_to_hex(blue), "#2F6BFF");
assert_eq!(format_color(blue, ColorFormat::Rgb), "rgb(47 107 255)");
let short = parse_color("#0f8", 0.0).expect("3-digit hex");
assert_eq!(color_to_hex(short), "#00FF88");
let translucent = parse_color("#2F6BFF80", 0.0).expect("8-digit hex");
assert!(translucent.a > 0.49 && translucent.a < 0.51);
assert!(format_color(translucent, ColorFormat::Rgb).contains("/ 50%"));
let from_rgb = parse_color("rgb(47 107 255)", 0.0).expect("rgb parses");
assert_eq!(color_to_hex(from_rgb), "#2F6BFF");
let from_hsl = parse_color("hsl(240 100% 50%)", 0.0).expect("hsl parses");
assert_eq!(color_to_hex(from_hsl), "#0000FF");
let from_oklch = parse_color("oklch(60% 0.18 260)", 0.0).expect("oklch parses");
assert!(color_to_hex(from_oklch).starts_with('#'));
assert!(parse_color("not-a-color", 0.0).is_none());
}
#[test]
fn wcag_contrast_ratio_and_grades() {
let black = parse_color("#000000", 0.0).unwrap();
let white_bg = RgbaColor {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
};
let ratio = contrast_ratio(black, white_bg);
assert!((ratio - 21.0).abs() < 0.05);
assert_eq!(contrast_grade(ratio), ContrastGrade::Aaa);
assert_eq!(contrast_grade(4.6), ContrastGrade::Aa);
assert_eq!(contrast_grade(3.2), ContrastGrade::AaLarge);
assert_eq!(contrast_grade(2.1), ContrastGrade::Fails);
}
struct PickerHost;
impl Render for PickerHost {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(400.0)).p(px(16.0)).child(
ColorPicker::new("cp-test")
.label("Accent")
.default_value("#2F6BFF")
.default_open(true)
.swatches(vec![
ColorSwatch::new("s1", "#2F6BFF"),
ColorSwatch::new("s2", "#16A34A"),
]),
)
}
}
#[gpui_kit::test]
fn color_picker_renders_panel_and_sliders(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (_view, cx) = cx.add_window_view(|_, _| PickerHost);
cx.update(|window, cx| {
window.render_frame(cx);
let panel = window.find(ElementId::NamedChild(
ElementId::Name("cp-test".into()).into(),
"panel".into(),
));
assert_eq!(panel.role(), Some(Role::Dialog));
for part in ["area", "hue", "alpha"] {
let slider = window.find(ElementId::NamedChild(
ElementId::Name("cp-test".into()).into(),
part.into(),
));
assert_eq!(slider.role(), Some(Role::Slider));
}
});
}
}