Skip to main content

sui_widgets/
workspace.rs

1use sui_core::{
2    Event, KeyState, Point, PointerButton, PointerEventKind, Rect, SemanticsAction,
3    SemanticsActionRequest, SemanticsNode, SemanticsRole, Size,
4};
5use sui_layout::Constraints;
6use sui_reactive::Signal;
7use sui_runtime::{
8    ArrangeCtx, Command, EventCtx, FocusScope, FocusScopeState, LayerOptions, MeasureCtx,
9    OVERLAY_DISMISS_REQUEST, OverlayDismissPolicy, OverlayFocusBehavior, OverlayKind,
10    OverlayOptions, PaintBoundaryMode, PaintCtx, SemanticsCtx, SingleChild, StackSurfaceOptions,
11    Widget, WidgetPodMutVisitor, WidgetPodVisitor,
12};
13use sui_scene::LayerCompositionMode;
14
15use crate::{DefaultTheme, SplitExtent, SplitState, SplitStateSnapshot, ThemeBreakpoints};
16
17/// Constraint-derived presentation class for adaptive workspace layouts.
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19pub enum AdaptiveClass {
20    #[default]
21    Compact,
22    Medium,
23    Expanded,
24}
25
26/// Width thresholds used by adaptive widgets.
27///
28/// Classification uses the widget's own incoming constraints, not a global
29/// window width, so adaptive views also work correctly inside split panes and
30/// embedded surfaces.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct AdaptiveBreakpoints {
33    pub medium: f32,
34    pub expanded: f32,
35}
36
37impl AdaptiveBreakpoints {
38    pub fn new(medium: f32, expanded: f32) -> Self {
39        let medium = medium.max(0.0);
40        Self {
41            medium,
42            expanded: expanded.max(medium),
43        }
44    }
45
46    pub fn classify(self, width: f32) -> AdaptiveClass {
47        if width < self.medium {
48            AdaptiveClass::Compact
49        } else if width < self.expanded {
50            AdaptiveClass::Medium
51        } else {
52            AdaptiveClass::Expanded
53        }
54    }
55}
56
57impl Default for AdaptiveBreakpoints {
58    fn default() -> Self {
59        Self::new(640.0, 1024.0)
60    }
61}
62
63impl From<ThemeBreakpoints> for AdaptiveBreakpoints {
64    fn from(value: ThemeBreakpoints) -> Self {
65        Self::new(value.sm, value.lg)
66    }
67}
68
69fn constraint_width(constraints: Constraints) -> f32 {
70    if constraints.max.width.is_finite() {
71        constraints.max.width
72    } else {
73        constraints.min.width
74    }
75}
76
77fn constraint_height(constraints: Constraints) -> f32 {
78    if constraints.max.height.is_finite() {
79        constraints.max.height
80    } else {
81        constraints.min.height
82    }
83}
84
85fn local_rect(width: f32, height: f32) -> Rect {
86    Rect::from_origin_size(Point::ZERO, Size::new(width.max(0.0), height.max(0.0)))
87}
88
89/// Retains one subtree per presentation class and switches between them based
90/// on the space allocated by the parent.
91///
92/// Each subtree keeps its widget identity while inactive. Focus history is
93/// scoped per presentation and restored when that presentation becomes active
94/// again.
95pub struct AdaptiveView {
96    breakpoints: AdaptiveBreakpoints,
97    active: AdaptiveClass,
98    compact_scope: FocusScopeState,
99    medium_scope: FocusScopeState,
100    expanded_scope: FocusScopeState,
101    compact: SingleChild,
102    medium: SingleChild,
103    expanded: SingleChild,
104    /// Whether a layout has chosen a class yet. The first choice reports
105    /// the class but moves no focus.
106    classified: bool,
107    on_class_change: Option<Box<dyn FnMut(AdaptiveClass)>>,
108}
109
110impl AdaptiveView {
111    pub fn new<C, M, E>(compact: C, medium: M, expanded: E) -> Self
112    where
113        C: Widget + 'static,
114        M: Widget + 'static,
115        E: Widget + 'static,
116    {
117        let compact_scope = FocusScopeState::new();
118        let medium_scope = FocusScopeState::new();
119        let expanded_scope = FocusScopeState::new();
120        Self {
121            breakpoints: AdaptiveBreakpoints::default(),
122            active: AdaptiveClass::Compact,
123            compact: SingleChild::new(FocusScope::new(compact).state(compact_scope.clone())),
124            medium: SingleChild::new(FocusScope::new(medium).state(medium_scope.clone())),
125            expanded: SingleChild::new(FocusScope::new(expanded).state(expanded_scope.clone())),
126            compact_scope,
127            medium_scope,
128            expanded_scope,
129            classified: false,
130            on_class_change: None,
131        }
132    }
133
134    pub fn breakpoints(mut self, breakpoints: AdaptiveBreakpoints) -> Self {
135        self.breakpoints = AdaptiveBreakpoints::new(breakpoints.medium, breakpoints.expanded);
136        self
137    }
138
139    pub fn on_class_change<F>(mut self, on_class_change: F) -> Self
140    where
141        F: FnMut(AdaptiveClass) + 'static,
142    {
143        self.on_class_change = Some(Box::new(on_class_change));
144        self
145    }
146
147    pub fn active_class(&self) -> AdaptiveClass {
148        self.active
149    }
150
151    fn active(&self) -> &SingleChild {
152        match self.active {
153            AdaptiveClass::Compact => &self.compact,
154            AdaptiveClass::Medium => &self.medium,
155            AdaptiveClass::Expanded => &self.expanded,
156        }
157    }
158
159    fn active_mut(&mut self) -> &mut SingleChild {
160        match self.active {
161            AdaptiveClass::Compact => &mut self.compact,
162            AdaptiveClass::Medium => &mut self.medium,
163            AdaptiveClass::Expanded => &mut self.expanded,
164        }
165    }
166
167    fn activate(&mut self, class: AdaptiveClass) {
168        let first = !std::mem::replace(&mut self.classified, true);
169        if self.active == class && !first {
170            return;
171        }
172        self.active = class;
173        if !first {
174            match class {
175                AdaptiveClass::Compact => self.compact_scope.request_restore(),
176                AdaptiveClass::Medium => self.medium_scope.request_restore(),
177                AdaptiveClass::Expanded => self.expanded_scope.request_restore(),
178            };
179        }
180        if let Some(on_class_change) = &mut self.on_class_change {
181            on_class_change(class);
182        }
183    }
184}
185
186impl Widget for AdaptiveView {
187    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
188        self.activate(self.breakpoints.classify(constraint_width(constraints)));
189        self.active_mut().measure(ctx, constraints)
190    }
191
192    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
193        self.active_mut().arrange(ctx, bounds);
194    }
195
196    fn paint(&self, ctx: &mut PaintCtx) {
197        self.active().paint(ctx);
198    }
199
200    fn semantics(&self, ctx: &mut SemanticsCtx) {
201        self.active().semantics(ctx);
202    }
203
204    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
205        self.active().visit_children(visitor);
206    }
207
208    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
209        self.active_mut().visit_children_mut(visitor);
210    }
211}
212
213#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
214pub enum ConstraintOrientation {
215    #[default]
216    Any,
217    Portrait,
218    Landscape,
219}
220
221/// Serializable, locally evaluated container query.
222///
223/// Queries use the widget's incoming constraints and never consult global
224/// window size, so the same view works inside split panes and embedded hosts.
225#[derive(Debug, Clone, Copy, PartialEq)]
226pub struct ConstraintQuery {
227    pub min_width: Option<f32>,
228    pub max_width: Option<f32>,
229    pub min_height: Option<f32>,
230    pub max_height: Option<f32>,
231    pub min_aspect_ratio: Option<f32>,
232    pub max_aspect_ratio: Option<f32>,
233    pub orientation: ConstraintOrientation,
234}
235
236impl ConstraintQuery {
237    pub const fn new() -> Self {
238        Self {
239            min_width: None,
240            max_width: None,
241            min_height: None,
242            max_height: None,
243            min_aspect_ratio: None,
244            max_aspect_ratio: None,
245            orientation: ConstraintOrientation::Any,
246        }
247    }
248
249    pub fn min_width(mut self, width: f32) -> Self {
250        self.min_width = Some(width.max(0.0));
251        self
252    }
253
254    pub fn max_width(mut self, width: f32) -> Self {
255        self.max_width = Some(width.max(0.0));
256        self
257    }
258
259    pub fn min_height(mut self, height: f32) -> Self {
260        self.min_height = Some(height.max(0.0));
261        self
262    }
263
264    pub fn max_height(mut self, height: f32) -> Self {
265        self.max_height = Some(height.max(0.0));
266        self
267    }
268
269    pub fn min_aspect_ratio(mut self, ratio: f32) -> Self {
270        self.min_aspect_ratio = Some(normalize_query_ratio(ratio));
271        self
272    }
273
274    pub fn max_aspect_ratio(mut self, ratio: f32) -> Self {
275        self.max_aspect_ratio = Some(normalize_query_ratio(ratio));
276        self
277    }
278
279    pub const fn orientation(mut self, orientation: ConstraintOrientation) -> Self {
280        self.orientation = orientation;
281        self
282    }
283
284    pub fn matches(self, constraints: Constraints) -> bool {
285        let width = constraint_width(constraints);
286        let height = constraint_height(constraints);
287        let aspect_ratio = if height > 0.0 { width / height } else { width };
288        self.min_width.is_none_or(|minimum| width >= minimum)
289            && self.max_width.is_none_or(|maximum| width <= maximum)
290            && self.min_height.is_none_or(|minimum| height >= minimum)
291            && self.max_height.is_none_or(|maximum| height <= maximum)
292            && self
293                .min_aspect_ratio
294                .is_none_or(|minimum| aspect_ratio >= minimum)
295            && self
296                .max_aspect_ratio
297                .is_none_or(|maximum| aspect_ratio <= maximum)
298            && match self.orientation {
299                ConstraintOrientation::Any => true,
300                ConstraintOrientation::Portrait => height >= width,
301                ConstraintOrientation::Landscape => width > height,
302            }
303    }
304}
305
306impl Default for ConstraintQuery {
307    fn default() -> Self {
308        Self::new()
309    }
310}
311
312fn normalize_query_ratio(ratio: f32) -> f32 {
313    if ratio.is_finite() {
314        ratio.max(0.0)
315    } else {
316        0.0
317    }
318}
319
320struct ConstraintBranch {
321    query: ConstraintQuery,
322    focus: FocusScopeState,
323    child: SingleChild,
324}
325
326impl ConstraintBranch {
327    fn new(query: ConstraintQuery, child: impl Widget + 'static) -> Self {
328        let focus = FocusScopeState::new();
329        Self {
330            query,
331            child: SingleChild::new(FocusScope::new(child).state(focus.clone())),
332            focus,
333        }
334    }
335}
336
337/// Retains each declarative query branch and visits only the first matching one.
338pub struct ConstraintView {
339    branches: Vec<ConstraintBranch>,
340    fallback_focus: FocusScopeState,
341    fallback: SingleChild,
342    active: Option<usize>,
343    /// Whether a layout has picked a branch yet.
344    selected: bool,
345}
346
347impl ConstraintView {
348    pub fn new<W>(fallback: W) -> Self
349    where
350        W: Widget + 'static,
351    {
352        let fallback_focus = FocusScopeState::new();
353        Self {
354            branches: Vec::new(),
355            fallback: SingleChild::new(FocusScope::new(fallback).state(fallback_focus.clone())),
356            fallback_focus,
357            active: None,
358            selected: false,
359        }
360    }
361
362    pub fn when<W>(mut self, query: ConstraintQuery, child: W) -> Self
363    where
364        W: Widget + 'static,
365    {
366        self.branches.push(ConstraintBranch::new(query, child));
367        self
368    }
369
370    pub const fn active_branch(&self) -> Option<usize> {
371        self.active
372    }
373
374    fn active(&self) -> &SingleChild {
375        match self.active {
376            Some(index) => &self.branches[index].child,
377            None => &self.fallback,
378        }
379    }
380
381    fn active_mut(&mut self) -> &mut SingleChild {
382        match self.active {
383            Some(index) => &mut self.branches[index].child,
384            None => &mut self.fallback,
385        }
386    }
387
388    fn select(&mut self, constraints: Constraints) {
389        let active = self
390            .branches
391            .iter()
392            .position(|branch| branch.query.matches(constraints));
393        // The first layout picks a branch without moving focus into it.
394        let first = !std::mem::replace(&mut self.selected, true);
395        if self.active == active || first {
396            self.active = active;
397            return;
398        }
399        self.active = active;
400        if let Some(index) = active {
401            self.branches[index].focus.request_restore();
402        } else {
403            self.fallback_focus.request_restore();
404        }
405    }
406}
407
408impl Widget for ConstraintView {
409    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
410        self.select(constraints);
411        self.active_mut().measure(ctx, constraints)
412    }
413
414    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
415        self.active_mut().arrange(ctx, bounds);
416    }
417
418    fn paint(&self, ctx: &mut PaintCtx) {
419        self.active().paint(ctx);
420    }
421
422    fn semantics(&self, ctx: &mut SemanticsCtx) {
423        self.active().semantics(ctx);
424    }
425
426    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
427        self.active().visit_children(visitor);
428    }
429
430    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
431        self.active_mut().visit_children_mut(visitor);
432    }
433}
434
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub struct ResponsiveSidebarSnapshot {
437    pub expanded: bool,
438    pub overlay_open: bool,
439}
440
441impl Default for ResponsiveSidebarSnapshot {
442    fn default() -> Self {
443        Self {
444            expanded: true,
445            overlay_open: false,
446        }
447    }
448}
449
450/// Cloneable application-owned state for a responsive sidebar.
451#[derive(Clone, Debug)]
452pub struct ResponsiveSidebarState {
453    snapshot: Signal<ResponsiveSidebarSnapshot>,
454}
455
456impl Default for ResponsiveSidebarState {
457    fn default() -> Self {
458        Self::new()
459    }
460}
461
462impl ResponsiveSidebarState {
463    pub fn new() -> Self {
464        Self {
465            snapshot: Signal::named(
466                "ResponsiveSidebarState",
467                ResponsiveSidebarSnapshot::default(),
468            ),
469        }
470    }
471
472    pub fn snapshot(&self) -> ResponsiveSidebarSnapshot {
473        self.snapshot.get()
474    }
475
476    pub fn apply_snapshot(&self, snapshot: ResponsiveSidebarSnapshot) -> bool {
477        self.snapshot.set(snapshot)
478    }
479
480    pub fn set_expanded(&self, expanded: bool) -> bool {
481        self.snapshot
482            .update(|snapshot| snapshot.expanded = expanded)
483    }
484
485    pub fn toggle_expanded(&self) -> bool {
486        self.snapshot
487            .update(|snapshot| snapshot.expanded = !snapshot.expanded)
488    }
489
490    pub fn open_overlay(&self) -> bool {
491        self.snapshot
492            .update(|snapshot| snapshot.overlay_open = true)
493    }
494
495    pub fn close_overlay(&self) -> bool {
496        self.snapshot
497            .update(|snapshot| snapshot.overlay_open = false)
498    }
499
500    pub fn toggle_overlay(&self) -> bool {
501        self.snapshot
502            .update(|snapshot| snapshot.overlay_open = !snapshot.overlay_open)
503    }
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
507pub enum ResponsiveSidebarMode {
508    OverlayClosed,
509    OverlayOpen,
510    Rail,
511    Inline,
512}
513
514/// A stable sidebar/content layout that becomes an overlay drawer in compact
515/// constraints and a collapsible rail or inline pane in wider constraints.
516pub struct ResponsiveSidebar {
517    theme: DefaultTheme,
518    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
519    name: Option<String>,
520    breakpoints: AdaptiveBreakpoints,
521    state: ResponsiveSidebarState,
522    snapshot: ResponsiveSidebarSnapshot,
523    split_state: SplitState,
524    split_snapshot: SplitStateSnapshot,
525    rail_width: f32,
526    overlay_width: f32,
527    mode: ResponsiveSidebarMode,
528    mode_chosen: bool,
529    sidebar_frame: Rect,
530    content_frame: Rect,
531    sidebar_scope: FocusScopeState,
532    content_scope: FocusScopeState,
533    sidebar: SingleChild,
534    content: SingleChild,
535    dismiss_on_scrim: bool,
536    on_mode_change: Option<Box<dyn FnMut(ResponsiveSidebarMode)>>,
537}
538
539impl ResponsiveSidebar {
540    pub fn new<S, C>(sidebar: S, content: C) -> Self
541    where
542        S: Widget + 'static,
543        C: Widget + 'static,
544    {
545        let sidebar_scope = FocusScopeState::new();
546        let content_scope = FocusScopeState::new();
547        let split_state = SplitState::pixels(280.0);
548        Self {
549            theme: DefaultTheme::default(),
550            theme_reader: None,
551            name: None,
552            breakpoints: AdaptiveBreakpoints::default(),
553            state: ResponsiveSidebarState::new(),
554            snapshot: ResponsiveSidebarSnapshot::default(),
555            split_snapshot: split_state.snapshot(),
556            split_state,
557            rail_width: 56.0,
558            overlay_width: 320.0,
559            mode: ResponsiveSidebarMode::OverlayClosed,
560            mode_chosen: false,
561            sidebar_frame: Rect::ZERO,
562            content_frame: Rect::ZERO,
563            sidebar: SingleChild::new(FocusScope::new(sidebar).state(sidebar_scope.clone())),
564            content: SingleChild::new(FocusScope::new(content).state(content_scope.clone())),
565            sidebar_scope,
566            content_scope,
567            dismiss_on_scrim: true,
568            on_mode_change: None,
569        }
570    }
571
572    pub fn theme(mut self, theme: DefaultTheme) -> Self {
573        self.theme = theme;
574        self.theme_reader = None;
575        self
576    }
577
578    /// Resolve the theme on every paint so the overlay scrim follows live
579    /// theme switches.
580    pub fn theme_when<F>(mut self, theme: F) -> Self
581    where
582        F: Fn() -> DefaultTheme + 'static,
583    {
584        self.theme_reader = Some(Box::new(theme));
585        self
586    }
587
588    fn resolved_theme(&self) -> DefaultTheme {
589        self.theme_reader
590            .as_ref()
591            .map(|theme| theme())
592            .unwrap_or(self.theme)
593    }
594
595    pub fn name(mut self, name: impl Into<String>) -> Self {
596        self.name = Some(name.into());
597        self
598    }
599
600    pub fn breakpoints(mut self, breakpoints: AdaptiveBreakpoints) -> Self {
601        self.breakpoints = AdaptiveBreakpoints::new(breakpoints.medium, breakpoints.expanded);
602        self
603    }
604
605    pub fn state(mut self, state: ResponsiveSidebarState) -> Self {
606        self.snapshot = state.snapshot();
607        self.state = state;
608        self
609    }
610
611    pub fn split_state(mut self, state: SplitState) -> Self {
612        self.split_snapshot = state.snapshot();
613        self.split_state = state;
614        self
615    }
616
617    pub fn rail_width(mut self, width: f32) -> Self {
618        self.rail_width = width.max(0.0);
619        self
620    }
621
622    pub fn overlay_width(mut self, width: f32) -> Self {
623        self.overlay_width = width.max(0.0);
624        self
625    }
626
627    pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
628        self.dismiss_on_scrim = dismiss;
629        self
630    }
631
632    pub fn on_mode_change<F>(mut self, on_mode_change: F) -> Self
633    where
634        F: FnMut(ResponsiveSidebarMode) + 'static,
635    {
636        self.on_mode_change = Some(Box::new(on_mode_change));
637        self
638    }
639
640    pub fn current_mode(&self) -> ResponsiveSidebarMode {
641        self.mode
642    }
643
644    pub fn sidebar_state(&self) -> ResponsiveSidebarState {
645        self.state.clone()
646    }
647
648    fn mode_for(&self, class: AdaptiveClass) -> ResponsiveSidebarMode {
649        match class {
650            AdaptiveClass::Compact if self.snapshot.overlay_open => {
651                ResponsiveSidebarMode::OverlayOpen
652            }
653            AdaptiveClass::Compact => ResponsiveSidebarMode::OverlayClosed,
654            AdaptiveClass::Medium | AdaptiveClass::Expanded if self.snapshot.expanded => {
655                ResponsiveSidebarMode::Inline
656            }
657            AdaptiveClass::Medium | AdaptiveClass::Expanded => ResponsiveSidebarMode::Rail,
658        }
659    }
660
661    fn activate(&mut self, mode: ResponsiveSidebarMode) {
662        // The first layout reports its mode but moves no focus.
663        let first = !std::mem::replace(&mut self.mode_chosen, true);
664        if self.mode == mode && !first {
665            return;
666        }
667        self.mode = mode;
668        if !first {
669            match mode {
670                ResponsiveSidebarMode::OverlayOpen
671                | ResponsiveSidebarMode::Rail
672                | ResponsiveSidebarMode::Inline => self.sidebar_scope.request_restore(),
673                ResponsiveSidebarMode::OverlayClosed => self.content_scope.request_restore(),
674            };
675        }
676        if let Some(on_mode_change) = &mut self.on_mode_change {
677            on_mode_change(mode);
678        }
679    }
680
681    fn resolved_inline_width(&self, available: f32) -> f32 {
682        match self.split_snapshot.extent {
683            SplitExtent::Fraction(fraction) => available * fraction,
684            SplitExtent::Pixels(pixels) => pixels,
685        }
686        .clamp(self.rail_width, available)
687    }
688
689    fn sidebar_visible(&self) -> bool {
690        self.mode != ResponsiveSidebarMode::OverlayClosed
691    }
692
693    fn dismiss_overlay(&mut self, ctx: &mut EventCtx) {
694        self.state.close_overlay();
695        self.content_scope.request_restore();
696        ctx.request_measure();
697        ctx.request_paint();
698        ctx.request_semantics();
699    }
700}
701
702impl Widget for ResponsiveSidebar {
703    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
704        if command.get(OVERLAY_DISMISS_REQUEST).is_some()
705            && self.mode == ResponsiveSidebarMode::OverlayOpen
706        {
707            self.dismiss_overlay(ctx);
708            ctx.set_handled();
709        }
710    }
711
712    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
713        self.snapshot = self.state.snapshot();
714        if self.mode == ResponsiveSidebarMode::OverlayOpen {
715            match event {
716                Event::Semantics(semantics)
717                    if semantics.target == ctx.widget_id()
718                        && matches!(semantics.action, SemanticsActionRequest::Collapse) =>
719                {
720                    self.dismiss_overlay(ctx);
721                    ctx.set_handled();
722                }
723                Event::Keyboard(key) if key.state == KeyState::Pressed && key.key == "Escape" => {
724                    self.dismiss_overlay(ctx);
725                    ctx.set_handled();
726                }
727                Event::Pointer(pointer)
728                    if pointer.kind == PointerEventKind::Down
729                        && pointer.button == Some(PointerButton::Primary)
730                        && !self
731                            .sidebar_frame
732                            .translate(ctx.bounds().origin.to_vector())
733                            .contains(pointer.position) =>
734                {
735                    if self.dismiss_on_scrim {
736                        self.dismiss_overlay(ctx);
737                    }
738                    ctx.set_handled();
739                }
740                _ => {}
741            }
742        }
743    }
744
745    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
746        self.snapshot = ctx.observe(&self.state.snapshot);
747        self.split_snapshot = ctx.observe(self.split_state.observable());
748        let width = constraint_width(constraints);
749        self.activate(self.mode_for(self.breakpoints.classify(width)));
750
751        let size = constraints.clamp(Size::new(width, constraint_height(constraints)));
752        let bounds = local_rect(size.width, size.height);
753        match self.mode {
754            ResponsiveSidebarMode::OverlayClosed => {
755                self.sidebar_frame = Rect::ZERO;
756                self.content_frame = bounds;
757                self.content.measure(ctx, Constraints::tight(size));
758            }
759            ResponsiveSidebarMode::OverlayOpen => {
760                self.content_frame = bounds;
761                self.sidebar_frame = local_rect(self.overlay_width.min(size.width), size.height);
762                self.content.measure(ctx, Constraints::tight(size));
763                self.sidebar
764                    .measure(ctx, Constraints::tight(self.sidebar_frame.size));
765            }
766            ResponsiveSidebarMode::Rail | ResponsiveSidebarMode::Inline => {
767                let sidebar_width = if self.mode == ResponsiveSidebarMode::Rail {
768                    self.rail_width.min(size.width)
769                } else {
770                    self.resolved_inline_width(size.width)
771                };
772                self.sidebar_frame = local_rect(sidebar_width, size.height);
773                self.content_frame = Rect::new(
774                    sidebar_width,
775                    0.0,
776                    (size.width - sidebar_width).max(0.0),
777                    size.height,
778                );
779                self.sidebar
780                    .measure(ctx, Constraints::tight(self.sidebar_frame.size));
781                self.content
782                    .measure(ctx, Constraints::tight(self.content_frame.size));
783            }
784        }
785        size
786    }
787
788    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
789        self.content
790            .arrange(ctx, self.content_frame.translate(bounds.origin.to_vector()));
791        if self.sidebar_visible() {
792            self.sidebar
793                .arrange(ctx, self.sidebar_frame.translate(bounds.origin.to_vector()));
794        }
795    }
796
797    fn paint(&self, ctx: &mut PaintCtx) {
798        self.content.paint(ctx);
799        if self.mode == ResponsiveSidebarMode::OverlayOpen {
800            ctx.fill_bounds(self.resolved_theme().surfaces.overlay_scrim);
801        }
802        if self.sidebar_visible() {
803            self.sidebar.paint(ctx);
804        }
805    }
806
807    fn layer_options(&self) -> LayerOptions {
808        LayerOptions {
809            paint_boundary: if self.mode == ResponsiveSidebarMode::OverlayOpen {
810                PaintBoundaryMode::Explicit
811            } else {
812                PaintBoundaryMode::Flat
813            },
814            composition_mode: if self.mode == ResponsiveSidebarMode::OverlayOpen {
815                LayerCompositionMode::Effect
816            } else {
817                LayerCompositionMode::Normal
818            },
819        }
820    }
821
822    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
823        (self.mode == ResponsiveSidebarMode::OverlayOpen).then_some(StackSurfaceOptions {
824            transient: true,
825            ..StackSurfaceOptions::default()
826        })
827    }
828
829    fn overlay_options(&self) -> Option<OverlayOptions> {
830        (self.mode == ResponsiveSidebarMode::OverlayOpen).then_some(
831            OverlayOptions::new(OverlayKind::Sheet)
832                .modal(true)
833                .dismiss(OverlayDismissPolicy {
834                    escape: true,
835                    outside_pointer: self.dismiss_on_scrim,
836                })
837                .focus(OverlayFocusBehavior::CONTAINED),
838        )
839    }
840
841    fn semantics(&self, ctx: &mut SemanticsCtx) {
842        if self.mode == ResponsiveSidebarMode::OverlayOpen {
843            let mut node = SemanticsNode::new(
844                ctx.widget_id(),
845                SemanticsRole::Dialog,
846                self.sidebar_frame
847                    .translate(ctx.bounds().origin.to_vector()),
848            );
849            node.name = self.name.clone().or_else(|| Some("Navigation".to_string()));
850            node.state.expanded = Some(true);
851            node.state.modal = true;
852            node.actions = vec![SemanticsAction::Collapse];
853            ctx.push(node);
854            self.sidebar.semantics(ctx);
855        } else {
856            self.content.semantics(ctx);
857            if self.sidebar_visible() {
858                self.sidebar.semantics(ctx);
859            }
860        }
861    }
862
863    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
864        self.content.visit_children(visitor);
865        if self.sidebar_visible() {
866            self.sidebar.visit_children(visitor);
867        }
868    }
869
870    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
871        self.content.visit_children_mut(visitor);
872        if self.sidebar_visible() {
873            self.sidebar.visit_children_mut(visitor);
874        }
875    }
876}
877
878#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
879pub enum MasterDetailRoute {
880    #[default]
881    Master,
882    Detail,
883}
884
885/// Cloneable navigation state shared by a master-detail layout and the app.
886#[derive(Clone, Debug)]
887pub struct MasterDetailState {
888    route: Signal<MasterDetailRoute>,
889}
890
891impl Default for MasterDetailState {
892    fn default() -> Self {
893        Self::new(MasterDetailRoute::default())
894    }
895}
896
897impl MasterDetailState {
898    pub fn new(route: MasterDetailRoute) -> Self {
899        Self {
900            route: Signal::named("MasterDetailState", route),
901        }
902    }
903
904    pub fn route(&self) -> MasterDetailRoute {
905        self.route.get()
906    }
907
908    pub fn show_master(&self) -> bool {
909        self.route.set(MasterDetailRoute::Master)
910    }
911
912    pub fn show_detail(&self) -> bool {
913        self.route.set(MasterDetailRoute::Detail)
914    }
915
916    pub fn set_route(&self, route: MasterDetailRoute) -> bool {
917        self.route.set(route)
918    }
919}
920
921/// Shows master and detail side-by-side when space permits, and converts to a
922/// focus-restoring navigation stack under compact constraints.
923pub struct MasterDetail {
924    breakpoints: AdaptiveBreakpoints,
925    state: MasterDetailState,
926    route: MasterDetailRoute,
927    split_state: SplitState,
928    split_snapshot: SplitStateSnapshot,
929    compact: bool,
930    /// Whether a layout has chosen between one pane and both yet.
931    measured: bool,
932    master_frame: Rect,
933    detail_frame: Rect,
934    master_scope: FocusScopeState,
935    detail_scope: FocusScopeState,
936    master: SingleChild,
937    detail: SingleChild,
938}
939
940impl MasterDetail {
941    pub fn new<M, D>(master: M, detail: D) -> Self
942    where
943        M: Widget + 'static,
944        D: Widget + 'static,
945    {
946        let master_scope = FocusScopeState::new();
947        let detail_scope = FocusScopeState::new();
948        let split_state = SplitState::pixels(320.0);
949        Self {
950            breakpoints: AdaptiveBreakpoints::default(),
951            state: MasterDetailState::default(),
952            route: MasterDetailRoute::Master,
953            split_snapshot: split_state.snapshot(),
954            split_state,
955            compact: true,
956            measured: false,
957            master_frame: Rect::ZERO,
958            detail_frame: Rect::ZERO,
959            master: SingleChild::new(FocusScope::new(master).state(master_scope.clone())),
960            detail: SingleChild::new(FocusScope::new(detail).state(detail_scope.clone())),
961            master_scope,
962            detail_scope,
963        }
964    }
965
966    pub fn breakpoints(mut self, breakpoints: AdaptiveBreakpoints) -> Self {
967        self.breakpoints = AdaptiveBreakpoints::new(breakpoints.medium, breakpoints.expanded);
968        self
969    }
970
971    pub fn state(mut self, state: MasterDetailState) -> Self {
972        self.route = state.route();
973        self.state = state;
974        self
975    }
976
977    pub fn split_state(mut self, state: SplitState) -> Self {
978        self.split_snapshot = state.snapshot();
979        self.split_state = state;
980        self
981    }
982
983    pub fn navigation_state(&self) -> MasterDetailState {
984        self.state.clone()
985    }
986
987    fn master_width(&self, available: f32) -> f32 {
988        match self.split_snapshot.extent {
989            SplitExtent::Fraction(fraction) => available * fraction,
990            SplitExtent::Pixels(pixels) => pixels,
991        }
992        .clamp(0.0, available)
993    }
994
995    fn route_changed(&mut self, route: MasterDetailRoute) {
996        if self.route == route {
997            return;
998        }
999        self.route = route;
1000        if self.compact {
1001            match route {
1002                MasterDetailRoute::Master => self.master_scope.request_restore(),
1003                MasterDetailRoute::Detail => self.detail_scope.request_restore(),
1004            };
1005        }
1006    }
1007}
1008
1009impl Widget for MasterDetail {
1010    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1011        self.route_changed(self.state.route());
1012        if self.compact
1013            && self.route == MasterDetailRoute::Detail
1014            && matches!(event, Event::Keyboard(key) if key.state == KeyState::Pressed && key.key == "Escape")
1015        {
1016            self.state.show_master();
1017            self.route_changed(MasterDetailRoute::Master);
1018            ctx.request_measure();
1019            ctx.request_paint();
1020            ctx.request_semantics();
1021            ctx.set_handled();
1022        }
1023    }
1024
1025    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1026        let route = ctx.observe(&self.state.route);
1027        self.route_changed(route);
1028        self.split_snapshot = ctx.observe(self.split_state.observable());
1029        let was_compact = self.compact;
1030        self.compact =
1031            self.breakpoints.classify(constraint_width(constraints)) == AdaptiveClass::Compact;
1032        // The first layout settles the policy without moving focus.
1033        let first = !std::mem::replace(&mut self.measured, true);
1034        if self.compact != was_compact && !first {
1035            if self.compact {
1036                match self.route {
1037                    MasterDetailRoute::Master => self.master_scope.request_restore(),
1038                    MasterDetailRoute::Detail => self.detail_scope.request_restore(),
1039                };
1040            } else {
1041                self.detail_scope.request_restore();
1042            }
1043        }
1044
1045        let size = constraints.clamp(Size::new(
1046            constraint_width(constraints),
1047            constraint_height(constraints),
1048        ));
1049        if self.compact {
1050            self.master_frame = local_rect(size.width, size.height);
1051            self.detail_frame = self.master_frame;
1052            match self.route {
1053                MasterDetailRoute::Master => {
1054                    self.master.measure(ctx, Constraints::tight(size));
1055                }
1056                MasterDetailRoute::Detail => {
1057                    self.detail.measure(ctx, Constraints::tight(size));
1058                }
1059            }
1060        } else {
1061            let master_width = self.master_width(size.width);
1062            self.master_frame = local_rect(master_width, size.height);
1063            self.detail_frame = Rect::new(
1064                master_width,
1065                0.0,
1066                (size.width - master_width).max(0.0),
1067                size.height,
1068            );
1069            self.master
1070                .measure(ctx, Constraints::tight(self.master_frame.size));
1071            self.detail
1072                .measure(ctx, Constraints::tight(self.detail_frame.size));
1073        }
1074        size
1075    }
1076
1077    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1078        if !self.compact || self.route == MasterDetailRoute::Master {
1079            self.master
1080                .arrange(ctx, self.master_frame.translate(bounds.origin.to_vector()));
1081        }
1082        if !self.compact || self.route == MasterDetailRoute::Detail {
1083            self.detail
1084                .arrange(ctx, self.detail_frame.translate(bounds.origin.to_vector()));
1085        }
1086    }
1087
1088    fn paint(&self, ctx: &mut PaintCtx) {
1089        if !self.compact || self.route == MasterDetailRoute::Master {
1090            self.master.paint(ctx);
1091        }
1092        if !self.compact || self.route == MasterDetailRoute::Detail {
1093            self.detail.paint(ctx);
1094        }
1095    }
1096
1097    fn semantics(&self, ctx: &mut SemanticsCtx) {
1098        if !self.compact || self.route == MasterDetailRoute::Master {
1099            self.master.semantics(ctx);
1100        }
1101        if !self.compact || self.route == MasterDetailRoute::Detail {
1102            self.detail.semantics(ctx);
1103        }
1104    }
1105
1106    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1107        if !self.compact || self.route == MasterDetailRoute::Master {
1108            self.master.visit_children(visitor);
1109        }
1110        if !self.compact || self.route == MasterDetailRoute::Detail {
1111            self.detail.visit_children(visitor);
1112        }
1113    }
1114
1115    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1116        if !self.compact || self.route == MasterDetailRoute::Master {
1117            self.master.visit_children_mut(visitor);
1118        }
1119        if !self.compact || self.route == MasterDetailRoute::Detail {
1120            self.detail.visit_children_mut(visitor);
1121        }
1122    }
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127    use std::{cell::RefCell, rc::Rc};
1128
1129    use sui_core::{Event, SemanticsNode, SemanticsRole, WindowEvent};
1130    use sui_runtime::{Application, Runtime, WindowBuilder};
1131
1132    use super::*;
1133
1134    struct NamedPane(&'static str);
1135
1136    impl Widget for NamedPane {
1137        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1138            constraints.clamp(Size::new(320.0, 180.0))
1139        }
1140
1141        fn semantics(&self, ctx: &mut SemanticsCtx) {
1142            let mut node = SemanticsNode::new(
1143                ctx.widget_id(),
1144                SemanticsRole::GenericContainer,
1145                ctx.bounds(),
1146            );
1147            node.name = Some(self.0.to_string());
1148            ctx.push(node);
1149        }
1150    }
1151
1152    fn resize(runtime: &mut Runtime, width: f32) {
1153        let window_id = runtime.window_ids()[0];
1154        runtime
1155            .handle_event(
1156                window_id,
1157                Event::Window(WindowEvent::Resized(Size::new(width, 480.0))),
1158            )
1159            .unwrap();
1160    }
1161
1162    fn render_named(runtime: &mut Runtime) -> Vec<(String, sui_core::WidgetId)> {
1163        let window_id = runtime.window_ids()[0];
1164        runtime
1165            .render(window_id)
1166            .unwrap()
1167            .semantics
1168            .into_iter()
1169            .filter_map(|node| node.name.map(|name| (name, node.id)))
1170            .collect()
1171    }
1172
1173    #[test]
1174    fn adaptive_view_uses_local_width_and_retains_variant_identity() {
1175        let mut runtime = Application::new()
1176            .window(
1177                WindowBuilder::new()
1178                    .title("Adaptive")
1179                    .root(AdaptiveView::new(
1180                        NamedPane("compact"),
1181                        NamedPane("medium"),
1182                        NamedPane("expanded"),
1183                    )),
1184            )
1185            .build()
1186            .unwrap();
1187
1188        resize(&mut runtime, 500.0);
1189        let compact = render_named(&mut runtime);
1190        assert_eq!(compact.len(), 1);
1191        assert_eq!(compact[0].0, "compact");
1192        let compact_id = compact[0].1;
1193
1194        resize(&mut runtime, 800.0);
1195        assert_eq!(render_named(&mut runtime)[0].0, "medium");
1196        resize(&mut runtime, 1200.0);
1197        assert_eq!(render_named(&mut runtime)[0].0, "expanded");
1198        resize(&mut runtime, 500.0);
1199        assert_eq!(
1200            render_named(&mut runtime)[0],
1201            ("compact".to_string(), compact_id)
1202        );
1203    }
1204
1205    #[test]
1206    fn constraint_view_matches_first_local_query_and_retains_identity() {
1207        let mut runtime = Application::new()
1208            .window(
1209                WindowBuilder::new().title("Constraint view").root(
1210                    ConstraintView::new(NamedPane("fallback"))
1211                        .when(
1212                            ConstraintQuery::new()
1213                                .min_width(700.0)
1214                                .orientation(ConstraintOrientation::Landscape),
1215                            NamedPane("wide"),
1216                        )
1217                        .when(
1218                            ConstraintQuery::new().max_width(699.0),
1219                            NamedPane("compact"),
1220                        ),
1221                ),
1222            )
1223            .build()
1224            .unwrap();
1225
1226        resize(&mut runtime, 500.0);
1227        let compact = render_named(&mut runtime);
1228        assert_eq!(compact[0].0, "compact");
1229        let compact_id = compact[0].1;
1230
1231        resize(&mut runtime, 900.0);
1232        assert_eq!(render_named(&mut runtime)[0].0, "wide");
1233        resize(&mut runtime, 500.0);
1234        assert_eq!(render_named(&mut runtime)[0].1, compact_id);
1235    }
1236
1237    #[test]
1238    fn master_detail_changes_policy_without_recreating_panes() {
1239        let state = MasterDetailState::default();
1240        let mut runtime = Application::new()
1241            .window(WindowBuilder::new().title("Master Detail").root(
1242                MasterDetail::new(NamedPane("master"), NamedPane("detail")).state(state.clone()),
1243            ))
1244            .build()
1245            .unwrap();
1246
1247        resize(&mut runtime, 900.0);
1248        let expanded = render_named(&mut runtime);
1249        let detail_id = expanded
1250            .iter()
1251            .find(|(name, _)| name == "detail")
1252            .unwrap()
1253            .1;
1254        assert_eq!(expanded.len(), 2);
1255
1256        resize(&mut runtime, 500.0);
1257        assert_eq!(render_named(&mut runtime)[0].0, "master");
1258        state.show_detail();
1259        let compact_detail = render_named(&mut runtime);
1260        assert_eq!(compact_detail, vec![("detail".to_string(), detail_id)]);
1261    }
1262
1263    #[test]
1264    fn responsive_sidebar_tracks_overlay_inline_and_rail_modes() {
1265        let state = ResponsiveSidebarState::new();
1266        let modes = Rc::new(RefCell::new(Vec::new()));
1267        let recorded_modes = Rc::clone(&modes);
1268        let mut runtime = Application::new()
1269            .window(
1270                WindowBuilder::new().title("Sidebar").root(
1271                    ResponsiveSidebar::new(NamedPane("sidebar"), NamedPane("content"))
1272                        .state(state.clone())
1273                        .on_mode_change(move |mode| recorded_modes.borrow_mut().push(mode)),
1274                ),
1275            )
1276            .build()
1277            .unwrap();
1278
1279        resize(&mut runtime, 500.0);
1280        let names = render_named(&mut runtime);
1281        assert_eq!(names.len(), 1);
1282        assert_eq!(names[0].0, "content");
1283
1284        state.open_overlay();
1285        assert_eq!(render_named(&mut runtime).len(), 2);
1286        assert_eq!(
1287            modes.borrow().last(),
1288            Some(&ResponsiveSidebarMode::OverlayOpen)
1289        );
1290
1291        resize(&mut runtime, 800.0);
1292        let _ = render_named(&mut runtime);
1293        assert_eq!(modes.borrow().last(), Some(&ResponsiveSidebarMode::Inline));
1294        state.set_expanded(false);
1295        let _ = render_named(&mut runtime);
1296        assert_eq!(modes.borrow().last(), Some(&ResponsiveSidebarMode::Rail));
1297    }
1298
1299    /// A pane that takes focus.
1300    struct FocusPane(&'static str);
1301
1302    impl Widget for FocusPane {
1303        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1304            constraints.clamp(Size::new(320.0, 180.0))
1305        }
1306
1307        fn accepts_focus(&self) -> bool {
1308            true
1309        }
1310
1311        fn semantics(&self, ctx: &mut SemanticsCtx) {
1312            let mut node = SemanticsNode::new(
1313                ctx.widget_id(),
1314                SemanticsRole::GenericContainer,
1315                ctx.bounds(),
1316            );
1317            node.name = Some(self.0.to_string());
1318            node.actions = vec![sui_core::SemanticsAction::Focus];
1319            ctx.push(node);
1320        }
1321    }
1322
1323    /// Render, then deliver the frames widgets asked for.
1324    fn settle(runtime: &mut Runtime) -> Vec<(String, sui_core::WidgetId)> {
1325        let names = render_named(runtime);
1326        for (window_id, event) in runtime.drain_ready_events() {
1327            runtime.handle_event(window_id, event).unwrap();
1328        }
1329        let _ = render_named(runtime);
1330        names
1331    }
1332
1333    fn id_of(names: &[(String, sui_core::WidgetId)], name: &str) -> sui_core::WidgetId {
1334        names
1335            .iter()
1336            .find(|(candidate, _)| candidate == name)
1337            .map(|(_, id)| *id)
1338            .unwrap_or_else(|| panic!("{name} is laid out"))
1339    }
1340
1341    #[test]
1342    fn responsive_sidebar_reports_its_first_mode_without_taking_focus() {
1343        let state = ResponsiveSidebarState::new();
1344        let modes = Rc::new(RefCell::new(Vec::new()));
1345        let recorded_modes = Rc::clone(&modes);
1346        let mut runtime = Application::new()
1347            .window(
1348                WindowBuilder::new().title("Sidebar").root(
1349                    ResponsiveSidebar::new(FocusPane("sidebar"), FocusPane("content"))
1350                        .state(state.clone())
1351                        .on_mode_change(move |mode| recorded_modes.borrow_mut().push(mode)),
1352                ),
1353            )
1354            .build()
1355            .unwrap();
1356        let window_id = runtime.window_ids()[0];
1357        resize(&mut runtime, 500.0);
1358        let _ = settle(&mut runtime);
1359
1360        // The mode it starts in is reported even though nothing changed.
1361        assert_eq!(&*modes.borrow(), &[ResponsiveSidebarMode::OverlayClosed]);
1362        assert_eq!(runtime.focused_widget(window_id).unwrap(), None);
1363
1364        // Opening the overlay later does move focus into it.
1365        state.open_overlay();
1366        let _ = settle(&mut runtime);
1367        let _ = settle(&mut runtime);
1368        assert!(runtime.focused_widget(window_id).unwrap().is_some());
1369    }
1370
1371    #[test]
1372    fn restoring_focus_leaves_focus_that_moved_elsewhere() {
1373        let mut runtime = Application::new()
1374            .window(
1375                WindowBuilder::new().title("Sidebar").root(
1376                    crate::Stack::vertical()
1377                        .with_child(FocusPane("outside"))
1378                        .with_child(ResponsiveSidebar::new(
1379                            FocusPane("sidebar"),
1380                            FocusPane("content"),
1381                        )),
1382                ),
1383            )
1384            .build()
1385            .unwrap();
1386        let window_id = runtime.window_ids()[0];
1387        resize(&mut runtime, 800.0);
1388        let names = settle(&mut runtime);
1389        let outside = id_of(&names, "outside");
1390        assert!(
1391            runtime
1392                .handle_semantics_action(
1393                    window_id,
1394                    outside,
1395                    sui_core::SemanticsActionRequest::Focus
1396                )
1397                .unwrap()
1398        );
1399
1400        // Narrowing hides the docked sidebar and asks the content to take
1401        // focus back, but focus was never in the sidebar.
1402        resize(&mut runtime, 500.0);
1403        let _ = settle(&mut runtime);
1404        let _ = settle(&mut runtime);
1405        assert_eq!(runtime.focused_widget(window_id).unwrap(), Some(outside));
1406    }
1407}