Skip to main content

egui_pop_core/
segmented.rs

1//! The segmented control ([`Segmented`]): a row of exclusive options, one
2//! selected, re-exported by [`widgets`](crate::widgets).
3
4use egui::{
5    IdSalt, Key, Modifiers, Rect, Response, Role, Sense, TextStyle, TextWrapMode, Ui, Vec2, Widget,
6    WidgetInfo, WidgetText, vec2,
7};
8
9use crate::icon::{Icon, Size};
10use crate::kit::{Glyph, Kit, State};
11use crate::strings;
12use crate::theme::Tokens;
13
14/// What a [`Segmented`] does with the options that do not fit its row.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum SegmentOverflow {
18    /// The options that do not fit go, from the end, into a "More
19    /// choices" button ([`Glyph::More`]) opening them as a menu, as a
20    /// toolbar's tools do; the selected option always stays in the row.
21    #[default]
22    Menu,
23    /// The row wraps onto as many lines as it needs.
24    Wrap,
25    /// The row scrolls sideways.
26    Scroll,
27}
28
29/// One option of a [`Segmented`]: its value, its label, and an icon of the
30/// registry drawn before the label.
31#[derive(Clone, Debug, PartialEq)]
32pub struct SegmentOption<V> {
33    pub value: V,
34    pub label: String,
35    /// An icon's name in the registry (`phosphor:images`,
36    /// `<plugin-id>:<name>`); one that does not resolve draws the
37    /// placeholder, and the registry reports it.
38    pub icon: Option<String>,
39    /// Its tooltip.
40    pub tip: Option<String>,
41    pub enabled: bool,
42}
43
44impl<V> SegmentOption<V> {
45    pub fn new(value: V, label: impl Into<String>) -> Self {
46        Self {
47            value,
48            label: label.into(),
49            icon: None,
50            tip: None,
51            enabled: true,
52        }
53    }
54
55    /// Draws the registry's icon `name` before the label.
56    #[must_use]
57    pub fn icon(mut self, name: impl Into<String>) -> Self {
58        self.icon = Some(name.into());
59        self
60    }
61
62    /// Its tooltip.
63    #[must_use]
64    pub fn tip(mut self, tip: impl Into<String>) -> Self {
65        self.tip = Some(tip.into());
66        self
67    }
68
69    /// Greyed and passed over by the keyboard when not `enabled`.
70    #[must_use]
71    pub fn enabled(mut self, enabled: bool) -> Self {
72        self.enabled = enabled;
73        self
74    }
75}
76
77/// A segmented control: a row of exclusive options, one selected (a view's
78/// modes, a panel's tabs), as Mantine's `SegmentedControl`, Ant's
79/// `Segmented` or libadwaita's `AdwToggleGroup` have it.
80///
81/// - **For assistive technology** it is a radio group named by
82///   [`Segmented::name`], each option a radio button, checked when
83///   selected.
84/// - **The keyboard**: it is one Tab stop; Left and Right select the
85///   option before or after (round from one end to the other), Home and
86///   End the first and the last; disabled options are passed over.
87/// - **Too narrow a row** goes by [`SegmentOverflow`]: by default the last
88///   options fold into a "More choices" menu, the selected one staying in
89///   the row; or the row wraps, or scrolls.
90/// - **Looks** come from the kit: each option is the `toggle-chip`
91///   component (`selected` for the option chosen), its padding egui's
92///   button padding, its icon `size.icon.inline` and the gap before its
93///   label `space.xs`.
94///
95/// It replaces a row of `selectable_value` buttons:
96///
97/// ```
98/// use egui_pop_core::widgets::{SegmentOption, Segmented};
99///
100/// #[derive(Clone, Copy, PartialEq)]
101/// enum Scope { Folders, Albums, Keywords }
102///
103/// fn scopes(ui: &mut egui::Ui, scope: &mut Scope) {
104///     let changed = ui
105///         .add(
106///             Segmented::new("library.scope", scope, [
107///                 SegmentOption::new(Scope::Folders, "Folders").icon("phosphor:folder"),
108///                 SegmentOption::new(Scope::Albums, "Albums"),
109///                 SegmentOption::new(Scope::Keywords, "Keywords"),
110///             ])
111///             .name("Browse by"),
112///         )
113///         .changed();
114///     let _ = changed;
115/// }
116/// ```
117///
118/// Need (input): one mode among a few, as a segmented control or a tab strip.
119#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
120pub struct Segmented<'a, V> {
121    salt: IdSalt,
122    value: &'a mut V,
123    options: Vec<SegmentOption<V>>,
124    name: String,
125    overflow: SegmentOverflow,
126}
127
128impl<V> std::fmt::Debug for Segmented<'_, V> {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        f.debug_struct("Segmented")
131            .field("salt", &self.salt)
132            .field("options", &self.options.len())
133            .field("name", &self.name)
134            .field("overflow", &self.overflow)
135            .finish_non_exhaustive()
136    }
137}
138
139impl<'a, V: PartialEq + Clone> Segmented<'a, V> {
140    /// A control under `id_salt` (unique in its parent), selecting one of
141    /// `options` into `value`.
142    pub fn new(
143        id_salt: impl egui::AsIdSalt,
144        value: &'a mut V,
145        options: impl IntoIterator<Item = SegmentOption<V>>,
146    ) -> Self {
147        Self {
148            salt: IdSalt::new(id_salt),
149            value,
150            options: options.into_iter().collect(),
151            name: String::new(),
152            overflow: SegmentOverflow::default(),
153        }
154    }
155
156    /// Its name for assistive technology ("View", "Browse by"): the radio
157    /// group's, and its "More choices" button's.
158    pub fn name(mut self, name: impl Into<String>) -> Self {
159        self.name = name.into();
160        self
161    }
162
163    /// What it does with the options that do not fit.
164    pub fn overflow(mut self, overflow: SegmentOverflow) -> Self {
165        self.overflow = overflow;
166        self
167    }
168}
169
170/// The option a key asks for, from `at` among `options` (`enabled` each),
171/// round from one end to the other; `None` for a key that moves nothing.
172///
173/// Left and Right step to the enabled option before or after, Home and End
174/// to the first and the last enabled.
175pub fn segment_step(enabled: &[bool], at: usize, key: Key) -> Option<usize> {
176    let n = enabled.len();
177    if n == 0 || !enabled.iter().any(|e| *e) {
178        return None;
179    }
180    let to = match key {
181        Key::Home => enabled.iter().position(|e| *e)?,
182        Key::End => enabled.iter().rposition(|e| *e)?,
183        Key::ArrowLeft | Key::ArrowRight => {
184            let forward = key == Key::ArrowRight;
185            let mut i = at.min(n - 1);
186            loop {
187                i = if forward {
188                    (i + 1) % n
189                } else {
190                    (i + n - 1) % n
191                };
192                if enabled[i] || i == at {
193                    break i;
194                }
195            }
196        }
197        _ => return None,
198    };
199    (to != at).then_some(to)
200}
201
202/// Which options a row of `room` points shows, with `widths` each and a
203/// "More" button of `more` points: all when they fit, else those from the
204/// start that fit beside the button, `selected` always among them. The rest
205/// go into the menu.
206pub fn segment_fit(widths: &[f32], more: f32, room: f32, selected: Option<usize>) -> Vec<usize> {
207    let total: f32 = widths.iter().sum();
208    if total <= room {
209        return (0..widths.len()).collect();
210    }
211    let mut shown = Vec::new();
212    let mut used = more;
213    for (i, w) in widths.iter().enumerate() {
214        if used + w > room {
215            break;
216        }
217        used += w;
218        shown.push(i);
219    }
220    if let Some(sel) = selected
221        && sel < widths.len()
222        && !shown.contains(&sel)
223    {
224        while used + widths[sel] > room
225            && let Some(last) = shown.pop()
226        {
227            used -= widths[last];
228        }
229        shown.push(sel);
230    }
231    shown
232}
233
234/// One option laid out: its label's galley, its icon, its size.
235struct Laid {
236    galley: std::sync::Arc<egui::Galley>,
237    icon: Option<Icon>,
238    size: Vec2,
239}
240
241impl<V: PartialEq + Clone> Widget for Segmented<'_, V> {
242    fn ui(self, ui: &mut Ui) -> Response {
243        let Segmented {
244            salt,
245            value,
246            options,
247            name,
248            overflow,
249        } = self;
250        let id = ui.make_persistent_id(salt);
251        let ctx = ui.ctx().clone();
252        let t = Tokens::of(&ctx);
253        let kit = Kit::of(&ctx);
254        let look = &kit.toggle_chip;
255        let room = look.border_room(ctx.pixels_per_point());
256        let padding = ui.spacing().button_padding.max(Vec2::splat(room));
257        let side = Size::Inline.points(&t);
258        let height = ui.spacing().interact_size.y;
259        let laid: Vec<Laid> = options
260            .iter()
261            .map(|o| {
262                let galley = WidgetText::from(o.label.as_str()).into_galley(
263                    ui,
264                    Some(TextWrapMode::Extend),
265                    f32::INFINITY,
266                    TextStyle::Button,
267                );
268                let icon = o.icon.as_deref().map(|n| {
269                    crate::icon::registry::resolve(n, "segmented")
270                        .unwrap_or(crate::icon::PLACEHOLDER)
271                });
272                let icon_w = if icon.is_some() {
273                    side + t.space.xs
274                } else {
275                    0.0
276                };
277                let size = vec2(
278                    2.0 * padding.x + icon_w + galley.size().x,
279                    height.max(galley.size().y + 2.0 * padding.y),
280                );
281                Laid { galley, icon, size }
282            })
283            .collect();
284        let selected = options.iter().position(|o| o.value == *value);
285        let seg_id = |i: usize| id.with(("segment", i));
286        // A step to an option folded in the menu: its focus is given once
287        // it is drawn in the row.
288        let pending_id = id.with("pending focus");
289        let pending: Option<usize> = ctx.data_mut(|d| d.remove_temp(pending_id));
290        let more_w = 2.0 * padding.x + side;
291        let shown = match overflow {
292            SegmentOverflow::Menu => {
293                let widths: Vec<f32> = laid.iter().map(|l| l.size.x).collect();
294                segment_fit(&widths, more_w, ui.available_width(), selected)
295            }
296            _ => (0..options.len()).collect(),
297        };
298        let mut picked: Option<usize> = None;
299        let mut focused: Option<usize> = None;
300        let group_name = name.clone();
301        let body = |ui: &mut Ui, picked: &mut Option<usize>, focused: &mut Option<usize>| {
302            ui.spacing_mut().item_spacing.x = 0.0;
303            for &i in &shown {
304                let o = &options[i];
305                let l = &laid[i];
306                let on = selected == Some(i);
307                let r = ui
308                    .add_enabled_ui(o.enabled, |ui| {
309                        let (rect, _) = ui.allocate_exact_size(l.size, Sense::hover());
310                        let r = ui.interact(rect, seg_id(i), Sense::click());
311                        paint_segment(ui, &r, l, on, padding, side, t.space.xs);
312                        r
313                    })
314                    .inner;
315                let enabled = o.enabled;
316                let label = o.label.clone();
317                r.widget_info(|| WidgetInfo::selected(Role::RadioButton, enabled, on, &label));
318                if pending == Some(i) {
319                    r.request_focus();
320                }
321                if r.has_focus() {
322                    *focused = Some(i);
323                }
324                let r = match &o.tip {
325                    Some(tip) => r.on_hover_text(tip),
326                    None => r,
327                };
328                if r.clicked() && !on {
329                    *picked = Some(i);
330                }
331            }
332            if shown.len() < options.len() {
333                let more_name =
334                    strings::tr_args(&ctx, &strings::SEGMENTED_MORE, &[("control", &group_name)]);
335                let (rect, _) = ui.allocate_exact_size(vec2(more_w, height), Sense::hover());
336                let r = ui.interact(rect, id.with("more"), Sense::click());
337                r.widget_info(|| WidgetInfo::labeled(Role::Button, true, &more_name));
338                if ui.is_rect_visible(rect) {
339                    let state = State::from_response(&r).with(State::DISABLED, !ui.is_enabled());
340                    paint_box(ui, rect, state);
341                    let at = Rect::from_center_size(rect.center(), Vec2::splat(side));
342                    Kit::of(ui.ctx()).glyph(Glyph::More).paint(
343                        ui.painter(),
344                        at,
345                        Kit::of(ui.ctx()).toggle_chip.style(state).text,
346                    );
347                }
348                egui::Popup::menu(&r).id(id.with("more menu")).show(|ui| {
349                    for (i, o) in options.iter().enumerate() {
350                        if shown.contains(&i) {
351                            continue;
352                        }
353                        let on = selected == Some(i);
354                        let r = ui.add_enabled(
355                            o.enabled,
356                            crate::widgets::SelectableRow::new(on, o.label.as_str()),
357                        );
358                        let label = o.label.clone();
359                        let enabled = o.enabled;
360                        r.widget_info(|| {
361                            WidgetInfo::selected(Role::RadioButton, enabled, on, &label)
362                        });
363                        if r.clicked() {
364                            *picked = Some(i);
365                            ui.close();
366                        }
367                    }
368                });
369            }
370        };
371        let roving = format!("egui_pop.segmented.{id:?}");
372        let inner = crate::tab::roving(ui, &roving, crate::tab::Axis::Own, |ui| {
373            ui.scope_builder(
374                egui::UiBuilder::new()
375                    .id_salt(id)
376                    .accessibility_role(egui::accesskit::Role::RadioGroup)
377                    .accessibility_label(name.clone()),
378                |ui| match overflow {
379                    SegmentOverflow::Wrap => {
380                        ui.horizontal_wrapped(|ui| body(ui, &mut picked, &mut focused));
381                    }
382                    SegmentOverflow::Scroll => {
383                        egui::ScrollArea::horizontal()
384                            .id_salt(id.with("scroll"))
385                            .show(ui, |ui| {
386                                ui.horizontal(|ui| body(ui, &mut picked, &mut focused));
387                            });
388                    }
389                    SegmentOverflow::Menu => {
390                        ui.horizontal(|ui| body(ui, &mut picked, &mut focused));
391                    }
392                },
393            )
394        });
395        let mut response = inner.response;
396        // The keys, from the option that has the keyboard.
397        if let Some(at) = focused {
398            let enabled: Vec<bool> = options.iter().map(|o| o.enabled).collect();
399            let step = [Key::ArrowLeft, Key::ArrowRight, Key::Home, Key::End]
400                .into_iter()
401                .find_map(|k| {
402                    let to = segment_step(&enabled, at, k)?;
403                    ui.input_mut(|i| i.consume_key(Modifiers::NONE, k))
404                        .then_some(to)
405                });
406            if let Some(to) = step {
407                picked = Some(to);
408                if shown.contains(&to) {
409                    ctx.memory_mut(|m| {
410                        m.request_focus(seg_id(to));
411                        m.move_focus(egui::FocusDirection::None);
412                    });
413                } else {
414                    ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
415                    ctx.data_mut(|d| d.insert_temp(pending_id, to));
416                }
417            }
418        }
419        if let Some(i) = picked {
420            *value = options[i].value.clone();
421            response.mark_changed();
422            ctx.request_repaint();
423        }
424        response
425    }
426}
427
428/// Paints the `toggle-chip` box over `rect` in `state`.
429fn paint_box(ui: &Ui, rect: Rect, state: State) {
430    let kit = Kit::of(ui.ctx());
431    kit.toggle_chip.paint(
432        &crate::kit::KitCx {
433            painter: ui.painter(),
434            ppp: ui.ctx().pixels_per_point(),
435        },
436        &crate::kit::Part {
437            rect,
438            room: rect,
439            state,
440            label: None,
441        },
442    );
443}
444
445/// Paints an option: its box, its icon and its label.
446fn paint_segment(ui: &Ui, r: &Response, l: &Laid, on: bool, padding: Vec2, side: f32, gap: f32) {
447    if !ui.is_rect_visible(r.rect) {
448        return;
449    }
450    let state = State::from_response(r).with(State::DISABLED, !ui.is_enabled());
451    // The chosen option is never `hover`: the choice stays under the
452    // pointer.
453    let state = if on {
454        State::REST
455            .with(State::SELECTED, true)
456            .with(State::FOCUS, state.contains(State::FOCUS))
457            .with(State::ACTIVE, state.contains(State::ACTIVE))
458            .with(State::DISABLED, state.contains(State::DISABLED))
459    } else {
460        state
461    };
462    paint_box(ui, r.rect, state);
463    let kit = Kit::of(ui.ctx());
464    let colour = ui
465        .visuals()
466        .override_text_color
467        .unwrap_or(kit.toggle_chip.style(state).text);
468    let mut x = r.rect.left() + padding.x;
469    if let Some(icon) = l.icon {
470        let at = Rect::from_min_size(
471            egui::pos2(x, r.rect.center().y - side / 2.0),
472            Vec2::splat(side),
473        );
474        icon.paint(ui.painter(), at, colour);
475        x += side + gap;
476    }
477    let pos = egui::pos2(x, r.rect.center().y - l.galley.size().y / 2.0);
478    ui.painter().galley(pos, l.galley.clone(), colour);
479}