Skip to main content

waft_material/
text_selection_toolbar_text_button.rs

1//! Flutter counterpart: material_ui's `text_selection_toolbar_text_button.dart`.
2
3use std::fmt::{self, Debug};
4
5use waft_embedder::{Brightness, Color, FontWeight, Size};
6use waft_foundation::{App, Listener};
7use waft_painting::{
8    AlignmentGeometry, EdgeInsetsDirectional, EdgeInsetsGeometry, RoundedRectangleBorder, TextStyle,
9};
10use waft_widgets::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
11
12use crate::color_scheme::ColorScheme;
13use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
14use crate::text_button::TextButton;
15use crate::theme::Theme;
16use crate::theme_data::ThemeData;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19enum TextSelectionToolbarItemPosition {
20    /// The first item among multiple in the menu.
21    First,
22
23    /// One of several items, not the first or last.
24    Middle,
25
26    /// The last item among multiple in the menu.
27    Last,
28
29    /// The only item in the menu.
30    Only,
31}
32
33/// A button styled like a Material native Android text selection menu button.
34#[derive(Clone)]
35pub struct TextSelectionToolbarTextButton {
36    pub key: Option<KeyRef>,
37    /// The child of this button.
38    ///
39    /// Usually a `Text`.
40    pub child: WidgetRef,
41    /// Called when this button is pressed.
42    pub on_pressed: Option<Listener>,
43    /// The padding between the button's edge and its child.
44    ///
45    /// In a standard Material `TextSelectionToolbar`, the padding depends on the
46    /// button's position within the toolbar.
47    ///
48    /// See also:
49    ///
50    ///  * [`get_padding`](Self::get_padding), which calculates the standard padding based on
51    ///    the button's position.
52    ///  * `ButtonStyle::padding`, which is where this padding is applied.
53    pub padding: EdgeInsetsGeometry,
54    /// The alignment of the button's child.
55    ///
56    /// By default, this will be `Alignment::CENTER`.
57    ///
58    /// See also:
59    ///
60    ///  * `ButtonStyle::alignment`, which is where this alignment is applied.
61    pub alignment: Option<AlignmentGeometry>,
62}
63
64impl Debug for TextSelectionToolbarTextButton {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.debug_struct("TextSelectionToolbarTextButton")
67            .field("padding", &self.padding)
68            .field("alignment", &self.alignment)
69            .finish_non_exhaustive()
70    }
71}
72
73impl TextSelectionToolbarTextButton {
74    // These values were eyeballed to match the native text selection menu on a
75    // Pixel 2 running Android 10.
76    const K_MIDDLE_PADDING: f64 = 9.5;
77    const K_END_PADDING: f64 = 14.5;
78
79    // These colors were taken from a screenshot of a Pixel 6 emulator running
80    // Android API level 34.
81    const DEFAULT_FOREGROUND_COLOR_LIGHT: Color = Color::new(0xff000000);
82    const DEFAULT_FOREGROUND_COLOR_DARK: Color = Color::new(0xffffffff);
83
84    // The background color is hardcoded to transparent by default so the buttons
85    // are the color of the container behind them. For example TextSelectionToolbar
86    // hardcodes the color value, and TextSelectionToolbarTextButtons that are its
87    // children become that color.
88    const DEFAULT_BACKGROUND_COLOR_TRANSPARENT: Color = Color::new(0x00000000);
89
90    /// Creates an instance of TextSelectionToolbarTextButton.
91    #[cfg_attr(debug_assertions, track_caller)]
92    pub fn new<K>(
93        child: impl IntoWidget<K>,
94        padding: impl Into<EdgeInsetsGeometry>,
95    ) -> TextSelectionToolbarTextButton {
96        TextSelectionToolbarTextButton {
97            key: None,
98            child: child.into_widget(),
99            on_pressed: None,
100            padding: padding.into(),
101            alignment: None,
102        }
103    }
104
105    /// Dart `TextSelectionToolbarTextButton(key:)`.
106    pub fn key(mut self, key: KeyRef) -> TextSelectionToolbarTextButton {
107        self.key = Some(key);
108        self
109    }
110
111    /// Dart `TextSelectionToolbarTextButton.copyWith(child:)`.
112    #[cfg_attr(debug_assertions, track_caller)]
113    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> TextSelectionToolbarTextButton {
114        self.child = child.into_widget();
115        self
116    }
117
118    /// Dart `TextSelectionToolbarTextButton(onPressed:)`.
119    pub fn on_pressed(mut self, on_pressed: Listener) -> TextSelectionToolbarTextButton {
120        self.on_pressed = Some(on_pressed);
121        self
122    }
123
124    /// Dart `TextSelectionToolbarTextButton.copyWith(padding:)`.
125    pub fn padding(
126        mut self,
127        padding: impl Into<EdgeInsetsGeometry>,
128    ) -> TextSelectionToolbarTextButton {
129        self.padding = padding.into();
130        self
131    }
132
133    /// Dart `TextSelectionToolbarTextButton(alignment:)`.
134    pub fn alignment(
135        mut self,
136        alignment: impl Into<AlignmentGeometry>,
137    ) -> TextSelectionToolbarTextButton {
138        self.alignment = Some(alignment.into());
139        self
140    }
141
142    /// Returns the standard padding for a button at index out of a total number
143    /// of buttons.
144    ///
145    /// Standard Material `TextSelectionToolbar`s have buttons with different
146    /// padding depending on their position in the toolbar.
147    pub fn get_padding(index: usize, total: usize) -> EdgeInsetsGeometry {
148        debug_assert!(total > 0 && index < total);
149        let position = Self::get_position(index, total);
150        EdgeInsetsDirectional::only(
151            Self::get_start_padding(position),
152            0.0,
153            Self::get_end_padding(position),
154            0.0,
155        )
156        .into()
157    }
158
159    fn get_start_padding(position: TextSelectionToolbarItemPosition) -> f64 {
160        if position == TextSelectionToolbarItemPosition::First
161            || position == TextSelectionToolbarItemPosition::Only
162        {
163            return Self::K_END_PADDING;
164        }
165        Self::K_MIDDLE_PADDING
166    }
167
168    fn get_end_padding(position: TextSelectionToolbarItemPosition) -> f64 {
169        if position == TextSelectionToolbarItemPosition::Last
170            || position == TextSelectionToolbarItemPosition::Only
171        {
172            return Self::K_END_PADDING;
173        }
174        Self::K_MIDDLE_PADDING
175    }
176
177    fn get_position(index: usize, total: usize) -> TextSelectionToolbarItemPosition {
178        if index == 0 {
179            return if total == 1 {
180                TextSelectionToolbarItemPosition::Only
181            } else {
182                TextSelectionToolbarItemPosition::First
183            };
184        }
185        if index == total - 1 {
186            return TextSelectionToolbarItemPosition::Last;
187        }
188        TextSelectionToolbarItemPosition::Middle
189    }
190
191    /// Returns a copy of the current [`TextSelectionToolbarTextButton`] instance
192    /// with specific overrides.
193    ///
194    /// Like Dart's, the copy has no key.
195    pub fn copy_with(&self) -> TextSelectionToolbarTextButton {
196        TextSelectionToolbarTextButton {
197            key: None,
198            ..self.clone()
199        }
200    }
201
202    fn get_foreground_color(app: &App, color_scheme: &ColorScheme) -> Color {
203        let is_default_on_surface = match color_scheme.brightness() {
204            Brightness::Light => {
205                ThemeData::new(app).color_scheme.on_surface() == color_scheme.on_surface()
206            }
207            Brightness::Dark => {
208                ThemeData::dark(app, None).color_scheme.on_surface() == color_scheme.on_surface()
209            }
210        };
211        if !is_default_on_surface {
212            return color_scheme.on_surface();
213        }
214        match color_scheme.brightness() {
215            Brightness::Light => Self::DEFAULT_FOREGROUND_COLOR_LIGHT,
216            Brightness::Dark => Self::DEFAULT_FOREGROUND_COLOR_DARK,
217        }
218    }
219}
220
221impl StatelessWidget for TextSelectionToolbarTextButton {
222    fn key(&self) -> Option<&KeyRef> {
223        self.key.as_ref()
224    }
225
226    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
227        let color_scheme = Theme::of(app, context).color_scheme.clone();
228        let mut style = TextButton::style_from()
229            .background_color(Self::DEFAULT_BACKGROUND_COLOR_TRANSPARENT)
230            .foreground_color(Self::get_foreground_color(app, &color_scheme))
231            .shape(RoundedRectangleBorder::default())
232            .minimum_size(Size::new(
233                K_MIN_INTERACTIVE_DIMENSION,
234                K_MIN_INTERACTIVE_DIMENSION,
235            ))
236            .padding(self.padding);
237        if let Some(alignment) = self.alignment {
238            style = style.alignment(alignment);
239        }
240        // This value was eyeballed from a screenshot of a Pixel 6 emulator
241        // running Android API level 34.
242        style = style.text_style(TextStyle::new().font_weight(FontWeight::W400));
243        TextButton::new(self.on_pressed.clone(), Some(self.child.clone()))
244            .style(style.build())
245            .into_widget()
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use std::cell::RefCell;
252    use std::rc::Rc;
253
254    use waft_painting::EdgeInsets;
255    use waft_widgets::{Center, SizedBox, StateSetter, StatefulBuilder, Text, WidgetStates};
256
257    use waft_widgets::testing::{WidgetTester, find, test_widgets};
258
259    use super::*;
260    use crate::button_style::ButtonStyle;
261    use crate::button_style_button::ButtonStyleButton;
262    use crate::colors::Colors;
263    #[allow(deprecated)]
264    use crate::material_state::MaterialStatePropertyAll;
265    use crate::scaffold::Scaffold;
266    use crate::test_support::material_app;
267    use crate::text_button_theme::TextButtonThemeData;
268
269    /// Dart's `<ColorScheme>[ThemeData().colorScheme, ThemeData.dark().colorScheme]`.
270    fn color_schemes(tester: &WidgetTester) -> [ColorScheme; 2] {
271        let app = tester.cell.borrow();
272        [
273            ThemeData::new(&app).color_scheme,
274            ThemeData::dark(&app, None).color_scheme,
275        ]
276    }
277
278    /// Dart's `ThemeData(colorScheme: color_scheme)`.
279    fn themed(tester: &WidgetTester, color_scheme: ColorScheme) -> ThemeData {
280        ThemeData::builder()
281            .color_scheme(color_scheme)
282            .build(&tester.cell.borrow())
283    }
284
285    /// `MaterialApp(theme: theme, home: Scaffold(body: Center(child: button)))`.
286    fn pump_button(tester: &mut WidgetTester, theme: ThemeData) {
287        let button = TextSelectionToolbarTextButton::new(
288            Text::new("button"),
289            TextSelectionToolbarTextButton::get_padding(0, 1),
290        );
291        tester.pump_widget(material_app(
292            theme,
293            Scaffold::new()
294                .body(Center::new().child(button))
295                .into_widget(),
296        ));
297    }
298
299    /// Dart's `tester.widget<TextButton>(find.byType(TextButton)).style!`.
300    fn text_button_style(tester: &WidgetTester) -> ButtonStyle {
301        let buttons = find::by_type::<TextButton>().evaluate(tester);
302        assert_eq!(buttons.len(), 1, "one TextButton");
303        tester.widget(buttons[0], |button: &TextButton| {
304            button
305                .button_style_button_data()
306                .style
307                .clone()
308                .expect("the button has a style")
309        })
310    }
311
312    #[test]
313    fn position_in_the_toolbar_changes_width() {
314        test_widgets(|tester| {
315            let position = Rc::new(RefCell::new((1, 3)));
316            let set_state: Rc<RefCell<Option<StateSetter>>> = Rc::new(RefCell::new(None));
317            let root = {
318                let app = tester.cell.borrow();
319                let position = Rc::clone(&position);
320                let set_state = Rc::clone(&set_state);
321                material_app(
322                    ThemeData::new(&app),
323                    Scaffold::new()
324                        .body(Center::new().child(StatefulBuilder::new(
325                            move |_app, _context, setter| {
326                                *set_state.borrow_mut() = Some(setter);
327                                let (index, total) = *position.borrow();
328                                TextSelectionToolbarTextButton::new(
329                                    Text::new("button"),
330                                    TextSelectionToolbarTextButton::get_padding(index, total),
331                                )
332                                .into_widget()
333                            },
334                        )))
335                        .into_widget(),
336                )
337            };
338            tester.pump_widget(root);
339            let size = |tester: &WidgetTester| {
340                let buttons = find::by_type::<TextSelectionToolbarTextButton>().evaluate(tester);
341                let render = tester.render_box_of(buttons[0]);
342                render.size(&tester.cell.borrow())
343            };
344            let set = |tester: &mut WidgetTester, index: usize, total: usize| {
345                let setter = set_state.borrow().clone().expect("built");
346                let position = Rc::clone(&position);
347                setter(&mut tester.cell.borrow_mut(), &mut |_app| {
348                    *position.borrow_mut() = (index, total);
349                });
350                tester.pump_by(std::time::Duration::ZERO);
351            };
352
353            let middle_size = size(tester);
354
355            set(tester, 0, 3);
356            let first_size = size(tester);
357            assert!(first_size.width() > middle_size.width());
358
359            set(tester, 2, 3);
360            let last_size = size(tester);
361            assert!(last_size.width() > middle_size.width());
362            assert_eq!(last_size.width(), first_size.width());
363
364            set(tester, 0, 1);
365            let only_size = size(tester);
366            assert!(only_size.width() > middle_size.width());
367            assert!(only_size.width() > first_size.width());
368            assert!(only_size.width() > last_size.width());
369        });
370    }
371
372    #[test]
373    fn foreground_color_by_default() {
374        for index in 0..2 {
375            test_widgets(|tester| {
376                let color_scheme = color_schemes(tester)[index].clone();
377                let brightness = color_scheme.brightness();
378                let theme = themed(tester, color_scheme);
379                pump_button(tester, theme);
380
381                // The foreground color is hardcoded to black or white by default, not the
382                // default value from ColorScheme.onSurface.
383                let style = text_button_style(tester);
384                assert_eq!(
385                    style
386                        .foreground_color
387                        .expect("a foreground color")
388                        .resolve(&WidgetStates::new()),
389                    Some(match brightness {
390                        Brightness::Light => Color::new(0xff000000),
391                        Brightness::Dark => Color::new(0xffffffff),
392                    })
393                );
394            });
395        }
396    }
397
398    #[test]
399    fn custom_foreground_color() {
400        for index in 0..2 {
401            test_widgets(|tester| {
402                let color_scheme = color_schemes(tester)[index].clone();
403                let custom_foreground_color = Colors::RED.primary();
404                let theme = themed(
405                    tester,
406                    color_scheme
407                        .copy_with()
408                        .with_on_surface(custom_foreground_color),
409                );
410                pump_button(tester, theme);
411
412                let style = text_button_style(tester);
413                assert_eq!(
414                    style
415                        .foreground_color
416                        .expect("a foreground color")
417                        .resolve(&WidgetStates::new()),
418                    Some(custom_foreground_color)
419                );
420            });
421        }
422    }
423
424    #[test]
425    fn background_color_by_default() {
426        for index in 0..2 {
427            test_widgets(|tester| {
428                let color_scheme = color_schemes(tester)[index].clone();
429                let theme = themed(tester, color_scheme);
430                pump_button(tester, theme);
431
432                // The background color is hardcoded to transparent by default so the buttons
433                // are the color of the container behind them. For example TextSelectionToolbar
434                // hardcodes the color value, and TextSelectionToolbarTextButton that are its
435                // children should be that color.
436                let style = text_button_style(tester);
437                assert_eq!(
438                    style
439                        .background_color
440                        .expect("a background color")
441                        .resolve(&WidgetStates::new()),
442                    Some(Colors::TRANSPARENT)
443                );
444            });
445        }
446    }
447
448    #[test]
449    #[allow(deprecated)]
450    fn text_button_theme_should_not_override_default_background_color() {
451        for index in 0..2 {
452            test_widgets(|tester| {
453                let color_scheme = color_schemes(tester)[index].clone();
454                let theme = ThemeData::builder()
455                    .color_scheme(color_scheme)
456                    .text_button_theme(TextButtonThemeData::new().style(
457                        ButtonStyle::new().background_color(Rc::new(
458                            MaterialStatePropertyAll::new(Some(Colors::BLUE.primary())),
459                        )),
460                    ))
461                    .build(&tester.cell.borrow());
462                pump_button(tester, theme);
463
464                // The background color is hardcoded to transparent by default so the buttons
465                // are the color of the container behind them. For example TextSelectionToolbar
466                // hardcodes the color value, and TextSelectionToolbarTextButton that are its
467                // children should be that color.
468                let style = text_button_style(tester);
469                assert_eq!(
470                    style
471                        .background_color
472                        .expect("a background color")
473                        .resolve(&WidgetStates::new()),
474                    Some(Colors::TRANSPARENT)
475                );
476            });
477        }
478    }
479
480    #[test]
481    fn text_selection_toolbar_text_button_does_not_crash_at_zero_area() {
482        test_widgets(|tester| {
483            let root = {
484                let app = tester.cell.borrow();
485                material_app(
486                    ThemeData::new(&app),
487                    Center::new()
488                        .child(
489                            SizedBox::shrink().child(TextSelectionToolbarTextButton::new(
490                                Text::new("X"),
491                                EdgeInsets::all(5.0),
492                            )),
493                        )
494                        .into_widget(),
495                )
496            };
497            tester.pump_widget(root);
498            let buttons = find::by_type::<TextSelectionToolbarTextButton>().evaluate(tester);
499            let render = tester.render_box_of(buttons[0]);
500            assert_eq!(render.size(&tester.cell.borrow()), Size::ZERO);
501        });
502    }
503
504    #[test]
505    fn get_padding_gives_the_end_padding_on_the_outer_edges() {
506        let padding = |index, total| match TextSelectionToolbarTextButton::get_padding(index, total)
507        {
508            EdgeInsetsGeometry::Directional(directional) => (directional.start, directional.end),
509            other => panic!("directional padding, not {other:?}"),
510        };
511        assert_eq!(padding(0, 1), (14.5, 14.5));
512        assert_eq!(padding(0, 3), (14.5, 9.5));
513        assert_eq!(padding(1, 3), (9.5, 9.5));
514        assert_eq!(padding(2, 3), (9.5, 14.5));
515    }
516}