Skip to main content

waft_material/
desktop_text_selection_toolbar_button.rs

1//! Flutter counterpart: material_ui's `desktop_text_selection_toolbar_button.dart`.
2
3use std::fmt::{self, Debug};
4
5use waft_embedder::{Brightness, FontWeight, Size};
6use waft_foundation::{App, Listener};
7use waft_painting::{
8    AlignmentGeometry, EdgeInsets, RoundedRectangleBorder, TextOverflow, TextStyle,
9};
10use waft_services::SystemMouseCursors;
11use waft_widgets::{BuildContext, IntoWidget, KeyRef, SizedBox, StatelessWidget, Text, WidgetRef};
12
13use crate::colors::Colors;
14use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
15use crate::text_button::TextButton;
16use crate::theme::Theme;
17
18fn k_toolbar_button_font_style() -> TextStyle {
19    TextStyle::new()
20        .inherit(false)
21        .font_size(14.0)
22        .letter_spacing(-0.15)
23        .font_weight(FontWeight::W400)
24}
25
26const K_TOOLBAR_BUTTON_PADDING: EdgeInsets = EdgeInsets::from_ltrb(20.0, 0.0, 20.0, 3.0);
27
28/// A [`TextButton`] for the Material desktop text selection toolbar.
29pub struct DesktopTextSelectionToolbarButton {
30    pub key: Option<KeyRef>,
31    /// Called when this button is pressed.
32    pub on_pressed: Option<Listener>,
33    /// The child of this button.
34    ///
35    /// Usually a [`Text`].
36    pub child: WidgetRef,
37}
38
39impl Debug for DesktopTextSelectionToolbarButton {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        f.debug_struct("DesktopTextSelectionToolbarButton")
42            .finish_non_exhaustive()
43    }
44}
45
46impl DesktopTextSelectionToolbarButton {
47    /// Creates an instance of DesktopTextSelectionToolbarButton.
48    #[cfg_attr(debug_assertions, track_caller)]
49    pub fn new<K>(
50        on_pressed: Option<Listener>,
51        child: impl IntoWidget<K>,
52    ) -> DesktopTextSelectionToolbarButton {
53        DesktopTextSelectionToolbarButton {
54            key: None,
55            on_pressed,
56            child: child.into_widget(),
57        }
58    }
59
60    /// Create an instance of [`DesktopTextSelectionToolbarButton`] whose child is
61    /// a [`Text`] widget in the style of the Material text selection toolbar.
62    pub fn text(
63        app: &mut App,
64        context: BuildContext,
65        on_pressed: Option<Listener>,
66        text: impl Into<String>,
67    ) -> DesktopTextSelectionToolbarButton {
68        let color = if Theme::of(app, context).color_scheme.brightness() == Brightness::Dark {
69            Colors::WHITE
70        } else {
71            Colors::BLACK87
72        };
73        DesktopTextSelectionToolbarButton {
74            key: None,
75            on_pressed,
76            child: Text::new(text)
77                .overflow(TextOverflow::Ellipsis)
78                .style(k_toolbar_button_font_style().copy_with().color(color))
79                .into_widget(),
80        }
81    }
82
83    /// Dart `DesktopTextSelectionToolbarButton(key:)`.
84    pub fn key(mut self, key: KeyRef) -> DesktopTextSelectionToolbarButton {
85        self.key = Some(key);
86        self
87    }
88}
89
90impl StatelessWidget for DesktopTextSelectionToolbarButton {
91    fn key(&self) -> Option<&KeyRef> {
92        self.key.as_ref()
93    }
94
95    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
96        // TODO(hansmuller): Should be colorScheme.onSurface
97        let theme = Theme::of(app, context);
98        let is_dark = theme.color_scheme.brightness() == Brightness::Dark;
99        let foreground_color = if is_dark {
100            Colors::WHITE
101        } else {
102            Colors::BLACK87
103        };
104
105        SizedBox::new()
106            .width(f64::INFINITY)
107            .child(
108                TextButton::new(self.on_pressed.clone(), Some(self.child.clone())).style(
109                    TextButton::style_from()
110                        .alignment(AlignmentGeometry::CENTER_LEFT)
111                        .enabled_mouse_cursor(SystemMouseCursors::BASIC.into())
112                        .disabled_mouse_cursor(SystemMouseCursors::BASIC.into())
113                        .foreground_color(foreground_color)
114                        .shape(RoundedRectangleBorder::default())
115                        .minimum_size(Size::new(K_MIN_INTERACTIVE_DIMENSION, 36.0))
116                        .padding(K_TOOLBAR_BUTTON_PADDING.into())
117                        .build(),
118                ),
119            )
120            .into_widget()
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use std::cell::Cell;
127    use std::rc::Rc;
128
129    use waft_widgets::Center;
130    use waft_widgets::testing::{WidgetTester, find, test_widgets};
131
132    use super::*;
133    use crate::button_style_button::ButtonStyleButton;
134    use crate::test_support::material_app;
135    use crate::theme_data::ThemeData;
136
137    /// `MaterialApp(home: Center(child: child))`.
138    fn pump_centered<K>(tester: &mut WidgetTester, child: impl IntoWidget<K>) {
139        let root = {
140            let app = tester.cell.borrow();
141            material_app(
142                ThemeData::new(&app),
143                Center::new().child(child).into_widget(),
144            )
145        };
146        tester.pump_widget(root);
147    }
148
149    #[test]
150    fn can_press() {
151        test_widgets(|tester| {
152            let pressed = Rc::new(Cell::new(false));
153            let on_pressed = {
154                let pressed = Rc::clone(&pressed);
155                Listener::new(move |_app| pressed.set(true))
156            };
157            pump_centered(
158                tester,
159                DesktopTextSelectionToolbarButton::new(Some(on_pressed), Text::new("Tap me")),
160            );
161
162            assert!(!pressed.get());
163
164            let buttons = find::by_type::<DesktopTextSelectionToolbarButton>().evaluate(tester);
165            let center = tester.get_rect(buttons[0]).center();
166            tester.tap_at(center, 1);
167            assert!(pressed.get());
168        });
169    }
170
171    #[test]
172    fn passing_null_to_on_pressed_disables_the_button() {
173        test_widgets(|tester| {
174            pump_centered(
175                tester,
176                DesktopTextSelectionToolbarButton::new(None, Text::new("Cannot tap me")),
177            );
178
179            let buttons = find::by_type::<TextButton>().evaluate(tester);
180            assert_eq!(buttons.len(), 1);
181            assert!(!tester.widget(buttons[0], |button: &TextButton| button.enabled()));
182        });
183    }
184
185    #[test]
186    fn desktop_text_selection_toolbar_button_does_not_crash_at_zero_area() {
187        test_widgets(|tester| {
188            pump_centered(
189                tester,
190                SizedBox::shrink()
191                    .child(DesktopTextSelectionToolbarButton::new(None, Text::new("X"))),
192            );
193            let buttons = find::by_type::<DesktopTextSelectionToolbarButton>().evaluate(tester);
194            assert_eq!(tester.get_size(buttons[0]), Size::ZERO);
195        });
196    }
197}