1use std::rc::Rc;
24
25use iced::Event as Input;
26use iced::advanced::layout::{self, Layout};
27use iced::advanced::widget::{Operation, Tree, Widget, tree};
28use iced::advanced::{Clipboard, Shell, overlay, renderer};
29use iced::keyboard::{self, key::Named};
30use iced::widget::{Space, button, column, container, mouse_area, row, scrollable, stack, text};
31use iced::{
32 Alignment, Background, Border, Color, Element, Length, Padding, Rectangle, Renderer, Shadow,
33 Size, Theme, Vector, mouse, touch,
34};
35
36use crate::icon::{Glyph, themed};
37use crate::keys::{self, Chord, Keymap};
38use crate::overlay::menu::{self, Parts, RowStatus};
39use crate::overlay::tooltip::{Position, tooltip};
40use crate::primitives::icon_button::{IconButton, icon_button};
41use crate::solid::solid;
42use crate::theme::{Tokens, fade, mix, radius, space, text_size};
43
44pub const WIDTH: f32 = 256.0;
46pub const RAIL_WIDTH: f32 = 48.0;
48pub const DRAWER_WIDTH: f32 = 288.0;
50pub const BREAKPOINT: f32 = 640.0;
52pub const BAR_HEIGHT: f32 = 48.0;
54
55const RAIL_BUTTON: f32 = 32.0;
57
58pub const TRIGGER_ID: iced::widget::Id = iced::widget::Id::new("iced-cube-sidebar-trigger");
60
61#[derive(Debug, Clone, PartialEq)]
64pub struct Item<Id> {
65 pub id: Id,
66 pub label: String,
67 pub icon: Option<Glyph>,
68 pub badge: Option<String>,
70 pub disabled: bool,
71 pub children: Vec<Item<Id>>,
72}
73
74pub fn item<Id>(id: Id, label: impl Into<String>) -> Item<Id> {
76 Item {
77 id,
78 label: label.into(),
79 icon: None,
80 badge: None,
81 disabled: false,
82 children: Vec::new(),
83 }
84}
85
86impl<Id> Item<Id> {
87 pub fn icon(mut self, glyph: Glyph) -> Self {
88 self.icon = Some(glyph);
89 self
90 }
91
92 pub fn badge(mut self, badge: impl Into<String>) -> Self {
93 self.badge = Some(badge.into());
94 self
95 }
96
97 pub fn disabled(mut self, disabled: bool) -> Self {
98 self.disabled = disabled;
99 self
100 }
101
102 pub fn children(mut self, children: impl IntoIterator<Item = Item<Id>>) -> Self {
104 self.children = children
105 .into_iter()
106 .map(|mut child| {
107 child.children.clear();
108 child
109 })
110 .collect();
111 self
112 }
113
114 pub fn has_children(&self) -> bool {
115 !self.children.is_empty()
116 }
117}
118
119#[derive(Debug, Clone, PartialEq)]
121pub struct Group<Id> {
122 pub label: String,
124 pub items: Vec<Item<Id>>,
125 pub collapsible: bool,
127}
128
129pub fn group<Id>(label: impl Into<String>, items: impl IntoIterator<Item = Item<Id>>) -> Group<Id> {
131 Group {
132 label: label.into(),
133 items: items.into_iter().collect(),
134 collapsible: false,
135 }
136}
137
138impl<Id> Group<Id> {
139 pub fn collapsible(mut self, collapsible: bool) -> Self {
140 self.collapsible = collapsible;
141 self
142 }
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148pub enum Row<Id> {
149 Group(usize),
150 Item(Id),
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum Event<Id> {
156 Activate(Id),
159 Next,
161 Previous,
163 First,
164 Last,
165 ActivateHighlighted,
168 Expand,
170 Collapse,
172 ToggleGroup(usize),
173 ToggleItem(Id),
175 ToggleRail,
176 SetRail(bool),
177 OpenDrawer,
178 CloseDrawer,
179 ToggleDrawer,
180 Toggle,
183 Narrow(bool),
186 Focus(bool),
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum Output<Id> {
193 Activated(Id),
195}
196
197#[derive(Debug, Clone, PartialEq)]
199pub struct State<Id> {
200 groups: Vec<Group<Id>>,
201 active: Option<Id>,
202 highlighted: Option<Row<Id>>,
203 closed: Vec<bool>,
204 expanded: Vec<Id>,
205 rail: bool,
206 drawer: bool,
207 narrow: bool,
208 focused: bool,
209 keyboard: bool,
211}
212
213impl<Id: Copy + PartialEq> State<Id> {
214 pub fn new(groups: impl IntoIterator<Item = Group<Id>>) -> Self {
216 let groups: Vec<Group<Id>> = groups.into_iter().collect();
217 Self {
218 closed: vec![false; groups.len()],
219 groups,
220 active: None,
221 highlighted: None,
222 expanded: Vec::new(),
223 rail: false,
224 drawer: false,
225 narrow: false,
226 focused: false,
227 keyboard: false,
228 }
229 }
230
231 pub fn with_active(mut self, id: Id) -> Self {
233 if self.item(id).is_some_and(|item| !item.disabled) {
234 self.active = Some(id);
235 if let Some(parent) = self.parent_of(id) {
236 self.open_item(parent);
237 }
238 }
239 self
240 }
241
242 pub fn with_rail(mut self, rail: bool) -> Self {
244 self.rail = rail;
245 self
246 }
247
248 pub fn groups(&self) -> &[Group<Id>] {
249 &self.groups
250 }
251
252 pub fn active(&self) -> Option<Id> {
253 self.active
254 }
255
256 pub fn highlighted(&self) -> Option<Row<Id>> {
257 self.highlighted
258 }
259
260 pub fn is_rail(&self) -> bool {
262 self.rail
263 }
264
265 pub fn is_compact(&self) -> bool {
268 self.rail && !self.narrow
269 }
270
271 pub fn is_narrow(&self) -> bool {
272 self.narrow
273 }
274
275 pub fn is_drawer_open(&self) -> bool {
276 self.narrow && self.drawer
277 }
278
279 pub fn is_focused(&self) -> bool {
280 self.focused
281 }
282
283 pub fn shows_highlight(&self) -> bool {
286 self.keyboard && self.has_keys()
287 }
288
289 pub fn has_keys(&self) -> bool {
292 self.focused || self.is_drawer_open()
293 }
294
295 pub fn is_group_open(&self, group: usize) -> bool {
296 !self.closed.get(group).copied().unwrap_or(true)
297 }
298
299 pub fn is_expanded(&self, id: Id) -> bool {
300 self.expanded.contains(&id)
301 }
302
303 pub fn item(&self, id: Id) -> Option<&Item<Id>> {
304 self.groups
305 .iter()
306 .flat_map(|group| &group.items)
307 .find_map(|item| {
308 if item.id == id {
309 return Some(item);
310 }
311 item.children.iter().find(|child| child.id == id)
312 })
313 }
314
315 pub fn parent_of(&self, id: Id) -> Option<Id> {
317 self.groups
318 .iter()
319 .flat_map(|group| &group.items)
320 .find(|item| item.children.iter().any(|child| child.id == id))
321 .map(|item| item.id)
322 }
323
324 fn group_of(&self, id: Id) -> Option<usize> {
325 self.groups.iter().position(|group| {
326 group
327 .items
328 .iter()
329 .any(|item| item.id == id || item.children.iter().any(|child| child.id == id))
330 })
331 }
332
333 pub fn is_active_branch(&self, item: &Item<Id>) -> bool {
336 Some(item.id) == self.active
337 || self
338 .active
339 .is_some_and(|active| item.children.iter().any(|child| child.id == active))
340 }
341
342 pub fn rows(&self) -> Vec<Row<Id>> {
345 let compact = self.is_compact();
346 let mut rows = Vec::new();
347 for (index, group) in self.groups.iter().enumerate() {
348 if group.collapsible && !compact {
349 rows.push(Row::Group(index));
350 }
351 if !compact && !self.is_group_open(index) {
352 continue;
353 }
354 for item in group.items.iter().filter(|item| !item.disabled) {
355 rows.push(Row::Item(item.id));
356 if compact || !self.is_expanded(item.id) {
357 continue;
358 }
359 rows.extend(
360 item.children
361 .iter()
362 .filter(|child| !child.disabled)
363 .map(|child| Row::Item(child.id)),
364 );
365 }
366 }
367 rows
368 }
369
370 pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>> {
372 match event {
373 Event::Next
374 | Event::Previous
375 | Event::First
376 | Event::Last
377 | Event::ActivateHighlighted
378 | Event::Expand
379 | Event::Collapse => self.keyboard = true,
380 Event::Activate(_)
381 | Event::ToggleGroup(_)
382 | Event::ToggleItem(_)
383 | Event::Focus(_)
384 | Event::OpenDrawer
385 | Event::ToggleDrawer
386 | Event::Toggle => self.keyboard = false,
387 _ => {}
388 }
389 match event {
390 Event::Activate(id) => return self.activate(id),
391 Event::Next => self.step(true),
392 Event::Previous => self.step(false),
393 Event::First => self.highlighted = self.rows().first().copied(),
394 Event::Last => self.highlighted = self.rows().last().copied(),
395 Event::ActivateHighlighted => match self.highlighted {
396 Some(Row::Group(index)) => self.toggle_group(index),
397 Some(Row::Item(id)) => return self.activate(id),
398 None => self.step(true),
399 },
400 Event::Expand => self.expand(),
401 Event::Collapse => self.collapse(),
402 Event::ToggleGroup(index) => self.toggle_group(index),
403 Event::ToggleItem(id) => self.toggle_item(id),
404 Event::ToggleRail => self.set_rail(!self.rail),
405 Event::SetRail(rail) => self.set_rail(rail),
406 Event::OpenDrawer => self.open_drawer(),
407 Event::CloseDrawer => self.drawer = false,
408 Event::ToggleDrawer if self.drawer => self.drawer = false,
409 Event::ToggleDrawer => self.open_drawer(),
410 Event::Toggle if self.narrow => {
411 return self.update(Event::ToggleDrawer);
412 }
413 Event::Toggle => self.set_rail(!self.rail),
414 Event::Narrow(narrow) => {
415 self.narrow = narrow;
416 if !narrow {
417 self.drawer = false;
418 }
419 self.settle_highlight();
420 }
421 Event::Focus(focused) => {
422 self.focused = focused;
423 if focused && self.highlighted.is_none() {
424 self.highlight_active();
425 }
426 }
427 }
428 None
429 }
430
431 pub fn shortcut(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event<Id>> {
435 keymap
436 .resolve_event(key)
437 .filter(|action| *action == Action::ToggleRail)
438 .and_then(|action| action.event(self))
439 }
440
441 fn activate(&mut self, id: Id) -> Option<Output<Id>> {
442 let item = self.item(id).filter(|item| !item.disabled)?;
443 if item.has_children() {
444 if self.is_compact() {
445 self.rail = false;
446 self.open_item(id);
447 } else {
448 self.toggle_item(id);
449 }
450 self.highlighted = Some(Row::Item(id));
451 return None;
452 }
453 self.active = Some(id);
454 self.highlighted = Some(Row::Item(id));
455 self.drawer = false;
456 Some(Output::Activated(id))
457 }
458
459 fn step(&mut self, forward: bool) {
460 let rows = self.rows();
461 if rows.is_empty() {
462 return;
463 }
464 let current = self
465 .highlighted
466 .and_then(|row| rows.iter().position(|candidate| *candidate == row));
467 let len = rows.len();
468 let next = match (current, forward) {
469 (None, true) => 0,
470 (None, false) => len - 1,
471 (Some(index), true) => (index + 1) % len,
472 (Some(index), false) => (index + len - 1) % len,
473 };
474 self.highlighted = rows.get(next).copied();
475 }
476
477 fn expand(&mut self) {
478 match self.highlighted {
479 Some(Row::Group(index)) if !self.is_group_open(index) => self.toggle_group(index),
480 Some(Row::Group(index)) => {
481 self.highlighted = self
482 .groups
483 .get(index)
484 .and_then(|group| group.items.iter().find(|item| !item.disabled))
485 .map(|item| Row::Item(item.id));
486 }
487 Some(Row::Item(id)) => {
488 let Some(item) = self.item(id).filter(|item| item.has_children()) else {
489 return;
490 };
491 if self.is_compact() {
492 return;
493 }
494 if !self.is_expanded(id) {
495 self.open_item(id);
496 return;
497 }
498 if let Some(child) = item.children.iter().find(|child| !child.disabled) {
499 self.highlighted = Some(Row::Item(child.id));
500 }
501 }
502 None => {}
503 }
504 }
505
506 fn collapse(&mut self) {
507 match self.highlighted {
508 Some(Row::Group(index)) if self.is_group_open(index) => self.toggle_group(index),
509 Some(Row::Group(_)) | None => {}
510 Some(Row::Item(id)) => {
511 if self.is_expanded(id) {
512 self.toggle_item(id);
513 return;
514 }
515 if let Some(parent) = self.parent_of(id) {
516 self.highlighted = Some(Row::Item(parent));
517 return;
518 }
519 let group = self
520 .group_of(id)
521 .filter(|&index| self.groups[index].collapsible && !self.is_compact());
522 if let Some(index) = group {
523 self.highlighted = Some(Row::Group(index));
524 }
525 }
526 }
527 }
528
529 fn toggle_group(&mut self, index: usize) {
530 let Some(closed) = self.closed.get_mut(index) else {
531 return;
532 };
533 if !self.groups[index].collapsible {
534 return;
535 }
536 *closed = !*closed;
537 if *closed && self.highlighted.is_some() {
538 let inside = match self.highlighted {
539 Some(Row::Item(id)) => self.group_of(id) == Some(index),
540 _ => false,
541 };
542 if inside {
543 self.highlighted = Some(Row::Group(index));
544 }
545 }
546 }
547
548 fn open_item(&mut self, id: Id) {
549 if !self.expanded.contains(&id) {
550 self.expanded.push(id);
551 }
552 }
553
554 fn toggle_item(&mut self, id: Id) {
555 if !self.item(id).is_some_and(Item::has_children) {
556 return;
557 }
558 if !self.expanded.contains(&id) {
559 self.open_item(id);
560 return;
561 }
562 self.expanded.retain(|expanded| *expanded != id);
563 if let Some(Row::Item(highlighted)) = self.highlighted
564 && self.parent_of(highlighted) == Some(id)
565 {
566 self.highlighted = Some(Row::Item(id));
567 }
568 }
569
570 fn set_rail(&mut self, rail: bool) {
571 self.rail = rail;
572 self.settle_highlight();
573 }
574
575 fn open_drawer(&mut self) {
576 self.drawer = true;
577 self.highlight_active();
578 }
579
580 fn highlight_active(&mut self) {
582 let rows = self.rows();
583 let active = self
584 .active
585 .map(Row::Item)
586 .filter(|row| rows.contains(row))
587 .or_else(|| {
588 self.active
589 .and_then(|id| self.parent_of(id))
590 .map(Row::Item)
591 .filter(|row| rows.contains(row))
592 });
593 self.highlighted = active.or_else(|| rows.first().copied());
594 }
595
596 fn settle_highlight(&mut self) {
599 let Some(row) = self.highlighted else {
600 return;
601 };
602 let rows = self.rows();
603 if rows.contains(&row) {
604 return;
605 }
606 let fallback = match row {
607 Row::Item(id) => self
608 .parent_of(id)
609 .map(Row::Item)
610 .filter(|row| rows.contains(row)),
611 Row::Group(index) => self
612 .groups
613 .get(index)
614 .and_then(|group| group.items.iter().find(|item| !item.disabled))
615 .map(|item| Row::Item(item.id)),
616 };
617 self.highlighted = fallback;
618 }
619}
620
621#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
623pub enum Action {
624 Next,
625 Previous,
626 First,
627 Last,
628 Activate,
629 Expand,
630 Collapse,
631 ToggleRail,
634 Close,
636}
637
638impl Action {
639 pub fn event<Id: Copy + PartialEq>(self, state: &State<Id>) -> Option<Event<Id>> {
642 let event = match self {
643 Action::Next => Event::Next,
644 Action::Previous => Event::Previous,
645 Action::First => Event::First,
646 Action::Last => Event::Last,
647 Action::Activate => Event::ActivateHighlighted,
648 Action::Expand => Event::Expand,
649 Action::Collapse => Event::Collapse,
650 Action::ToggleRail => Event::Toggle,
651 Action::Close if state.is_drawer_open() => Event::CloseDrawer,
652 Action::Close if state.is_focused() => Event::Focus(false),
653 Action::Close => return None,
654 };
655 Some(event)
656 }
657}
658
659impl keys::Action for Action {
660 const ALL: &'static [Self] = &[
661 Action::Next,
662 Action::Previous,
663 Action::First,
664 Action::Last,
665 Action::Activate,
666 Action::Expand,
667 Action::Collapse,
668 Action::ToggleRail,
669 Action::Close,
670 ];
671
672 fn defaults() -> Keymap<Self> {
673 default_keymap()
674 }
675
676 fn name(self) -> &'static str {
677 match self {
678 Action::Next => "Next",
679 Action::Previous => "Previous",
680 Action::First => "First",
681 Action::Last => "Last",
682 Action::Activate => "Activate",
683 Action::Expand => "Expand",
684 Action::Collapse => "Collapse",
685 Action::ToggleRail => "ToggleRail",
686 Action::Close => "Close",
687 }
688 }
689
690 fn description(self) -> &'static str {
691 match self {
692 Action::Next => "Highlights the next row, wrapping.",
693 Action::Previous => "Highlights the previous row, wrapping.",
694 Action::First => "Highlights the first row.",
695 Action::Last => "Highlights the last row.",
696 Action::Activate => "Activates the highlighted item or opens and closes its group.",
697 Action::Expand => "Opens the highlighted group or parent item, or moves into it.",
698 Action::Collapse => "Closes the highlighted group or parent item, or moves out to it.",
699 Action::ToggleRail => {
700 "Collapses the sidebar to an icon rail and back, or toggles the drawer on a narrow window."
701 }
702 Action::Close => "Closes the drawer, or leaves the sidebar.",
703 }
704 }
705}
706
707pub fn default_keymap() -> Keymap<Action> {
725 Keymap::new()
726 .bind(Chord::named(Named::ArrowDown), Action::Next)
727 .bind(Chord::named(Named::ArrowUp), Action::Previous)
728 .bind(Chord::named(Named::Home), Action::First)
729 .bind(Chord::named(Named::End), Action::Last)
730 .bind(Chord::named(Named::Enter), Action::Activate)
731 .bind(Chord::named(Named::Space), Action::Activate)
732 .bind(Chord::named(Named::ArrowRight), Action::Expand)
733 .bind(Chord::named(Named::ArrowLeft), Action::Collapse)
734 .bind(Chord::character('b').command(), Action::ToggleRail)
735 .bind(Chord::named(Named::Escape), Action::Close)
736}
737
738pub fn surface_style(tokens: &Tokens) -> container::Style {
741 let background = if tokens.is_dark {
742 mix(tokens.background, tokens.foreground, 0.04)
743 } else {
744 mix(tokens.background, tokens.muted, 0.5)
745 };
746 container::Style {
747 background: Some(Background::Color(background)),
748 text_color: Some(tokens.foreground),
749 ..container::Style::default()
750 }
751}
752
753pub fn edge_style(tokens: &Tokens) -> container::Style {
755 container::Style {
756 background: Some(Background::Color(tokens.border)),
757 ..container::Style::default()
758 }
759}
760
761pub fn scrim_style(tokens: &Tokens) -> container::Style {
763 container::Style {
764 background: Some(Background::Color(fade(
765 Color::BLACK,
766 if tokens.is_dark { 0.7 } else { 0.5 },
767 ))),
768 ..container::Style::default()
769 }
770}
771
772pub fn item_style(
776 tokens: &Tokens,
777 active: bool,
778 keyboard: bool,
779 status: button::Status,
780) -> button::Style {
781 let row = match status {
782 button::Status::Disabled => RowStatus::Disabled,
783 _ if active => RowStatus::Highlighted,
784 button::Status::Hovered | button::Status::Pressed => RowStatus::Highlighted,
785 button::Status::Active => RowStatus::Idle,
786 };
787 let colours = menu::row_style(tokens, row, false);
788 button::Style {
789 background: colours.background.map(Background::Color),
790 text_color: colours.text,
791 border: Border {
792 color: if keyboard {
793 tokens.ring
794 } else {
795 Color::TRANSPARENT
796 },
797 width: if keyboard { 1.0 } else { 0.0 },
798 radius: radius::SM.into(),
799 },
800 shadow: Shadow::default(),
801 snap: true,
802 }
803}
804
805pub struct Sidebar<'a, Id, Message> {
807 state: &'a State<Id>,
808 header: Option<Element<'a, Message>>,
809 footer: Option<Element<'a, Message>>,
810 content: Option<Element<'a, Message>>,
811 width: Option<Length>,
812 breakpoint: f32,
813 trigger: bool,
814 keymap: Keymap<Action>,
815 on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
816}
817
818impl<Id: std::fmt::Debug, Message> std::fmt::Debug for Sidebar<'_, Id, Message> {
819 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
820 f.debug_struct("Sidebar")
821 .field("state", self.state)
822 .field("width", &self.width)
823 .field("breakpoint", &self.breakpoint)
824 .field("trigger", &self.trigger)
825 .field("keymap", &self.keymap)
826 .finish_non_exhaustive()
827 }
828}
829
830pub fn sidebar<Id, Message>(state: &State<Id>) -> Sidebar<'_, Id, Message> {
833 Sidebar {
834 state,
835 header: None,
836 footer: None,
837 content: None,
838 width: None,
839 breakpoint: BREAKPOINT,
840 trigger: true,
841 keymap: default_keymap(),
842 on_event: None,
843 }
844}
845
846impl<'a, Id, Message> Sidebar<'a, Id, Message> {
847 pub fn header(mut self, header: impl Into<Element<'a, Message>>) -> Self {
850 self.header = Some(header.into());
851 self
852 }
853
854 pub fn footer(mut self, footer: impl Into<Element<'a, Message>>) -> Self {
856 self.footer = Some(footer.into());
857 self
858 }
859
860 pub fn content(mut self, content: impl Into<Element<'a, Message>>) -> Self {
863 self.content = Some(content.into());
864 self
865 }
866
867 pub fn width(mut self, width: impl Into<Length>) -> Self {
870 self.width = Some(width.into());
871 self
872 }
873
874 pub fn breakpoint(mut self, width: f32) -> Self {
876 self.breakpoint = width;
877 self
878 }
879
880 pub fn trigger(mut self, trigger: bool) -> Self {
883 self.trigger = trigger;
884 self
885 }
886
887 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
890 self.keymap = keymap;
891 self
892 }
893
894 pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
895 self.on_event = Some(Box::new(on_event));
896 self
897 }
898}
899
900type OnEvent<'a, Id, Message> = Rc<dyn Fn(Event<Id>) -> Message + 'a>;
901
902#[derive(Debug, Clone, Copy, PartialEq, Eq)]
904enum Mode {
905 Docked,
906 Rail,
907 Drawer,
908}
909
910impl<'a, Id, Message> From<Sidebar<'a, Id, Message>> for Element<'a, Message>
911where
912 Id: Copy + PartialEq + 'a,
913 Message: Clone + 'a,
914{
915 fn from(sidebar: Sidebar<'a, Id, Message>) -> Self {
916 let Sidebar {
917 state,
918 header,
919 footer,
920 content,
921 width,
922 breakpoint,
923 trigger: show_trigger,
924 keymap,
925 on_event,
926 } = sidebar;
927 let on_event: Option<OnEvent<'a, Id, Message>> = on_event.map(Rc::from);
928
929 let Some(content) = content else {
930 let mode = if state.rail { Mode::Rail } else { Mode::Docked };
931 let panel = panel(state, header, footer, mode, width, false, on_event.clone());
934 return watch(panel, state, Some(keymap), true, None, on_event);
935 };
936
937 if !state.narrow {
938 let mode = if state.rail { Mode::Rail } else { Mode::Docked };
939 let panel = panel(state, header, footer, mode, width, true, on_event.clone());
940 let panel = watch(panel, state, Some(keymap), true, None, on_event.clone());
941 let page = row![panel, container(content).width(Length::Fill)].height(Length::Fill);
942 return watch(page.into(), state, None, false, Some(breakpoint), on_event);
943 }
944
945 let mut page = column![];
946 if show_trigger {
947 let bar = container(
948 trigger(
949 on_event
950 .as_ref()
951 .map(|on_event| on_event(Event::ToggleDrawer)),
952 )
953 .tooltip(None)
954 .id(TRIGGER_ID),
955 )
956 .padding([0.0, space::SM])
957 .height(BAR_HEIGHT)
958 .width(Length::Fill)
959 .align_y(Alignment::Center);
960 page = page.push(bar).push(edge(Length::Fill, Length::Fixed(1.0)));
961 }
962 page = page.push(container(content).width(Length::Fill).height(Length::Fill));
963
964 let mut layers = stack![page].width(Length::Fill).height(Length::Fill);
965 if state.is_drawer_open() {
966 let scrim = container(Space::new())
967 .width(Length::Fill)
968 .height(Length::Fill)
969 .style(|theme| scrim_style(&Tokens::of(theme)));
970 let scrim: Element<'a, Message> = match &on_event {
971 Some(on_event) => solid(mouse_area(scrim).on_press(on_event(Event::CloseDrawer))),
972 None => solid(scrim),
973 };
974 #[cfg(feature = "icedwright")]
975 let scrim: Element<'a, Message> = icedwright_probe::semantic(scrim)
976 .role(icedwright_probe::role::Scrim)
977 .component("iced_cube::sidebar")
978 .into();
979 let drawer = panel(
980 state,
981 header,
982 footer,
983 Mode::Drawer,
984 None,
985 true,
986 on_event.clone(),
987 );
988 let drawer = watch(drawer, state, Some(keymap), false, None, on_event.clone());
989 layers = layers.push(scrim).push(solid(drawer));
990 }
991 watch(
992 layers.into(),
993 state,
994 None,
995 false,
996 Some(breakpoint),
997 on_event,
998 )
999 }
1000}
1001
1002pub fn trigger<'a, Message>(on_press: Option<Message>) -> IconButton<'a, Message> {
1005 icon_button(crate::lucide!(PanelLeft))
1006 .label("Toggle sidebar")
1007 .on_press_maybe(on_press)
1008}
1009
1010fn edge<'a, Message: 'a>(width: Length, height: Length) -> Element<'a, Message> {
1011 container(Space::new())
1012 .width(width)
1013 .height(height)
1014 .style(|theme| edge_style(&Tokens::of(theme)))
1015 .into()
1016}
1017
1018fn panel<'a, Id, Message>(
1019 state: &'a State<Id>,
1020 header: Option<Element<'a, Message>>,
1021 footer: Option<Element<'a, Message>>,
1022 mode: Mode,
1023 width: Option<Length>,
1024 with_edge: bool,
1025 on_event: Option<OnEvent<'a, Id, Message>>,
1026) -> Element<'a, Message>
1027where
1028 Id: Copy + PartialEq + 'a,
1029 Message: Clone + 'a,
1030{
1031 let on_event = on_event.as_deref();
1032 let keyboard = state.shows_highlight();
1033 let mut body = column![].spacing(space::SM).width(Length::Fill);
1034 for (index, group) in state.groups.iter().enumerate() {
1035 body = body.push(group_block(state, index, group, mode, keyboard, on_event));
1036 }
1037 let body: Element<'a, Message> = body.into();
1038 #[cfg(feature = "icedwright")]
1039 let body: Element<'a, Message> = icedwright_probe::semantic(body)
1040 .role(icedwright_probe::role::List)
1041 .component("iced_cube::sidebar")
1042 .into();
1043
1044 let mut sections = column![].width(Length::Fill).height(Length::Fill);
1045 if let Some(header) = header {
1046 sections = sections.push(container(header).padding(space::SM).width(Length::Fill));
1047 }
1048 sections = sections.push(
1049 scrollable(body)
1050 .direction(scrollable::Direction::Vertical(
1051 scrollable::Scrollbar::hidden(),
1052 ))
1053 .height(Length::Fill),
1054 );
1055 if let Some(footer) = footer {
1056 sections = sections.push(container(footer).padding(space::SM).width(Length::Fill));
1057 }
1058
1059 let width = match mode {
1060 Mode::Rail => Length::Fixed(RAIL_WIDTH),
1061 Mode::Docked => width.unwrap_or(Length::Fixed(WIDTH)),
1062 Mode::Drawer => Length::Fixed(DRAWER_WIDTH),
1063 };
1064 let surface = container(sections)
1065 .width(Length::Fill)
1066 .height(Length::Fill)
1067 .style(|theme| surface_style(&Tokens::of(theme)));
1068 let mut panel = row![surface].width(width).height(Length::Fill);
1069 if with_edge {
1070 panel = panel.push(edge(Length::Fixed(1.0), Length::Fill));
1071 }
1072 let panel: Element<'a, Message> = if mode == Mode::Drawer {
1073 container(panel)
1074 .max_width(DRAWER_WIDTH)
1075 .height(Length::Fill)
1076 .style(|theme| drawer_style(&Tokens::of(theme)))
1077 .into()
1078 } else {
1079 panel.into()
1080 };
1081 #[cfg(feature = "icedwright")]
1082 let panel = icedwright_probe::semantic(panel)
1083 .role(icedwright_probe::role::Navigation)
1084 .name("Sidebar")
1085 .component("iced_cube::sidebar")
1086 .into();
1087 panel
1088}
1089
1090pub fn drawer_style(tokens: &Tokens) -> container::Style {
1092 container::Style {
1093 shadow: Shadow {
1094 color: fade(Color::BLACK, if tokens.is_dark { 0.5 } else { 0.15 }),
1095 offset: Vector::new(4.0, 0.0),
1096 blur_radius: 16.0,
1097 },
1098 ..container::Style::default()
1099 }
1100}
1101
1102fn group_block<'a, Id, Message>(
1103 state: &'a State<Id>,
1104 index: usize,
1105 group: &'a Group<Id>,
1106 mode: Mode,
1107 keyboard: bool,
1108 on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1109) -> Element<'a, Message>
1110where
1111 Id: Copy + PartialEq + 'a,
1112 Message: Clone + 'a,
1113{
1114 let mut block = column![].width(Length::Fill);
1115 if mode == Mode::Rail {
1116 for item in &group.items {
1117 block = block.push(rail_item(state, item, on_event));
1118 }
1119 let block: Element<'a, Message> = container(block.spacing(space::XS))
1120 .padding(space::SM)
1121 .width(Length::Fill)
1122 .into();
1123 #[cfg(feature = "icedwright")]
1124 let block = icedwright_probe::semantic(block)
1125 .role(icedwright_probe::role::Group)
1126 .name(group.label.as_str())
1127 .component("iced_cube::sidebar")
1128 .into();
1129 return block;
1130 }
1131
1132 if !group.label.is_empty() {
1133 let highlighted = keyboard && state.highlighted == Some(Row::Group(index));
1134 block = block.push(group_heading(state, index, group, highlighted, on_event));
1135 }
1136 if state.is_group_open(index) || !group.collapsible {
1137 for item in &group.items {
1138 block = block.push(item_rows(state, item, keyboard, on_event));
1139 }
1140 }
1141 let block: Element<'a, Message> = container(block.spacing(2.0))
1142 .padding([space::XS, space::XS])
1143 .width(Length::Fill)
1144 .into();
1145 #[cfg(feature = "icedwright")]
1146 let block = {
1147 let annotated = icedwright_probe::semantic(block)
1148 .role(icedwright_probe::role::Group)
1149 .component("iced_cube::sidebar");
1150 if group.label.is_empty() {
1151 annotated.into()
1152 } else {
1153 annotated.name(group.label.as_str()).into()
1154 }
1155 };
1156 block
1157}
1158
1159fn group_heading<'a, Id, Message>(
1160 state: &State<Id>,
1161 index: usize,
1162 group: &'a Group<Id>,
1163 highlighted: bool,
1164 on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1165) -> Element<'a, Message>
1166where
1167 Id: Copy + PartialEq + 'a,
1168 Message: Clone + 'a,
1169{
1170 let label = text(group.label.as_str())
1171 .size(text_size::XS)
1172 .font(crate::theme::semibold())
1173 .wrapping(text::Wrapping::None)
1174 .width(Length::Fill)
1175 .style(|theme: &Theme| menu::label_style(&Tokens::of(theme)));
1176 if !group.collapsible {
1177 return menu::inset(
1178 container(label)
1179 .padding(menu::ROW_PADDING)
1180 .height(menu::ROW_PADDING.top + menu::LINE_HEIGHT + menu::ROW_PADDING.bottom)
1181 .align_y(Alignment::Center),
1182 );
1183 }
1184 let chevron = if state.is_group_open(index) {
1185 crate::lucide!(ChevronDown)
1186 } else {
1187 crate::lucide!(ChevronRight)
1188 };
1189 let heading = row![
1190 label,
1191 themed(chevron, menu::ICON_SIZE, 1.0, |theme| {
1192 Tokens::of(theme).muted_foreground
1193 })
1194 ]
1195 .align_y(Alignment::Center);
1196 let heading = menu::inset(
1197 button(heading)
1198 .padding(menu::ROW_PADDING)
1199 .width(Length::Fill)
1200 .on_press_maybe(on_event.map(|on_event| on_event(Event::ToggleGroup(index))))
1201 .style(move |theme, status| item_style(&Tokens::of(theme), false, highlighted, status)),
1202 );
1203 #[cfg(feature = "icedwright")]
1204 let heading = {
1205 let mut annotated = icedwright_probe::semantic(heading)
1206 .role(icedwright_probe::role::Button)
1207 .name(group.label.as_str())
1208 .expanded(state.is_group_open(index))
1209 .component("iced_cube::sidebar");
1210 if on_event.is_none() {
1211 annotated = annotated.disabled(true);
1212 }
1213 annotated.into()
1214 };
1215 heading
1216}
1217
1218fn item_rows<'a, Id, Message>(
1219 state: &'a State<Id>,
1220 item: &'a Item<Id>,
1221 keyboard: bool,
1222 on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1223) -> Element<'a, Message>
1224where
1225 Id: Copy + PartialEq + 'a,
1226 Message: Clone + 'a,
1227{
1228 let expanded = state.is_expanded(item.id);
1229 let active = if item.has_children() {
1230 !expanded && state.is_active_branch(item)
1231 } else {
1232 state.active == Some(item.id)
1233 };
1234 let row_element = item_row(state, item, active, keyboard, on_event);
1235 if !item.has_children() || !expanded {
1236 return row_element;
1237 }
1238
1239 let children = column(item.children.iter().map(|child| {
1240 let active = state.active == Some(child.id);
1241 item_row(state, child, active, keyboard, on_event)
1242 }))
1243 .spacing(2.0)
1244 .width(Length::Fill);
1245 let nested = row![
1246 edge(Length::Fixed(1.0), Length::Fill),
1247 container(children).padding(Padding::ZERO.left(space::SM)),
1248 ]
1249 .height(Length::Shrink);
1250 column![
1251 row_element,
1252 container(nested).padding(Padding {
1253 top: 2.0,
1254 bottom: 0.0,
1255 left: space::LG + space::XS,
1256 right: 0.0,
1257 })
1258 ]
1259 .spacing(0.0)
1260 .into()
1261}
1262
1263fn item_row<'a, Id, Message>(
1264 state: &State<Id>,
1265 item: &'a Item<Id>,
1266 active: bool,
1267 keyboard: bool,
1268 on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1269) -> Element<'a, Message>
1270where
1271 Id: Copy + PartialEq + 'a,
1272 Message: Clone + 'a,
1273{
1274 let message = on_event
1275 .filter(|_| !item.disabled)
1276 .map(|on_event| on_event(Event::Activate(item.id)));
1277 let status = if message.is_some() {
1278 RowStatus::Idle
1279 } else {
1280 RowStatus::Disabled
1281 };
1282 let highlighted = keyboard && state.highlighted == Some(Row::Item(item.id));
1283
1284 let parts = Parts {
1285 icon: item.icon,
1286 hint: item.badge.as_deref(),
1287 ..Parts::label(&item.label)
1288 };
1289 let mut content = menu::content(parts, status, false);
1290 if item.has_children() {
1291 let chevron = if state.is_expanded(item.id) {
1292 crate::lucide!(ChevronDown)
1293 } else {
1294 crate::lucide!(ChevronRight)
1295 };
1296 let opacity = crate::icon::opacity(message.is_some());
1297 content = content.push(themed(chevron, menu::ICON_SIZE, opacity, |theme| {
1298 Tokens::of(theme).muted_foreground
1299 }));
1300 }
1301
1302 #[cfg(feature = "icedwright")]
1303 let enabled = message.is_some();
1304 let row = menu::inset(
1305 button(content)
1306 .padding(menu::ROW_PADDING)
1307 .width(Length::Fill)
1308 .on_press_maybe(message)
1309 .style(move |theme, status| {
1310 item_style(&Tokens::of(theme), active, highlighted, status)
1311 }),
1312 );
1313 #[cfg(feature = "icedwright")]
1314 let row = link(row, item.label.as_str(), active, enabled);
1315 row
1316}
1317
1318#[cfg(feature = "icedwright")]
1320fn link<'a, Message: 'a>(
1321 element: Element<'a, Message>,
1322 name: &'a str,
1323 current: bool,
1324 enabled: bool,
1325) -> Element<'a, Message> {
1326 let mut annotated = icedwright_probe::semantic(element)
1327 .role(icedwright_probe::role::Link)
1328 .name(name)
1329 .current(current)
1330 .component("iced_cube::sidebar");
1331 if !enabled {
1332 annotated = annotated.disabled(true);
1333 }
1334 annotated.into()
1335}
1336
1337fn rail_item<'a, Id, Message>(
1338 state: &State<Id>,
1339 item: &'a Item<Id>,
1340 on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1341) -> Element<'a, Message>
1342where
1343 Id: Copy + PartialEq + 'a,
1344 Message: Clone + 'a,
1345{
1346 let message = on_event
1347 .filter(|_| !item.disabled)
1348 .map(|on_event| on_event(Event::Activate(item.id)));
1349 let enabled = message.is_some();
1350 let active = state.is_active_branch(item);
1351 let highlighted = state.shows_highlight() && state.highlighted == Some(Row::Item(item.id));
1352
1353 let face: Element<'a, Message> = match item.icon {
1354 Some(glyph) => themed(
1355 glyph,
1356 menu::ICON_SIZE,
1357 crate::icon::opacity(enabled),
1358 |theme| Tokens::of(theme).foreground,
1359 )
1360 .into(),
1361 None => text(
1362 item.label
1363 .chars()
1364 .next()
1365 .map(String::from)
1366 .unwrap_or_default(),
1367 )
1368 .size(text_size::SM)
1369 .font(crate::theme::semibold())
1370 .into(),
1371 };
1372 let square = button(container(face).center(RAIL_BUTTON))
1373 .width(RAIL_BUTTON)
1374 .height(RAIL_BUTTON)
1375 .padding(0)
1376 .on_press_maybe(message)
1377 .style(move |theme, status| item_style(&Tokens::of(theme), active, highlighted, status));
1378 let element: Element<'a, Message> = tooltip(square, item.label.as_str())
1379 .position(Position::Right)
1380 .into();
1381 #[cfg(feature = "icedwright")]
1382 let element = link(element, item.label.as_str(), active, enabled);
1383 element
1384}
1385
1386pub struct MenuButton<'a, Message> {
1390 title: text::Fragment<'a>,
1391 subtitle: Option<text::Fragment<'a>>,
1392 icon: Option<Glyph>,
1393 initials: Option<text::Fragment<'a>>,
1394 compact: bool,
1395 on_press: Option<Message>,
1396}
1397
1398impl<Message> std::fmt::Debug for MenuButton<'_, Message> {
1399 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1400 f.debug_struct("MenuButton")
1401 .field("title", &self.title)
1402 .field("subtitle", &self.subtitle)
1403 .field("compact", &self.compact)
1404 .finish_non_exhaustive()
1405 }
1406}
1407
1408pub fn menu_button<'a, Message>(title: impl text::IntoFragment<'a>) -> MenuButton<'a, Message> {
1410 MenuButton {
1411 title: title.into_fragment(),
1412 subtitle: None,
1413 icon: None,
1414 initials: None,
1415 compact: false,
1416 on_press: None,
1417 }
1418}
1419
1420impl<'a, Message> MenuButton<'a, Message> {
1421 pub fn subtitle(mut self, subtitle: impl text::IntoFragment<'a>) -> Self {
1422 self.subtitle = Some(subtitle.into_fragment());
1423 self
1424 }
1425
1426 pub fn icon(mut self, glyph: Glyph) -> Self {
1428 self.icon = Some(glyph);
1429 self
1430 }
1431
1432 pub fn initials(mut self, initials: impl text::IntoFragment<'a>) -> Self {
1434 self.initials = Some(initials.into_fragment());
1435 self
1436 }
1437
1438 pub fn compact(mut self, compact: bool) -> Self {
1441 self.compact = compact;
1442 self
1443 }
1444
1445 pub fn on_press(mut self, message: Message) -> Self {
1446 self.on_press = Some(message);
1447 self
1448 }
1449
1450 pub fn on_press_maybe(mut self, message: Option<Message>) -> Self {
1451 self.on_press = message;
1452 self
1453 }
1454}
1455
1456impl<'a, Message: Clone + 'a> From<MenuButton<'a, Message>> for Element<'a, Message> {
1457 fn from(menu_button: MenuButton<'a, Message>) -> Self {
1458 let MenuButton {
1459 title,
1460 subtitle,
1461 icon,
1462 initials,
1463 compact,
1464 on_press,
1465 } = menu_button;
1466 let logo = icon.is_some();
1467 let face: Element<'a, Message> = match (icon, initials) {
1468 (Some(glyph), _) => themed(glyph, menu::ICON_SIZE, 1.0, |theme| {
1469 Tokens::of(theme).primary_foreground
1470 })
1471 .into(),
1472 (None, Some(initials)) => text(initials)
1473 .size(text_size::XS)
1474 .font(crate::theme::semibold())
1475 .wrapping(text::Wrapping::None)
1476 .into(),
1477 (None, None) => themed(crate::lucide!(User), menu::ICON_SIZE, 1.0, |theme| {
1478 Tokens::of(theme).foreground
1479 })
1480 .into(),
1481 };
1482 let square = container(face)
1483 .center(RAIL_BUTTON)
1484 .style(move |theme| avatar_style(&Tokens::of(theme), logo));
1485
1486 let content: Element<'a, Message> = if compact {
1487 square.into()
1488 } else {
1489 let mut lines = column![
1490 text(title)
1491 .size(text_size::SM)
1492 .font(crate::theme::semibold())
1493 .wrapping(text::Wrapping::None)
1494 ];
1495 if let Some(subtitle) = subtitle {
1496 lines = lines.push(
1497 text(subtitle)
1498 .size(text_size::XS)
1499 .wrapping(text::Wrapping::None)
1500 .style(|theme: &Theme| text::Style {
1501 color: Some(Tokens::of(theme).muted_foreground),
1502 }),
1503 );
1504 }
1505 row![
1506 square,
1507 container(lines).width(Length::Fill).clip(true),
1508 themed(
1509 crate::lucide!(ChevronsUpDown),
1510 menu::ICON_SIZE,
1511 1.0,
1512 |theme| { Tokens::of(theme).muted_foreground }
1513 ),
1514 ]
1515 .spacing(space::SM)
1516 .align_y(Alignment::Center)
1517 .into()
1518 };
1519
1520 let width = if compact {
1521 Length::Fixed(RAIL_BUTTON)
1522 } else {
1523 Length::Fill
1524 };
1525 let padding = if compact { 0.0 } else { space::SM };
1526 button(content)
1527 .padding(padding)
1528 .width(width)
1529 .on_press_maybe(on_press)
1530 .style(|theme, status| {
1531 let status = match status {
1532 button::Status::Disabled => button::Status::Active,
1533 status => status,
1534 };
1535 item_style(&Tokens::of(theme), false, false, status)
1536 })
1537 .into()
1538 }
1539}
1540
1541pub fn avatar_style(tokens: &Tokens, logo: bool) -> container::Style {
1543 let (background, text_color) = if logo {
1544 (tokens.primary, tokens.primary_foreground)
1545 } else {
1546 (tokens.muted, tokens.foreground)
1547 };
1548 container::Style {
1549 background: Some(Background::Color(background)),
1550 text_color: Some(text_color),
1551 border: Border {
1552 radius: radius::MD.into(),
1553 ..Border::default()
1554 },
1555 ..container::Style::default()
1556 }
1557}
1558
1559fn watch<'a, Id, Message>(
1561 content: Element<'a, Message>,
1562 state: &'a State<Id>,
1563 keymap: Option<Keymap<Action>>,
1564 track_focus: bool,
1565 breakpoint: Option<f32>,
1566 on_event: Option<OnEvent<'a, Id, Message>>,
1567) -> Element<'a, Message>
1568where
1569 Id: Copy + PartialEq + 'a,
1570 Message: 'a,
1571{
1572 let Some(on_event) = on_event else {
1573 return content;
1574 };
1575 Element::new(Watch {
1576 content,
1577 state,
1578 keymap,
1579 track_focus,
1580 breakpoint,
1581 on_event,
1582 })
1583}
1584
1585struct Watch<'a, Id, Message> {
1589 content: Element<'a, Message>,
1590 state: &'a State<Id>,
1591 keymap: Option<Keymap<Action>>,
1592 track_focus: bool,
1593 breakpoint: Option<f32>,
1594 on_event: OnEvent<'a, Id, Message>,
1595}
1596
1597fn is_press(event: &Input) -> bool {
1598 matches!(
1599 event,
1600 Input::Mouse(mouse::Event::ButtonPressed(_))
1601 | Input::Touch(touch::Event::FingerPressed { .. })
1602 )
1603}
1604
1605fn press_position(event: &Input, cursor: mouse::Cursor) -> Option<iced::Point> {
1606 match event {
1607 Input::Touch(touch::Event::FingerPressed { position, .. }) => Some(*position),
1608 _ => cursor.position(),
1609 }
1610}
1611
1612impl<Id, Message> Widget<Message, Theme, Renderer> for Watch<'_, Id, Message>
1613where
1614 Id: Copy + PartialEq,
1615{
1616 fn size(&self) -> Size<Length> {
1617 self.content.as_widget().size()
1618 }
1619
1620 fn size_hint(&self) -> Size<Length> {
1621 self.content.as_widget().size_hint()
1622 }
1623
1624 fn tag(&self) -> tree::Tag {
1625 self.content.as_widget().tag()
1626 }
1627
1628 fn state(&self) -> tree::State {
1629 self.content.as_widget().state()
1630 }
1631
1632 fn children(&self) -> Vec<Tree> {
1633 self.content.as_widget().children()
1634 }
1635
1636 fn diff(&self, tree: &mut Tree) {
1637 self.content.as_widget().diff(tree);
1638 }
1639
1640 fn layout(
1641 &mut self,
1642 tree: &mut Tree,
1643 renderer: &Renderer,
1644 limits: &layout::Limits,
1645 ) -> layout::Node {
1646 self.content.as_widget_mut().layout(tree, renderer, limits)
1647 }
1648
1649 fn draw(
1650 &self,
1651 tree: &Tree,
1652 renderer: &mut Renderer,
1653 theme: &Theme,
1654 style: &renderer::Style,
1655 layout: Layout<'_>,
1656 cursor: mouse::Cursor,
1657 viewport: &Rectangle,
1658 ) {
1659 self.content
1660 .as_widget()
1661 .draw(tree, renderer, theme, style, layout, cursor, viewport);
1662 }
1663
1664 fn operate(
1665 &mut self,
1666 tree: &mut Tree,
1667 layout: Layout<'_>,
1668 renderer: &Renderer,
1669 operation: &mut dyn Operation,
1670 ) {
1671 self.content
1672 .as_widget_mut()
1673 .operate(tree, layout, renderer, operation);
1674 }
1675
1676 fn update(
1677 &mut self,
1678 tree: &mut Tree,
1679 event: &Input,
1680 layout: Layout<'_>,
1681 cursor: mouse::Cursor,
1682 renderer: &Renderer,
1683 clipboard: &mut dyn Clipboard,
1684 shell: &mut Shell<'_, Message>,
1685 viewport: &Rectangle,
1686 ) {
1687 if let Some(breakpoint) = self.breakpoint {
1688 let narrow = layout.bounds().width < breakpoint;
1689 if narrow != self.state.narrow {
1690 shell.publish((self.on_event)(Event::Narrow(narrow)));
1691 }
1692 }
1693
1694 if let (Some(keymap), Input::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })) =
1695 (&self.keymap, event)
1696 && self.state.has_keys()
1697 && let Some(action) = keymap.resolve(key, *modifiers)
1698 {
1699 if let Some(event) = action.event(self.state) {
1700 shell.publish((self.on_event)(event));
1701 }
1702 shell.capture_event();
1703 return;
1704 }
1705
1706 if self.track_focus && is_press(event) {
1707 let inside =
1708 press_position(event, cursor).is_some_and(|point| layout.bounds().contains(point));
1709 if inside != self.state.focused {
1710 shell.publish((self.on_event)(Event::Focus(inside)));
1711 }
1712 }
1713
1714 self.content.as_widget_mut().update(
1715 tree, event, layout, cursor, renderer, clipboard, shell, viewport,
1716 );
1717 }
1718
1719 fn mouse_interaction(
1720 &self,
1721 tree: &Tree,
1722 layout: Layout<'_>,
1723 cursor: mouse::Cursor,
1724 viewport: &Rectangle,
1725 renderer: &Renderer,
1726 ) -> mouse::Interaction {
1727 self.content
1728 .as_widget()
1729 .mouse_interaction(tree, layout, cursor, viewport, renderer)
1730 }
1731
1732 fn overlay<'b>(
1733 &'b mut self,
1734 tree: &'b mut Tree,
1735 layout: Layout<'b>,
1736 renderer: &Renderer,
1737 viewport: &Rectangle,
1738 translation: Vector,
1739 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1740 self.content
1741 .as_widget_mut()
1742 .overlay(tree, layout, renderer, viewport, translation)
1743 }
1744}
1745
1746#[cfg(test)]
1747mod tests {
1748 use super::*;
1749 use crate::theme::{dark, light};
1750
1751 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1752 enum Page {
1753 Home,
1754 Inbox,
1755 Projects,
1756 Alpha,
1757 Beta,
1758 Archived,
1759 Settings,
1760 Billing,
1761 }
1762
1763 use Page::*;
1764
1765 fn state() -> State<Page> {
1766 State::new([
1767 group(
1768 "Platform",
1769 [
1770 item(Home, "Home"),
1771 item(Inbox, "Inbox").badge("12"),
1772 item(Projects, "Projects").children([
1773 item(Alpha, "Alpha"),
1774 item(Beta, "Beta"),
1775 item(Archived, "Archived").disabled(true),
1776 ]),
1777 ],
1778 ),
1779 group(
1780 "Account",
1781 [item(Settings, "Settings"), item(Billing, "Billing")],
1782 )
1783 .collapsible(true),
1784 ])
1785 }
1786
1787 fn rows(state: &State<Page>) -> Vec<Row<Page>> {
1788 state.rows()
1789 }
1790
1791 #[test]
1792 fn builders_set_fields() {
1793 let entry = item(Home, "Home")
1794 .icon(crate::lucide!(House))
1795 .badge("3")
1796 .disabled(true);
1797 assert_eq!(entry.badge.as_deref(), Some("3"));
1798 assert!(entry.icon.is_some() && entry.disabled);
1799
1800 let nested = item(Projects, "Projects")
1801 .children([item(Alpha, "Alpha").children([item(Beta, "Beta")])]);
1802 assert!(nested.children[0].children.is_empty(), "one level deep");
1803
1804 let group = group("G", [item(Home, "Home")]).collapsible(true);
1805 assert!(group.collapsible);
1806
1807 let state = State::new([group]);
1808 assert!(!state.is_rail() && !state.is_narrow() && !state.is_focused());
1809 assert_eq!(state.active(), None);
1810 }
1811
1812 #[test]
1813 fn with_active_opens_the_parent_and_ignores_disabled() {
1814 let state = state().with_active(Beta);
1815 assert_eq!(state.active(), Some(Beta));
1816 assert!(state.is_expanded(Projects));
1817 assert_eq!(state.clone().with_active(Archived).active(), Some(Beta));
1818 }
1819
1820 #[test]
1821 fn rows_follow_what_is_showing() {
1822 let mut state = state();
1823 assert_eq!(
1824 rows(&state),
1825 [
1826 Row::Item(Home),
1827 Row::Item(Inbox),
1828 Row::Item(Projects),
1829 Row::Group(1),
1830 Row::Item(Settings),
1831 Row::Item(Billing)
1832 ]
1833 );
1834 let _ = state.update(Event::ToggleItem(Projects));
1835 assert!(rows(&state).contains(&Row::Item(Alpha)));
1836 assert!(!rows(&state).contains(&Row::Item(Archived)), "disabled");
1837 let _ = state.update(Event::ToggleGroup(1));
1838 assert!(!rows(&state).contains(&Row::Item(Settings)));
1839 assert!(rows(&state).contains(&Row::Group(1)));
1840 }
1841
1842 #[test]
1843 fn the_rail_shows_top_level_items_only() {
1844 let state = state().with_rail(true);
1845 assert!(state.is_compact());
1846 assert_eq!(
1847 rows(&state),
1848 [
1849 Row::Item(Home),
1850 Row::Item(Inbox),
1851 Row::Item(Projects),
1852 Row::Item(Settings),
1853 Row::Item(Billing)
1854 ]
1855 );
1856 let mut narrow = state.clone();
1857 let _ = narrow.update(Event::Narrow(true));
1858 assert!(
1859 narrow.is_rail() && !narrow.is_compact(),
1860 "the drawer shows labels"
1861 );
1862 }
1863
1864 #[test]
1865 fn activating_a_leaf_makes_it_active() {
1866 let mut state = state();
1867 assert_eq!(
1868 state.update(Event::Activate(Inbox)),
1869 Some(Output::Activated(Inbox))
1870 );
1871 assert_eq!(state.active(), Some(Inbox));
1872 assert_eq!(state.highlighted(), Some(Row::Item(Inbox)));
1873 assert_eq!(state.update(Event::Activate(Archived)), None);
1874 assert_eq!(state.active(), Some(Inbox));
1875 }
1876
1877 #[test]
1878 fn activating_a_parent_toggles_its_children() {
1879 let mut state = state();
1880 assert_eq!(state.update(Event::Activate(Projects)), None);
1881 assert!(state.is_expanded(Projects));
1882 let _ = state.update(Event::Activate(Projects));
1883 assert!(!state.is_expanded(Projects));
1884 }
1885
1886 #[test]
1887 fn a_parent_in_the_rail_expands_the_sidebar() {
1888 let mut state = state().with_rail(true);
1889 let _ = state.update(Event::Activate(Projects));
1890 assert!(!state.is_rail());
1891 assert!(state.is_expanded(Projects));
1892 }
1893
1894 #[test]
1895 fn up_and_down_wrap_through_rows() {
1896 let mut state = state();
1897 let _ = state.update(Event::Next);
1898 assert_eq!(state.highlighted(), Some(Row::Item(Home)));
1899 let _ = state.update(Event::Previous);
1900 assert_eq!(state.highlighted(), Some(Row::Item(Billing)));
1901 let _ = state.update(Event::Next);
1902 assert_eq!(state.highlighted(), Some(Row::Item(Home)));
1903 let _ = state.update(Event::Last);
1904 assert_eq!(state.highlighted(), Some(Row::Item(Billing)));
1905 let _ = state.update(Event::First);
1906 assert_eq!(state.highlighted(), Some(Row::Item(Home)));
1907 }
1908
1909 #[test]
1910 fn enter_activates_the_highlight() {
1911 let mut state = state();
1912 let _ = state.update(Event::Next);
1913 let _ = state.update(Event::Next);
1914 assert_eq!(
1915 state.update(Event::ActivateHighlighted),
1916 Some(Output::Activated(Inbox))
1917 );
1918 let _ = state.update(Event::Last);
1919 let _ = state.update(Event::Previous);
1920 let _ = state.update(Event::Previous);
1921 assert_eq!(state.highlighted(), Some(Row::Group(1)));
1922 let _ = state.update(Event::ActivateHighlighted);
1923 assert!(!state.is_group_open(1));
1924 }
1925
1926 #[test]
1927 fn right_and_left_open_close_and_move_through_parents() {
1928 let mut state = state();
1929 state.highlighted = Some(Row::Item(Projects));
1930 let _ = state.update(Event::Expand);
1931 assert!(state.is_expanded(Projects));
1932 let _ = state.update(Event::Expand);
1933 assert_eq!(state.highlighted(), Some(Row::Item(Alpha)));
1934 let _ = state.update(Event::Collapse);
1935 assert_eq!(state.highlighted(), Some(Row::Item(Projects)));
1936 let _ = state.update(Event::Collapse);
1937 assert!(!state.is_expanded(Projects));
1938 }
1939
1940 #[test]
1941 fn right_and_left_open_and_close_groups() {
1942 let mut state = state();
1943 state.highlighted = Some(Row::Item(Settings));
1944 let _ = state.update(Event::Collapse);
1945 assert_eq!(state.highlighted(), Some(Row::Group(1)));
1946 let _ = state.update(Event::Collapse);
1947 assert!(!state.is_group_open(1));
1948 let _ = state.update(Event::Expand);
1949 assert!(state.is_group_open(1));
1950 let _ = state.update(Event::Expand);
1951 assert_eq!(state.highlighted(), Some(Row::Item(Settings)));
1952 state.highlighted = Some(Row::Item(Home));
1953 let _ = state.update(Event::Collapse);
1954 assert_eq!(state.highlighted(), Some(Row::Item(Home)), "group is fixed");
1955 }
1956
1957 #[test]
1958 fn closing_moves_a_hidden_highlight_out() {
1959 let mut state = state().with_active(Alpha);
1960 state.highlighted = Some(Row::Item(Alpha));
1961 let _ = state.update(Event::ToggleItem(Projects));
1962 assert_eq!(state.highlighted(), Some(Row::Item(Projects)));
1963
1964 state.highlighted = Some(Row::Item(Billing));
1965 let _ = state.update(Event::ToggleGroup(1));
1966 assert_eq!(state.highlighted(), Some(Row::Group(1)));
1967 let _ = state.update(Event::ToggleGroup(0));
1968 assert!(state.is_group_open(0), "fixed groups stay open");
1969 }
1970
1971 #[test]
1972 fn toggling_the_rail_moves_the_highlight_to_a_showing_row() {
1973 let mut state = state().with_active(Alpha);
1974 state.highlighted = Some(Row::Item(Alpha));
1975 let _ = state.update(Event::ToggleRail);
1976 assert!(state.is_rail());
1977 assert_eq!(state.highlighted(), Some(Row::Item(Projects)));
1978 state.highlighted = Some(Row::Group(1));
1979 let _ = state.update(Event::SetRail(true));
1980 assert_eq!(state.highlighted(), Some(Row::Item(Settings)));
1981 }
1982
1983 #[test]
1984 fn the_trigger_toggles_the_rail_or_the_drawer() {
1985 let mut state = state().with_active(Inbox);
1986 let _ = state.update(Event::Toggle);
1987 assert!(state.is_rail());
1988 let _ = state.update(Event::Narrow(true));
1989 let _ = state.update(Event::Toggle);
1990 assert!(state.is_drawer_open());
1991 assert_eq!(state.highlighted(), Some(Row::Item(Inbox)));
1992 let _ = state.update(Event::Toggle);
1993 assert!(!state.is_drawer_open());
1994 }
1995
1996 #[test]
1997 fn the_drawer_closes_on_activation_and_when_the_window_widens() {
1998 let mut state = state();
1999 let _ = state.update(Event::Narrow(true));
2000 let _ = state.update(Event::OpenDrawer);
2001 assert!(state.has_keys());
2002 let _ = state.update(Event::Activate(Home));
2003 assert!(!state.is_drawer_open());
2004
2005 let _ = state.update(Event::OpenDrawer);
2006 let _ = state.update(Event::Narrow(false));
2007 assert!(!state.is_drawer_open());
2008 let _ = state.update(Event::Narrow(true));
2009 assert!(!state.is_drawer_open(), "stays closed");
2010 let _ = state.update(Event::ToggleDrawer);
2011 let _ = state.update(Event::CloseDrawer);
2012 assert!(!state.is_drawer_open());
2013 }
2014
2015 #[test]
2016 fn the_ring_shows_once_the_keyboard_moves_the_highlight() {
2017 let mut state = state().with_active(Home);
2018 let _ = state.update(Event::Focus(true));
2019 assert!(!state.shows_highlight(), "a press does not draw the ring");
2020 let _ = state.update(Event::Next);
2021 assert!(state.shows_highlight());
2022 let _ = state.update(Event::Activate(Inbox));
2023 assert!(!state.shows_highlight(), "a click hides it again");
2024 let _ = state.update(Event::Next);
2025 let _ = state.update(Event::Focus(false));
2026 assert!(!state.shows_highlight(), "only while the sidebar has keys");
2027 }
2028
2029 #[test]
2030 fn focus_highlights_the_active_item() {
2031 let mut state = state().with_active(Beta);
2032 let _ = state.update(Event::Focus(true));
2033 assert!(state.is_focused());
2034 assert_eq!(state.highlighted(), Some(Row::Item(Beta)));
2035 let _ = state.update(Event::Focus(false));
2036 assert!(!state.has_keys());
2037
2038 let mut closed = state.clone();
2039 closed.highlighted = None;
2040 let _ = closed.update(Event::ToggleItem(Projects));
2041 let _ = closed.update(Event::Focus(true));
2042 assert_eq!(closed.highlighted(), Some(Row::Item(Projects)));
2043 }
2044
2045 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
2046 let chord: Chord = chord.parse().unwrap();
2047 keymap.resolve(chord.key(), chord.modifiers())
2048 }
2049
2050 #[test]
2051 fn default_keymap_covers_every_action() {
2052 let keymap = default_keymap();
2053 assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
2054 assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
2055 assert_eq!(press(&keymap, "Home"), Some(Action::First));
2056 assert_eq!(press(&keymap, "End"), Some(Action::Last));
2057 assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
2058 assert_eq!(press(&keymap, "Space"), Some(Action::Activate));
2059 assert_eq!(press(&keymap, "ArrowRight"), Some(Action::Expand));
2060 assert_eq!(press(&keymap, "ArrowLeft"), Some(Action::Collapse));
2061 assert_eq!(press(&keymap, "Mod+B"), Some(Action::ToggleRail));
2062 assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
2063 assert_eq!(press(&keymap, "B"), None);
2064 for action in <Action as keys::Action>::ALL {
2065 assert!(!keymap.chords(action).is_empty(), "{action:?}");
2066 }
2067 assert_eq!(Keymap::<Action>::defaults(), keymap);
2068 }
2069
2070 #[test]
2071 fn keymap_overrides_and_unbinding() {
2072 let keymap = default_keymap()
2073 .unbind(&"Mod+B".parse().unwrap())
2074 .bind("Ctrl+Shift+S".parse().unwrap(), Action::ToggleRail);
2075 assert_eq!(press(&keymap, "Mod+B"), None);
2076 assert_eq!(press(&keymap, "Ctrl+Shift+S"), Some(Action::ToggleRail));
2077 }
2078
2079 #[test]
2080 fn actions_map_to_events() {
2081 let mut state = state();
2082 assert_eq!(Action::Next.event(&state), Some(Event::Next));
2083 assert_eq!(
2084 Action::Activate.event(&state),
2085 Some(Event::ActivateHighlighted)
2086 );
2087 assert_eq!(Action::ToggleRail.event(&state), Some(Event::Toggle));
2088 assert_eq!(Action::Close.event(&state), None);
2089 let _ = state.update(Event::Focus(true));
2090 assert_eq!(Action::Close.event(&state), Some(Event::Focus(false)));
2091 let _ = state.update(Event::Narrow(true));
2092 let _ = state.update(Event::OpenDrawer);
2093 assert_eq!(Action::Close.event(&state), Some(Event::CloseDrawer));
2094 }
2095
2096 #[test]
2097 fn shortcut_only_resolves_the_app_wide_action() {
2098 let state = state();
2099 let keymap = default_keymap();
2100 let key = |chord: &str| {
2101 let chord: Chord = chord.parse().unwrap();
2102 keys::Event {
2103 key: chord.key().clone(),
2104 modifiers: chord.modifiers(),
2105 }
2106 };
2107 assert_eq!(state.shortcut(&keymap, &key("Mod+B")), Some(Event::Toggle));
2108 assert_eq!(state.shortcut(&keymap, &key("ArrowDown")), None);
2109 }
2110
2111 #[test]
2112 fn rows_highlight_when_active_hovered_or_pressed() {
2113 for theme in [light(), dark()] {
2114 let tokens = Tokens::of(&theme);
2115 let idle = item_style(&tokens, false, false, button::Status::Active);
2116 assert_eq!(idle.background, None);
2117 assert_eq!(idle.text_color, tokens.foreground);
2118 for status in [button::Status::Hovered, button::Status::Pressed] {
2119 let style = item_style(&tokens, false, false, status);
2120 assert_eq!(style.background, Some(Background::Color(tokens.accent)));
2121 }
2122 let active = item_style(&tokens, true, false, button::Status::Active);
2123 assert_eq!(active.background, Some(Background::Color(tokens.accent)));
2124 let disabled = item_style(&tokens, true, false, button::Status::Disabled);
2125 assert_eq!(disabled.background, None);
2126 assert_eq!(disabled.text_color, tokens.muted_foreground);
2127 }
2128 }
2129
2130 #[test]
2131 fn the_keyboard_highlight_draws_a_ring() {
2132 let tokens = Tokens::of(&light());
2133 let ring = item_style(&tokens, false, true, button::Status::Active);
2134 assert_eq!(ring.border.color, tokens.ring);
2135 assert_eq!(ring.border.width, 1.0);
2136 let plain = item_style(&tokens, false, false, button::Status::Active);
2137 assert_eq!(plain.border.width, 0.0);
2138 }
2139
2140 #[test]
2141 fn surfaces_sit_between_page_and_card() {
2142 for theme in [light(), dark()] {
2143 let tokens = Tokens::of(&theme);
2144 let surface = surface_style(&tokens).background;
2145 assert!(surface.is_some());
2146 assert_ne!(surface, Some(Background::Color(tokens.background)));
2147 assert_eq!(
2148 edge_style(&tokens).background,
2149 Some(Background::Color(tokens.border))
2150 );
2151 assert!(scrim_style(&tokens).background.is_some());
2152 }
2153 let logo = avatar_style(&Tokens::of(&light()), true);
2154 assert_eq!(
2155 logo.text_color,
2156 Some(Tokens::of(&light()).primary_foreground)
2157 );
2158 }
2159
2160 #[test]
2161 fn builder_defaults() {
2162 let state = state();
2163 let sidebar: Sidebar<'_, Page, ()> = sidebar(&state);
2164 assert_eq!(sidebar.breakpoint, BREAKPOINT);
2165 assert!(sidebar.trigger);
2166 assert!(sidebar.content.is_none());
2167 assert!(sidebar.on_event.is_none());
2168 assert_eq!(sidebar.keymap, default_keymap());
2169 }
2170}