Skip to main content

iced_cube/navigation/
sidebar.rs

1//! Persistent app navigation down one side of the window.
2//!
3//! [`State`] owns the groups and items, which item is active, the keyboard
4//! highlight, which groups and parent items are open, and whether the
5//! sidebar is collapsed to an icon rail. Its [`update`](State::update)
6//! handles clicks and keyboard navigation and returns an [`Output`] when an
7//! item is activated.
8//!
9//! [`sidebar`] draws the panel, and with [`content`](Sidebar::content)
10//! the page beside it. On a window narrower than the
11//! [breakpoint](Sidebar::breakpoint) the panel becomes an off-canvas
12//! drawer instead: a trigger button opens it over a scrim, and a tap on
13//! the scrim, Escape or choosing an item closes it.
14//!
15//! # Keyboard
16//!
17//! Every enabled item, and every collapsible group's heading, takes
18//! keyboard focus from iced's focus operations, so Tab reaches each in
19//! turn alongside other controls. The focused row is ringed and Enter or
20//! Space activates it. A press inside the sidebar also gives it keyboard
21//! focus, and an open drawer always has it. While focused the sidebar
22//! resolves its own [`Keymap`] of [`Action`]s and captures the keys it
23//! uses; see [`default_keymap`]. Focus follows the arrow keys, so Tab
24//! carries on from the highlighted row. Only [`Action::ToggleRail`] is
25//! meant to work app-wide: route key presses from [`keys::subscription`]
26//! through [`State::shortcut`] for that.
27
28use std::rc::Rc;
29
30use iced::Event as Input;
31use iced::advanced::layout::{self, Layout};
32use iced::advanced::widget::operation::Focusable;
33use iced::advanced::widget::{Operation, Tree, Widget, tree};
34use iced::advanced::{Clipboard, Shell, overlay, renderer};
35use iced::keyboard::{self, key::Named};
36use iced::widget::{Space, button, column, container, mouse_area, row, scrollable, stack, text};
37use iced::{
38    Alignment, Background, Border, Color, Element, Length, Padding, Rectangle, Renderer, Shadow,
39    Size, Theme, Vector, mouse, touch,
40};
41
42use crate::focus;
43use crate::icon::{Glyph, themed};
44use crate::keys::{self, Chord, Keymap};
45use crate::overlay::menu::{self, Parts, RowStatus};
46use crate::overlay::tooltip::{Position, tooltip};
47use crate::primitives::icon_button::{IconButton, icon_button};
48use crate::solid::solid;
49use crate::theme::{Tokens, fade, mix, radius, space, text_size};
50
51/// Width of the expanded sidebar.
52pub const WIDTH: f32 = 256.0;
53/// Width of the icon rail.
54pub const RAIL_WIDTH: f32 = 48.0;
55/// Width of the drawer on narrow windows.
56pub const DRAWER_WIDTH: f32 = 288.0;
57/// Below this window width the sidebar becomes a drawer.
58pub const BREAKPOINT: f32 = 640.0;
59/// Height of the bar holding the trigger on narrow windows.
60pub const BAR_HEIGHT: f32 = 48.0;
61
62/// Side of the square buttons in the rail.
63const RAIL_BUTTON: f32 = 32.0;
64
65/// The widget id of the trigger in the narrow window bar, for tests.
66pub const TRIGGER_ID: iced::widget::Id = iced::widget::Id::new("iced-cube-sidebar-trigger");
67
68/// One navigation item. Items nest one level: children of children are
69/// ignored.
70#[derive(Debug, Clone, PartialEq)]
71pub struct Item<Id> {
72    pub id: Id,
73    pub label: String,
74    pub icon: Option<Glyph>,
75    /// A short count or status on the right, such as `12`.
76    pub badge: Option<String>,
77    pub disabled: bool,
78    pub children: Vec<Item<Id>>,
79}
80
81/// Creates an enabled item.
82pub fn item<Id>(id: Id, label: impl Into<String>) -> Item<Id> {
83    Item {
84        id,
85        label: label.into(),
86        icon: None,
87        badge: None,
88        disabled: false,
89        children: Vec::new(),
90    }
91}
92
93impl<Id> Item<Id> {
94    pub fn icon(mut self, glyph: Glyph) -> Self {
95        self.icon = Some(glyph);
96        self
97    }
98
99    pub fn badge(mut self, badge: impl Into<String>) -> Self {
100        self.badge = Some(badge.into());
101        self
102    }
103
104    pub fn disabled(mut self, disabled: bool) -> Self {
105        self.disabled = disabled;
106        self
107    }
108
109    /// Nested items, shown below this one while it is expanded.
110    pub fn children(mut self, children: impl IntoIterator<Item = Item<Id>>) -> Self {
111        self.children = children
112            .into_iter()
113            .map(|mut child| {
114                child.children.clear();
115                child
116            })
117            .collect();
118        self
119    }
120
121    pub fn has_children(&self) -> bool {
122        !self.children.is_empty()
123    }
124}
125
126/// A labelled group of items.
127#[derive(Debug, Clone, PartialEq)]
128pub struct Group<Id> {
129    /// The heading. An empty label draws no heading.
130    pub label: String,
131    pub items: Vec<Item<Id>>,
132    /// Whether the heading opens and closes the group.
133    pub collapsible: bool,
134}
135
136/// Creates a group that is always open.
137pub fn group<Id>(label: impl Into<String>, items: impl IntoIterator<Item = Item<Id>>) -> Group<Id> {
138    Group {
139        label: label.into(),
140        items: items.into_iter().collect(),
141        collapsible: false,
142    }
143}
144
145impl<Id> Group<Id> {
146    pub fn collapsible(mut self, collapsible: bool) -> Self {
147        self.collapsible = collapsible;
148        self
149    }
150}
151
152/// A row the keyboard can highlight: a collapsible group's heading or an
153/// item.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
155pub enum Row<Id> {
156    Group(usize),
157    Item(Id),
158}
159
160/// Changes to a sidebar.
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum Event<Id> {
163    /// Chooses an item, as a click does. A parent item opens or closes
164    /// its children instead.
165    Activate(Id),
166    /// Highlights the next row, wrapping.
167    Next,
168    /// Highlights the previous row, wrapping.
169    Previous,
170    First,
171    Last,
172    /// Activates the highlighted item or opens and closes the highlighted
173    /// group.
174    ActivateHighlighted,
175    /// Opens the highlighted group or parent, or moves into it when open.
176    Expand,
177    /// Closes the highlighted group or parent, or moves out to it.
178    Collapse,
179    ToggleGroup(usize),
180    /// Opens or closes a parent item's children.
181    ToggleItem(Id),
182    ToggleRail,
183    SetRail(bool),
184    OpenDrawer,
185    CloseDrawer,
186    ToggleDrawer,
187    /// What the trigger does: toggles the drawer on a narrow window and
188    /// the rail otherwise.
189    Toggle,
190    /// Whether the window is narrower than the breakpoint. The sidebar
191    /// sends this itself when the width crosses the breakpoint.
192    Narrow(bool),
193    /// The sidebar gained or lost keyboard focus.
194    Focus(bool),
195    /// Keyboard focus moved onto a row, as Tab moves it: the sidebar takes
196    /// focus and highlights the row. The sidebar sends this itself.
197    FocusRow(Row<Id>),
198    /// Keyboard focus left a row. The sidebar gives up focus unless it
199    /// already moved to another row. The sidebar sends this itself.
200    BlurRow(Row<Id>),
201}
202
203/// What an event did that the app should act on.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum Output<Id> {
206    /// An item was activated: show its page.
207    Activated(Id),
208}
209
210/// The navigation, the active item and how the sidebar is shown.
211#[derive(Debug, Clone, PartialEq)]
212pub struct State<Id> {
213    groups: Vec<Group<Id>>,
214    active: Option<Id>,
215    highlighted: Option<Row<Id>>,
216    closed: Vec<bool>,
217    expanded: Vec<Id>,
218    rail: bool,
219    drawer: bool,
220    narrow: bool,
221    focused: bool,
222    /// Whether the keyboard moved the highlight last, so it is drawn.
223    keyboard: bool,
224}
225
226impl<Id: Copy + PartialEq> State<Id> {
227    /// An expanded sidebar with every group open and nothing active.
228    pub fn new(groups: impl IntoIterator<Item = Group<Id>>) -> Self {
229        let groups: Vec<Group<Id>> = groups.into_iter().collect();
230        Self {
231            closed: vec![false; groups.len()],
232            groups,
233            active: None,
234            highlighted: None,
235            expanded: Vec::new(),
236            rail: false,
237            drawer: false,
238            narrow: false,
239            focused: false,
240            keyboard: false,
241        }
242    }
243
244    /// Starts with `id` active, opening its parent when it is a child.
245    pub fn with_active(mut self, id: Id) -> Self {
246        if self.item(id).is_some_and(|item| !item.disabled) {
247            self.active = Some(id);
248            if let Some(parent) = self.parent_of(id) {
249                self.open_item(parent);
250            }
251        }
252        self
253    }
254
255    /// Starts collapsed to the icon rail.
256    pub fn with_rail(mut self, rail: bool) -> Self {
257        self.rail = rail;
258        self
259    }
260
261    pub fn groups(&self) -> &[Group<Id>] {
262        &self.groups
263    }
264
265    pub fn active(&self) -> Option<Id> {
266        self.active
267    }
268
269    pub fn highlighted(&self) -> Option<Row<Id>> {
270        self.highlighted
271    }
272
273    /// Whether the sidebar is set to collapse to a rail on wide windows.
274    pub fn is_rail(&self) -> bool {
275        self.rail
276    }
277
278    /// Whether the sidebar is drawn as a rail right now: collapsed on a
279    /// wide window. The drawer always shows labels.
280    pub fn is_compact(&self) -> bool {
281        self.rail && !self.narrow
282    }
283
284    pub fn is_narrow(&self) -> bool {
285        self.narrow
286    }
287
288    pub fn is_drawer_open(&self) -> bool {
289        self.narrow && self.drawer
290    }
291
292    pub fn is_focused(&self) -> bool {
293        self.focused
294    }
295
296    /// Whether the highlighted row gets a ring: while the sidebar has keys
297    /// and the keyboard moved the highlight last.
298    pub fn shows_highlight(&self) -> bool {
299        self.keyboard && self.has_keys()
300    }
301
302    /// Whether the sidebar resolves its keymap: while focused or while
303    /// the drawer is open.
304    pub fn has_keys(&self) -> bool {
305        self.focused || self.is_drawer_open()
306    }
307
308    pub fn is_group_open(&self, group: usize) -> bool {
309        !self.closed.get(group).copied().unwrap_or(true)
310    }
311
312    pub fn is_expanded(&self, id: Id) -> bool {
313        self.expanded.contains(&id)
314    }
315
316    pub fn item(&self, id: Id) -> Option<&Item<Id>> {
317        self.groups
318            .iter()
319            .flat_map(|group| &group.items)
320            .find_map(|item| {
321                if item.id == id {
322                    return Some(item);
323                }
324                item.children.iter().find(|child| child.id == id)
325            })
326    }
327
328    /// The parent of a child item.
329    pub fn parent_of(&self, id: Id) -> Option<Id> {
330        self.groups
331            .iter()
332            .flat_map(|group| &group.items)
333            .find(|item| item.children.iter().any(|child| child.id == id))
334            .map(|item| item.id)
335    }
336
337    fn group_of(&self, id: Id) -> Option<usize> {
338        self.groups.iter().position(|group| {
339            group
340                .items
341                .iter()
342                .any(|item| item.id == id || item.children.iter().any(|child| child.id == id))
343        })
344    }
345
346    /// Whether an item or one of its children is the active one, so a
347    /// closed parent still shows where the page is.
348    pub fn is_active_branch(&self, item: &Item<Id>) -> bool {
349        Some(item.id) == self.active
350            || self
351                .active
352                .is_some_and(|active| item.children.iter().any(|child| child.id == active))
353    }
354
355    /// The rows the keyboard moves through, in order: headings of
356    /// collapsible groups and the enabled items that are showing.
357    pub fn rows(&self) -> Vec<Row<Id>> {
358        let compact = self.is_compact();
359        let mut rows = Vec::new();
360        for (index, group) in self.groups.iter().enumerate() {
361            if group.collapsible && !compact {
362                rows.push(Row::Group(index));
363            }
364            if !compact && !self.is_group_open(index) {
365                continue;
366            }
367            for item in group.items.iter().filter(|item| !item.disabled) {
368                rows.push(Row::Item(item.id));
369                if compact || !self.is_expanded(item.id) {
370                    continue;
371                }
372                rows.extend(
373                    item.children
374                        .iter()
375                        .filter(|child| !child.disabled)
376                        .map(|child| Row::Item(child.id)),
377                );
378            }
379        }
380        rows
381    }
382
383    /// Applies an event and returns the activated item, if any.
384    pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>> {
385        match event {
386            Event::Next
387            | Event::Previous
388            | Event::First
389            | Event::Last
390            | Event::ActivateHighlighted
391            | Event::Expand
392            | Event::Collapse
393            | Event::FocusRow(_) => self.keyboard = true,
394            Event::Activate(_)
395            | Event::ToggleGroup(_)
396            | Event::ToggleItem(_)
397            | Event::Focus(_)
398            | Event::OpenDrawer
399            | Event::ToggleDrawer
400            | Event::Toggle => self.keyboard = false,
401            _ => {}
402        }
403        match event {
404            Event::Activate(id) => return self.activate(id),
405            Event::Next => self.step(true),
406            Event::Previous => self.step(false),
407            Event::First => self.highlighted = self.rows().first().copied(),
408            Event::Last => self.highlighted = self.rows().last().copied(),
409            Event::ActivateHighlighted => match self.highlighted {
410                Some(Row::Group(index)) => self.toggle_group(index),
411                Some(Row::Item(id)) => return self.activate(id),
412                None => self.step(true),
413            },
414            Event::Expand => self.expand(),
415            Event::Collapse => self.collapse(),
416            Event::ToggleGroup(index) => self.toggle_group(index),
417            Event::ToggleItem(id) => self.toggle_item(id),
418            Event::ToggleRail => self.set_rail(!self.rail),
419            Event::SetRail(rail) => self.set_rail(rail),
420            Event::OpenDrawer => self.open_drawer(),
421            Event::CloseDrawer => self.drawer = false,
422            Event::ToggleDrawer if self.drawer => self.drawer = false,
423            Event::ToggleDrawer => self.open_drawer(),
424            Event::Toggle if self.narrow => {
425                return self.update(Event::ToggleDrawer);
426            }
427            Event::Toggle => self.set_rail(!self.rail),
428            Event::Narrow(narrow) => {
429                self.narrow = narrow;
430                if !narrow {
431                    self.drawer = false;
432                }
433                self.settle_highlight();
434            }
435            Event::Focus(focused) => {
436                self.focused = focused;
437                if focused && self.highlighted.is_none() {
438                    self.highlight_active();
439                }
440            }
441            Event::FocusRow(row) if self.rows().contains(&row) => {
442                self.focused = true;
443                self.highlighted = Some(row);
444            }
445            Event::FocusRow(_) => {}
446            Event::BlurRow(row) => {
447                if self.highlighted == Some(row) {
448                    self.focused = false;
449                }
450            }
451        }
452        None
453    }
454
455    /// Turns a key press from [`keys::subscription`] into an event for the
456    /// app-wide action, [`Action::ToggleRail`]. The sidebar resolves every
457    /// other action itself while it has focus.
458    pub fn shortcut(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event<Id>> {
459        keymap
460            .resolve_event(key)
461            .filter(|action| *action == Action::ToggleRail)
462            .and_then(|action| action.event(self))
463    }
464
465    fn activate(&mut self, id: Id) -> Option<Output<Id>> {
466        let item = self.item(id).filter(|item| !item.disabled)?;
467        if item.has_children() {
468            if self.is_compact() {
469                self.rail = false;
470                self.open_item(id);
471            } else {
472                self.toggle_item(id);
473            }
474            self.highlighted = Some(Row::Item(id));
475            return None;
476        }
477        self.active = Some(id);
478        self.highlighted = Some(Row::Item(id));
479        self.drawer = false;
480        Some(Output::Activated(id))
481    }
482
483    fn step(&mut self, forward: bool) {
484        let rows = self.rows();
485        if rows.is_empty() {
486            return;
487        }
488        let current = self
489            .highlighted
490            .and_then(|row| rows.iter().position(|candidate| *candidate == row));
491        let len = rows.len();
492        let next = match (current, forward) {
493            (None, true) => 0,
494            (None, false) => len - 1,
495            (Some(index), true) => (index + 1) % len,
496            (Some(index), false) => (index + len - 1) % len,
497        };
498        self.highlighted = rows.get(next).copied();
499    }
500
501    fn expand(&mut self) {
502        match self.highlighted {
503            Some(Row::Group(index)) if !self.is_group_open(index) => self.toggle_group(index),
504            Some(Row::Group(index)) => {
505                self.highlighted = self
506                    .groups
507                    .get(index)
508                    .and_then(|group| group.items.iter().find(|item| !item.disabled))
509                    .map(|item| Row::Item(item.id));
510            }
511            Some(Row::Item(id)) => {
512                let Some(item) = self.item(id).filter(|item| item.has_children()) else {
513                    return;
514                };
515                if self.is_compact() {
516                    return;
517                }
518                if !self.is_expanded(id) {
519                    self.open_item(id);
520                    return;
521                }
522                if let Some(child) = item.children.iter().find(|child| !child.disabled) {
523                    self.highlighted = Some(Row::Item(child.id));
524                }
525            }
526            None => {}
527        }
528    }
529
530    fn collapse(&mut self) {
531        match self.highlighted {
532            Some(Row::Group(index)) if self.is_group_open(index) => self.toggle_group(index),
533            Some(Row::Group(_)) | None => {}
534            Some(Row::Item(id)) => {
535                if self.is_expanded(id) {
536                    self.toggle_item(id);
537                    return;
538                }
539                if let Some(parent) = self.parent_of(id) {
540                    self.highlighted = Some(Row::Item(parent));
541                    return;
542                }
543                let group = self
544                    .group_of(id)
545                    .filter(|&index| self.groups[index].collapsible && !self.is_compact());
546                if let Some(index) = group {
547                    self.highlighted = Some(Row::Group(index));
548                }
549            }
550        }
551    }
552
553    fn toggle_group(&mut self, index: usize) {
554        let Some(closed) = self.closed.get_mut(index) else {
555            return;
556        };
557        if !self.groups[index].collapsible {
558            return;
559        }
560        *closed = !*closed;
561        if *closed && self.highlighted.is_some() {
562            let inside = match self.highlighted {
563                Some(Row::Item(id)) => self.group_of(id) == Some(index),
564                _ => false,
565            };
566            if inside {
567                self.highlighted = Some(Row::Group(index));
568            }
569        }
570    }
571
572    fn open_item(&mut self, id: Id) {
573        if !self.expanded.contains(&id) {
574            self.expanded.push(id);
575        }
576    }
577
578    fn toggle_item(&mut self, id: Id) {
579        if !self.item(id).is_some_and(Item::has_children) {
580            return;
581        }
582        if !self.expanded.contains(&id) {
583            self.open_item(id);
584            return;
585        }
586        self.expanded.retain(|expanded| *expanded != id);
587        if let Some(Row::Item(highlighted)) = self.highlighted
588            && self.parent_of(highlighted) == Some(id)
589        {
590            self.highlighted = Some(Row::Item(id));
591        }
592    }
593
594    fn set_rail(&mut self, rail: bool) {
595        self.rail = rail;
596        self.settle_highlight();
597    }
598
599    fn open_drawer(&mut self) {
600        self.drawer = true;
601        self.highlight_active();
602    }
603
604    /// Highlights the active item, or the first row, if it is showing.
605    fn highlight_active(&mut self) {
606        let rows = self.rows();
607        let active = self
608            .active
609            .map(Row::Item)
610            .filter(|row| rows.contains(row))
611            .or_else(|| {
612                self.active
613                    .and_then(|id| self.parent_of(id))
614                    .map(Row::Item)
615                    .filter(|row| rows.contains(row))
616            });
617        self.highlighted = active.or_else(|| rows.first().copied());
618    }
619
620    /// Moves a highlight that is no longer showing to its parent or group,
621    /// or drops it.
622    fn settle_highlight(&mut self) {
623        let Some(row) = self.highlighted else {
624            return;
625        };
626        let rows = self.rows();
627        if rows.contains(&row) {
628            return;
629        }
630        let fallback = match row {
631            Row::Item(id) => self
632                .parent_of(id)
633                .map(Row::Item)
634                .filter(|row| rows.contains(row)),
635            Row::Group(index) => self
636                .groups
637                .get(index)
638                .and_then(|group| group.items.iter().find(|item| !item.disabled))
639                .map(|item| Row::Item(item.id)),
640        };
641        self.highlighted = fallback;
642    }
643}
644
645/// What a sidebar keyboard shortcut does.
646#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
647pub enum Action {
648    Next,
649    Previous,
650    First,
651    Last,
652    Activate,
653    Expand,
654    Collapse,
655    /// Collapses to the rail and back, or opens and closes the drawer on
656    /// a narrow window.
657    ToggleRail,
658    /// Closes the drawer, or gives up keyboard focus.
659    Close,
660}
661
662impl Action {
663    /// The [`Event`] this action sends to `state`, or `None` when
664    /// [`Action::Close`] has nothing to close.
665    pub fn event<Id: Copy + PartialEq>(self, state: &State<Id>) -> Option<Event<Id>> {
666        let event = match self {
667            Action::Next => Event::Next,
668            Action::Previous => Event::Previous,
669            Action::First => Event::First,
670            Action::Last => Event::Last,
671            Action::Activate => Event::ActivateHighlighted,
672            Action::Expand => Event::Expand,
673            Action::Collapse => Event::Collapse,
674            Action::ToggleRail => Event::Toggle,
675            Action::Close if state.is_drawer_open() => Event::CloseDrawer,
676            Action::Close if state.is_focused() => Event::Focus(false),
677            Action::Close => return None,
678        };
679        Some(event)
680    }
681}
682
683impl keys::Action for Action {
684    const ALL: &'static [Self] = &[
685        Action::Next,
686        Action::Previous,
687        Action::First,
688        Action::Last,
689        Action::Activate,
690        Action::Expand,
691        Action::Collapse,
692        Action::ToggleRail,
693        Action::Close,
694    ];
695
696    fn defaults() -> Keymap<Self> {
697        default_keymap()
698    }
699
700    fn name(self) -> &'static str {
701        match self {
702            Action::Next => "Next",
703            Action::Previous => "Previous",
704            Action::First => "First",
705            Action::Last => "Last",
706            Action::Activate => "Activate",
707            Action::Expand => "Expand",
708            Action::Collapse => "Collapse",
709            Action::ToggleRail => "ToggleRail",
710            Action::Close => "Close",
711        }
712    }
713
714    fn description(self) -> &'static str {
715        match self {
716            Action::Next => "Highlights the next row, wrapping.",
717            Action::Previous => "Highlights the previous row, wrapping.",
718            Action::First => "Highlights the first row.",
719            Action::Last => "Highlights the last row.",
720            Action::Activate => "Activates the highlighted item or opens and closes its group.",
721            Action::Expand => "Opens the highlighted group or parent item, or moves into it.",
722            Action::Collapse => "Closes the highlighted group or parent item, or moves out to it.",
723            Action::ToggleRail => {
724                "Collapses the sidebar to an icon rail and back, or toggles the drawer on a narrow window."
725            }
726            Action::Close => "Closes the drawer, or leaves the sidebar.",
727        }
728    }
729}
730
731/// The default sidebar shortcuts:
732///
733/// | Keys | Action |
734/// | --- | --- |
735/// | `ArrowDown` | [`Action::Next`] |
736/// | `ArrowUp` | [`Action::Previous`] |
737/// | `Home` | [`Action::First`] |
738/// | `End` | [`Action::Last`] |
739/// | `Enter`, `Space` | [`Action::Activate`] |
740/// | `ArrowRight` | [`Action::Expand`] |
741/// | `ArrowLeft` | [`Action::Collapse`] |
742/// | `Ctrl+B` (`Cmd+B` on macOS) | [`Action::ToggleRail`] |
743/// | `Escape` | [`Action::Close`] |
744///
745/// The sidebar resolves these itself while it has focus or its drawer is
746/// open. Route [`keys::subscription`] through [`State::shortcut`] so
747/// `Ctrl+B` works everywhere else too.
748pub fn default_keymap() -> Keymap<Action> {
749    Keymap::new()
750        .bind(Chord::named(Named::ArrowDown), Action::Next)
751        .bind(Chord::named(Named::ArrowUp), Action::Previous)
752        .bind(Chord::named(Named::Home), Action::First)
753        .bind(Chord::named(Named::End), Action::Last)
754        .bind(Chord::named(Named::Enter), Action::Activate)
755        .bind(Chord::named(Named::Space), Action::Activate)
756        .bind(Chord::named(Named::ArrowRight), Action::Expand)
757        .bind(Chord::named(Named::ArrowLeft), Action::Collapse)
758        .bind(Chord::character('b').command(), Action::ToggleRail)
759        .bind(Chord::named(Named::Escape), Action::Close)
760}
761
762/// The sidebar surface: a shade off the page in light themes, and lifted
763/// like a card in dark ones.
764pub fn surface_style(tokens: &Tokens) -> container::Style {
765    let background = if tokens.is_dark {
766        mix(tokens.background, tokens.foreground, 0.04)
767    } else {
768        mix(tokens.background, tokens.muted, 0.5)
769    };
770    container::Style {
771        background: Some(Background::Color(background)),
772        text_color: Some(tokens.foreground),
773        ..container::Style::default()
774    }
775}
776
777/// The one pixel edge between the sidebar and the page.
778pub fn edge_style(tokens: &Tokens) -> container::Style {
779    container::Style {
780        background: Some(Background::Color(tokens.border)),
781        ..container::Style::default()
782    }
783}
784
785/// The scrim behind the open drawer.
786pub fn scrim_style(tokens: &Tokens) -> container::Style {
787    container::Style {
788        background: Some(Background::Color(fade(
789            Color::BLACK,
790            if tokens.is_dark { 0.7 } else { 0.5 },
791        ))),
792        ..container::Style::default()
793    }
794}
795
796/// How an item row is drawn: in the shared menu row colours, highlighted
797/// while active or under the pointer, with a ring while it has the
798/// keyboard highlight.
799pub fn item_style(
800    tokens: &Tokens,
801    active: bool,
802    keyboard: bool,
803    status: button::Status,
804) -> button::Style {
805    let row = match status {
806        button::Status::Disabled => RowStatus::Disabled,
807        _ if active => RowStatus::Highlighted,
808        button::Status::Hovered | button::Status::Pressed => RowStatus::Highlighted,
809        button::Status::Active => RowStatus::Idle,
810    };
811    let colours = menu::row_style(tokens, row, false);
812    button::Style {
813        background: colours.background.map(Background::Color),
814        text_color: colours.text,
815        border: Border {
816            color: if keyboard {
817                tokens.ring
818            } else {
819                Color::TRANSPARENT
820            },
821            width: if keyboard { 1.0 } else { 0.0 },
822            radius: radius::SM.into(),
823        },
824        shadow: Shadow::default(),
825        snap: true,
826    }
827}
828
829/// A sidebar builder. Convert it into an [`Element`] to render.
830pub struct Sidebar<'a, Id, Message> {
831    state: &'a State<Id>,
832    header: Option<Element<'a, Message>>,
833    footer: Option<Element<'a, Message>>,
834    content: Option<Element<'a, Message>>,
835    width: Option<Length>,
836    breakpoint: f32,
837    trigger: bool,
838    keymap: Keymap<Action>,
839    on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
840}
841
842impl<Id: std::fmt::Debug, Message> std::fmt::Debug for Sidebar<'_, Id, Message> {
843    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
844        f.debug_struct("Sidebar")
845            .field("state", self.state)
846            .field("width", &self.width)
847            .field("breakpoint", &self.breakpoint)
848            .field("trigger", &self.trigger)
849            .field("keymap", &self.keymap)
850            .finish_non_exhaustive()
851    }
852}
853
854/// Renders the navigation of `state`. Without
855/// [`on_event`](Sidebar::on_event) every item renders disabled.
856pub fn sidebar<Id, Message>(state: &State<Id>) -> Sidebar<'_, Id, Message> {
857    Sidebar {
858        state,
859        header: None,
860        footer: None,
861        content: None,
862        width: None,
863        breakpoint: BREAKPOINT,
864        trigger: true,
865        keymap: default_keymap(),
866        on_event: None,
867    }
868}
869
870impl<'a, Id, Message> Sidebar<'a, Id, Message> {
871    /// Content above the groups, such as the app name and a switcher
872    /// built with [`menu_button`].
873    pub fn header(mut self, header: impl Into<Element<'a, Message>>) -> Self {
874        self.header = Some(header.into());
875        self
876    }
877
878    /// Content below the groups, such as the signed in user.
879    pub fn footer(mut self, footer: impl Into<Element<'a, Message>>) -> Self {
880        self.footer = Some(footer.into());
881        self
882    }
883
884    /// The page beside the sidebar. With content, the sidebar turns into a
885    /// drawer on narrow windows; without it, only the panel is drawn.
886    pub fn content(mut self, content: impl Into<Element<'a, Message>>) -> Self {
887        self.content = Some(content.into());
888        self
889    }
890
891    /// The expanded width. Defaults to [`WIDTH`]; use [`Length::Fill`]
892    /// inside a resizable panel.
893    pub fn width(mut self, width: impl Into<Length>) -> Self {
894        self.width = Some(width.into());
895        self
896    }
897
898    /// The window width below which the sidebar becomes a drawer.
899    pub fn breakpoint(mut self, width: f32) -> Self {
900        self.breakpoint = width;
901        self
902    }
903
904    /// Whether narrow windows get a bar with the trigger above the
905    /// content. Turn it off to place [`trigger`] in your own header.
906    pub fn trigger(mut self, trigger: bool) -> Self {
907        self.trigger = trigger;
908        self
909    }
910
911    /// Replaces the [`default_keymap`] the focused sidebar resolves keys
912    /// with.
913    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
914        self.keymap = keymap;
915        self
916    }
917
918    pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
919        self.on_event = Some(Box::new(on_event));
920        self
921    }
922}
923
924type OnEvent<'a, Id, Message> = Rc<dyn Fn(Event<Id>) -> Message + 'a>;
925
926/// How the panel is drawn.
927#[derive(Debug, Clone, Copy, PartialEq, Eq)]
928enum Mode {
929    Docked,
930    Rail,
931    Drawer,
932}
933
934impl<'a, Id, Message> From<Sidebar<'a, Id, Message>> for Element<'a, Message>
935where
936    Id: Copy + PartialEq + 'a,
937    Message: Clone + 'a,
938{
939    fn from(sidebar: Sidebar<'a, Id, Message>) -> Self {
940        let Sidebar {
941            state,
942            header,
943            footer,
944            content,
945            width,
946            breakpoint,
947            trigger: show_trigger,
948            keymap,
949            on_event,
950        } = sidebar;
951        let on_event: Option<OnEvent<'a, Id, Message>> = on_event.map(Rc::from);
952
953        let Some(content) = content else {
954            let mode = if state.rail { Mode::Rail } else { Mode::Docked };
955            // Whatever sits beside a lone panel, such as a handle, draws
956            // the edge.
957            let panel = panel(state, header, footer, mode, width, false, on_event.clone());
958            return watch(panel, state, Some(keymap), true, None, on_event);
959        };
960
961        if !state.narrow {
962            let mode = if state.rail { Mode::Rail } else { Mode::Docked };
963            let panel = panel(state, header, footer, mode, width, true, on_event.clone());
964            let panel = watch(panel, state, Some(keymap), true, None, on_event.clone());
965            let page = row![panel, container(content).width(Length::Fill)].height(Length::Fill);
966            return watch(page.into(), state, None, false, Some(breakpoint), on_event);
967        }
968
969        let mut page = column![];
970        if show_trigger {
971            let bar = container(
972                trigger(
973                    on_event
974                        .as_ref()
975                        .map(|on_event| on_event(Event::ToggleDrawer)),
976                )
977                .tooltip(None)
978                .id(TRIGGER_ID),
979            )
980            .padding([0.0, space::SM])
981            .height(BAR_HEIGHT)
982            .width(Length::Fill)
983            .align_y(Alignment::Center);
984            page = page.push(bar).push(edge(Length::Fill, Length::Fixed(1.0)));
985        }
986        page = page.push(container(content).width(Length::Fill).height(Length::Fill));
987
988        let mut layers = stack![page].width(Length::Fill).height(Length::Fill);
989        if state.is_drawer_open() {
990            let scrim = container(Space::new())
991                .width(Length::Fill)
992                .height(Length::Fill)
993                .style(|theme| scrim_style(&Tokens::of(theme)));
994            let scrim: Element<'a, Message> = match &on_event {
995                Some(on_event) => solid(mouse_area(scrim).on_press(on_event(Event::CloseDrawer))),
996                None => solid(scrim),
997            };
998            #[cfg(feature = "icedwright")]
999            let scrim: Element<'a, Message> = icedwright_probe::semantic(scrim)
1000                .role(icedwright_probe::role::Scrim)
1001                .component("iced_cube::sidebar")
1002                .into();
1003            let drawer = panel(
1004                state,
1005                header,
1006                footer,
1007                Mode::Drawer,
1008                None,
1009                true,
1010                on_event.clone(),
1011            );
1012            let drawer = watch(drawer, state, Some(keymap), false, None, on_event.clone());
1013            layers = layers.push(scrim).push(solid(drawer));
1014        }
1015        watch(
1016            layers.into(),
1017            state,
1018            None,
1019            false,
1020            Some(breakpoint),
1021            on_event,
1022        )
1023    }
1024}
1025
1026/// The icon button that opens the drawer or collapses the sidebar. Send
1027/// [`Event::Toggle`] from it to do whichever fits the window.
1028pub fn trigger<'a, Message>(on_press: Option<Message>) -> IconButton<'a, Message> {
1029    icon_button(crate::lucide!(PanelLeft))
1030        .label("Toggle sidebar")
1031        .on_press_maybe(on_press)
1032}
1033
1034fn edge<'a, Message: 'a>(width: Length, height: Length) -> Element<'a, Message> {
1035    container(Space::new())
1036        .width(width)
1037        .height(height)
1038        .style(|theme| edge_style(&Tokens::of(theme)))
1039        .into()
1040}
1041
1042fn panel<'a, Id, Message>(
1043    state: &'a State<Id>,
1044    header: Option<Element<'a, Message>>,
1045    footer: Option<Element<'a, Message>>,
1046    mode: Mode,
1047    width: Option<Length>,
1048    with_edge: bool,
1049    on_event: Option<OnEvent<'a, Id, Message>>,
1050) -> Element<'a, Message>
1051where
1052    Id: Copy + PartialEq + 'a,
1053    Message: Clone + 'a,
1054{
1055    let on_event = on_event.as_deref();
1056    let keyboard = state.shows_highlight();
1057    let mut body = column![].spacing(space::SM).width(Length::Fill);
1058    for (index, group) in state.groups.iter().enumerate() {
1059        body = body.push(group_block(state, index, group, mode, keyboard, on_event));
1060    }
1061    let body: Element<'a, Message> = body.into();
1062    #[cfg(feature = "icedwright")]
1063    let body: Element<'a, Message> = icedwright_probe::semantic(body)
1064        .role(icedwright_probe::role::List)
1065        .component("iced_cube::sidebar")
1066        .into();
1067
1068    let mut sections = column![].width(Length::Fill).height(Length::Fill);
1069    if let Some(header) = header {
1070        sections = sections.push(container(header).padding(space::SM).width(Length::Fill));
1071    }
1072    sections = sections.push(
1073        scrollable(body)
1074            .direction(scrollable::Direction::Vertical(
1075                scrollable::Scrollbar::hidden(),
1076            ))
1077            .height(Length::Fill),
1078    );
1079    if let Some(footer) = footer {
1080        sections = sections.push(container(footer).padding(space::SM).width(Length::Fill));
1081    }
1082
1083    let width = match mode {
1084        Mode::Rail => Length::Fixed(RAIL_WIDTH),
1085        Mode::Docked => width.unwrap_or(Length::Fixed(WIDTH)),
1086        Mode::Drawer => Length::Fixed(DRAWER_WIDTH),
1087    };
1088    let surface = container(sections)
1089        .width(Length::Fill)
1090        .height(Length::Fill)
1091        .style(|theme| surface_style(&Tokens::of(theme)));
1092    let mut panel = row![surface].width(width).height(Length::Fill);
1093    if with_edge {
1094        panel = panel.push(edge(Length::Fixed(1.0), Length::Fill));
1095    }
1096    let panel: Element<'a, Message> = if mode == Mode::Drawer {
1097        container(panel)
1098            .max_width(DRAWER_WIDTH)
1099            .height(Length::Fill)
1100            .style(|theme| drawer_style(&Tokens::of(theme)))
1101            .into()
1102    } else {
1103        panel.into()
1104    };
1105    #[cfg(feature = "icedwright")]
1106    let panel = icedwright_probe::semantic(panel)
1107        .role(icedwright_probe::role::Navigation)
1108        .name("Sidebar")
1109        .component("iced_cube::sidebar")
1110        .into();
1111    panel
1112}
1113
1114/// The shadow the drawer casts over the page.
1115pub fn drawer_style(tokens: &Tokens) -> container::Style {
1116    container::Style {
1117        shadow: Shadow {
1118            color: fade(Color::BLACK, if tokens.is_dark { 0.5 } else { 0.15 }),
1119            offset: Vector::new(4.0, 0.0),
1120            blur_radius: 16.0,
1121        },
1122        ..container::Style::default()
1123    }
1124}
1125
1126fn group_block<'a, Id, Message>(
1127    state: &'a State<Id>,
1128    index: usize,
1129    group: &'a Group<Id>,
1130    mode: Mode,
1131    keyboard: bool,
1132    on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1133) -> Element<'a, Message>
1134where
1135    Id: Copy + PartialEq + 'a,
1136    Message: Clone + 'a,
1137{
1138    let mut block = column![].width(Length::Fill);
1139    if mode == Mode::Rail {
1140        for item in &group.items {
1141            block = block.push(rail_item(state, item, on_event));
1142        }
1143        let block: Element<'a, Message> = container(block.spacing(space::XS))
1144            .padding(space::SM)
1145            .width(Length::Fill)
1146            .into();
1147        #[cfg(feature = "icedwright")]
1148        let block = icedwright_probe::semantic(block)
1149            .role(icedwright_probe::role::Group)
1150            .name(group.label.as_str())
1151            .component("iced_cube::sidebar")
1152            .into();
1153        return block;
1154    }
1155
1156    if !group.label.is_empty() {
1157        let highlighted = keyboard && state.highlighted == Some(Row::Group(index));
1158        block = block.push(group_heading(state, index, group, highlighted, on_event));
1159    }
1160    if state.is_group_open(index) || !group.collapsible {
1161        for item in &group.items {
1162            block = block.push(item_rows(state, item, keyboard, on_event));
1163        }
1164    }
1165    let block: Element<'a, Message> = container(block.spacing(2.0))
1166        .padding([space::XS, space::XS])
1167        .width(Length::Fill)
1168        .into();
1169    #[cfg(feature = "icedwright")]
1170    let block = {
1171        let annotated = icedwright_probe::semantic(block)
1172            .role(icedwright_probe::role::Group)
1173            .component("iced_cube::sidebar");
1174        if group.label.is_empty() {
1175            annotated.into()
1176        } else {
1177            annotated.name(group.label.as_str()).into()
1178        }
1179    };
1180    block
1181}
1182
1183fn group_heading<'a, Id, Message>(
1184    state: &State<Id>,
1185    index: usize,
1186    group: &'a Group<Id>,
1187    highlighted: bool,
1188    on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1189) -> Element<'a, Message>
1190where
1191    Id: Copy + PartialEq + 'a,
1192    Message: Clone + 'a,
1193{
1194    let label = text(group.label.as_str())
1195        .size(text_size::XS)
1196        .font(crate::theme::semibold())
1197        .wrapping(text::Wrapping::None)
1198        .width(Length::Fill)
1199        .style(|theme: &Theme| menu::label_style(&Tokens::of(theme)));
1200    if !group.collapsible {
1201        return menu::inset(
1202            container(label)
1203                .padding(menu::ROW_PADDING)
1204                .height(menu::ROW_PADDING.top + menu::LINE_HEIGHT + menu::ROW_PADDING.bottom)
1205                .align_y(Alignment::Center),
1206        );
1207    }
1208    let chevron = if state.is_group_open(index) {
1209        crate::lucide!(ChevronDown)
1210    } else {
1211        crate::lucide!(ChevronRight)
1212    };
1213    let heading = row![
1214        label,
1215        themed(chevron, menu::ICON_SIZE, 1.0, |theme| {
1216            Tokens::of(theme).muted_foreground
1217        })
1218    ]
1219    .align_y(Alignment::Center);
1220    let toggle = on_event.map(|on_event| on_event(Event::ToggleGroup(index)));
1221    let heading = menu::inset(
1222        button(heading)
1223            .padding(menu::ROW_PADDING)
1224            .width(Length::Fill)
1225            .on_press_maybe(toggle.clone())
1226            .style(move |theme, status| item_style(&Tokens::of(theme), false, highlighted, status)),
1227    );
1228    let heading = stop(heading, state, Row::Group(index), toggle, on_event);
1229    #[cfg(feature = "icedwright")]
1230    let heading = icedwright_probe::semantic(heading)
1231        .role(icedwright_probe::role::Button)
1232        .name(group.label.as_str())
1233        .expanded(state.is_group_open(index))
1234        .disabled(on_event.is_none())
1235        .component("iced_cube::sidebar")
1236        .into();
1237    heading
1238}
1239
1240fn item_rows<'a, Id, Message>(
1241    state: &'a State<Id>,
1242    item: &'a Item<Id>,
1243    keyboard: bool,
1244    on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1245) -> Element<'a, Message>
1246where
1247    Id: Copy + PartialEq + 'a,
1248    Message: Clone + 'a,
1249{
1250    let expanded = state.is_expanded(item.id);
1251    let active = if item.has_children() {
1252        !expanded && state.is_active_branch(item)
1253    } else {
1254        state.active == Some(item.id)
1255    };
1256    let row_element = item_row(state, item, active, keyboard, on_event);
1257    if !item.has_children() || !expanded {
1258        return row_element;
1259    }
1260
1261    let children = column(item.children.iter().map(|child| {
1262        let active = state.active == Some(child.id);
1263        item_row(state, child, active, keyboard, on_event)
1264    }))
1265    .spacing(2.0)
1266    .width(Length::Fill);
1267    let nested = row![
1268        edge(Length::Fixed(1.0), Length::Fill),
1269        container(children).padding(Padding::ZERO.left(space::SM)),
1270    ]
1271    .height(Length::Shrink);
1272    column![
1273        row_element,
1274        container(nested).padding(Padding {
1275            top: 2.0,
1276            bottom: 0.0,
1277            left: space::LG + space::XS,
1278            right: 0.0,
1279        })
1280    ]
1281    .spacing(0.0)
1282    .into()
1283}
1284
1285fn item_row<'a, Id, Message>(
1286    state: &State<Id>,
1287    item: &'a Item<Id>,
1288    active: bool,
1289    keyboard: bool,
1290    on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1291) -> Element<'a, Message>
1292where
1293    Id: Copy + PartialEq + 'a,
1294    Message: Clone + 'a,
1295{
1296    let message = on_event
1297        .filter(|_| !item.disabled)
1298        .map(|on_event| on_event(Event::Activate(item.id)));
1299    let status = if message.is_some() {
1300        RowStatus::Idle
1301    } else {
1302        RowStatus::Disabled
1303    };
1304    let highlighted = keyboard && state.highlighted == Some(Row::Item(item.id));
1305
1306    let parts = Parts {
1307        icon: item.icon,
1308        hint: item.badge.as_deref(),
1309        ..Parts::label(&item.label)
1310    };
1311    let mut content = menu::content(parts, status, false);
1312    if item.has_children() {
1313        let chevron = if state.is_expanded(item.id) {
1314            crate::lucide!(ChevronDown)
1315        } else {
1316            crate::lucide!(ChevronRight)
1317        };
1318        let opacity = crate::icon::opacity(message.is_some());
1319        content = content.push(themed(chevron, menu::ICON_SIZE, opacity, |theme| {
1320            Tokens::of(theme).muted_foreground
1321        }));
1322    }
1323
1324    #[cfg(feature = "icedwright")]
1325    let enabled = message.is_some();
1326    let row = menu::inset(
1327        button(content)
1328            .padding(menu::ROW_PADDING)
1329            .width(Length::Fill)
1330            .on_press_maybe(message.clone())
1331            .style(move |theme, status| {
1332                item_style(&Tokens::of(theme), active, highlighted, status)
1333            }),
1334    );
1335    let row = stop(row, state, Row::Item(item.id), message, on_event);
1336    #[cfg(feature = "icedwright")]
1337    let row = link(row, item.label.as_str(), active, enabled);
1338    row
1339}
1340
1341/// Reports a destination as a link.
1342#[cfg(feature = "icedwright")]
1343fn link<'a, Message: 'a>(
1344    element: Element<'a, Message>,
1345    name: &'a str,
1346    current: bool,
1347    enabled: bool,
1348) -> Element<'a, Message> {
1349    icedwright_probe::semantic(element)
1350        .role(icedwright_probe::role::Link)
1351        .name(name)
1352        .current(current)
1353        .disabled(!enabled)
1354        .component("iced_cube::sidebar")
1355        .into()
1356}
1357
1358fn rail_item<'a, Id, Message>(
1359    state: &State<Id>,
1360    item: &'a Item<Id>,
1361    on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1362) -> Element<'a, Message>
1363where
1364    Id: Copy + PartialEq + 'a,
1365    Message: Clone + 'a,
1366{
1367    let message = on_event
1368        .filter(|_| !item.disabled)
1369        .map(|on_event| on_event(Event::Activate(item.id)));
1370    let enabled = message.is_some();
1371    let active = state.is_active_branch(item);
1372    let highlighted = state.shows_highlight() && state.highlighted == Some(Row::Item(item.id));
1373
1374    let face: Element<'a, Message> = match item.icon {
1375        Some(glyph) => themed(
1376            glyph,
1377            menu::ICON_SIZE,
1378            crate::icon::opacity(enabled),
1379            |theme| Tokens::of(theme).foreground,
1380        )
1381        .into(),
1382        None => text(
1383            item.label
1384                .chars()
1385                .next()
1386                .map(String::from)
1387                .unwrap_or_default(),
1388        )
1389        .size(text_size::SM)
1390        .font(crate::theme::semibold())
1391        .into(),
1392    };
1393    let square = button(container(face).center(RAIL_BUTTON))
1394        .width(RAIL_BUTTON)
1395        .height(RAIL_BUTTON)
1396        .padding(0)
1397        .on_press_maybe(message.clone())
1398        .style(move |theme, status| item_style(&Tokens::of(theme), active, highlighted, status));
1399    let element: Element<'a, Message> = tooltip(square, item.label.as_str())
1400        .position(Position::Right)
1401        .into();
1402    let element = stop(element, state, Row::Item(item.id), message, on_event);
1403    #[cfg(feature = "icedwright")]
1404    let element = link(element, item.label.as_str(), active, enabled);
1405    element
1406}
1407
1408/// A header or footer button: a logo or avatar, a title and a subtitle,
1409/// with an up and down chevron to show it opens a menu. Wrap it in a
1410/// dropdown menu for an app switcher or a user menu.
1411pub struct MenuButton<'a, Message> {
1412    title: text::Fragment<'a>,
1413    subtitle: Option<text::Fragment<'a>>,
1414    icon: Option<Glyph>,
1415    initials: Option<text::Fragment<'a>>,
1416    compact: bool,
1417    on_press: Option<Message>,
1418}
1419
1420impl<Message> std::fmt::Debug for MenuButton<'_, Message> {
1421    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1422        f.debug_struct("MenuButton")
1423            .field("title", &self.title)
1424            .field("subtitle", &self.subtitle)
1425            .field("compact", &self.compact)
1426            .finish_non_exhaustive()
1427    }
1428}
1429
1430/// Creates a header or footer button titled `title`.
1431pub fn menu_button<'a, Message>(title: impl text::IntoFragment<'a>) -> MenuButton<'a, Message> {
1432    MenuButton {
1433        title: title.into_fragment(),
1434        subtitle: None,
1435        icon: None,
1436        initials: None,
1437        compact: false,
1438        on_press: None,
1439    }
1440}
1441
1442impl<'a, Message> MenuButton<'a, Message> {
1443    pub fn subtitle(mut self, subtitle: impl text::IntoFragment<'a>) -> Self {
1444        self.subtitle = Some(subtitle.into_fragment());
1445        self
1446    }
1447
1448    /// A logo icon on a primary square, as for an app or team.
1449    pub fn icon(mut self, glyph: Glyph) -> Self {
1450        self.icon = Some(glyph);
1451        self
1452    }
1453
1454    /// Initials on a muted square, as for a person.
1455    pub fn initials(mut self, initials: impl text::IntoFragment<'a>) -> Self {
1456        self.initials = Some(initials.into_fragment());
1457        self
1458    }
1459
1460    /// Shows only the square, for the rail. Pass
1461    /// [`State::is_compact`].
1462    pub fn compact(mut self, compact: bool) -> Self {
1463        self.compact = compact;
1464        self
1465    }
1466
1467    pub fn on_press(mut self, message: Message) -> Self {
1468        self.on_press = Some(message);
1469        self
1470    }
1471
1472    pub fn on_press_maybe(mut self, message: Option<Message>) -> Self {
1473        self.on_press = message;
1474        self
1475    }
1476}
1477
1478impl<'a, Message: Clone + 'a> From<MenuButton<'a, Message>> for Element<'a, Message> {
1479    fn from(menu_button: MenuButton<'a, Message>) -> Self {
1480        let MenuButton {
1481            title,
1482            subtitle,
1483            icon,
1484            initials,
1485            compact,
1486            on_press,
1487        } = menu_button;
1488        let logo = icon.is_some();
1489        let face: Element<'a, Message> = match (icon, initials) {
1490            (Some(glyph), _) => themed(glyph, menu::ICON_SIZE, 1.0, |theme| {
1491                Tokens::of(theme).primary_foreground
1492            })
1493            .into(),
1494            (None, Some(initials)) => text(initials)
1495                .size(text_size::XS)
1496                .font(crate::theme::semibold())
1497                .wrapping(text::Wrapping::None)
1498                .into(),
1499            (None, None) => themed(crate::lucide!(User), menu::ICON_SIZE, 1.0, |theme| {
1500                Tokens::of(theme).foreground
1501            })
1502            .into(),
1503        };
1504        let square = container(face)
1505            .center(RAIL_BUTTON)
1506            .style(move |theme| avatar_style(&Tokens::of(theme), logo));
1507
1508        let content: Element<'a, Message> = if compact {
1509            square.into()
1510        } else {
1511            let mut lines = column![
1512                text(title)
1513                    .size(text_size::SM)
1514                    .font(crate::theme::semibold())
1515                    .wrapping(text::Wrapping::None)
1516            ];
1517            if let Some(subtitle) = subtitle {
1518                lines = lines.push(
1519                    text(subtitle)
1520                        .size(text_size::XS)
1521                        .wrapping(text::Wrapping::None)
1522                        .style(|theme: &Theme| text::Style {
1523                            color: Some(Tokens::of(theme).muted_foreground),
1524                        }),
1525                );
1526            }
1527            row![
1528                square,
1529                container(lines).width(Length::Fill).clip(true),
1530                themed(
1531                    crate::lucide!(ChevronsUpDown),
1532                    menu::ICON_SIZE,
1533                    1.0,
1534                    |theme| { Tokens::of(theme).muted_foreground }
1535                ),
1536            ]
1537            .spacing(space::SM)
1538            .align_y(Alignment::Center)
1539            .into()
1540        };
1541
1542        let width = if compact {
1543            Length::Fixed(RAIL_BUTTON)
1544        } else {
1545            Length::Fill
1546        };
1547        let padding = if compact { 0.0 } else { space::SM };
1548        button(content)
1549            .padding(padding)
1550            .width(width)
1551            .on_press_maybe(on_press)
1552            .style(|theme, status| {
1553                let status = match status {
1554                    button::Status::Disabled => button::Status::Active,
1555                    status => status,
1556                };
1557                item_style(&Tokens::of(theme), false, false, status)
1558            })
1559            .into()
1560    }
1561}
1562
1563/// The square behind a menu button's logo or initials.
1564pub fn avatar_style(tokens: &Tokens, logo: bool) -> container::Style {
1565    let (background, text_color) = if logo {
1566        (tokens.primary, tokens.primary_foreground)
1567    } else {
1568        (tokens.muted, tokens.foreground)
1569    };
1570    container::Style {
1571        background: Some(Background::Color(background)),
1572        text_color: Some(text_color),
1573        border: Border {
1574            radius: radius::MD.into(),
1575            ..Border::default()
1576        },
1577        ..container::Style::default()
1578    }
1579}
1580
1581/// Wraps part of the sidebar to watch for presses, keys and width.
1582fn watch<'a, Id, Message>(
1583    content: Element<'a, Message>,
1584    state: &'a State<Id>,
1585    keymap: Option<Keymap<Action>>,
1586    track_focus: bool,
1587    breakpoint: Option<f32>,
1588    on_event: Option<OnEvent<'a, Id, Message>>,
1589) -> Element<'a, Message>
1590where
1591    Id: Copy + PartialEq + 'a,
1592    Message: 'a,
1593{
1594    let Some(on_event) = on_event else {
1595        return content;
1596    };
1597    Element::new(Watch {
1598        content,
1599        state,
1600        keymap,
1601        track_focus,
1602        breakpoint,
1603        on_event,
1604    })
1605}
1606
1607/// Gives the sidebar keyboard focus on a press inside it and takes it
1608/// away on a press outside, resolves its keymap while it has keys, and
1609/// reports when the width crosses the breakpoint.
1610struct Watch<'a, Id, Message> {
1611    content: Element<'a, Message>,
1612    state: &'a State<Id>,
1613    keymap: Option<Keymap<Action>>,
1614    track_focus: bool,
1615    breakpoint: Option<f32>,
1616    on_event: OnEvent<'a, Id, Message>,
1617}
1618
1619fn is_press(event: &Input) -> bool {
1620    matches!(
1621        event,
1622        Input::Mouse(mouse::Event::ButtonPressed(_))
1623            | Input::Touch(touch::Event::FingerPressed { .. })
1624    )
1625}
1626
1627fn press_position(event: &Input, cursor: mouse::Cursor) -> Option<iced::Point> {
1628    match event {
1629        Input::Touch(touch::Event::FingerPressed { position, .. }) => Some(*position),
1630        _ => cursor.position(),
1631    }
1632}
1633
1634impl<Id, Message> Widget<Message, Theme, Renderer> for Watch<'_, Id, Message>
1635where
1636    Id: Copy + PartialEq,
1637{
1638    fn size(&self) -> Size<Length> {
1639        self.content.as_widget().size()
1640    }
1641
1642    fn size_hint(&self) -> Size<Length> {
1643        self.content.as_widget().size_hint()
1644    }
1645
1646    fn tag(&self) -> tree::Tag {
1647        self.content.as_widget().tag()
1648    }
1649
1650    fn state(&self) -> tree::State {
1651        self.content.as_widget().state()
1652    }
1653
1654    fn children(&self) -> Vec<Tree> {
1655        self.content.as_widget().children()
1656    }
1657
1658    fn diff(&self, tree: &mut Tree) {
1659        self.content.as_widget().diff(tree);
1660    }
1661
1662    fn layout(
1663        &mut self,
1664        tree: &mut Tree,
1665        renderer: &Renderer,
1666        limits: &layout::Limits,
1667    ) -> layout::Node {
1668        self.content.as_widget_mut().layout(tree, renderer, limits)
1669    }
1670
1671    fn draw(
1672        &self,
1673        tree: &Tree,
1674        renderer: &mut Renderer,
1675        theme: &Theme,
1676        style: &renderer::Style,
1677        layout: Layout<'_>,
1678        cursor: mouse::Cursor,
1679        viewport: &Rectangle,
1680    ) {
1681        self.content
1682            .as_widget()
1683            .draw(tree, renderer, theme, style, layout, cursor, viewport);
1684    }
1685
1686    fn operate(
1687        &mut self,
1688        tree: &mut Tree,
1689        layout: Layout<'_>,
1690        renderer: &Renderer,
1691        operation: &mut dyn Operation,
1692    ) {
1693        self.content
1694            .as_widget_mut()
1695            .operate(tree, layout, renderer, operation);
1696    }
1697
1698    fn update(
1699        &mut self,
1700        tree: &mut Tree,
1701        event: &Input,
1702        layout: Layout<'_>,
1703        cursor: mouse::Cursor,
1704        renderer: &Renderer,
1705        clipboard: &mut dyn Clipboard,
1706        shell: &mut Shell<'_, Message>,
1707        viewport: &Rectangle,
1708    ) {
1709        if let Some(breakpoint) = self.breakpoint {
1710            let narrow = layout.bounds().width < breakpoint;
1711            if narrow != self.state.narrow {
1712                shell.publish((self.on_event)(Event::Narrow(narrow)));
1713            }
1714        }
1715
1716        if let (Some(keymap), Input::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })) =
1717            (&self.keymap, event)
1718            && self.state.has_keys()
1719            && let Some(action) = keymap.resolve(key, *modifiers)
1720        {
1721            if let Some(event) = action.event(self.state) {
1722                shell.publish((self.on_event)(event));
1723            }
1724            shell.capture_event();
1725            return;
1726        }
1727
1728        if self.track_focus && is_press(event) {
1729            let inside =
1730                press_position(event, cursor).is_some_and(|point| layout.bounds().contains(point));
1731            if inside != self.state.focused {
1732                shell.publish((self.on_event)(Event::Focus(inside)));
1733            }
1734        }
1735
1736        self.content.as_widget_mut().update(
1737            tree, event, layout, cursor, renderer, clipboard, shell, viewport,
1738        );
1739    }
1740
1741    fn mouse_interaction(
1742        &self,
1743        tree: &Tree,
1744        layout: Layout<'_>,
1745        cursor: mouse::Cursor,
1746        viewport: &Rectangle,
1747        renderer: &Renderer,
1748    ) -> mouse::Interaction {
1749        self.content
1750            .as_widget()
1751            .mouse_interaction(tree, layout, cursor, viewport, renderer)
1752    }
1753
1754    fn overlay<'b>(
1755        &'b mut self,
1756        tree: &'b mut Tree,
1757        layout: Layout<'b>,
1758        renderer: &Renderer,
1759        viewport: &Rectangle,
1760        translation: Vector,
1761    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1762        self.content
1763            .as_widget_mut()
1764            .overlay(tree, layout, renderer, viewport, translation)
1765    }
1766}
1767
1768/// Makes a row a Tab stop while it can be activated.
1769fn stop<'a, Id, Message>(
1770    content: Element<'a, Message>,
1771    state: &State<Id>,
1772    row: Row<Id>,
1773    on_activate: Option<Message>,
1774    on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1775) -> Element<'a, Message>
1776where
1777    Id: Copy + PartialEq,
1778    Message: Clone + 'a,
1779{
1780    let (Some(on_activate), Some(on_event)) = (on_activate, on_event) else {
1781        return content;
1782    };
1783    Element::new(Stop {
1784        content,
1785        highlighted: state.shows_highlight() && state.highlighted == Some(row),
1786        on_focus: on_event(Event::FocusRow(row)),
1787        on_blur: on_event(Event::BlurRow(row)),
1788        on_activate,
1789    })
1790}
1791
1792/// A row that iced's focus operations visit. Focus arriving or leaving is
1793/// sent to the app as [`Event::FocusRow`] and [`Event::BlurRow`], and focus
1794/// follows the keyboard highlight, so Tab carries on from wherever the
1795/// arrow keys left it. The highlight draws the ring.
1796struct Stop<'a, Message> {
1797    content: Element<'a, Message>,
1798    highlighted: bool,
1799    on_focus: Message,
1800    on_blur: Message,
1801    on_activate: Message,
1802}
1803
1804#[derive(Debug, Clone, Copy, Default)]
1805struct StopState {
1806    focus: focus::State,
1807    /// Focus an operation gave or took, not yet sent: `true` when gained.
1808    pending: Option<bool>,
1809    /// Whether the row was highlighted when last seen.
1810    highlighted: bool,
1811}
1812
1813impl Focusable for StopState {
1814    fn is_focused(&self) -> bool {
1815        self.focus.is_focused()
1816    }
1817
1818    fn focus(&mut self) {
1819        if !self.focus.is_focused() {
1820            self.pending = Some(true);
1821        }
1822        self.focus.focus();
1823    }
1824
1825    fn unfocus(&mut self) {
1826        if self.focus.is_focused() {
1827            self.pending = Some(false);
1828        }
1829        self.focus.unfocus();
1830    }
1831}
1832
1833impl<Message: Clone> Widget<Message, Theme, Renderer> for Stop<'_, Message> {
1834    fn size(&self) -> Size<Length> {
1835        self.content.as_widget().size()
1836    }
1837
1838    fn size_hint(&self) -> Size<Length> {
1839        self.content.as_widget().size_hint()
1840    }
1841
1842    fn tag(&self) -> tree::Tag {
1843        tree::Tag::of::<StopState>()
1844    }
1845
1846    fn state(&self) -> tree::State {
1847        tree::State::new(StopState::default())
1848    }
1849
1850    fn children(&self) -> Vec<Tree> {
1851        vec![Tree::new(&self.content)]
1852    }
1853
1854    fn diff(&self, tree: &mut Tree) {
1855        tree.diff_children(std::slice::from_ref(&self.content));
1856    }
1857
1858    fn layout(
1859        &mut self,
1860        tree: &mut Tree,
1861        renderer: &Renderer,
1862        limits: &layout::Limits,
1863    ) -> layout::Node {
1864        self.content
1865            .as_widget_mut()
1866            .layout(&mut tree.children[0], renderer, limits)
1867    }
1868
1869    fn draw(
1870        &self,
1871        tree: &Tree,
1872        renderer: &mut Renderer,
1873        theme: &Theme,
1874        style: &renderer::Style,
1875        layout: Layout<'_>,
1876        cursor: mouse::Cursor,
1877        viewport: &Rectangle,
1878    ) {
1879        self.content.as_widget().draw(
1880            &tree.children[0],
1881            renderer,
1882            theme,
1883            style,
1884            layout,
1885            cursor,
1886            viewport,
1887        );
1888    }
1889
1890    fn operate(
1891        &mut self,
1892        tree: &mut Tree,
1893        layout: Layout<'_>,
1894        renderer: &Renderer,
1895        operation: &mut dyn Operation,
1896    ) {
1897        let state = tree.state.downcast_mut::<StopState>();
1898        focus::report(operation, None, layout.bounds(), state);
1899        // Under icedwright the content nests under the focus report, so the
1900        // recorder folds the focus into the row's annotation.
1901        #[cfg(feature = "icedwright")]
1902        {
1903            let content = &mut self.content;
1904            let child = &mut tree.children[0];
1905            operation.traverse(&mut |operation| {
1906                content
1907                    .as_widget_mut()
1908                    .operate(child, layout, renderer, operation);
1909            });
1910        }
1911        #[cfg(not(feature = "icedwright"))]
1912        self.content
1913            .as_widget_mut()
1914            .operate(&mut tree.children[0], layout, renderer, operation);
1915    }
1916
1917    fn update(
1918        &mut self,
1919        tree: &mut Tree,
1920        event: &Input,
1921        layout: Layout<'_>,
1922        cursor: mouse::Cursor,
1923        renderer: &Renderer,
1924        clipboard: &mut dyn Clipboard,
1925        shell: &mut Shell<'_, Message>,
1926        viewport: &Rectangle,
1927    ) {
1928        let state = tree.state.downcast_mut::<StopState>();
1929        if let Some(gained) = state.pending.take() {
1930            let message = if gained {
1931                &self.on_focus
1932            } else {
1933                &self.on_blur
1934            };
1935            shell.publish(message.clone());
1936            // The highlight seen here predates the message.
1937            state.highlighted = self.highlighted;
1938        } else if state.highlighted != self.highlighted {
1939            state.highlighted = self.highlighted;
1940            if self.highlighted {
1941                state.focus.focus();
1942            } else {
1943                state.focus.unfocus();
1944            }
1945        }
1946        let _ = state.focus.update(event);
1947        if state.focus.is_focused() && !shell.is_event_captured() && focus::activates(event) {
1948            shell.publish(self.on_activate.clone());
1949            shell.capture_event();
1950            return;
1951        }
1952        self.content.as_widget_mut().update(
1953            &mut tree.children[0],
1954            event,
1955            layout,
1956            cursor,
1957            renderer,
1958            clipboard,
1959            shell,
1960            viewport,
1961        );
1962    }
1963
1964    fn mouse_interaction(
1965        &self,
1966        tree: &Tree,
1967        layout: Layout<'_>,
1968        cursor: mouse::Cursor,
1969        viewport: &Rectangle,
1970        renderer: &Renderer,
1971    ) -> mouse::Interaction {
1972        self.content.as_widget().mouse_interaction(
1973            &tree.children[0],
1974            layout,
1975            cursor,
1976            viewport,
1977            renderer,
1978        )
1979    }
1980
1981    fn overlay<'b>(
1982        &'b mut self,
1983        tree: &'b mut Tree,
1984        layout: Layout<'b>,
1985        renderer: &Renderer,
1986        viewport: &Rectangle,
1987        translation: Vector,
1988    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1989        self.content.as_widget_mut().overlay(
1990            &mut tree.children[0],
1991            layout,
1992            renderer,
1993            viewport,
1994            translation,
1995        )
1996    }
1997}
1998
1999#[cfg(test)]
2000mod tests {
2001    use super::*;
2002    use crate::theme::{dark, light};
2003
2004    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2005    enum Page {
2006        Home,
2007        Inbox,
2008        Projects,
2009        Alpha,
2010        Beta,
2011        Archived,
2012        Settings,
2013        Billing,
2014    }
2015
2016    use Page::*;
2017
2018    fn state() -> State<Page> {
2019        State::new([
2020            group(
2021                "Platform",
2022                [
2023                    item(Home, "Home"),
2024                    item(Inbox, "Inbox").badge("12"),
2025                    item(Projects, "Projects").children([
2026                        item(Alpha, "Alpha"),
2027                        item(Beta, "Beta"),
2028                        item(Archived, "Archived").disabled(true),
2029                    ]),
2030                ],
2031            ),
2032            group(
2033                "Account",
2034                [item(Settings, "Settings"), item(Billing, "Billing")],
2035            )
2036            .collapsible(true),
2037        ])
2038    }
2039
2040    fn rows(state: &State<Page>) -> Vec<Row<Page>> {
2041        state.rows()
2042    }
2043
2044    #[test]
2045    fn builders_set_fields() {
2046        let entry = item(Home, "Home")
2047            .icon(crate::lucide!(House))
2048            .badge("3")
2049            .disabled(true);
2050        assert_eq!(entry.badge.as_deref(), Some("3"));
2051        assert!(entry.icon.is_some() && entry.disabled);
2052
2053        let nested = item(Projects, "Projects")
2054            .children([item(Alpha, "Alpha").children([item(Beta, "Beta")])]);
2055        assert!(nested.children[0].children.is_empty(), "one level deep");
2056
2057        let group = group("G", [item(Home, "Home")]).collapsible(true);
2058        assert!(group.collapsible);
2059
2060        let state = State::new([group]);
2061        assert!(!state.is_rail() && !state.is_narrow() && !state.is_focused());
2062        assert_eq!(state.active(), None);
2063    }
2064
2065    #[test]
2066    fn with_active_opens_the_parent_and_ignores_disabled() {
2067        let state = state().with_active(Beta);
2068        assert_eq!(state.active(), Some(Beta));
2069        assert!(state.is_expanded(Projects));
2070        assert_eq!(state.clone().with_active(Archived).active(), Some(Beta));
2071    }
2072
2073    #[test]
2074    fn rows_follow_what_is_showing() {
2075        let mut state = state();
2076        assert_eq!(
2077            rows(&state),
2078            [
2079                Row::Item(Home),
2080                Row::Item(Inbox),
2081                Row::Item(Projects),
2082                Row::Group(1),
2083                Row::Item(Settings),
2084                Row::Item(Billing)
2085            ]
2086        );
2087        let _ = state.update(Event::ToggleItem(Projects));
2088        assert!(rows(&state).contains(&Row::Item(Alpha)));
2089        assert!(!rows(&state).contains(&Row::Item(Archived)), "disabled");
2090        let _ = state.update(Event::ToggleGroup(1));
2091        assert!(!rows(&state).contains(&Row::Item(Settings)));
2092        assert!(rows(&state).contains(&Row::Group(1)));
2093    }
2094
2095    #[test]
2096    fn the_rail_shows_top_level_items_only() {
2097        let state = state().with_rail(true);
2098        assert!(state.is_compact());
2099        assert_eq!(
2100            rows(&state),
2101            [
2102                Row::Item(Home),
2103                Row::Item(Inbox),
2104                Row::Item(Projects),
2105                Row::Item(Settings),
2106                Row::Item(Billing)
2107            ]
2108        );
2109        let mut narrow = state.clone();
2110        let _ = narrow.update(Event::Narrow(true));
2111        assert!(
2112            narrow.is_rail() && !narrow.is_compact(),
2113            "the drawer shows labels"
2114        );
2115    }
2116
2117    #[test]
2118    fn activating_a_leaf_makes_it_active() {
2119        let mut state = state();
2120        assert_eq!(
2121            state.update(Event::Activate(Inbox)),
2122            Some(Output::Activated(Inbox))
2123        );
2124        assert_eq!(state.active(), Some(Inbox));
2125        assert_eq!(state.highlighted(), Some(Row::Item(Inbox)));
2126        assert_eq!(state.update(Event::Activate(Archived)), None);
2127        assert_eq!(state.active(), Some(Inbox));
2128    }
2129
2130    #[test]
2131    fn activating_a_parent_toggles_its_children() {
2132        let mut state = state();
2133        assert_eq!(state.update(Event::Activate(Projects)), None);
2134        assert!(state.is_expanded(Projects));
2135        let _ = state.update(Event::Activate(Projects));
2136        assert!(!state.is_expanded(Projects));
2137    }
2138
2139    #[test]
2140    fn a_parent_in_the_rail_expands_the_sidebar() {
2141        let mut state = state().with_rail(true);
2142        let _ = state.update(Event::Activate(Projects));
2143        assert!(!state.is_rail());
2144        assert!(state.is_expanded(Projects));
2145    }
2146
2147    #[test]
2148    fn up_and_down_wrap_through_rows() {
2149        let mut state = state();
2150        let _ = state.update(Event::Next);
2151        assert_eq!(state.highlighted(), Some(Row::Item(Home)));
2152        let _ = state.update(Event::Previous);
2153        assert_eq!(state.highlighted(), Some(Row::Item(Billing)));
2154        let _ = state.update(Event::Next);
2155        assert_eq!(state.highlighted(), Some(Row::Item(Home)));
2156        let _ = state.update(Event::Last);
2157        assert_eq!(state.highlighted(), Some(Row::Item(Billing)));
2158        let _ = state.update(Event::First);
2159        assert_eq!(state.highlighted(), Some(Row::Item(Home)));
2160    }
2161
2162    #[test]
2163    fn enter_activates_the_highlight() {
2164        let mut state = state();
2165        let _ = state.update(Event::Next);
2166        let _ = state.update(Event::Next);
2167        assert_eq!(
2168            state.update(Event::ActivateHighlighted),
2169            Some(Output::Activated(Inbox))
2170        );
2171        let _ = state.update(Event::Last);
2172        let _ = state.update(Event::Previous);
2173        let _ = state.update(Event::Previous);
2174        assert_eq!(state.highlighted(), Some(Row::Group(1)));
2175        let _ = state.update(Event::ActivateHighlighted);
2176        assert!(!state.is_group_open(1));
2177    }
2178
2179    #[test]
2180    fn right_and_left_open_close_and_move_through_parents() {
2181        let mut state = state();
2182        state.highlighted = Some(Row::Item(Projects));
2183        let _ = state.update(Event::Expand);
2184        assert!(state.is_expanded(Projects));
2185        let _ = state.update(Event::Expand);
2186        assert_eq!(state.highlighted(), Some(Row::Item(Alpha)));
2187        let _ = state.update(Event::Collapse);
2188        assert_eq!(state.highlighted(), Some(Row::Item(Projects)));
2189        let _ = state.update(Event::Collapse);
2190        assert!(!state.is_expanded(Projects));
2191    }
2192
2193    #[test]
2194    fn right_and_left_open_and_close_groups() {
2195        let mut state = state();
2196        state.highlighted = Some(Row::Item(Settings));
2197        let _ = state.update(Event::Collapse);
2198        assert_eq!(state.highlighted(), Some(Row::Group(1)));
2199        let _ = state.update(Event::Collapse);
2200        assert!(!state.is_group_open(1));
2201        let _ = state.update(Event::Expand);
2202        assert!(state.is_group_open(1));
2203        let _ = state.update(Event::Expand);
2204        assert_eq!(state.highlighted(), Some(Row::Item(Settings)));
2205        state.highlighted = Some(Row::Item(Home));
2206        let _ = state.update(Event::Collapse);
2207        assert_eq!(state.highlighted(), Some(Row::Item(Home)), "group is fixed");
2208    }
2209
2210    #[test]
2211    fn closing_moves_a_hidden_highlight_out() {
2212        let mut state = state().with_active(Alpha);
2213        state.highlighted = Some(Row::Item(Alpha));
2214        let _ = state.update(Event::ToggleItem(Projects));
2215        assert_eq!(state.highlighted(), Some(Row::Item(Projects)));
2216
2217        state.highlighted = Some(Row::Item(Billing));
2218        let _ = state.update(Event::ToggleGroup(1));
2219        assert_eq!(state.highlighted(), Some(Row::Group(1)));
2220        let _ = state.update(Event::ToggleGroup(0));
2221        assert!(state.is_group_open(0), "fixed groups stay open");
2222    }
2223
2224    #[test]
2225    fn toggling_the_rail_moves_the_highlight_to_a_showing_row() {
2226        let mut state = state().with_active(Alpha);
2227        state.highlighted = Some(Row::Item(Alpha));
2228        let _ = state.update(Event::ToggleRail);
2229        assert!(state.is_rail());
2230        assert_eq!(state.highlighted(), Some(Row::Item(Projects)));
2231        state.highlighted = Some(Row::Group(1));
2232        let _ = state.update(Event::SetRail(true));
2233        assert_eq!(state.highlighted(), Some(Row::Item(Settings)));
2234    }
2235
2236    #[test]
2237    fn the_trigger_toggles_the_rail_or_the_drawer() {
2238        let mut state = state().with_active(Inbox);
2239        let _ = state.update(Event::Toggle);
2240        assert!(state.is_rail());
2241        let _ = state.update(Event::Narrow(true));
2242        let _ = state.update(Event::Toggle);
2243        assert!(state.is_drawer_open());
2244        assert_eq!(state.highlighted(), Some(Row::Item(Inbox)));
2245        let _ = state.update(Event::Toggle);
2246        assert!(!state.is_drawer_open());
2247    }
2248
2249    #[test]
2250    fn the_drawer_closes_on_activation_and_when_the_window_widens() {
2251        let mut state = state();
2252        let _ = state.update(Event::Narrow(true));
2253        let _ = state.update(Event::OpenDrawer);
2254        assert!(state.has_keys());
2255        let _ = state.update(Event::Activate(Home));
2256        assert!(!state.is_drawer_open());
2257
2258        let _ = state.update(Event::OpenDrawer);
2259        let _ = state.update(Event::Narrow(false));
2260        assert!(!state.is_drawer_open());
2261        let _ = state.update(Event::Narrow(true));
2262        assert!(!state.is_drawer_open(), "stays closed");
2263        let _ = state.update(Event::ToggleDrawer);
2264        let _ = state.update(Event::CloseDrawer);
2265        assert!(!state.is_drawer_open());
2266    }
2267
2268    #[test]
2269    fn the_ring_shows_once_the_keyboard_moves_the_highlight() {
2270        let mut state = state().with_active(Home);
2271        let _ = state.update(Event::Focus(true));
2272        assert!(!state.shows_highlight(), "a press does not draw the ring");
2273        let _ = state.update(Event::Next);
2274        assert!(state.shows_highlight());
2275        let _ = state.update(Event::Activate(Inbox));
2276        assert!(!state.shows_highlight(), "a click hides it again");
2277        let _ = state.update(Event::Next);
2278        let _ = state.update(Event::Focus(false));
2279        assert!(!state.shows_highlight(), "only while the sidebar has keys");
2280    }
2281
2282    #[test]
2283    fn focus_highlights_the_active_item() {
2284        let mut state = state().with_active(Beta);
2285        let _ = state.update(Event::Focus(true));
2286        assert!(state.is_focused());
2287        assert_eq!(state.highlighted(), Some(Row::Item(Beta)));
2288        let _ = state.update(Event::Focus(false));
2289        assert!(!state.has_keys());
2290
2291        let mut closed = state.clone();
2292        closed.highlighted = None;
2293        let _ = closed.update(Event::ToggleItem(Projects));
2294        let _ = closed.update(Event::Focus(true));
2295        assert_eq!(closed.highlighted(), Some(Row::Item(Projects)));
2296    }
2297
2298    #[test]
2299    fn focus_on_a_row_highlights_and_rings_it() {
2300        let mut state = state();
2301        let _ = state.update(Event::FocusRow(Row::Item(Inbox)));
2302        assert!(state.is_focused() && state.shows_highlight());
2303        assert_eq!(state.highlighted(), Some(Row::Item(Inbox)));
2304
2305        let _ = state.update(Event::FocusRow(Row::Item(Archived)));
2306        assert_eq!(
2307            state.highlighted(),
2308            Some(Row::Item(Inbox)),
2309            "a row that is not showing is never highlighted"
2310        );
2311    }
2312
2313    #[test]
2314    fn blur_gives_up_focus_only_from_the_highlighted_row() {
2315        let mut state = state();
2316        let _ = state.update(Event::FocusRow(Row::Item(Home)));
2317        // Tab onwards: the next row hears first, then the one left behind.
2318        let _ = state.update(Event::FocusRow(Row::Item(Inbox)));
2319        let _ = state.update(Event::BlurRow(Row::Item(Home)));
2320        assert!(state.is_focused());
2321        assert_eq!(state.highlighted(), Some(Row::Item(Inbox)));
2322
2323        let _ = state.update(Event::BlurRow(Row::Item(Inbox)));
2324        assert!(!state.is_focused() && !state.shows_highlight());
2325    }
2326
2327    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
2328        let chord: Chord = chord.parse().unwrap();
2329        keymap.resolve(chord.key(), chord.modifiers())
2330    }
2331
2332    #[test]
2333    fn default_keymap_covers_every_action() {
2334        let keymap = default_keymap();
2335        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
2336        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
2337        assert_eq!(press(&keymap, "Home"), Some(Action::First));
2338        assert_eq!(press(&keymap, "End"), Some(Action::Last));
2339        assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
2340        assert_eq!(press(&keymap, "Space"), Some(Action::Activate));
2341        assert_eq!(press(&keymap, "ArrowRight"), Some(Action::Expand));
2342        assert_eq!(press(&keymap, "ArrowLeft"), Some(Action::Collapse));
2343        assert_eq!(press(&keymap, "Mod+B"), Some(Action::ToggleRail));
2344        assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
2345        assert_eq!(press(&keymap, "B"), None);
2346        for action in <Action as keys::Action>::ALL {
2347            assert!(!keymap.chords(action).is_empty(), "{action:?}");
2348        }
2349        assert_eq!(Keymap::<Action>::defaults(), keymap);
2350    }
2351
2352    #[test]
2353    fn keymap_overrides_and_unbinding() {
2354        let keymap = default_keymap()
2355            .unbind(&"Mod+B".parse().unwrap())
2356            .bind("Ctrl+Shift+S".parse().unwrap(), Action::ToggleRail);
2357        assert_eq!(press(&keymap, "Mod+B"), None);
2358        assert_eq!(press(&keymap, "Ctrl+Shift+S"), Some(Action::ToggleRail));
2359    }
2360
2361    #[test]
2362    fn actions_map_to_events() {
2363        let mut state = state();
2364        assert_eq!(Action::Next.event(&state), Some(Event::Next));
2365        assert_eq!(
2366            Action::Activate.event(&state),
2367            Some(Event::ActivateHighlighted)
2368        );
2369        assert_eq!(Action::ToggleRail.event(&state), Some(Event::Toggle));
2370        assert_eq!(Action::Close.event(&state), None);
2371        let _ = state.update(Event::Focus(true));
2372        assert_eq!(Action::Close.event(&state), Some(Event::Focus(false)));
2373        let _ = state.update(Event::Narrow(true));
2374        let _ = state.update(Event::OpenDrawer);
2375        assert_eq!(Action::Close.event(&state), Some(Event::CloseDrawer));
2376    }
2377
2378    #[test]
2379    fn shortcut_only_resolves_the_app_wide_action() {
2380        let state = state();
2381        let keymap = default_keymap();
2382        let key = |chord: &str| {
2383            let chord: Chord = chord.parse().unwrap();
2384            keys::Event {
2385                key: chord.key().clone(),
2386                modifiers: chord.modifiers(),
2387            }
2388        };
2389        assert_eq!(state.shortcut(&keymap, &key("Mod+B")), Some(Event::Toggle));
2390        assert_eq!(state.shortcut(&keymap, &key("ArrowDown")), None);
2391    }
2392
2393    #[test]
2394    fn rows_highlight_when_active_hovered_or_pressed() {
2395        for theme in [light(), dark()] {
2396            let tokens = Tokens::of(&theme);
2397            let idle = item_style(&tokens, false, false, button::Status::Active);
2398            assert_eq!(idle.background, None);
2399            assert_eq!(idle.text_color, tokens.foreground);
2400            for status in [button::Status::Hovered, button::Status::Pressed] {
2401                let style = item_style(&tokens, false, false, status);
2402                assert_eq!(style.background, Some(Background::Color(tokens.accent)));
2403            }
2404            let active = item_style(&tokens, true, false, button::Status::Active);
2405            assert_eq!(active.background, Some(Background::Color(tokens.accent)));
2406            let disabled = item_style(&tokens, true, false, button::Status::Disabled);
2407            assert_eq!(disabled.background, None);
2408            assert_eq!(disabled.text_color, tokens.muted_foreground);
2409        }
2410    }
2411
2412    #[test]
2413    fn the_keyboard_highlight_draws_a_ring() {
2414        let tokens = Tokens::of(&light());
2415        let ring = item_style(&tokens, false, true, button::Status::Active);
2416        assert_eq!(ring.border.color, tokens.ring);
2417        assert_eq!(ring.border.width, 1.0);
2418        let plain = item_style(&tokens, false, false, button::Status::Active);
2419        assert_eq!(plain.border.width, 0.0);
2420    }
2421
2422    #[test]
2423    fn surfaces_sit_between_page_and_card() {
2424        for theme in [light(), dark()] {
2425            let tokens = Tokens::of(&theme);
2426            let surface = surface_style(&tokens).background;
2427            assert!(surface.is_some());
2428            assert_ne!(surface, Some(Background::Color(tokens.background)));
2429            assert_eq!(
2430                edge_style(&tokens).background,
2431                Some(Background::Color(tokens.border))
2432            );
2433            assert!(scrim_style(&tokens).background.is_some());
2434        }
2435        let logo = avatar_style(&Tokens::of(&light()), true);
2436        assert_eq!(
2437            logo.text_color,
2438            Some(Tokens::of(&light()).primary_foreground)
2439        );
2440    }
2441
2442    #[test]
2443    fn builder_defaults() {
2444        let state = state();
2445        let sidebar: Sidebar<'_, Page, ()> = sidebar(&state);
2446        assert_eq!(sidebar.breakpoint, BREAKPOINT);
2447        assert!(sidebar.trigger);
2448        assert!(sidebar.content.is_none());
2449        assert!(sidebar.on_event.is_none());
2450        assert_eq!(sidebar.keymap, default_keymap());
2451    }
2452}