Skip to main content

iced_cube/navigation/
tabs.rs

1//! Switches between related views that share one place on screen.
2//!
3//! [`State`] owns the tabs and the selection. Its [`update`](State::update)
4//! handles selecting, moving to the next or previous tab with wrap-around,
5//! and skips disabled tabs. The app renders the selected view itself.
6//!
7//! Shortcuts from [`default_keymap`] act only while the tab list has
8//! keyboard focus (Tab reaches it) or was the last thing pressed, so several
9//! on one screen never fight over keys.
10
11use iced::keyboard::key::Named;
12use iced::widget::{self, button::Status, column, container, row, rule, scrollable, text};
13use iced::{Alignment, Background, Border, Color, Element, Length, Shadow, Theme, Vector};
14
15use crate::focus;
16use crate::icon::{Glyph, opacity, themed};
17use crate::keys::{self, Chord, Keymap};
18use crate::natural::natural;
19use crate::theme::{Tokens, fade, mix, radius, space, text_size};
20
21/// How the tab list looks.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
23pub enum Variant {
24    /// Plain labels over a rule, the selected one underlined.
25    #[default]
26    Underline,
27    /// A segmented control, the selected tab raised.
28    Pills,
29}
30
31impl Variant {
32    pub const ALL: [Variant; 2] = [Variant::Underline, Variant::Pills];
33}
34
35/// One tab in a [`State`].
36#[derive(Debug, Clone, PartialEq)]
37pub struct Tab<Id> {
38    pub id: Id,
39    pub label: String,
40    pub icon: Option<Glyph>,
41    pub disabled: bool,
42}
43
44/// Creates an enabled tab.
45pub fn tab<Id>(id: Id, label: impl Into<String>) -> Tab<Id> {
46    Tab {
47        id,
48        label: label.into(),
49        icon: None,
50        disabled: false,
51    }
52}
53
54impl<Id> Tab<Id> {
55    pub fn icon(mut self, glyph: Glyph) -> Self {
56        self.icon = Some(glyph);
57        self
58    }
59
60    pub fn disabled(mut self, disabled: bool) -> Self {
61        self.disabled = disabled;
62        self
63    }
64}
65
66/// Changes to the selection.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum Event<Id> {
69    Select(Id),
70    Next,
71    Previous,
72}
73
74/// The tabs and which one is selected.
75#[derive(Debug, Clone, PartialEq)]
76pub struct State<Id> {
77    tabs: Vec<Tab<Id>>,
78    selected: Option<usize>,
79}
80
81impl<Id: Copy + PartialEq> State<Id> {
82    /// Selects the first enabled tab.
83    pub fn new(tabs: impl IntoIterator<Item = Tab<Id>>) -> Self {
84        let tabs: Vec<_> = tabs.into_iter().collect();
85        let selected = tabs.iter().position(|tab| !tab.disabled);
86        Self { tabs, selected }
87    }
88
89    /// Starts on `id` when it exists and is enabled.
90    pub fn with_selected(mut self, id: Id) -> Self {
91        let _ = self.update(Event::Select(id));
92        self
93    }
94
95    pub fn tabs(&self) -> &[Tab<Id>] {
96        &self.tabs
97    }
98
99    pub fn selected(&self) -> Option<Id> {
100        self.selected.map(|index| self.tabs[index].id)
101    }
102
103    pub fn is_selected(&self, id: Id) -> bool {
104        self.selected() == Some(id)
105    }
106
107    /// Enables or disables a tab. The selection stays where it is.
108    pub fn set_disabled(&mut self, id: Id, disabled: bool) {
109        if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) {
110            tab.disabled = disabled;
111        }
112    }
113
114    /// Applies an event and returns the newly selected id, if it changed.
115    pub fn update(&mut self, event: Event<Id>) -> Option<Id> {
116        let target = match event {
117            Event::Select(id) => self
118                .tabs
119                .iter()
120                .position(|tab| tab.id == id && !tab.disabled),
121            Event::Next => self.step(true),
122            Event::Previous => self.step(false),
123        }?;
124
125        if self.selected == Some(target) {
126            return None;
127        }
128        self.selected = Some(target);
129        Some(self.tabs[target].id)
130    }
131
132    /// The nearest enabled index in one direction, wrapping round.
133    fn step(&self, forward: bool) -> Option<usize> {
134        let len = self.tabs.len();
135        if len == 0 {
136            return None;
137        }
138        let start = self.selected.unwrap_or(if forward { len - 1 } else { 0 });
139        let offset = if forward { 1 } else { len - 1 };
140        (1..=len)
141            .map(|n| (start + offset * n) % len)
142            .find(|&index| !self.tabs[index].disabled)
143    }
144}
145
146/// What a tabs keyboard shortcut does.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148pub enum Action {
149    Next,
150    Previous,
151    First,
152    Last,
153}
154
155impl Action {
156    /// The [`Event`] this action sends to `state`, or `None` when no tab
157    /// is enabled.
158    pub fn event<Id: Copy + PartialEq>(self, state: &State<Id>) -> Option<Event<Id>> {
159        let mut enabled = state.tabs.iter().filter(|tab| !tab.disabled);
160        match self {
161            Action::Next => Some(Event::Next),
162            Action::Previous => Some(Event::Previous),
163            Action::First => enabled.next().map(|tab| Event::Select(tab.id)),
164            Action::Last => enabled.next_back().map(|tab| Event::Select(tab.id)),
165        }
166    }
167}
168
169impl keys::Action for Action {
170    const ALL: &'static [Self] = &[Action::Next, Action::Previous, Action::First, Action::Last];
171
172    fn defaults() -> Keymap<Self> {
173        default_keymap()
174    }
175
176    fn name(self) -> &'static str {
177        match self {
178            Action::Next => "Next",
179            Action::Previous => "Previous",
180            Action::First => "First",
181            Action::Last => "Last",
182        }
183    }
184
185    fn description(self) -> &'static str {
186        match self {
187            Action::Next => "Selects the next enabled tab, wrapping at the end.",
188            Action::Previous => "Selects the previous enabled tab, wrapping at the start.",
189            Action::First => "Selects the first enabled tab.",
190            Action::Last => "Selects the last enabled tab.",
191        }
192    }
193}
194
195/// The default tabs shortcuts:
196///
197/// | Keys | Action |
198/// | --- | --- |
199/// | `Ctrl+Tab`, `ArrowRight` | [`Action::Next`] |
200/// | `Ctrl+Shift+Tab`, `ArrowLeft` | [`Action::Previous`] |
201/// | `Home` | [`Action::First`] |
202/// | `End` | [`Action::Last`] |
203///
204/// The tab list resolves them itself while it has keyboard focus or was the
205/// last thing pressed. Pass a changed keymap with [`Tabs::keymap`]. To
206/// switch tabs with `Ctrl+Tab` from anywhere, the app can also resolve a
207/// keymap from [`keys::subscription`] and send [`Action::event`] to the
208/// state. Document tabs bind `Ctrl+Tab` and `Ctrl+Shift+Tab` too, so an
209/// app routing both should unbind them here or there.
210pub fn default_keymap() -> Keymap<Action> {
211    Keymap::new()
212        .bind(Chord::named(Named::Tab).ctrl(), Action::Next)
213        .bind(Chord::named(Named::ArrowRight), Action::Next)
214        .bind(Chord::named(Named::Tab).ctrl().shift(), Action::Previous)
215        .bind(Chord::named(Named::ArrowLeft), Action::Previous)
216        .bind(Chord::named(Named::Home), Action::First)
217        .bind(Chord::named(Named::End), Action::Last)
218}
219
220/// A tab list builder. Convert it into an [`Element`] to render.
221pub struct Tabs<'a, Id, Message> {
222    state: &'a State<Id>,
223    variant: Variant,
224    width: Option<Length>,
225    keymap: Keymap<Action>,
226    on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
227}
228
229/// Renders the tab list of `state`. Without
230/// [`on_event`](Tabs::on_event) every tab renders disabled.
231pub fn tabs<Id, Message>(state: &State<Id>) -> Tabs<'_, Id, Message> {
232    Tabs {
233        state,
234        variant: Variant::default(),
235        width: None,
236        keymap: default_keymap(),
237        on_event: None,
238    }
239}
240
241impl<Id: std::fmt::Debug, Message> std::fmt::Debug for Tabs<'_, Id, Message> {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        f.debug_struct("Tabs")
244            .field("state", self.state)
245            .field("variant", &self.variant)
246            .field("keymap", &self.keymap)
247            .finish_non_exhaustive()
248    }
249}
250
251impl<'a, Id, Message> Tabs<'a, Id, Message> {
252    pub fn variant(mut self, variant: Variant) -> Self {
253        self.variant = variant;
254        self
255    }
256
257    /// Underline lists fill their row by default, pills shrink to fit.
258    pub fn width(mut self, width: impl Into<Length>) -> Self {
259        self.width = Some(width.into());
260        self
261    }
262
263    pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
264        self.on_event = Some(Box::new(on_event));
265        self
266    }
267
268    /// Replaces the [`default_keymap`] the tab list resolves keys with
269    /// while it has keyboard focus or was the last thing pressed.
270    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
271        self.keymap = keymap;
272        self
273    }
274}
275
276impl<'a, Id, Message> From<Tabs<'a, Id, Message>> for Element<'a, Message>
277where
278    Id: Copy + PartialEq + 'a,
279    Message: Clone + 'a,
280{
281    fn from(tabs: Tabs<'a, Id, Message>) -> Self {
282        let Tabs {
283            state,
284            variant,
285            width,
286            keymap,
287            on_event,
288        } = tabs;
289
290        let items = state.tabs.iter().map(|tab| {
291            let selected = state.is_selected(tab.id);
292            let message = on_event
293                .as_ref()
294                .filter(|_| !tab.disabled)
295                .map(|on_event| on_event(Event::Select(tab.id)));
296            item(tab, variant, selected, message)
297        });
298
299        let list: Element<'a, Message> = match variant {
300            Variant::Underline => column![
301                sideways(row(items).spacing(space::XS)),
302                rule::horizontal(1).style(|theme: &Theme| rule::Style {
303                    color: Tokens::of(theme).border,
304                    radius: 0.0.into(),
305                    fill_mode: rule::FillMode::Full,
306                    snap: true,
307                }),
308            ]
309            .width(width.unwrap_or(Length::Fill))
310            .into(),
311            Variant::Pills => container(sideways(row(items).spacing(space::XS)))
312                .padding(space::XS)
313                .width(width.unwrap_or(Length::Shrink))
314                .style(move |theme| list_style(&Tokens::of(theme), variant))
315                .into(),
316        };
317        let list = match on_event {
318            Some(on_event) => focus::keyed(list, keymap, move |action: Action| {
319                action.event(state).map(&on_event).into_iter().collect()
320            })
321            .radius(radius::MD)
322            .into(),
323            None => list,
324        };
325        #[cfg(feature = "icedwright")]
326        let list = icedwright_probe::semantic(list)
327            .role(icedwright_probe::role::TabList)
328            .component("iced_cube::tabs")
329            .into();
330        list
331    }
332}
333
334/// Lets a tab list wider than its space scroll sideways rather than run off
335/// the edge or squeeze its triggers.
336fn sideways<'a, Message: 'a>(list: widget::Row<'a, Message>) -> widget::Scrollable<'a, Message> {
337    widget::scrollable(list).direction(scrollable::Direction::Horizontal(
338        scrollable::Scrollbar::hidden(),
339    ))
340}
341
342fn item<'a, Id, Message: Clone + 'a>(
343    tab: &'a Tab<Id>,
344    variant: Variant,
345    selected: bool,
346    message: Option<Message>,
347) -> Element<'a, Message> {
348    let enabled = message.is_some();
349    let mut label = row![].spacing(space::SM).align_y(Alignment::Center);
350    if let Some(glyph) = tab.icon {
351        let status = if enabled {
352            Status::Active
353        } else {
354            Status::Disabled
355        };
356        label = label.push(themed(glyph, 16.0, opacity(enabled), move |theme| {
357            foreground(&Tokens::of(theme), selected, status)
358        }));
359    }
360    label = label.push(
361        text(tab.label.as_str())
362            .size(text_size::SM)
363            .wrapping(text::Wrapping::None),
364    );
365
366    let button = widget::button(label)
367        .padding([6.0, space::MD])
368        .on_press_maybe(message)
369        .style(move |theme, status| style(&Tokens::of(theme), variant, selected, status));
370
371    let element = if variant == Variant::Pills {
372        natural(button)
373    } else {
374        natural(
375            column![
376                button,
377                container(iced::widget::space())
378                    .width(Length::Fill)
379                    .height(2)
380                    .style(move |theme| indicator_style(&Tokens::of(theme), selected)),
381            ]
382            .width(Length::Shrink),
383        )
384    };
385    #[cfg(feature = "icedwright")]
386    let element = {
387        let mut annotated = icedwright_probe::semantic(element)
388            .role(icedwright_probe::role::Tab)
389            .name(tab.label.as_str())
390            .selected(selected)
391            .component("iced_cube::tabs");
392        if !enabled {
393            annotated = annotated.disabled(true);
394        }
395        annotated.into()
396    };
397    element
398}
399
400fn foreground(tokens: &Tokens, selected: bool, status: Status) -> Color {
401    let colour = match status {
402        _ if selected => tokens.foreground,
403        Status::Hovered | Status::Pressed => tokens.foreground,
404        _ => tokens.muted_foreground,
405    };
406    if status == Status::Disabled {
407        fade(colour, 0.5)
408    } else {
409        colour
410    }
411}
412
413/// The style of one tab.
414pub fn style(
415    tokens: &Tokens,
416    variant: Variant,
417    selected: bool,
418    status: Status,
419) -> widget::button::Style {
420    let raised = variant == Variant::Pills && selected;
421    let background = raised.then(|| {
422        if tokens.is_dark {
423            mix(tokens.muted, tokens.foreground, 0.12)
424        } else {
425            tokens.background
426        }
427    });
428
429    widget::button::Style {
430        background: background.map(Background::Color),
431        text_color: foreground(tokens, selected, status),
432        border: Border {
433            radius: radius::MD.into(),
434            ..Border::default()
435        },
436        shadow: if raised {
437            Shadow {
438                color: fade(Color::BLACK, 0.1),
439                offset: Vector::new(0.0, 1.0),
440                blur_radius: 3.0,
441            }
442        } else {
443            Shadow::default()
444        },
445        snap: true,
446    }
447}
448
449/// The underline below a tab.
450pub fn indicator_style(tokens: &Tokens, selected: bool) -> container::Style {
451    container::Style {
452        background: selected.then_some(Background::Color(tokens.foreground)),
453        ..container::Style::default()
454    }
455}
456
457/// The container around the tab list.
458pub fn list_style(tokens: &Tokens, variant: Variant) -> container::Style {
459    match variant {
460        Variant::Underline => container::Style::default(),
461        Variant::Pills => container::Style {
462            background: Some(Background::Color(tokens.muted)),
463            border: Border {
464                radius: radius::LG.into(),
465                ..Border::default()
466            },
467            ..container::Style::default()
468        },
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use crate::theme::{dark, light};
476
477    fn state() -> State<u8> {
478        State::new([
479            tab(0, "A"),
480            tab(1, "B").disabled(true),
481            tab(2, "C"),
482            tab(3, "D"),
483        ])
484    }
485
486    #[test]
487    fn new_selects_first_enabled_tab() {
488        assert_eq!(state().selected(), Some(0));
489        let skipped = State::new([tab(0, "A").disabled(true), tab(1, "B")]);
490        assert_eq!(skipped.selected(), Some(1));
491    }
492
493    #[test]
494    fn empty_and_all_disabled_have_no_selection() {
495        let mut empty: State<u8> = State::new([]);
496        assert_eq!(empty.selected(), None);
497        assert_eq!(empty.update(Event::Next), None);
498        assert_eq!(empty.update(Event::Previous), None);
499
500        let mut disabled = State::new([tab(0, "A").disabled(true)]);
501        assert_eq!(disabled.selected(), None);
502        assert_eq!(disabled.update(Event::Next), None);
503    }
504
505    #[test]
506    fn select_ignores_disabled_unknown_and_current() {
507        let mut state = state();
508        assert_eq!(state.update(Event::Select(1)), None);
509        assert_eq!(state.update(Event::Select(9)), None);
510        assert_eq!(state.update(Event::Select(0)), None);
511        assert_eq!(state.update(Event::Select(3)), Some(3));
512        assert_eq!(state.selected(), Some(3));
513    }
514
515    #[test]
516    fn next_skips_disabled_and_wraps() {
517        let mut state = state();
518        assert_eq!(state.update(Event::Next), Some(2));
519        assert_eq!(state.update(Event::Next), Some(3));
520        assert_eq!(state.update(Event::Next), Some(0));
521    }
522
523    #[test]
524    fn previous_skips_disabled_and_wraps() {
525        let mut state = state();
526        assert_eq!(state.update(Event::Previous), Some(3));
527        assert_eq!(state.update(Event::Previous), Some(2));
528        assert_eq!(state.update(Event::Previous), Some(0));
529    }
530
531    #[test]
532    fn single_enabled_tab_never_moves() {
533        let mut state = State::new([tab(0, "A"), tab(1, "B").disabled(true)]);
534        assert_eq!(state.update(Event::Next), None);
535        assert_eq!(state.update(Event::Previous), None);
536        assert_eq!(state.selected(), Some(0));
537    }
538
539    #[test]
540    fn with_selected_and_set_disabled() {
541        let mut state = state().with_selected(2);
542        assert_eq!(state.selected(), Some(2));
543        state.set_disabled(1, false);
544        assert_eq!(state.update(Event::Previous), Some(1));
545    }
546
547    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
548        let chord: Chord = chord.parse().unwrap();
549        keymap.resolve(chord.key(), chord.modifiers())
550    }
551
552    #[test]
553    fn default_keymap_covers_every_action() {
554        let keymap = default_keymap();
555        assert_eq!(press(&keymap, "Ctrl+Tab"), Some(Action::Next));
556        assert_eq!(press(&keymap, "ArrowRight"), Some(Action::Next));
557        assert_eq!(press(&keymap, "Ctrl+Shift+Tab"), Some(Action::Previous));
558        assert_eq!(press(&keymap, "ArrowLeft"), Some(Action::Previous));
559        assert_eq!(press(&keymap, "Home"), Some(Action::First));
560        assert_eq!(press(&keymap, "End"), Some(Action::Last));
561        assert_eq!(press(&keymap, "Tab"), None);
562        for action in <Action as keys::Action>::ALL {
563            assert!(!keymap.chords(action).is_empty(), "{action:?}");
564        }
565        assert_eq!(Keymap::<Action>::defaults(), keymap);
566    }
567
568    #[test]
569    fn keymap_overrides_and_unbinding() {
570        let keymap = default_keymap()
571            .unbind(&"ArrowRight".parse().unwrap())
572            .unbind(&"ArrowLeft".parse().unwrap())
573            .bind("Ctrl+PageDown".parse().unwrap(), Action::Next);
574        assert_eq!(press(&keymap, "ArrowRight"), None);
575        assert_eq!(press(&keymap, "Ctrl+PageDown"), Some(Action::Next));
576        assert_eq!(press(&keymap, "Ctrl+Tab"), Some(Action::Next));
577    }
578
579    #[test]
580    fn actions_map_to_events() {
581        let mut state = state().with_selected(2);
582        assert_eq!(Action::Next.event(&state), Some(Event::Next));
583        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
584        assert_eq!(Action::First.event(&state), Some(Event::Select(0)));
585        assert_eq!(Action::Last.event(&state), Some(Event::Select(3)));
586
587        let event = Action::First.event(&state).unwrap();
588        assert_eq!(state.update(event), Some(0));
589
590        let disabled = State::new([tab(0, "A").disabled(true)]);
591        assert_eq!(Action::First.event(&disabled), None);
592        assert_eq!(Action::Last.event(&disabled), None);
593    }
594
595    #[test]
596    fn first_and_last_skip_disabled_tabs() {
597        let state = State::new([
598            tab(0, "A").disabled(true),
599            tab(1, "B"),
600            tab(2, "C"),
601            tab(3, "D").disabled(true),
602        ]);
603        assert_eq!(Action::First.event(&state), Some(Event::Select(1)));
604        assert_eq!(Action::Last.event(&state), Some(Event::Select(2)));
605    }
606
607    #[test]
608    fn selected_tab_is_emphasised_in_both_themes() {
609        for theme in [light(), dark()] {
610            let tokens = Tokens::of(&theme);
611            for variant in Variant::ALL {
612                let on = style(&tokens, variant, true, Status::Active);
613                let off = style(&tokens, variant, false, Status::Active);
614                assert_eq!(on.text_color, tokens.foreground);
615                assert_eq!(off.text_color, tokens.muted_foreground);
616            }
617        }
618    }
619
620    #[test]
621    fn only_selected_pill_is_raised() {
622        let tokens = Tokens::of(&light());
623        assert!(
624            style(&tokens, Variant::Pills, true, Status::Active)
625                .background
626                .is_some()
627        );
628        assert!(
629            style(&tokens, Variant::Pills, false, Status::Active)
630                .background
631                .is_none()
632        );
633        assert!(
634            style(&tokens, Variant::Underline, true, Status::Active)
635                .background
636                .is_none()
637        );
638    }
639
640    #[test]
641    fn hover_and_disabled_change_the_label_colour() {
642        let tokens = Tokens::of(&dark());
643        let hovered = style(&tokens, Variant::Underline, false, Status::Hovered);
644        let disabled = style(&tokens, Variant::Underline, false, Status::Disabled);
645        assert_eq!(hovered.text_color, tokens.foreground);
646        assert!(disabled.text_color.a < tokens.muted_foreground.a);
647    }
648
649    #[test]
650    fn indicator_and_list_styles() {
651        let tokens = Tokens::of(&light());
652        assert!(indicator_style(&tokens, true).background.is_some());
653        assert!(indicator_style(&tokens, false).background.is_none());
654        assert!(list_style(&tokens, Variant::Pills).background.is_some());
655        assert!(list_style(&tokens, Variant::Underline).background.is_none());
656    }
657}