1use crate::*;
4use std::{fmt, rc::Rc, time::Duration};
5use waft_animation::{Cubic, Interval};
6use waft_embedder::{Color, FontWeight};
7use waft_foundation::{App, Listener};
8use waft_painting::Alignment;
9use waft_rendering::{BoxConstraints, HitTestBehavior};
10use waft_widgets::*;
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum NavigationViewItemKind {
15 #[default]
17 Item,
18
19 Header,
21
22 Separator,
24}
25
26#[derive(Clone)]
28pub struct NavigationViewItem {
29 pub id: String,
31
32 pub kind: NavigationViewItemKind,
34
35 pub content: WidgetRef,
37
38 pub has_content: bool,
40
41 pub text: Option<String>,
43
44 pub icon: Option<WidgetRef>,
46
47 pub menu_items: Vec<NavigationViewItem>,
49
50 pub selects_on_invoked: bool,
52
53 pub is_enabled: bool,
55
56 pub is_visible: bool,
58
59 pub info_badge: Option<WidgetRef>,
61
62 pub has_unrealized_children: bool,
64
65 pub tool_tip: Option<ToolTip>,
67}
68
69impl fmt::Debug for NavigationViewItem {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.debug_struct("NavigationViewItem")
72 .field("id", &self.id)
73 .field("kind", &self.kind)
74 .finish_non_exhaustive()
75 }
76}
77
78impl NavigationViewItem {
79 #[cfg_attr(debug_assertions, track_caller)]
81 pub fn new<K>(id: impl Into<String>, content: impl IntoWidget<K>) -> Self {
82 Self {
83 id: id.into(),
84 kind: NavigationViewItemKind::Item,
85 content: content.into_widget(),
86 has_content: true,
87 text: None,
88 icon: None,
89 menu_items: vec![],
90 selects_on_invoked: true,
91 is_enabled: true,
92 is_visible: true,
93 info_badge: None,
94 has_unrealized_children: false,
95 tool_tip: None,
96 }
97 }
98
99 pub fn without_content(mut self) -> Self {
101 self.has_content = false;
102 self.content = SizedBox::shrink().into_widget();
103 self.text = None;
104 self
105 }
106
107 pub fn text(id: impl Into<String>, text: impl Into<String>) -> Self {
109 let text = text.into();
110 let mut item = Self::new(id, Text::new(text.clone()));
111 item.text = Some(text);
112 item
113 }
114
115 pub fn header(id: impl Into<String>, text: impl Into<String>) -> Self {
117 let mut item = Self::text(id, text);
118 item.kind = NavigationViewItemKind::Header;
119 item.is_enabled = false;
120 item.selects_on_invoked = false;
121 item
122 }
123
124 pub fn separator(id: impl Into<String>) -> Self {
126 let mut item = Self::new(id, SizedBox::shrink());
127 item.kind = NavigationViewItemKind::Separator;
128 item.is_enabled = false;
129 item.selects_on_invoked = false;
130 item
131 }
132
133 #[cfg_attr(debug_assertions, track_caller)]
135 pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> Self {
136 self.icon = Some(icon.into_widget());
137 self
138 }
139
140 pub fn menu_items(mut self, items: impl IntoIterator<Item = Self>) -> Self {
142 self.menu_items = items.into_iter().collect();
143 self
144 }
145
146 pub fn selects_on_invoked(mut self, value: bool) -> Self {
148 self.selects_on_invoked = value;
149 self
150 }
151
152 pub fn is_enabled(mut self, value: bool) -> Self {
154 self.is_enabled = value;
155 self
156 }
157
158 pub fn is_visible(mut self, value: bool) -> Self {
160 self.is_visible = value;
161 self
162 }
163
164 #[cfg_attr(debug_assertions, track_caller)]
166 pub fn info_badge<K>(mut self, badge: impl IntoWidget<K>) -> Self {
167 self.info_badge = Some(badge.into_widget());
168 self
169 }
170
171 pub fn tool_tip(mut self, tool_tip: ToolTip) -> Self {
173 self.tool_tip = Some(tool_tip);
174 self
175 }
176
177 pub fn has_unrealized_children(mut self, value: bool) -> Self {
179 self.has_unrealized_children = value;
180 self
181 }
182}
183
184#[derive(Clone, Copy, Debug, PartialEq, Eq)]
186pub(crate) enum NavigationViewItemPosition {
187 Left,
188 TopPrimary,
189 TopFooter,
191 TopOverflow,
192}
193
194#[derive(Clone, Debug)]
196pub(crate) struct NavigationViewItemPresenter {
197 pub item: NavigationViewItem,
199 pub position: NavigationViewItemPosition,
201 pub is_selected: bool,
203 pub is_expanded: bool,
205 pub is_closed_compact: bool,
207 pub is_top_level_item: bool,
209 pub is_keyboard_focused: bool,
211 pub is_child_selected: bool,
213 pub focus_node: FocusNodeRef,
215 pub depth: usize,
217 pub compact_pane_length: f64,
219 pub on_invoked: Listener,
221 pub on_expansion_toggled: Listener,
223
224 pub indicator_key: GlobalKey,
226
227 pub indicator_controller: waft_foundation::Ref<waft_animation::AnimationController>,
229
230 pub indicator_animation: Option<NavigationIndicatorTransition>,
232
233 pub indicator_opacity: Option<f64>,
235}
236
237impl StatelessWidget for NavigationViewItemPresenter {
238 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
239 if !self.item.is_visible {
240 return SizedBox::shrink().into_widget();
241 }
242 if self.item.kind != NavigationViewItemKind::Item {
243 return self.section_template(&ThemeResources::of(app, context));
244 }
245 let w = self.clone();
246 let content = CommonStates::new(self.on_invoked.clone(), move |app, context, states| {
247 let resources = ThemeResources::of(app, context);
248 FocusVisual::new(w.template(&resources, states.common), resources.theme)
249 .visible(states.focused || w.is_keyboard_focused)
250 .corner_radius(resources.control_corner_radius[0])
251 .into_widget()
252 })
253 .is_enabled(self.item.is_enabled)
254 .focus_node(self.focus_node.clone())
255 .into_widget();
256 let tooltip = self.item.tool_tip.clone().or_else(|| {
257 (self.is_closed_compact && self.position == NavigationViewItemPosition::Left)
258 .then(|| self.item.text.as_ref().map(ToolTip::text))
259 .flatten()
260 });
261 if let Some(tooltip) = tooltip {
262 return ToolTipService::new(content, tooltip)
263 .is_enabled(self.item.is_enabled)
264 .into_widget();
265 }
266 content
267 }
268}
269
270impl NavigationViewItemPresenter {
271 fn section_template(&self, r: &ThemeResources) -> WidgetRef {
273 let top = matches!(
274 self.position,
275 NavigationViewItemPosition::TopPrimary | NavigationViewItemPosition::TopFooter
276 );
277 if self.item.kind == NavigationViewItemKind::Header {
278 let collapsed = self.is_closed_compact && self.is_top_level_item;
279 let mut margin = if self.position != NavigationViewItemPosition::Left {
280 r.top_navigation_view_item_inner_header_margin
281 } else {
282 r.navigation_view_item_inner_header_margin
283 };
284 margin[0] += self.depth as f64 * 31.0;
285 let text = AnimatedOpacity::new(
287 if collapsed { 0.0 } else { 1.0 },
288 Duration::from_millis(200),
289 )
290 .curve(Rc::new(Interval::new(
291 if collapsed { 0.0 } else { 0.5 },
292 if collapsed { 0.5 } else { 1.0 },
293 Rc::new(Cubic::new(0.0, 0.35, 0.15, 1.0)),
294 )))
295 .child(Margin::new(
296 [0.0, -1.0, 0.0, -1.0],
297 DefaultTextStyle::new(
298 control_text_style(
299 r,
300 14.0,
301 FontWeight::W600,
302 r.navigation_view_item_header_foreground,
303 ),
304 self.item.content.clone(),
305 )
306 .soft_wrap(false),
307 ));
308 return PresenterGrid::new()
309 .height(if collapsed { 0.0 } else { 40.0 })
310 .margin(margin)
311 .child(
312 Align::new()
313 .alignment(Alignment::CENTER_LEFT.into())
314 .child(text),
315 )
316 .into_widget();
317 }
318 let line = PresenterGrid::new().background(Brush::Solid(if top {
319 r.top_navigation_view_item_separator_foreground
320 } else {
321 r.navigation_view_item_separator_foreground
322 }));
323 if top {
324 line.width(r.top_navigation_view_item_separator_width)
325 .height(24.0)
326 .margin(r.top_navigation_view_item_separator_margin)
327 .into_widget()
328 } else {
329 let mut margin = if self.is_closed_compact {
330 r.navigation_view_compact_item_separator_margin
331 } else {
332 r.navigation_view_item_separator_margin
333 };
334 margin[0] += self.depth as f64 * 31.0;
335 line.height(r.navigation_view_item_separator_height)
336 .margin(margin)
337 .into_widget()
338 }
339 }
340
341 fn template(&self, r: &ThemeResources, state: CommonState) -> WidgetRef {
343 let top = matches!(
344 self.position,
345 NavigationViewItemPosition::TopPrimary | NavigationViewItemPosition::TopFooter
346 );
347 let overflow = self.position == NavigationViewItemPosition::TopOverflow;
348 let (background, mut foreground) = item_colors(
349 r,
350 top,
351 self.is_selected,
352 if state == CommonState::Disabled {
353 CommonState::Normal
354 } else {
355 state
356 },
357 );
358 if state == CommonState::Disabled && (top || overflow) {
359 foreground = r.top_navigation_view_item_foreground_disabled;
360 }
361 let compact = self.is_closed_compact && !top && !overflow && self.is_top_level_item;
362 let show_chevron =
363 (!self.item.menu_items.is_empty() || self.item.has_unrealized_children) && !compact;
364 let icon_width = if top && !self.item.has_content {
365 36.0
366 } else if top {
367 28.0
368 } else if overflow {
369 32.0
370 } else if self.item.icon.is_none() {
371 8.0
372 } else {
373 (self.compact_pane_length - 8.0).max(0.0)
374 };
375 let icon = self
376 .item
377 .icon
378 .clone()
379 .unwrap_or_else(|| SizedBox::shrink().into_widget());
380 let mut icon_box = SizedBox::new().height(16.0);
382 if (top && self.item.has_content) || overflow {
383 icon_box = icon_box.width(16.0);
384 }
385 let icon = SizedBox::new().width(icon_width).child(
386 Align::new()
387 .alignment(if (top && self.item.has_content) || overflow {
388 Alignment::CENTER_RIGHT.into()
389 } else {
390 Alignment::CENTER.into()
391 })
392 .child(icon_box.child(FittedBox::new().child(icon))),
393 );
394 let margin = if compact {
395 r.navigation_view_compact_item_content_presenter_margin
396 } else if top {
397 if self.item.icon.is_some() {
398 r.top_navigation_view_item_content_presenter_margin
399 } else {
400 r.top_navigation_view_item_content_only_content_presenter_margin
401 }
402 } else if overflow {
403 if self.item.icon.is_some() {
404 r.top_navigation_view_item_on_overflow_content_presenter_margin
405 } else {
406 r.top_navigation_view_item_on_overflow_no_icon_content_presenter_margin
407 }
408 } else {
409 r.navigation_view_item_content_presenter_margin
410 };
411 let mut cells = vec![];
412 if self.item.icon.is_some() || (!top && !overflow) {
413 cells.push(GridCell::new(icon).column(0));
414 }
415 if self.item.has_content {
416 cells.push(
417 GridCell::new(
418 PresenterGrid::new().margin(margin).child(
419 Align::new()
420 .alignment(Alignment::CENTER_LEFT.into())
421 .child(self.item.content.clone()),
422 ),
423 )
424 .column(1),
425 );
426 }
427 if let Some(badge) = &self.item.info_badge {
428 let badge = Margin::new(
429 if compact {
430 [0.0, 2.0, 2.0, 0.0]
431 } else if top {
432 [-16.0, 0.0, 2.0, 13.0]
433 } else {
434 [0.0; 4]
435 },
436 Align::new()
437 .alignment(if compact {
438 Alignment::TOP_RIGHT.into()
439 } else {
440 Alignment::CENTER.into()
441 })
442 .child(badge.clone()),
443 );
444 cells.push(
445 GridCell::new(badge)
446 .column(if compact {
447 0
448 } else if top {
449 3
450 } else {
451 2
452 })
453 .column_span(if compact { 4 } else { 1 }),
454 );
455 }
456 if show_chevron {
457 let callback = self.on_expansion_toggled.clone();
458 let enabled = self.item.is_enabled;
459 let glyph = FontIcon::symbol(FluentSymbol::ChevronDown)
460 .font_size(r.navigation_view_item_expanded_glyph_font_size);
461 let glyph = AnimatedRotation::new(
462 if self.is_expanded { 0.5 } else { 0.0 },
463 r.control_normal_animation_duration,
464 )
465 .child(glyph);
466 let chevron = GestureDetector::new()
467 .behavior(HitTestBehavior::Opaque)
468 .on_tap(Listener::new(move |app| {
469 if enabled {
470 callback.call(app);
471 }
472 }))
473 .child(
474 SizedBox::new()
475 .width(40.0)
476 .child(Center::new().child(glyph)),
477 );
478 cells.push(
479 GridCell::new(
480 PresenterGrid::new()
481 .margin(if top {
482 if !self.item.has_content {
483 r.top_navigation_view_item_icon_only_expand_chevron_margin
484 } else if self.item.icon.is_some() {
485 r.top_navigation_view_item_expand_chevron_margin
486 } else {
487 r.top_navigation_view_item_content_only_expand_chevron_margin
488 }
489 } else if overflow {
490 r.top_navigation_view_item_on_overflow_expand_chevron_margin
491 } else {
492 r.navigation_view_item_expand_chevron_margin
493 })
494 .child(chevron),
495 )
496 .column(if top { 2 } else { 3 }),
497 );
498 }
499 let content = PresenterGrid::new()
500 .columns([
501 ColumnDefinition::new(GridLength::AUTO),
502 if top {
503 ColumnDefinition::new(GridLength::AUTO)
504 } else {
505 ColumnDefinition::new(GridLength::star(1.0))
506 },
507 ColumnDefinition::new(GridLength::AUTO),
508 ColumnDefinition::new(GridLength::AUTO),
509 ])
510 .min_height(36.0)
511 .margin([
512 self.depth as f64 * 31.0,
513 0.0,
514 if top || compact { 0.0 } else { 14.0 },
515 0.0,
516 ])
517 .cells(cells);
518 let mut layers = vec![content.into_widget()];
519 {
520 let indicator = PresenterGrid::new()
521 .background(Brush::Solid(
522 r.navigation_view_selection_indicator_foreground,
523 ))
524 .corner_radius(r.navigation_view_selection_indicator_radius)
525 .width(if top {
526 16.0
527 } else if overflow {
528 2.0
529 } else {
530 r.navigation_view_selection_indicator_width
531 })
532 .height(if top {
533 3.0
534 } else if overflow {
535 24.0
536 } else {
537 r.navigation_view_selection_indicator_height
538 });
539 let visible = self.is_selected || (self.is_child_selected && !self.is_expanded);
540 let indicator = NavigationIndicatorTransition::build(
541 self.indicator_controller.clone(),
542 self.indicator_animation.clone(),
543 self.indicator_opacity
544 .unwrap_or(if visible { 1.0 } else { 0.0 }),
545 indicator.into_widget(),
546 );
547 let indicator = KeyedSubtree::new(indicator).key(self.indicator_key.clone().into());
548 layers.push(
549 Positioned::fill(
550 IgnorePointer::new().child(
551 Align::new()
552 .alignment(if top {
553 Alignment::BOTTOM_CENTER.into()
554 } else {
555 Alignment::CENTER_LEFT.into()
556 })
557 .child(
558 PresenterGrid::new()
559 .margin(if top {
560 if !self.item.has_content {
561 [0.0; 4]
562 } else if self.item.icon.is_none() {
563 [12.0, 0.0, 12.0, 4.0]
564 } else {
565 [16.0, 0.0, 16.0, 4.0]
566 }
567 } else if overflow {
568 [4.0, 0.0, 0.0, 0.0]
569 } else {
570 [0.0; 4]
571 })
572 .child(indicator),
573 ),
574 ),
575 )
576 .into_widget(),
577 );
578 }
579 let root = PresenterGrid::new()
580 .background(Brush::Solid(background))
581 .corner_radius(r.control_corner_radius[0])
582 .margin(if overflow {
583 [0.0; 4]
584 } else if top && !self.item.has_content {
585 [2.0; 4]
586 } else {
587 r.navigation_view_item_button_margin
588 })
589 .child(Stack::new().children(layers));
590 DefaultTextStyle::new(
591 control_text_style(
592 r,
593 r.control_content_theme_font_size,
594 FontWeight::W400,
595 foreground,
596 ),
597 Opacity::new(if !top && !overflow && state == CommonState::Disabled {
598 r.list_view_item_disabled_theme_opacity
599 } else {
600 1.0
601 })
602 .child(root),
603 )
604 .soft_wrap(false)
605 .into_widget()
606 }
607}
608
609fn item_colors(
611 r: &ThemeResources,
612 top: bool,
613 selected: bool,
614 state: CommonState,
615) -> (Color, Color) {
616 use CommonState::*;
617 if top {
618 match (selected, state) {
619 (_, Disabled) => (
620 r.navigation_view_item_background,
621 r.top_navigation_view_item_foreground_disabled,
622 ),
623 (true, Pressed) => (
624 r.top_navigation_view_item_background_selected_pressed,
625 r.top_navigation_view_item_foreground_selected_pressed,
626 ),
627 (true, PointerOver) => (
628 r.top_navigation_view_item_background_selected_pointer_over,
629 r.top_navigation_view_item_foreground_selected_pointer_over,
630 ),
631 (true, Normal) => (
632 r.top_navigation_view_item_background_selected,
633 r.top_navigation_view_item_foreground_selected,
634 ),
635 (false, Pressed) => (
636 r.top_navigation_view_item_background_pressed,
637 r.top_navigation_view_item_foreground_pressed,
638 ),
639 (false, PointerOver) => (
640 r.top_navigation_view_item_background_pointer_over,
641 r.top_navigation_view_item_foreground_pointer_over,
642 ),
643 (false, Normal) => (
644 r.navigation_view_item_background,
645 r.top_navigation_view_item_foreground,
646 ),
647 }
648 } else {
649 match (selected, state) {
650 (_, Disabled) => (
651 r.navigation_view_item_background_disabled,
652 r.navigation_view_item_foreground_disabled,
653 ),
654 (true, Pressed) => (
655 r.navigation_view_item_background_selected_pressed,
656 r.navigation_view_item_foreground_selected_pressed,
657 ),
658 (true, PointerOver) => (
659 r.navigation_view_item_background_selected_pointer_over,
660 r.navigation_view_item_foreground_selected_pointer_over,
661 ),
662 (true, Normal) => (
663 r.navigation_view_item_background_selected,
664 r.navigation_view_item_foreground_selected,
665 ),
666 (false, Pressed) => (
667 r.navigation_view_item_background_pressed,
668 r.navigation_view_item_foreground_pressed,
669 ),
670 (false, PointerOver) => (
671 r.navigation_view_item_background_pointer_over,
672 r.navigation_view_item_foreground_pointer_over,
673 ),
674 (false, Normal) => (
675 r.navigation_view_item_background,
676 r.navigation_view_item_foreground,
677 ),
678 }
679 }
680}
681
682#[derive(Debug, Default)]
684struct PresenterGrid {
685 children: Vec<WidgetRef>,
686 columns: Vec<ColumnDefinition>,
687 width: Option<f64>,
688 height: Option<f64>,
689 minimum_height: f64,
690 margin: [f64; 4],
691 background: Option<Brush>,
692 radius: f64,
693}
694
695impl PresenterGrid {
696 fn new() -> Self {
697 Self::default()
698 }
699 fn width(mut self, value: f64) -> Self {
700 self.width = Some(value);
701 self
702 }
703 fn height(mut self, value: f64) -> Self {
704 self.height = Some(value);
705 self
706 }
707 fn min_height(mut self, value: f64) -> Self {
708 self.minimum_height = value;
709 self
710 }
711 fn margin(mut self, value: [f64; 4]) -> Self {
712 self.margin = value;
713 self
714 }
715 fn background(mut self, value: Brush) -> Self {
716 self.background = Some(value);
717 self
718 }
719 fn corner_radius(mut self, value: f64) -> Self {
720 self.radius = value;
721 self
722 }
723 fn columns(mut self, value: impl IntoIterator<Item = ColumnDefinition>) -> Self {
724 self.columns = value.into_iter().collect();
725 self
726 }
727 fn cells(mut self, value: Vec<GridCell>) -> Self {
728 self.children = value.into_iter().map(IntoWidget::into_widget).collect();
729 self
730 }
731 #[cfg_attr(debug_assertions, track_caller)]
732 fn child<K>(mut self, value: impl IntoWidget<K>) -> Self {
733 self.children = vec![value.into_widget()];
734 self
735 }
736}
737
738impl StatelessWidget for PresenterGrid {
739 fn build(&self, _: &mut App, _: BuildContext) -> WidgetRef {
740 let mut grid = Grid::new()
741 .column_definitions(self.columns.clone())
742 .children(self.children.clone())
743 .corner_radius(self.radius);
744 grid.background = self.background;
745 let mut outer = Container::new()
746 .constraints(BoxConstraints::new().min_height(self.minimum_height))
747 .child(grid);
748 if let Some(width) = self.width {
749 outer = outer.width(width);
750 }
751 if let Some(height) = self.height {
752 outer = outer.height(height);
753 }
754 Margin::new(self.margin, outer).into_widget()
755 }
756}