Skip to main content

egui_pop_core/
compact.rs

1//! Controls for dense rows, where a control has a slot of a given size
2//! and no label beside it (a HUD's parts, a property sheet, a card's
3//! fold): a choice in a compact cell and a menu row. The scrub field is
4//! the slider's [`scrub`](crate::slider::Slider::scrub) look, and a text
5//! in a compact cell the decorated input's [`cell`](crate::input::Input::cell).
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! - [`ChoiceCell`]: one of a few words in a slot, egui-pop's
11//!   [`combo_box`] sized to it. Its name is
12//!   given to assistive technologies and shown in its tooltip; while it
13//!   has the focus and its list is closed, Up and Down choose the
14//!   previous and next word, Home and End the first and last, as a
15//!   native drop-down does; Space or Enter opens the list.
16//! - [`MenuRow`]: a row the width of its room in the look of a menu's
17//!   items (the kit's `menu-item`), its text at the start and a muted
18//!   note at the end (a count, a key): an entry of a "More (n)" fold, a
19//!   "Show all". A button to assistive technologies, focused by Tab and
20//!   pressed with Space or Enter.
21//! - [`RowButton`]: a button small enough for a list's row (Cancel,
22//!   Retry beside a job), the kit's `button` around its words with a
23//!   hairline's padding, no taller than the row ([`Tokens`]'
24//!   `size.row.height`). A button to assistive technologies, named by its
25//!   words, focused by Tab and pressed with Space or Enter.
26//!
27//! ```
28//! use egui_pop_core::compact::{ChoiceCell, MenuRow, RowButton};
29//!
30//! fn row(ui: &mut egui::Ui, mode: &mut usize) {
31//!     let size = egui::vec2(120.0, 22.0);
32//!     ChoiceCell::new("Blend mode", mode, &["Normal", "Multiply", "Screen"])
33//!         .size(size)
34//!         .show(ui);
35//!     if ui.add(MenuRow::new("Show Contrast").note("hidden")).clicked() {
36//!         // reveal it
37//!     }
38//!     if ui.add(RowButton::new("Cancel")).clicked() {
39//!         // cancel the row's job
40//!     }
41//! }
42//! ```
43
44use egui::{Color32, Id, Key, Rect, Response, Role, Sense, Ui, Vec2, Widget, WidgetInfo, vec2};
45
46use crate::kit::{Kit, KitCx, Part, State, Tone};
47use crate::theme::Tokens;
48use crate::widgets::{combo_box, selectable_value};
49
50/// One of a few words in a compact cell (see [the module](self)).
51#[derive(Debug)]
52#[must_use = "draw it with `show`"]
53pub struct ChoiceCell<'a, S> {
54    name: &'a str,
55    selected: &'a mut usize,
56    choices: &'a [S],
57    size: Option<Vec2>,
58    salt: Option<Id>,
59}
60
61impl<'a, S: AsRef<str>> ChoiceCell<'a, S> {
62    /// A cell choosing `selected` among `choices`, named `name`.
63    pub fn new(name: &'a str, selected: &'a mut usize, choices: &'a [S]) -> Self {
64        Self {
65            name,
66            selected,
67            choices,
68            size: None,
69            salt: None,
70        }
71    }
72
73    /// Its size; by default the available width and a row's height.
74    pub fn size(mut self, size: Vec2) -> Self {
75        self.size = Some(size);
76        self
77    }
78
79    /// Distinguishes cells with the same name in one place.
80    pub fn id_salt(mut self, salt: impl std::hash::Hash + std::fmt::Debug) -> Self {
81        self.salt = Some(Id::unique(salt));
82        self
83    }
84
85    /// Draws it; its response is marked changed when the choice changed.
86    pub fn show(self, ui: &mut Ui) -> Response {
87        let ChoiceCell {
88            name,
89            selected,
90            choices,
91            size,
92            salt,
93        } = self;
94        let size = size.unwrap_or_else(|| vec2(ui.available_width(), ui.spacing().interact_size.y));
95        let id = salt.unwrap_or_else(|| Id::unique(("egui_pop_choice_cell", name)));
96        let word = |i: usize| choices.get(i).map_or("", AsRef::as_ref);
97        let before = *selected;
98        let pad = Tokens::of(ui.ctx()).space.xs;
99        let mut response = ui
100            .scope(|ui| {
101                // egui's combo box truncates its word to the room left,
102                // not to its width: a long word would widen the slot.
103                ui.set_max_width(size.x);
104                let spacing = ui.spacing_mut();
105                spacing.interact_size.y = size.y;
106                spacing.button_padding = vec2(pad, 0.0);
107                combo_box(id)
108                    .selected_text(word(*selected))
109                    .width(size.x)
110                    .truncate()
111                    .show_ui(ui, |ui| {
112                        for (i, c) in choices.iter().enumerate() {
113                            selectable_value(ui, selected, i, c.as_ref());
114                        }
115                    })
116                    .response
117            })
118            .inner;
119        let n = choices.len();
120        crate::focus::takes_keys(ui.ctx(), response.id);
121        if n > 0 && response.has_focus() && !egui::ComboBox::is_open(ui.ctx(), response.id) {
122            // The arrows choose, they do not move the focus.
123            ui.memory_mut(|m| {
124                m.set_focus_lock_filter(
125                    response.id,
126                    egui::EventFilter {
127                        vertical_arrows: true,
128                        ..Default::default()
129                    },
130                );
131            });
132            let last = n - 1;
133            ui.input(|i| {
134                if i.key_pressed(Key::ArrowDown) {
135                    *selected = (*selected + 1).min(last);
136                }
137                if i.key_pressed(Key::ArrowUp) {
138                    *selected = selected.saturating_sub(1).min(last);
139                }
140                if i.key_pressed(Key::Home) {
141                    *selected = 0;
142                }
143                if i.key_pressed(Key::End) {
144                    *selected = last;
145                }
146            });
147        }
148        if *selected != before {
149            response.mark_changed();
150        }
151        let shown = word(*selected).to_owned();
152        ui.ctx().accesskit_node_builder(response.id, |node| {
153            node.set_label(name);
154            node.set_value(shown);
155        });
156        response.on_hover_text(name)
157    }
158}
159
160/// A row in the look of a menu's items (see [the module](self)).
161#[derive(Clone, Debug)]
162#[must_use = "add it with `ui.add`"]
163pub struct MenuRow {
164    text: String,
165    note: Option<String>,
166    height: Option<f32>,
167}
168
169impl MenuRow {
170    /// A row saying `text`, its accessible name.
171    pub fn new(text: impl Into<String>) -> Self {
172        Self {
173            text: text.into(),
174            note: None,
175            height: None,
176        }
177    }
178
179    /// A muted text at the row's end (a count, a key), read after the
180    /// row's text by assistive technologies.
181    pub fn note(mut self, note: impl Into<String>) -> Self {
182        self.note = Some(note.into());
183        self
184    }
185
186    /// Its height; by default the kit's `menu-item.height`, at least a
187    /// row's.
188    pub fn height(mut self, height: f32) -> Self {
189        self.height = Some(height);
190        self
191    }
192}
193
194impl Widget for MenuRow {
195    fn ui(self, ui: &mut Ui) -> Response {
196        let ctx = ui.ctx().clone();
197        let kit = Kit::of(&ctx);
198        let item = &kit.menu_item;
199        let height = self
200            .height
201            .unwrap_or_else(|| item.data.height.max(ui.spacing().interact_size.y).max(1.0));
202        let width = ui.available_width().max(height);
203        let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::click());
204        if ui.is_rect_visible(rect) {
205            let state = State::from_response(&response);
206            let font = egui::TextStyle::Button.resolve(ui.style());
207            let label =
208                ui.painter()
209                    .layout_no_wrap(self.text.clone(), font.clone(), Color32::PLACEHOLDER);
210            let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect()));
211            let cx = KitCx {
212                painter: &painter,
213                ppp: ctx.pixels_per_point(),
214            };
215            item.paint(
216                &cx,
217                &Part {
218                    rect,
219                    room: rect,
220                    state,
221                    label: None,
222                },
223            );
224            // The text at the start, as a menu's items have it, whatever
225            // the component's label alignment.
226            let pad = item.data.padding_x.max(0.0);
227            painter.galley(
228                egui::pos2(rect.left() + pad, rect.center().y - label.size().y / 2.0),
229                label,
230                item.style(state).text,
231            );
232            if let Some(note) = &self.note {
233                let galley = painter.layout_no_wrap(
234                    note.clone(),
235                    font,
236                    item.style_toned(Tone::Muted, state).text,
237                );
238                let at = Rect::from_min_size(
239                    egui::pos2(
240                        rect.right() - pad - galley.size().x,
241                        rect.center().y - galley.size().y / 2.0,
242                    ),
243                    galley.size(),
244                );
245                painter.galley(at.min, galley, Color32::PLACEHOLDER);
246            }
247        }
248        let name = match &self.note {
249            Some(n) => format!("{}, {n}", self.text),
250            None => self.text.clone(),
251        };
252        let enabled = ui.is_enabled();
253        response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &name));
254        response
255    }
256}
257
258/// A button small enough for a list's row (see [the module](self)).
259///
260/// Need (action): a small (compact) button in a dense list row.
261#[derive(Clone, Debug)]
262#[must_use = "add it with `ui.add`"]
263pub struct RowButton {
264    text: String,
265    tone: Tone,
266    height: Option<f32>,
267}
268
269impl RowButton {
270    /// A button saying `text`, its accessible name.
271    pub fn new(text: impl Into<String>) -> Self {
272        Self {
273            text: text.into(),
274            tone: Tone::Neutral,
275            height: None,
276        }
277    }
278
279    /// Its tone, from the kit's `button.tone.*` (a danger "Delete").
280    pub fn tone(mut self, tone: Tone) -> Self {
281        self.tone = tone;
282        self
283    }
284
285    /// Its height; by default its words with `space.xs` above and below,
286    /// no taller than a row (`size.row.height`).
287    pub fn height(mut self, height: f32) -> Self {
288        self.height = Some(height);
289        self
290    }
291}
292
293impl Widget for RowButton {
294    fn ui(self, ui: &mut Ui) -> Response {
295        let ctx = ui.ctx().clone();
296        let t = Tokens::of(&ctx);
297        let kit = Kit::of(&ctx);
298        let button = &kit.button;
299        let font = egui::TextStyle::Button.resolve(ui.style());
300        let label = ui
301            .painter()
302            .layout_no_wrap(self.text.clone(), font, Color32::PLACEHOLDER);
303        let height = self.height.unwrap_or_else(|| {
304            (label.size().y + 2.0 * t.space.xs)
305                .min(t.size.row_height)
306                .max(label.size().y)
307        });
308        let pad = t.space.s.max(button.border_room(ctx.pixels_per_point()));
309        let size = vec2((label.size().x + 2.0 * pad).max(height), height.max(1.0));
310        let (rect, response) = ui.allocate_exact_size(size, Sense::click());
311        if ui.is_rect_visible(rect) {
312            let state = State::from_response(&response).toned(self.tone);
313            let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect()));
314            let cx = KitCx {
315                painter: &painter,
316                ppp: ctx.pixels_per_point(),
317            };
318            button.paint(
319                &cx,
320                &Part {
321                    rect,
322                    room: rect,
323                    state,
324                    label: None,
325                },
326            );
327            // Centred whatever the component's label alignment, with the
328            // compact padding rather than the button's own.
329            painter.galley(
330                rect.center() - label.size() / 2.0,
331                label,
332                button.style(state).text,
333            );
334        }
335        let enabled = ui.is_enabled();
336        response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &self.text));
337        response
338    }
339}