Skip to main content

waft_material/
selection_area.rs

1//! Flutter counterpart: `material/selection_area.dart`.
2//!
3//! A [`SelectionArea`] is a [`SelectableRegion`] with this platform's selection controls and a
4//! Material context menu over them, so a subtree of texts, cards and lists can be selected and
5//! copied.
6
7use std::rc::Rc;
8
9use waft_embedder::TargetPlatform;
10use waft_foundation::{App, Handle, ValueChanged};
11use waft_widgets::{
12    BuildContext, FocusNodeRef, GlobalKey, IntoWidget, KeyRef, SelectableRegion,
13    SelectableRegionContextMenuBuilder, SelectableRegionState, State, StateData, StatefulWidget,
14    TextMagnifierConfiguration, TextSelectionControls, WidgetRef,
15};
16
17use waft_cupertino::{
18    cupertino_desktop_text_selection_handle_controls, cupertino_text_selection_handle_controls,
19};
20use waft_rendering::SelectedContent;
21
22use crate::adaptive_text_selection_toolbar::AdaptiveTextSelectionToolbar;
23use crate::debug::debug_check_has_material_localizations;
24use crate::desktop_text_selection::desktop_text_selection_handle_controls;
25use crate::magnifier::TextMagnifier;
26use crate::text_selection::material_text_selection_handle_controls;
27use crate::theme::Theme;
28
29/// A widget that introduces an area for user selections with adaptive selection controls.
30///
31/// It is a [`SelectableRegion`] whose controls and context menu follow the ambient
32/// [`Theme`]'s platform.
33pub struct SelectionArea {
34    /// See [`Widget::key`](waft_widgets::Widget::key).
35    pub key: Option<KeyRef>,
36    /// The configuration for the magnifier in the selection region.
37    pub magnifier_configuration: Option<TextMagnifierConfiguration>,
38    /// The focus node of the region the area builds.
39    pub focus_node: Option<FocusNodeRef>,
40    /// The delegate that builds the selection handles and toolbar; one of the platform's own
41    /// when `None`.
42    pub selection_controls: Option<Rc<dyn TextSelectionControls>>,
43    /// Builds the context menu; `None` shows none.
44    pub context_menu_builder: Option<SelectableRegionContextMenuBuilder>,
45    /// Called when the selected content changes.
46    pub on_selection_changed: Option<ValueChanged<Option<SelectedContent>>>,
47    /// The child widget this selection area applies to.
48    pub child: WidgetRef,
49}
50
51impl SelectionArea {
52    /// Creates a selection area over `child`.
53    #[cfg_attr(debug_assertions, track_caller)]
54    pub fn new<K>(child: impl IntoWidget<K>) -> SelectionArea {
55        SelectionArea {
56            key: None,
57            magnifier_configuration: None,
58            focus_node: None,
59            selection_controls: None,
60            context_menu_builder: Some(Rc::new(Self::default_context_menu_builder)),
61            on_selection_changed: None,
62            child: child.into_widget(),
63        }
64    }
65
66    /// Dart `SelectionArea(key:)`.
67    pub fn key(mut self, key: KeyRef) -> SelectionArea {
68        self.key = Some(key);
69        self
70    }
71
72    /// Dart `SelectionArea(focusNode:)`.
73    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> SelectionArea {
74        self.focus_node = Some(focus_node);
75        self
76    }
77
78    /// Dart `SelectionArea(selectionControls:)`.
79    pub fn selection_controls(
80        mut self,
81        selection_controls: Rc<dyn TextSelectionControls>,
82    ) -> SelectionArea {
83        self.selection_controls = Some(selection_controls);
84        self
85    }
86
87    /// Dart `SelectionArea(contextMenuBuilder:)`.
88    pub fn context_menu_builder(
89        mut self,
90        context_menu_builder: Option<SelectableRegionContextMenuBuilder>,
91    ) -> SelectionArea {
92        self.context_menu_builder = context_menu_builder;
93        self
94    }
95
96    /// Dart `SelectionArea(magnifierConfiguration:)`.
97    pub fn magnifier_configuration(
98        mut self,
99        magnifier_configuration: TextMagnifierConfiguration,
100    ) -> SelectionArea {
101        self.magnifier_configuration = Some(magnifier_configuration);
102        self
103    }
104
105    /// Dart `SelectionArea(onSelectionChanged:)`.
106    pub fn on_selection_changed(
107        mut self,
108        on_selection_changed: ValueChanged<Option<SelectedContent>>,
109    ) -> SelectionArea {
110        self.on_selection_changed = Some(on_selection_changed);
111        self
112    }
113
114    /// The area's default context menu, as `AdaptiveTextSelectionToolbar.selectableRegion`.
115    fn default_context_menu_builder(
116        app: &mut App,
117        _context: BuildContext,
118        state: Handle<SelectableRegionState>,
119    ) -> WidgetRef {
120        AdaptiveTextSelectionToolbar::selectable_region(app, state).into_widget()
121    }
122}
123
124impl std::fmt::Debug for SelectionArea {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.debug_struct("SelectionArea").finish_non_exhaustive()
127    }
128}
129
130impl StatefulWidget for SelectionArea {
131    type State = SelectionAreaState;
132
133    fn key(&self) -> Option<&KeyRef> {
134        self.key.as_ref()
135    }
136
137    fn create_state(&self) -> SelectionAreaState {
138        SelectionAreaState {
139            state: StateData::new(),
140            selectable_region_key: GlobalKey::new(),
141        }
142    }
143}
144
145/// State for a [`SelectionArea`].
146pub struct SelectionAreaState {
147    state: StateData<SelectionArea>,
148    /// The key of the [`SelectableRegion`] this area builds.
149    selectable_region_key: GlobalKey,
150}
151
152impl SelectionAreaState {
153    /// The state of the [`SelectableRegion`] this area wraps.
154    pub fn selectable_region(self: Handle<Self>, app: &App) -> Handle<SelectableRegionState> {
155        app.get(self)
156            .selectable_region_key
157            .current_state::<SelectableRegionState>(app)
158            .expect("the area has built its region")
159    }
160}
161
162impl State for SelectionAreaState {
163    type Widget = SelectionArea;
164    waft_widgets::state_accessors!();
165
166    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
167        debug_assert!(
168            debug_check_has_material_localizations(app, context),
169            "A SelectionArea needs a MaterialLocalizations ancestor, as a MaterialApp provides."
170        );
171        let (
172            selection_controls,
173            context_menu_builder,
174            magnifier_configuration,
175            focus_node,
176            on_selection_changed,
177            child,
178        ) = {
179            let widget = self.widget(app);
180            (
181                widget.selection_controls.clone(),
182                widget.context_menu_builder.clone(),
183                widget.magnifier_configuration.clone(),
184                widget.focus_node.clone(),
185                widget.on_selection_changed.clone(),
186                widget.child.clone(),
187            )
188        };
189        let controls =
190            selection_controls.unwrap_or_else(|| match Theme::of(app, context).platform {
191                TargetPlatform::Android | TargetPlatform::Fuchsia => {
192                    material_text_selection_handle_controls()
193                }
194                TargetPlatform::Linux | TargetPlatform::Windows => {
195                    desktop_text_selection_handle_controls()
196                }
197                TargetPlatform::IOS => cupertino_text_selection_handle_controls(),
198                TargetPlatform::MacOS => cupertino_desktop_text_selection_handle_controls(),
199            });
200        let region_key = app.get(self).selectable_region_key.clone();
201        let mut region = SelectableRegion::new(controls, child)
202            .key(KeyRef::Global(region_key))
203            .magnifier_configuration(
204                magnifier_configuration
205                    .unwrap_or_else(|| TextMagnifier::adaptive_magnifier_configuration(app)),
206            );
207        if let Some(context_menu_builder) = context_menu_builder {
208            region = region.context_menu_builder(context_menu_builder);
209        }
210        if let Some(focus_node) = focus_node {
211            region = region.focus_node(focus_node);
212        }
213        if let Some(on_selection_changed) = on_selection_changed {
214            region = region.on_selection_changed(on_selection_changed);
215        }
216        region.into_widget()
217    }
218}
219
220#[cfg(test)]
221pub(crate) mod tests {
222    //! `selection_area_test.dart`'s cases.
223
224    use waft_embedder::{Offset, Rect, TargetPlatform, TextPosition};
225    use waft_rendering::{RenderBox, RenderHandle, RenderParagraph};
226
227    use waft_widgets::Text;
228    use waft_widgets::testing::{
229        TargetPlatformVariant, TestPointer, WidgetTester, find, test_widgets, test_widgets_variant,
230    };
231
232    use super::*;
233    use crate::app::MaterialApp;
234    use crate::text_selection::material_text_selection_handle_controls;
235    use waft_cupertino::{
236        cupertino_desktop_text_selection_handle_controls, cupertino_text_selection_handle_controls,
237    };
238    use waft_gestures::K_PRIMARY_BUTTON;
239
240    /// The global position of the caret at `offset` in `paragraph`, as flutter_test's
241    /// `textOffsetToPosition` places it.
242    fn text_offset_to_position(
243        tester: &mut WidgetTester,
244        paragraph: RenderHandle<RenderParagraph>,
245        offset: i32,
246    ) -> Offset {
247        tester.update(|app| {
248            let caret = Rect::from_ltwh(0.0, 0.0, 2.0, 20.0);
249            let local = paragraph.get_offset_for_caret(app, TextPosition::new(offset), caret);
250            paragraph.as_box().local_to_global(app, local, None)
251        })
252    }
253
254    /// The paragraph showing `text`.
255    fn paragraph_showing(tester: &WidgetTester, text: &str) -> RenderHandle<RenderParagraph> {
256        let paragraphs = tester.all::<RenderParagraph>();
257        tester.update(|app| {
258            *paragraphs
259                .iter()
260                .find(|paragraph| paragraph.text(app).to_plain_text(true, true) == text)
261                .unwrap_or_else(|| panic!("a paragraph showing {text}"))
262        })
263    }
264
265    // selection_area_test.dart 'SelectionArea uses correct selection controls'.
266    #[test]
267    fn selection_area_uses_correct_selection_controls() {
268        test_widgets_variant(TargetPlatformVariant::all(), |tester| {
269            tester.pump_widget(MaterialApp::new().home(SelectionArea::new(Text::new("abc"))));
270            let region = tester.widget(
271                tester.element(find::by_type::<SelectableRegion>()),
272                |region: &SelectableRegion| region.selection_controls.clone(),
273            );
274            let expected: Rc<dyn TextSelectionControls> = match tester.target_platform() {
275                TargetPlatform::Android | TargetPlatform::Fuchsia => {
276                    material_text_selection_handle_controls()
277                }
278                TargetPlatform::IOS => cupertino_text_selection_handle_controls(),
279                TargetPlatform::Linux | TargetPlatform::Windows => {
280                    desktop_text_selection_handle_controls()
281                }
282                TargetPlatform::MacOS => cupertino_desktop_text_selection_handle_controls(),
283            };
284            assert!(Rc::ptr_eq(&region, &expected));
285        });
286    }
287
288    // selection_area_test.dart 'onSelectionChange is called when the selection changes'.
289    #[test]
290    fn on_selection_change_is_called_when_the_selection_changes() {
291        test_widgets(|tester| {
292            let content: Rc<std::cell::RefCell<Option<SelectedContent>>> =
293                Rc::new(std::cell::RefCell::new(None));
294            let log = Rc::clone(&content);
295            tester.pump_widget(MaterialApp::new().home(
296                SelectionArea::new(Text::new("How are you")).on_selection_changed(Rc::new(
297                    move |_app, selected_content| *log.borrow_mut() = selected_content,
298                )),
299            ));
300            let plain_text = || content.borrow().as_ref().map(|c| c.plain_text.clone());
301            let paragraph = paragraph_showing(tester, "How are you");
302            let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
303            let at = text_offset_to_position(tester, paragraph, 4);
304            tester.down(&mut gesture, at);
305            assert!(content.borrow().is_none());
306            tester.pump();
307
308            let at = text_offset_to_position(tester, paragraph, 7);
309            tester.move_to(&mut gesture, at, true);
310            tester.up(&gesture);
311            tester.pump();
312            assert_eq!(plain_text(), Some("are".to_string()));
313
314            // Backwards selection.
315            let at = text_offset_to_position(tester, paragraph, 3);
316            tester.down(&mut gesture, at);
317            tester.pump();
318            tester.up(&gesture);
319            tester.pump_and_settle_by(waft_gestures::K_DOUBLE_TAP_TIMEOUT);
320            assert_eq!(plain_text(), Some(String::new()));
321
322            let at = text_offset_to_position(tester, paragraph, 3);
323            tester.down(&mut gesture, at);
324            tester.pump();
325            let at = text_offset_to_position(tester, paragraph, 0);
326            tester.move_to(&mut gesture, at, true);
327            tester.up(&gesture);
328            tester.pump();
329            assert_eq!(plain_text(), Some("How".to_string()));
330            tester.remove_pointer(&gesture);
331        });
332    }
333
334    // selection_area_test.dart 'SelectionArea does not crash at zero area'.
335    #[test]
336    fn selection_area_does_not_crash_at_zero_area() {
337        test_widgets(|tester| {
338            tester.pump_widget(MaterialApp::new().home(waft_widgets::Center::new().child(
339                waft_widgets::SizedBox::shrink().child(SelectionArea::new(Text::new("X"))),
340            )));
341            assert_eq!(
342                tester.get_size(find::by_type::<SelectionArea>()),
343                waft_embedder::Size::ZERO
344            );
345        });
346    }
347}