Skip to main content

waft_winui/controls/
split_view.rs

1//! WinUI SplitView: the two-column template and the pane lifecycle from SplitView_Partial.cpp.
2
3use super::split_view_visuals::{self, DisplayModeState};
4use crate::{
5    Brush, ColorTransition, ColumnDefinition, Grid, GridCell, GridLength, SizeObserver,
6    ThemeResources, after_next_frame,
7};
8use std::{any::Any, fmt, rc::Rc, time::Duration};
9use waft_embedder::{Color, Offset, Path, PathBuilder, PathFillType, Rect, Size};
10use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
11use waft_painting::{Alignment, EdgeInsets, transform_point};
12use waft_rendering::{BoxConstraints, CustomClipper, StackFit};
13use waft_scheduler::{FrameCallback, SchedulerBinding, Ticker};
14use waft_services::{KeyEvent, LogicalKeyboardKey};
15use waft_widgets::*;
16
17/// Specifies how the pane and content areas of a [`SplitView`] are displayed.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum SplitViewDisplayMode {
20    /// The open pane covers content; the closed pane is hidden.
21    #[default]
22    Overlay,
23    /// The open pane reserves its full width beside the content; the closed pane is hidden.
24    Inline,
25    /// The closed pane reserves its compact width; the open pane overlays the content.
26    CompactOverlay,
27    /// The pane reserves its compact width when closed and its full width when open.
28    CompactInline,
29}
30
31impl SplitViewDisplayMode {
32    /// Whether this mode allows interactions outside the pane to close it.
33    fn light_dismissible(self) -> bool {
34        matches!(self, Self::Overlay | Self::CompactOverlay)
35    }
36}
37
38/// Specifies which side of a [`SplitView`] contains its pane.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum SplitViewPanePlacement {
41    /// Displays the pane on the left side.
42    #[default]
43    Left,
44    /// Displays the pane on the right side.
45    Right,
46}
47
48/// Specifies whether a light-dismiss layer visually dims the content.
49///
50/// This controls the layer's appearance, not whether tapping it dismisses the pane.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
52pub enum LightDismissOverlayMode {
53    /// Uses the platform default: transparent on desktop.
54    #[default]
55    Auto,
56    /// Dims the content using the themed light-dismiss overlay brush.
57    On,
58    /// Keeps the dismiss layer transparent.
59    Off,
60}
61
62/// `OverlayVisibilityStates`; desktop Auto leaves the dismiss layer transparent.
63enum OverlayVisibilityState {
64    OverlayNotVisible,
65    OverlayVisible,
66}
67
68impl LightDismissOverlayMode {
69    /// Selects the template state controlling the dismiss layer's fill.
70    fn visual_state(self) -> OverlayVisibilityState {
71        match self {
72            Self::On => OverlayVisibilityState::OverlayVisible,
73            Self::Auto | Self::Off => OverlayVisibilityState::OverlayNotVisible,
74        }
75    }
76}
77
78/// Read-only values supplied to the SplitView template. Auto resolves after the pane's layout.
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct SplitViewTemplateSettings {
81    /// The resolved width of the fully open pane.
82    pub open_pane_length: f64,
83    /// The negated open width used by the left-pane translation.
84    pub negative_open_pane_length: f64,
85    /// The additional width revealed when expanding from compact to open.
86    pub open_pane_length_minus_compact_length: f64,
87    /// The negated expansion width used by left-pane clip and content animations.
88    pub negative_open_pane_length_minus_compact_length: f64,
89    /// The resolved open width expressed as a pixel Grid length.
90    pub open_pane_grid_length: GridLength,
91    /// The compact width expressed as a pixel Grid length.
92    pub compact_pane_grid_length: GridLength,
93}
94
95impl SplitViewTemplateSettings {
96    /// Derives animation and Grid values from the resolved open and compact widths.
97    fn new(open: f64, compact: f64) -> Self {
98        Self {
99            open_pane_length: open,
100            negative_open_pane_length: -open,
101            open_pane_length_minus_compact_length: open - compact,
102            negative_open_pane_length_minus_compact_length: -(open - compact),
103            open_pane_grid_length: GridLength::pixel(open),
104            compact_pane_grid_length: GridLength::pixel(compact),
105        }
106    }
107}
108
109/// `Cancel` is honored for light dismissal, not an explicit `is_pane_open = false` update.
110#[derive(Clone, Copy, Debug, Default)]
111pub struct SplitViewPaneClosingEventArgs {
112    /// Set to `true` to cancel light dismissal; ignored for explicit owner-driven closes.
113    pub cancel: bool,
114}
115
116/// Receives a requested `IsPaneOpen` value; the owner applies or rejects the change.
117pub type SplitViewPaneChangedHandler = Rc<dyn Fn(&mut App, bool)>;
118
119type PaneEvent = Listener;
120
121/// Receives `PaneClosing` arguments before a light-dismiss close request is applied.
122pub type SplitViewPaneClosingHandler = Rc<dyn Fn(&mut App, &mut SplitViewPaneClosingEventArgs)>;
123
124/// A container with a content area and a pane that can expand, collapse or overlay the content.
125///
126/// The owner supplies [`is_pane_open`](Self::is_pane_open) and applies requested changes.
127/// Open overlay modes require a native [`Overlay`] ancestor for dismissal outside the control.
128/// Pane and content widgets retain their state when the pane opens or closes.
129#[derive(Clone)]
130pub struct SplitView {
131    /// Identifies this widget when the parent rebuilds.
132    pub key: Option<KeyRef>,
133    /// Whether the pane is expanded to its open width.
134    pub is_pane_open: bool,
135    /// Requests a new open value from the owner after an uncanceled light dismissal.
136    pub is_pane_open_changed: SplitViewPaneChangedHandler,
137    /// The widget displayed in the pane area; retained while the pane is closed.
138    pub pane: Option<WidgetRef>,
139    /// The widget displayed in the main content area.
140    pub content: Option<WidgetRef>,
141    /// How the pane shares space with the content; defaults to Overlay.
142    pub display_mode: SplitViewDisplayMode,
143    /// The side containing the pane; defaults to Left.
144    pub pane_placement: SplitViewPanePlacement,
145    /// The open pane width; `f64::NAN` sizes to the pane content, and `None` is the theme's
146    /// `SplitViewOpenPaneThemeLength`.
147    pub open_pane_length: Option<f64>,
148    /// The width reserved by a closed compact pane; the theme's `SplitViewCompactPaneThemeLength`
149    /// when `None`.
150    pub compact_pane_length: Option<f64>,
151    /// Whether the dismiss layer dims the content; defaults to desktop Auto (transparent).
152    pub light_dismiss_overlay_mode: LightDismissOverlayMode,
153    /// The pane fill; `None` resolves the default brush from the current theme.
154    pub pane_background: Option<Brush>,
155    /// The background behind both pane and content; `None` leaves it unpainted.
156    pub background: Option<Brush>,
157    /// The pane border brush; the default theme brush is transparent.
158    pub border_brush: Option<Brush>,
159    /// Pane border widths in left, top, right, bottom order; the theme's
160    /// `SplitViewLeftBorderThemeThickness` when `None`.
161    pub border_thickness: Option<[f64; 4]>,
162    /// Pane radii in top-left, top-right, bottom-right, bottom-left order; the theme's
163    /// `SplitViewPaneRootCornerRadius` when `None`.
164    pub corner_radius: Option<[f64; 4]>,
165    /// Called after the first layout of an opening transition, before focus moves into the pane.
166    pub pane_opening: Option<PaneEvent>,
167    /// Called when the current opening transition completes.
168    pub pane_opened: Option<PaneEvent>,
169    /// Called before light dismissal, or after the first layout of an explicit closing update.
170    pub pane_closing: Option<SplitViewPaneClosingHandler>,
171    /// Called when the current closing transition completes.
172    pub pane_closed: Option<PaneEvent>,
173}
174
175impl SplitView {
176    /// The owner applies requested `IsPaneOpen` changes, as with other reveal controls.
177    pub fn new(is_pane_open: bool, changed: impl Fn(&mut App, bool) + 'static) -> Self {
178        Self {
179            key: None,
180            is_pane_open,
181            is_pane_open_changed: Rc::new(changed),
182            pane: None,
183            content: None,
184            display_mode: SplitViewDisplayMode::Overlay,
185            pane_placement: SplitViewPanePlacement::Left,
186            open_pane_length: None,
187            compact_pane_length: None,
188            light_dismiss_overlay_mode: LightDismissOverlayMode::Auto,
189            pane_background: None,
190            background: None,
191            border_brush: None,
192            border_thickness: None,
193            corner_radius: None,
194            pane_opening: None,
195            pane_opened: None,
196            pane_closing: None,
197            pane_closed: None,
198        }
199    }
200
201    /// Sets the widget identity.
202    pub fn key(mut self, key: KeyRef) -> Self {
203        self.key = Some(key);
204        self
205    }
206
207    /// Sets the widget displayed in the pane area.
208    #[cfg_attr(debug_assertions, track_caller)]
209    pub fn pane<K>(mut self, pane: impl IntoWidget<K>) -> Self {
210        self.pane = Some(pane.into_widget());
211        self
212    }
213
214    /// Sets the widget displayed in the main content area.
215    #[cfg_attr(debug_assertions, track_caller)]
216    pub fn content<K>(mut self, content: impl IntoWidget<K>) -> Self {
217        self.content = Some(content.into_widget());
218        self
219    }
220
221    /// Sets how the pane shares space with the content.
222    pub fn display_mode(mut self, mode: SplitViewDisplayMode) -> Self {
223        self.display_mode = mode;
224        self
225    }
226
227    /// Sets which side contains the pane.
228    pub fn pane_placement(mut self, placement: SplitViewPanePlacement) -> Self {
229        self.pane_placement = placement;
230        self
231    }
232
233    /// `f64::NAN` is WinUI's Auto length, measured from the pane content.
234    ///
235    /// Panics for negative lengths or infinity.
236    pub fn open_pane_length(mut self, length: f64) -> Self {
237        assert!(length.is_nan() || (length.is_finite() && length >= 0.0));
238        self.open_pane_length = Some(length);
239        self
240    }
241
242    /// Sets the width reserved when a compact pane is closed.
243    ///
244    /// Panics if the length is negative or non-finite.
245    pub fn compact_pane_length(mut self, length: f64) -> Self {
246        assert!(length.is_finite() && length >= 0.0);
247        self.compact_pane_length = Some(length);
248        self
249    }
250
251    /// Sets the appearance of the light-dismiss layer.
252    pub fn light_dismiss_overlay_mode(mut self, mode: LightDismissOverlayMode) -> Self {
253        self.light_dismiss_overlay_mode = mode;
254        self
255    }
256
257    /// Sets the background behind the pane and content.
258    pub fn background(mut self, brush: Brush) -> Self {
259        self.background = Some(brush);
260        self
261    }
262
263    /// Sets pane radii in top-left, top-right, bottom-right, bottom-left order.
264    pub fn corner_radius_corners(mut self, radius: [f64; 4]) -> Self {
265        self.corner_radius = Some(radius);
266        self
267    }
268
269    /// Sets the pane fill brush.
270    pub fn pane_background(mut self, brush: Brush) -> Self {
271        self.pane_background = Some(brush);
272        self
273    }
274
275    /// Sets the pane border brush.
276    pub fn border_brush(mut self, brush: Brush) -> Self {
277        self.border_brush = Some(brush);
278        self
279    }
280
281    /// Sets the same pane border width on all four sides.
282    pub fn border_thickness(mut self, thickness: f64) -> Self {
283        self.border_thickness = Some([thickness; 4]);
284        self
285    }
286
287    /// Sets pane border widths in left, top, right, bottom order.
288    pub fn border_thickness_ltrb(mut self, thickness: [f64; 4]) -> Self {
289        self.border_thickness = Some(thickness);
290        self
291    }
292
293    /// Sets the same radius on all four pane corners.
294    pub fn corner_radius(mut self, radius: f64) -> Self {
295        self.corner_radius = Some([radius; 4]);
296        self
297    }
298
299    /// Registers a handler for the start of an opening transition.
300    pub fn pane_opening(mut self, callback: Listener) -> Self {
301        self.pane_opening = Some(callback);
302        self
303    }
304
305    /// Registers a handler for completion of an opening transition.
306    pub fn pane_opened(mut self, callback: Listener) -> Self {
307        self.pane_opened = Some(callback);
308        self
309    }
310
311    /// Registers a handler that can cancel light dismissal through its event arguments.
312    pub fn pane_closing(
313        mut self,
314        callback: impl Fn(&mut App, &mut SplitViewPaneClosingEventArgs) + 'static,
315    ) -> Self {
316        self.pane_closing = Some(Rc::new(callback));
317        self
318    }
319
320    /// Registers a handler for completion of a closing transition.
321    pub fn pane_closed(mut self, callback: Listener) -> Self {
322        self.pane_closed = Some(callback);
323        self
324    }
325
326    /// Selects the template state for the current mode, open value and pane placement.
327    fn visual_state(&self) -> DisplayModeState {
328        use DisplayModeState::*;
329        let right = self.pane_placement == SplitViewPanePlacement::Right;
330        match (self.display_mode, self.is_pane_open, right) {
331            (SplitViewDisplayMode::Overlay | SplitViewDisplayMode::Inline, false, _) => Closed,
332            (_, false, false) => ClosedCompactLeft,
333            (_, false, true) => ClosedCompactRight,
334            (SplitViewDisplayMode::Overlay, true, false) => OpenOverlayLeft,
335            (SplitViewDisplayMode::Overlay, true, true) => OpenOverlayRight,
336            (SplitViewDisplayMode::CompactOverlay, true, false) => OpenCompactOverlayLeft,
337            (SplitViewDisplayMode::CompactOverlay, true, true) => OpenCompactOverlayRight,
338            (_, true, false) => OpenInlineLeft,
339            (_, true, true) => OpenInlineRight,
340        }
341    }
342}
343
344impl fmt::Debug for SplitView {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        f.debug_struct("SplitView")
347            .field("is_pane_open", &self.is_pane_open)
348            .field("display_mode", &self.display_mode)
349            .finish_non_exhaustive()
350    }
351}
352
353/// Retains pane animation, focus and measured template values across widget updates.
354pub struct SplitViewState {
355    state: StateData<SplitView>,
356    single_ticker_provider: SingleTickerProviderStateMixinData,
357    ticker: Option<Ref<Ticker>>,
358    pane_focus: Option<Ref<FocusScopeNode>>,
359    content_focus: Option<Ref<FocusScopeNode>>,
360    /// The focus target saved on overlay opening and consumed when restoring focus.
361    previous_focus: Option<AnyFocusNode>,
362    /// Hosts the outer dismiss layer above the application's content.
363    portal: Option<Ref<OverlayPortalController>>,
364    /// The source state of the currently evaluated transition.
365    from: DisplayModeState,
366    /// Elapsed time within the current transition.
367    elapsed: Duration,
368    /// Total transition duration; zero selects the settled target state.
369    duration: Duration,
370    /// Invalidates completion callbacks when a transition is replaced.
371    epoch: u64,
372    /// Whether the pending visual-state change should emit an opened or closed event.
373    opening_or_closing: bool,
374    /// Suppresses duplicate closing notifications while a light-dismiss request is pending.
375    closing_by_dismiss: bool,
376    /// Latest measured pane width, retained even in explicit-width mode for a later Auto update.
377    measured_pane_length: f64,
378    /// Live values captured at interruption for tracks without an explicit starting keyframe; set
379    /// when a transition starts.
380    initial_visuals: Option<split_view_visuals::Visuals>,
381    /// The pane's lengths as the last build resolved them.
382    lengths: (f64, f64),
383    /// Previous window metrics used to detect changes that should light-dismiss the pane.
384    root_metrics: Option<(Size, f64, EdgeInsets, EdgeInsets)>,
385}
386
387impl StatefulWidget for SplitView {
388    type State = SplitViewState;
389
390    fn key(&self) -> Option<&KeyRef> {
391        self.key.as_ref()
392    }
393
394    fn create_state(&self) -> SplitViewState {
395        SplitViewState {
396            state: StateData::new(),
397            single_ticker_provider: Default::default(),
398            ticker: None,
399            pane_focus: None,
400            content_focus: None,
401            previous_focus: None,
402            portal: None,
403            from: self.visual_state(),
404            elapsed: Duration::ZERO,
405            duration: Duration::ZERO,
406            epoch: 0,
407            opening_or_closing: false,
408            closing_by_dismiss: false,
409            measured_pane_length: 0.0,
410            root_metrics: None,
411            initial_visuals: None,
412            lengths: (0.0, 0.0),
413        }
414    }
415}
416
417impl SingleTickerProviderStateMixin for SplitViewState {
418    fn single_ticker_provider_data(
419        self: Handle<Self>,
420        app: &App,
421    ) -> &SingleTickerProviderStateMixinData {
422        &app.get(self).single_ticker_provider
423    }
424
425    fn single_ticker_provider_data_mut(
426        self: Handle<Self>,
427        app: &mut App,
428    ) -> &mut SingleTickerProviderStateMixinData {
429        &mut app.get_mut(self).single_ticker_provider
430    }
431}
432
433impl SplitViewState {
434    /// Returns the resolved lengths used by this control's template.
435    ///
436    /// For Auto pane width, these values reflect the latest completed layout.
437    pub fn template_settings(self: Handle<Self>, app: &App) -> SplitViewTemplateSettings {
438        let (open, compact) = app.get(self).lengths;
439        let open = if open.is_nan() {
440            app.get(self).measured_pane_length
441        } else {
442            open
443        };
444        SplitViewTemplateSettings::new(open, compact)
445    }
446
447    /// Whether an open overlay pane can start another light-dismiss request.
448    fn can_light_dismiss(self: Handle<Self>, app: &App) -> bool {
449        self.widget(app).is_pane_open
450            && self.widget(app).display_mode.light_dismissible()
451            && !app.get(self).closing_by_dismiss
452    }
453
454    /// Raises `PaneClosing` to give the owner a chance to cancel before requesting closure.
455    fn dismiss(self: Handle<Self>, app: &mut App) {
456        if !app.contains(self) || !self.mounted(app) || !self.can_light_dismiss(app) {
457            return;
458        }
459        let mut args = SplitViewPaneClosingEventArgs::default();
460        let callback = self.widget(app).pane_closing.clone();
461        app.get_mut(self).closing_by_dismiss = true;
462        if let Some(callback) = callback {
463            callback(app, &mut args);
464        }
465        if !app.contains(self) || !self.mounted(app) {
466            return;
467        }
468        if args.cancel {
469            app.get_mut(self).closing_by_dismiss = false;
470            return;
471        }
472        let changed = self.widget(app).is_pane_open_changed.clone();
473        changed(app, false);
474        after_next_frame(
475            app,
476            View::maybe_id_of(app, self.context(app)),
477            FrameCallback::new(move |app, _| {
478                if app.contains(self) && self.mounted(app) && self.widget(app).is_pane_open {
479                    app.get_mut(self).closing_by_dismiss = false;
480                }
481            }),
482        );
483    }
484
485    /// Restores the focus target saved on opening, falling back to the content if it is gone.
486    fn restore_focus(self: Handle<Self>, app: &mut App) {
487        if let Some(previous) = app.get_mut(self).previous_focus.take() {
488            if app.contains(previous.id())
489                && !app.is_disposed(previous.id())
490                && previous.context(app).is_some()
491                && previous.parent(app).is_some()
492                && previous.can_request_focus(app)
493            {
494                previous.request_focus(app, None);
495            } else {
496                app.get(self)
497                    .content_focus
498                    .clone()
499                    .unwrap()
500                    .as_node()
501                    .next_focus(app);
502            }
503        }
504    }
505
506    /// Saves the current focus target and moves focus into an opening overlay pane.
507    fn focus_pane(self: Handle<Self>, app: &mut App) {
508        if !self.widget(app).display_mode.light_dismissible() || !self.widget(app).is_pane_open {
509            return;
510        }
511        let pane = app.get(self).pane_focus.clone().unwrap();
512        if app.get(self).previous_focus.is_none() {
513            app.get_mut(self).previous_focus = primary_focus(app);
514        }
515        let first = pane
516            .as_node()
517            .traversal_descendants(app)
518            .into_iter()
519            .find(|node| node.can_request_focus(app));
520        first.unwrap_or(pane.as_node()).request_focus(app, None);
521    }
522
523    /// Delivers the opened or closed event only for the current transition.
524    fn complete(self: Handle<Self>, app: &mut App, epoch: u64) {
525        if !self.mounted(app) || app.get(self).epoch != epoch || !app.get(self).opening_or_closing {
526            return;
527        }
528        app.get_mut(self).opening_or_closing = false;
529        let open = self.widget(app).is_pane_open;
530        if !open {
531            app.get_mut(self).closing_by_dismiss = false;
532        }
533        let callback = if open {
534            self.widget(app).pane_opened.clone()
535        } else {
536            self.widget(app).pane_closed.clone()
537        };
538        if let Some(callback) = callback {
539            callback.call(app);
540        }
541    }
542
543    /// Advances the active storyboard and queues its completion after the rendered frame.
544    fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
545        if !self.mounted(app) {
546            return;
547        }
548        self.set_state(app, |s| s.elapsed = elapsed);
549        if elapsed >= app.get(self).duration {
550            app.get(self).ticker.handle().unwrap().stop(app, false);
551            let epoch = app.get(self).epoch;
552            SchedulerBinding::add_post_frame_callback(
553                app,
554                FrameCallback::new(move |app, _| {
555                    if app.contains(self) {
556                        self.complete(app, epoch);
557                    }
558                }),
559                View::maybe_id_of(app, self.context(app)),
560            );
561        }
562    }
563
564    /// Updates the outer dismiss layer after build, when native overlay mutations are allowed.
565    fn update_portal(self: Handle<Self>, app: &mut App) {
566        SchedulerBinding::add_post_frame_callback(
567            app,
568            FrameCallback::new(move |app, _| {
569                if !app.contains(self) || !self.mounted(app) {
570                    return;
571                }
572                let portal = app.get(self).portal.clone().unwrap();
573                let show = self.widget(app).is_pane_open
574                    && self.widget(app).display_mode.light_dismissible();
575                if show != portal.is_showing(app) {
576                    if show {
577                        portal.show(app);
578                    } else {
579                        portal.hide(app);
580                    }
581                }
582            }),
583            View::maybe_id_of(app, self.context(app)),
584        );
585    }
586}
587
588/// `PaneLayout` is the pane's lengths, border and corners: the widget's own, else the theme's.
589#[derive(Clone, Copy, Debug, PartialEq)]
590struct PaneLayout {
591    /// The open pane width; `f64::NAN` sizes to the pane content.
592    open: f64,
593    /// The width reserved by a closed compact pane.
594    compact: f64,
595    /// Pane border widths in left, top, right, bottom order.
596    border_thickness: [f64; 4],
597    /// Pane radii in top-left, top-right, bottom-right, bottom-left order.
598    corner_radius: [f64; 4],
599}
600
601impl SplitView {
602    /// `pane_layout` is the pane's lengths, border and corners, the theme's where the widget sets
603    /// none, as the style's setters do.
604    fn pane_layout(&self, r: &ThemeResources) -> PaneLayout {
605        PaneLayout {
606            open: self
607                .open_pane_length
608                .unwrap_or(r.split_view_open_pane_theme_length),
609            compact: self
610                .compact_pane_length
611                .unwrap_or(r.split_view_compact_pane_theme_length),
612            border_thickness: self
613                .border_thickness
614                .unwrap_or(r.split_view_left_border_theme_thickness),
615            corner_radius: self
616                .corner_radius
617                .unwrap_or(r.split_view_pane_root_corner_radius),
618        }
619    }
620}
621
622impl State for SplitViewState {
623    type Widget = SplitView;
624    waft_widgets::state_accessors!();
625    fn init_state(self: Handle<Self>, app: &mut App) {
626        let pane = FocusScopeNode::new(app);
627        let content = FocusScopeNode::new(app);
628        content.set_traversal_edge_behavior(app, TraversalEdgeBehavior::ParentScope);
629        let portal = OverlayPortalController::new(app, Some("SplitView outer dismissal".into()));
630        let ticker = SingleTickerProviderStateMixin::create_ticker(
631            self,
632            app,
633            FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
634        );
635        let s = app.get_mut(self);
636        s.pane_focus = Some(pane.clone());
637        s.content_focus = Some(content.clone());
638        s.portal = Some(portal.clone());
639        s.ticker = Some(ticker);
640        self.update_portal(app);
641        SchedulerBinding::add_post_frame_callback(
642            app,
643            FrameCallback::new(move |app, _| {
644                if app.contains(self) && self.mounted(app) {
645                    self.focus_pane(app);
646                }
647            }),
648            View::maybe_id_of(app, self.context(app)),
649        );
650    }
651
652    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &SplitView) {
653        let widget = self.widget(app).clone();
654        let change = old.is_pane_open != widget.is_pane_open;
655        let from = old.visual_state();
656        let to = widget.visual_state();
657        if old.display_mode != widget.display_mode {
658            self.restore_focus(app);
659        }
660        self.update_portal(app);
661        let r = ThemeResources::of(app, self.context(app));
662        let (old_pane, pane) = (old.pane_layout(&r), widget.pane_layout(&r));
663        let lengths_changed = !(old_pane.open == pane.open
664            || (old_pane.open.is_nan() && pane.open.is_nan()))
665            || old_pane.compact != pane.compact;
666        if from == to && !lengths_changed {
667            return;
668        }
669        let previous = app.get(self);
670        let old_open = if old_pane.open.is_nan() {
671            previous.measured_pane_length
672        } else {
673            old_pane.open
674        };
675        let initial = if previous.duration.is_zero() {
676            split_view_visuals::settled(from, old_open, old_pane.compact)
677        } else {
678            split_view_visuals::transition_from_visuals(
679                &r,
680                previous.from,
681                from,
682                previous.elapsed,
683                old_open,
684                old_pane.compact,
685                previous
686                    .initial_visuals
687                    .expect("set when a transition starts"),
688            )
689        };
690        let ticker = app.get(self).ticker.clone().unwrap();
691        ticker.stop(app, false);
692        let duration = if lengths_changed {
693            Duration::ZERO
694        } else {
695            split_view_visuals::transition_duration(&r, from, to).unwrap_or_default()
696        };
697        let s = app.get_mut(self);
698        s.initial_visuals = Some(initial);
699        s.from = from;
700        s.duration = duration;
701        s.elapsed = Duration::ZERO;
702        s.epoch += 1;
703        s.opening_or_closing |= change;
704        let epoch = s.epoch;
705        if change {
706            let by_dismiss = app.get(self).closing_by_dismiss;
707            if !widget.is_pane_open {
708                self.restore_focus(app);
709            }
710            SchedulerBinding::add_post_frame_callback(
711                app,
712                FrameCallback::new(move |app, _| {
713                    if !app.contains(self) || !self.mounted(app) || app.get(self).epoch != epoch {
714                        return;
715                    }
716                    if widget.is_pane_open {
717                        if let Some(callback) = &widget.pane_opening {
718                            callback.call(app);
719                        }
720                        if app.contains(self) && self.mounted(app) {
721                            self.focus_pane(app);
722                        }
723                    } else if !by_dismiss && let Some(callback) = &widget.pane_closing {
724                        callback(app, &mut SplitViewPaneClosingEventArgs::default());
725                    }
726                }),
727                View::maybe_id_of(app, self.context(app)),
728            );
729        }
730        if duration.is_zero() {
731            SchedulerBinding::add_post_frame_callback(
732                app,
733                FrameCallback::new(move |app, _| {
734                    if app.contains(self) {
735                        self.complete(app, epoch);
736                    }
737                }),
738                View::maybe_id_of(app, self.context(app)),
739            );
740        } else {
741            ticker.start(app);
742        }
743    }
744
745    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
746        let metrics = MediaQuery::maybe_of(app, self.context(app))
747            .map(|m| (m.size, m.device_pixel_ratio, m.view_insets, m.view_padding));
748        let previous = app.get(self).root_metrics;
749        app.get_mut(self).root_metrics = metrics;
750        if previous.is_some() && previous != metrics {
751            SchedulerBinding::add_post_frame_callback(
752                app,
753                FrameCallback::new(move |app, _| {
754                    if app.contains(self) && self.mounted(app) {
755                        self.dismiss(app);
756                    }
757                }),
758                View::maybe_id_of(app, self.context(app)),
759            );
760        }
761    }
762
763    fn activate(self: Handle<Self>, app: &mut App) {
764        SingleTickerProviderStateMixin::activate(self, app);
765    }
766
767    fn dispose(self: Handle<Self>, app: &mut App) {
768        // OnUnloaded tears down dismissal; focus restoration belongs to closing or changing mode,
769        // not to a subtree whose focus attachments have already been detached.
770        app.get_mut(self).previous_focus = None;
771        app.get(self).ticker.handle().unwrap().dispose(app);
772        let pane = app.get(self).pane_focus.clone().unwrap();
773        let content = app.get(self).content_focus.clone().unwrap();
774        pane.as_node().dispose(app);
775        content.as_node().dispose(app);
776        SingleTickerProviderStateMixin::dispose(self, app);
777    }
778
779    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
780        let widget = self.widget(app).clone();
781        let pane = app.get(self).pane_focus.clone().unwrap();
782        pane.set_traversal_edge_behavior(
783            app,
784            if widget.is_pane_open && widget.display_mode.light_dismissible() {
785                TraversalEdgeBehavior::ClosedLoop
786            } else {
787                TraversalEdgeBehavior::ParentScope
788            },
789        );
790        let resources = ThemeResources::of(app, context);
791        let body = LayoutBuilder::new(move |app, _, constraints| {
792            self.build_template(app, constraints.constraints(), resources.clone())
793        });
794        let body = SizeObserver::new(
795            body.into_widget(),
796            Rc::new(move |app, old, _new| {
797                if (old.width() != 0.0 || old.height() != 0.0) && self.can_light_dismiss(app) {
798                    self.dismiss(app);
799                }
800            }),
801        )
802        .into_widget();
803        let body = Focus::new(body)
804            .skip_traversal(true)
805            .can_request_focus(false)
806            .on_key_event(Rc::new(move |app, _, event| {
807                if matches!(event, KeyEvent::Down(_))
808                    && matches!(
809                        event.logical_key(),
810                        LogicalKeyboardKey::ESCAPE | LogicalKeyboardKey::GAME_BUTTON_B
811                    )
812                    && self.can_light_dismiss(app)
813                {
814                    self.dismiss(app);
815                    KeyEventResult::Handled
816                } else {
817                    KeyEventResult::Ignored
818                }
819            }))
820            .into_widget();
821        if Overlay::maybe_of(app, context, true).is_none() {
822            assert!(
823                !widget.is_pane_open || !widget.display_mode.light_dismissible(),
824                "SplitView overlay modes require an Overlay ancestor for window-wide light dismissal"
825            );
826            return body;
827        }
828        OverlayPortal::overlay_child_layout_builder(
829            app.get(self).portal.clone().unwrap(),
830            move |_app, _, info| {
831                let size = info.child_size();
832                let transform = info.child_paint_transform();
833                let corners = [
834                    Offset::ZERO,
835                    Offset::new(0.0, size.height()),
836                    Offset::new(size.width(), size.height()),
837                    Offset::new(size.width(), 0.0),
838                ]
839                .map(|p| transform_point(&transform, p));
840                ClipPath::new()
841                    .clipper(Rc::new(OutsideClipper(corners)))
842                    .child(
843                        ModalBarrier::new().on_dismiss(Listener::new(move |app| self.dismiss(app))),
844                    )
845                    .into_widget()
846            },
847        )
848        .overlay_location(OverlayChildLocation::RootOverlay)
849        .child(body)
850        .into_widget()
851    }
852}
853
854impl SplitViewState {
855    /// Builds the named template parts from the current visual-state setters and storyboard tracks.
856    fn build_template(
857        self: Handle<Self>,
858        app: &mut App,
859        constraints: BoxConstraints,
860        resources: Rc<ThemeResources>,
861    ) -> WidgetRef {
862        let widget = self.widget(app).clone();
863        let pane = widget.pane_layout(&resources);
864        app.get_mut(self).lengths = (pane.open, pane.compact);
865        let open = if pane.open.is_nan() {
866            app.get(self).measured_pane_length
867        } else {
868            pane.open
869        };
870        let state = app.get(self);
871        let v = if state.duration.is_zero() {
872            split_view_visuals::settled(widget.visual_state(), open, pane.compact)
873        } else {
874            split_view_visuals::transition_from_visuals(
875                &resources,
876                state.from,
877                widget.visual_state(),
878                state.elapsed,
879                open,
880                pane.compact,
881                state.initial_visuals.expect("set when a transition starts"),
882            )
883        };
884        let pane_focus = state.pane_focus.clone().unwrap();
885        let content_focus = state.content_focus.clone().unwrap();
886        let pane_child = widget
887            .pane
888            .unwrap_or_else(|| SizedBox::shrink().into_widget());
889        // The content probe stays at the same tree position when switching Auto and explicit widths.
890        let pane_child = SizeObserver::new(
891            pane_child,
892            Rc::new(move |app, _, new| {
893                if app.get(self).measured_pane_length != new.width() {
894                    if app.get(self).lengths.0.is_nan() {
895                        self.set_state(app, |s| s.measured_pane_length = new.width());
896                    } else {
897                        app.get_mut(self).measured_pane_length = new.width();
898                    }
899                }
900            }),
901        );
902        let auto = pane.open.is_nan();
903        let pane_child = OverflowBox::new()
904            .alignment(Alignment::TOP_LEFT.into())
905            .min_width(if auto {
906                0.0
907            } else {
908                (open - pane.border_thickness[0] - pane.border_thickness[2]).max(0.0)
909            })
910            .max_width(if auto {
911                constraints.max_width
912            } else {
913                (open - pane.border_thickness[0] - pane.border_thickness[2]).max(0.0)
914            })
915            .child(
916                Align::new()
917                    .alignment(Alignment::TOP_LEFT.into())
918                    .width_factor(1.0)
919                    .child(pane_child),
920            );
921        let pane_child = FocusScope::new(pane_child)
922            .node(pane_focus)
923            .descendants_are_focusable(v.pane_visible)
924            .into_widget();
925        let background = widget.pane_background.unwrap_or(Brush::Solid(
926            resources.system_control_page_background_chrome_low_brush,
927        ));
928        let border_brush = widget.border_brush.unwrap_or(Brush::Solid(
929            resources.system_control_foreground_transparent_brush,
930        ));
931        // PaneRoot: Grid chrome and its default BrushTransition (150 ms in SimplePropertiesMetadata.g.h).
932        let pane_root = ColorTransition::new(
933            background.representative_color(),
934            Duration::from_millis(150),
935            move |_app, color| {
936                Grid::new()
937                    .background(if matches!(background, Brush::Solid(_)) {
938                        Brush::Solid(color)
939                    } else {
940                        background
941                    })
942                    .border_brush(border_brush)
943                    .border_thickness_ltrb(pane.border_thickness)
944                    .corner_radius_corners(pane.corner_radius)
945                    .children([pane_child.clone()])
946                    .into_widget()
947            },
948        );
949        let pane_root = SizedBox::new().width(open).child(pane_root);
950        // PaneClipRectangle / PaneClipRectangleTransform, then PaneTransform.
951        // HCPaneBorder is transparent in both emitted themes.
952        let pane_root = ClipRect::new()
953            .clipper(PaneClipper(v.clip_translate))
954            .child(pane_root);
955        let pane_root = Transform::translate(Offset::new(v.pane_translate, 0.0)).child(pane_root);
956        let pane_root = Visibility::new(pane_root)
957            .visible(v.pane_visible)
958            .maintain_state(true);
959        let pane_root = OverflowBox::new()
960            .min_width(open)
961            .max_width(open)
962            .alignment(
963                if v.pane_right {
964                    Alignment::CENTER_RIGHT
965                } else {
966                    Alignment::CENTER_LEFT
967                }
968                .into(),
969            )
970            .child(pane_root);
971        // ContentRoot: the content Border followed by LightDismissLayer.
972        let mut content = vec![
973            FocusScope::new(
974                widget
975                    .content
976                    .unwrap_or_else(|| SizedBox::shrink().into_widget()),
977            )
978            .node(content_focus)
979            .into_widget(),
980        ];
981        let color = match widget.light_dismiss_overlay_mode.visual_state() {
982            OverlayVisibilityState::OverlayVisible => {
983                resources.split_view_light_dismiss_overlay_background
984            }
985            OverlayVisibilityState::OverlayNotVisible => Color::from_argb(0, 0, 0, 0),
986        };
987        content.push(
988            Visibility::new(
989                Opacity::new(v.overlay_opacity).child(
990                    ModalBarrier::new()
991                        .color(color)
992                        .on_dismiss(Listener::new(move |app| self.dismiss(app))),
993                ),
994            )
995            .visible(v.overlay_visible)
996            .maintain_state(true)
997            .into_widget(),
998        );
999        let content_root = Transform::translate(Offset::new(v.content_translate, 0.0))
1000            .child(Stack::new().fit(StackFit::Expand).children(content));
1001        let mut root = Grid::new();
1002        if let Some(background) = widget.background {
1003            root = root.background(background);
1004        }
1005        // ColumnDefinition1 / ColumnDefinition2. PaneRoot's Canvas.ZIndex=1 puts it above ContentRoot.
1006        root.column_definitions([
1007            ColumnDefinition::new(v.column1),
1008            ColumnDefinition::new(v.column2),
1009        ])
1010        .children([
1011            GridCell::new(content_root)
1012                .column(v.content_column)
1013                .column_span(v.content_span)
1014                .into_widget(),
1015            GridCell::new(pane_root)
1016                .column(v.pane_column)
1017                .column_span(v.pane_span)
1018                .into_widget(),
1019        ])
1020        .into_widget()
1021    }
1022}
1023
1024/// The pane rectangle translated by `PaneClipRectangleTransform` before `PaneTransform`.
1025#[derive(Debug)]
1026struct PaneClipper(f64);
1027impl CustomClipper<Rect> for PaneClipper {
1028    fn get_clip(&self, _app: &App, size: Size) -> Rect {
1029        Rect::from_ltwh(self.0, 0.0, size.width(), size.height())
1030    }
1031
1032    fn should_reclip(&self, _app: &App, old: &dyn CustomClipper<Rect>) -> bool {
1033        old.as_any()
1034            .downcast_ref::<Self>()
1035            .is_none_or(|old| old.0 != self.0)
1036    }
1037
1038    fn as_any(&self) -> &dyn Any {
1039        self
1040    }
1041}
1042
1043/// The outer dismiss layer that detects interactions outside the SplitView bounds.
1044///
1045/// WinUI uses four polygonal elements for DComp input; the native overlay uses a clipped hole.
1046#[derive(Debug)]
1047struct OutsideClipper([Offset; 4]);
1048impl CustomClipper<Path> for OutsideClipper {
1049    fn get_clip(&self, _app: &App, size: Size) -> Path {
1050        let hole = self.0;
1051        let mut path = PathBuilder::new();
1052        for polygon in [
1053            [
1054                Offset::ZERO,
1055                Offset::new(size.width(), 0.0),
1056                Offset::new(size.width(), size.height()),
1057                Offset::new(0.0, size.height()),
1058            ],
1059            hole,
1060        ] {
1061            path.move_to((polygon[0].dx() as f32, polygon[0].dy() as f32));
1062            for p in &polygon[1..] {
1063                path.line_to((p.dx() as f32, p.dy() as f32));
1064            }
1065            path.close();
1066        }
1067        let mut path = Path::new(path.build());
1068        // The hole cuts out of the bounds whichever way a reflected ancestor turns it.
1069        path.fill_type = PathFillType::EvenOdd;
1070        path
1071    }
1072
1073    fn should_reclip(&self, _app: &App, old: &dyn CustomClipper<Path>) -> bool {
1074        old.as_any()
1075            .downcast_ref::<Self>()
1076            .is_none_or(|old| old.0 != self.0)
1077    }
1078
1079    fn as_any(&self) -> &dyn Any {
1080        self
1081    }
1082}