Skip to main content

waft_material/
spell_check_suggestions_toolbar_layout_delegate.rs

1//! Flutter counterpart: material_ui's `spell_check_suggestions_toolbar_layout_delegate.dart`.
2
3use std::any::Any;
4
5use waft_embedder::{Offset, Size};
6use waft_rendering::{BoxConstraints, SingleChildLayoutDelegate};
7use waft_widgets::TextSelectionToolbarLayoutDelegate;
8
9/// Positions the toolbar below [`anchor`](Self::anchor) or adjusts it higher to fit above
10/// the bottom view insets, if applicable.
11///
12/// See also:
13///
14///   * `SpellCheckSuggestionsToolbar`, which uses this to position itself.
15#[derive(Debug)]
16pub struct SpellCheckSuggestionsToolbarLayoutDelegate {
17    /// The focal point below which the toolbar attempts to position itself.
18    ///
19    /// Should be provided in local coordinates.
20    pub anchor: Offset,
21}
22
23impl SpellCheckSuggestionsToolbarLayoutDelegate {
24    /// Creates an instance of [`SpellCheckSuggestionsToolbarLayoutDelegate`].
25    pub fn new(anchor: Offset) -> SpellCheckSuggestionsToolbarLayoutDelegate {
26        SpellCheckSuggestionsToolbarLayoutDelegate { anchor }
27    }
28}
29
30impl SingleChildLayoutDelegate for SpellCheckSuggestionsToolbarLayoutDelegate {
31    fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
32        constraints.loosen()
33    }
34
35    fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
36        Offset::new(
37            TextSelectionToolbarLayoutDelegate::center_on(
38                self.anchor.dx(),
39                child_size.width(),
40                size.width(),
41            ),
42            // Positions child (of childSize) just enough upwards to fit within size
43            // if it otherwise does not fit below the anchor.
44            if self.anchor.dy() + child_size.height() > size.height() {
45                size.height() - child_size.height()
46            } else {
47                self.anchor.dy()
48            },
49        )
50    }
51
52    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
53        old_delegate
54            .as_any()
55            .downcast_ref::<SpellCheckSuggestionsToolbarLayoutDelegate>()
56            .is_none_or(|old| self.anchor != old.anchor)
57    }
58
59    fn as_any(&self) -> &dyn Any {
60        self
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use std::cell::{Cell, RefCell};
67    use std::rc::Rc;
68
69    use waft_embedder::{Color, TextDirection};
70    use waft_widgets::{
71        Container, CustomSingleChildLayout, Directionality, IntoWidget, MediaQuery, MediaQueryData,
72        StateSetter, StatefulBuilder,
73    };
74
75    use waft_widgets::testing::{WidgetTester, find, test_widgets};
76
77    use super::*;
78
79    #[test]
80    fn positions_itself_at_anchor_above_if_it_fits_and_shifts_up_when_not() {
81        test_widgets(|_tester| {
82            let mut tester = WidgetTester::on(waft_embedder::TargetPlatform::Android);
83            let set_state: Rc<RefCell<Option<StateSetter>>> = Rc::new(RefCell::new(None));
84            const TOOLBAR_OVERLAP: f64 = 100.0;
85            const HEIGHT: f64 = 500.0;
86            let anchor_y = Rc::new(Cell::new(200.0));
87
88            let builder = {
89                let set_state = Rc::clone(&set_state);
90                let anchor_y = Rc::clone(&anchor_y);
91                StatefulBuilder::new(move |_app, _context, setter| {
92                    *set_state.borrow_mut() = Some(setter);
93                    CustomSingleChildLayout::new(Rc::new(
94                        SpellCheckSuggestionsToolbarLayoutDelegate::new(Offset::new(
95                            50.0,
96                            anchor_y.get(),
97                        )),
98                    ))
99                    .child(
100                        Container::new()
101                            .width(200.0)
102                            .height(HEIGHT)
103                            .color(Color::new(0xffff0000)),
104                    )
105                    .into_widget()
106                })
107            };
108            tester.pump_widget(
109                MediaQuery::new(
110                    MediaQueryData::new(),
111                    Directionality::new(TextDirection::Ltr, builder),
112                )
113                .into_widget(),
114            );
115
116            let toolbar_y = |tester: &WidgetTester| {
117                let container = find::by_type::<Container>().evaluate(tester)[0];
118                tester.get_rect(container).top
119            };
120
121            // When the toolbar doesn't fit below anchor, it positions itself such that
122            // it can just fit.
123            // Total height available is 600.
124            assert_eq!(toolbar_y(&tester), TOOLBAR_OVERLAP);
125
126            // When it does fit below anchor, it positions itself there.
127            let setter = set_state.borrow().clone().expect("the builder built");
128            setter(&mut tester.cell.borrow_mut(), &mut |_app| {
129                anchor_y.set(anchor_y.get() - TOOLBAR_OVERLAP);
130            });
131            tester.pump();
132            assert_eq!(toolbar_y(&tester), anchor_y.get());
133        });
134    }
135}