1use crate::capabilities::foundation::theme::{use_theme, Theme};
4use crate::capabilities::overlays::popover::{Popover, PopoverContent};
5use crate::capabilities::primitives::text::{Text, TextVariant};
6use gpui::{prelude::FluentBuilder as _, *};
7use std::rc::Rc;
8
9const MAX_RECENT_COLORS: usize = 10;
10
11#[derive(Copy, Clone, Debug, PartialEq, Eq)]
12pub enum ColorMode {
13 HSL,
14 RGB,
15 HEX,
16}
17
18pub struct ColorPickerState {
20 selected_color: Hsla,
21 mode: ColorMode,
22 recent_colors: Vec<Hsla>,
23}
24
25impl ColorPickerState {
26 pub fn new(initial_color: Hsla) -> Self {
27 Self {
28 selected_color: initial_color,
29 mode: ColorMode::HSL,
30 recent_colors: Vec::new(),
31 }
32 }
33
34 pub fn set_hue(&mut self, hue: f32) {
36 self.selected_color.h = hue.clamp(0.0, 1.0);
37 }
38
39 pub fn set_saturation(&mut self, saturation: f32) {
40 self.selected_color.s = saturation.clamp(0.0, 1.0);
41 }
42
43 pub fn set_lightness(&mut self, lightness: f32) {
44 self.selected_color.l = lightness.clamp(0.0, 1.0);
45 }
46
47 pub fn set_alpha(&mut self, alpha: f32) {
48 self.selected_color.a = alpha.clamp(0.0, 1.0);
49 }
50
51 pub fn set_color(&mut self, color: Hsla) {
52 self.selected_color = color;
53 }
54
55 pub fn add_to_recent(&mut self, color: Hsla) {
56 self.recent_colors
57 .retain(|&c| !(c.h == color.h && c.s == color.s && c.l == color.l && c.a == color.a));
58
59 self.recent_colors.insert(0, color);
60
61 if self.recent_colors.len() > MAX_RECENT_COLORS {
62 self.recent_colors.truncate(MAX_RECENT_COLORS);
63 }
64 }
65
66 pub fn selected_color(&self) -> Hsla {
67 self.selected_color
68 }
69
70 pub fn recent_colors(&self) -> &[Hsla] {
71 &self.recent_colors
72 }
73
74 pub fn mode(&self) -> ColorMode {
75 self.mode
76 }
77
78 pub fn set_mode(&mut self, mode: ColorMode) {
79 self.mode = mode;
80 }
81}
82
83#[derive(IntoElement)]
84pub struct ColorPicker {
85 id: ElementId,
86 state: Entity<ColorPickerState>,
87 show_alpha: bool,
88 swatches: Vec<Hsla>,
89 on_change: Option<Rc<dyn Fn(Hsla, &mut Window, &mut App)>>,
90 disabled: bool,
91 style: StyleRefinement,
92}
93
94impl ColorPicker {
95 pub fn new(id: impl Into<ElementId>, state: Entity<ColorPickerState>) -> Self {
97 Self {
98 id: id.into(),
99 state,
100 show_alpha: true,
101 swatches: default_swatches(),
102 on_change: None,
103 disabled: false,
104 style: StyleRefinement::default(),
105 }
106 }
107
108 pub fn show_alpha(mut self, show: bool) -> Self {
110 self.show_alpha = show;
111 self
112 }
113
114 pub fn swatches(mut self, swatches: Vec<Hsla>) -> Self {
116 self.swatches = swatches;
117 self
118 }
119
120 pub fn on_change(mut self, handler: impl Fn(Hsla, &mut Window, &mut App) + 'static) -> Self {
122 self.on_change = Some(Rc::new(handler));
123 self
124 }
125
126 pub fn disabled(mut self, disabled: bool) -> Self {
128 self.disabled = disabled;
129 self
130 }
131
132 fn hsl_to_rgb_f32(h: f32, s: f32, l: f32) -> (f32, f32, f32) {
134 let h = h * 360.0;
135 let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
136 let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
137 let m = l - c / 2.0;
138
139 if h < 60.0 {
140 (c + m, x + m, m)
141 } else if h < 120.0 {
142 (x + m, c + m, m)
143 } else if h < 180.0 {
144 (m, c + m, x + m)
145 } else if h < 240.0 {
146 (m, x + m, c + m)
147 } else if h < 300.0 {
148 (x + m, m, c + m)
149 } else {
150 (c + m, m, x + m)
151 }
152 }
153
154 fn hsla_to_hex(color: Hsla) -> String {
156 let (r, g, b) = Self::hsl_to_rgb_f32(color.h, color.s, color.l);
157 format!(
158 "#{:02X}{:02X}{:02X}",
159 (r * 255.0) as u8,
160 (g * 255.0) as u8,
161 (b * 255.0) as u8
162 )
163 }
164
165 fn hsla_to_rgb(color: Hsla) -> (u8, u8, u8) {
167 let (r, g, b) = Self::hsl_to_rgb_f32(color.h, color.s, color.l);
168 ((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8)
169 }
170}
171
172impl Styled for ColorPicker {
173 fn style(&mut self) -> &mut StyleRefinement {
174 &mut self.style
175 }
176}
177
178impl RenderOnce for ColorPicker {
179 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
180 let theme = use_theme(cx);
181 let state = self.state.clone();
182 let color = state.read(cx).selected_color();
183 let _show_alpha = self.show_alpha;
184 let swatches = self.swatches.clone();
185 let on_change = self.on_change.clone();
186 let disabled = self.disabled;
187 let user_style = self.style;
188 let picker_id = self.id.clone();
189
190 let preview_button = div()
191 .flex()
192 .items_center()
193 .gap_2()
194 .h(px(40.0))
195 .px(px(12.0))
196 .bg(theme.tokens.background)
197 .border_1()
198 .border_color(theme.tokens.border)
199 .rounded(theme.tokens.radius_md)
200 .when(!disabled, |this| {
201 this.cursor(CursorStyle::PointingHand)
202 .hover(|style| style.bg(theme.tokens.accent.opacity(0.1)))
203 })
204 .when(disabled, |this| this.opacity(0.5))
205 .child(
206 div()
207 .size(px(24.0))
208 .rounded(px(4.0))
209 .bg(color)
210 .border_1()
211 .border_color(theme.tokens.border),
212 )
213 .child(
214 Text::new(Self::hsla_to_hex(color))
215 .variant(TextVariant::Custom)
216 .size(px(14.0))
217 .color(theme.tokens.foreground),
218 )
219 .map(|mut this| {
220 this.style().refine(&user_style);
221 this
222 });
223
224 if disabled {
225 return preview_button.into_any_element();
226 }
227
228 Popover::new(picker_id)
229 .trigger(preview_button)
230 .content(move |window, cx| {
231 let swatches_for_content = swatches.clone();
232 let on_change_for_content = on_change.clone();
233 let state_for_content = state.clone();
234
235 cx.new(|cx| {
236 PopoverContent::new(window, cx, move |_window, cx| {
237 let theme = use_theme(cx);
238
239 let current_color = state_for_content.read(cx).selected_color();
241 let current_mode = state_for_content.read(cx).mode();
242 let recent_vec = state_for_content.read(cx).recent_colors().to_vec();
243
244 let swatches_clone = swatches_for_content.clone();
245 let on_change_clone = on_change_for_content.clone();
246
247 div()
248 .flex()
249 .flex_col()
250 .gap_3()
251 .w(px(280.0))
252 .child(render_color_preview(current_color, theme.clone()))
253 .child(render_mode_selector(
254 current_mode,
255 state_for_content.clone(),
256 theme.clone(),
257 ))
258 .child(render_color_value(
259 current_color,
260 current_mode,
261 theme.clone(),
262 ))
263 .when(!swatches_clone.is_empty(), |this| {
264 this.child(render_swatches(
265 swatches_clone,
266 state_for_content.clone(),
267 on_change_clone.clone(),
268 theme.clone(),
269 ))
270 })
271 .when(!recent_vec.is_empty(), |this| {
272 this.child(render_recent_colors(
273 recent_vec,
274 state_for_content.clone(),
275 on_change_clone.clone(),
276 theme.clone(),
277 ))
278 })
279 .child(render_actions(
280 current_color,
281 state_for_content.clone(),
282 on_change_clone.clone(),
283 theme.clone(),
284 ))
285 .into_any_element()
286 })
287 })
288 })
289 .into_any_element()
290 }
291}
292
293fn render_color_preview(color: Hsla, theme: Theme) -> impl IntoElement {
294 div()
295 .flex()
296 .flex_col()
297 .gap_2()
298 .child(
299 Text::new("Selected Color")
300 .variant(TextVariant::Custom)
301 .size(px(12.0))
302 .color(theme.tokens.muted_foreground),
303 )
304 .child(
305 div()
306 .w_full()
307 .h(px(80.0))
308 .rounded(theme.tokens.radius_md)
309 .bg(color)
310 .border_1()
311 .border_color(theme.tokens.border),
312 )
313}
314
315fn render_mode_selector(
316 current_mode: ColorMode,
317 state: Entity<ColorPickerState>,
318 theme: Theme,
319) -> impl IntoElement {
320 div()
321 .flex()
322 .gap_1()
323 .child(render_mode_button(
324 "HSL",
325 ColorMode::HSL,
326 current_mode,
327 state.clone(),
328 theme.clone(),
329 ))
330 .child(render_mode_button(
331 "RGB",
332 ColorMode::RGB,
333 current_mode,
334 state.clone(),
335 theme.clone(),
336 ))
337 .child(render_mode_button(
338 "HEX",
339 ColorMode::HEX,
340 current_mode,
341 state,
342 theme,
343 ))
344}
345
346fn render_mode_button(
347 label: &'static str,
348 mode: ColorMode,
349 current_mode: ColorMode,
350 state: Entity<ColorPickerState>,
351 theme: Theme,
352) -> impl IntoElement {
353 let is_active = mode == current_mode;
354
355 div()
356 .flex_1()
357 .py(px(6.0))
358 .px(px(12.0))
359 .rounded(theme.tokens.radius_sm)
360 .text_size(px(12.0))
361 .text_align(TextAlign::Center)
362 .when(is_active, |this| {
363 this.bg(theme.tokens.primary)
364 .text_color(theme.tokens.primary_foreground)
365 })
366 .when(!is_active, |this| {
367 this.bg(theme.tokens.muted.opacity(0.3))
368 .text_color(theme.tokens.foreground)
369 .cursor(CursorStyle::PointingHand)
370 .hover(|style| style.bg(theme.tokens.muted.opacity(0.5)))
371 .on_mouse_down(MouseButton::Left, move |_, _, cx| {
372 state.update(cx, |state, cx| {
373 state.set_mode(mode);
374 cx.notify();
375 });
376 })
377 })
378 .child(label)
379}
380
381fn render_color_value(color: Hsla, mode: ColorMode, theme: Theme) -> impl IntoElement {
382 let value = match mode {
383 ColorMode::HSL => {
384 format!(
385 "hsl({:.0}, {:.0}%, {:.0}%)",
386 color.h * 360.0,
387 color.s * 100.0,
388 color.l * 100.0
389 )
390 }
391 ColorMode::RGB => {
392 let (r, g, b) = ColorPicker::hsla_to_rgb(color);
393 format!("rgb({}, {}, {})", r, g, b)
394 }
395 ColorMode::HEX => ColorPicker::hsla_to_hex(color),
396 };
397
398 div()
399 .flex()
400 .items_center()
401 .justify_between()
402 .p(px(8.0))
403 .bg(theme.tokens.muted.opacity(0.2))
404 .rounded(theme.tokens.radius_sm)
405 .child(
406 Text::new(value)
407 .variant(TextVariant::Custom)
408 .size(px(13.0))
409 .color(theme.tokens.foreground),
410 )
411}
412
413fn render_swatches(
414 swatches: Vec<Hsla>,
415 state: Entity<ColorPickerState>,
416 on_change: Option<Rc<dyn Fn(Hsla, &mut Window, &mut App)>>,
417 theme: Theme,
418) -> impl IntoElement {
419 div()
420 .flex()
421 .flex_col()
422 .gap_2()
423 .child(
424 Text::new("Swatches")
425 .variant(TextVariant::Custom)
426 .size(px(12.0))
427 .color(theme.tokens.muted_foreground),
428 )
429 .child(
430 div()
431 .flex()
432 .flex_wrap()
433 .gap_2()
434 .children(swatches.into_iter().map(move |swatch| {
435 render_color_swatch(swatch, state.clone(), on_change.clone(), theme.clone())
436 })),
437 )
438}
439
440fn render_recent_colors(
441 recent: Vec<Hsla>,
442 state: Entity<ColorPickerState>,
443 on_change: Option<Rc<dyn Fn(Hsla, &mut Window, &mut App)>>,
444 theme: Theme,
445) -> impl IntoElement {
446 div()
447 .flex()
448 .flex_col()
449 .gap_2()
450 .child(
451 Text::new("Recent Colors")
452 .variant(TextVariant::Custom)
453 .size(px(12.0))
454 .color(theme.tokens.muted_foreground),
455 )
456 .child(
457 div()
458 .flex()
459 .flex_wrap()
460 .gap_2()
461 .children(recent.into_iter().map(move |color| {
462 render_color_swatch(color, state.clone(), on_change.clone(), theme.clone())
463 })),
464 )
465}
466
467fn render_color_swatch(
468 color: Hsla,
469 state: Entity<ColorPickerState>,
470 on_change: Option<Rc<dyn Fn(Hsla, &mut Window, &mut App)>>,
471 theme: Theme,
472) -> impl IntoElement {
473 div()
474 .size(px(28.0))
475 .rounded(theme.tokens.radius_sm)
476 .bg(color)
477 .border_1()
478 .border_color(theme.tokens.border)
479 .cursor(CursorStyle::PointingHand)
480 .hover(|style| style.shadow_sm())
481 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
482 state.update(cx, |state, _| {
483 state.set_color(color);
484 });
485
486 if let Some(handler) = on_change.as_ref() {
487 handler(color, window, cx);
488 }
489 })
490}
491
492fn render_actions(
493 color: Hsla,
494 state: Entity<ColorPickerState>,
495 on_change: Option<Rc<dyn Fn(Hsla, &mut Window, &mut App)>>,
496 theme: Theme,
497) -> impl IntoElement {
498 div()
499 .flex()
500 .gap_2()
501 .child(
502 div()
503 .flex_1()
504 .py(px(8.0))
505 .px(px(12.0))
506 .bg(theme.tokens.secondary)
507 .text_color(theme.tokens.secondary_foreground)
508 .rounded(theme.tokens.radius_sm)
509 .text_size(px(13.0))
510 .text_align(TextAlign::Center)
511 .cursor(CursorStyle::PointingHand)
512 .hover(|style| style.bg(theme.tokens.secondary.opacity(0.8)))
513 .child("Copy")
514 .on_mouse_down(MouseButton::Left, move |_, _window, cx| {
515 let hex = ColorPicker::hsla_to_hex(color);
516 cx.write_to_clipboard(ClipboardItem::new_string(hex));
517 cx.stop_propagation();
518 }),
519 )
520 .child(
521 div()
522 .flex_1()
523 .py(px(8.0))
524 .px(px(12.0))
525 .bg(theme.tokens.primary)
526 .text_color(theme.tokens.primary_foreground)
527 .rounded(theme.tokens.radius_sm)
528 .text_size(px(13.0))
529 .text_align(TextAlign::Center)
530 .cursor(CursorStyle::PointingHand)
531 .hover(|style| style.bg(theme.tokens.primary.opacity(0.9)))
532 .child("Apply")
533 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
534 state.update(cx, |state, _| {
535 state.add_to_recent(color);
536 });
537
538 if let Some(handler) = on_change.as_ref() {
539 handler(color, window, cx);
540 }
541 }),
542 )
543}
544
545fn default_swatches() -> Vec<Hsla> {
546 vec![
547 hsla(0.0 / 360.0, 0.7, 0.5, 1.0),
548 hsla(0.0 / 360.0, 0.8, 0.4, 1.0),
549 hsla(0.0 / 360.0, 0.9, 0.3, 1.0),
550 hsla(30.0 / 360.0, 0.8, 0.5, 1.0),
551 hsla(40.0 / 360.0, 0.9, 0.5, 1.0),
552 hsla(60.0 / 360.0, 0.8, 0.5, 1.0),
553 hsla(50.0 / 360.0, 0.9, 0.6, 1.0),
554 hsla(120.0 / 360.0, 0.6, 0.4, 1.0),
555 hsla(140.0 / 360.0, 0.7, 0.4, 1.0),
556 hsla(160.0 / 360.0, 0.6, 0.4, 1.0),
557 hsla(180.0 / 360.0, 0.6, 0.5, 1.0),
558 hsla(190.0 / 360.0, 0.7, 0.5, 1.0),
559 hsla(210.0 / 360.0, 0.7, 0.5, 1.0),
560 hsla(220.0 / 360.0, 0.8, 0.5, 1.0),
561 hsla(240.0 / 360.0, 0.7, 0.5, 1.0),
562 hsla(270.0 / 360.0, 0.6, 0.5, 1.0),
563 hsla(290.0 / 360.0, 0.6, 0.5, 1.0),
564 hsla(310.0 / 360.0, 0.7, 0.5, 1.0),
565 hsla(330.0 / 360.0, 0.7, 0.5, 1.0),
566 hsla(0.0, 0.0, 0.2, 1.0),
567 hsla(0.0, 0.0, 0.4, 1.0),
568 hsla(0.0, 0.0, 0.6, 1.0),
569 hsla(0.0, 0.0, 0.8, 1.0),
570 hsla(0.0, 0.0, 0.95, 1.0),
571 ]
572}
573
574#[cfg(test)]
575mod tests {
576 use super::ColorPicker;
577 use gpui::hsla;
578
579 #[gpui::test]
580 fn hex_and_rgb_agree_across_hue_sectors() {
581 for h_degrees in [
582 0.0_f32, 59.0, 60.0, 119.0, 120.0, 179.0, 180.0, 239.0, 240.0, 299.0, 300.0, 359.0,
583 ] {
584 let color = hsla(h_degrees / 360.0, 0.8, 0.5, 1.0);
585 let (r, g, b) = ColorPicker::hsla_to_rgb(color);
586 let hex = ColorPicker::hsla_to_hex(color);
587 assert_eq!(
588 hex,
589 format!("#{:02X}{:02X}{:02X}", r, g, b),
590 "h={h_degrees}deg"
591 );
592 }
593 }
594
595 #[gpui::test]
596 fn known_colors_match_ground_truth() {
597 assert_eq!(
598 ColorPicker::hsla_to_hex(hsla(0.0, 1.0, 0.5, 1.0)),
599 "#FF0000"
600 );
601 assert_eq!(
602 ColorPicker::hsla_to_rgb(hsla(120.0 / 360.0, 1.0, 0.5, 1.0)),
603 (0, 255, 0)
604 );
605 assert_eq!(
606 ColorPicker::hsla_to_hex(hsla(240.0 / 360.0, 1.0, 0.5, 1.0)),
607 "#0000FF"
608 );
609 assert_eq!(
610 ColorPicker::hsla_to_rgb(hsla(0.5, 1.0, 0.5, 1.0)),
611 (0, 255, 255)
612 );
613 }
614
615 #[gpui::test]
616 fn grayscale_has_equal_channels() {
617 let (r, g, b) = ColorPicker::hsla_to_rgb(hsla(0.0, 0.0, 0.4, 1.0));
618 assert_eq!(r, g);
619 assert_eq!(g, b);
620 }
621
622 #[gpui::test]
623 fn black_and_white_bounds() {
624 let (r, g, b) = ColorPicker::hsla_to_rgb(hsla(0.0, 1.0, 0.0, 1.0));
625 assert_eq!((r, g, b), (0, 0, 0));
626 let (r, g, b) = ColorPicker::hsla_to_rgb(hsla(0.0, 1.0, 1.0, 1.0));
627 assert_eq!((r, g, b), (255, 255, 255));
628 }
629
630 #[gpui::test]
631 fn hex_is_uppercase_zero_padded() {
632 assert_eq!(
633 ColorPicker::hsla_to_hex(hsla(0.0, 1.0, 0.0, 1.0)),
634 "#000000"
635 );
636 assert_eq!(
637 ColorPicker::hsla_to_hex(hsla(0.0, 1.0, 1.0, 1.0)),
638 "#FFFFFF"
639 );
640 }
641}