Skip to main content

waft_material/
desktop_text_selection_toolbar.rs

1//! Flutter counterpart: material_ui's `desktop_text_selection_toolbar.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_embedder::{Clip, Offset, Radius};
7use waft_foundation::App;
8use waft_painting::{BorderRadius, EdgeInsetsGeometry};
9use waft_widgets::{
10    BuildContext, Column, CustomSingleChildLayout, DesktopTextSelectionToolbarLayoutDelegate,
11    IntoWidget, KeyRef, MainAxisSize, MediaQuery, Padding, SizedBox, StatelessWidget, WidgetRef,
12    debug_check_has_media_query,
13};
14
15use crate::material::{Material, MaterialType};
16
17// These values were measured from a screenshot of TextEdit on macOS 10.15.7 on
18// a Macbook Pro.
19const K_TOOLBAR_SCREEN_PADDING: f64 = 8.0;
20const K_TOOLBAR_WIDTH: f64 = 222.0;
21
22/// A Material-style desktop text selection toolbar.
23///
24/// Typically displays buttons for text manipulation, e.g. copying and pasting
25/// text.
26///
27/// Tries to position its top left corner as closely as possible to [`anchor`](Self::anchor)
28/// while remaining fully inside the viewport.
29///
30/// See also:
31///
32///  * `AdaptiveTextSelectionToolbar`, which builds the toolbar for the current
33///    platform.
34///  * `TextSelectionToolbar`, which is similar, but builds an Android-style
35///    toolbar.
36pub struct DesktopTextSelectionToolbar {
37    pub key: Option<KeyRef>,
38    /// The point where the toolbar will attempt to position itself as closely as
39    /// possible.
40    pub anchor: Offset,
41    /// The children that will be displayed in the text selection toolbar.
42    ///
43    /// Typically these are buttons.
44    ///
45    /// Must not be empty.
46    ///
47    /// See also:
48    ///   * `DesktopTextSelectionToolbarButton`, which builds a default
49    ///     Material-style desktop text selection toolbar text button.
50    pub children: Vec<WidgetRef>,
51}
52
53impl Debug for DesktopTextSelectionToolbar {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.debug_struct("DesktopTextSelectionToolbar")
56            .field("anchor", &self.anchor)
57            .finish_non_exhaustive()
58    }
59}
60
61impl DesktopTextSelectionToolbar {
62    /// Creates a const instance of DesktopTextSelectionToolbar.
63    pub fn new(
64        anchor: Offset,
65        children: impl IntoIterator<Item = WidgetRef>,
66    ) -> DesktopTextSelectionToolbar {
67        let children: Vec<WidgetRef> = children.into_iter().collect();
68        debug_assert!(!children.is_empty());
69        DesktopTextSelectionToolbar {
70            key: None,
71            anchor,
72            children,
73        }
74    }
75
76    /// Dart `DesktopTextSelectionToolbar(key:)`.
77    pub fn key(mut self, key: KeyRef) -> DesktopTextSelectionToolbar {
78        self.key = Some(key);
79        self
80    }
81
82    // Builds a desktop toolbar in the Material style.
83    fn default_toolbar_builder(
84        _app: &mut App,
85        _context: BuildContext,
86        child: WidgetRef,
87    ) -> WidgetRef {
88        SizedBox::new()
89            .width(K_TOOLBAR_WIDTH)
90            .child(
91                Material::new()
92                    .border_radius(BorderRadius::all(Radius::circular(7.0)))
93                    .clip_behavior(Clip::AntiAlias)
94                    .elevation(1.0)
95                    .r#type(MaterialType::Card)
96                    .child(child),
97            )
98            .into_widget()
99    }
100}
101
102impl StatelessWidget for DesktopTextSelectionToolbar {
103    fn key(&self) -> Option<&KeyRef> {
104        self.key.as_ref()
105    }
106
107    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
108        debug_assert!(debug_check_has_media_query(app, context));
109
110        let padding_above = MediaQuery::padding_of(app, context).top + K_TOOLBAR_SCREEN_PADDING;
111        let local_adjustment = Offset::new(K_TOOLBAR_SCREEN_PADDING, padding_above);
112
113        Padding::new(EdgeInsetsGeometry::from_ltrb(
114            K_TOOLBAR_SCREEN_PADDING,
115            padding_above,
116            K_TOOLBAR_SCREEN_PADDING,
117            K_TOOLBAR_SCREEN_PADDING,
118        ))
119        .child(
120            CustomSingleChildLayout::new(Rc::new(DesktopTextSelectionToolbarLayoutDelegate::new(
121                self.anchor - local_adjustment,
122            )))
123            .child(Self::default_toolbar_builder(
124                app,
125                context,
126                Column::new()
127                    .main_axis_size(MainAxisSize::Min)
128                    .children(self.children.clone())
129                    .into_widget(),
130            )),
131        )
132        .into_widget()
133    }
134}
135
136#[cfg(test)]
137mod tests {
138
139    use waft_foundation::Listener;
140    use waft_widgets::{Center, Text};
141
142    use waft_widgets::testing::{WidgetTester, find, test_widgets};
143
144    use super::*;
145    use crate::desktop_text_selection_toolbar_button::DesktopTextSelectionToolbarButton;
146    use crate::test_support::material_app;
147    use crate::theme_data::ThemeData;
148
149    /// `MaterialApp(home: Center(child: child))`.
150    fn pump_centered<K>(tester: &mut WidgetTester, child: impl IntoWidget<K>) {
151        let root = {
152            let app = tester.cell.borrow();
153            material_app(
154                ThemeData::new(&app),
155                Center::new().child(child).into_widget(),
156            )
157        };
158        tester.pump_widget(root);
159    }
160
161    #[test]
162    fn positions_itself_at_the_anchor() {
163        test_widgets(|tester| {
164            // An arbitrary point on the screen to position at.
165            let anchor = Offset::new(30.0, 40.0);
166
167            pump_centered(
168                tester,
169                DesktopTextSelectionToolbar::new(
170                    anchor,
171                    [DesktopTextSelectionToolbarButton::new(
172                        Some(Listener::new(|_app| {})),
173                        Text::new("Tap me"),
174                    )
175                    .into_widget()],
176                ),
177            );
178
179            let buttons = find::by_type::<DesktopTextSelectionToolbarButton>().evaluate(tester);
180            let top_left = tester.get_rect(buttons[0]).top_left();
181            assert_eq!(top_left, anchor);
182        });
183    }
184
185    #[test]
186    fn desktop_text_selection_toolbar_renders_at_zero_area() {
187        test_widgets(|tester| {
188            pump_centered(
189                tester,
190                SizedBox::shrink().child(DesktopTextSelectionToolbar::new(
191                    Offset::new(10.0, 10.0),
192                    [Text::new("X").into_widget()],
193                )),
194            );
195            let toolbars = find::by_type::<DesktopTextSelectionToolbar>().evaluate(tester);
196            let render = tester.render_box_of(toolbars[0]);
197            assert!(render.size(&tester.cell.borrow()).is_empty());
198        });
199    }
200}