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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19pub enum AdaptiveClass {
20 #[default]
21 Compact,
22 Medium,
23 Expanded,
24}
25
26#[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
89pub 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 on_class_change: Option<Box<dyn FnMut(AdaptiveClass)>>,
105}
106
107impl AdaptiveView {
108 pub fn new<C, M, E>(compact: C, medium: M, expanded: E) -> Self
109 where
110 C: Widget + 'static,
111 M: Widget + 'static,
112 E: Widget + 'static,
113 {
114 let compact_scope = FocusScopeState::new();
115 let medium_scope = FocusScopeState::new();
116 let expanded_scope = FocusScopeState::new();
117 Self {
118 breakpoints: AdaptiveBreakpoints::default(),
119 active: AdaptiveClass::Compact,
120 compact: SingleChild::new(FocusScope::new(compact).state(compact_scope.clone())),
121 medium: SingleChild::new(FocusScope::new(medium).state(medium_scope.clone())),
122 expanded: SingleChild::new(FocusScope::new(expanded).state(expanded_scope.clone())),
123 compact_scope,
124 medium_scope,
125 expanded_scope,
126 on_class_change: None,
127 }
128 }
129
130 pub fn breakpoints(mut self, breakpoints: AdaptiveBreakpoints) -> Self {
131 self.breakpoints = AdaptiveBreakpoints::new(breakpoints.medium, breakpoints.expanded);
132 self
133 }
134
135 pub fn on_class_change<F>(mut self, on_class_change: F) -> Self
136 where
137 F: FnMut(AdaptiveClass) + 'static,
138 {
139 self.on_class_change = Some(Box::new(on_class_change));
140 self
141 }
142
143 pub fn active_class(&self) -> AdaptiveClass {
144 self.active
145 }
146
147 fn active(&self) -> &SingleChild {
148 match self.active {
149 AdaptiveClass::Compact => &self.compact,
150 AdaptiveClass::Medium => &self.medium,
151 AdaptiveClass::Expanded => &self.expanded,
152 }
153 }
154
155 fn active_mut(&mut self) -> &mut SingleChild {
156 match self.active {
157 AdaptiveClass::Compact => &mut self.compact,
158 AdaptiveClass::Medium => &mut self.medium,
159 AdaptiveClass::Expanded => &mut self.expanded,
160 }
161 }
162
163 fn activate(&mut self, class: AdaptiveClass) {
164 if self.active == class {
165 return;
166 }
167 self.active = class;
168 match class {
169 AdaptiveClass::Compact => self.compact_scope.request_restore(),
170 AdaptiveClass::Medium => self.medium_scope.request_restore(),
171 AdaptiveClass::Expanded => self.expanded_scope.request_restore(),
172 };
173 if let Some(on_class_change) = &mut self.on_class_change {
174 on_class_change(class);
175 }
176 }
177}
178
179impl Widget for AdaptiveView {
180 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
181 self.activate(self.breakpoints.classify(constraint_width(constraints)));
182 self.active_mut().measure(ctx, constraints)
183 }
184
185 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
186 self.active_mut().arrange(ctx, bounds);
187 }
188
189 fn paint(&self, ctx: &mut PaintCtx) {
190 self.active().paint(ctx);
191 }
192
193 fn semantics(&self, ctx: &mut SemanticsCtx) {
194 self.active().semantics(ctx);
195 }
196
197 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
198 self.active().visit_children(visitor);
199 }
200
201 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
202 self.active_mut().visit_children_mut(visitor);
203 }
204}
205
206#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
207pub enum ConstraintOrientation {
208 #[default]
209 Any,
210 Portrait,
211 Landscape,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq)]
219pub struct ConstraintQuery {
220 pub min_width: Option<f32>,
221 pub max_width: Option<f32>,
222 pub min_height: Option<f32>,
223 pub max_height: Option<f32>,
224 pub min_aspect_ratio: Option<f32>,
225 pub max_aspect_ratio: Option<f32>,
226 pub orientation: ConstraintOrientation,
227}
228
229impl ConstraintQuery {
230 pub const fn new() -> Self {
231 Self {
232 min_width: None,
233 max_width: None,
234 min_height: None,
235 max_height: None,
236 min_aspect_ratio: None,
237 max_aspect_ratio: None,
238 orientation: ConstraintOrientation::Any,
239 }
240 }
241
242 pub fn min_width(mut self, width: f32) -> Self {
243 self.min_width = Some(width.max(0.0));
244 self
245 }
246
247 pub fn max_width(mut self, width: f32) -> Self {
248 self.max_width = Some(width.max(0.0));
249 self
250 }
251
252 pub fn min_height(mut self, height: f32) -> Self {
253 self.min_height = Some(height.max(0.0));
254 self
255 }
256
257 pub fn max_height(mut self, height: f32) -> Self {
258 self.max_height = Some(height.max(0.0));
259 self
260 }
261
262 pub fn min_aspect_ratio(mut self, ratio: f32) -> Self {
263 self.min_aspect_ratio = Some(normalize_query_ratio(ratio));
264 self
265 }
266
267 pub fn max_aspect_ratio(mut self, ratio: f32) -> Self {
268 self.max_aspect_ratio = Some(normalize_query_ratio(ratio));
269 self
270 }
271
272 pub const fn orientation(mut self, orientation: ConstraintOrientation) -> Self {
273 self.orientation = orientation;
274 self
275 }
276
277 pub fn matches(self, constraints: Constraints) -> bool {
278 let width = constraint_width(constraints);
279 let height = constraint_height(constraints);
280 let aspect_ratio = if height > 0.0 { width / height } else { width };
281 self.min_width.is_none_or(|minimum| width >= minimum)
282 && self.max_width.is_none_or(|maximum| width <= maximum)
283 && self.min_height.is_none_or(|minimum| height >= minimum)
284 && self.max_height.is_none_or(|maximum| height <= maximum)
285 && self
286 .min_aspect_ratio
287 .is_none_or(|minimum| aspect_ratio >= minimum)
288 && self
289 .max_aspect_ratio
290 .is_none_or(|maximum| aspect_ratio <= maximum)
291 && match self.orientation {
292 ConstraintOrientation::Any => true,
293 ConstraintOrientation::Portrait => height >= width,
294 ConstraintOrientation::Landscape => width > height,
295 }
296 }
297}
298
299impl Default for ConstraintQuery {
300 fn default() -> Self {
301 Self::new()
302 }
303}
304
305fn normalize_query_ratio(ratio: f32) -> f32 {
306 if ratio.is_finite() {
307 ratio.max(0.0)
308 } else {
309 0.0
310 }
311}
312
313struct ConstraintBranch {
314 query: ConstraintQuery,
315 focus: FocusScopeState,
316 child: SingleChild,
317}
318
319impl ConstraintBranch {
320 fn new(query: ConstraintQuery, child: impl Widget + 'static) -> Self {
321 let focus = FocusScopeState::new();
322 Self {
323 query,
324 child: SingleChild::new(FocusScope::new(child).state(focus.clone())),
325 focus,
326 }
327 }
328}
329
330pub struct ConstraintView {
332 branches: Vec<ConstraintBranch>,
333 fallback_focus: FocusScopeState,
334 fallback: SingleChild,
335 active: Option<usize>,
336}
337
338impl ConstraintView {
339 pub fn new<W>(fallback: W) -> Self
340 where
341 W: Widget + 'static,
342 {
343 let fallback_focus = FocusScopeState::new();
344 Self {
345 branches: Vec::new(),
346 fallback: SingleChild::new(FocusScope::new(fallback).state(fallback_focus.clone())),
347 fallback_focus,
348 active: None,
349 }
350 }
351
352 pub fn when<W>(mut self, query: ConstraintQuery, child: W) -> Self
353 where
354 W: Widget + 'static,
355 {
356 self.branches.push(ConstraintBranch::new(query, child));
357 self
358 }
359
360 pub const fn active_branch(&self) -> Option<usize> {
361 self.active
362 }
363
364 fn active(&self) -> &SingleChild {
365 match self.active {
366 Some(index) => &self.branches[index].child,
367 None => &self.fallback,
368 }
369 }
370
371 fn active_mut(&mut self) -> &mut SingleChild {
372 match self.active {
373 Some(index) => &mut self.branches[index].child,
374 None => &mut self.fallback,
375 }
376 }
377
378 fn select(&mut self, constraints: Constraints) {
379 let active = self
380 .branches
381 .iter()
382 .position(|branch| branch.query.matches(constraints));
383 if self.active == active {
384 return;
385 }
386 self.active = active;
387 if let Some(index) = active {
388 self.branches[index].focus.request_restore();
389 } else {
390 self.fallback_focus.request_restore();
391 }
392 }
393}
394
395impl Widget for ConstraintView {
396 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
397 self.select(constraints);
398 self.active_mut().measure(ctx, constraints)
399 }
400
401 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
402 self.active_mut().arrange(ctx, bounds);
403 }
404
405 fn paint(&self, ctx: &mut PaintCtx) {
406 self.active().paint(ctx);
407 }
408
409 fn semantics(&self, ctx: &mut SemanticsCtx) {
410 self.active().semantics(ctx);
411 }
412
413 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
414 self.active().visit_children(visitor);
415 }
416
417 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
418 self.active_mut().visit_children_mut(visitor);
419 }
420}
421
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423pub struct ResponsiveSidebarSnapshot {
424 pub expanded: bool,
425 pub overlay_open: bool,
426}
427
428impl Default for ResponsiveSidebarSnapshot {
429 fn default() -> Self {
430 Self {
431 expanded: true,
432 overlay_open: false,
433 }
434 }
435}
436
437#[derive(Clone, Debug)]
439pub struct ResponsiveSidebarState {
440 snapshot: Signal<ResponsiveSidebarSnapshot>,
441}
442
443impl Default for ResponsiveSidebarState {
444 fn default() -> Self {
445 Self::new()
446 }
447}
448
449impl ResponsiveSidebarState {
450 pub fn new() -> Self {
451 Self {
452 snapshot: Signal::named(
453 "ResponsiveSidebarState",
454 ResponsiveSidebarSnapshot::default(),
455 ),
456 }
457 }
458
459 pub fn snapshot(&self) -> ResponsiveSidebarSnapshot {
460 self.snapshot.get()
461 }
462
463 pub fn apply_snapshot(&self, snapshot: ResponsiveSidebarSnapshot) -> bool {
464 self.snapshot.set(snapshot)
465 }
466
467 pub fn set_expanded(&self, expanded: bool) -> bool {
468 self.snapshot
469 .update(|snapshot| snapshot.expanded = expanded)
470 }
471
472 pub fn toggle_expanded(&self) -> bool {
473 self.snapshot
474 .update(|snapshot| snapshot.expanded = !snapshot.expanded)
475 }
476
477 pub fn open_overlay(&self) -> bool {
478 self.snapshot
479 .update(|snapshot| snapshot.overlay_open = true)
480 }
481
482 pub fn close_overlay(&self) -> bool {
483 self.snapshot
484 .update(|snapshot| snapshot.overlay_open = false)
485 }
486
487 pub fn toggle_overlay(&self) -> bool {
488 self.snapshot
489 .update(|snapshot| snapshot.overlay_open = !snapshot.overlay_open)
490 }
491}
492
493#[derive(Debug, Clone, Copy, PartialEq, Eq)]
494pub enum ResponsiveSidebarMode {
495 OverlayClosed,
496 OverlayOpen,
497 Rail,
498 Inline,
499}
500
501pub struct ResponsiveSidebar {
504 theme: DefaultTheme,
505 name: Option<String>,
506 breakpoints: AdaptiveBreakpoints,
507 state: ResponsiveSidebarState,
508 snapshot: ResponsiveSidebarSnapshot,
509 split_state: SplitState,
510 split_snapshot: SplitStateSnapshot,
511 rail_width: f32,
512 overlay_width: f32,
513 mode: ResponsiveSidebarMode,
514 sidebar_frame: Rect,
515 content_frame: Rect,
516 sidebar_scope: FocusScopeState,
517 content_scope: FocusScopeState,
518 sidebar: SingleChild,
519 content: SingleChild,
520 dismiss_on_scrim: bool,
521 on_mode_change: Option<Box<dyn FnMut(ResponsiveSidebarMode)>>,
522}
523
524impl ResponsiveSidebar {
525 pub fn new<S, C>(sidebar: S, content: C) -> Self
526 where
527 S: Widget + 'static,
528 C: Widget + 'static,
529 {
530 let sidebar_scope = FocusScopeState::new();
531 let content_scope = FocusScopeState::new();
532 let split_state = SplitState::pixels(280.0);
533 Self {
534 theme: DefaultTheme::default(),
535 name: None,
536 breakpoints: AdaptiveBreakpoints::default(),
537 state: ResponsiveSidebarState::new(),
538 snapshot: ResponsiveSidebarSnapshot::default(),
539 split_snapshot: split_state.snapshot(),
540 split_state,
541 rail_width: 56.0,
542 overlay_width: 320.0,
543 mode: ResponsiveSidebarMode::OverlayClosed,
544 sidebar_frame: Rect::ZERO,
545 content_frame: Rect::ZERO,
546 sidebar: SingleChild::new(FocusScope::new(sidebar).state(sidebar_scope.clone())),
547 content: SingleChild::new(FocusScope::new(content).state(content_scope.clone())),
548 sidebar_scope,
549 content_scope,
550 dismiss_on_scrim: true,
551 on_mode_change: None,
552 }
553 }
554
555 pub fn theme(mut self, theme: DefaultTheme) -> Self {
556 self.theme = theme;
557 self
558 }
559
560 pub fn name(mut self, name: impl Into<String>) -> Self {
561 self.name = Some(name.into());
562 self
563 }
564
565 pub fn breakpoints(mut self, breakpoints: AdaptiveBreakpoints) -> Self {
566 self.breakpoints = AdaptiveBreakpoints::new(breakpoints.medium, breakpoints.expanded);
567 self
568 }
569
570 pub fn state(mut self, state: ResponsiveSidebarState) -> Self {
571 self.snapshot = state.snapshot();
572 self.state = state;
573 self
574 }
575
576 pub fn split_state(mut self, state: SplitState) -> Self {
577 self.split_snapshot = state.snapshot();
578 self.split_state = state;
579 self
580 }
581
582 pub fn rail_width(mut self, width: f32) -> Self {
583 self.rail_width = width.max(0.0);
584 self
585 }
586
587 pub fn overlay_width(mut self, width: f32) -> Self {
588 self.overlay_width = width.max(0.0);
589 self
590 }
591
592 pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
593 self.dismiss_on_scrim = dismiss;
594 self
595 }
596
597 pub fn on_mode_change<F>(mut self, on_mode_change: F) -> Self
598 where
599 F: FnMut(ResponsiveSidebarMode) + 'static,
600 {
601 self.on_mode_change = Some(Box::new(on_mode_change));
602 self
603 }
604
605 pub fn current_mode(&self) -> ResponsiveSidebarMode {
606 self.mode
607 }
608
609 pub fn sidebar_state(&self) -> ResponsiveSidebarState {
610 self.state.clone()
611 }
612
613 fn mode_for(&self, class: AdaptiveClass) -> ResponsiveSidebarMode {
614 match class {
615 AdaptiveClass::Compact if self.snapshot.overlay_open => {
616 ResponsiveSidebarMode::OverlayOpen
617 }
618 AdaptiveClass::Compact => ResponsiveSidebarMode::OverlayClosed,
619 AdaptiveClass::Medium | AdaptiveClass::Expanded if self.snapshot.expanded => {
620 ResponsiveSidebarMode::Inline
621 }
622 AdaptiveClass::Medium | AdaptiveClass::Expanded => ResponsiveSidebarMode::Rail,
623 }
624 }
625
626 fn activate(&mut self, mode: ResponsiveSidebarMode) {
627 if self.mode == mode {
628 return;
629 }
630 self.mode = mode;
631 match mode {
632 ResponsiveSidebarMode::OverlayOpen
633 | ResponsiveSidebarMode::Rail
634 | ResponsiveSidebarMode::Inline => self.sidebar_scope.request_restore(),
635 ResponsiveSidebarMode::OverlayClosed => self.content_scope.request_restore(),
636 };
637 if let Some(on_mode_change) = &mut self.on_mode_change {
638 on_mode_change(mode);
639 }
640 }
641
642 fn resolved_inline_width(&self, available: f32) -> f32 {
643 match self.split_snapshot.extent {
644 SplitExtent::Fraction(fraction) => available * fraction,
645 SplitExtent::Pixels(pixels) => pixels,
646 }
647 .clamp(self.rail_width, available)
648 }
649
650 fn sidebar_visible(&self) -> bool {
651 self.mode != ResponsiveSidebarMode::OverlayClosed
652 }
653
654 fn dismiss_overlay(&mut self, ctx: &mut EventCtx) {
655 self.state.close_overlay();
656 self.content_scope.request_restore();
657 ctx.request_measure();
658 ctx.request_paint();
659 ctx.request_semantics();
660 }
661}
662
663impl Widget for ResponsiveSidebar {
664 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
665 if command.get(OVERLAY_DISMISS_REQUEST).is_some()
666 && self.mode == ResponsiveSidebarMode::OverlayOpen
667 {
668 self.dismiss_overlay(ctx);
669 ctx.set_handled();
670 }
671 }
672
673 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
674 self.snapshot = self.state.snapshot();
675 if self.mode == ResponsiveSidebarMode::OverlayOpen {
676 match event {
677 Event::Semantics(semantics)
678 if semantics.target == ctx.widget_id()
679 && matches!(semantics.action, SemanticsActionRequest::Collapse) =>
680 {
681 self.dismiss_overlay(ctx);
682 ctx.set_handled();
683 }
684 Event::Keyboard(key) if key.state == KeyState::Pressed && key.key == "Escape" => {
685 self.dismiss_overlay(ctx);
686 ctx.set_handled();
687 }
688 Event::Pointer(pointer)
689 if pointer.kind == PointerEventKind::Down
690 && pointer.button == Some(PointerButton::Primary)
691 && !self
692 .sidebar_frame
693 .translate(ctx.bounds().origin.to_vector())
694 .contains(pointer.position) =>
695 {
696 if self.dismiss_on_scrim {
697 self.dismiss_overlay(ctx);
698 }
699 ctx.set_handled();
700 }
701 _ => {}
702 }
703 }
704 }
705
706 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
707 self.snapshot = ctx.observe(&self.state.snapshot);
708 self.split_snapshot = ctx.observe(self.split_state.observable());
709 let width = constraint_width(constraints);
710 self.activate(self.mode_for(self.breakpoints.classify(width)));
711
712 let size = constraints.clamp(Size::new(width, constraint_height(constraints)));
713 let bounds = local_rect(size.width, size.height);
714 match self.mode {
715 ResponsiveSidebarMode::OverlayClosed => {
716 self.sidebar_frame = Rect::ZERO;
717 self.content_frame = bounds;
718 self.content.measure(ctx, Constraints::tight(size));
719 }
720 ResponsiveSidebarMode::OverlayOpen => {
721 self.content_frame = bounds;
722 self.sidebar_frame = local_rect(self.overlay_width.min(size.width), size.height);
723 self.content.measure(ctx, Constraints::tight(size));
724 self.sidebar
725 .measure(ctx, Constraints::tight(self.sidebar_frame.size));
726 }
727 ResponsiveSidebarMode::Rail | ResponsiveSidebarMode::Inline => {
728 let sidebar_width = if self.mode == ResponsiveSidebarMode::Rail {
729 self.rail_width.min(size.width)
730 } else {
731 self.resolved_inline_width(size.width)
732 };
733 self.sidebar_frame = local_rect(sidebar_width, size.height);
734 self.content_frame = Rect::new(
735 sidebar_width,
736 0.0,
737 (size.width - sidebar_width).max(0.0),
738 size.height,
739 );
740 self.sidebar
741 .measure(ctx, Constraints::tight(self.sidebar_frame.size));
742 self.content
743 .measure(ctx, Constraints::tight(self.content_frame.size));
744 }
745 }
746 size
747 }
748
749 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
750 self.content
751 .arrange(ctx, self.content_frame.translate(bounds.origin.to_vector()));
752 if self.sidebar_visible() {
753 self.sidebar
754 .arrange(ctx, self.sidebar_frame.translate(bounds.origin.to_vector()));
755 }
756 }
757
758 fn paint(&self, ctx: &mut PaintCtx) {
759 self.content.paint(ctx);
760 if self.mode == ResponsiveSidebarMode::OverlayOpen {
761 ctx.fill_bounds(self.theme.surfaces.overlay_scrim);
762 }
763 if self.sidebar_visible() {
764 self.sidebar.paint(ctx);
765 }
766 }
767
768 fn layer_options(&self) -> LayerOptions {
769 LayerOptions {
770 paint_boundary: if self.mode == ResponsiveSidebarMode::OverlayOpen {
771 PaintBoundaryMode::Explicit
772 } else {
773 PaintBoundaryMode::Flat
774 },
775 composition_mode: if self.mode == ResponsiveSidebarMode::OverlayOpen {
776 LayerCompositionMode::Effect
777 } else {
778 LayerCompositionMode::Normal
779 },
780 }
781 }
782
783 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
784 (self.mode == ResponsiveSidebarMode::OverlayOpen).then_some(StackSurfaceOptions {
785 transient: true,
786 ..StackSurfaceOptions::default()
787 })
788 }
789
790 fn overlay_options(&self) -> Option<OverlayOptions> {
791 (self.mode == ResponsiveSidebarMode::OverlayOpen).then_some(
792 OverlayOptions::new(OverlayKind::Sheet)
793 .modal(true)
794 .dismiss(OverlayDismissPolicy {
795 escape: true,
796 outside_pointer: self.dismiss_on_scrim,
797 })
798 .focus(OverlayFocusBehavior::CONTAINED),
799 )
800 }
801
802 fn semantics(&self, ctx: &mut SemanticsCtx) {
803 if self.mode == ResponsiveSidebarMode::OverlayOpen {
804 let mut node = SemanticsNode::new(
805 ctx.widget_id(),
806 SemanticsRole::Dialog,
807 self.sidebar_frame
808 .translate(ctx.bounds().origin.to_vector()),
809 );
810 node.name = self.name.clone().or_else(|| Some("Navigation".to_string()));
811 node.state.expanded = Some(true);
812 node.state.modal = true;
813 node.actions = vec![SemanticsAction::Collapse];
814 ctx.push(node);
815 self.sidebar.semantics(ctx);
816 } else {
817 self.content.semantics(ctx);
818 if self.sidebar_visible() {
819 self.sidebar.semantics(ctx);
820 }
821 }
822 }
823
824 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
825 self.content.visit_children(visitor);
826 if self.sidebar_visible() {
827 self.sidebar.visit_children(visitor);
828 }
829 }
830
831 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
832 self.content.visit_children_mut(visitor);
833 if self.sidebar_visible() {
834 self.sidebar.visit_children_mut(visitor);
835 }
836 }
837}
838
839#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
840pub enum MasterDetailRoute {
841 #[default]
842 Master,
843 Detail,
844}
845
846#[derive(Clone, Debug)]
848pub struct MasterDetailState {
849 route: Signal<MasterDetailRoute>,
850}
851
852impl Default for MasterDetailState {
853 fn default() -> Self {
854 Self::new(MasterDetailRoute::default())
855 }
856}
857
858impl MasterDetailState {
859 pub fn new(route: MasterDetailRoute) -> Self {
860 Self {
861 route: Signal::named("MasterDetailState", route),
862 }
863 }
864
865 pub fn route(&self) -> MasterDetailRoute {
866 self.route.get()
867 }
868
869 pub fn show_master(&self) -> bool {
870 self.route.set(MasterDetailRoute::Master)
871 }
872
873 pub fn show_detail(&self) -> bool {
874 self.route.set(MasterDetailRoute::Detail)
875 }
876
877 pub fn set_route(&self, route: MasterDetailRoute) -> bool {
878 self.route.set(route)
879 }
880}
881
882pub struct MasterDetail {
885 breakpoints: AdaptiveBreakpoints,
886 state: MasterDetailState,
887 route: MasterDetailRoute,
888 split_state: SplitState,
889 split_snapshot: SplitStateSnapshot,
890 compact: bool,
891 master_frame: Rect,
892 detail_frame: Rect,
893 master_scope: FocusScopeState,
894 detail_scope: FocusScopeState,
895 master: SingleChild,
896 detail: SingleChild,
897}
898
899impl MasterDetail {
900 pub fn new<M, D>(master: M, detail: D) -> Self
901 where
902 M: Widget + 'static,
903 D: Widget + 'static,
904 {
905 let master_scope = FocusScopeState::new();
906 let detail_scope = FocusScopeState::new();
907 let split_state = SplitState::pixels(320.0);
908 Self {
909 breakpoints: AdaptiveBreakpoints::default(),
910 state: MasterDetailState::default(),
911 route: MasterDetailRoute::Master,
912 split_snapshot: split_state.snapshot(),
913 split_state,
914 compact: true,
915 master_frame: Rect::ZERO,
916 detail_frame: Rect::ZERO,
917 master: SingleChild::new(FocusScope::new(master).state(master_scope.clone())),
918 detail: SingleChild::new(FocusScope::new(detail).state(detail_scope.clone())),
919 master_scope,
920 detail_scope,
921 }
922 }
923
924 pub fn breakpoints(mut self, breakpoints: AdaptiveBreakpoints) -> Self {
925 self.breakpoints = AdaptiveBreakpoints::new(breakpoints.medium, breakpoints.expanded);
926 self
927 }
928
929 pub fn state(mut self, state: MasterDetailState) -> Self {
930 self.route = state.route();
931 self.state = state;
932 self
933 }
934
935 pub fn split_state(mut self, state: SplitState) -> Self {
936 self.split_snapshot = state.snapshot();
937 self.split_state = state;
938 self
939 }
940
941 pub fn navigation_state(&self) -> MasterDetailState {
942 self.state.clone()
943 }
944
945 fn master_width(&self, available: f32) -> f32 {
946 match self.split_snapshot.extent {
947 SplitExtent::Fraction(fraction) => available * fraction,
948 SplitExtent::Pixels(pixels) => pixels,
949 }
950 .clamp(0.0, available)
951 }
952
953 fn route_changed(&mut self, route: MasterDetailRoute) {
954 if self.route == route {
955 return;
956 }
957 self.route = route;
958 if self.compact {
959 match route {
960 MasterDetailRoute::Master => self.master_scope.request_restore(),
961 MasterDetailRoute::Detail => self.detail_scope.request_restore(),
962 };
963 }
964 }
965}
966
967impl Widget for MasterDetail {
968 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
969 self.route_changed(self.state.route());
970 if self.compact
971 && self.route == MasterDetailRoute::Detail
972 && matches!(event, Event::Keyboard(key) if key.state == KeyState::Pressed && key.key == "Escape")
973 {
974 self.state.show_master();
975 self.route_changed(MasterDetailRoute::Master);
976 ctx.request_measure();
977 ctx.request_paint();
978 ctx.request_semantics();
979 ctx.set_handled();
980 }
981 }
982
983 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
984 let route = ctx.observe(&self.state.route);
985 self.route_changed(route);
986 self.split_snapshot = ctx.observe(self.split_state.observable());
987 let was_compact = self.compact;
988 self.compact =
989 self.breakpoints.classify(constraint_width(constraints)) == AdaptiveClass::Compact;
990 if self.compact != was_compact {
991 if self.compact {
992 match self.route {
993 MasterDetailRoute::Master => self.master_scope.request_restore(),
994 MasterDetailRoute::Detail => self.detail_scope.request_restore(),
995 };
996 } else {
997 self.detail_scope.request_restore();
998 }
999 }
1000
1001 let size = constraints.clamp(Size::new(
1002 constraint_width(constraints),
1003 constraint_height(constraints),
1004 ));
1005 if self.compact {
1006 self.master_frame = local_rect(size.width, size.height);
1007 self.detail_frame = self.master_frame;
1008 match self.route {
1009 MasterDetailRoute::Master => {
1010 self.master.measure(ctx, Constraints::tight(size));
1011 }
1012 MasterDetailRoute::Detail => {
1013 self.detail.measure(ctx, Constraints::tight(size));
1014 }
1015 }
1016 } else {
1017 let master_width = self.master_width(size.width);
1018 self.master_frame = local_rect(master_width, size.height);
1019 self.detail_frame = Rect::new(
1020 master_width,
1021 0.0,
1022 (size.width - master_width).max(0.0),
1023 size.height,
1024 );
1025 self.master
1026 .measure(ctx, Constraints::tight(self.master_frame.size));
1027 self.detail
1028 .measure(ctx, Constraints::tight(self.detail_frame.size));
1029 }
1030 size
1031 }
1032
1033 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1034 if !self.compact || self.route == MasterDetailRoute::Master {
1035 self.master
1036 .arrange(ctx, self.master_frame.translate(bounds.origin.to_vector()));
1037 }
1038 if !self.compact || self.route == MasterDetailRoute::Detail {
1039 self.detail
1040 .arrange(ctx, self.detail_frame.translate(bounds.origin.to_vector()));
1041 }
1042 }
1043
1044 fn paint(&self, ctx: &mut PaintCtx) {
1045 if !self.compact || self.route == MasterDetailRoute::Master {
1046 self.master.paint(ctx);
1047 }
1048 if !self.compact || self.route == MasterDetailRoute::Detail {
1049 self.detail.paint(ctx);
1050 }
1051 }
1052
1053 fn semantics(&self, ctx: &mut SemanticsCtx) {
1054 if !self.compact || self.route == MasterDetailRoute::Master {
1055 self.master.semantics(ctx);
1056 }
1057 if !self.compact || self.route == MasterDetailRoute::Detail {
1058 self.detail.semantics(ctx);
1059 }
1060 }
1061
1062 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1063 if !self.compact || self.route == MasterDetailRoute::Master {
1064 self.master.visit_children(visitor);
1065 }
1066 if !self.compact || self.route == MasterDetailRoute::Detail {
1067 self.detail.visit_children(visitor);
1068 }
1069 }
1070
1071 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1072 if !self.compact || self.route == MasterDetailRoute::Master {
1073 self.master.visit_children_mut(visitor);
1074 }
1075 if !self.compact || self.route == MasterDetailRoute::Detail {
1076 self.detail.visit_children_mut(visitor);
1077 }
1078 }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083 use std::{cell::RefCell, rc::Rc};
1084
1085 use sui_core::{Event, SemanticsNode, SemanticsRole, WindowEvent};
1086 use sui_runtime::{Application, Runtime, WindowBuilder};
1087
1088 use super::*;
1089
1090 struct NamedPane(&'static str);
1091
1092 impl Widget for NamedPane {
1093 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1094 constraints.clamp(Size::new(320.0, 180.0))
1095 }
1096
1097 fn semantics(&self, ctx: &mut SemanticsCtx) {
1098 let mut node = SemanticsNode::new(
1099 ctx.widget_id(),
1100 SemanticsRole::GenericContainer,
1101 ctx.bounds(),
1102 );
1103 node.name = Some(self.0.to_string());
1104 ctx.push(node);
1105 }
1106 }
1107
1108 fn resize(runtime: &mut Runtime, width: f32) {
1109 let window_id = runtime.window_ids()[0];
1110 runtime
1111 .handle_event(
1112 window_id,
1113 Event::Window(WindowEvent::Resized(Size::new(width, 480.0))),
1114 )
1115 .unwrap();
1116 }
1117
1118 fn render_named(runtime: &mut Runtime) -> Vec<(String, sui_core::WidgetId)> {
1119 let window_id = runtime.window_ids()[0];
1120 runtime
1121 .render(window_id)
1122 .unwrap()
1123 .semantics
1124 .into_iter()
1125 .filter_map(|node| node.name.map(|name| (name, node.id)))
1126 .collect()
1127 }
1128
1129 #[test]
1130 fn adaptive_view_uses_local_width_and_retains_variant_identity() {
1131 let mut runtime = Application::new()
1132 .window(
1133 WindowBuilder::new()
1134 .title("Adaptive")
1135 .root(AdaptiveView::new(
1136 NamedPane("compact"),
1137 NamedPane("medium"),
1138 NamedPane("expanded"),
1139 )),
1140 )
1141 .build()
1142 .unwrap();
1143
1144 resize(&mut runtime, 500.0);
1145 let compact = render_named(&mut runtime);
1146 assert_eq!(compact.len(), 1);
1147 assert_eq!(compact[0].0, "compact");
1148 let compact_id = compact[0].1;
1149
1150 resize(&mut runtime, 800.0);
1151 assert_eq!(render_named(&mut runtime)[0].0, "medium");
1152 resize(&mut runtime, 1200.0);
1153 assert_eq!(render_named(&mut runtime)[0].0, "expanded");
1154 resize(&mut runtime, 500.0);
1155 assert_eq!(
1156 render_named(&mut runtime)[0],
1157 ("compact".to_string(), compact_id)
1158 );
1159 }
1160
1161 #[test]
1162 fn constraint_view_matches_first_local_query_and_retains_identity() {
1163 let mut runtime = Application::new()
1164 .window(
1165 WindowBuilder::new().title("Constraint view").root(
1166 ConstraintView::new(NamedPane("fallback"))
1167 .when(
1168 ConstraintQuery::new()
1169 .min_width(700.0)
1170 .orientation(ConstraintOrientation::Landscape),
1171 NamedPane("wide"),
1172 )
1173 .when(
1174 ConstraintQuery::new().max_width(699.0),
1175 NamedPane("compact"),
1176 ),
1177 ),
1178 )
1179 .build()
1180 .unwrap();
1181
1182 resize(&mut runtime, 500.0);
1183 let compact = render_named(&mut runtime);
1184 assert_eq!(compact[0].0, "compact");
1185 let compact_id = compact[0].1;
1186
1187 resize(&mut runtime, 900.0);
1188 assert_eq!(render_named(&mut runtime)[0].0, "wide");
1189 resize(&mut runtime, 500.0);
1190 assert_eq!(render_named(&mut runtime)[0].1, compact_id);
1191 }
1192
1193 #[test]
1194 fn master_detail_changes_policy_without_recreating_panes() {
1195 let state = MasterDetailState::default();
1196 let mut runtime = Application::new()
1197 .window(WindowBuilder::new().title("Master Detail").root(
1198 MasterDetail::new(NamedPane("master"), NamedPane("detail")).state(state.clone()),
1199 ))
1200 .build()
1201 .unwrap();
1202
1203 resize(&mut runtime, 900.0);
1204 let expanded = render_named(&mut runtime);
1205 let detail_id = expanded
1206 .iter()
1207 .find(|(name, _)| name == "detail")
1208 .unwrap()
1209 .1;
1210 assert_eq!(expanded.len(), 2);
1211
1212 resize(&mut runtime, 500.0);
1213 assert_eq!(render_named(&mut runtime)[0].0, "master");
1214 state.show_detail();
1215 let compact_detail = render_named(&mut runtime);
1216 assert_eq!(compact_detail, vec![("detail".to_string(), detail_id)]);
1217 }
1218
1219 #[test]
1220 fn responsive_sidebar_tracks_overlay_inline_and_rail_modes() {
1221 let state = ResponsiveSidebarState::new();
1222 let modes = Rc::new(RefCell::new(Vec::new()));
1223 let recorded_modes = Rc::clone(&modes);
1224 let mut runtime = Application::new()
1225 .window(
1226 WindowBuilder::new().title("Sidebar").root(
1227 ResponsiveSidebar::new(NamedPane("sidebar"), NamedPane("content"))
1228 .state(state.clone())
1229 .on_mode_change(move |mode| recorded_modes.borrow_mut().push(mode)),
1230 ),
1231 )
1232 .build()
1233 .unwrap();
1234
1235 resize(&mut runtime, 500.0);
1236 let names = render_named(&mut runtime);
1237 assert_eq!(names.len(), 1);
1238 assert_eq!(names[0].0, "content");
1239
1240 state.open_overlay();
1241 assert_eq!(render_named(&mut runtime).len(), 2);
1242 assert_eq!(
1243 modes.borrow().last(),
1244 Some(&ResponsiveSidebarMode::OverlayOpen)
1245 );
1246
1247 resize(&mut runtime, 800.0);
1248 let _ = render_named(&mut runtime);
1249 assert_eq!(modes.borrow().last(), Some(&ResponsiveSidebarMode::Inline));
1250 state.set_expanded(false);
1251 let _ = render_named(&mut runtime);
1252 assert_eq!(modes.borrow().last(), Some(&ResponsiveSidebarMode::Rail));
1253 }
1254}