Skip to main content

iced_cube/navigation/
breadcrumb.rs

1//! Shows where the current view sits in a hierarchy, with a link to each
2//! level above it.
3//!
4//! The last crumb is the current view and never responds to clicks. Crumbs
5//! before it are links when they have a message. A long trail collapses its
6//! middle into an ellipsis with [`max_items`](Breadcrumb::max_items); see
7//! [`slots`]. A trail too wide for one line hides more of its middle until
8//! it fits, unless [`collapse_to_fit`](Breadcrumb::collapse_to_fit) is off.
9//!
10//! Keyboard shortcuts resolve through a [`Keymap`] of [`Action`]s; see
11//! [`default_keymap`] and [`crate::keys`].
12
13use iced::keyboard::key::Named;
14use iced::widget::{self, button::Status, container, row, text};
15use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Shadow, Theme};
16
17use crate::fit::first_fit;
18use crate::icon::{Glyph, themed};
19use crate::keys::{self, Chord, Keymap};
20use crate::lucide;
21use crate::theme::{Tokens, mix, radius, text_size};
22
23const ICON_SIZE: f32 = 14.0;
24
25/// What goes between two crumbs.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
27pub enum Separator {
28    #[default]
29    Chevron,
30    Slash,
31}
32
33impl Separator {
34    pub const ALL: [Separator; 2] = [Separator::Chevron, Separator::Slash];
35}
36
37/// One place in a rendered trail.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum Slot {
40    /// The crumb at this index.
41    Crumb(usize),
42    /// Crumbs left out of the middle.
43    Ellipsis,
44}
45
46/// The crumbs to show for a trail of `len`, keeping at most `max` of them.
47///
48/// The first crumb and the last `max - 1` stay, with an ellipsis for the
49/// rest, so the root and the levels nearest the current view remain one
50/// click away. `max` is at least 2. `None` shows every crumb.
51pub fn slots(len: usize, max: Option<usize>) -> Vec<Slot> {
52    let max = max.map_or(len, |max| max.max(2));
53    if len <= max {
54        return (0..len).map(Slot::Crumb).collect();
55    }
56    let tail = max - 1;
57    let mut slots = vec![Slot::Crumb(0), Slot::Ellipsis];
58    slots.extend((len - tail..len).map(Slot::Crumb));
59    slots
60}
61
62/// One level in a [`Breadcrumb`].
63#[derive(Debug, Clone)]
64pub struct Crumb<'a, Message> {
65    label: text::Fragment<'a>,
66    icon: Option<Glyph>,
67    on_press: Option<Message>,
68}
69
70/// Creates a crumb with a text label. Add a message with
71/// [`on_press`](Crumb::on_press) to make it a link.
72pub fn crumb<'a, Message>(label: impl text::IntoFragment<'a>) -> Crumb<'a, Message> {
73    Crumb {
74        label: label.into_fragment(),
75        icon: None,
76        on_press: None,
77    }
78}
79
80impl<Message> Crumb<'_, Message> {
81    /// Adds an icon before the label, such as a house for the root.
82    pub fn icon(mut self, glyph: Glyph) -> Self {
83        self.icon = Some(glyph);
84        self
85    }
86
87    pub fn on_press(mut self, message: Message) -> Self {
88        self.on_press = Some(message);
89        self
90    }
91
92    pub fn on_press_maybe(mut self, message: Option<Message>) -> Self {
93        self.on_press = message;
94        self
95    }
96
97    pub fn is_link(&self) -> bool {
98        self.on_press.is_some()
99    }
100}
101
102/// A breadcrumb trail builder. Convert it into an [`Element`] to render.
103#[derive(Debug)]
104pub struct Breadcrumb<'a, Message> {
105    crumbs: Vec<Crumb<'a, Message>>,
106    separator: Separator,
107    max_items: Option<usize>,
108    on_expand: Option<Message>,
109    collapse_to_fit: bool,
110}
111
112/// Creates a trail from the root to the current view, in that order.
113pub fn breadcrumb<'a, Message>(
114    crumbs: impl IntoIterator<Item = Crumb<'a, Message>>,
115) -> Breadcrumb<'a, Message> {
116    Breadcrumb {
117        crumbs: crumbs.into_iter().collect(),
118        separator: Separator::default(),
119        max_items: None,
120        on_expand: None,
121        collapse_to_fit: true,
122    }
123}
124
125/// The crumb limits to try, longest first, when the trail must fit on one
126/// line: the requested limit (or every crumb), then one fewer at a time
127/// down to the first crumb and the current one.
128pub fn fit_limits(len: usize, max: Option<usize>) -> Vec<usize> {
129    let start = max.map_or(len, |max| max.max(2)).min(len);
130    if start <= 2 {
131        return vec![start];
132    }
133    (2..=start).rev().collect()
134}
135
136impl<Message> Breadcrumb<'_, Message> {
137    pub fn separator(mut self, separator: Separator) -> Self {
138        self.separator = separator;
139        self
140    }
141
142    /// Shows at most `max` crumbs, collapsing the middle into an ellipsis.
143    pub fn max_items(mut self, max: usize) -> Self {
144        self.max_items = Some(max);
145        self
146    }
147
148    /// Makes the ellipsis a button that sends `message`, such as one that
149    /// lifts the limit to show the whole trail.
150    pub fn on_expand(mut self, message: Message) -> Self {
151        self.on_expand = Some(message);
152        self
153    }
154
155    /// Whether a trail too wide for one line collapses more of its middle
156    /// until it fits, before it wraps. Defaults to `true`. Turn it off to
157    /// show every crumb on as many lines as it takes, such as after the
158    /// reader expands the trail.
159    pub fn collapse_to_fit(mut self, collapse: bool) -> Self {
160        self.collapse_to_fit = collapse;
161        self
162    }
163
164    pub fn len(&self) -> usize {
165        self.crumbs.len()
166    }
167
168    pub fn is_empty(&self) -> bool {
169        self.crumbs.is_empty()
170    }
171}
172
173impl<'a, Message: Clone + 'a> From<Breadcrumb<'a, Message>> for Element<'a, Message> {
174    fn from(breadcrumb: Breadcrumb<'a, Message>) -> Self {
175        let Breadcrumb {
176            crumbs,
177            separator,
178            max_items,
179            on_expand,
180            collapse_to_fit,
181        } = breadcrumb;
182        let len = crumbs.len();
183        if !collapse_to_fit {
184            return navigation(list(
185                trail(&crumbs, separator, max_items, &on_expand)
186                    .wrap()
187                    .into(),
188            ));
189        }
190
191        // Each shorter trail is tried in turn; the shortest wraps if even
192        // it is too wide.
193        let limits = fit_limits(len, max_items);
194        let last = limits.len().saturating_sub(1);
195        let candidates = limits
196            .into_iter()
197            .enumerate()
198            .map(|(index, max)| {
199                let trail = trail(&crumbs, separator, Some(max), &on_expand);
200                if index == last {
201                    list(trail.wrap().into())
202                } else {
203                    list(trail.into())
204                }
205            })
206            .collect();
207        navigation(first_fit(candidates))
208    }
209}
210
211#[cfg(feature = "icedwright")]
212fn navigation<'a, Message: 'a>(trail: Element<'a, Message>) -> Element<'a, Message> {
213    icedwright_probe::semantic(trail)
214        .role(icedwright_probe::role::Navigation)
215        .name("Breadcrumb")
216        .component("iced_cube::breadcrumb")
217        .into()
218}
219
220#[cfg(not(feature = "icedwright"))]
221fn navigation<Message>(trail: Element<'_, Message>) -> Element<'_, Message> {
222    trail
223}
224
225#[cfg(feature = "icedwright")]
226fn list<'a, Message: 'a>(trail: Element<'a, Message>) -> Element<'a, Message> {
227    icedwright_probe::semantic(trail)
228        .role(icedwright_probe::role::List)
229        .component("iced_cube::breadcrumb")
230        .into()
231}
232
233#[cfg(not(feature = "icedwright"))]
234fn list<Message>(trail: Element<'_, Message>) -> Element<'_, Message> {
235    trail
236}
237
238/// One row of crumbs, showing at most `max` of them.
239fn trail<'a, Message: Clone + 'a>(
240    crumbs: &[Crumb<'a, Message>],
241    separator: Separator,
242    max: Option<usize>,
243    on_expand: &Option<Message>,
244) -> iced::widget::Row<'a, Message> {
245    let len = crumbs.len();
246    let mut trail = row![].spacing(6).align_y(Alignment::Center);
247    let mut first = true;
248    for slot in slots(len, max) {
249        let element = match slot {
250            Slot::Crumb(at) => {
251                let Some(crumb) = crumbs.get(at) else {
252                    continue;
253                };
254                item(crumb.clone(), at + 1 == len)
255            }
256            Slot::Ellipsis => ellipsis(on_expand.clone()),
257        };
258        // A divider travels with the crumb after it, so a wrapped trail
259        // never ends a line on a separator.
260        if first {
261            trail = trail.push(element);
262        } else {
263            trail = trail.push(
264                row![divider(separator), element]
265                    .spacing(6)
266                    .align_y(Alignment::Center),
267            );
268        }
269        first = false;
270    }
271    trail
272}
273
274fn item<'a, Message: Clone + 'a>(crumb: Crumb<'a, Message>, current: bool) -> Element<'a, Message> {
275    let Crumb {
276        label,
277        icon,
278        on_press,
279    } = crumb;
280    let message = on_press.filter(|_| !current);
281
282    #[cfg(feature = "icedwright")]
283    let link = message.is_some();
284    #[cfg(feature = "icedwright")]
285    let name = label.clone();
286    let element = crumb_element(label, icon, message, current);
287    #[cfg(feature = "icedwright")]
288    let element = {
289        let mut annotated = icedwright_probe::semantic(element)
290            .role(icedwright_probe::role::Link)
291            .name(name)
292            .current(current)
293            .component("iced_cube::breadcrumb");
294        if !link && !current {
295            annotated = annotated.disabled(true);
296        }
297        annotated.into()
298    };
299    element
300}
301
302fn crumb_element<'a, Message: Clone + 'a>(
303    label: text::Fragment<'a>,
304    icon: Option<Glyph>,
305    message: Option<Message>,
306    current: bool,
307) -> Element<'a, Message> {
308    let link = message.is_some();
309    let content = |status: Status| {
310        let mut content = row![].spacing(6).align_y(Alignment::Center);
311        if let Some(glyph) = icon {
312            content = content.push(themed(glyph, ICON_SIZE, 1.0, move |theme| {
313                foreground(&Tokens::of(theme), current, link, status)
314            }));
315        }
316        content.push(
317            text(label.clone())
318                .size(text_size::SM)
319                .wrapping(text::Wrapping::None),
320        )
321    };
322
323    let Some(message) = message else {
324        return container(content(Status::Active))
325            .padding(Padding::from([2.0, 0.0]))
326            .style(move |theme: &Theme| container::Style {
327                text_color: Some(foreground(
328                    &Tokens::of(theme),
329                    current,
330                    false,
331                    Status::Active,
332                )),
333                ..container::Style::default()
334            })
335            .into();
336    };
337    // The icon is drawn twice so it follows the label's hover colour: iced
338    // tints an svg by its own hover state, not its button's.
339    widget::button(widget::hover(
340        content(Status::Active),
341        content(Status::Hovered),
342    ))
343    .padding(Padding::from([2.0, 0.0]))
344    .on_press(message)
345    .style(|theme, status| style(&Tokens::of(theme), status))
346    .into()
347}
348
349fn divider<'a, Message: 'a>(separator: Separator) -> Element<'a, Message> {
350    let colour = |theme: &Theme| Tokens::of(theme).muted_foreground;
351    match separator {
352        Separator::Chevron => themed(lucide!(ChevronRight), ICON_SIZE, 1.0, colour).into(),
353        Separator::Slash => text("/")
354            .size(text_size::SM)
355            .style(move |theme: &Theme| text::Style {
356                color: Some(colour(theme)),
357            })
358            .into(),
359    }
360}
361
362fn ellipsis<'a, Message: Clone + 'a>(on_expand: Option<Message>) -> Element<'a, Message> {
363    let glyph = |status| {
364        themed(lucide!(Ellipsis), 16.0, 1.0, move |theme| {
365            foreground(&Tokens::of(theme), false, true, status)
366        })
367    };
368    let Some(message) = on_expand else {
369        let element: Element<'a, Message> = container(glyph(Status::Active))
370            .center_y(Length::Fixed(24.0))
371            .into();
372        #[cfg(feature = "icedwright")]
373        let element = icedwright_probe::semantic(element)
374            .role(icedwright_probe::role::Button)
375            .name("Show path")
376            .disabled(true)
377            .component("iced_cube::breadcrumb")
378            .into();
379        return element;
380    };
381    let element: Element<'a, Message> = widget::button(glyph(Status::Active))
382        .padding(Padding::from([4.0, 2.0]))
383        .on_press(message)
384        .style(|theme, status| ellipsis_style(&Tokens::of(theme), status))
385        .into();
386    #[cfg(feature = "icedwright")]
387    let element = icedwright_probe::semantic(element)
388        .role(icedwright_probe::role::Button)
389        .name("Show path")
390        .component("iced_cube::breadcrumb")
391        .into();
392    element
393}
394
395/// The text colour of a crumb: the current one in the foreground colour,
396/// the levels above it muted until a link is hovered.
397pub fn foreground(tokens: &Tokens, current: bool, link: bool, status: Status) -> Color {
398    let hover = matches!(status, Status::Hovered | Status::Pressed);
399    if current || (link && hover) {
400        tokens.foreground
401    } else {
402        tokens.muted_foreground
403    }
404}
405
406/// The style of a crumb that is a link.
407pub fn style(tokens: &Tokens, status: Status) -> widget::button::Style {
408    widget::button::Style {
409        background: None,
410        text_color: foreground(tokens, false, true, status),
411        border: Border::default(),
412        shadow: Shadow::default(),
413        snap: true,
414    }
415}
416
417/// The style of the ellipsis when it expands the trail: a small ghost
418/// button, so it reads as clickable.
419pub fn ellipsis_style(tokens: &Tokens, status: Status) -> widget::button::Style {
420    let hover = matches!(status, Status::Hovered | Status::Pressed);
421    widget::button::Style {
422        background: hover.then(|| Background::Color(mix(tokens.background, tokens.muted, 0.9))),
423        text_color: foreground(tokens, false, true, status),
424        border: Border {
425            radius: radius::SM.into(),
426            ..Border::default()
427        },
428        shadow: Shadow::default(),
429        snap: true,
430    }
431}
432
433/// What a breadcrumb keyboard shortcut does.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
435pub enum Action {
436    Parent,
437    Root,
438}
439
440impl Action {
441    /// The index of the crumb to go to in a trail of `len`, where the last
442    /// crumb is the current view, or `None` when already at the top.
443    pub fn target(self, len: usize) -> Option<usize> {
444        match self {
445            Action::Parent => len.checked_sub(2),
446            Action::Root => (len > 1).then_some(0),
447        }
448    }
449}
450
451impl keys::Action for Action {
452    const ALL: &'static [Self] = &[Action::Parent, Action::Root];
453
454    fn defaults() -> Keymap<Self> {
455        default_keymap()
456    }
457
458    fn name(self) -> &'static str {
459        match self {
460            Action::Parent => "Parent",
461            Action::Root => "Root",
462        }
463    }
464
465    fn description(self) -> &'static str {
466        match self {
467            Action::Parent => "Goes up one level, to the crumb before the current one.",
468            Action::Root => "Goes to the first crumb.",
469        }
470    }
471}
472
473/// The default breadcrumb shortcuts:
474///
475/// | Keys | Action |
476/// | --- | --- |
477/// | `Alt+ArrowUp` | [`Action::Parent`] |
478/// | `Alt+Shift+ArrowUp` | [`Action::Root`] |
479///
480/// `Alt+ArrowUp` goes to the parent folder in desktop file managers.
481pub fn default_keymap() -> Keymap<Action> {
482    Keymap::new()
483        .bind(Chord::named(Named::ArrowUp).alt(), Action::Parent)
484        .bind(Chord::named(Named::ArrowUp).alt().shift(), Action::Root)
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490    use crate::theme::{dark, light};
491
492    #[test]
493    fn every_crumb_shows_without_a_limit() {
494        assert_eq!(slots(0, None), vec![]);
495        assert_eq!(slots(3, None), (0..3).map(Slot::Crumb).collect::<Vec<_>>());
496        assert_eq!(slots(3, Some(3)), slots(3, None));
497        assert_eq!(slots(3, Some(10)), slots(3, None));
498    }
499
500    #[test]
501    fn fit_limits_shorten_one_crumb_at_a_time() {
502        assert_eq!(fit_limits(5, None), vec![5, 4, 3, 2]);
503        assert_eq!(fit_limits(5, Some(3)), vec![3, 2]);
504        assert_eq!(fit_limits(5, Some(9)), vec![5, 4, 3, 2]);
505        assert_eq!(fit_limits(2, None), vec![2]);
506        assert_eq!(fit_limits(1, None), vec![1]);
507        assert_eq!(fit_limits(0, None), vec![0]);
508    }
509
510    #[test]
511    fn collapsing_to_fit_is_on_by_default() {
512        let trail = breadcrumb::<u8>([crumb("Home")]);
513        assert!(trail.collapse_to_fit);
514        assert!(!trail.collapse_to_fit(false).collapse_to_fit);
515    }
516
517    #[test]
518    fn a_long_trail_keeps_the_root_and_the_nearest_levels() {
519        assert_eq!(
520            slots(6, Some(3)),
521            vec![
522                Slot::Crumb(0),
523                Slot::Ellipsis,
524                Slot::Crumb(4),
525                Slot::Crumb(5)
526            ]
527        );
528        assert_eq!(
529            slots(6, Some(4)),
530            vec![
531                Slot::Crumb(0),
532                Slot::Ellipsis,
533                Slot::Crumb(3),
534                Slot::Crumb(4),
535                Slot::Crumb(5)
536            ]
537        );
538    }
539
540    #[test]
541    fn the_limit_never_drops_below_root_and_current() {
542        let expected = vec![Slot::Crumb(0), Slot::Ellipsis, Slot::Crumb(4)];
543        assert_eq!(slots(5, Some(0)), expected);
544        assert_eq!(slots(5, Some(1)), expected);
545        assert_eq!(slots(5, Some(2)), expected);
546    }
547
548    #[test]
549    fn builder_defaults_and_options() {
550        let trail: Breadcrumb<'_, u8> = breadcrumb([crumb("Home").on_press(0), crumb("Docs")]);
551        assert_eq!(trail.separator, Separator::Chevron);
552        assert_eq!(trail.max_items, None);
553        assert!(trail.on_expand.is_none());
554        assert_eq!(trail.len(), 2);
555        assert!(!trail.is_empty());
556
557        let trail = trail.separator(Separator::Slash).max_items(3).on_expand(9);
558        assert_eq!(trail.separator, Separator::Slash);
559        assert_eq!(trail.max_items, Some(3));
560        assert_eq!(trail.on_expand, Some(9));
561        assert!(breadcrumb::<u8>([]).is_empty());
562    }
563
564    #[test]
565    fn crumbs_are_links_only_with_a_message() {
566        let home = crumb::<u8>("Home").icon(lucide!(House));
567        assert!(!home.is_link());
568        assert_eq!(home.icon.map(Glyph::name), Some("house"));
569        assert!(home.clone().on_press(1).is_link());
570        assert!(!home.on_press(1).on_press_maybe(None).is_link());
571    }
572
573    #[test]
574    fn current_crumb_is_foreground_and_links_are_muted_until_hovered() {
575        for theme in [light(), dark()] {
576            let tokens = Tokens::of(&theme);
577            for status in [Status::Active, Status::Hovered] {
578                assert_eq!(foreground(&tokens, true, false, status), tokens.foreground);
579                assert_eq!(
580                    foreground(&tokens, false, false, status),
581                    tokens.muted_foreground
582                );
583            }
584            assert_eq!(
585                foreground(&tokens, false, true, Status::Active),
586                tokens.muted_foreground
587            );
588            assert_eq!(
589                foreground(&tokens, false, true, Status::Hovered),
590                tokens.foreground
591            );
592            assert_eq!(
593                foreground(&tokens, false, true, Status::Pressed),
594                tokens.foreground
595            );
596        }
597    }
598
599    #[test]
600    fn links_have_no_background_or_border() {
601        let tokens = Tokens::of(&light());
602        for status in [Status::Active, Status::Hovered, Status::Pressed] {
603            let style = style(&tokens, status);
604            assert!(style.background.is_none());
605            assert_eq!(style.border.width, 0.0);
606        }
607    }
608
609    #[test]
610    fn the_ellipsis_fills_only_on_hover() {
611        for theme in [light(), dark()] {
612            let tokens = Tokens::of(&theme);
613            assert!(ellipsis_style(&tokens, Status::Active).background.is_none());
614            assert!(
615                ellipsis_style(&tokens, Status::Hovered)
616                    .background
617                    .is_some()
618            );
619        }
620    }
621
622    #[test]
623    fn actions_target_the_parent_and_the_root() {
624        assert_eq!(Action::Parent.target(4), Some(2));
625        assert_eq!(Action::Root.target(4), Some(0));
626        assert_eq!(Action::Parent.target(2), Some(0));
627        assert_eq!(Action::Parent.target(1), None);
628        assert_eq!(Action::Root.target(1), None);
629        assert_eq!(Action::Parent.target(0), None);
630        assert_eq!(Action::Root.target(0), None);
631    }
632
633    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
634        let chord: Chord = chord.parse().unwrap();
635        keymap.resolve(chord.key(), chord.modifiers())
636    }
637
638    #[test]
639    fn default_keymap_covers_every_action() {
640        let keymap = default_keymap();
641        assert_eq!(press(&keymap, "Alt+ArrowUp"), Some(Action::Parent));
642        assert_eq!(press(&keymap, "Alt+Shift+ArrowUp"), Some(Action::Root));
643        assert_eq!(press(&keymap, "ArrowUp"), None);
644        for action in <Action as keys::Action>::ALL {
645            assert!(!keymap.chords(action).is_empty(), "{action:?}");
646        }
647        assert_eq!(Keymap::<Action>::defaults(), keymap);
648    }
649
650    #[test]
651    fn keymap_overrides_and_unbinding() {
652        let keymap = default_keymap()
653            .unbind(&Chord::named(Named::ArrowUp).alt())
654            .bind("Backspace".parse().unwrap(), Action::Parent);
655        assert_eq!(press(&keymap, "Alt+ArrowUp"), None);
656        assert_eq!(press(&keymap, "Backspace"), Some(Action::Parent));
657        assert_eq!(press(&keymap, "Alt+Shift+ArrowUp"), Some(Action::Root));
658    }
659}