Skip to main content

waft_winui/controls/
navigation_view.rs

1//! NavigationView's adaptive pane, hierarchical selection and top projection from NavigationView.cpp.
2
3use super::navigation_indicator_transition::NAVIGATION_INDICATOR_DURATION;
4use super::navigation_view_chrome::{
5    PaneChrome, back_button_template, pane_title, pane_toggle_template,
6};
7use super::navigation_view_item::{NavigationViewItemPosition, NavigationViewItemPresenter};
8use super::top_navigation_view_data_provider::TopNavigationViewDataProvider;
9use crate::*;
10use std::{
11    cell::Cell,
12    collections::{HashMap, HashSet},
13    fmt,
14    rc::Rc,
15    time::Duration,
16};
17use waft_animation::{AnimationBehavior, AnimationController, Curves};
18use waft_embedder::{Color, FontWeight, Offset, Rect, TextDirection};
19use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
20use waft_painting::{Alignment, EdgeInsets, EdgeInsetsGeometry};
21use waft_rendering::{BoxConstraints, CrossAxisAlignment, MainAxisSize, StackFit};
22use waft_scheduler::{
23    FrameCallback, SchedulerBinding, Ticker, TickerCallback, TickerProviderObject,
24};
25use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey};
26use waft_widgets::*;
27
28/// The space available to the left navigation pane.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum NavigationViewDisplayMode {
31    /// Only the toggle button is visible while the pane is closed.
32    #[default]
33    Minimal,
34    /// A compact icon rail remains visible while the pane is closed.
35    Compact,
36    /// The pane occupies space beside the content.
37    Expanded,
38}
39
40/// Selects adaptive left navigation or an explicit pane configuration.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum NavigationViewPaneDisplayMode {
43    /// Uses the compact and expanded width thresholds.
44    #[default]
45    Auto,
46    /// Keeps the expanded left layout at every width.
47    Left,
48    /// Places primary items in a horizontal strip with an overflow menu.
49    Top,
50    /// Keeps a compact left rail at every width.
51    LeftCompact,
52    /// Keeps a light-dismiss overlay pane at every width.
53    LeftMinimal,
54}
55
56/// Controls whether the navigation back button occupies its template slot.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58pub enum NavigationViewBackButtonVisible {
59    /// Hides the back button and its placeholder.
60    Collapsed,
61    /// Shows the back button.
62    Visible,
63    /// Shows the desktop back button, matching the source's non-console branch.
64    #[default]
65    Auto,
66}
67
68/// Whether moving keyboard focus also invokes selection.
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub enum NavigationViewSelectionFollowsFocus {
71    /// Focus moves independently of selection.
72    #[default]
73    Disabled,
74    /// Keyboard focus changes select eligible items.
75    Enabled,
76}
77
78/// The source's suggested page-transition direction; the owner performs navigation.
79#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
80pub enum NavigationRecommendedTransitionDirection {
81    /// The default transition used by left navigation and settings.
82    #[default]
83    Default,
84    /// A top selection moved toward an item to the left.
85    FromLeft,
86    /// A top selection moved toward an item to the right.
87    FromRight,
88    /// A top selection came from the overflow menu.
89    FromOverflow,
90}
91
92/// Identifies a menu item independently of its current visual projection.
93#[derive(Clone, Debug)]
94pub struct NavigationViewItemEventArgs {
95    /// The owner's item snapshot at the time of the event.
96    pub item: NavigationViewItem,
97    /// Main/footer block, root index and any child indices.
98    pub index_path: Vec<usize>,
99    /// Whether the built-in settings item was invoked or selected.
100    pub is_settings: bool,
101    /// The source's suggestion for the owner's page transition.
102    pub recommended_transition_direction: NavigationRecommendedTransitionDirection,
103}
104
105/// Describes selection, including clearing selection when the selected item is removed.
106#[derive(Clone, Debug)]
107pub struct NavigationViewSelectionChangedEventArgs {
108    /// Selected source item, or None when the selection is cleared.
109    pub item: Option<NavigationViewItem>,
110    /// Main/footer block and child indices, empty when selection is cleared.
111    pub index_path: Vec<usize>,
112    /// Whether the built-in settings item is selected.
113    pub is_settings: bool,
114    /// The suggested transition for the owner's page navigation.
115    pub recommended_transition_direction: NavigationRecommendedTransitionDirection,
116}
117
118impl From<NavigationViewItemEventArgs> for NavigationViewSelectionChangedEventArgs {
119    fn from(args: NavigationViewItemEventArgs) -> Self {
120        Self {
121            item: Some(args.item),
122            index_path: args.index_path,
123            is_settings: args.is_settings,
124            recommended_transition_direction: args.recommended_transition_direction,
125        }
126    }
127}
128
129/// Receives both selection and deselection requests.
130pub type NavigationViewSelectionChanged =
131    Rc<dyn Fn(&mut App, NavigationViewSelectionChangedEventArgs)>;
132
133/// Requests owner-controlled pane openness.
134pub type NavigationViewPaneOpenChanged = Rc<dyn Fn(&mut App, bool)>;
135
136/// Reports the effective adaptive display mode.
137pub type NavigationViewDisplayModeChanged = Rc<dyn Fn(&mut App, NavigationViewDisplayMode)>;
138
139/// Receives selection, invocation, expansion or collapse with a stable item identity.
140pub type NavigationViewItemEvent = Rc<dyn Fn(&mut App, NavigationViewItemEventArgs)>;
141
142/// A navigation shell; the owner supplies content and handles navigation events.
143#[derive(Clone)]
144pub struct NavigationView {
145    /// Identity retained across owner rebuilds.
146    pub key: Option<KeyRef>,
147    /// Main menu items and their nested children.
148    pub menu_items: Vec<NavigationViewItem>,
149    /// Footer menu items, before the built-in settings item.
150    pub footer_menu_items: Vec<NavigationViewItem>,
151    /// Stable identity selected by the owner.
152    pub selected_item: Option<String>,
153    /// Requests selection after ItemInvoked has been raised.
154    pub selection_changed: NavigationViewSelectionChanged,
155    /// Receives every invocation, including the already selected item.
156    pub item_invoked: Option<NavigationViewItemEvent>,
157    /// The page content; NavigationView does not instantiate pages itself.
158    pub content: WidgetRef,
159    /// Chooses the adaptive or explicit layout.
160    pub pane_display_mode: NavigationViewPaneDisplayMode,
161    /// Below this positive width Auto uses Minimal.
162    pub compact_mode_threshold_width: f64,
163    /// At and above this width Auto uses Expanded.
164    pub expanded_mode_threshold_width: f64,
165    /// The width of the closed icon rail.
166    pub compact_pane_length: f64,
167    /// The requested open pane width, clamped to the available control width.
168    pub open_pane_length: f64,
169    /// Optional owner override; None lets the adaptive pane maintain its openness.
170    pub is_pane_open: Option<bool>,
171    /// Requests an owner update when a controlled pane opens or closes.
172    pub pane_open_changed: Option<NavigationViewPaneOpenChanged>,
173    /// Whether either pane is visible.
174    pub is_pane_visible: bool,
175    /// `IsTitleBarAutoPaddingEnabled`: whether the toggle, the pane's items and the content's
176    /// controls keep clear of what the system covers of the view (the `MediaQuery`'s `padding`,
177    /// which a `FluentPage` that `extends_content_into_system_bars` leaves), while the pane and the
178    /// content reach the view's edges.
179    pub is_title_bar_auto_padding_enabled: bool,
180    /// Whether the menu toggle is visible in left layouts.
181    pub is_pane_toggle_button_visible: bool,
182    /// Whether the settings entry is appended to the footer.
183    pub is_settings_visible: bool,
184    /// Whether the back button is visible.
185    pub is_back_button_visible: NavigationViewBackButtonVisible,
186    /// Whether the visible back button accepts input.
187    pub is_back_enabled: bool,
188    /// Receives back-button activation without changing the selected page.
189    pub back_requested: Option<Listener>,
190    /// Whether keyboard focus selects menu items.
191    pub selection_follows_focus: NavigationViewSelectionFollowsFocus,
192    /// Optional page header above content.
193    pub header: Option<WidgetRef>,
194    /// Keeps the page header visible outside Minimal mode.
195    pub always_show_header: bool,
196    /// Text next to the pane toggle, or preceding top items.
197    pub pane_title: String,
198    /// Custom header in the pane.
199    pub pane_header: Option<WidgetRef>,
200    /// Custom content between pane header and menu items.
201    pub pane_custom_content: Option<WidgetRef>,
202    /// Native search content hosted in the source AutoSuggestBox presenter slot.
203    pub auto_suggest_box: Option<WidgetRef>,
204    /// Custom content above footer menu items.
205    pub pane_footer: Option<WidgetRef>,
206    /// Content placed below the top pane, before page content.
207    pub content_overlay: Option<WidgetRef>,
208    /// Receives adaptive display-mode changes.
209    pub display_mode_changed: Option<NavigationViewDisplayModeChanged>,
210    /// Fires before expanded children become visible.
211    pub expanding: Option<NavigationViewItemEvent>,
212    /// Fires after collapsed children are hidden.
213    pub collapsed: Option<NavigationViewItemEvent>,
214    /// Fires when the pane starts opening.
215    pub pane_opening: Option<Listener>,
216    /// Fires when the pane finishes opening.
217    pub pane_opened: Option<Listener>,
218    /// Can cancel a pane closing request.
219    pub pane_closing: Option<SplitViewPaneClosingHandler>,
220    /// Fires when the pane finishes closing.
221    pub pane_closed: Option<Listener>,
222}
223
224impl fmt::Debug for NavigationView {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        f.debug_struct("NavigationView")
227            .field("selected_item", &self.selected_item)
228            .field("pane_display_mode", &self.pane_display_mode)
229            .finish_non_exhaustive()
230    }
231}
232
233impl NavigationView {
234    /// Stable identity of the built-in settings item; owner item ids must not use it.
235    pub const SETTINGS_ITEM_ID: &'static str = "__navigation_settings";
236
237    /// Creates an adaptive navigation shell with owner-managed selection and page content.
238    #[cfg_attr(debug_assertions, track_caller)]
239    pub fn new<C>(
240        menu_items: Vec<NavigationViewItem>,
241        selected_item: Option<String>,
242        selection_changed: impl Fn(&mut App, NavigationViewSelectionChangedEventArgs) + 'static,
243        content: impl IntoWidget<C>,
244    ) -> Self {
245        Self {
246            key: None,
247            menu_items,
248            footer_menu_items: Vec::new(),
249            selected_item,
250            selection_changed: Rc::new(selection_changed),
251            item_invoked: None,
252            content: content.into_widget(),
253            pane_display_mode: NavigationViewPaneDisplayMode::Auto,
254            compact_mode_threshold_width: 641.0,
255            expanded_mode_threshold_width: 1008.0,
256            compact_pane_length: 48.0,
257            open_pane_length: 320.0,
258            is_pane_open: None,
259            pane_open_changed: None,
260            is_pane_visible: true,
261            is_title_bar_auto_padding_enabled: true,
262            is_pane_toggle_button_visible: true,
263            is_settings_visible: true,
264            is_back_button_visible: NavigationViewBackButtonVisible::Auto,
265            is_back_enabled: false,
266            back_requested: None,
267            selection_follows_focus: NavigationViewSelectionFollowsFocus::Disabled,
268            header: None,
269            always_show_header: true,
270            pane_title: String::new(),
271            pane_header: None,
272            pane_custom_content: None,
273            auto_suggest_box: None,
274            pane_footer: None,
275            content_overlay: None,
276            display_mode_changed: None,
277            expanding: None,
278            collapsed: None,
279            pane_opening: None,
280            pane_opened: None,
281            pane_closing: None,
282            pane_closed: None,
283        }
284    }
285}
286
287/// Retains one logical container through pane/overflow reparenting.
288#[derive(Clone)]
289struct NavigationContainer {
290    /// Global identity preserving state in caller-supplied item content.
291    key: GlobalKey,
292    /// Focus shared with the item's native input presenter.
293    focus: FocusNodeRef,
294    /// Exact source indicator geometry, including while its opacity is zero.
295    indicator_key: GlobalKey,
296    /// Source compositor CenterPoint.X survives completion and is retained per owner.
297    indicator_pivot_x: Rc<Cell<f64>>,
298    /// An existing CenterPoint animation keeps its final step even if Scale is replaced.
299    indicator_pivot_step: Cell<Option<(Duration, f64)>>,
300}
301
302/// Source state that cannot be derived from the current width alone.
303pub struct NavigationViewState {
304    /// Native widget lifecycle data.
305    state: StateData<NavigationView>,
306    /// Stable item containers, including currently collapsed children.
307    containers: HashMap<String, NavigationContainer>,
308    /// Stable native identities for owner content reparented by pane-mode changes.
309    slot_keys: HashMap<&'static str, GlobalKey>,
310    /// Expanded ids independent of where their children are presented.
311    expanded: HashSet<String>,
312    /// Expanded left items restored when a compact pane reopens.
313    restore_expanded: HashSet<String>,
314    /// Current adaptive display mode.
315    display_mode: NavigationViewDisplayMode,
316    /// Native pane openness when not controlled by the owner.
317    pane_open: bool,
318    /// Prevents a second PaneClosing event after a NavigationView light-close request.
319    block_next_closing: bool,
320    /// Explicit closure prevents automatic reopening on later Expanded layouts.
321    was_force_closed: bool,
322    /// Whether the first non-forced width update has occurred.
323    initial_mode_update: bool,
324    /// Last width used for adaptive updates.
325    width: f64,
326    /// Last pane mode applied by the layout callback.
327    pane_mode: NavigationViewPaneDisplayMode,
328    /// Independent native scrolling for main and footer groups.
329    scrolls: Vec<Ref<ScrollViewportController>>,
330    /// Native focus scope retained when the search presenter moves between pane modes.
331    search_focus: Option<Ref<FocusScopeNode>>,
332    /// Natural heights of the main, footer and pane-footer content.
333    group_heights: [f64; 3],
334    /// Top-level source order and attached natural width cache.
335    top: TopNavigationViewDataProvider,
336    /// Forces a full primary measure before partitioning changed content.
337    top_measure_pending: bool,
338    /// Width consumed by top header, custom content and footer slots.
339    top_chrome_width: f64,
340    /// Natural leading and trailing top slots.
341    top_chrome_sizes: [f64; 3],
342    /// Whether the top overflow flyout is open.
343    overflow_open: bool,
344    /// Selected identity used to detect owner changes and transitions.
345    selected: Option<String>,
346    /// Actual outgoing/incoming owners and initial geometry for source relative transforms.
347    indicator_transition: Option<(NavigationIndicatorOwner, NavigationIndicatorOwner, bool)>,
348    /// Keeps the outgoing owner visible while the destination receives its first layout.
349    pending_indicator: Option<NavigationIndicatorOwner>,
350    /// Shared native clock for both actual item visuals.
351    indicator_controller: Option<Ref<AnimationController>>,
352    /// Native ticker ownership for the selection storyboard.
353    indicator_ticker: SingleTickerProviderStateMixinData,
354    /// Invalidates geometry/completion callbacks when selection changes again.
355    indicator_epoch: u64,
356}
357
358impl StatefulWidget for NavigationView {
359    type State = NavigationViewState;
360
361    fn key(&self) -> Option<&KeyRef> {
362        self.key.as_ref()
363    }
364
365    fn create_state(&self) -> Self::State {
366        NavigationViewState {
367            state: StateData::new(),
368            containers: HashMap::new(),
369            slot_keys: [
370                "content",
371                "header",
372                "pane_header",
373                "custom",
374                "footer",
375                "search",
376            ]
377            .into_iter()
378            .map(|slot| (slot, GlobalKey::labeled(format!("Navigation {slot}"))))
379            .collect(),
380            expanded: HashSet::new(),
381            restore_expanded: HashSet::new(),
382            display_mode: NavigationViewDisplayMode::Minimal,
383            pane_open: true,
384            block_next_closing: false,
385            was_force_closed: false,
386            initial_mode_update: true,
387            width: f64::NAN,
388            pane_mode: self.pane_display_mode,
389            scrolls: Vec::new(),
390            search_focus: None,
391            group_heights: [0.0; 3],
392            top: TopNavigationViewDataProvider::default(),
393            top_measure_pending: true,
394            top_chrome_width: 56.0,
395            top_chrome_sizes: [0.0; 3],
396            overflow_open: false,
397            selected: self.selected_item.clone(),
398            indicator_transition: None,
399            pending_indicator: None,
400            indicator_controller: None,
401            indicator_ticker: SingleTickerProviderStateMixinData::default(),
402            indicator_epoch: 0,
403        }
404    }
405}
406
407/// Actual indicator identity and its settled geometry at animation setup.
408#[derive(Clone, Debug)]
409struct NavigationIndicatorOwner {
410    /// Stable menu identity whose actual SelectionIndicator receives the transform.
411    id: String,
412    /// Settled bounds at setup; parent motion remains inherited by the real visual.
413    rect: Rect,
414}
415
416impl SingleTickerProviderStateMixin for NavigationViewState {
417    fn single_ticker_provider_data(
418        self: Handle<Self>,
419        app: &App,
420    ) -> &SingleTickerProviderStateMixinData {
421        &app.get(self).indicator_ticker
422    }
423
424    fn single_ticker_provider_data_mut(
425        self: Handle<Self>,
426        app: &mut App,
427    ) -> &mut SingleTickerProviderStateMixinData {
428        &mut app.get_mut(self).indicator_ticker
429    }
430}
431
432impl TickerProviderObject for NavigationViewState {
433    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
434        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
435    }
436}
437
438/// Flattens source identities and paths without depending on visual parentage.
439fn collect_items(
440    items: &[NavigationViewItem],
441    parent: &[usize],
442    output: &mut Vec<(NavigationViewItem, Vec<usize>)>,
443) {
444    for (index, item) in items.iter().enumerate() {
445        let mut path = parent.to_vec();
446        path.push(index);
447        output.push((item.clone(), path.clone()));
448        collect_items(&item.menu_items, &path, output);
449    }
450}
451
452impl NavigationViewState {
453    /// Returns the current adaptive display mode.
454    pub fn display_mode(self: Handle<Self>, app: &App) -> NavigationViewDisplayMode {
455        app.get(self).display_mode
456    }
457
458    /// Returns the current pane openness, including an owner override.
459    pub fn is_pane_open(self: Handle<Self>, app: &App) -> bool {
460        self.widget(app)
461            .is_pane_open
462            .unwrap_or(app.get(self).pane_open)
463    }
464
465    /// Returns a mounted container by stable identity, including flyout children.
466    pub fn container_from_menu_item(
467        self: Handle<Self>,
468        app: &mut App,
469        id: &str,
470    ) -> Option<BuildContext> {
471        let key = app.get(self).containers.get(id)?.key.clone();
472        key.current_context(app)
473    }
474
475    /// Returns an item's current index path independent of the current projection.
476    pub fn index_path_from_item(self: Handle<Self>, app: &App, id: &str) -> Option<Vec<usize>> {
477        self.all_items(app)
478            .into_iter()
479            .find(|(item, _)| item.id == id)
480            .map(|(_, path)| path)
481    }
482
483    /// Retains an owner-supplied content subtree when the source template reparents its slot.
484    fn slot(self: Handle<Self>, app: &App, name: &'static str, child: WidgetRef) -> WidgetRef {
485        KeyedSubtree::new(child)
486            .key(app.get(self).slot_keys[name].clone().into())
487            .into_widget()
488    }
489
490    /// The built-in settings item follows user footer entries.
491    fn footer_items(self: Handle<Self>, app: &App) -> Vec<NavigationViewItem> {
492        let widget = self.widget(app);
493        let mut items = widget.footer_menu_items.clone();
494        if widget.is_settings_visible {
495            let mut settings =
496                NavigationViewItem::text(NavigationView::SETTINGS_ITEM_ID, "Settings")
497                    .icon(FontIcon::symbol(FluentSymbol::Settings));
498            if widget.pane_display_mode == NavigationViewPaneDisplayMode::Top {
499                settings = settings
500                    .without_content()
501                    .tool_tip(ToolTip::text("Settings"));
502            }
503            items.push(settings);
504        }
505        items
506    }
507
508    /// Gets the main and footer source blocks in SelectionModel path order.
509    fn all_items(self: Handle<Self>, app: &App) -> Vec<(NavigationViewItem, Vec<usize>)> {
510        let mut result = Vec::new();
511        collect_items(&self.widget(app).menu_items, &[0], &mut result);
512        collect_items(&self.footer_items(app), &[1], &mut result);
513        result
514    }
515
516    /// Reconciles container ownership and releases removed nodes after native detach.
517    fn sync_items(self: Handle<Self>, app: &mut App) {
518        let items = self.all_items(app);
519        let ids: HashSet<_> = items.iter().map(|(item, _)| item.id.clone()).collect();
520        assert_eq!(
521            ids.len(),
522            items.len(),
523            "NavigationView item ids must be unique, including nested items"
524        );
525        let removed: Vec<_> = app
526            .get(self)
527            .containers
528            .keys()
529            .filter(|id| !ids.contains(*id))
530            .cloned()
531            .collect();
532        for id in removed {
533            let entry = app.get_mut(self).containers.remove(&id).unwrap();
534            SchedulerBinding::add_post_frame_callback(
535                app,
536                FrameCallback::new(move |app, _| {
537                    entry.focus.dispose(app);
538                }),
539                View::maybe_id_of(app, self.context(app)),
540            );
541        }
542        for id in ids {
543            if !app.get(self).containers.contains_key(&id) {
544                let entry = NavigationContainer {
545                    key: GlobalKey::labeled(id.clone()),
546                    focus: FocusNode::new(app).into_erased(),
547                    indicator_key: GlobalKey::labeled(format!("Indicator {id}")),
548                    indicator_pivot_x: Rc::new(Cell::new(0.0)),
549                    indicator_pivot_step: Cell::new(None),
550                };
551                app.get_mut(self).containers.insert(id, entry);
552            }
553        }
554        let ids = self
555            .widget(app)
556            .menu_items
557            .iter()
558            .map(|item| item.id.clone())
559            .collect::<Vec<_>>();
560        app.get_mut(self).top.set_data_source(ids);
561        let hidden: Vec<_> = self
562            .widget(app)
563            .menu_items
564            .iter()
565            .enumerate()
566            .filter_map(|(index, item)| (!item.is_visible).then_some(index))
567            .collect();
568        for index in hidden {
569            app.get_mut(self).top.set_width_for_item(index, 0.0);
570        }
571    }
572
573    /// Raises a callback after the current build/layout phase.
574    fn after_frame(self: Handle<Self>, app: &mut App, callback: impl Fn(&mut App) + 'static) {
575        after_next_frame(
576            app,
577            View::maybe_id_of(app, self.context(app)),
578            FrameCallback::new(move |app, _| {
579                if app.contains(self) && self.mounted(app) {
580                    callback(app);
581                }
582            }),
583        );
584    }
585
586    /// OpenPane/ClosePane requests, with explicit closure remembered for adaptive resizing.
587    fn set_pane_open(self: Handle<Self>, app: &mut App, open: bool, explicit: bool) {
588        if explicit {
589            app.get_mut(self).was_force_closed = !open;
590        }
591        if self.is_pane_open(app) == open {
592            return;
593        }
594        self.set_state(app, |state| {
595            state.pane_open = open;
596            if open {
597                state.was_force_closed = false;
598            }
599        });
600        self.apply_pane_expansion_memory(app, open);
601        if let Some(callback) = self.widget(app).pane_open_changed.clone() {
602            callback(app, open);
603        }
604    }
605
606    /// Source HandleExpansionStateMemory changes only top-level owners, preserving nested expansion.
607    fn apply_pane_expansion_memory(self: Handle<Self>, app: &mut App, open: bool) {
608        let roots: Vec<_> = self
609            .all_items(app)
610            .into_iter()
611            .filter(|(_, path)| path.len() == 2)
612            .map(|(item, _)| item.id)
613            .collect();
614        for id in roots {
615            if open {
616                if app.get_mut(self).restore_expanded.remove(&id)
617                    && !app.get(self).expanded.contains(&id)
618                {
619                    self.toggle_expanded(app, &id);
620                }
621            } else if app.get(self).expanded.contains(&id) {
622                app.get_mut(self).restore_expanded.insert(id.clone());
623                self.toggle_expanded(app, &id);
624            }
625        }
626    }
627
628    /// UpdateAdaptiveLayout retains source initial-update and force-closed flags.
629    fn update_adaptive_layout(self: Handle<Self>, app: &mut App, width: f64) {
630        let widget = self.widget(app).clone();
631        if app.get(self).width == width && app.get(self).pane_mode == widget.pane_display_mode {
632            return;
633        }
634        let old_mode = app.get(self).display_mode;
635        let old_pane_mode = app.get(self).pane_mode;
636        let mode = match widget.pane_display_mode {
637            NavigationViewPaneDisplayMode::Top | NavigationViewPaneDisplayMode::LeftMinimal => {
638                NavigationViewDisplayMode::Minimal
639            }
640            NavigationViewPaneDisplayMode::Left => NavigationViewDisplayMode::Expanded,
641            NavigationViewPaneDisplayMode::LeftCompact => NavigationViewDisplayMode::Compact,
642            NavigationViewPaneDisplayMode::Auto
643                if width >= widget.expanded_mode_threshold_width =>
644            {
645                NavigationViewDisplayMode::Expanded
646            }
647            NavigationViewPaneDisplayMode::Auto
648                if width > 0.0 && width < widget.compact_mode_threshold_width =>
649            {
650                NavigationViewDisplayMode::Minimal
651            }
652            _ => NavigationViewDisplayMode::Compact,
653        };
654        let initial = app.get(self).initial_mode_update;
655        {
656            let state = app.get_mut(self);
657            state.width = width;
658            state.pane_mode = widget.pane_display_mode;
659            state.display_mode = mode;
660            state.initial_mode_update = false;
661        }
662        let close = widget.pane_display_mode == NavigationViewPaneDisplayMode::Top
663            || mode == NavigationViewDisplayMode::Minimal
664            || (initial && mode == NavigationViewDisplayMode::Compact)
665            || (old_mode == NavigationViewDisplayMode::Expanded
666                && mode == NavigationViewDisplayMode::Compact);
667        let open = mode == NavigationViewDisplayMode::Expanded
668            && widget.is_pane_visible
669            && (!app.get(self).was_force_closed
670                || old_pane_mode == NavigationViewPaneDisplayMode::LeftMinimal);
671        if close || open {
672            self.after_frame(app, move |app| self.set_pane_open(app, !close, false));
673        }
674        if old_mode != mode
675            && let Some(callback) = widget.display_mode_changed
676        {
677            self.after_frame(app, move |app| callback(app, mode));
678        }
679    }
680
681    /// Builds event arguments from stable source paths and the current top projection.
682    fn event_args(
683        self: Handle<Self>,
684        app: &App,
685        id: &str,
686        overflow: bool,
687    ) -> Option<NavigationViewItemEventArgs> {
688        let (item, index_path) = self
689            .all_items(app)
690            .into_iter()
691            .find(|(item, _)| item.id == id)?;
692        let settings = id == NavigationView::SETTINGS_ITEM_ID;
693        let direction = if settings
694            || self.widget(app).pane_display_mode != NavigationViewPaneDisplayMode::Top
695        {
696            NavigationRecommendedTransitionDirection::Default
697        } else if overflow {
698            NavigationRecommendedTransitionDirection::FromOverflow
699        } else {
700            let old = app
701                .get(self)
702                .selected
703                .as_ref()
704                .and_then(|id| self.index_path_from_item(app, id));
705            match old {
706                Some(old) if old < index_path => {
707                    NavigationRecommendedTransitionDirection::FromRight
708                }
709                Some(old) if old > index_path => NavigationRecommendedTransitionDirection::FromLeft,
710                _ => NavigationRecommendedTransitionDirection::Default,
711            }
712        };
713        Some(NavigationViewItemEventArgs {
714            item,
715            index_path,
716            is_settings: settings,
717            recommended_transition_direction: direction,
718        })
719    }
720
721    /// Raises invocation before selection, then toggles children and dismisses leaf navigation.
722    fn invoke(self: Handle<Self>, app: &mut App, id: &str, overflow: bool) {
723        let Some(args) = self.event_args(app, id, overflow) else {
724            return;
725        };
726        if !args.item.is_enabled
727            || !args.item.is_visible
728            || args.item.kind != NavigationViewItemKind::Item
729        {
730            return;
731        }
732        let before = app.get(self).selected.clone();
733        let old_indicator = before.as_ref().and_then(|id| self.indicator_rect(app, id));
734        if let Some(callback) = self.widget(app).item_invoked.clone() {
735            callback(app, args.clone());
736        }
737        if args.item.selects_on_invoked
738            && before == app.get(self).selected
739            && before.as_deref() != Some(id)
740        {
741            let callback = self.widget(app).selection_changed.clone();
742            self.set_state(app, |state| state.selected = Some(id.to_owned()));
743            if overflow && args.index_path[0] == 0 {
744                let width = (app.get(self).width - app.get(self).top_chrome_width).max(0.0);
745                app.get_mut(self)
746                    .top
747                    .select_overflow_item(args.index_path[1], width);
748            }
749            callback(app, args.clone().into());
750            self.animate_selection(app, old_indicator);
751        }
752        if !args.item.menu_items.is_empty() || args.item.has_unrealized_children {
753            self.toggle_expanded(app, id);
754        } else {
755            self.set_state(app, |state| {
756                state.overflow_open = false;
757            });
758            if args.item.selects_on_invoked
759                && args.index_path.len() > 2
760                && (self.widget(app).pane_display_mode == NavigationViewPaneDisplayMode::Top
761                    || !self.is_pane_open(app))
762            {
763                let root = self
764                    .all_items(app)
765                    .into_iter()
766                    .find(|(_, path)| path.as_slice() == &args.index_path[..2]);
767                if let Some((root, _)) = root
768                    && app.get(self).expanded.contains(&root.id)
769                {
770                    self.toggle_expanded(app, &root.id);
771                }
772            }
773            if self.is_pane_open(app)
774                && app.get(self).display_mode != NavigationViewDisplayMode::Expanded
775            {
776                self.set_pane_open(app, false, false);
777            }
778        }
779    }
780
781    /// Expanding precedes children; Collapsed follows the rebuild that hides them.
782    fn toggle_expanded(self: Handle<Self>, app: &mut App, id: &str) {
783        let Some(args) = self.event_args(app, id, false) else {
784            return;
785        };
786        let expanded = app.get(self).expanded.contains(id);
787        let selected = app.get(self).selected.clone();
788        let previous_indicator = selected.as_ref().and_then(|selected| {
789            let path = self.index_path_from_item(app, selected)?;
790            (selected != id && path.starts_with(&args.index_path))
791                .then(|| self.indicator_rect(app, selected))
792                .flatten()
793        });
794        if !expanded && let Some(callback) = self.widget(app).expanding.clone() {
795            callback(app, args.clone());
796        }
797        self.set_state(app, |state| {
798            if expanded {
799                state.expanded.remove(id);
800            } else {
801                state.expanded.insert(id.to_owned());
802            }
803        });
804        if previous_indicator.is_some() {
805            self.animate_selection(app, previous_indicator);
806        }
807        if expanded && let Some(callback) = self.widget(app).collapsed.clone() {
808            self.after_frame(app, move |app| callback(app, args.clone()));
809        }
810    }
811}
812
813impl NavigationViewState {
814    /// Finds the visible selected indicator or its collapsed ancestor in control coordinates.
815    fn indicator_rect(
816        self: Handle<Self>,
817        app: &mut App,
818        selected: &str,
819    ) -> Option<NavigationIndicatorOwner> {
820        let all = self.all_items(app);
821        let (_, path) = all.iter().find(|(item, _)| item.id == selected)?;
822        let mut id = selected.to_owned();
823        for length in 2..path.len() {
824            let (parent, _) = all
825                .iter()
826                .find(|(_, candidate)| candidate.as_slice() == &path[..length])?;
827            if !app.get(self).expanded.contains(&parent.id) {
828                id = parent.id.clone();
829                break;
830            }
831        }
832        let key = app.get(self).containers.get(&id)?.indicator_key.clone();
833        let context = key.current_context(app)?;
834        let object = context.find_render_object(app)?.as_box()?;
835        let root = self.context(app).find_render_object(app)?.as_box()?;
836        let origin = object.local_to_global(app, Offset::ZERO, None)
837            - root.local_to_global(app, Offset::ZERO, None);
838        Some(NavigationIndicatorOwner {
839            id,
840            rect: origin & object.size(app),
841        })
842    }
843
844    /// Source CenterPoint's 200ms step outlives an interrupted Scale storyboard.
845    fn update_indicator_pivots(self: Handle<Self>, app: &mut App) {
846        let now = SchedulerBinding::current_frame_time_stamp(app);
847        for container in app.get(self).containers.values() {
848            if let Some((deadline, final_pivot)) = container.indicator_pivot_step.get()
849                && now >= deadline
850            {
851                container.indicator_pivot_x.set(final_pivot);
852                container.indicator_pivot_step.set(None);
853            }
854        }
855    }
856
857    /// PlayIndicatorAnimations replaces CenterPoint.X only for same-level top navigation.
858    fn schedule_indicator_pivots(self: Handle<Self>, app: &mut App) {
859        let now = SchedulerBinding::current_frame_time_stamp(app);
860        let Some((from, to, true)) = app.get(self).indicator_transition.as_ref() else {
861            return;
862        };
863        if from.rect.top != to.rect.top {
864            return;
865        }
866        let increasing = from.rect.left < to.rect.left;
867        for owner in [from, to] {
868            if let Some(container) = app.get(self).containers.get(&owner.id) {
869                container
870                    .indicator_pivot_x
871                    .set(if increasing { 0.0 } else { owner.rect.width() });
872                container.indicator_pivot_step.set(Some((
873                    now + Duration::from_millis(200),
874                    if increasing { owner.rect.width() } else { 0.0 },
875                )));
876            }
877        }
878    }
879
880    /// Measures the destination after layout, then runs the source compositor tracks natively.
881    fn animate_selection(
882        self: Handle<Self>,
883        app: &mut App,
884        from: Option<NavigationIndicatorOwner>,
885    ) {
886        let selected = app.get(self).selected.clone();
887        let next = selected
888            .as_ref()
889            .and_then(|id| self.indicator_rect(app, id));
890        if app
891            .get(self)
892            .indicator_transition
893            .as_ref()
894            .is_some_and(|(_, to, _)| next.as_ref().is_some_and(|next| next.id == to.id))
895        {
896            return;
897        }
898        app.get_mut(self).indicator_epoch += 1;
899        app.get_mut(self).indicator_transition = None;
900        let from = from.filter(|owner| owner.rect.width() > 0.0 && owner.rect.height() > 0.0);
901        app.get_mut(self).pending_indicator = from.clone();
902        let epoch = app.get(self).indicator_epoch;
903        let Some(from) = from else {
904            return;
905        };
906        self.after_frame(app, move |app| {
907            if app.get(self).indicator_epoch != epoch {
908                return;
909            }
910            let selected = app.get(self).selected.clone();
911            let to = selected
912                .as_ref()
913                .and_then(|id| self.indicator_rect(app, id));
914            let top = self.widget(app).pane_display_mode == NavigationViewPaneDisplayMode::Top;
915            self.set_state(app, |state| {
916                state.pending_indicator = None;
917                state.indicator_transition = to
918                    .filter(|to| {
919                        from.id != to.id && to.rect.width() > 0.0 && to.rect.height() > 0.0
920                    })
921                    .map(|to| (from.clone(), to, top));
922            });
923            if app.get(self).indicator_transition.is_some() {
924                self.schedule_indicator_pivots(app);
925                let controller = app.get(self).indicator_controller.handle().unwrap();
926                controller.set_value(app, 0.0);
927                controller.animate_to(app, 1.0, None, Curves::linear());
928            }
929        });
930    }
931
932    /// Focuses a logical item and scrolls its current visual container into view.
933    fn focus_item(self: Handle<Self>, app: &mut App, id: &str) {
934        let Some(container) = app.get(self).containers.get(id).cloned() else {
935            return;
936        };
937        container.focus.request_focus(app, None);
938        if let Some(context) = container.key.current_context(app) {
939            drop(Scrollable::ensure_visible(
940                app,
941                context,
942                0.0,
943                Duration::ZERO,
944                Curves::linear(),
945                ScrollPositionAlignmentPolicy::KeepVisibleAtStart,
946            ));
947            drop(Scrollable::ensure_visible(
948                app,
949                context,
950                1.0,
951                Duration::ZERO,
952                Curves::linear(),
953                ScrollPositionAlignmentPolicy::KeepVisibleAtEnd,
954            ));
955        }
956    }
957
958    /// Visible preorder excludes collapsed descendants, headers and separators.
959    fn focus_order(self: Handle<Self>, app: &App, current_id: &str) -> Vec<String> {
960        let all = self.all_items(app);
961        let Some((_, current_path)) = all.iter().find(|(item, _)| item.id == current_id) else {
962            return Vec::new();
963        };
964        let top = self.widget(app).pane_display_mode == NavigationViewPaneDisplayMode::Top;
965        let compact = !self.is_pane_open(app)
966            && app.get(self).display_mode != NavigationViewDisplayMode::Minimal;
967        let flyout_root = current_path.len() > 2 && (top || compact);
968        let prefix = if flyout_root {
969            &current_path[..2]
970        } else {
971            &current_path[..1]
972        };
973        let overflow = app.get(self).top.overflow_items();
974        let current_in_overflow =
975            top && current_path[0] == 0 && overflow.contains(&current_path[1]);
976        all.iter()
977            .filter(|(item, path)| {
978                if !item.is_enabled
979                    || !item.is_visible
980                    || item.kind != NavigationViewItemKind::Item
981                    || !path.starts_with(prefix)
982                    || path.len() <= prefix.len()
983                {
984                    return false;
985                }
986                if top && !flyout_root {
987                    if path.len() != 2 {
988                        return false;
989                    }
990                    if path[0] == 0 && overflow.contains(&path[1]) != current_in_overflow {
991                        return false;
992                    }
993                }
994                (2..path.len()).all(|length| {
995                    all.iter()
996                        .find(|(_, candidate)| candidate.as_slice() == &path[..length])
997                        .is_some_and(|(parent, _)| {
998                            parent.is_visible && app.get(self).expanded.contains(&parent.id)
999                        })
1000                })
1001            })
1002            .map(|(item, _)| item.id.clone())
1003            .collect()
1004    }
1005
1006    /// Source Home/End and hierarchical direction policy over the native focus tree.
1007    fn on_item_key(
1008        self: Handle<Self>,
1009        app: &mut App,
1010        id: &str,
1011        event: &KeyEvent,
1012        top: bool,
1013    ) -> KeyEventResult {
1014        if !matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_)) {
1015            return KeyEventResult::Ignored;
1016        }
1017        let key = event.logical_key();
1018        if HardwareKeyboard::instance(app).is_alt_pressed(app) {
1019            return KeyEventResult::Ignored;
1020        }
1021        let mut order = self.focus_order(app, id);
1022        if matches!(key, LogicalKeyboardKey::HOME | LogicalKeyboardKey::END) {
1023            let root_depth = order
1024                .iter()
1025                .filter_map(|id| self.index_path_from_item(app, id).map(|path| path.len()))
1026                .min()
1027                .unwrap_or(2);
1028            order.retain(|id| {
1029                self.index_path_from_item(app, id)
1030                    .is_some_and(|path| path.len() == root_depth)
1031            });
1032        }
1033        let current = order
1034            .iter()
1035            .position(|candidate| candidate == id)
1036            .unwrap_or(0);
1037        if order.is_empty() {
1038            return KeyEventResult::Ignored;
1039        }
1040        let rtl = Directionality::of(app, self.context(app)) == TextDirection::Rtl;
1041        let forward = if top {
1042            if rtl {
1043                LogicalKeyboardKey::ARROW_LEFT
1044            } else {
1045                LogicalKeyboardKey::ARROW_RIGHT
1046            }
1047        } else {
1048            LogicalKeyboardKey::ARROW_DOWN
1049        };
1050        let backward = if top {
1051            if rtl {
1052                LogicalKeyboardKey::ARROW_RIGHT
1053            } else {
1054                LogicalKeyboardKey::ARROW_LEFT
1055            }
1056        } else {
1057            LogicalKeyboardKey::ARROW_UP
1058        };
1059        let next = if key == LogicalKeyboardKey::HOME {
1060            Some(0)
1061        } else if key == LogicalKeyboardKey::END {
1062            order.len().checked_sub(1)
1063        } else if key == forward {
1064            (current + 1 < order.len()).then_some(current + 1)
1065        } else if key == backward {
1066            current.checked_sub(1)
1067        } else {
1068            None
1069        };
1070        if let Some(next) = next {
1071            self.focus_item(app, &order[next]);
1072            return KeyEventResult::Handled;
1073        }
1074        let expand_key = if rtl {
1075            LogicalKeyboardKey::ARROW_LEFT
1076        } else {
1077            LogicalKeyboardKey::ARROW_RIGHT
1078        };
1079        let collapse_key = if rtl {
1080            LogicalKeyboardKey::ARROW_RIGHT
1081        } else {
1082            LogicalKeyboardKey::ARROW_LEFT
1083        };
1084        if !top && key == expand_key {
1085            if let Some(args) = self.event_args(app, id, false)
1086                && (!args.item.menu_items.is_empty() || args.item.has_unrealized_children)
1087            {
1088                if !app.get(self).expanded.contains(id) {
1089                    self.toggle_expanded(app, id);
1090                } else if let Some(child) = args.item.menu_items.iter().find(|item| {
1091                    item.is_enabled && item.is_visible && item.kind == NavigationViewItemKind::Item
1092                }) {
1093                    self.focus_item(app, &child.id);
1094                }
1095                return KeyEventResult::Handled;
1096            }
1097        } else if !top && key == collapse_key {
1098            if app.get(self).expanded.contains(id) {
1099                self.toggle_expanded(app, id);
1100                return KeyEventResult::Handled;
1101            }
1102            if let Some(mut path) = self.index_path_from_item(app, id)
1103                && path.len() > 2
1104            {
1105                path.pop();
1106                if let Some((parent, _)) = self
1107                    .all_items(app)
1108                    .into_iter()
1109                    .find(|(_, candidate)| *candidate == path)
1110                {
1111                    self.focus_item(app, &parent.id);
1112                    return KeyEventResult::Handled;
1113                }
1114            }
1115        }
1116        KeyEventResult::Ignored
1117    }
1118
1119    /// Builds one keyed eager item and its inline or attached child repeater.
1120    fn item_widget(
1121        self: Handle<Self>,
1122        r: &ThemeResources,
1123        app: &mut App,
1124        item: NavigationViewItem,
1125        position: NavigationViewItemPosition,
1126        depth: usize,
1127        closed_compact: bool,
1128    ) -> WidgetRef {
1129        let id = item.id.clone();
1130        let container = app.get(self).containers[&id].clone();
1131        let expanded = app.get(self).expanded.contains(&id);
1132        let selected = app.get(self).selected.as_deref() == Some(&id);
1133        let child_selected = app.get(self).selected.as_ref().is_some_and(|selected| {
1134            let mut descendants = Vec::new();
1135            collect_items(&item.menu_items, &[], &mut descendants);
1136            descendants.iter().any(|(item, _)| &item.id == selected)
1137        });
1138        let top_primary = position == NavigationViewItemPosition::TopPrimary;
1139        let top = matches!(
1140            position,
1141            NavigationViewItemPosition::TopPrimary | NavigationViewItemPosition::TopFooter
1142        );
1143        let overflow = position == NavigationViewItemPosition::TopOverflow;
1144        let is_top_level_item = self
1145            .index_path_from_item(app, &id)
1146            .is_some_and(|path| path.len() == 2);
1147        let flyout_children = (closed_compact && is_top_level_item) || top_primary;
1148        let invoke_id = id.clone();
1149        let expand_id = id.clone();
1150        let focus_id = id.clone();
1151        let key_id = id.clone();
1152        let presenter = NavigationViewItemPresenter {
1153            item: item.clone(),
1154            position,
1155            is_selected: selected,
1156            is_child_selected: child_selected,
1157            is_expanded: expanded,
1158            is_closed_compact: closed_compact,
1159            is_top_level_item,
1160            depth,
1161            compact_pane_length: self.widget(app).compact_pane_length,
1162            focus_node: container.focus.clone(),
1163            is_keyboard_focused: false,
1164            indicator_key: container.indicator_key.clone(),
1165            indicator_controller: app.get(self).indicator_controller.clone().unwrap(),
1166            indicator_animation: app.get(self).indicator_transition.as_ref().and_then(
1167                |(from, to, top)| {
1168                    (item.id == from.id || item.id == to.id).then(|| {
1169                        NavigationIndicatorTransition {
1170                            from: from.rect,
1171                            to: to.rect,
1172                            top: *top,
1173                            outgoing: item.id == from.id,
1174                            pivot_x: container.indicator_pivot_x.clone(),
1175                        }
1176                    })
1177                },
1178            ),
1179            indicator_opacity: app
1180                .get(self)
1181                .pending_indicator
1182                .as_ref()
1183                .map(|from| if item.id == from.id { 1.0 } else { 0.0 }),
1184            on_invoked: Listener::new(move |app| self.invoke(app, &invoke_id, overflow)),
1185            on_expansion_toggled: Listener::new(move |app| self.toggle_expanded(app, &expand_id)),
1186        };
1187        let presenter = Focus::new(presenter)
1188            .can_request_focus(false)
1189            .skip_traversal(true)
1190            .on_key_event(Rc::new(move |app, _, event| {
1191                self.on_item_key(app, &key_id, event, top)
1192            }))
1193            .on_focus_change(move |app, focused| {
1194                if focused
1195                    && self.widget(app).selection_follows_focus
1196                        == NavigationViewSelectionFollowsFocus::Enabled
1197                    && app.get(self).selected.as_deref() != Some(&focus_id)
1198                    && self
1199                        .event_args(app, &focus_id, false)
1200                        .is_some_and(|args| args.item.selects_on_invoked)
1201                {
1202                    // Source excludes focus received inside an overflow flyout from selection-following.
1203                    if !overflow {
1204                        self.invoke(app, &focus_id, false);
1205                    }
1206                }
1207            })
1208            .into_widget();
1209        let presenter = if top {
1210            let measure_id = id.clone();
1211            SizeObserver::new(
1212                presenter,
1213                Rc::new(move |app, _, size| {
1214                    if !app.contains(self) || !self.mounted(app) {
1215                        return;
1216                    }
1217                    let index = self
1218                        .widget(app)
1219                        .menu_items
1220                        .iter()
1221                        .position(|item| item.id == measure_id);
1222                    if let Some(index) = index
1223                        && app
1224                            .get_mut(self)
1225                            .top
1226                            .set_width_for_item(index, size.width())
1227                    {
1228                        self.set_state(app, |_| {});
1229                    }
1230                }),
1231            )
1232            .into_widget()
1233        } else {
1234            presenter
1235        };
1236        let children: Vec<_> = item
1237            .menu_items
1238            .iter()
1239            .filter(|item| item.is_visible)
1240            .cloned()
1241            .map(|child| {
1242                self.item_widget(
1243                    r,
1244                    app,
1245                    child,
1246                    if top {
1247                        NavigationViewItemPosition::TopOverflow
1248                    } else {
1249                        position
1250                    },
1251                    if flyout_children { 0 } else { depth + 1 },
1252                    closed_compact,
1253                )
1254            })
1255            .collect();
1256        let child_column = Column::new()
1257            .main_axis_size(MainAxisSize::Min)
1258            .cross_axis_alignment(CrossAxisAlignment::Stretch)
1259            .children(children)
1260            .into_widget();
1261        // Vertical child repeaters measure naturally inside the unbounded horizontal top strip too.
1262        let child_column = if flyout_children || top {
1263            IntrinsicWidth::new().child(child_column).into_widget()
1264        } else {
1265            child_column
1266        };
1267        let result =
1268            if flyout_children && (!item.menu_items.is_empty() || item.has_unrealized_children) {
1269                let dismiss_id = id.clone();
1270                let popup = child_column.clone();
1271                let anchor = AnchoredFlyout::new(
1272                    expanded,
1273                    presenter,
1274                    popup,
1275                    Listener::new(move |app| {
1276                        if app.get(self).expanded.contains(&dismiss_id) {
1277                            self.toggle_expanded(app, &dismiss_id);
1278                        }
1279                    }),
1280                )
1281                .placement(if top {
1282                    AnchoredFlyoutPlacement::BottomEdgeAlignedLeft
1283                } else {
1284                    AnchoredFlyoutPlacement::RightEdgeAlignedTop
1285                })
1286                .padding(r.navigation_view_item_children_menu_flyout_padding)
1287                .offset(if top {
1288                    Offset::ZERO
1289                } else {
1290                    Offset::new(0.0, -4.0)
1291                });
1292                Column::new()
1293                    .main_axis_size(MainAxisSize::Min)
1294                    .cross_axis_alignment(if top {
1295                        CrossAxisAlignment::Start
1296                    } else {
1297                        CrossAxisAlignment::Stretch
1298                    })
1299                    .children([
1300                        anchor.into_widget(),
1301                        Offstage::new()
1302                            .offstage(true)
1303                            .child(if expanded {
1304                                SizedBox::shrink().into_widget()
1305                            } else {
1306                                child_column
1307                            })
1308                            .into_widget(),
1309                    ])
1310                    .into_widget()
1311            } else {
1312                Column::new()
1313                    .main_axis_size(MainAxisSize::Min)
1314                    .cross_axis_alignment(if top {
1315                        CrossAxisAlignment::Start
1316                    } else {
1317                        CrossAxisAlignment::Stretch
1318                    })
1319                    .children([
1320                        presenter,
1321                        Offstage::new()
1322                            .offstage(!expanded)
1323                            .child(
1324                                Focus::new(child_column)
1325                                    .can_request_focus(false)
1326                                    .descendants_are_focusable(expanded),
1327                            )
1328                            .into_widget(),
1329                    ])
1330                    .into_widget()
1331            };
1332        KeyedSubtree::new(result)
1333            .key(container.key.into())
1334            .into_widget()
1335    }
1336
1337    /// Measures a group's natural height without replacing its source-owned scroll controller.
1338    fn measured_group(self: Handle<Self>, children: Vec<WidgetRef>, group: usize) -> WidgetRef {
1339        SizeObserver::new(
1340            Column::new()
1341                .main_axis_size(MainAxisSize::Min)
1342                .cross_axis_alignment(CrossAxisAlignment::Stretch)
1343                .children(children),
1344            Rc::new(move |app, _, size| {
1345                if app.contains(self)
1346                    && self.mounted(app)
1347                    && app.get(self).group_heights[group] != size.height()
1348                {
1349                    self.set_state(app, |state| state.group_heights[group] = size.height());
1350                }
1351            }),
1352        )
1353        .into_widget()
1354    }
1355
1356    /// Main/footer scroll allocation from UpdatePaneLayout, preserving the smaller group.
1357    fn pane_items(self: Handle<Self>, app: &mut App, closed_compact: bool) -> WidgetRef {
1358        let r = ThemeResources::of(app, self.context(app));
1359        let main_items = self.widget(app).menu_items.clone();
1360        let footer_items = self.footer_items(app);
1361        let main = main_items
1362            .into_iter()
1363            .filter(|item| item.is_visible)
1364            .map(|item| {
1365                self.item_widget(
1366                    &r,
1367                    app,
1368                    item,
1369                    NavigationViewItemPosition::Left,
1370                    0,
1371                    closed_compact,
1372                )
1373            })
1374            .collect();
1375        let footer = footer_items
1376            .into_iter()
1377            .filter(|item| item.is_visible)
1378            .map(|item| {
1379                self.item_widget(
1380                    &r,
1381                    app,
1382                    item,
1383                    NavigationViewItemPosition::Left,
1384                    0,
1385                    closed_compact,
1386                )
1387            })
1388            .collect();
1389        let main = self.measured_group(main, 0);
1390        let footer = self.measured_group(footer, 1);
1391        let custom = self
1392            .widget(app)
1393            .pane_footer
1394            .clone()
1395            .map(|child| self.slot(app, "footer", child))
1396            .unwrap_or_else(|| SizedBox::shrink().into_widget());
1397        let custom = self.measured_group(vec![custom], 2);
1398        LayoutBuilder::new(move |app, context, constraints| {
1399            let height = constraints.max_height;
1400            let [main_height, footer_height, custom_height] = app.get(self).group_heights;
1401            let footer_group = footer_height + custom_height;
1402            let main_space = if footer_height == 0.0 {
1403                (height - custom_height).max(0.0)
1404            } else if main_height == 0.0 {
1405                0.0
1406            } else if main_height + footer_group <= height {
1407                height - footer_group
1408            } else if main_height <= height / 2.0 {
1409                main_height
1410            } else if footer_group <= height / 2.0 {
1411                height - footer_group
1412            } else {
1413                height / 2.0
1414            };
1415            let separator =
1416                main_height > 0.0 && footer_height > 0.0 && main_height + footer_group > height;
1417            let theme = ThemeResources::of(app, context);
1418            let line_height = if separator { 3.0 } else { 0.0 };
1419            let main_space = main_space.min((height - line_height).max(0.0));
1420            let footer_space = (height - main_space - custom_height - line_height).max(0.0);
1421            let scrolls = app.get(self).scrolls.clone();
1422            Column::new()
1423                .cross_axis_alignment(CrossAxisAlignment::Stretch)
1424                .children([
1425                    SizedBox::new()
1426                        .height(main_space)
1427                        .child(ScrollBarViewport::new(scrolls[0].clone(), main.clone()))
1428                        .into_widget(),
1429                    SizedBox::new()
1430                        .height(line_height)
1431                        .child(Align::new().alignment(Alignment::TOP_CENTER.into()).child(
1432                            SizedBox::new().height(1.0).child(ColoredBox::new(
1433                                theme.navigation_view_item_separator_foreground,
1434                            )),
1435                        ))
1436                        .into_widget(),
1437                    ConstrainedBox::new(BoxConstraints::new().max_height(height))
1438                        .child(custom.clone())
1439                        .into_widget(),
1440                    SizedBox::new()
1441                        .height(footer_space)
1442                        .child(ScrollBarViewport::new(scrolls[1].clone(), footer.clone()))
1443                        .into_widget(),
1444                ])
1445                .into_widget()
1446        })
1447        .into_widget()
1448    }
1449}
1450
1451impl NavigationViewState {
1452    /// Builds the source toggle/back/overflow button template with its discrete states.
1453    fn icon_button(
1454        self: Handle<Self>,
1455        icon: FluentSymbol,
1456        callback: Listener,
1457        enabled: bool,
1458        tooltip: &str,
1459        focus_margin: [f64; 4],
1460    ) -> WidgetRef {
1461        ToolTipService::new(
1462            Button::new(
1463                FontIcon::symbol(icon)
1464                    .font_size(16.0)
1465                    .mirrored_when_right_to_left(true),
1466                callback,
1467            )
1468            .is_enabled(enabled)
1469            .template(move |app, context, states, content| {
1470                navigation_button_template(app, context, states, content, focus_margin)
1471            }),
1472            ToolTip::text(tooltip),
1473        )
1474        .into_widget()
1475    }
1476
1477    /// Keeps the native search editor mounted while a compact pane shows its search button.
1478    fn search_presenter(
1479        self: Handle<Self>,
1480        r: &ThemeResources,
1481        app: &mut App,
1482        top: bool,
1483        compact: bool,
1484    ) -> WidgetRef {
1485        let Some(child) = self.widget(app).auto_suggest_box.clone() else {
1486            return SizedBox::shrink().into_widget();
1487        };
1488        let scope = app.get(self).search_focus.clone().unwrap();
1489        let editor = FocusScope::new(self.slot(app, "search", child))
1490            .node(scope.clone())
1491            .descendants_are_focusable(!compact);
1492        let padding = if top {
1493            r.top_navigation_view_auto_suggest_box_margin
1494        } else {
1495            r.navigation_view_auto_suggest_box_margin
1496        };
1497        let editor = Padding::new(EdgeInsetsGeometry::only(
1498            padding[0], padding[1], padding[2], padding[3],
1499        ))
1500        .child(
1501            ConstrainedBox::new(
1502                BoxConstraints::new()
1503                    .min_height(r.navigation_view_auto_suggest_area_height)
1504                    .min_width(if top { 216.0 } else { 0.0 }),
1505            )
1506            .child(editor),
1507        );
1508        if compact {
1509            let button = self.icon_button(
1510                FluentSymbol::Search,
1511                Listener::new(move |app| {
1512                    self.set_pane_open(app, true, true);
1513                    let scope = scope.clone();
1514                    self.after_frame(app, move |app| {
1515                        if let Some(node) =
1516                            scope.as_node().traversal_descendants(app).first().copied()
1517                        {
1518                            node.request_focus(app, None);
1519                        }
1520                    });
1521                }),
1522                true,
1523                "Search",
1524                [-4.0, 0.0, -4.0, 0.0],
1525            );
1526            Column::new()
1527                .main_axis_size(MainAxisSize::Min)
1528                .children([
1529                    button,
1530                    Offstage::new().offstage(true).child(editor).into_widget(),
1531                ])
1532                .into_widget()
1533        } else {
1534            Padding::new(EdgeInsetsGeometry::only(
1535                0.0,
1536                0.0,
1537                0.0,
1538                if top { 0.0 } else { 8.0 },
1539            ))
1540            .child(editor)
1541            .into_widget()
1542        }
1543    }
1544
1545    /// The page HeaderContent and ContentPresenter preserve owner state across pane layouts.
1546    fn page_content(
1547        self: Handle<Self>,
1548        app: &mut App,
1549        context: BuildContext,
1550        top: bool,
1551        bars: EdgeInsets,
1552    ) -> WidgetRef {
1553        let widget = self.widget(app).clone();
1554        let resources = ThemeResources::of(app, context);
1555        let r = &resources;
1556        let minimal = app.get(self).display_mode == NavigationViewDisplayMode::Minimal;
1557        let (border, corners) = if top {
1558            (
1559                r.top_navigation_view_content_grid_border_thickness,
1560                r.top_navigation_view_content_grid_corner_radius,
1561            )
1562        } else if minimal {
1563            (
1564                r.navigation_view_minimal_content_grid_border_thickness,
1565                r.navigation_view_minimal_content_grid_corner_radius,
1566            )
1567        } else {
1568            (
1569                r.navigation_view_content_grid_border_thickness,
1570                r.navigation_view_content_grid_corner_radius,
1571            )
1572        };
1573        let chrome = PaneChrome::resolve(
1574            &resources,
1575            &widget,
1576            app.get(self).display_mode,
1577            self.is_pane_open(app),
1578            app.get(self).width,
1579        );
1580        let mut children = vec![
1581            GridCell::new(SizedBox::new().width(chrome.content_left_padding))
1582                .row(1)
1583                .into_widget(),
1584        ];
1585        if let Some(header) = widget
1586            .header
1587            .clone()
1588            .filter(|_| widget.always_show_header || (minimal && !top))
1589        {
1590            let margin = if minimal && !top {
1591                r.navigation_view_minimal_header_margin
1592            } else {
1593                r.navigation_view_header_margin
1594            };
1595            children.push(
1596                GridCell::new(Margin::new(
1597                    margin,
1598                    ConstrainedBox::new(
1599                        BoxConstraints::new().min_height(r.pane_toggle_button_height),
1600                    )
1601                    .child(DefaultTextStyle::new(
1602                        control_text_style(
1603                            &resources,
1604                            28.0,
1605                            FontWeight::W600,
1606                            resources.text_fill_color_primary,
1607                        ),
1608                        self.slot(app, "header", header),
1609                    )),
1610                ))
1611                .row(1)
1612                .column(1)
1613                .into_widget(),
1614            );
1615        }
1616        children.push(
1617            GridCell::new(Margin::new(
1618                r.navigation_view_content_presenter_margin,
1619                self.slot(app, "content", widget.content),
1620            ))
1621            .row(2)
1622            .column_span(2)
1623            .into_widget(),
1624        );
1625        Grid::new()
1626            .background(Brush::Solid(r.navigation_view_content_background))
1627            .border_brush(Brush::Solid(r.navigation_view_content_grid_border_brush))
1628            .border_thickness_ltrb(border)
1629            .corner_radius_corners(corners)
1630            .padding([bars.left, bars.top, bars.right, bars.bottom])
1631            .column_definitions([
1632                ColumnDefinition::new(GridLength::AUTO),
1633                ColumnDefinition::new(GridLength::STAR),
1634            ])
1635            .row_definitions([
1636                RowDefinition::new(GridLength::AUTO),
1637                RowDefinition::new(GridLength::AUTO),
1638                RowDefinition::new(GridLength::STAR),
1639            ])
1640            .children(children)
1641            .into_widget()
1642    }
1643
1644    /// `UpdateTitleBarPadding`'s padding, widened from the title bar to every side the system's
1645    /// bars cover: the `MediaQuery`'s `padding` a `FluentPage` extending its content into the bars
1646    /// leaves, while `IsTitleBarAutoPaddingEnabled`. A page that pads for the bars itself removes
1647    /// that padding, and the navigation keeps clear of nothing more, as WinUI's adds no title-bar
1648    /// padding to a navigation not at the window's top.
1649    fn system_bars(self: Handle<Self>, app: &mut App, context: BuildContext) -> EdgeInsets {
1650        if self.widget(app).is_title_bar_auto_padding_enabled {
1651            MediaQuery::padding_of(app, context)
1652        } else {
1653            EdgeInsets::ZERO
1654        }
1655    }
1656
1657    /// PaneContentGrid reserves the toggle row before custom content and item groups.
1658    fn left_pane(self: Handle<Self>, app: &mut App) -> WidgetRef {
1659        let r = ThemeResources::of(app, self.context(app));
1660        let widget = self.widget(app).clone();
1661        let chrome = PaneChrome::resolve(
1662            &r,
1663            &widget,
1664            app.get(self).display_mode,
1665            self.is_pane_open(app),
1666            app.get(self).width,
1667        );
1668        let compact = chrome.closed_compact;
1669        let header = widget
1670            .pane_header
1671            .clone()
1672            .map(|child| self.slot(app, "pane_header", child))
1673            .unwrap_or_else(|| SizedBox::shrink().into_widget());
1674        // PaneHeaderContentBorder is independent of PaneTitleTextBlock and collapses in ListSizeCompact.
1675        let header = Grid::new()
1676            .row_definitions([
1677                RowDefinition::new(GridLength::AUTO).min_height(chrome.header_row_min_height)
1678            ])
1679            .column_definitions([
1680                ColumnDefinition::new(GridLength::pixel(chrome.header_close_width)),
1681                ColumnDefinition::new(GridLength::pixel(chrome.header_toggle_width)),
1682                ColumnDefinition::new(GridLength::STAR),
1683            ])
1684            .children([GridCell::new(
1685                Offstage::new()
1686                    .offstage(compact)
1687                    .child(Focus::new(header).descendants_are_focusable(!compact)),
1688            )
1689            .column(2)
1690            .into_widget()]);
1691        let custom = widget
1692            .pane_custom_content
1693            .map(|child| self.slot(app, "custom", child))
1694            .unwrap_or_else(|| SizedBox::shrink().into_widget());
1695        let search = self.search_presenter(&r, app, false, compact);
1696        let items = self.pane_items(app, compact);
1697        // PaneContentGrid follows the template's padding, Back, toggle, search, custom and item rows.
1698        let pane = Grid::new()
1699            .row_definitions([
1700                RowDefinition::new(GridLength::AUTO),
1701                RowDefinition::new(GridLength::pixel(chrome.back_row)),
1702                RowDefinition::new(GridLength::AUTO).min_height(chrome.toggle_row_min_height),
1703                RowDefinition::new(GridLength::AUTO),
1704                RowDefinition::new(GridLength::AUTO),
1705                RowDefinition::new(GridLength::pixel(0.0)),
1706                RowDefinition::new(GridLength::STAR),
1707            ])
1708            .children([
1709                GridCell::new(header).row(2).into_widget(),
1710                GridCell::new(search).row(3).into_widget(),
1711                GridCell::new(custom).row(4).into_widget(),
1712                GridCell::new(items).row(6).into_widget(),
1713            ])
1714            .into_widget();
1715        // ListSizeCompact sizes PaneContentGrid itself; SplitView's outer clip is not its layout width.
1716        let mut pane = SizedBox::new().child(pane);
1717        if compact {
1718            pane = pane.width(widget.compact_pane_length);
1719        }
1720        Align::new()
1721            .alignment(Alignment::TOP_LEFT.into())
1722            .child(pane)
1723            .into_widget()
1724    }
1725
1726    /// RootSplitView maps Expanded/Compact/Minimal to the three source SplitView modes.
1727    fn left_template(
1728        self: Handle<Self>,
1729        app: &mut App,
1730        context: BuildContext,
1731        bars: EdgeInsets,
1732    ) -> WidgetRef {
1733        let widget = self.widget(app).clone();
1734        let resources = ThemeResources::of(app, context);
1735        let r = &resources;
1736        let open = self.is_pane_open(app) && widget.is_pane_visible;
1737        let mode = app.get(self).display_mode;
1738        let chrome = PaneChrome::resolve(&resources, &widget, mode, open, app.get(self).width);
1739        let pane = self.left_pane(app);
1740        // The rail and the open pane grow by the bar at their side; content beside no rail keeps
1741        // clear of it itself.
1742        let rail = widget.is_pane_visible && mode != NavigationViewDisplayMode::Minimal;
1743        let content_bars = EdgeInsets::from_ltrb(
1744            if rail { 0.0 } else { bars.left },
1745            bars.top,
1746            bars.right,
1747            bars.bottom,
1748        );
1749        let content = self.page_content(app, context, false, content_bars);
1750        let mut split = SplitView::new(open, move |app, open| self.set_pane_open(app, open, false))
1751            .display_mode(if !widget.is_pane_visible {
1752                SplitViewDisplayMode::CompactOverlay
1753            } else {
1754                match mode {
1755                    NavigationViewDisplayMode::Expanded => SplitViewDisplayMode::CompactInline,
1756                    NavigationViewDisplayMode::Compact => SplitViewDisplayMode::CompactOverlay,
1757                    NavigationViewDisplayMode::Minimal => SplitViewDisplayMode::Overlay,
1758                }
1759            })
1760            .compact_pane_length(if widget.is_pane_visible {
1761                widget.compact_pane_length + bars.left
1762            } else {
1763                0.0
1764            })
1765            .open_pane_length(widget.open_pane_length.min(app.get(self).width).max(0.0) + bars.left)
1766            .pane_background(if mode == NavigationViewDisplayMode::Expanded {
1767                Brush::Solid(r.navigation_view_expanded_pane_background)
1768            } else {
1769                Brush::Acrylic(r.navigation_view_default_pane_background)
1770            })
1771            .border_brush(Brush::Solid(
1772                if mode == NavigationViewDisplayMode::Expanded {
1773                    Color::new(0)
1774                } else {
1775                    r.navigation_view_item_separator_foreground
1776                },
1777            ))
1778            .border_thickness_ltrb(r.navigation_view_border_thickness)
1779            .corner_radius_corners([
1780                0.0,
1781                r.overlay_corner_radius[1],
1782                r.overlay_corner_radius[2],
1783                0.0,
1784            ])
1785            .pane(
1786                Padding::new(EdgeInsetsGeometry::from_ltrb(
1787                    bars.left,
1788                    bars.top,
1789                    0.0,
1790                    bars.bottom,
1791                ))
1792                .child(Margin::new(
1793                    r.navigation_view_pane_content_grid_margin,
1794                    pane,
1795                )),
1796            )
1797            .content(content);
1798        if let Some(callback) = widget.pane_opening {
1799            split = split.pane_opening(callback);
1800        }
1801        if let Some(callback) = widget.pane_opened {
1802            split = split.pane_opened(callback);
1803        }
1804        if let Some(callback) = widget.pane_closed {
1805            split = split.pane_closed(callback);
1806        }
1807        // SplitView's cancelable light-dismiss request is forwarded before its value callback.
1808        split = split.pane_closing(move |app, args| {
1809            if std::mem::take(&mut app.get_mut(self).block_next_closing) {
1810                return;
1811            }
1812            if let Some(callback) = self.widget(app).pane_closing.clone() {
1813                callback(app, args);
1814            }
1815        });
1816        let mut children = vec![split.into_widget()];
1817        if widget.is_pane_visible && (chrome.show_back || chrome.show_close) {
1818            let close = chrome.show_close;
1819            let callback = if close {
1820                Listener::new(move |app| self.set_pane_open(app, false, true))
1821            } else {
1822                widget
1823                    .back_requested
1824                    .clone()
1825                    .unwrap_or_else(|| Listener::new(|_| {}))
1826            };
1827            let back_width = if close {
1828                r.navigation_back_button_width
1829            } else {
1830                chrome.back_width
1831            };
1832            let small = chrome.overlay && !close;
1833            let button = Button::new(
1834                FontIcon::symbol(FluentSymbol::Back)
1835                    .font_size(16.0)
1836                    .mirrored_when_right_to_left(true),
1837                callback,
1838            )
1839            .key(
1840                waft_foundation::ValueKey::new(if close {
1841                    "NavigationViewCloseButton"
1842                } else {
1843                    "NavigationViewBackButton"
1844                })
1845                .into(),
1846            )
1847            .is_enabled(close || widget.is_back_enabled)
1848            .template(move |app, context, states, child| {
1849                back_button_template(app, context, states, child, back_width, small)
1850            });
1851            children.push(
1852                Positioned::new(ToolTipService::new(
1853                    button,
1854                    ToolTip::text(if close { "Close navigation" } else { "Back" }),
1855                ))
1856                .left(bars.left)
1857                .top(4.0 + bars.top)
1858                .into_widget(),
1859            );
1860        }
1861        if chrome.show_toggle {
1862            let icon_width = (widget.compact_pane_length - 8.0).max(0.0);
1863            let title = Offstage::new()
1864                .offstage(chrome.closed_compact)
1865                .child(pane_title(&resources, widget.pane_title.clone()));
1866            let button = Button::new(
1867                title,
1868                Listener::new(move |app| self.set_pane_open(app, !self.is_pane_open(app), true)),
1869            )
1870            .key(waft_foundation::ValueKey::new("TogglePaneButton").into())
1871            .template(move |app, context, states, child| {
1872                pane_toggle_template(app, context, states, child, icon_width)
1873            });
1874            children.push(
1875                Positioned::new(SizedBox::new().width(chrome.toggle_width).child(
1876                    ToolTipService::new(
1877                        button,
1878                        ToolTip::text(if open {
1879                            "Close navigation"
1880                        } else {
1881                            "Open navigation"
1882                        }),
1883                    ),
1884                ))
1885                .left(chrome.toggle_left + bars.left)
1886                .top(4.0 + chrome.toggle_top + bars.top)
1887                .into_widget(),
1888            );
1889        } else if chrome.show_title_holder && widget.is_pane_visible {
1890            children.push(
1891                Positioned::new(
1892                    SizedBox::new()
1893                        .height(r.navigation_view_pane_header_row_min_height)
1894                        // The holder shows only in TogglePaneButtonVisible, whose setter
1895                        // replaces NavigationViewPaneTitlePresenterMargin.
1896                        .child(Margin::new(
1897                            r.navigation_view_item_inner_header_margin,
1898                            Offstage::new()
1899                                .offstage(chrome.closed_compact)
1900                                .child(pane_title(&resources, widget.pane_title.clone())),
1901                        )),
1902                )
1903                .left(chrome.toggle_left + bars.left)
1904                .top(4.0 + chrome.toggle_top + bars.top)
1905                .into_widget(),
1906            );
1907        }
1908        Stack::new()
1909            .fit(StackFit::Expand)
1910            .children(children)
1911            .into_widget()
1912    }
1913
1914    /// Measures top chrome independently of the star column's allocated width.
1915    fn top_chrome(
1916        self: Handle<Self>,
1917        r: &ThemeResources,
1918        child: WidgetRef,
1919        slot: usize,
1920    ) -> WidgetRef {
1921        let custom_content_min_width = r.top_navigation_view_pane_custom_content_min_width;
1922        SizeObserver::new(
1923            child,
1924            Rc::new(move |app, _, size| {
1925                if app.contains(self)
1926                    && self.mounted(app)
1927                    && app.get(self).top_chrome_sizes[slot] != size.width()
1928                {
1929                    self.set_state(app, |state| {
1930                        state.top_chrome_sizes[slot] = size.width();
1931                        state.top_chrome_width = state.top_chrome_sizes[0]
1932                            + state.top_chrome_sizes[1]
1933                            + state.top_chrome_sizes[2].max(custom_content_min_width)
1934                            + 8.0;
1935                    });
1936                }
1937            }),
1938        )
1939        .into_widget()
1940    }
1941
1942    /// TopNavGrid projects original indices without turning overflow into horizontal scrolling.
1943    fn top_template(
1944        self: Handle<Self>,
1945        app: &mut App,
1946        context: BuildContext,
1947        bars: EdgeInsets,
1948    ) -> WidgetRef {
1949        let widget = self.widget(app).clone();
1950        let resources = ThemeResources::of(app, context);
1951        let r = &resources;
1952        let selected = app
1953            .get(self)
1954            .selected
1955            .as_ref()
1956            .and_then(|id| self.index_path_from_item(app, id))
1957            .filter(|path| path[0] == 0)
1958            .map(|path| path[1]);
1959        let available = (app.get(self).width - app.get(self).top_chrome_width).max(0.0);
1960        app.get_mut(self).top.overflow_button_width = r.top_navigation_view_overflow_button_width;
1961        if app.get(self).top_measure_pending {
1962            self.after_frame(app, move |app| {
1963                let ids: Vec<_> = self
1964                    .widget(app)
1965                    .menu_items
1966                    .iter()
1967                    .map(|item| item.id.clone())
1968                    .collect();
1969                for (index, id) in ids.iter().enumerate() {
1970                    if !self.widget(app).menu_items[index].is_visible {
1971                        app.get_mut(self).top.set_width_for_item(index, 0.0);
1972                        continue;
1973                    }
1974                    if let Some(context) = self.container_from_menu_item(app, id)
1975                        && let Some(object) = context
1976                            .find_render_object(app)
1977                            .and_then(|object| object.as_box())
1978                    {
1979                        let width = object.size(app).width();
1980                        app.get_mut(self).top.set_width_for_item(index, width);
1981                    }
1982                }
1983                self.set_state(app, |state| state.top_measure_pending = false);
1984            });
1985        } else {
1986            app.get_mut(self).top.arrange(available, selected);
1987        }
1988        let primary_indices = app.get(self).top.primary_items();
1989        let overflow_indices = app.get(self).top.overflow_items();
1990        let overflow_open = app.get(self).overflow_open && !overflow_indices.is_empty();
1991        let primary: Vec<_> = primary_indices
1992            .into_iter()
1993            .filter(|index| widget.menu_items[*index].is_visible)
1994            .map(|index| {
1995                self.item_widget(
1996                    &resources,
1997                    app,
1998                    widget.menu_items[index].clone(),
1999                    NavigationViewItemPosition::TopPrimary,
2000                    0,
2001                    false,
2002                )
2003            })
2004            .collect();
2005        let overflow: Vec<_> = overflow_indices
2006            .iter()
2007            .filter(|index| widget.menu_items[**index].is_visible)
2008            .map(|index| {
2009                self.item_widget(
2010                    &resources,
2011                    app,
2012                    widget.menu_items[*index].clone(),
2013                    if overflow_open {
2014                        NavigationViewItemPosition::TopOverflow
2015                    } else {
2016                        NavigationViewItemPosition::TopPrimary
2017                    },
2018                    0,
2019                    false,
2020                )
2021            })
2022            .collect();
2023        let primary = ClipRect::new().child(
2024            Row::new()
2025                .main_axis_size(MainAxisSize::Min)
2026                .children(primary),
2027        );
2028        let has_overflow = !overflow_indices.is_empty();
2029        let overflow_button = self.icon_button(
2030            FluentSymbol::More,
2031            Listener::new(move |app| {
2032                self.set_state(app, |state| state.overflow_open = !state.overflow_open)
2033            }),
2034            true,
2035            "More",
2036            [0.0; 4],
2037        );
2038        let popup = IntrinsicWidth::new().child(
2039            Column::new()
2040                .main_axis_size(MainAxisSize::Min)
2041                .cross_axis_alignment(CrossAxisAlignment::Stretch)
2042                .children(if overflow_open {
2043                    overflow.clone()
2044                } else {
2045                    Vec::new()
2046                }),
2047        );
2048        let overflow_button = AnchoredFlyout::new(
2049            overflow_open,
2050            overflow_button,
2051            popup,
2052            Listener::new(move |app| self.set_state(app, |state| state.overflow_open = false)),
2053        )
2054        .padding(r.top_navigation_view_overflow_menu_padding)
2055        .max_width(r.flyout_theme_max_width);
2056        let chrome = PaneChrome::resolve(
2057            &resources,
2058            &widget,
2059            app.get(self).display_mode,
2060            self.is_pane_open(app),
2061            app.get(self).width,
2062        );
2063        // PaneHeaderOnTopPane and PaneTitleOnTopPane share column 2 in the source template.
2064        let title_column = Stack::new().children([
2065            widget
2066                .pane_header
2067                .clone()
2068                .map(|child| self.slot(app, "pane_header", child))
2069                .unwrap_or_else(|| SizedBox::shrink().into_widget()),
2070            if chrome.show_top_title {
2071                Margin::new(
2072                    r.navigation_view_item_inner_header_margin,
2073                    pane_title(&resources, widget.pane_title.clone()),
2074                )
2075                .into_widget()
2076            } else {
2077                SizedBox::shrink().into_widget()
2078            },
2079        ]);
2080        let leading = Row::new()
2081            .main_axis_size(MainAxisSize::Min)
2082            .children([
2083                SizedBox::new()
2084                    .width(if chrome.show_back {
2085                        r.navigation_back_button_width
2086                    } else {
2087                        0.0
2088                    })
2089                    .into_widget(),
2090                title_column.into_widget(),
2091            ])
2092            .into_widget();
2093        let footer_items = self
2094            .footer_items(app)
2095            .into_iter()
2096            .filter(|item| item.is_visible)
2097            .map(|item| {
2098                self.item_widget(
2099                    &resources,
2100                    app,
2101                    item,
2102                    NavigationViewItemPosition::TopFooter,
2103                    0,
2104                    false,
2105                )
2106            })
2107            .collect::<Vec<_>>();
2108        let search = self.search_presenter(&resources, app, true, false);
2109        let trailing = Row::new()
2110            .main_axis_size(MainAxisSize::Min)
2111            .children([
2112                search,
2113                widget
2114                    .pane_footer
2115                    .clone()
2116                    .map(|child| self.slot(app, "footer", child))
2117                    .unwrap_or_else(|| SizedBox::shrink().into_widget()),
2118                Row::new()
2119                    .main_axis_size(MainAxisSize::Min)
2120                    .children(footer_items)
2121                    .into_widget(),
2122            ])
2123            .into_widget();
2124        let leading = self.top_chrome(&resources, leading, 0);
2125        let trailing = self.top_chrome(&resources, trailing, 1);
2126        let custom = widget
2127            .pane_custom_content
2128            .clone()
2129            .map(|child| self.slot(app, "custom", child))
2130            .unwrap_or_else(|| SizedBox::shrink().into_widget());
2131        let custom = Align::new()
2132            .alignment(Alignment::CENTER_LEFT.into())
2133            .child(self.top_chrome(&resources, custom, 2));
2134        let top_row = Grid::new()
2135            .column_definitions([
2136                ColumnDefinition::new(GridLength::AUTO),
2137                ColumnDefinition::new(GridLength::AUTO),
2138                ColumnDefinition::new(GridLength::AUTO),
2139                // WinUI measures TopNavGrid at infinite width before partitioning items.
2140                ColumnDefinition::new(if app.get(self).top_measure_pending {
2141                    GridLength::AUTO
2142                } else {
2143                    GridLength::STAR
2144                })
2145                .min_width(
2146                    app.get(self).top_chrome_sizes[2]
2147                        .max(r.top_navigation_view_pane_custom_content_min_width),
2148                ),
2149                ColumnDefinition::new(GridLength::AUTO),
2150            ])
2151            .children([
2152                GridCell::new(leading).into_widget(),
2153                GridCell::new(
2154                    ConstrainedBox::new(
2155                        BoxConstraints::new().max_width(
2156                            (available
2157                                - if has_overflow {
2158                                    r.top_navigation_view_overflow_button_width
2159                                } else {
2160                                    0.0
2161                                })
2162                            .max(0.0),
2163                        ),
2164                    )
2165                    .child(primary),
2166                )
2167                .column(1)
2168                .into_widget(),
2169                GridCell::new(if has_overflow {
2170                    overflow_button.into_widget()
2171                } else {
2172                    SizedBox::shrink().into_widget()
2173                })
2174                .column(2)
2175                .into_widget(),
2176                GridCell::new(custom).column(3).into_widget(),
2177                GridCell::new(trailing).column(4).into_widget(),
2178            ]);
2179        let top_row = Offstage::new().offstage(!widget.is_pane_visible).child(
2180            SizedBox::new()
2181                .height(r.navigation_view_top_pane_height)
2182                .child(Padding::new(EdgeInsetsGeometry::only(4.0, 0.0, 4.0, 0.0)).child(top_row)),
2183        );
2184        // The top pane's background reaches the view's top and sides; its items keep clear.
2185        let top_row = Padding::new(EdgeInsetsGeometry::from_ltrb(
2186            bars.left, bars.top, bars.right, 0.0,
2187        ))
2188        .child(top_row);
2189        let content = self.page_content(
2190            app,
2191            context,
2192            true,
2193            EdgeInsets::from_ltrb(bars.left, 0.0, bars.right, bars.bottom),
2194        );
2195        let overlay = widget
2196            .content_overlay
2197            .unwrap_or_else(|| SizedBox::shrink().into_widget());
2198        let rows = Grid::new()
2199            .row_definitions([
2200                RowDefinition::new(GridLength::AUTO),
2201                RowDefinition::new(GridLength::AUTO),
2202                RowDefinition::new(GridLength::star(1.0)),
2203            ])
2204            .children([
2205                GridCell::new(
2206                    ColoredBox::new(r.navigation_view_top_pane_background).child(top_row),
2207                )
2208                .into_widget(),
2209                GridCell::new(overlay).row(1).into_widget(),
2210                GridCell::new(content).row(2).into_widget(),
2211            ]);
2212        let mut children = vec![
2213            rows.into_widget(),
2214            Offstage::new()
2215                .offstage(true)
2216                .child(
2217                    Row::new()
2218                        .main_axis_size(MainAxisSize::Min)
2219                        .children(if overflow_open { Vec::new() } else { overflow }),
2220                )
2221                .into_widget(),
2222        ];
2223        if widget.is_pane_visible && chrome.show_back {
2224            let width = chrome.back_width;
2225            let button = Button::new(
2226                FontIcon::symbol(FluentSymbol::Back)
2227                    .font_size(16.0)
2228                    .mirrored_when_right_to_left(true),
2229                widget
2230                    .back_requested
2231                    .clone()
2232                    .unwrap_or_else(|| Listener::new(|_| {})),
2233            )
2234            .key(waft_foundation::ValueKey::new("NavigationViewBackButton").into())
2235            .is_enabled(widget.is_back_enabled)
2236            .template(move |app, context, states, child| {
2237                back_button_template(app, context, states, child, width, false)
2238            });
2239            children.push(
2240                Positioned::new(ToolTipService::new(button, ToolTip::text("Back")))
2241                    .left(bars.left)
2242                    .top(4.0 + bars.top)
2243                    .into_widget(),
2244            );
2245        }
2246        Stack::new()
2247            .fit(StackFit::Expand)
2248            .children(children)
2249            .into_widget()
2250    }
2251}
2252
2253impl State for NavigationViewState {
2254    type Widget = NavigationView;
2255    waft_widgets::state_accessors!();
2256
2257    fn init_state(self: Handle<Self>, app: &mut App) {
2258        let controller = AnimationController::new(
2259            app,
2260            Some(0.0),
2261            Some(NAVIGATION_INDICATOR_DURATION),
2262            None,
2263            0.0,
2264            1.0,
2265            AnimationBehavior::Normal,
2266            self,
2267        );
2268        app.get_mut(self).indicator_controller = Some(controller.clone());
2269        let handle = controller.handle();
2270        controller.add_listener(
2271            app,
2272            Listener::new(move |app| {
2273                self.update_indicator_pivots(app);
2274                if handle.value(app) >= 1.0 && app.get(self).indicator_transition.is_some() {
2275                    self.set_state(app, |state| state.indicator_transition = None);
2276                }
2277            }),
2278        );
2279        let scope = FocusScopeNode::new(app);
2280        app.get_mut(self).search_focus = Some(scope);
2281        for _ in 0..2 {
2282            let scroll = ScrollViewportController::new(app);
2283            app.get_mut(self).scrolls.push(scroll);
2284        }
2285        self.sync_items(app);
2286    }
2287
2288    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &NavigationView) {
2289        if old.pane_display_mode != self.widget(app).pane_display_mode {
2290            app.get_mut(self).was_force_closed = false;
2291        }
2292        if old.is_pane_open != self.widget(app).is_pane_open
2293            && let Some(open) = self.widget(app).is_pane_open
2294        {
2295            app.get_mut(self).was_force_closed = !open;
2296            if app.get(self).pane_open != open {
2297                app.get_mut(self).pane_open = open;
2298                self.apply_pane_expansion_memory(app, open);
2299            }
2300        }
2301        if old.is_pane_visible != self.widget(app).is_pane_visible {
2302            let open = self.widget(app).is_pane_visible
2303                && app.get(self).display_mode == NavigationViewDisplayMode::Expanded;
2304            self.after_frame(app, move |app| self.set_pane_open(app, open, false));
2305        }
2306        self.sync_items(app);
2307        if old.selected_item != self.widget(app).selected_item
2308            && app.get(self).selected != self.widget(app).selected_item
2309        {
2310            let previous = app
2311                .get(self)
2312                .selected
2313                .clone()
2314                .and_then(|id| self.indicator_rect(app, &id));
2315            app.get_mut(self).selected = self.widget(app).selected_item.clone();
2316            self.animate_selection(app, previous);
2317        }
2318        if app
2319            .get(self)
2320            .selected
2321            .as_ref()
2322            .is_some_and(|id| !self.all_items(app).iter().any(|(item, _)| &item.id == id))
2323        {
2324            app.get_mut(self).selected = None;
2325            app.get_mut(self).indicator_transition = None;
2326            app.get_mut(self).pending_indicator = None;
2327            app.get_mut(self).indicator_epoch += 1;
2328            let callback = self.widget(app).selection_changed.clone();
2329            self.after_frame(app, move |app| {
2330                callback(
2331                    app,
2332                    NavigationViewSelectionChangedEventArgs {
2333                        item: None,
2334                        index_path: Vec::new(),
2335                        is_settings: false,
2336                        recommended_transition_direction:
2337                            NavigationRecommendedTransitionDirection::Default,
2338                    },
2339                )
2340            });
2341        }
2342        if old.compact_mode_threshold_width != self.widget(app).compact_mode_threshold_width
2343            || old.expanded_mode_threshold_width != self.widget(app).expanded_mode_threshold_width
2344        {
2345            app.get_mut(self).width = f64::NAN;
2346        }
2347        if old
2348            .pane_custom_content
2349            .as_ref()
2350            .zip(self.widget(app).pane_custom_content.as_ref())
2351            .is_some_and(|(old, new)| !Rc::ptr_eq(old, new))
2352            || old.pane_custom_content.is_some() != self.widget(app).pane_custom_content.is_some()
2353            || old
2354                .menu_items
2355                .iter()
2356                .zip(&self.widget(app).menu_items)
2357                .any(|(old, new)| {
2358                    old.text != new.text
2359                        || old.has_content != new.has_content
2360                        || old.is_visible != new.is_visible
2361                        || old.icon.is_some() != new.icon.is_some()
2362                        || (old.text.is_none() && !Rc::ptr_eq(&old.content, &new.content))
2363                })
2364        {
2365            app.get_mut(self).top.invalidate_width_cache();
2366            app.get_mut(self).top_measure_pending = true;
2367        }
2368    }
2369
2370    fn activate(self: Handle<Self>, app: &mut App) {
2371        SingleTickerProviderStateMixin::activate(self, app);
2372    }
2373
2374    fn dispose(self: Handle<Self>, app: &mut App) {
2375        let controller = app.get_mut(self).indicator_controller.take().unwrap();
2376        controller.dispose(app);
2377        SingleTickerProviderStateMixin::dispose(self, app);
2378
2379        if let Some(scope) = app.get_mut(self).search_focus.take() {
2380            scope.as_node().dispose(app);
2381        }
2382        for scroll in std::mem::take(&mut app.get_mut(self).scrolls) {
2383            scroll.dispose(app);
2384        }
2385        for (_, container) in std::mem::take(&mut app.get_mut(self).containers) {
2386            container.focus.dispose(app);
2387        }
2388    }
2389
2390    fn build(self: Handle<Self>, _: &mut App, _: BuildContext) -> WidgetRef {
2391        let content = LayoutBuilder::new(move |app, context, constraints| {
2392            let bars = self.system_bars(app, context);
2393            self.update_adaptive_layout(app, constraints.max_width - bars.left - bars.right);
2394            let resources = ThemeResources::of(app, context);
2395            let child = if self.widget(app).pane_display_mode == NavigationViewPaneDisplayMode::Top
2396            {
2397                self.top_template(app, context, bars)
2398            } else {
2399                self.left_template(app, context, bars)
2400            };
2401            // What the navigation keeps clear of, its descendants need not. The `MediaQuery` is
2402            // there whether there are bars or not, so that bars arriving keep the tree below.
2403            let media = MediaQuery::of(app, context);
2404            let child = MediaQuery::new(
2405                if bars == EdgeInsets::ZERO {
2406                    media
2407                } else {
2408                    media.remove_padding(true, true, true, true)
2409                },
2410                child,
2411            )
2412            .into_widget();
2413            DefaultTextStyle::new(
2414                control_text_style(
2415                    &resources,
2416                    14.0,
2417                    FontWeight::NORMAL,
2418                    resources.text_fill_color_primary,
2419                ),
2420                child,
2421            )
2422            .into_widget()
2423        })
2424        .into_widget();
2425        Focus::new(content)
2426            .can_request_focus(false)
2427            .skip_traversal(true)
2428            .on_key_event(Rc::new(move |app, _, event| {
2429                if matches!(event, KeyEvent::Down(_))
2430                    && event.logical_key() == LogicalKeyboardKey::ARROW_LEFT
2431                    && HardwareKeyboard::instance(app).is_alt_pressed(app)
2432                    && self.is_pane_open(app)
2433                    && app.get(self).display_mode != NavigationViewDisplayMode::Expanded
2434                {
2435                    let mut args = SplitViewPaneClosingEventArgs::default();
2436                    if let Some(callback) = self.widget(app).pane_closing.clone() {
2437                        callback(app, &mut args);
2438                    }
2439                    if !args.cancel || app.get(self).was_force_closed {
2440                        app.get_mut(self).block_next_closing = true;
2441                        self.set_pane_open(app, false, false);
2442                        return KeyEventResult::Handled;
2443                    }
2444                }
2445                KeyEventResult::Ignored
2446            }))
2447            .into_widget()
2448    }
2449}
2450
2451/// RootGrid discrete button states shared by the navigation toggle and back styles.
2452fn navigation_button_template(
2453    app: &mut App,
2454    context: BuildContext,
2455    states: ControlStates,
2456    content: WidgetRef,
2457    focus_margin: [f64; 4],
2458) -> WidgetRef {
2459    let resources = ThemeResources::of(app, context);
2460    let r = &resources;
2461    let (background, foreground) = match states.common {
2462        CommonState::PointerOver => (
2463            r.navigation_view_button_background_pointer_over,
2464            r.navigation_view_button_foreground_pointer_over,
2465        ),
2466        CommonState::Pressed => (
2467            r.navigation_view_button_background_pressed,
2468            r.navigation_view_button_foreground_pressed,
2469        ),
2470        CommonState::Disabled => (Color::new(0), r.navigation_view_button_foreground_disabled),
2471        _ => (Color::new(0), r.navigation_view_item_foreground),
2472    };
2473    let content = Padding::new(EdgeInsetsGeometry::only(4.0, 2.0, 4.0, 2.0))
2474        .child(
2475            SizedBox::new()
2476                .width(r.pane_toggle_button_width)
2477                .height(r.pane_toggle_button_height)
2478                .child(
2479                    ControlBorder::new(Brush::Solid(background), Brush::Solid(Color::new(0)))
2480                        .corner_radius(r.control_corner_radius[0])
2481                        .child(Center::new().child(DefaultTextStyle::new(
2482                            control_text_style(&resources, 16.0, FontWeight::NORMAL, foreground),
2483                            content,
2484                        ))),
2485                ),
2486        )
2487        .into_widget();
2488    FocusVisual::new(content, resources.theme)
2489        .visible(states.focused)
2490        .margin(focus_margin)
2491        .corner_radius(r.control_corner_radius[0])
2492        .into_widget()
2493}
2494
2495impl NavigationView {
2496    /// Sets `pane_display_mode`.
2497    pub fn pane_display_mode(mut self, value: NavigationViewPaneDisplayMode) -> Self {
2498        self.pane_display_mode = value;
2499        self
2500    }
2501
2502    /// Sets `is_pane_visible`.
2503    pub fn is_pane_visible(mut self, value: bool) -> Self {
2504        self.is_pane_visible = value;
2505        self
2506    }
2507
2508    /// Sets `IsTitleBarAutoPaddingEnabled`.
2509    pub fn is_title_bar_auto_padding_enabled(mut self, value: bool) -> Self {
2510        self.is_title_bar_auto_padding_enabled = value;
2511        self
2512    }
2513
2514    /// Sets `is_pane_toggle_button_visible`.
2515    pub fn is_pane_toggle_button_visible(mut self, value: bool) -> Self {
2516        self.is_pane_toggle_button_visible = value;
2517        self
2518    }
2519
2520    /// Sets `is_settings_visible`.
2521    pub fn is_settings_visible(mut self, value: bool) -> Self {
2522        self.is_settings_visible = value;
2523        self
2524    }
2525
2526    /// Sets `is_back_button_visible`.
2527    pub fn is_back_button_visible(mut self, value: NavigationViewBackButtonVisible) -> Self {
2528        self.is_back_button_visible = value;
2529        self
2530    }
2531
2532    /// Sets `is_back_enabled`.
2533    pub fn is_back_enabled(mut self, value: bool) -> Self {
2534        self.is_back_enabled = value;
2535        self
2536    }
2537
2538    /// Sets `always_show_header`.
2539    pub fn always_show_header(mut self, value: bool) -> Self {
2540        self.always_show_header = value;
2541        self
2542    }
2543
2544    /// Sets `selection_follows_focus`.
2545    pub fn selection_follows_focus(mut self, value: NavigationViewSelectionFollowsFocus) -> Self {
2546        self.selection_follows_focus = value;
2547        self
2548    }
2549
2550    /// Sets `compact_mode_threshold_width`, coercing negative values to zero like the source property.
2551    pub fn compact_mode_threshold_width(mut self, value: f64) -> Self {
2552        assert!(value.is_finite());
2553        self.compact_mode_threshold_width = value.max(0.0);
2554        self
2555    }
2556
2557    /// Sets `expanded_mode_threshold_width`, coercing negative values to zero like the source property.
2558    pub fn expanded_mode_threshold_width(mut self, value: f64) -> Self {
2559        assert!(value.is_finite());
2560        self.expanded_mode_threshold_width = value.max(0.0);
2561        self
2562    }
2563
2564    /// Sets `compact_pane_length`, coercing negative values to zero like the source property.
2565    pub fn compact_pane_length(mut self, value: f64) -> Self {
2566        assert!(value.is_finite());
2567        self.compact_pane_length = value.max(0.0);
2568        self
2569    }
2570
2571    /// Sets `open_pane_length`, coercing negative values to zero like the source property.
2572    pub fn open_pane_length(mut self, value: f64) -> Self {
2573        assert!(value.is_finite());
2574        self.open_pane_length = value.max(0.0);
2575        self
2576    }
2577
2578    /// Supplies the source `header` content slot.
2579    #[cfg_attr(debug_assertions, track_caller)]
2580    pub fn header<K>(mut self, child: impl IntoWidget<K>) -> Self {
2581        self.header = Some(child.into_widget());
2582        self
2583    }
2584
2585    /// Supplies the source `pane_header` content slot.
2586    #[cfg_attr(debug_assertions, track_caller)]
2587    pub fn pane_header<K>(mut self, child: impl IntoWidget<K>) -> Self {
2588        self.pane_header = Some(child.into_widget());
2589        self
2590    }
2591
2592    /// Supplies the source `pane_custom_content` content slot.
2593    #[cfg_attr(debug_assertions, track_caller)]
2594    pub fn pane_custom_content<K>(mut self, child: impl IntoWidget<K>) -> Self {
2595        self.pane_custom_content = Some(child.into_widget());
2596        self
2597    }
2598
2599    /// Supplies the source `pane_footer` content slot.
2600    #[cfg_attr(debug_assertions, track_caller)]
2601    pub fn pane_footer<K>(mut self, child: impl IntoWidget<K>) -> Self {
2602        self.pane_footer = Some(child.into_widget());
2603        self
2604    }
2605
2606    /// Supplies the source `content_overlay` content slot.
2607    #[cfg_attr(debug_assertions, track_caller)]
2608    pub fn content_overlay<K>(mut self, child: impl IntoWidget<K>) -> Self {
2609        self.content_overlay = Some(child.into_widget());
2610        self
2611    }
2612
2613    /// Supplies the source `auto_suggest_box` content slot.
2614    #[cfg_attr(debug_assertions, track_caller)]
2615    pub fn auto_suggest_box<K>(mut self, child: impl IntoWidget<K>) -> Self {
2616        self.auto_suggest_box = Some(child.into_widget());
2617        self
2618    }
2619
2620    /// Sets the pane title shown beside the toggle or before top items.
2621    pub fn pane_title(mut self, title: impl Into<String>) -> Self {
2622        self.pane_title = title.into();
2623        self
2624    }
2625
2626    /// Supplies footer entries before the built-in settings item.
2627    pub fn footer_menu_items(
2628        mut self,
2629        items: impl IntoIterator<Item = NavigationViewItem>,
2630    ) -> Self {
2631        self.footer_menu_items = items.into_iter().collect();
2632        self
2633    }
2634
2635    /// Gives the owner control of pane openness while retaining adaptive change requests.
2636    pub fn is_pane_open(mut self, open: bool, changed: impl Fn(&mut App, bool) + 'static) -> Self {
2637        self.is_pane_open = Some(open);
2638        self.pane_open_changed = Some(Rc::new(changed));
2639        self
2640    }
2641
2642    /// Sets the widget identity.
2643    pub fn key(mut self, key: KeyRef) -> Self {
2644        self.key = Some(key);
2645        self
2646    }
2647    /// Receives the source `item_invoked` event.
2648    pub fn item_invoked(
2649        mut self,
2650        callback: impl Fn(&mut App, NavigationViewItemEventArgs) + 'static,
2651    ) -> Self {
2652        self.item_invoked = Some(Rc::new(callback));
2653        self
2654    }
2655
2656    /// Receives the source `expanding` event.
2657    pub fn expanding(
2658        mut self,
2659        callback: impl Fn(&mut App, NavigationViewItemEventArgs) + 'static,
2660    ) -> Self {
2661        self.expanding = Some(Rc::new(callback));
2662        self
2663    }
2664
2665    /// Receives the source `collapsed` event.
2666    pub fn collapsed(
2667        mut self,
2668        callback: impl Fn(&mut App, NavigationViewItemEventArgs) + 'static,
2669    ) -> Self {
2670        self.collapsed = Some(Rc::new(callback));
2671        self
2672    }
2673}