Skip to main content

mitsuami_widgets/
color_well.rs

1//! Colour wells.
2
3use mitsuami_core::{Color, Element, ElementBuilder, EventValue, NodeId, Prop, Tweak, Ui, UiEvent, View, WidgetKind};
4use mitsuami_reactive::{IntoValue, Signal};
5
6/// A colour well: a button showing a colour, which opens the platform's
7/// own way to pick another (AppKit's colour panel, GTK's colour dialog,
8/// WinUI's colour picker, Qt's colour dialog). Its label is its accessible
9/// name. Opaque colours only: a semantic colour or alpha isn't a well's.
10///
11/// ```ignore
12/// let color = signal(Color::rgb(0, 120, 215));
13/// ColorWell::new("Colour").bind(color)
14/// ```
15pub struct ColorWell(Element);
16widget!(ColorWell);
17
18impl ColorWell {
19    /// The platform's own colour until it's given one.
20    pub fn new(label: impl IntoValue<String>) -> ColorWell {
21        let mut element = Element::new(WidgetKind::ColorWell);
22        element.prop(label.into_value(), Prop::Label);
23        ColorWell(element)
24    }
25
26    /// Its label: the accessible name, which `new` takes. In `view!`,
27    /// `<ColorWell label="…"/>`.
28    pub fn label(mut self, label: impl IntoValue<String>) -> ColorWell {
29        self.0.prop(label.into_value(), Prop::Label);
30        self
31    }
32
33    /// The colour it shows, made opaque.
34    pub fn color(mut self, color: impl IntoValue<Color>) -> ColorWell {
35        let opaque = |color: Color| match color {
36            Color::Rgba(r, g, b, _) => Color::rgb(r, g, b),
37            other => other,
38        };
39        self.0.prop(color.into_value(), move |c| Prop::ColorValue(opaque(c)));
40        self
41    }
42
43    /// Two-way binding, Vue's `v-model`.
44    pub fn bind(self, signal: Signal<Color>) -> ColorWell {
45        self.color(signal).on_change(move |color| signal.set(color))
46    }
47
48    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> ColorWell {
49        self.0.prop(enabled.into_value(), Prop::Enabled);
50        self
51    }
52
53    /// Called with the colour the user picked, as the platform reports
54    /// picks: AppKit's panel and WinUI's picker as it's dragged, GTK's and
55    /// Qt's dialogs once they're accepted.
56    pub fn on_change(mut self, handler: impl Fn(Color) + 'static) -> ColorWell {
57        self.0.on(move |event| {
58            if let UiEvent::Changed(EventValue::Color(color)) = event {
59                handler(*color);
60            }
61        });
62        self
63    }
64
65    /// Raw platform settings, past the semantic ones: see [`Tweak`].
66    pub fn native(mut self, tweak: Tweak<ColorWell>) -> ColorWell {
67        tweak.apply(&mut self.0);
68        self
69    }
70
71    /// `<ColorWell label="Colour" bind=color/>`
72    #[doc(hidden)]
73    pub fn __tag() -> ColorWell {
74        ColorWell(Element::new(WidgetKind::ColorWell))
75    }
76}