Skip to main content

mitsuami_widgets/
choices.rs

1//! Choosing one of a list of options: pop-up menus and radio groups.
2
3use std::rc::Rc;
4
5use mitsuami_core::{Element, ElementBuilder, EventValue, NodeId, Prop, Tweak, Ui, UiEvent, View, WidgetKind};
6use mitsuami_reactive::{IntoValue, Signal, Value};
7
8/// A pop-up menu of text options to choose one from: `NSPopUpButton`,
9/// `ComboBox`, `gtk::DropDown`, `QQC2.ComboBox`. Its label is its
10/// accessible name; like a text field's, it isn't drawn, so put a `Text`
11/// next to it.
12///
13/// As with HTML's `<select>`, one option is always chosen (GTK can't show
14/// none): the first, unless `selected` says otherwise. An index past the
15/// options chooses the first too. Only a `Select` without options has
16/// nothing chosen.
17///
18/// ```ignore
19/// let color = signal(0);
20/// Select::new("Color").options(["Red", "Green", "Blue"]).bind(color)
21/// ```
22pub struct Select {
23    element: Element,
24    options: Value<Vec<String>>,
25    selected: Value<usize>,
26}
27
28impl ElementBuilder for Select {
29    fn element(&mut self) -> &mut Element {
30        &mut self.element
31    }
32}
33
34impl View for Select {
35    fn build(mut self, ui: &Ui) -> NodeId {
36        let chosen = |index: usize, count: usize| (count > 0).then_some(if index < count { index } else { 0 });
37        let selected = match (self.selected, self.options.clone()) {
38            (Value::Static(index), Value::Static(options)) => Value::Static(chosen(index, options.len())),
39            (index, options) => Value::Dynamic(Rc::new(move || chosen(index.get(), options.get().len()))),
40        };
41        self.element.prop(self.options, Prop::Options);
42        self.element.prop(selected, Prop::SelectedIndex);
43        self.element.build(ui)
44    }
45}
46
47impl Select {
48    pub fn new(label: impl IntoValue<String>) -> Select {
49        let mut element = Element::new(WidgetKind::Select);
50        element.prop(label.into_value(), Prop::Label);
51        Select { element, options: Value::Static(Vec::new()), selected: Value::Static(0) }
52    }
53
54    /// Its label: the accessible name, which `new` takes. In `view!`,
55    /// `<Select label="…"/>`.
56    pub fn label(mut self, label: impl IntoValue<String>) -> Select {
57        self.element.prop(label.into_value(), Prop::Label);
58        self
59    }
60
61    /// The options, in order: a list of strings, or a signal or closure
62    /// giving one.
63    pub fn options(mut self, options: impl IntoValue<Vec<String>>) -> Select {
64        self.options = options.into_value();
65        self
66    }
67
68    /// The index of the chosen option.
69    pub fn selected(mut self, index: impl IntoValue<usize>) -> Select {
70        self.selected = index.into_value();
71        self
72    }
73
74    /// Two-way binding, Vue's `v-model`.
75    pub fn bind(self, signal: Signal<usize>) -> Select {
76        self.selected(signal).on_change(move |index| signal.set(index))
77    }
78
79    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> Select {
80        self.element.prop(enabled.into_value(), Prop::Enabled);
81        self
82    }
83
84    /// Raw platform settings: see [`Tweak`]. Selects have no semantic
85    /// options past their options and choice: what the platforms offer (a
86    /// borderless pop-up on AppKit and Qt, search on GTK, a header on
87    /// WinUI) is each one's own.
88    pub fn native(mut self, tweak: Tweak<Select>) -> Select {
89        tweak.apply(&mut self.element);
90        self
91    }
92
93    /// Called with the option's index when the user chooses one.
94    pub fn on_change(mut self, handler: impl Fn(usize) + 'static) -> Select {
95        self.element.on(move |event| {
96            if let UiEvent::Changed(EventValue::Index(index)) = event {
97                handler(*index);
98            }
99        });
100        self
101    }
102}
103
104/// Radio buttons, one for each of its options, to choose one from:
105/// `NSButton`s of the radio type, `RadioButtons`, `gtk::CheckButton`s in a
106/// group, `QQC2.RadioButton`s. Down a column, as each platform stacks
107/// them. Its label is its accessible name; it isn't drawn, so put a `Text`
108/// above it.
109///
110/// Unlike a `Select`, a radio group can have none chosen, as on every
111/// platform: until the user picks one, if `selected` says `None` or an
112/// index past the options. The user can't go back to none.
113///
114/// ```ignore
115/// let size = signal(Some(1));
116/// RadioGroup::new("Size").options(["Small", "Medium", "Large"]).bind(size)
117/// ```
118pub struct RadioGroup {
119    element: Element,
120    options: Value<Vec<String>>,
121    selected: Value<Option<usize>>,
122}
123
124impl ElementBuilder for RadioGroup {
125    fn element(&mut self) -> &mut Element {
126        &mut self.element
127    }
128}
129
130impl View for RadioGroup {
131    fn build(mut self, ui: &Ui) -> NodeId {
132        let chosen = |index: Option<usize>, count: usize| index.filter(|i| *i < count);
133        let selected = match (self.selected, self.options.clone()) {
134            (Value::Static(index), Value::Static(options)) => Value::Static(chosen(index, options.len())),
135            (index, options) => Value::Dynamic(Rc::new(move || chosen(index.get(), options.get().len()))),
136        };
137        self.element.prop(self.options, Prop::Options);
138        self.element.prop(selected, Prop::SelectedIndex);
139        self.element.build(ui)
140    }
141}
142
143impl RadioGroup {
144    pub fn new(label: impl IntoValue<String>) -> RadioGroup {
145        let mut element = Element::new(WidgetKind::RadioGroup);
146        element.prop(label.into_value(), Prop::Label);
147        RadioGroup { element, options: Value::Static(Vec::new()), selected: Value::Static(None) }
148    }
149
150    /// Its label: the accessible name, which `new` takes. In `view!`,
151    /// `<RadioGroup label="…"/>`.
152    pub fn label(mut self, label: impl IntoValue<String>) -> RadioGroup {
153        self.element.prop(label.into_value(), Prop::Label);
154        self
155    }
156
157    /// The options, in order: a list of strings, or a signal or closure
158    /// giving one.
159    pub fn options(mut self, options: impl IntoValue<Vec<String>>) -> RadioGroup {
160        self.options = options.into_value();
161        self
162    }
163
164    /// The index of the chosen option, `None` for none.
165    pub fn selected(mut self, index: impl IntoValue<Option<usize>>) -> RadioGroup {
166        self.selected = index.into_value();
167        self
168    }
169
170    /// Two-way binding, Vue's `v-model`.
171    pub fn bind(self, signal: Signal<Option<usize>>) -> RadioGroup {
172        self.selected(signal).on_change(move |index| signal.set(Some(index)))
173    }
174
175    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> RadioGroup {
176        self.element.prop(enabled.into_value(), Prop::Enabled);
177        self
178    }
179
180    /// Raw platform settings: see [`Tweak`]. The tweak gets the group's
181    /// container (an `NSStackView`, the `RadioButtons`, a `gtk::Box`, a
182    /// QML `ColumnLayout`), which holds the buttons.
183    pub fn native(mut self, tweak: Tweak<RadioGroup>) -> RadioGroup {
184        tweak.apply(&mut self.element);
185        self
186    }
187
188    /// Called with the option's index when the user chooses one.
189    pub fn on_change(mut self, handler: impl Fn(usize) + 'static) -> RadioGroup {
190        self.element.on(move |event| {
191            if let UiEvent::Changed(EventValue::Index(index)) = event {
192                handler(*index);
193            }
194        });
195        self
196    }
197}
198
199impl Select {
200    /// `<Select a11y_label="Color" options=["Red", "Green"] bind=color/>`
201    #[doc(hidden)]
202    pub fn __tag() -> Select {
203        Select {
204            element: Element::new(WidgetKind::Select),
205            options: Value::Static(Vec::new()),
206            selected: Value::Static(0),
207        }
208    }
209}
210
211impl RadioGroup {
212    /// `<RadioGroup a11y_label="Size" options=["Small", "Large"] bind=size/>`
213    #[doc(hidden)]
214    pub fn __tag() -> RadioGroup {
215        RadioGroup {
216            element: Element::new(WidgetKind::RadioGroup),
217            options: Value::Static(Vec::new()),
218            selected: Value::Static(None),
219        }
220    }
221}