Skip to main content

iced_cube/navigation/
bottom_nav.rs

1//! A bar of three to five destinations along the bottom of a phone screen.
2//!
3//! Each destination is an icon above a short label, sharing the width
4//! equally. The active one sits on a pill. The app owns which destination
5//! is active and changes it in `on_select`; selecting the active one sends
6//! `on_select` too, which apps use to go back to the top of that screen.
7//!
8//! Destinations respond to taps without capturing the finger, as a
9//! [`tappable`](mod@crate::primitives::tappable) does.
10//!
11//! Keyboard shortcuts resolve through a [`Keymap`] of [`Action`]s; see
12//! [`default_keymap`] and [`crate::keys`].
13//!
14//! ```no_run
15//! use iced_cube::{bottom_nav, lucide};
16//!
17//! #[derive(Debug, Clone, Copy, PartialEq)]
18//! enum Screen { Notes, Search, Settings }
19//!
20//! #[derive(Debug, Clone)]
21//! enum Message { Go(Screen) }
22//!
23//! let bar: iced::Element<'_, Message> = bottom_nav(Screen::Notes)
24//!     .item(Screen::Notes, lucide!(NotebookText), "Notes")
25//!     .item(Screen::Search, lucide!(Search), "Search")
26//!     .item(Screen::Settings, lucide!(Settings), "Settings")
27//!     .on_select(Message::Go)
28//!     .into();
29//! ```
30
31use std::fmt;
32
33use iced::widget::{column, container, row, space, text};
34use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Theme};
35
36use crate::icon::{Glyph, opacity, themed};
37use crate::keys::{self, Chord, Keymap};
38use crate::primitives::tappable::{self, Status, tappable};
39use crate::theme::{Tokens, fade, mix, radius, text_size};
40
41/// Height of the bar above any inset, its top border included.
42pub const HEIGHT: f32 = 80.0;
43/// Size of the pill behind the active icon.
44pub const PILL: (f32, f32) = (64.0, 32.0);
45/// Icon size.
46pub const ICON: f32 = 24.0;
47/// Label size.
48pub const LABEL: f32 = text_size::XS;
49/// The narrowest a destination gets: a comfortable touch target.
50pub const MIN_SLOT_WIDTH: f32 = 48.0;
51/// The most destinations a bar shows. Later items are dropped.
52pub const MAX_ITEMS: usize = 5;
53
54/// One destination.
55#[derive(Debug, Clone, PartialEq)]
56pub struct Item<Id> {
57    pub id: Id,
58    pub glyph: Glyph,
59    pub label: String,
60}
61
62/// A bottom navigation builder. Convert it into an [`Element`] to render.
63///
64/// Without [`on_select`](BottomNav::on_select) the destinations do nothing
65/// and are drawn faded.
66pub struct BottomNav<'a, Id, Message> {
67    active: Id,
68    items: Vec<Item<Id>>,
69    on_select: Option<Box<dyn Fn(Id) -> Message + 'a>>,
70    inset: f32,
71}
72
73/// Creates a bar with `active` as the current destination.
74pub fn bottom_nav<'a, Id: Copy + PartialEq, Message>(active: Id) -> BottomNav<'a, Id, Message> {
75    BottomNav {
76        active,
77        items: Vec::new(),
78        on_select: None,
79        inset: 0.0,
80    }
81}
82
83impl<Id: fmt::Debug, Message> fmt::Debug for BottomNav<'_, Id, Message> {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.debug_struct("BottomNav")
86            .field("active", &self.active)
87            .field("items", &self.items)
88            .field("enabled", &self.on_select.is_some())
89            .field("inset", &self.inset)
90            .finish()
91    }
92}
93
94impl<'a, Id: Copy + PartialEq, Message> BottomNav<'a, Id, Message> {
95    /// Adds a destination. Use three to five; past five the rest are not
96    /// shown.
97    pub fn item(mut self, id: Id, glyph: Glyph, label: impl Into<String>) -> Self {
98        self.items.push(Item {
99            id,
100            glyph,
101            label: label.into(),
102        });
103        self
104    }
105
106    /// The message for selecting a destination, the active one included.
107    pub fn on_select(mut self, on_select: impl Fn(Id) -> Message + 'a) -> Self {
108        self.on_select = Some(Box::new(on_select));
109        self
110    }
111
112    /// Extra space below the destinations, such as the height of a system
113    /// navigation bar drawn over the window. Defaults to 0.
114    pub fn inset(mut self, bottom: f32) -> Self {
115        self.inset = bottom.max(0.0);
116        self
117    }
118
119    pub fn items(&self) -> &[Item<Id>] {
120        &self.items
121    }
122
123    pub fn is_enabled(&self) -> bool {
124        self.on_select.is_some()
125    }
126}
127
128impl<'a, Id, Message> From<BottomNav<'a, Id, Message>> for Element<'a, Message>
129where
130    Id: Copy + PartialEq + 'a,
131    Message: Clone + 'a,
132{
133    fn from(nav: BottomNav<'a, Id, Message>) -> Self {
134        let BottomNav {
135            active,
136            items,
137            on_select,
138            inset,
139        } = nav;
140        let enabled = on_select.is_some();
141
142        let slots = items.into_iter().take(MAX_ITEMS).map(|item| {
143            let on = item.id == active;
144            let message = on_select.as_ref().map(|on_select| on_select(item.id));
145            slot(item, on, enabled, message)
146        });
147
148        let border = container(space())
149            .width(Length::Fill)
150            .height(1)
151            .style(|theme: &Theme| container::Style {
152                background: Some(Background::Color(Tokens::of(theme).border)),
153                ..container::Style::default()
154            });
155
156        let bar: Element<'a, Message> = container(column![
157            border,
158            row(slots).width(Length::Fill).height(HEIGHT - 1.0)
159        ])
160        .width(Length::Fill)
161        .padding(Padding {
162            bottom: inset,
163            ..Padding::ZERO
164        })
165        .style(|theme: &Theme| bar_style(&Tokens::of(theme)))
166        .into();
167        #[cfg(feature = "icedwright")]
168        let bar = icedwright_probe::semantic(bar)
169            .role(icedwright_probe::role::Navigation)
170            .component("iced_cube::bottom_nav")
171            .into();
172        bar
173    }
174}
175
176fn slot<'a, Id, Message: Clone + 'a>(
177    item: Item<Id>,
178    on: bool,
179    enabled: bool,
180    message: Option<Message>,
181) -> Element<'a, Message> {
182    #[cfg(feature = "icedwright")]
183    let name = item.label.clone();
184    let icon = themed(item.glyph, ICON, opacity(enabled), move |theme| {
185        colours(&Tokens::of(theme), on).icon
186    });
187    let pill = container(icon)
188        .center_x(PILL.0)
189        .center_y(PILL.1)
190        .style(move |theme: &Theme| pill_style(&Tokens::of(theme), on));
191    let label = text(item.label)
192        .size(LABEL)
193        .font(if on {
194            crate::theme::semibold()
195        } else {
196            crate::theme::font()
197        })
198        .wrapping(text::Wrapping::None)
199        .style(move |theme: &Theme| {
200            let colour = colours(&Tokens::of(theme), on).label;
201            text::Style {
202                color: Some(if enabled { colour } else { fade(colour, 0.5) }),
203            }
204        });
205
206    let content = container(column![pill, label].spacing(4).align_x(Alignment::Center))
207        .width(Length::Fill)
208        .height(Length::Fill)
209        .align_x(Alignment::Center)
210        .align_y(Alignment::Center)
211        .clip(true);
212
213    let mut slot = tappable(content)
214        .width(Length::FillPortion(1))
215        .height(Length::Fill)
216        .style(|theme, status| slot_style(&Tokens::of(theme), status));
217    if let Some(message) = message {
218        slot = slot.on_tap(message);
219    }
220    let slot: Element<'a, Message> = slot.into();
221    #[cfg(feature = "icedwright")]
222    let slot = {
223        let mut annotated = icedwright_probe::semantic(slot)
224            .role(icedwright_probe::role::Link)
225            .name(name)
226            .current(on)
227            .component("iced_cube::bottom_nav");
228        if !enabled {
229            annotated = annotated.disabled(true);
230        }
231        annotated.into()
232    };
233    slot
234}
235
236/// Icon and label colours of a destination.
237#[derive(Debug, Clone, Copy, PartialEq)]
238pub struct Colours {
239    pub icon: Color,
240    pub label: Color,
241}
242
243/// The active destination's icon reads on its pill and its label in full
244/// foreground; the others are muted but readable in both themes.
245pub fn colours(tokens: &Tokens, active: bool) -> Colours {
246    if active {
247        return Colours {
248            icon: tokens.accent_foreground,
249            label: tokens.foreground,
250        };
251    }
252    Colours {
253        icon: tokens.muted_foreground,
254        label: tokens.muted_foreground,
255    }
256}
257
258/// The pill behind the active icon, and nothing behind the others. It takes
259/// the accent pulled towards the foreground, as a selected segment of an
260/// outlined toggle group does, so it stands out in dark themes too.
261pub fn pill_style(tokens: &Tokens, active: bool) -> container::Style {
262    container::Style {
263        background: active.then_some(Background::Color(mix(
264            tokens.accent,
265            tokens.foreground,
266            0.1,
267        ))),
268        border: Border {
269            radius: radius::FULL.into(),
270            ..Border::default()
271        },
272        ..container::Style::default()
273    }
274}
275
276/// A destination's touch feedback: a faint wash of the foreground on hover
277/// and a stronger one while pressed, visible on any bar colour.
278pub fn slot_style(tokens: &Tokens, status: Status) -> container::Style {
279    let alpha = match status {
280        Status::Active => return container::Style::default(),
281        Status::Hovered => 0.04,
282        Status::Pressed => 0.1,
283    };
284    container::Style {
285        background: Some(Background::Color(fade(tokens.foreground, alpha))),
286        ..tappable::style(tokens, status)
287    }
288}
289
290/// The bar itself.
291pub fn bar_style(tokens: &Tokens) -> container::Style {
292    container::Style {
293        background: Some(Background::Color(tokens.background)),
294        text_color: Some(tokens.foreground),
295        ..container::Style::default()
296    }
297}
298
299/// What a bottom navigation keyboard shortcut does: go to the destination
300/// at an index, counting from zero.
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
302pub enum Action {
303    Go(usize),
304}
305
306impl Action {
307    /// The destination to send through the bar's `on_select` message, if
308    /// there is one at this action's index.
309    pub fn apply<Id: Copy>(self, ids: &[Id]) -> Option<Id> {
310        let Action::Go(index) = self;
311        ids.get(index).copied()
312    }
313}
314
315impl keys::Action for Action {
316    const ALL: &'static [Self] = &[
317        Action::Go(0),
318        Action::Go(1),
319        Action::Go(2),
320        Action::Go(3),
321        Action::Go(4),
322    ];
323
324    fn defaults() -> Keymap<Self> {
325        default_keymap()
326    }
327
328    fn name(self) -> &'static str {
329        match self {
330            Action::Go(0) => "First",
331            Action::Go(1) => "Second",
332            Action::Go(2) => "Third",
333            Action::Go(3) => "Fourth",
334            Action::Go(_) => "Fifth",
335        }
336    }
337
338    fn description(self) -> &'static str {
339        match self {
340            Action::Go(0) => "Selects the first destination.",
341            Action::Go(1) => "Selects the second destination.",
342            Action::Go(2) => "Selects the third destination.",
343            Action::Go(3) => "Selects the fourth destination.",
344            Action::Go(_) => "Selects the fifth destination.",
345        }
346    }
347}
348
349/// The default bottom navigation shortcuts:
350///
351/// | Keys | Action |
352/// | --- | --- |
353/// | `Alt+1` to `Alt+5` | [`Action::Go`] with index 0 to 4 |
354///
355/// Ctrl and a number belong to document tabs, so the bar uses Alt. Some
356/// browsers keep Alt and a number for their own tabs, so a web build may
357/// never receive these; rebind them there.
358pub fn default_keymap() -> Keymap<Action> {
359    ['1', '2', '3', '4', '5']
360        .into_iter()
361        .enumerate()
362        .fold(Keymap::new(), |keymap, (index, key)| {
363            keymap.bind(Chord::character(key).alt(), Action::Go(index))
364        })
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use crate::theme::{dark, light};
371
372    #[test]
373    fn builder_defaults() {
374        let nav: BottomNav<'_, u8, ()> = bottom_nav(0);
375        assert!(nav.items().is_empty());
376        assert!(!nav.is_enabled());
377        assert_eq!(nav.inset, 0.0);
378        let nav: BottomNav<'_, u8, u8> = bottom_nav(1)
379            .item(0, crate::lucide!(House), "Home")
380            .item(1, crate::lucide!(Search), "Search")
381            .inset(-4.0)
382            .on_select(|id| id);
383        assert_eq!(nav.items().len(), 2);
384        assert_eq!(nav.items()[1].label, "Search");
385        assert!(nav.is_enabled());
386        assert_eq!(nav.inset, 0.0);
387    }
388
389    #[test]
390    fn the_active_destination_stands_out_in_both_themes() {
391        for theme in [light(), dark()] {
392            let tokens = Tokens::of(&theme);
393            let on = colours(&tokens, true);
394            let off = colours(&tokens, false);
395            assert_ne!(on.label, off.label);
396            assert_eq!(off.label, tokens.muted_foreground);
397            assert!(pill_style(&tokens, false).background.is_none());
398            let Some(Background::Color(pill)) = pill_style(&tokens, true).background else {
399                panic!("the active pill has no fill");
400            };
401            let distance = |colour: Color| {
402                let lightness = |c: Color| (c.r + c.g + c.b) / 3.0;
403                (lightness(colour) - lightness(tokens.background)).abs()
404            };
405            assert!(distance(pill) > distance(tokens.accent), "{theme:?}");
406        }
407    }
408
409    #[test]
410    fn inactive_labels_are_readable_in_dark_mode() {
411        let tokens = Tokens::of(&dark());
412        let label = colours(&tokens, false).label;
413        let lightness = (label.r + label.g + label.b) / 3.0;
414        let background = (tokens.background.r + tokens.background.g + tokens.background.b) / 3.0;
415        assert!(lightness - background > 0.4, "{label:?}");
416    }
417
418    #[test]
419    fn slot_feedback_is_clear_at_rest_and_stronger_when_pressed() {
420        for theme in [light(), dark()] {
421            let tokens = Tokens::of(&theme);
422            assert!(slot_style(&tokens, Status::Active).background.is_none());
423            let alpha = |status| match slot_style(&tokens, status).background {
424                Some(Background::Color(colour)) => colour.a,
425                _ => 0.0,
426            };
427            assert!(alpha(Status::Pressed) > alpha(Status::Hovered));
428            assert!(alpha(Status::Hovered) > 0.0);
429        }
430    }
431
432    #[test]
433    fn the_bar_uses_the_background() {
434        let tokens = Tokens::of(&light());
435        assert_eq!(
436            bar_style(&tokens).background,
437            Some(Background::Color(tokens.background))
438        );
439    }
440
441    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
442        let chord: Chord = chord.parse().unwrap();
443        keymap.resolve(chord.key(), chord.modifiers())
444    }
445
446    #[test]
447    fn default_keymap_covers_every_action() {
448        let keymap = default_keymap();
449        assert_eq!(press(&keymap, "Alt+1"), Some(Action::Go(0)));
450        assert_eq!(press(&keymap, "Alt+5"), Some(Action::Go(4)));
451        assert_eq!(press(&keymap, "1"), None);
452        for action in <Action as keys::Action>::ALL {
453            assert!(!keymap.chords(action).is_empty(), "{action:?}");
454        }
455        assert_eq!(Keymap::<Action>::defaults(), keymap);
456    }
457
458    #[test]
459    fn keymap_overrides_and_unbinding() {
460        let keymap = default_keymap()
461            .unbind(&Chord::character('1').alt())
462            .bind("Ctrl+1".parse().unwrap(), Action::Go(0));
463        assert_eq!(press(&keymap, "Alt+1"), None);
464        assert_eq!(press(&keymap, "Ctrl+1"), Some(Action::Go(0)));
465    }
466
467    #[test]
468    fn actions_pick_the_destination_at_their_index() {
469        let ids = ['a', 'b', 'c'];
470        assert_eq!(Action::Go(0).apply(&ids), Some('a'));
471        assert_eq!(Action::Go(2).apply(&ids), Some('c'));
472        assert_eq!(Action::Go(4).apply(&ids), None);
473    }
474}