1use std::any::Any;
67
68use iced::advanced::layout::{self, Layout};
69use iced::advanced::widget::operation::scrollable::AbsoluteOffset;
70use iced::advanced::widget::operation::{Focusable, Scrollable};
71use iced::advanced::widget::{Operation, Tree, Widget, tree};
72use iced::advanced::{Clipboard, Shell, overlay, renderer};
73use iced::keyboard::key::Named;
74use iced::widget::{self, center, column, container, mouse_area, row, stack, text};
75use iced::{
76 Alignment, Background, Border, Color, Element, Event, Length, Padding, Point, Rectangle,
77 Renderer, Size as Bounds, Theme, Vector, keyboard, mouse,
78};
79
80use crate::focus;
81use crate::keys::{self, Chord, Keymap};
82use crate::overlay::anchored;
83use crate::primitives::button::{self, Size as ButtonSize};
84use crate::primitives::icon_button::icon_button;
85use crate::primitives::scroll_area::scroll_area;
86use crate::solid::solid;
87use crate::theme::{Tokens, fade, heading, radius, space, supporting, text_size};
88
89pub const DEFAULT_ID: widget::Id = widget::Id::new("iced-cube-dialog");
91
92pub const CLOSE_BUTTON_ID: widget::Id = widget::Id::new("iced-cube-dialog-close");
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
97pub enum Size {
98 Sm,
99 #[default]
100 Md,
101 Lg,
102}
103
104impl Size {
105 pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
106
107 pub const fn width(self) -> f32 {
109 match self {
110 Size::Sm => 384.0,
111 Size::Md => 512.0,
112 Size::Lg => 640.0,
113 }
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119pub enum Action {
120 Close,
121 Confirm,
122 FocusNext,
123 FocusPrevious,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128pub enum Direction {
129 Next,
130 Previous,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
135pub enum Effect {
136 Dismiss,
138 Confirm,
140 Focus(Direction),
142}
143
144impl Action {
145 pub fn effect(self, dismiss_on_escape: bool) -> Option<Effect> {
148 match self {
149 Action::Close => dismiss_on_escape.then_some(Effect::Dismiss),
150 Action::Confirm => Some(Effect::Confirm),
151 Action::FocusNext => Some(Effect::Focus(Direction::Next)),
152 Action::FocusPrevious => Some(Effect::Focus(Direction::Previous)),
153 }
154 }
155}
156
157impl keys::Action for Action {
158 const ALL: &'static [Self] = &[
159 Action::Close,
160 Action::Confirm,
161 Action::FocusNext,
162 Action::FocusPrevious,
163 ];
164
165 fn defaults() -> Keymap<Self> {
166 default_keymap()
167 }
168
169 fn name(self) -> &'static str {
170 match self {
171 Action::Close => "Close",
172 Action::Confirm => "Confirm",
173 Action::FocusNext => "FocusNext",
174 Action::FocusPrevious => "FocusPrevious",
175 }
176 }
177
178 fn description(self) -> &'static str {
179 match self {
180 Action::Close => "Dismisses the dialog, unless Escape dismissal is turned off.",
181 Action::Confirm => {
182 "Sends the dialog's confirm message. An alert dialog's destructive action only runs on Enter when it opts in."
183 }
184 Action::FocusNext => {
185 "Focuses the next field, button or control in the dialog, wrapping from the last to the first."
186 }
187 Action::FocusPrevious => {
188 "Focuses the previous field, button or control in the dialog, wrapping from the first to the last."
189 }
190 }
191 }
192}
193
194pub fn default_keymap() -> Keymap<Action> {
211 Keymap::new()
212 .bind(Chord::named(Named::Escape), Action::Close)
213 .bind(Chord::named(Named::Enter), Action::Confirm)
214 .bind(Chord::named(Named::Tab), Action::FocusNext)
215 .bind(Chord::named(Named::Tab).shift(), Action::FocusPrevious)
216}
217
218pub struct Dialog<'a, Message> {
220 base: Element<'a, Message>,
221 open: bool,
222 title: Option<text::Fragment<'a>>,
223 description: Option<text::Fragment<'a>>,
224 body: Option<Element<'a, Message>>,
225 actions: Vec<Element<'a, Message>>,
226 on_dismiss: Option<Message>,
227 on_confirm: Option<Message>,
228 dismiss_on_escape: bool,
229 dismiss_on_scrim: bool,
230 close_button: bool,
231 width: f32,
232 max_height: f32,
233 id: widget::Id,
234 keymap: Keymap<Action>,
235 pass_through: Vec<Chord>,
236}
237
238impl<Message> std::fmt::Debug for Dialog<'_, Message> {
239 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
240 f.debug_struct("Dialog")
241 .field("open", &self.open)
242 .field("title", &self.title)
243 .field("description", &self.description)
244 .field("actions", &self.actions.len())
245 .field("dismiss_on_escape", &self.dismiss_on_escape)
246 .field("dismiss_on_scrim", &self.dismiss_on_scrim)
247 .field("close_button", &self.close_button)
248 .field("width", &self.width)
249 .field("max_height", &self.max_height)
250 .field("id", &self.id)
251 .field("pass_through", &self.pass_through)
252 .finish_non_exhaustive()
253 }
254}
255
256pub fn dialog<'a, Message>(base: impl Into<Element<'a, Message>>) -> Dialog<'a, Message> {
259 Dialog {
260 base: base.into(),
261 open: false,
262 title: None,
263 description: None,
264 body: None,
265 actions: Vec::new(),
266 on_dismiss: None,
267 on_confirm: None,
268 dismiss_on_escape: true,
269 dismiss_on_scrim: true,
270 close_button: true,
271 width: Size::default().width(),
272 max_height: f32::INFINITY,
273 id: DEFAULT_ID,
274 keymap: default_keymap(),
275 pass_through: Vec::new(),
276 }
277}
278
279impl<'a, Message> Dialog<'a, Message> {
280 pub fn open(mut self, open: bool) -> Self {
281 self.open = open;
282 self
283 }
284
285 pub fn title(mut self, title: impl text::IntoFragment<'a>) -> Self {
286 self.title = Some(title.into_fragment());
287 self
288 }
289
290 pub fn description(mut self, description: impl text::IntoFragment<'a>) -> Self {
292 self.description = Some(description.into_fragment());
293 self
294 }
295
296 pub fn body(mut self, body: impl Into<Element<'a, Message>>) -> Self {
299 self.body = Some(body.into());
300 self
301 }
302
303 pub fn action(mut self, action: impl Into<Element<'a, Message>>) -> Self {
306 self.actions.push(action.into());
307 self
308 }
309
310 pub fn on_dismiss(mut self, message: Message) -> Self {
314 self.on_dismiss = Some(message);
315 self
316 }
317
318 pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
320 self.dismiss_on_escape = dismiss;
321 self
322 }
323
324 pub fn on_confirm(mut self, message: Message) -> Self {
328 self.on_confirm = Some(message);
329 self
330 }
331
332 pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
335 self.dismiss_on_scrim = dismiss;
336 self
337 }
338
339 pub fn close_button(mut self, show: bool) -> Self {
342 self.close_button = show;
343 self
344 }
345
346 pub fn size(mut self, size: Size) -> Self {
348 self.width = size.width();
349 self
350 }
351
352 pub fn width(mut self, width: f32) -> Self {
354 self.width = width;
355 self
356 }
357
358 pub fn max_height(mut self, height: f32) -> Self {
361 self.max_height = height;
362 self
363 }
364
365 pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
368 self.id = id.into();
369 self
370 }
371
372 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
374 self.keymap = keymap;
375 self
376 }
377
378 pub fn pass_through(mut self, chords: impl IntoIterator<Item = Chord>) -> Self {
381 self.pass_through = chords.into_iter().collect();
382 self
383 }
384
385 pub fn is_open(&self) -> bool {
386 self.open
387 }
388}
389
390impl<'a, Message: Clone + 'a> From<Dialog<'a, Message>> for Element<'a, Message> {
391 fn from(dialog: Dialog<'a, Message>) -> Self {
392 let Dialog {
393 base,
394 open,
395 title,
396 description,
397 body,
398 actions,
399 on_dismiss,
400 on_confirm,
401 dismiss_on_escape,
402 dismiss_on_scrim,
403 close_button,
404 width,
405 max_height,
406 id,
407 keymap,
408 pass_through,
409 } = dialog;
410
411 let guarded = Element::new(Guard {
412 content: base,
413 blocked: open,
414 });
415
416 let mut layers = stack![guarded].width(Length::Fill).height(Length::Fill);
419
420 if open {
421 let surface = surface(
422 title,
423 description,
424 body,
425 actions,
426 close_button.then(|| on_dismiss.clone()),
427 Bounds::new(width, max_height),
428 id.clone(),
429 );
430 let scrim = center(solid(surface))
431 .padding(space::LG)
432 .style(|theme| scrim_style(&Tokens::of(theme)));
433 let layer: Element<'a, Message> = match on_dismiss.clone().filter(|_| dismiss_on_scrim)
434 {
435 Some(message) => solid(mouse_area(scrim).on_press(message)),
436 None => solid(scrim),
437 };
438 layers = layers.push(layer);
439 }
440
441 Element::new(Scope {
442 content: layers.into(),
443 open,
444 surface: id,
445 keymap,
446 pass_through,
447 on_escape: on_dismiss.filter(|_| dismiss_on_escape),
448 on_confirm,
449 })
450 }
451}
452
453fn surface<'a, Message: Clone + 'a>(
454 title: Option<text::Fragment<'a>>,
455 description: Option<text::Fragment<'a>>,
456 body: Option<Element<'a, Message>>,
457 actions: Vec<Element<'a, Message>>,
458 close: Option<Option<Message>>,
459 max: Bounds,
460 id: widget::Id,
461) -> Element<'a, Message> {
462 let mut header = column![].spacing(space::XS);
463 if let Some(title) = title {
464 header = header.push(heading(title, text_size::LG));
465 }
466 if let Some(description) = description {
467 header = header.push(supporting(description));
468 }
469 if close.is_some() {
471 header = header.padding(Padding::ZERO.right(space::XL));
472 }
473
474 let mut parts: Vec<Element<'a, Message>> = vec![header.into()];
475 let mut flexible = None;
476 if let Some(body) = body {
477 flexible = Some(parts.len());
478 parts.push(scroll_area(body).width(Length::Fill).into());
479 }
480 if !actions.is_empty() {
481 parts.push(
482 container(row(actions).spacing(space::SM))
483 .width(Length::Fill)
484 .align_x(Alignment::End)
485 .into(),
486 );
487 }
488 let content = Element::new(Pinned {
489 children: parts,
490 flexible,
491 spacing: space::LG,
492 });
493
494 let mut layers = stack![container(content).padding(space::XL)];
495 if let Some(on_press) = close {
496 layers = layers.push(
497 container(
498 icon_button(crate::lucide!(X))
499 .label("Close")
500 .tooltip(None)
501 .size(ButtonSize::Sm)
502 .id(CLOSE_BUTTON_ID)
503 .on_press_maybe(on_press),
504 )
505 .padding(space::MD)
506 .width(Length::Fill)
507 .align_x(Alignment::End),
508 );
509 }
510
511 container(layers)
512 .id(id)
513 .width(Length::Fill)
514 .max_width(max.width)
515 .max_height(max.height)
516 .style(|theme| surface_style(&Tokens::of(theme)))
517 .into()
518}
519
520fn room(available: f32, fixed: f32, spacing: f32, count: usize) -> f32 {
523 let gaps = spacing * count.saturating_sub(1) as f32;
524 (available - fixed - gaps).max(0.0)
525}
526
527struct Pinned<'a, Message> {
531 children: Vec<Element<'a, Message>>,
532 flexible: Option<usize>,
533 spacing: f32,
534}
535
536impl<Message> Widget<Message, Theme, Renderer> for Pinned<'_, Message> {
537 fn size(&self) -> Bounds<Length> {
538 Bounds::new(Length::Fill, Length::Shrink)
539 }
540
541 fn children(&self) -> Vec<Tree> {
542 self.children.iter().map(Tree::new).collect()
543 }
544
545 fn diff(&self, tree: &mut Tree) {
546 tree.diff_children(&self.children);
547 }
548
549 fn layout(
550 &mut self,
551 tree: &mut Tree,
552 renderer: &Renderer,
553 limits: &layout::Limits,
554 ) -> layout::Node {
555 let max = limits.max();
556 let loose = layout::Limits::new(Bounds::ZERO, max);
557 let mut nodes: Vec<Option<layout::Node>> = self
558 .children
559 .iter_mut()
560 .zip(&mut tree.children)
561 .enumerate()
562 .map(|(index, (child, tree))| {
563 (self.flexible != Some(index))
564 .then(|| child.as_widget_mut().layout(tree, renderer, &loose))
565 })
566 .collect();
567
568 if let Some(index) = self.flexible {
569 let fixed = nodes.iter().flatten().map(|node| node.size().height).sum();
570 let height = room(max.height, fixed, self.spacing, self.children.len());
571 let limits = layout::Limits::new(Bounds::ZERO, Bounds::new(max.width, height));
572 if let (Some(child), Some(tree), Some(slot)) = (
573 self.children.get_mut(index),
574 tree.children.get_mut(index),
575 nodes.get_mut(index),
576 ) {
577 *slot = Some(child.as_widget_mut().layout(tree, renderer, &limits));
578 }
579 }
580
581 let (nodes, size) = stack_vertically(nodes.into_iter().flatten(), self.spacing);
582 layout::Node::with_children(limits.resolve(Length::Fill, Length::Shrink, size), nodes)
583 }
584
585 fn draw(
586 &self,
587 tree: &Tree,
588 renderer: &mut Renderer,
589 theme: &Theme,
590 style: &renderer::Style,
591 layout: Layout<'_>,
592 cursor: mouse::Cursor,
593 viewport: &Rectangle,
594 ) {
595 for ((child, tree), layout) in self
596 .children
597 .iter()
598 .zip(&tree.children)
599 .zip(layout.children())
600 {
601 child
602 .as_widget()
603 .draw(tree, renderer, theme, style, layout, cursor, viewport);
604 }
605 }
606
607 fn operate(
608 &mut self,
609 tree: &mut Tree,
610 layout: Layout<'_>,
611 renderer: &Renderer,
612 operation: &mut dyn Operation,
613 ) {
614 operate_all(&mut self.children, tree, layout, renderer, operation);
615 }
616
617 fn update(
618 &mut self,
619 tree: &mut Tree,
620 event: &Event,
621 layout: Layout<'_>,
622 cursor: mouse::Cursor,
623 renderer: &Renderer,
624 clipboard: &mut dyn Clipboard,
625 shell: &mut Shell<'_, Message>,
626 viewport: &Rectangle,
627 ) {
628 for ((child, tree), layout) in self
629 .children
630 .iter_mut()
631 .zip(&mut tree.children)
632 .zip(layout.children())
633 {
634 child.as_widget_mut().update(
635 tree, event, layout, cursor, renderer, clipboard, shell, viewport,
636 );
637 }
638 }
639
640 fn mouse_interaction(
641 &self,
642 tree: &Tree,
643 layout: Layout<'_>,
644 cursor: mouse::Cursor,
645 viewport: &Rectangle,
646 renderer: &Renderer,
647 ) -> mouse::Interaction {
648 interaction_of_all(&self.children, tree, layout, cursor, viewport, renderer)
649 }
650
651 fn overlay<'b>(
652 &'b mut self,
653 tree: &'b mut Tree,
654 layout: Layout<'b>,
655 renderer: &Renderer,
656 viewport: &Rectangle,
657 translation: Vector,
658 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
659 overlay::from_children(
660 &mut self.children,
661 tree,
662 layout,
663 renderer,
664 viewport,
665 translation,
666 )
667 }
668}
669
670fn stack_vertically(
673 nodes: impl IntoIterator<Item = layout::Node>,
674 spacing: f32,
675) -> (Vec<layout::Node>, Bounds) {
676 let mut y = 0.0;
677 let mut width: f32 = 0.0;
678 let placed: Vec<layout::Node> = nodes
679 .into_iter()
680 .map(|node| {
681 let size = node.size();
682 let node = node.move_to(Point::new(0.0, y));
683 y += size.height + spacing;
684 width = width.max(size.width);
685 node
686 })
687 .collect();
688 let height = if placed.is_empty() { 0.0 } else { y - spacing };
689 (placed, Bounds::new(width, height))
690}
691
692fn operate_all<Message>(
693 children: &mut [Element<'_, Message>],
694 tree: &mut Tree,
695 layout: Layout<'_>,
696 renderer: &Renderer,
697 operation: &mut dyn Operation,
698) {
699 operation.container(None, layout.bounds());
700 operation.traverse(&mut |operation| {
701 for ((child, tree), layout) in children
702 .iter_mut()
703 .zip(&mut tree.children)
704 .zip(layout.children())
705 {
706 child
707 .as_widget_mut()
708 .operate(tree, layout, renderer, operation);
709 }
710 });
711}
712
713fn interaction_of_all<Message>(
714 children: &[Element<'_, Message>],
715 tree: &Tree,
716 layout: Layout<'_>,
717 cursor: mouse::Cursor,
718 viewport: &Rectangle,
719 renderer: &Renderer,
720) -> mouse::Interaction {
721 children
722 .iter()
723 .zip(&tree.children)
724 .zip(layout.children())
725 .map(|((child, tree), layout)| {
726 child
727 .as_widget()
728 .mouse_interaction(tree, layout, cursor, viewport, renderer)
729 })
730 .max()
731 .unwrap_or_default()
732}
733
734pub fn surface_style(tokens: &Tokens) -> container::Style {
737 let style = anchored::surface_style(tokens);
738 container::Style {
739 border: Border {
740 radius: radius::LG.into(),
741 ..style.border
742 },
743 ..style
744 }
745}
746
747pub fn scrim_style(tokens: &Tokens) -> container::Style {
750 container::Style {
751 background: Some(Background::Color(fade(
752 Color::BLACK,
753 if tokens.is_dark { 0.7 } else { 0.5 },
754 ))),
755 ..container::Style::default()
756 }
757}
758
759struct Guard<'a, Message> {
762 content: Element<'a, Message>,
763 blocked: bool,
764}
765
766impl<Message> Widget<Message, Theme, Renderer> for Guard<'_, Message> {
767 fn size(&self) -> Bounds<Length> {
768 self.content.as_widget().size()
769 }
770
771 fn size_hint(&self) -> Bounds<Length> {
772 self.content.as_widget().size_hint()
773 }
774
775 fn tag(&self) -> tree::Tag {
776 self.content.as_widget().tag()
777 }
778
779 fn state(&self) -> tree::State {
780 self.content.as_widget().state()
781 }
782
783 fn children(&self) -> Vec<Tree> {
784 self.content.as_widget().children()
785 }
786
787 fn diff(&self, tree: &mut Tree) {
788 self.content.as_widget().diff(tree);
789 }
790
791 fn layout(
792 &mut self,
793 tree: &mut Tree,
794 renderer: &Renderer,
795 limits: &layout::Limits,
796 ) -> layout::Node {
797 self.content.as_widget_mut().layout(tree, renderer, limits)
798 }
799
800 fn draw(
801 &self,
802 tree: &Tree,
803 renderer: &mut Renderer,
804 theme: &Theme,
805 style: &renderer::Style,
806 layout: Layout<'_>,
807 cursor: mouse::Cursor,
808 viewport: &Rectangle,
809 ) {
810 let cursor = if self.blocked {
811 mouse::Cursor::Unavailable
812 } else {
813 cursor
814 };
815 self.content
816 .as_widget()
817 .draw(tree, renderer, theme, style, layout, cursor, viewport);
818 }
819
820 fn operate(
821 &mut self,
822 tree: &mut Tree,
823 layout: Layout<'_>,
824 renderer: &Renderer,
825 operation: &mut dyn Operation,
826 ) {
827 self.content
828 .as_widget_mut()
829 .operate(tree, layout, renderer, operation);
830 }
831
832 fn update(
833 &mut self,
834 tree: &mut Tree,
835 event: &Event,
836 layout: Layout<'_>,
837 cursor: mouse::Cursor,
838 renderer: &Renderer,
839 clipboard: &mut dyn Clipboard,
840 shell: &mut Shell<'_, Message>,
841 viewport: &Rectangle,
842 ) {
843 if !self.blocked {
844 self.content.as_widget_mut().update(
845 tree, event, layout, cursor, renderer, clipboard, shell, viewport,
846 );
847 return;
848 }
849 if !matches!(event, Event::Window(_)) {
851 return;
852 }
853 self.content.as_widget_mut().update(
854 tree,
855 event,
856 layout,
857 mouse::Cursor::Unavailable,
858 renderer,
859 clipboard,
860 shell,
861 viewport,
862 );
863 }
864
865 fn mouse_interaction(
866 &self,
867 tree: &Tree,
868 layout: Layout<'_>,
869 cursor: mouse::Cursor,
870 viewport: &Rectangle,
871 renderer: &Renderer,
872 ) -> mouse::Interaction {
873 if self.blocked {
874 return mouse::Interaction::None;
875 }
876 self.content
877 .as_widget()
878 .mouse_interaction(tree, layout, cursor, viewport, renderer)
879 }
880
881 fn overlay<'b>(
882 &'b mut self,
883 tree: &'b mut Tree,
884 layout: Layout<'b>,
885 renderer: &Renderer,
886 viewport: &Rectangle,
887 translation: Vector,
888 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
889 if self.blocked {
890 return None;
891 }
892 self.content
893 .as_widget_mut()
894 .overlay(tree, layout, renderer, viewport, translation)
895 }
896}
897
898struct Scope<'a, Message> {
901 content: Element<'a, Message>,
902 open: bool,
903 surface: widget::Id,
904 keymap: Keymap<Action>,
905 pass_through: Vec<Chord>,
906 on_escape: Option<Message>,
907 on_confirm: Option<Message>,
908}
909
910fn key_of(event: &Event) -> Option<(&keyboard::Key, keyboard::Modifiers, bool)> {
912 match event {
913 Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) => {
914 Some((key, *modifiers, true))
915 }
916 Event::Keyboard(keyboard::Event::KeyReleased { key, modifiers, .. }) => {
917 Some((key, *modifiers, false))
918 }
919 _ => None,
920 }
921}
922
923#[derive(Debug, Default)]
925struct ScopeState {
926 entered: bool,
927}
928
929fn dismisses_anyway(focused_before: bool, focused_after: bool) -> bool {
932 focused_before && !focused_after
933}
934
935impl<Message> Scope<'_, Message> {
936 fn is_dismissal(&self, event: &Event) -> bool {
938 let Some((key, modifiers, true)) = key_of(event) else {
939 return false;
940 };
941 self.open
942 && self.on_escape.is_some()
943 && !self
944 .pass_through
945 .iter()
946 .any(|chord| chord.matches(key, modifiers))
947 && self.keymap.resolve(key, modifiers) == Some(Action::Close)
948 }
949
950 fn has_focus_inside(
951 &mut self,
952 tree: &mut Tree,
953 layout: Layout<'_>,
954 renderer: &Renderer,
955 ) -> bool {
956 let mut survey = Survey::new(self.surface.clone());
957 self.content
958 .as_widget_mut()
959 .operate(tree, layout, renderer, &mut survey);
960 survey.has_focus_inside()
961 }
962
963 fn move_focus(
964 &mut self,
965 tree: &mut Tree,
966 layout: Layout<'_>,
967 renderer: &Renderer,
968 movement: Movement,
969 ) {
970 let mut survey = Survey::new(self.surface.clone());
971 self.content
972 .as_widget_mut()
973 .operate(tree, layout, renderer, &mut survey);
974
975 let mut apply = Apply {
976 target: target(&survey.slots, movement),
977 index: 0,
978 focused: None,
979 };
980 self.content
981 .as_widget_mut()
982 .operate(tree, layout, renderer, &mut apply);
983
984 let Some(focused) = apply.focused else {
985 return;
986 };
987 let mut reveal = Reveal {
988 scope: Survey::new(self.surface.clone()),
989 target: focused,
990 };
991 self.content
992 .as_widget_mut()
993 .operate(tree, layout, renderer, &mut reveal);
994 }
995}
996
997impl<Message: Clone> Widget<Message, Theme, Renderer> for Scope<'_, Message> {
998 fn size(&self) -> Bounds<Length> {
999 self.content.as_widget().size()
1000 }
1001
1002 fn size_hint(&self) -> Bounds<Length> {
1003 self.content.as_widget().size_hint()
1004 }
1005
1006 fn tag(&self) -> tree::Tag {
1007 tree::Tag::of::<ScopeState>()
1008 }
1009
1010 fn state(&self) -> tree::State {
1011 tree::State::new(ScopeState::default())
1012 }
1013
1014 fn children(&self) -> Vec<Tree> {
1015 vec![Tree::new(&self.content)]
1016 }
1017
1018 fn diff(&self, tree: &mut Tree) {
1019 tree.diff_children(std::slice::from_ref(&self.content));
1020 }
1021
1022 fn layout(
1023 &mut self,
1024 tree: &mut Tree,
1025 renderer: &Renderer,
1026 limits: &layout::Limits,
1027 ) -> layout::Node {
1028 self.content
1029 .as_widget_mut()
1030 .layout(&mut tree.children[0], renderer, limits)
1031 }
1032
1033 fn draw(
1034 &self,
1035 tree: &Tree,
1036 renderer: &mut Renderer,
1037 theme: &Theme,
1038 style: &renderer::Style,
1039 layout: Layout<'_>,
1040 cursor: mouse::Cursor,
1041 viewport: &Rectangle,
1042 ) {
1043 self.content.as_widget().draw(
1044 &tree.children[0],
1045 renderer,
1046 theme,
1047 style,
1048 layout,
1049 cursor,
1050 viewport,
1051 );
1052 }
1053
1054 fn operate(
1055 &mut self,
1056 tree: &mut Tree,
1057 layout: Layout<'_>,
1058 renderer: &Renderer,
1059 operation: &mut dyn Operation,
1060 ) {
1061 self.content
1062 .as_widget_mut()
1063 .operate(&mut tree.children[0], layout, renderer, operation);
1064 }
1065
1066 fn update(
1067 &mut self,
1068 tree: &mut Tree,
1069 event: &Event,
1070 layout: Layout<'_>,
1071 cursor: mouse::Cursor,
1072 renderer: &Renderer,
1073 clipboard: &mut dyn Clipboard,
1074 shell: &mut Shell<'_, Message>,
1075 viewport: &Rectangle,
1076 ) {
1077 let state = tree.state.downcast_mut::<ScopeState>();
1078 let entering = self.open && !state.entered;
1079 state.entered = self.open;
1080
1081 let content = &mut tree.children[0];
1082 if entering {
1083 self.move_focus(content, layout, renderer, Movement::First);
1084 shell.request_redraw();
1085 }
1086
1087 let dismissal = self.is_dismissal(event);
1091 let focused_before = dismissal && self.has_focus_inside(content, layout, renderer);
1092
1093 self.content.as_widget_mut().update(
1094 content, event, layout, cursor, renderer, clipboard, shell, viewport,
1095 );
1096 if !self.open {
1097 return;
1098 }
1099 if shell.is_event_captured() {
1100 if !dismissal {
1101 return;
1102 }
1103 let focused_after = self.has_focus_inside(content, layout, renderer);
1104 if let Some(message) = self
1105 .on_escape
1106 .clone()
1107 .filter(|_| dismisses_anyway(focused_before, focused_after))
1108 {
1109 shell.publish(message);
1110 }
1111 return;
1112 }
1113
1114 let Some((key, modifiers, pressed)) = key_of(event) else {
1115 return;
1116 };
1117 if self
1118 .pass_through
1119 .iter()
1120 .any(|chord| chord.matches(key, modifiers))
1121 {
1122 return;
1123 }
1124 shell.capture_event();
1125 if !pressed {
1126 return;
1127 }
1128 let Some(effect) = self
1129 .keymap
1130 .resolve(key, modifiers)
1131 .and_then(|action| action.effect(self.on_escape.is_some()))
1132 else {
1133 return;
1134 };
1135
1136 match effect {
1137 Effect::Dismiss => {
1138 let Some(message) = self.on_escape.clone() else {
1139 return;
1140 };
1141 shell.publish(message);
1142 }
1143 Effect::Confirm => {
1144 let Some(message) = self.on_confirm.clone() else {
1145 return;
1146 };
1147 shell.publish(message);
1148 }
1149 Effect::Focus(direction) => {
1150 self.move_focus(content, layout, renderer, Movement::from(direction));
1151 shell.request_redraw();
1152 }
1153 }
1154 }
1155
1156 fn mouse_interaction(
1157 &self,
1158 tree: &Tree,
1159 layout: Layout<'_>,
1160 cursor: mouse::Cursor,
1161 viewport: &Rectangle,
1162 renderer: &Renderer,
1163 ) -> mouse::Interaction {
1164 self.content.as_widget().mouse_interaction(
1165 &tree.children[0],
1166 layout,
1167 cursor,
1168 viewport,
1169 renderer,
1170 )
1171 }
1172
1173 fn overlay<'b>(
1174 &'b mut self,
1175 tree: &'b mut Tree,
1176 layout: Layout<'b>,
1177 renderer: &Renderer,
1178 viewport: &Rectangle,
1179 translation: Vector,
1180 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1181 self.content.as_widget_mut().overlay(
1182 &mut tree.children[0],
1183 layout,
1184 renderer,
1185 viewport,
1186 translation,
1187 )
1188 }
1189}
1190
1191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1193enum Movement {
1194 First,
1195 Next,
1196 Previous,
1197}
1198
1199impl From<Direction> for Movement {
1200 fn from(direction: Direction) -> Self {
1201 match direction {
1202 Direction::Next => Movement::Next,
1203 Direction::Previous => Movement::Previous,
1204 }
1205 }
1206}
1207
1208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1210struct Slot {
1211 inside: bool,
1212 focused: bool,
1213 control: bool,
1215}
1216
1217fn target(slots: &[Slot], movement: Movement) -> Option<usize> {
1221 let inside: Vec<usize> = (0..slots.len()).filter(|&i| slots[i].inside).collect();
1222 if movement == Movement::First {
1223 return inside.into_iter().find(|&i| !slots[i].control);
1224 }
1225 let (first, last) = (inside.first().copied()?, inside.last().copied()?);
1226 let current = inside.iter().position(|&i| slots[i].focused);
1227 let count = inside.len();
1228
1229 match (movement, current) {
1230 (Movement::First, _) | (Movement::Next, None) => Some(first),
1231 (Movement::Previous, None) => Some(last),
1232 (Movement::Next, Some(at)) => inside.get((at + 1) % count).copied(),
1233 (Movement::Previous, Some(at)) => inside.get((at + count - 1) % count).copied(),
1234 }
1235}
1236
1237struct Survey {
1239 scope: widget::Id,
1240 entering: bool,
1241 depth: usize,
1242 control: bool,
1244 slots: Vec<Slot>,
1245}
1246
1247impl Survey {
1248 fn new(scope: widget::Id) -> Self {
1249 Self {
1250 scope,
1251 entering: false,
1252 depth: 0,
1253 control: false,
1254 slots: Vec::new(),
1255 }
1256 }
1257
1258 fn has_focus_inside(&self) -> bool {
1259 self.slots.iter().any(|slot| slot.inside && slot.focused)
1260 }
1261}
1262
1263impl Operation for Survey {
1264 fn container(&mut self, id: Option<&widget::Id>, _bounds: Rectangle) {
1265 if id == Some(&self.scope) {
1266 self.entering = true;
1267 }
1268 }
1269
1270 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1273 let entered = std::mem::take(&mut self.entering);
1274 self.depth += usize::from(entered);
1275 operate(self);
1276 self.depth -= usize::from(entered);
1277 }
1278
1279 fn custom(&mut self, _id: Option<&widget::Id>, _bounds: Rectangle, state: &mut dyn Any) {
1280 if state.is::<focus::Control>() {
1281 self.control = true;
1282 }
1283 }
1284
1285 fn focusable(
1286 &mut self,
1287 _id: Option<&widget::Id>,
1288 _bounds: Rectangle,
1289 state: &mut dyn Focusable,
1290 ) {
1291 self.slots.push(Slot {
1292 inside: self.depth > 0,
1293 focused: state.is_focused(),
1294 control: std::mem::take(&mut self.control),
1295 });
1296 }
1297}
1298
1299struct Apply {
1302 target: Option<usize>,
1303 index: usize,
1304 focused: Option<Rectangle>,
1305}
1306
1307impl Operation for Apply {
1308 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1309 operate(self);
1310 }
1311
1312 fn focusable(
1313 &mut self,
1314 _id: Option<&widget::Id>,
1315 bounds: Rectangle,
1316 state: &mut dyn Focusable,
1317 ) {
1318 let is_target = self.target == Some(self.index);
1319 if is_target {
1320 self.focused = Some(bounds);
1321 }
1322 if is_target && !state.is_focused() {
1323 state.focus();
1324 } else if !is_target && state.is_focused() {
1325 state.unfocus();
1326 }
1327 self.index += 1;
1328 }
1329}
1330
1331const REVEAL_MARGIN: f32 = space::XS;
1334
1335fn reveal(viewport: Rectangle, content: Rectangle, offset: f32, target: Rectangle) -> Option<f32> {
1340 if !content.intersects(&target) {
1341 return None;
1342 }
1343 let top = (target.y - content.y - REVEAL_MARGIN).max(0.0);
1344 let bottom = target.y + target.height - content.y + REVEAL_MARGIN;
1345 if top < offset {
1346 return Some(top);
1347 }
1348 if bottom > offset + viewport.height {
1349 return Some((bottom - viewport.height).min(top));
1350 }
1351 None
1352}
1353
1354struct Reveal {
1356 scope: Survey,
1357 target: Rectangle,
1358}
1359
1360impl Operation for Reveal {
1361 fn container(&mut self, id: Option<&widget::Id>, bounds: Rectangle) {
1362 self.scope.container(id, bounds);
1363 }
1364
1365 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1366 let entered = std::mem::take(&mut self.scope.entering);
1367 self.scope.depth += usize::from(entered);
1368 operate(self);
1369 self.scope.depth -= usize::from(entered);
1370 }
1371
1372 fn scrollable(
1373 &mut self,
1374 _id: Option<&widget::Id>,
1375 bounds: Rectangle,
1376 content_bounds: Rectangle,
1377 translation: Vector,
1378 state: &mut dyn Scrollable,
1379 ) {
1380 if self.scope.depth == 0 {
1381 return;
1382 }
1383 let Some(y) = reveal(bounds, content_bounds, translation.y, self.target) else {
1384 return;
1385 };
1386 state.scroll_to(AbsoluteOffset {
1387 x: None,
1388 y: Some(y),
1389 });
1390 }
1391}
1392
1393pub struct AlertDialog<'a, Message> {
1403 base: Element<'a, Message>,
1404 open: bool,
1405 title: text::Fragment<'a>,
1406 description: text::Fragment<'a>,
1407 cancel: text::Fragment<'a>,
1408 confirm: text::Fragment<'a>,
1409 on_cancel: Option<Message>,
1410 on_confirm: Option<Message>,
1411 confirm_on_enter: bool,
1412 dismiss_on_escape: bool,
1413 dismiss_on_scrim: bool,
1414 size: Size,
1415 keymap: Keymap<Action>,
1416}
1417
1418impl<Message> std::fmt::Debug for AlertDialog<'_, Message> {
1419 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1420 f.debug_struct("AlertDialog")
1421 .field("open", &self.open)
1422 .field("title", &self.title)
1423 .field("description", &self.description)
1424 .field("cancel", &self.cancel)
1425 .field("confirm", &self.confirm)
1426 .field("confirm_on_enter", &self.confirm_on_enter)
1427 .field("dismiss_on_escape", &self.dismiss_on_escape)
1428 .field("dismiss_on_scrim", &self.dismiss_on_scrim)
1429 .field("size", &self.size)
1430 .finish_non_exhaustive()
1431 }
1432}
1433
1434pub fn alert_dialog<'a, Message>(
1437 base: impl Into<Element<'a, Message>>,
1438 title: impl text::IntoFragment<'a>,
1439 description: impl text::IntoFragment<'a>,
1440) -> AlertDialog<'a, Message> {
1441 AlertDialog {
1442 base: base.into(),
1443 open: false,
1444 title: title.into_fragment(),
1445 description: description.into_fragment(),
1446 cancel: "Cancel".into(),
1447 confirm: "Continue".into(),
1448 on_cancel: None,
1449 on_confirm: None,
1450 confirm_on_enter: false,
1451 dismiss_on_escape: true,
1452 dismiss_on_scrim: false,
1453 size: Size::default(),
1454 keymap: default_keymap(),
1455 }
1456}
1457
1458impl<'a, Message> AlertDialog<'a, Message> {
1459 pub fn open(mut self, open: bool) -> Self {
1460 self.open = open;
1461 self
1462 }
1463
1464 pub fn cancel(mut self, label: impl text::IntoFragment<'a>) -> Self {
1466 self.cancel = label.into_fragment();
1467 self
1468 }
1469
1470 pub fn confirm(mut self, label: impl text::IntoFragment<'a>) -> Self {
1472 self.confirm = label.into_fragment();
1473 self
1474 }
1475
1476 pub fn on_cancel(mut self, message: Message) -> Self {
1478 self.on_cancel = Some(message);
1479 self
1480 }
1481
1482 pub fn on_confirm(mut self, message: Message) -> Self {
1485 self.on_confirm = Some(message);
1486 self
1487 }
1488
1489 pub fn confirm_on_enter(mut self, confirm: bool) -> Self {
1494 self.confirm_on_enter = confirm;
1495 self
1496 }
1497
1498 pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
1500 self.dismiss_on_escape = dismiss;
1501 self
1502 }
1503
1504 pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
1507 self.dismiss_on_scrim = dismiss;
1508 self
1509 }
1510
1511 pub fn size(mut self, size: Size) -> Self {
1512 self.size = size;
1513 self
1514 }
1515
1516 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
1518 self.keymap = keymap;
1519 self
1520 }
1521}
1522
1523impl<'a, Message: Clone + 'a> From<AlertDialog<'a, Message>> for Dialog<'a, Message> {
1524 fn from(alert: AlertDialog<'a, Message>) -> Self {
1525 let mut dialog = dialog(alert.base)
1526 .open(alert.open)
1527 .title(alert.title)
1528 .description(alert.description)
1529 .action(
1530 button::button(alert.cancel)
1531 .variant(button::Variant::Outline)
1532 .on_press_maybe(alert.on_cancel.clone()),
1533 )
1534 .action(
1535 button::button(alert.confirm)
1536 .variant(button::Variant::Destructive)
1537 .on_press_maybe(alert.on_confirm.clone()),
1538 )
1539 .dismiss_on_escape(alert.dismiss_on_escape)
1540 .dismiss_on_scrim(alert.dismiss_on_scrim)
1541 .close_button(false)
1542 .size(alert.size)
1543 .keymap(alert.keymap);
1544 if let Some(message) = alert.on_cancel {
1545 dialog = dialog.on_dismiss(message);
1546 }
1547 let Some(message) = alert.on_confirm.filter(|_| alert.confirm_on_enter) else {
1548 return dialog;
1549 };
1550 dialog.on_confirm(message)
1551 }
1552}
1553
1554impl<'a, Message: Clone + 'a> From<AlertDialog<'a, Message>> for Element<'a, Message> {
1555 fn from(alert: AlertDialog<'a, Message>) -> Self {
1556 Dialog::from(alert).into()
1557 }
1558}
1559
1560pub struct Section<'a, Message> {
1563 title: text::Fragment<'a>,
1564 description: Option<text::Fragment<'a>>,
1565 body: Element<'a, Message>,
1566}
1567
1568impl<Message> std::fmt::Debug for Section<'_, Message> {
1569 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1570 f.debug_struct("Section")
1571 .field("title", &self.title)
1572 .field("description", &self.description)
1573 .finish_non_exhaustive()
1574 }
1575}
1576
1577pub fn section<'a, Message>(
1580 title: impl text::IntoFragment<'a>,
1581 body: impl Into<Element<'a, Message>>,
1582) -> Section<'a, Message> {
1583 Section {
1584 title: title.into_fragment(),
1585 description: None,
1586 body: body.into(),
1587 }
1588}
1589
1590impl<'a, Message> Section<'a, Message> {
1591 pub fn description(mut self, description: impl text::IntoFragment<'a>) -> Self {
1593 self.description = Some(description.into_fragment());
1594 self
1595 }
1596}
1597
1598pub const SECTION_TITLE_SIZE: f32 = text_size::MD;
1600
1601impl<'a, Message: 'a> From<Section<'a, Message>> for Element<'a, Message> {
1602 fn from(section: Section<'a, Message>) -> Self {
1603 let mut header = column![heading(section.title, SECTION_TITLE_SIZE)].spacing(space::XS);
1604 if let Some(description) = section.description {
1605 header = header.push(supporting(description));
1606 }
1607 column![header, section.body]
1608 .spacing(space::MD)
1609 .width(Length::Fill)
1610 .into()
1611 }
1612}
1613
1614pub const BREAKPOINT: f32 = 400.0;
1616
1617pub fn cells(width: f32, breakpoint: f32, spacing: f32) -> (usize, f32) {
1619 if !width.is_finite() || width < breakpoint {
1620 return (1, width);
1621 }
1622 (2, ((width - spacing) / 2.0).max(0.0))
1623}
1624
1625pub struct Columns<'a, Message> {
1628 children: Vec<Element<'a, Message>>,
1629 breakpoint: f32,
1630 spacing: f32,
1631}
1632
1633impl<Message> std::fmt::Debug for Columns<'_, Message> {
1634 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1635 f.debug_struct("Columns")
1636 .field("children", &self.children.len())
1637 .field("breakpoint", &self.breakpoint)
1638 .field("spacing", &self.spacing)
1639 .finish()
1640 }
1641}
1642
1643pub fn columns<'a, Message>(
1647 children: impl IntoIterator<Item = Element<'a, Message>>,
1648) -> Columns<'a, Message> {
1649 Columns {
1650 children: children.into_iter().collect(),
1651 breakpoint: BREAKPOINT,
1652 spacing: space::XL,
1653 }
1654}
1655
1656impl<'a, Message> Columns<'a, Message> {
1657 pub fn push(mut self, child: impl Into<Element<'a, Message>>) -> Self {
1659 self.children.push(child.into());
1660 self
1661 }
1662
1663 pub fn breakpoint(mut self, width: f32) -> Self {
1666 self.breakpoint = width;
1667 self
1668 }
1669
1670 pub fn spacing(mut self, spacing: f32) -> Self {
1672 self.spacing = spacing;
1673 self
1674 }
1675}
1676
1677impl<'a, Message: 'a> From<Columns<'a, Message>> for Element<'a, Message> {
1678 fn from(columns: Columns<'a, Message>) -> Self {
1679 Element::new(columns)
1680 }
1681}
1682
1683impl<Message> Widget<Message, Theme, Renderer> for Columns<'_, Message> {
1684 fn size(&self) -> Bounds<Length> {
1685 Bounds::new(Length::Fill, Length::Shrink)
1686 }
1687
1688 fn children(&self) -> Vec<Tree> {
1689 self.children.iter().map(Tree::new).collect()
1690 }
1691
1692 fn diff(&self, tree: &mut Tree) {
1693 tree.diff_children(&self.children);
1694 }
1695
1696 fn layout(
1697 &mut self,
1698 tree: &mut Tree,
1699 renderer: &Renderer,
1700 limits: &layout::Limits,
1701 ) -> layout::Node {
1702 let max = limits.max();
1703 let (count, cell) = cells(max.width, self.breakpoint, self.spacing);
1704 let cell_limits = layout::Limits::new(Bounds::ZERO, Bounds::new(cell, max.height));
1705
1706 let mut nodes = Vec::with_capacity(self.children.len());
1707 let mut y = 0.0;
1708 let mut width: f32 = 0.0;
1709 for (children, trees) in self
1710 .children
1711 .chunks_mut(count)
1712 .zip(tree.children.chunks_mut(count))
1713 {
1714 let mut height: f32 = 0.0;
1715 for (column, (child, tree)) in children.iter_mut().zip(trees).enumerate() {
1716 let node = child.as_widget_mut().layout(tree, renderer, &cell_limits);
1717 let x = column as f32 * (cell + self.spacing);
1718 let size = node.size();
1719 height = height.max(size.height);
1720 width = width.max(x + size.width);
1721 nodes.push(node.move_to(Point::new(x, y)));
1722 }
1723 y += height + self.spacing;
1724 }
1725 let height = if nodes.is_empty() {
1726 0.0
1727 } else {
1728 y - self.spacing
1729 };
1730
1731 let intrinsic = Bounds::new(width, height);
1732 let size = if max.width.is_finite() {
1733 limits.resolve(Length::Fill, Length::Shrink, intrinsic)
1734 } else {
1735 intrinsic
1736 };
1737 layout::Node::with_children(size, nodes)
1738 }
1739
1740 fn draw(
1741 &self,
1742 tree: &Tree,
1743 renderer: &mut Renderer,
1744 theme: &Theme,
1745 style: &renderer::Style,
1746 layout: Layout<'_>,
1747 cursor: mouse::Cursor,
1748 viewport: &Rectangle,
1749 ) {
1750 for ((child, tree), layout) in self
1751 .children
1752 .iter()
1753 .zip(&tree.children)
1754 .zip(layout.children())
1755 {
1756 child
1757 .as_widget()
1758 .draw(tree, renderer, theme, style, layout, cursor, viewport);
1759 }
1760 }
1761
1762 fn operate(
1763 &mut self,
1764 tree: &mut Tree,
1765 layout: Layout<'_>,
1766 renderer: &Renderer,
1767 operation: &mut dyn Operation,
1768 ) {
1769 operate_all(&mut self.children, tree, layout, renderer, operation);
1770 }
1771
1772 fn update(
1773 &mut self,
1774 tree: &mut Tree,
1775 event: &Event,
1776 layout: Layout<'_>,
1777 cursor: mouse::Cursor,
1778 renderer: &Renderer,
1779 clipboard: &mut dyn Clipboard,
1780 shell: &mut Shell<'_, Message>,
1781 viewport: &Rectangle,
1782 ) {
1783 for ((child, tree), layout) in self
1784 .children
1785 .iter_mut()
1786 .zip(&mut tree.children)
1787 .zip(layout.children())
1788 {
1789 child.as_widget_mut().update(
1790 tree, event, layout, cursor, renderer, clipboard, shell, viewport,
1791 );
1792 }
1793 }
1794
1795 fn mouse_interaction(
1796 &self,
1797 tree: &Tree,
1798 layout: Layout<'_>,
1799 cursor: mouse::Cursor,
1800 viewport: &Rectangle,
1801 renderer: &Renderer,
1802 ) -> mouse::Interaction {
1803 interaction_of_all(&self.children, tree, layout, cursor, viewport, renderer)
1804 }
1805
1806 fn overlay<'b>(
1807 &'b mut self,
1808 tree: &'b mut Tree,
1809 layout: Layout<'b>,
1810 renderer: &Renderer,
1811 viewport: &Rectangle,
1812 translation: Vector,
1813 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1814 overlay::from_children(
1815 &mut self.children,
1816 tree,
1817 layout,
1818 renderer,
1819 viewport,
1820 translation,
1821 )
1822 }
1823}
1824
1825#[cfg(test)]
1826mod tests {
1827 use super::*;
1828 use crate::theme::{dark, light};
1829
1830 fn slots(layout: &[(bool, bool)]) -> Vec<Slot> {
1831 layout
1832 .iter()
1833 .map(|&(inside, focused)| Slot {
1834 inside,
1835 focused,
1836 control: false,
1837 })
1838 .collect()
1839 }
1840
1841 #[test]
1842 fn a_captured_close_still_dismisses_when_it_only_unfocused_a_field() {
1843 assert!(dismisses_anyway(true, false));
1844 assert!(!dismisses_anyway(true, true), "something else used the key");
1845 assert!(!dismisses_anyway(false, false));
1846 assert!(!dismisses_anyway(false, true));
1847 }
1848
1849 #[test]
1850 fn the_survey_marks_controls_and_finds_focus_inside() {
1851 let mut survey = Survey::new(DEFAULT_ID);
1852 let mut field = focus::State::default();
1853 let mut control = focus::State::default();
1854 let bounds = Rectangle::with_size(Bounds::new(10.0, 10.0));
1855 survey.container(Some(&DEFAULT_ID), bounds);
1856 survey.traverse(&mut |operation| {
1857 operation.focusable(None, bounds, &mut field);
1858 focus::report(operation, None, bounds, &mut control);
1859 });
1860 assert_eq!(
1861 survey
1862 .slots
1863 .iter()
1864 .map(|slot| slot.control)
1865 .collect::<Vec<_>>(),
1866 vec![false, true]
1867 );
1868 assert!(survey.slots.iter().all(|slot| slot.inside));
1869 assert!(!survey.has_focus_inside());
1870
1871 let mut outside = Survey::new(DEFAULT_ID);
1872 Focusable::focus(&mut field);
1873 outside.focusable(None, bounds, &mut field);
1874 assert!(!outside.has_focus_inside(), "focus outside the surface");
1875 }
1876
1877 #[test]
1878 fn builder_defaults() {
1879 let d: Dialog<'_, ()> = dialog(text("Base"));
1880 assert!(!d.is_open());
1881 assert!(d.dismiss_on_escape);
1882 assert!(d.dismiss_on_scrim);
1883 assert!(d.close_button);
1884 assert!(d.on_dismiss.is_none());
1885 assert_eq!(d.width, Size::Md.width());
1886 assert_eq!(d.max_height, f32::INFINITY);
1887 assert_eq!(d.id, DEFAULT_ID);
1888 assert_eq!(d.keymap, default_keymap());
1889 assert!(d.pass_through.is_empty());
1890 }
1891
1892 #[test]
1893 fn builder_sets_every_option() {
1894 let d = dialog::<u8>(text("Base"))
1895 .open(true)
1896 .title("Title")
1897 .description("Description")
1898 .body(text("Body"))
1899 .action(text("One"))
1900 .action(text("Two"))
1901 .on_dismiss(1)
1902 .dismiss_on_escape(false)
1903 .dismiss_on_scrim(false)
1904 .close_button(false)
1905 .size(Size::Lg)
1906 .max_height(420.0)
1907 .id("custom")
1908 .keymap(Keymap::new())
1909 .pass_through([Chord::character('k').command()]);
1910 assert_eq!(d.pass_through, vec![Chord::character('k').command()]);
1911 assert!(d.is_open());
1912 assert_eq!(d.title.as_deref(), Some("Title"));
1913 assert_eq!(d.description.as_deref(), Some("Description"));
1914 assert!(d.body.is_some());
1915 assert_eq!(d.actions.len(), 2);
1916 assert_eq!(d.on_dismiss, Some(1));
1917 assert!(!d.dismiss_on_escape && !d.dismiss_on_scrim && !d.close_button);
1918 assert_eq!(d.width, 640.0);
1919 assert_eq!(d.max_height, 420.0);
1920 assert_eq!(d.id, widget::Id::new("custom"));
1921 assert!(d.keymap.is_empty());
1922 assert_eq!(dialog::<u8>(text("Base")).width(300.0).width, 300.0);
1923 }
1924
1925 #[test]
1926 fn sizes_grow_monotonically() {
1927 let widths = Size::ALL.map(Size::width);
1928 assert!(widths.windows(2).all(|w| w[0] < w[1]));
1929 assert_eq!(Size::default(), Size::Md);
1930 }
1931
1932 #[test]
1933 fn alert_dialog_needs_an_explicit_answer() {
1934 let alert = alert_dialog::<u8>(text("Base"), "Delete file?", "This cannot be undone.")
1935 .open(true)
1936 .confirm("Delete")
1937 .on_cancel(1)
1938 .on_confirm(2);
1939 assert_eq!(alert.cancel.as_ref(), "Cancel");
1940 assert_eq!(alert.confirm.as_ref(), "Delete");
1941
1942 let d = Dialog::from(alert);
1943 assert!(d.is_open());
1944 assert!(!d.dismiss_on_scrim);
1945 assert!(!d.close_button);
1946 assert!(d.dismiss_on_escape);
1947 assert_eq!(d.on_dismiss, Some(1));
1948 assert_eq!(d.on_confirm, None, "Enter does not destroy by default");
1949 assert_eq!(d.actions.len(), 2);
1950 }
1951
1952 #[test]
1953 fn alert_dialog_can_cancel_on_the_scrim() {
1954 let alert = alert_dialog::<u8>(text("Base"), "Discard draft?", "It has not been saved.");
1955 assert!(!alert.dismiss_on_scrim);
1956
1957 let d = Dialog::from(alert.on_cancel(1).dismiss_on_scrim(true));
1958 assert!(d.dismiss_on_scrim);
1959 assert_eq!(d.on_dismiss, Some(1), "the scrim sends on_cancel");
1960 }
1961
1962 #[test]
1963 fn the_body_gets_what_the_header_footer_and_gaps_leave() {
1964 assert_eq!(room(600.0, 100.0, 16.0, 3), 600.0 - 100.0 - 32.0);
1965 assert_eq!(room(600.0, 100.0, 16.0, 1), 500.0);
1966 assert_eq!(room(100.0, 200.0, 16.0, 3), 0.0, "never negative");
1967 assert_eq!(room(f32::INFINITY, 50.0, 16.0, 2), f32::INFINITY);
1968 assert_eq!(room(100.0, 0.0, 16.0, 0), 100.0);
1969 }
1970
1971 #[test]
1972 fn stacking_places_nodes_under_each_other() {
1973 let nodes = [Bounds::new(40.0, 10.0), Bounds::new(80.0, 20.0)]
1974 .map(layout::Node::new)
1975 .to_vec();
1976 let (placed, size) = stack_vertically(nodes, 5.0);
1977 assert_eq!(size, Bounds::new(80.0, 35.0));
1978 assert_eq!(placed[1].bounds().y, 15.0);
1979 assert_eq!(stack_vertically([], 5.0).1, Bounds::ZERO);
1980 }
1981
1982 #[test]
1983 fn reveal_scrolls_a_hidden_field_into_view() {
1984 let viewport = Rectangle::new(Point::new(0.0, 100.0), Bounds::new(300.0, 200.0));
1985 let content = Rectangle::new(Point::new(0.0, 100.0), Bounds::new(300.0, 800.0));
1986 let field = |y: f32| Rectangle::new(Point::new(0.0, 100.0 + y), Bounds::new(300.0, 40.0));
1987
1988 assert_eq!(reveal(viewport, content, 0.0, field(50.0)), None, "in view");
1989 assert_eq!(
1990 reveal(viewport, content, 0.0, field(400.0)),
1991 Some(400.0 + 40.0 + REVEAL_MARGIN - 200.0),
1992 "below: its bottom lines up with the bottom"
1993 );
1994 assert_eq!(
1995 reveal(viewport, content, 300.0, field(100.0)),
1996 Some(100.0 - REVEAL_MARGIN),
1997 "above: its top lines up with the top"
1998 );
1999 let tall = Rectangle::new(Point::new(0.0, 500.0), Bounds::new(300.0, 300.0));
2000 assert_eq!(
2001 reveal(viewport, content, 0.0, tall),
2002 Some(400.0 - REVEAL_MARGIN),
2003 "a field taller than the view shows its top"
2004 );
2005 let elsewhere = Rectangle::new(Point::new(0.0, 1000.0), Bounds::new(300.0, 40.0));
2006 assert_eq!(reveal(viewport, content, 0.0, elsewhere), None);
2007 }
2008
2009 #[test]
2010 fn columns_fall_back_to_one_below_the_breakpoint() {
2011 assert_eq!(cells(464.0, BREAKPOINT, 24.0), (2, 220.0));
2012 assert_eq!(cells(BREAKPOINT, BREAKPOINT, 24.0), (2, 188.0));
2013 assert_eq!(
2014 cells(BREAKPOINT - 1.0, BREAKPOINT, 24.0),
2015 (1, BREAKPOINT - 1.0)
2016 );
2017 assert_eq!(cells(280.0, 200.0, 0.0), (2, 140.0));
2018 assert_eq!(cells(f32::INFINITY, BREAKPOINT, 24.0).0, 1);
2019 }
2020
2021 #[test]
2022 fn columns_and_sections_builders() {
2023 let c = columns::<()>([text("A").into()])
2024 .push(text("B"))
2025 .breakpoint(320.0)
2026 .spacing(8.0);
2027 assert_eq!(c.children.len(), 2);
2028 assert_eq!(c.breakpoint, 320.0);
2029 assert_eq!(c.spacing, 8.0);
2030 let d = columns::<()>([]);
2031 assert_eq!((d.breakpoint, d.spacing), (BREAKPOINT, space::XL));
2032
2033 let s = section::<()>("Event", text("Body")).description("When and where");
2034 assert_eq!(s.title.as_ref(), "Event");
2035 assert_eq!(s.description.as_deref(), Some("When and where"));
2036 const { assert!(SECTION_TITLE_SIZE < text_size::LG) };
2037 }
2038
2039 #[test]
2040 fn alert_dialog_confirms_on_enter_only_when_asked() {
2041 let alert = alert_dialog::<u8>(text("Base"), "Delete file?", "This cannot be undone.")
2042 .on_confirm(2)
2043 .confirm_on_enter(true);
2044 assert_eq!(Dialog::from(alert).on_confirm, Some(2));
2045 }
2046
2047 #[test]
2048 fn alert_dialog_without_cancel_has_no_dismiss() {
2049 let d = Dialog::from(
2050 alert_dialog::<u8>(text("Base"), "Title", "Description").dismiss_on_escape(false),
2051 );
2052 assert!(d.on_dismiss.is_none());
2053 assert!(d.on_confirm.is_none());
2054 assert!(!d.dismiss_on_escape);
2055 }
2056
2057 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
2058 let chord: Chord = chord.parse().ok()?;
2059 keymap.resolve(chord.key(), chord.modifiers())
2060 }
2061
2062 #[test]
2063 fn default_keymap_and_overrides() {
2064 let keymap = default_keymap();
2065 assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
2066 assert_eq!(press(&keymap, "Enter"), Some(Action::Confirm));
2067 assert_eq!(press(&keymap, "Shift+Enter"), None);
2068 assert_eq!(press(&keymap, "Tab"), Some(Action::FocusNext));
2069 assert_eq!(press(&keymap, "Shift+Tab"), Some(Action::FocusPrevious));
2070 assert_eq!(press(&keymap, "Ctrl+Tab"), None);
2071
2072 let custom = keymap
2073 .unbind(&Chord::named(Named::Escape))
2074 .bind(Chord::character('w').command(), Action::Close);
2075 assert_eq!(press(&custom, "Escape"), None);
2076 assert_eq!(press(&custom, "Mod+W"), Some(Action::Close));
2077 assert!(
2078 custom
2079 .unbind_action(&Action::Close)
2080 .chords(&Action::Close)
2081 .is_empty()
2082 );
2083 }
2084
2085 #[test]
2086 fn close_only_dismisses_when_escape_is_allowed() {
2087 assert_eq!(Action::Close.effect(true), Some(Effect::Dismiss));
2088 assert_eq!(Action::Close.effect(false), None);
2089 for allowed in [true, false] {
2090 assert_eq!(Action::Confirm.effect(allowed), Some(Effect::Confirm));
2091 assert_eq!(
2092 Action::FocusNext.effect(allowed),
2093 Some(Effect::Focus(Direction::Next))
2094 );
2095 assert_eq!(
2096 Action::FocusPrevious.effect(allowed),
2097 Some(Effect::Focus(Direction::Previous))
2098 );
2099 }
2100 }
2101
2102 #[test]
2103 fn every_action_has_a_name_and_a_sentence() {
2104 use keys::Action as _;
2105 for action in Action::ALL {
2106 assert!(!action.name().is_empty());
2107 assert!(action.description().ends_with('.'));
2108 }
2109 }
2110
2111 #[test]
2112 fn first_focuses_the_first_field_inside() {
2113 let layout = slots(&[(false, true), (true, false), (true, false)]);
2114 assert_eq!(target(&layout, Movement::First), Some(1));
2115 }
2116
2117 #[test]
2118 fn opening_skips_controls_but_tab_reaches_them() {
2119 let mut layout = slots(&[(true, false), (true, false)]);
2120 for slot in &mut layout {
2121 slot.control = true;
2122 }
2123 assert_eq!(target(&layout, Movement::First), None);
2124 assert_eq!(target(&layout, Movement::Next), Some(0));
2125 assert_eq!(target(&layout, Movement::Previous), Some(1));
2126
2127 layout[1].control = false;
2128 assert_eq!(target(&layout, Movement::First), Some(1));
2129 }
2130
2131 #[test]
2132 fn next_and_previous_wrap_inside_the_dialog() {
2133 let last = slots(&[(false, false), (true, false), (true, true), (false, false)]);
2134 assert_eq!(target(&last, Movement::Next), Some(1));
2135 assert_eq!(target(&last, Movement::Previous), Some(1));
2136
2137 let first = slots(&[(true, true), (true, false), (true, false)]);
2138 assert_eq!(target(&first, Movement::Previous), Some(2));
2139 assert_eq!(target(&first, Movement::Next), Some(1));
2140 }
2141
2142 #[test]
2143 fn focus_outside_moves_to_either_end_inside() {
2144 let layout = slots(&[(false, true), (true, false), (true, false), (false, false)]);
2145 assert_eq!(target(&layout, Movement::Next), Some(1));
2146 assert_eq!(target(&layout, Movement::Previous), Some(2));
2147 }
2148
2149 #[test]
2150 fn nothing_to_focus_without_fields_inside() {
2151 let layout = slots(&[(false, true), (false, false)]);
2152 for movement in [Movement::First, Movement::Next, Movement::Previous] {
2153 assert_eq!(target(&layout, movement), None);
2154 }
2155 assert_eq!(target(&[], Movement::Next), None);
2156 }
2157
2158 #[test]
2159 fn a_single_field_keeps_focus() {
2160 let layout = slots(&[(true, true)]);
2161 assert_eq!(target(&layout, Movement::Next), Some(0));
2162 assert_eq!(target(&layout, Movement::Previous), Some(0));
2163 }
2164
2165 #[test]
2166 fn surface_uses_the_shared_floating_style() {
2167 for theme in [light(), dark()] {
2168 let tokens = Tokens::of(&theme);
2169 let style = surface_style(&tokens);
2170 let shared = anchored::surface_style(&tokens);
2171 assert_eq!(style.background, Some(Background::Color(tokens.popover)));
2172 assert_eq!(style.text_color, Some(tokens.foreground));
2173 assert_eq!(style.border.color, tokens.border);
2174 assert_eq!(style.border.width, 1.0);
2175 assert_eq!(style.border.radius, radius::LG.into());
2176 assert_eq!(style.shadow, shared.shadow);
2177 }
2178 }
2179
2180 #[test]
2181 fn dark_theme_has_a_stronger_shadow_and_scrim() {
2182 let light = Tokens::of(&light());
2183 let dark = Tokens::of(&dark());
2184 assert!(surface_style(&dark).shadow.color.a > surface_style(&light).shadow.color.a);
2185
2186 let alpha = |tokens: &Tokens| match scrim_style(tokens).background {
2187 Some(Background::Color(colour)) => colour.a,
2188 _ => 0.0,
2189 };
2190 assert!((alpha(&light) - 0.5).abs() < 1e-6);
2191 assert!((alpha(&dark) - 0.7).abs() < 1e-6);
2192 }
2193}