Skip to main content

waft_material/
text_selection_toolbar.rs

1//! Flutter counterpart: material_ui's `text_selection_toolbar.dart`.
2//!
3//! Dart's `_TextSelectionToolbarItemsLayoutElement` exists only to override
4//! `debugVisitOnstageChildren`, which Waft's `Element` has not got: the items layout takes the
5//! default `MultiChildRenderObjectElement`.
6
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9use std::time::Duration;
10
11use waft_cupertino::CupertinoTextSelectionToolbar;
12use waft_embedder::{Brightness, Clip, Color, Matrix4, Offset, Radius, Size, TextBaseline};
13use waft_foundation::{App, DiagnosticsNode, Handle, Listener, UniqueKey};
14use waft_painting::{BorderRadius, EdgeInsetsGeometry, TextDirection};
15use waft_rendering::{
16    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ContainerBoxParentData,
17    ContainerParentDataMixin, ContainerRenderObjectData, ContainerRenderObjectMixin,
18    PaintingContext, PipelineOwner, RenderBox, RenderBoxData, RenderHandle, RenderObject,
19    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
20};
21use waft_widgets::AnyElement;
22use waft_widgets::{
23    AnimatedSize, BuildContext, CustomSingleChildLayout, Directionality, Icon, IntoWidget, KeyRef,
24    MediaQuery, MultiChildRenderObjectWidget, Padding, RenderObjectWidget,
25    SingleChildRenderObjectWidget, StandardComponentType, State, StateData, StatefulWidget,
26    StatelessWidget, TextSelectionToolbarLayoutDelegate, ToolbarBuilder, ToolbarItemsParentData,
27    WidgetRef,
28};
29
30use crate::color_scheme::ColorScheme;
31use crate::debug::debug_check_has_material_localizations;
32use crate::icon_button::IconButton;
33use crate::icons::Icons;
34use crate::material::{Material, MaterialType};
35use crate::material_localizations::MaterialLocalizations;
36use crate::theme::Theme;
37use crate::theme_data::ThemeData;
38
39const K_TOOLBAR_HEIGHT: f64 = 44.0;
40const K_TOOLBAR_CONTENT_DISTANCE: f64 = 8.0;
41
42/// A fully-functional Material-style text selection toolbar.
43///
44/// Tries to position itself above [`anchor_above`](Self::anchor_above), but if it doesn't fit,
45/// then it positions itself below [`anchor_below`](Self::anchor_below).
46///
47/// If any children don't fit in the menu, an overflow menu will automatically
48/// be created.
49///
50/// See also:
51///
52///  * `AdaptiveTextSelectionToolbar`, which builds the toolbar for the current
53///    platform.
54///  * [`CupertinoTextSelectionToolbar`], which is similar, but builds an iOS-
55///    style toolbar.
56pub struct TextSelectionToolbar {
57    pub key: Option<KeyRef>,
58    /// The focal point above which the toolbar attempts to position itself.
59    ///
60    /// If there is not enough room above before reaching the top of the screen,
61    /// then the toolbar will position itself below
62    /// [`anchor_below`](Self::anchor_below).
63    pub anchor_above: Offset,
64    /// The focal point below which the toolbar attempts to position itself, if
65    /// it doesn't fit above [`anchor_above`](Self::anchor_above).
66    pub anchor_below: Offset,
67    /// The children that will be displayed in the text selection toolbar.
68    ///
69    /// Typically these are buttons.
70    ///
71    /// Must not be empty.
72    ///
73    /// See also:
74    ///   * `TextSelectionToolbarTextButton`, which builds a default Material-
75    ///     style text selection toolbar text button.
76    pub children: Vec<WidgetRef>,
77    /// Builds the toolbar container.
78    ///
79    /// Useful for customizing the high-level background of the toolbar. The
80    /// given child Widget will contain all of the children.
81    pub toolbar_builder: ToolbarBuilder,
82}
83
84impl Debug for TextSelectionToolbar {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.debug_struct("TextSelectionToolbar")
87            .field("anchor_above", &self.anchor_above)
88            .field("anchor_below", &self.anchor_below)
89            .finish_non_exhaustive()
90    }
91}
92
93impl TextSelectionToolbar {
94    /// The size of the text selection handles.
95    ///
96    /// See also:
97    ///
98    ///  * `SpellCheckSuggestionsToolbar`, which references this value to calculate
99    ///    the padding between the toolbar and anchor.
100    pub const K_HANDLE_SIZE: f64 = 22.0;
101
102    /// Padding between the toolbar and the anchor.
103    pub const K_TOOLBAR_CONTENT_DISTANCE_BELOW: f64 = Self::K_HANDLE_SIZE - 2.0;
104
105    /// Creates an instance of TextSelectionToolbar.
106    pub fn new(
107        anchor_above: Offset,
108        anchor_below: Offset,
109        children: impl IntoIterator<Item = WidgetRef>,
110    ) -> TextSelectionToolbar {
111        let children: Vec<WidgetRef> = children.into_iter().collect();
112        debug_assert!(!children.is_empty());
113        TextSelectionToolbar {
114            key: None,
115            anchor_above,
116            anchor_below,
117            children,
118            toolbar_builder: Rc::new(Self::default_toolbar_builder),
119        }
120    }
121
122    /// Dart `TextSelectionToolbar(key:)`.
123    pub fn key(mut self, key: KeyRef) -> TextSelectionToolbar {
124        self.key = Some(key);
125        self
126    }
127
128    /// Dart `TextSelectionToolbar(toolbarBuilder:)`.
129    pub fn toolbar_builder(mut self, toolbar_builder: ToolbarBuilder) -> TextSelectionToolbar {
130        self.toolbar_builder = toolbar_builder;
131        self
132    }
133
134    // Build the default Android Material text selection menu toolbar.
135    fn default_toolbar_builder(
136        _app: &mut App,
137        _context: BuildContext,
138        child: WidgetRef,
139    ) -> WidgetRef {
140        TextSelectionToolbarContainer { child }.into_widget()
141    }
142}
143
144impl StatelessWidget for TextSelectionToolbar {
145    fn key(&self) -> Option<&KeyRef> {
146        self.key.as_ref()
147    }
148
149    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
150        // Incorporate the padding distance between the content and toolbar.
151        let anchor_above_padded = self.anchor_above - Offset::new(0.0, K_TOOLBAR_CONTENT_DISTANCE);
152        let anchor_below_padded =
153            self.anchor_below + Offset::new(0.0, Self::K_TOOLBAR_CONTENT_DISTANCE_BELOW);
154
155        const SCREEN_PADDING: f64 = CupertinoTextSelectionToolbar::K_TOOLBAR_SCREEN_PADDING;
156        let padding_above = MediaQuery::padding_of(app, context).top + SCREEN_PADDING;
157        let available_height =
158            anchor_above_padded.dy() - K_TOOLBAR_CONTENT_DISTANCE - padding_above;
159        let fits_above = K_TOOLBAR_HEIGHT <= available_height;
160        // Makes up for the Padding above the Stack.
161        let local_adjustment = Offset::new(SCREEN_PADDING, padding_above);
162
163        Padding::new(EdgeInsetsGeometry::from_ltrb(
164            SCREEN_PADDING,
165            padding_above,
166            SCREEN_PADDING,
167            SCREEN_PADDING,
168        ))
169        .child(
170            CustomSingleChildLayout::new(Rc::new(
171                TextSelectionToolbarLayoutDelegate::new(
172                    anchor_above_padded - local_adjustment,
173                    anchor_below_padded - local_adjustment,
174                )
175                .fits_above(fits_above),
176            ))
177            .child(TextSelectionToolbarOverflowable {
178                is_above: fits_above,
179                toolbar_builder: self.toolbar_builder.clone(),
180                children: self.children.clone(),
181            }),
182        )
183        .into_widget()
184    }
185}
186
187// A toolbar containing the given children. If they overflow the width
188// available, then the overflowing children will be displayed in an overflow
189// menu.
190struct TextSelectionToolbarOverflowable {
191    children: Vec<WidgetRef>,
192    // When true, the toolbar fits above its anchor and will be positioned there.
193    is_above: bool,
194    // Builds the toolbar that will be populated with the children and fit inside
195    // of the layout that adjusts to overflow.
196    toolbar_builder: ToolbarBuilder,
197}
198
199impl Debug for TextSelectionToolbarOverflowable {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        f.debug_struct("_TextSelectionToolbarOverflowable")
202            .field("is_above", &self.is_above)
203            .finish_non_exhaustive()
204    }
205}
206
207impl StatefulWidget for TextSelectionToolbarOverflowable {
208    type State = TextSelectionToolbarOverflowableState;
209
210    fn create_state(&self) -> TextSelectionToolbarOverflowableState {
211        debug_assert!(!self.children.is_empty());
212        TextSelectionToolbarOverflowableState {
213            state: StateData::new(),
214            overflow_open: false,
215            container_key: UniqueKey::new().into(),
216        }
217    }
218}
219
220struct TextSelectionToolbarOverflowableState {
221    state: StateData<TextSelectionToolbarOverflowable>,
222    // Whether or not the overflow menu is open. When it is closed, the menu
223    // items that don't overflow are shown. When it is open, only the overflowing
224    // menu items are shown.
225    overflow_open: bool,
226    // The key for _TextSelectionToolbarTrailingEdgeAlign.
227    container_key: KeyRef,
228}
229
230impl TextSelectionToolbarOverflowableState {
231    // Close the menu and reset layout calculations, as in when the menu has
232    // changed and saved values are no longer relevant. This should be called in
233    // setState or another context where a rebuild is happening.
234    fn reset(self: Handle<Self>, app: &mut App) {
235        let this = app.get_mut(self);
236        // Change _TextSelectionToolbarTrailingEdgeAlign's key when the menu changes
237        // in order to cause it to rebuild. This lets it recalculate its
238        // saved width for the new set of children, and it prevents AnimatedSize
239        // from animating the size change.
240        this.container_key = UniqueKey::new().into();
241        // If the menu items change, make sure the overflow menu is closed. This
242        // prevents getting into a broken state where _overflowOpen is true when
243        // there are not enough children to cause overflow.
244        this.overflow_open = false;
245    }
246
247    /// Dart's `listEquals` over widgets, which compare by identity.
248    fn children_equal(a: &[WidgetRef], b: &[WidgetRef]) -> bool {
249        a.len() == b.len() && a.iter().zip(b).all(|(left, right)| Rc::ptr_eq(left, right))
250    }
251}
252
253impl State for TextSelectionToolbarOverflowableState {
254    type Widget = TextSelectionToolbarOverflowable;
255    waft_widgets::state_accessors!();
256
257    fn did_update_widget(
258        self: Handle<Self>,
259        app: &mut App,
260        old_widget: &TextSelectionToolbarOverflowable,
261    ) {
262        // If the children are changing at all, the current page should be reset.
263        if !Self::children_equal(&self.widget(app).children, &old_widget.children) {
264            self.reset(app);
265        }
266    }
267
268    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
269        debug_assert!(debug_check_has_material_localizations(app, context));
270        let localizations = <dyn MaterialLocalizations>::of(app, context);
271        let text_direction = Directionality::of(app, context);
272
273        let overflow_open = app.get(self).overflow_open;
274        let container_key = app.get(self).container_key.clone();
275        let is_above = self.widget(app).is_above;
276        let toolbar_builder = self.widget(app).toolbar_builder.clone();
277        let children = self.widget(app).children.clone();
278
279        let mut items: Vec<WidgetRef> = Vec::with_capacity(children.len() + 1);
280        // TODO(justinmc): This overflow button should have its own slot in
281        // _TextSelectionToolbarItemsLayout separate from children, similar
282        // to how it's done in Cupertino's text selection menu.
283        // https://github.com/flutter/flutter/issues/69908
284        // The navButton that shows and hides the overflow menu is the
285        // first child.
286        items.push(
287            TextSelectionToolbarOverflowButton {
288                key: Some(if overflow_open {
289                    StandardComponentType::BackButton.key()
290                } else {
291                    StandardComponentType::MoreButton.key()
292                }),
293                icon: Icon::new(Some(if overflow_open {
294                    Icons::arrow_back()
295                } else {
296                    Icons::more_vert()
297                }))
298                .into_widget(),
299                on_pressed: Some(Listener::new(move |app| {
300                    self.set_state(app, |state| {
301                        state.overflow_open = !state.overflow_open;
302                    });
303                })),
304                tooltip: Some(if overflow_open {
305                    localizations.back_button_tooltip()
306                } else {
307                    localizations.more_button_tooltip()
308                }),
309            }
310            .into_widget(),
311        );
312        items.extend(children);
313
314        let toolbar = toolbar_builder(
315            app,
316            context,
317            TextSelectionToolbarItemsLayout {
318                is_above,
319                overflow_open,
320                text_direction,
321                children: items,
322            }
323            .into_widget(),
324        );
325        TextSelectionToolbarTrailingEdgeAlign {
326            key: Some(container_key),
327            overflow_open,
328            text_direction,
329            // This duration was eyeballed on a Pixel 2 emulator running Android
330            // API 28.
331            child: AnimatedSize::new(Duration::from_millis(140))
332                .child(toolbar)
333                .into_widget(),
334        }
335        .into_widget()
336    }
337}
338
339// When the overflow menu is open, it tries to align its trailing edge to the
340// trailing edge of the closed menu. This widget handles this effect by
341// measuring and maintaining the width of the closed menu and aligning the child
342// to that side.
343#[derive(Debug)]
344struct TextSelectionToolbarTrailingEdgeAlign {
345    key: Option<KeyRef>,
346    child: WidgetRef,
347    overflow_open: bool,
348    text_direction: TextDirection,
349}
350
351impl RenderObjectWidget for TextSelectionToolbarTrailingEdgeAlign {
352    type RenderObject = TextSelectionToolbarTrailingEdgeAlignRenderBox;
353
354    fn key(&self) -> Option<&KeyRef> {
355        self.key.as_ref()
356    }
357
358    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
359        TextSelectionToolbarTrailingEdgeAlignRenderBox::new(
360            app,
361            self.overflow_open,
362            self.text_direction,
363        )
364        .as_object()
365    }
366
367    fn update_render_object(
368        &self,
369        app: &mut App,
370        _context: BuildContext,
371        render_object: RenderHandle<TextSelectionToolbarTrailingEdgeAlignRenderBox>,
372    ) {
373        render_object.set_overflow_open(app, self.overflow_open);
374        render_object.set_text_direction(app, self.text_direction);
375    }
376}
377
378impl SingleChildRenderObjectWidget for TextSelectionToolbarTrailingEdgeAlign {
379    fn child(&self) -> Option<&WidgetRef> {
380        Some(&self.child)
381    }
382}
383
384pub(crate) struct TextSelectionToolbarTrailingEdgeAlignRenderBox {
385    render_object: RenderObjectData,
386    render_box: RenderBoxData,
387    child: RenderObjectWithChildData<AnyRenderBox>,
388    // The width of the menu when it was closed. This is used to achieve the
389    // behavior where the open menu aligns its trailing edge to the closed menu's
390    // trailing edge.
391    closed_width: Option<f64>,
392    overflow_open: bool,
393    text_direction: TextDirection,
394}
395
396impl TextSelectionToolbarTrailingEdgeAlignRenderBox {
397    fn new(
398        app: &mut App,
399        overflow_open: bool,
400        text_direction: TextDirection,
401    ) -> RenderHandle<TextSelectionToolbarTrailingEdgeAlignRenderBox> {
402        RenderHandle::new_box(
403            app,
404            TextSelectionToolbarTrailingEdgeAlignRenderBox {
405                render_object: RenderObjectData::new(),
406                render_box: RenderBoxData::new(),
407                child: RenderObjectWithChildData::new(),
408                closed_width: None,
409                overflow_open,
410                text_direction,
411            },
412        )
413    }
414
415    fn overflow_open(self: RenderHandle<Self>, app: &App) -> bool {
416        self.get(app).overflow_open
417    }
418
419    fn set_overflow_open(self: RenderHandle<Self>, app: &mut App, value: bool) {
420        if value == self.overflow_open(app) {
421            return;
422        }
423        self.get_mut(app).overflow_open = value;
424        self.mark_needs_layout(app);
425    }
426
427    fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
428        self.get(app).text_direction
429    }
430
431    fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
432        if value == self.text_direction(app) {
433            return;
434        }
435        self.get_mut(app).text_direction = value;
436        self.mark_needs_layout(app);
437    }
438
439    fn child_offset(self: RenderHandle<Self>, app: &App, child: AnyRenderBox) -> Offset {
440        child
441            .as_object()
442            .parent_data_of::<ToolbarItemsParentData>(app)
443            .offset()
444    }
445}
446
447impl RenderObjectWithChildMixin for TextSelectionToolbarTrailingEdgeAlignRenderBox {
448    type ChildType = AnyRenderBox;
449
450    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
451        &self.get(app).child
452    }
453
454    fn child_data_mut(
455        self: RenderHandle<Self>,
456        app: &mut App,
457    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
458        &mut self.get_mut(app).child
459    }
460}
461
462impl RenderProxyBoxMixin for TextSelectionToolbarTrailingEdgeAlignRenderBox {}
463
464impl RenderObject for TextSelectionToolbarTrailingEdgeAlignRenderBox {
465    waft_rendering::render_object_accessors!();
466
467    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
468        let child = self.child(app).expect("the toolbar's child");
469        let constraints = self.constraints(app);
470        child.layout(app, constraints.loosen(), true);
471        let child_size = child.size(app);
472
473        // Save the width when the menu is closed. If the menu changes, this width
474        // is invalid, so it's important that this RenderBox be recreated in that
475        // case. Currently, this is achieved by providing a new key to
476        // _TextSelectionToolbarTrailingEdgeAlign.
477        if !self.overflow_open(app) && self.get(app).closed_width.is_none() {
478            self.get_mut(app).closed_width = Some(child_size.width());
479        }
480
481        let closed_width = self.get(app).closed_width;
482        let size = constraints.constrain(Size::new(
483            // If the open menu is wider than the closed menu, just use its own width
484            // and don't worry about aligning the trailing edges.
485            // _closedWidth is used even when the menu is closed to allow it to
486            // animate its size while keeping the same edge alignment.
487            match closed_width {
488                Some(closed_width) if child_size.width() <= closed_width => closed_width,
489                _ => child_size.width(),
490            },
491            child_size.height(),
492        ));
493        self.set_size(app, size);
494
495        // Set the offset in the parent data such that the child will be aligned to
496        // the trailing edge, depending on the text direction.
497        let dx = if self.text_direction(app) == TextDirection::Rtl {
498            0.0
499        } else {
500            size.width() - child_size.width()
501        };
502        child
503            .as_object()
504            .parent_data_of_mut::<ToolbarItemsParentData>(app)
505            .set_offset(Offset::new(dx, 0.0));
506    }
507
508    // Paint at the offset set in the parent data.
509    fn paint(
510        self: RenderHandle<Self>,
511        app: &mut App,
512        context: &mut PaintingContext,
513        offset: Offset,
514    ) {
515        let child = self.child(app).expect("the toolbar's child");
516        let child_offset = self.child_offset(app, child);
517        context.paint_child(app, child.as_object(), child_offset + offset);
518    }
519
520    fn visit_children(
521        self: RenderHandle<Self>,
522        app: &App,
523        visitor: &mut dyn FnMut(AnyRenderObject),
524    ) {
525        if let Some(child) = self.child(app) {
526            visitor(child.as_object());
527        }
528    }
529}
530
531impl RenderBox for TextSelectionToolbarTrailingEdgeAlignRenderBox {
532    waft_rendering::render_box_accessors!();
533
534    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
535        if !child.parent_data_is::<ToolbarItemsParentData>(app) {
536            child.set_parent_data(app, ToolbarItemsParentData::new());
537        }
538    }
539
540    fn apply_paint_transform(
541        self: RenderHandle<Self>,
542        app: &App,
543        child: AnyRenderObject,
544        transform: &mut Matrix4,
545    ) {
546        let offset = child.parent_data_of::<ToolbarItemsParentData>(app).offset();
547        *transform = transform.then(&Matrix4::translation(
548            offset.dx() as f32,
549            offset.dy() as f32,
550        ));
551        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
552    }
553
554    // Include the parent data offset in the hit test.
555    fn hit_test_children(
556        self: RenderHandle<Self>,
557        app: &mut App,
558        result: &mut BoxHitTestResult<'_>,
559        position: Offset,
560    ) -> bool {
561        // The x, y parameters have the top left of the node's box as the origin.
562        let child = self.child(app).expect("the toolbar's child");
563        let child_offset = self.child_offset(app, child);
564        result.add_with_paint_offset(Some(child_offset), position, |result, transformed| {
565            debug_assert_eq!(transformed, position - child_offset);
566            child.hit_test(app, result, transformed)
567        })
568    }
569
570    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
571        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
572    }
573
574    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
575        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
576    }
577
578    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
579        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
580    }
581
582    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
583        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
584    }
585
586    fn compute_distance_to_actual_baseline(
587        self: RenderHandle<Self>,
588        app: &mut App,
589        baseline: TextBaseline,
590    ) -> Option<f64> {
591        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
592    }
593
594    fn compute_dry_baseline(
595        self: RenderHandle<Self>,
596        app: &mut App,
597        constraints: BoxConstraints,
598        baseline: TextBaseline,
599    ) -> Option<f64> {
600        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
601    }
602
603    fn compute_dry_layout(
604        self: RenderHandle<Self>,
605        app: &mut App,
606        constraints: BoxConstraints,
607    ) -> Size {
608        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
609    }
610}
611
612// Renders the menu items in the correct positions in the menu and its overflow
613// submenu based on calculating which item would first overflow.
614#[derive(Debug)]
615struct TextSelectionToolbarItemsLayout {
616    is_above: bool,
617    overflow_open: bool,
618    text_direction: TextDirection,
619    children: Vec<WidgetRef>,
620}
621
622/// Dart's `_TextSelectionToolbarItemsLayoutElement._shouldPaint`.
623fn should_paint(app: &App, child: AnyElement) -> bool {
624    child
625        .render_object(app)
626        .and_then(|render| render.parent_data(app))
627        .and_then(|data| data.part::<ToolbarItemsParentData>())
628        .is_some_and(|data| data.should_paint)
629}
630
631impl RenderObjectWidget for TextSelectionToolbarItemsLayout {
632    type RenderObject = RenderTextSelectionToolbarItemsLayout;
633
634    /// Dart's `_TextSelectionToolbarItemsLayoutElement.debugVisitOnstageChildren`: the children
635    /// the layout paints.
636    fn debug_visit_onstage_children(
637        &self,
638        app: &App,
639        children: &[AnyElement],
640        visitor: &mut dyn FnMut(AnyElement),
641    ) {
642        children
643            .iter()
644            .filter(|child| should_paint(app, **child))
645            .for_each(|child| visitor(*child));
646    }
647
648    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
649        RenderTextSelectionToolbarItemsLayout::new(
650            app,
651            self.is_above,
652            self.overflow_open,
653            self.text_direction,
654        )
655        .as_object()
656    }
657
658    fn update_render_object(
659        &self,
660        app: &mut App,
661        _context: BuildContext,
662        render_object: RenderHandle<RenderTextSelectionToolbarItemsLayout>,
663    ) {
664        render_object.set_is_above(app, self.is_above);
665        render_object.set_text_direction(app, self.text_direction);
666        render_object.set_overflow_open(app, self.overflow_open);
667    }
668}
669
670impl MultiChildRenderObjectWidget for TextSelectionToolbarItemsLayout {
671    fn children(&self) -> &[WidgetRef] {
672        &self.children
673    }
674}
675
676/// Dart's `_RenderTextSelectionToolbarItemsLayout`: crate-visible so the test finders can
677/// skip the children it does not paint, as Dart's element does for them.
678pub(crate) struct RenderTextSelectionToolbarItemsLayout {
679    render_object: RenderObjectData,
680    render_box: RenderBoxData,
681    container: ContainerRenderObjectData<AnyRenderBox>,
682    // The index of the last item that doesn't overflow.
683    last_index_that_fits: i32,
684    is_above: bool,
685    overflow_open: bool,
686    text_direction: TextDirection,
687}
688
689impl RenderTextSelectionToolbarItemsLayout {
690    fn new(
691        app: &mut App,
692        is_above: bool,
693        overflow_open: bool,
694        text_direction: TextDirection,
695    ) -> RenderHandle<RenderTextSelectionToolbarItemsLayout> {
696        RenderHandle::new_box(
697            app,
698            RenderTextSelectionToolbarItemsLayout {
699                render_object: RenderObjectData::new(),
700                render_box: RenderBoxData::new(),
701                container: ContainerRenderObjectData::new(),
702                last_index_that_fits: -1,
703                is_above,
704                overflow_open,
705                text_direction,
706            },
707        )
708    }
709
710    fn is_above(self: RenderHandle<Self>, app: &App) -> bool {
711        self.get(app).is_above
712    }
713
714    fn set_is_above(self: RenderHandle<Self>, app: &mut App, value: bool) {
715        if value == self.is_above(app) {
716            return;
717        }
718        self.get_mut(app).is_above = value;
719        self.mark_needs_layout(app);
720    }
721
722    fn overflow_open(self: RenderHandle<Self>, app: &App) -> bool {
723        self.get(app).overflow_open
724    }
725
726    fn set_overflow_open(self: RenderHandle<Self>, app: &mut App, value: bool) {
727        if value == self.overflow_open(app) {
728            return;
729        }
730        self.get_mut(app).overflow_open = value;
731        self.mark_needs_layout(app);
732    }
733
734    fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
735        self.get(app).text_direction
736    }
737
738    fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
739        if value == self.text_direction(app) {
740            return;
741        }
742        self.get_mut(app).text_direction = value;
743        self.mark_needs_layout(app);
744    }
745
746    fn parent_data_of(app: &App, child: AnyRenderBox) -> &ToolbarItemsParentData {
747        child
748            .as_object()
749            .parent_data_of::<ToolbarItemsParentData>(app)
750    }
751
752    fn parent_data_of_mut(app: &mut App, child: AnyRenderBox) -> &mut ToolbarItemsParentData {
753        child
754            .as_object()
755            .parent_data_of_mut::<ToolbarItemsParentData>(app)
756    }
757
758    // Layout the necessary children, and figure out where the children first
759    // overflow, if at all.
760    fn layout_children(self: RenderHandle<Self>, app: &mut App) {
761        // When overflow is not open, the toolbar is always a specific height.
762        let constraints = self.constraints(app);
763        let overflow_open = self.overflow_open(app);
764        let sized_constraints = if overflow_open {
765            constraints
766        } else {
767            BoxConstraints::loose(Size::new(constraints.max_width, K_TOOLBAR_HEIGHT))
768        };
769
770        let mut i = -1;
771        let mut width = 0.0;
772        for child in self.children_as_list(app) {
773            i += 1;
774
775            // No need to layout children inside the overflow menu when it's closed.
776            // The opposite is not true. It is necessary to layout the children that
777            // don't overflow when the overflow menu is open in order to calculate
778            // _lastIndexThatFits.
779            if self.get(app).last_index_that_fits != -1 && !overflow_open {
780                continue;
781            }
782
783            child.layout(app, sized_constraints.loosen(), true);
784            width += child.size(app).width();
785
786            if width > sized_constraints.max_width && self.get(app).last_index_that_fits == -1 {
787                self.get_mut(app).last_index_that_fits = i - 1;
788            }
789        }
790
791        // If the last child overflows, but only because of the width of the
792        // overflow button, then just show it and hide the overflow button.
793        let nav_button = self.first_child(app).expect("the overflow button");
794        let last_index_that_fits = self.get(app).last_index_that_fits;
795        if last_index_that_fits != -1
796            && last_index_that_fits == self.child_count(app) as i32 - 2
797            && width - nav_button.size(app).width() <= sized_constraints.max_width
798        {
799            self.get_mut(app).last_index_that_fits = -1;
800        }
801    }
802
803    // Returns true when the child should be painted, false otherwise.
804    fn should_paint_child(
805        self: RenderHandle<Self>,
806        app: &App,
807        render_object_child: AnyRenderBox,
808        index: i32,
809    ) -> bool {
810        let last_index_that_fits = self.get(app).last_index_that_fits;
811        // Paint the navButton when there is overflow.
812        if Some(render_object_child) == self.first_child(app) {
813            return last_index_that_fits != -1;
814        }
815
816        // If there is no overflow, all children besides the navButton are painted.
817        if last_index_that_fits == -1 {
818            return true;
819        }
820
821        // When there is overflow, paint if the child is in the part of the menu
822        // that is currently open. Overflowing children are painted when the
823        // overflow menu is open, and the children that fit are painted when the
824        // overflow menu is closed.
825        (index > last_index_that_fits) == self.overflow_open(app)
826    }
827
828    /// Horizontal layout.
829    fn place_children_horizontally(self: RenderHandle<Self>, app: &mut App) -> Size {
830        let nav_button = self.first_child(app).expect("the overflow button");
831        let is_rtl = self.text_direction(app) == TextDirection::Rtl;
832
833        let mut content_items: Vec<AnyRenderBox> = Vec::new();
834
835        let mut total_width = 0.0;
836        let mut max_height: f64 = 0.0;
837
838        // First pass: calculate dimensions and collect items.
839        let mut i = -1;
840        for child in self.children_as_list(app) {
841            i += 1;
842
843            if !self.should_paint_child(app, child, i) {
844                // There is no need to update children that won't be painted.
845                Self::parent_data_of_mut(app, child).should_paint = false;
846            } else {
847                Self::parent_data_of_mut(app, child).should_paint = true;
848
849                total_width += child.size(app).width();
850                max_height = max_height.max(child.size(app).height());
851
852                if child != nav_button {
853                    content_items.push(child);
854                }
855            }
856        }
857
858        // Position items based on text direction.
859        let mut current_x = 0.0;
860        let show_nav_button = self.get(app).last_index_that_fits >= 0;
861
862        if is_rtl {
863            // In RTL, we want the nav button on the left and items right-aligned.
864            if show_nav_button {
865                Self::parent_data_of_mut(app, nav_button).set_offset(Offset::ZERO);
866            }
867
868            // Position content items from right to left.
869            let mut right_edge = total_width;
870            for item in content_items {
871                right_edge -= item.size(app).width();
872                Self::parent_data_of_mut(app, item).set_offset(Offset::new(right_edge, 0.0));
873            }
874        } else {
875            // LTR: Place content items first, then nav button.
876            // First position all content items from left to right.
877            for item in content_items {
878                Self::parent_data_of_mut(app, item).set_offset(Offset::new(current_x, 0.0));
879                current_x += item.size(app).width();
880            }
881
882            // Then place the nav button at the end.
883            if show_nav_button {
884                Self::parent_data_of_mut(app, nav_button).set_offset(Offset::new(current_x, 0.0));
885            }
886        }
887
888        Size::new(total_width, max_height)
889    }
890
891    /// Vertical layout (overflow menu).
892    fn place_children_vertically(self: RenderHandle<Self>, app: &mut App) -> Size {
893        let nav_button = self.first_child(app).expect("the overflow button");
894
895        let mut current_y = 0.0;
896        let mut max_width: f64 = 0.0;
897
898        if self.should_paint_child(app, nav_button, 0) {
899            Self::parent_data_of_mut(app, nav_button).should_paint = true;
900            if !self.is_above(app) {
901                Self::parent_data_of_mut(app, nav_button).set_offset(Offset::ZERO);
902                current_y += nav_button.size(app).height();
903                max_width = max_width.max(nav_button.size(app).width());
904            }
905        } else {
906            Self::parent_data_of_mut(app, nav_button).should_paint = false;
907        }
908
909        let mut i = -1;
910        for child in self.children_as_list(app) {
911            i += 1;
912
913            // Ignore the navigation button.
914            if child == nav_button {
915                continue;
916            }
917
918            // There is no need to update children that won't be painted.
919            if !self.should_paint_child(app, child, i) {
920                Self::parent_data_of_mut(app, child).should_paint = false;
921                continue;
922            }
923
924            let child_parent_data = Self::parent_data_of_mut(app, child);
925            child_parent_data.should_paint = true;
926            child_parent_data.set_offset(Offset::new(0.0, current_y));
927            current_y += child.size(app).height();
928            max_width = max_width.max(child.size(app).width());
929        }
930
931        if self.is_above(app) && Self::parent_data_of(app, nav_button).should_paint {
932            Self::parent_data_of_mut(app, nav_button).set_offset(Offset::new(0.0, current_y));
933            current_y += nav_button.size(app).height();
934            max_width = max_width.max(nav_button.size(app).width());
935        }
936
937        Size::new(max_width, current_y)
938    }
939
940    // Decide which children will be painted, set their shouldPaint, and set the
941    // offset that painted children will be placed at.
942    fn place_children(self: RenderHandle<Self>, app: &mut App) {
943        let size = if self.overflow_open(app) {
944            self.place_children_vertically(app)
945        } else {
946            self.place_children_horizontally(app)
947        };
948        self.set_size(app, size);
949    }
950
951    // Horizontally expand the children when the menu overflows so they can react to
952    // pointer events into their whole area.
953    fn resize_children_when_overflow(self: RenderHandle<Self>, app: &mut App) {
954        if !self.overflow_open(app) {
955            return;
956        }
957
958        let nav_button = self.first_child(app).expect("the overflow button");
959        let mut i = -1;
960
961        for child in self.children_as_list(app) {
962            i += 1;
963
964            // Ignore the navigation button.
965            if child == nav_button {
966                continue;
967            }
968
969            // There is no need to update children that won't be painted.
970            if !self.should_paint_child(app, child, i) {
971                Self::parent_data_of_mut(app, child).should_paint = false;
972                continue;
973            }
974
975            let width = self.size(app).width();
976            child.layout(app, BoxConstraints::tight_for(Some(width), None), true);
977        }
978    }
979}
980
981impl ContainerRenderObjectMixin for RenderTextSelectionToolbarItemsLayout {
982    type ChildType = AnyRenderBox;
983    type ParentDataType = ToolbarItemsParentData;
984
985    fn container_data(
986        self: RenderHandle<Self>,
987        app: &App,
988    ) -> &ContainerRenderObjectData<AnyRenderBox> {
989        &self.get(app).container
990    }
991
992    fn container_data_mut(
993        self: RenderHandle<Self>,
994        app: &mut App,
995    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
996        &mut self.get_mut(app).container
997    }
998}
999
1000impl RenderObject for RenderTextSelectionToolbarItemsLayout {
1001    waft_rendering::render_object_accessors!();
1002
1003    fn debug_describe_children(
1004        self: RenderHandle<Self>,
1005        app: &App,
1006    ) -> Vec<Rc<dyn DiagnosticsNode>> {
1007        ContainerRenderObjectMixin::debug_describe_children(self, app)
1008    }
1009
1010    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1011        self.get_mut(app).last_index_that_fits = -1;
1012        if self.first_child(app).is_none() {
1013            let smallest = self.constraints(app).smallest();
1014            self.set_size(app, smallest);
1015            return;
1016        }
1017
1018        self.layout_children(app);
1019        self.place_children(app);
1020        self.resize_children_when_overflow(app);
1021    }
1022
1023    fn paint(
1024        self: RenderHandle<Self>,
1025        app: &mut App,
1026        context: &mut PaintingContext,
1027        offset: Offset,
1028    ) {
1029        for child in self.children_as_list(app) {
1030            let child_parent_data = Self::parent_data_of(app, child);
1031            if !child_parent_data.should_paint {
1032                continue;
1033            }
1034
1035            let child_offset = child_parent_data.offset();
1036            context.paint_child(app, child.as_object(), child_offset + offset);
1037        }
1038    }
1039
1040    fn visit_children(
1041        self: RenderHandle<Self>,
1042        app: &App,
1043        visitor: &mut dyn FnMut(AnyRenderObject),
1044    ) {
1045        ContainerRenderObjectMixin::visit_children(self, app, visitor);
1046    }
1047
1048    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
1049        ContainerRenderObjectMixin::did_attach(self, app, owner);
1050    }
1051
1052    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1053        ContainerRenderObjectMixin::did_detach(self, app);
1054    }
1055
1056    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1057        ContainerRenderObjectMixin::redepth_children(self, app);
1058    }
1059}
1060
1061impl RenderBox for RenderTextSelectionToolbarItemsLayout {
1062    waft_rendering::render_box_accessors!();
1063
1064    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1065        if !child.parent_data_is::<ToolbarItemsParentData>(app) {
1066            child.set_parent_data(app, ToolbarItemsParentData::new());
1067        }
1068    }
1069
1070    fn hit_test_children(
1071        self: RenderHandle<Self>,
1072        app: &mut App,
1073        result: &mut BoxHitTestResult<'_>,
1074        position: Offset,
1075    ) -> bool {
1076        let mut child = self.last_child(app);
1077        while let Some(current) = child {
1078            // The x, y parameters have the top left of the node's box as the origin.
1079            let child_parent_data = Self::parent_data_of(app, current);
1080
1081            // Don't hit test children aren't shown.
1082            if !child_parent_data.should_paint {
1083                child = child_parent_data.previous_sibling();
1084                continue;
1085            }
1086
1087            let offset = child_parent_data.offset();
1088            let is_hit =
1089                result.add_with_paint_offset(Some(offset), position, |result, transformed| {
1090                    debug_assert_eq!(transformed, position - offset);
1091                    current.hit_test(app, result, transformed)
1092                });
1093            if is_hit {
1094                return true;
1095            }
1096            child = Self::parent_data_of(app, current).previous_sibling();
1097        }
1098        false
1099    }
1100}
1101
1102// The Material-styled toolbar outline. Fill it with any widgets you want. No
1103// overflow ability.
1104#[derive(Debug)]
1105struct TextSelectionToolbarContainer {
1106    child: WidgetRef,
1107}
1108
1109impl TextSelectionToolbarContainer {
1110    // These colors were taken from a screenshot of a Pixel 6 emulator running
1111    // Android API level 34.
1112    const DEFAULT_COLOR_LIGHT: Color = Color::new(0xffffffff);
1113    const DEFAULT_COLOR_DARK: Color = Color::new(0xff424242);
1114
1115    fn get_color(app: &App, color_scheme: &ColorScheme) -> Color {
1116        let is_default_surface = match color_scheme.brightness() {
1117            Brightness::Light => {
1118                ThemeData::new(app).color_scheme.surface() == color_scheme.surface()
1119            }
1120            Brightness::Dark => {
1121                ThemeData::dark(app, None).color_scheme.surface() == color_scheme.surface()
1122            }
1123        };
1124        if !is_default_surface {
1125            return color_scheme.surface();
1126        }
1127        match color_scheme.brightness() {
1128            Brightness::Light => Self::DEFAULT_COLOR_LIGHT,
1129            Brightness::Dark => Self::DEFAULT_COLOR_DARK,
1130        }
1131    }
1132}
1133
1134impl StatelessWidget for TextSelectionToolbarContainer {
1135    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1136        let color_scheme = Theme::of(app, context).color_scheme.clone();
1137        Material::new()
1138            // This value was eyeballed to match the native text selection menu on
1139            // a Pixel 6 emulator running Android API level 34.
1140            .border_radius(BorderRadius::all(Radius::circular(K_TOOLBAR_HEIGHT / 2.0)))
1141            .clip_behavior(Clip::AntiAlias)
1142            .color(Self::get_color(app, &color_scheme))
1143            .elevation(1.0)
1144            .r#type(MaterialType::Card)
1145            .child(self.child.clone())
1146            .into_widget()
1147    }
1148}
1149
1150// A button styled like a Material native Android text selection overflow menu
1151// forward and back controls.
1152#[derive(Debug)]
1153struct TextSelectionToolbarOverflowButton {
1154    key: Option<KeyRef>,
1155    // An `Icon`.
1156    icon: WidgetRef,
1157    on_pressed: Option<Listener>,
1158    tooltip: Option<String>,
1159}
1160
1161impl StatelessWidget for TextSelectionToolbarOverflowButton {
1162    fn key(&self) -> Option<&KeyRef> {
1163        self.key.as_ref()
1164    }
1165
1166    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1167        // TODO(justinmc): This should be an AnimatedIcon, but
1168        // AnimatedIcons doesn't yet support arrow_back to more_vert.
1169        // https://github.com/flutter/flutter/issues/51209
1170        let mut icon_button = IconButton::new(self.on_pressed.clone(), self.icon.clone());
1171        if let Some(tooltip) = self.tooltip.clone() {
1172            icon_button = icon_button.tooltip(tooltip);
1173        }
1174        Material::new()
1175            .r#type(MaterialType::Card)
1176            .color(Color::new(0x00000000))
1177            .child(icon_button)
1178            .into_widget()
1179    }
1180}
1181
1182#[cfg(test)]
1183mod tests {
1184    use std::cell::RefCell;
1185
1186    use waft_embedder::Rect;
1187    use waft_foundation::ValueKey;
1188    use waft_widgets::{
1189        AnyElement, Center, Container, SizedBox, StateSetter, StatefulBuilder, Text,
1190        downcast_widget,
1191    };
1192
1193    use waft_widgets::testing::{
1194        WidgetTester, expect, find, finds_n_widgets, finds_nothing, finds_one_widget, test_widgets,
1195    };
1196
1197    use super::*;
1198    use crate::colors::Colors;
1199    use crate::scaffold::Scaffold;
1200    use crate::test_support::material_app;
1201    use crate::text_selection_toolbar_text_button::TextSelectionToolbarTextButton;
1202
1203    /// Dart's `TestBox`: a `SizedBox` of `ITEM_WIDTH` by `ITEM_HEIGHT`.
1204    #[derive(Debug)]
1205    struct TestBox {
1206        key: Option<KeyRef>,
1207        child: Option<WidgetRef>,
1208    }
1209
1210    impl TestBox {
1211        const ITEM_HEIGHT: f64 = 44.0;
1212        const ITEM_WIDTH: f64 = 100.0;
1213
1214        fn new() -> TestBox {
1215            TestBox {
1216                key: None,
1217                child: None,
1218            }
1219        }
1220    }
1221
1222    impl StatelessWidget for TestBox {
1223        fn key(&self) -> Option<&KeyRef> {
1224            self.key.as_ref()
1225        }
1226
1227        fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1228            let sized = SizedBox::new()
1229                .width(Self::ITEM_WIDTH)
1230                .height(Self::ITEM_HEIGHT);
1231            match self.child.clone() {
1232                Some(child) => sized.child(child).into_widget(),
1233                None => sized.into_widget(),
1234            }
1235        }
1236    }
1237
1238    /// `MaterialApp(home: Scaffold(body: body))` under the default theme.
1239    fn pump_in_scaffold(tester: &mut WidgetTester, body: WidgetRef) {
1240        let root = {
1241            let app = tester.cell.borrow();
1242            material_app(
1243                ThemeData::new(&app),
1244                Scaffold::new().body(body).into_widget(),
1245            )
1246        };
1247        tester.pump_widget(root);
1248    }
1249
1250    /// A `StatefulBuilder` building a toolbar of `children`, and its setter once built.
1251    fn toolbar_of(
1252        children: Rc<RefCell<Vec<WidgetRef>>>,
1253        anchor_above: Rc<RefCell<Offset>>,
1254        anchor_below: Offset,
1255    ) -> (WidgetRef, Rc<RefCell<Option<StateSetter>>>) {
1256        let set_state: Rc<RefCell<Option<StateSetter>>> = Rc::new(RefCell::new(None));
1257        let builder = {
1258            let set_state = Rc::clone(&set_state);
1259            StatefulBuilder::new(move |_app, _context, setter| {
1260                *set_state.borrow_mut() = Some(setter);
1261                TextSelectionToolbar::new(
1262                    *anchor_above.borrow(),
1263                    anchor_below,
1264                    children.borrow().clone(),
1265                )
1266                .into_widget()
1267            })
1268            .into_widget()
1269        };
1270        (builder, set_state)
1271    }
1272
1273    /// Runs `update` through the builder's `setState`, then Dart's `pumpAndSettle`.
1274    fn set_state_and_settle(
1275        tester: &mut WidgetTester,
1276        set_state: &Rc<RefCell<Option<StateSetter>>>,
1277        update: impl FnOnce(),
1278    ) {
1279        let setter = set_state.borrow().clone().expect("the builder built");
1280        let mut update = Some(update);
1281        setter(&mut tester.cell.borrow_mut(), &mut |_app| {
1282            if let Some(update) = update.take() {
1283                update();
1284            }
1285        });
1286        tester.pump_and_settle();
1287    }
1288
1289    /// Dart's `findOverflowButton()`.
1290    fn find_overflow_button(tester: &WidgetTester) -> Vec<AnyElement> {
1291        find::by_type::<TextSelectionToolbarOverflowButton>().evaluate(tester)
1292    }
1293
1294    /// Dart's `tester.tap(findOverflowButton())` and `pumpAndSettle`.
1295    fn tap_overflow_button(tester: &mut WidgetTester) {
1296        let buttons = find_overflow_button(tester);
1297        assert_eq!(buttons.len(), 1, "one overflow button");
1298        let center = tester.get_rect(buttons[0]).center();
1299        tester.tap_at(center, 1);
1300        tester.pump_and_settle();
1301    }
1302
1303    /// Dart's `tester.getRect(finder)` of the first element found.
1304    fn rect_of(tester: &WidgetTester, elements: &[AnyElement]) -> Rect {
1305        tester.get_rect(elements[0])
1306    }
1307
1308    fn test_boxes(count: usize) -> Vec<WidgetRef> {
1309        (0..count).map(|_| TestBox::new().into_widget()).collect()
1310    }
1311
1312    fn overflows_into_a_menu(tester: &mut WidgetTester, text_direction: TextDirection) {
1313        let children = Rc::new(RefCell::new(test_boxes(7)));
1314        let (toolbar, set_state) = toolbar_of(
1315            Rc::clone(&children),
1316            Rc::new(RefCell::new(Offset::new(50.0, 100.0))),
1317            Offset::new(50.0, 200.0),
1318        );
1319        pump_in_scaffold(
1320            tester,
1321            Directionality::new(text_direction, toolbar).into_widget(),
1322        );
1323
1324        // All children fit on the screen, so they are all rendered.
1325        let count = children.borrow().len();
1326        assert_eq!(find::by_type::<TestBox>().evaluate(tester).len(), count);
1327        assert!(find_overflow_button(tester).is_empty());
1328
1329        // Adding one more child makes the children overflow.
1330        set_state_and_settle(tester, &set_state, || {
1331            children.borrow_mut().push(TestBox::new().into_widget());
1332        });
1333        let count = children.borrow().len();
1334        assert_eq!(find::by_type::<TestBox>().evaluate(tester).len(), count - 1);
1335        assert_eq!(find_overflow_button(tester).len(), 1);
1336
1337        // Tap the overflow button to show the overflow menu.
1338        tap_overflow_button(tester);
1339        expect(tester, &find::by_type::<TestBox>(), finds_one_widget());
1340        assert_eq!(find_overflow_button(tester).len(), 1);
1341
1342        // Tap the overflow button again to hide the overflow menu.
1343        tap_overflow_button(tester);
1344        assert_eq!(find::by_type::<TestBox>().evaluate(tester).len(), count - 1);
1345        assert_eq!(find_overflow_button(tester).len(), 1);
1346    }
1347
1348    #[test]
1349    fn puts_children_in_an_overflow_menu_if_they_overflow() {
1350        test_widgets(|tester| overflows_into_a_menu(tester, TextDirection::Ltr));
1351    }
1352
1353    #[test]
1354    fn positions_itself_at_anchor_above_if_it_fits() {
1355        test_widgets(|tester| {
1356            const HEIGHT: f64 = 44.0;
1357            const ANCHOR_BELOW_Y: f64 = 500.0;
1358            let anchor_above = Rc::new(RefCell::new(Offset::new(50.0, 0.0)));
1359            let children = Rc::new(RefCell::new(vec![
1360                Container::new()
1361                    .color(Colors::RED.primary())
1362                    .width(50.0)
1363                    .height(HEIGHT)
1364                    .into_widget(),
1365                Container::new()
1366                    .color(Colors::GREEN.primary())
1367                    .width(50.0)
1368                    .height(HEIGHT)
1369                    .into_widget(),
1370                Container::new()
1371                    .color(Colors::BLUE.primary())
1372                    .width(50.0)
1373                    .height(HEIGHT)
1374                    .into_widget(),
1375            ]));
1376            let (toolbar, set_state) = toolbar_of(
1377                children,
1378                Rc::clone(&anchor_above),
1379                Offset::new(50.0, ANCHOR_BELOW_Y),
1380            );
1381            pump_in_scaffold(tester, toolbar);
1382            let toolbar_y = |tester: &WidgetTester| {
1383                rect_of(
1384                    tester,
1385                    &find::by_type::<TextSelectionToolbarOverflowable>().evaluate(tester),
1386                )
1387                .top
1388            };
1389
1390            // When the toolbar doesn't fit above aboveAnchor, it positions itself below
1391            // belowAnchor.
1392            assert_eq!(
1393                toolbar_y(tester),
1394                ANCHOR_BELOW_Y + TextSelectionToolbar::K_TOOLBAR_CONTENT_DISTANCE_BELOW
1395            );
1396
1397            // Even when it barely doesn't fit.
1398            set_state_and_settle(tester, &set_state, || {
1399                *anchor_above.borrow_mut() = Offset::new(50.0, 60.0);
1400            });
1401            assert_eq!(
1402                toolbar_y(tester),
1403                ANCHOR_BELOW_Y + TextSelectionToolbar::K_TOOLBAR_CONTENT_DISTANCE_BELOW
1404            );
1405
1406            // When it does fit above aboveAnchor, it positions itself there.
1407            set_state_and_settle(tester, &set_state, || {
1408                *anchor_above.borrow_mut() = Offset::new(50.0, 70.0);
1409            });
1410            assert_eq!(
1411                toolbar_y(tester),
1412                70.0 - HEIGHT - K_TOOLBAR_CONTENT_DISTANCE
1413            );
1414        });
1415    }
1416
1417    /// Dart's `toolbarContainer.color`: the first `Material` under the
1418    /// `_TextSelectionToolbarContainer`.
1419    fn toolbar_container_color(tester: &WidgetTester) -> Option<Color> {
1420        let containers = find::by_type::<TextSelectionToolbarContainer>().evaluate(tester);
1421        assert!(!containers.is_empty());
1422        let materials = tester.descendants_of_type::<Material>(containers[0]);
1423        assert!(!materials.is_empty());
1424        tester.widget(materials[0], |material: &Material| material.color)
1425    }
1426
1427    fn pump_toolbar_under(tester: &mut WidgetTester, color_scheme: ColorScheme) {
1428        let root = {
1429            let app = tester.cell.borrow();
1430            material_app(
1431                ThemeData::builder().color_scheme(color_scheme).build(&app),
1432                Scaffold::new()
1433                    .body(
1434                        Center::new().child(TextSelectionToolbar::new(
1435                            Offset::ZERO,
1436                            Offset::ZERO,
1437                            [TextSelectionToolbarTextButton::new(
1438                                Text::new("Custom button"),
1439                                TextSelectionToolbarTextButton::get_padding(0, 1),
1440                            )
1441                            .on_pressed(Listener::new(|_app| {}))
1442                            .into_widget()],
1443                        )),
1444                    )
1445                    .into_widget(),
1446            )
1447        };
1448        tester.pump_widget(root);
1449    }
1450
1451    /// Dart's `<ColorScheme>[ThemeData().colorScheme, ThemeData.dark().colorScheme]`.
1452    fn color_schemes(tester: &WidgetTester) -> [ColorScheme; 2] {
1453        let app = tester.cell.borrow();
1454        [
1455            ThemeData::new(&app).color_scheme,
1456            ThemeData::dark(&app, None).color_scheme,
1457        ]
1458    }
1459
1460    #[test]
1461    fn default_background_color() {
1462        for index in 0..2 {
1463            test_widgets(|tester| {
1464                let color_scheme = color_schemes(tester)[index].clone();
1465                let brightness = color_scheme.brightness();
1466                pump_toolbar_under(tester, color_scheme);
1467                assert_eq!(
1468                    toolbar_container_color(tester),
1469                    // The default colors are hardcoded and don't take the default value of
1470                    // the theme's surface color.
1471                    Some(match brightness {
1472                        Brightness::Light => Color::new(0xffffffff),
1473                        Brightness::Dark => Color::new(0xff424242),
1474                    })
1475                );
1476            });
1477        }
1478    }
1479
1480    #[test]
1481    fn custom_background_color() {
1482        for index in 0..2 {
1483            test_widgets(|tester| {
1484                let color_scheme = color_schemes(tester)[index].clone();
1485                let custom_background_color = Colors::RED.primary();
1486                pump_toolbar_under(
1487                    tester,
1488                    color_scheme
1489                        .copy_with()
1490                        .with_surface(custom_background_color),
1491                );
1492                assert_eq!(
1493                    toolbar_container_color(tester),
1494                    Some(custom_background_color)
1495                );
1496            });
1497        }
1498    }
1499
1500    #[test]
1501    fn overflowed_menu_expands_children_horizontally() {
1502        // Regression test for https://github.com/flutter/flutter/issues/144089.
1503        test_widgets(|tester| {
1504            let children = Rc::new(RefCell::new(test_boxes(7)));
1505            let (toolbar, set_state) = toolbar_of(
1506                Rc::clone(&children),
1507                Rc::new(RefCell::new(Offset::new(50.0, 100.0))),
1508                Offset::new(50.0, 200.0),
1509            );
1510            pump_in_scaffold(tester, toolbar);
1511
1512            // All children fit on the screen, so they are all rendered.
1513            let count = children.borrow().len();
1514            assert_eq!(find::by_type::<TestBox>().evaluate(tester).len(), count);
1515            assert!(find_overflow_button(tester).is_empty());
1516
1517            const SHORT: &str = "Short";
1518            const MEDIUM: &str = "Medium length";
1519            const LONG: &str = "Long label in the overflow menu";
1520
1521            // Adding several children makes the menu overflow.
1522            set_state_and_settle(tester, &set_state, || {
1523                children.borrow_mut().extend([
1524                    Text::new(SHORT).into_widget(),
1525                    Text::new(MEDIUM).into_widget(),
1526                    Text::new(LONG).into_widget(),
1527                ]);
1528            });
1529            assert_eq!(find_overflow_button(tester).len(), 1);
1530
1531            // Tap the overflow button to show the overflow menu.
1532            tap_overflow_button(tester);
1533            expect(tester, &find::by_type::<TestBox>(), finds_nothing());
1534            expect(tester, &find::by_type::<Text>(), finds_n_widgets(3));
1535            assert_eq!(find_overflow_button(tester).len(), 1);
1536
1537            let containers = find::by_type::<TextSelectionToolbarContainer>().evaluate(tester);
1538            assert!(!containers.is_empty());
1539
1540            // Buttons have their width set to the container width.
1541            let overflow_menu_width = rect_of(tester, &containers).width();
1542            let text_width = |text: &str| {
1543                let found: Vec<AnyElement> = find::text(text).evaluate(tester);
1544                rect_of(tester, &found).width()
1545            };
1546            assert_eq!(text_width(LONG), overflow_menu_width);
1547            assert_eq!(text_width(MEDIUM), overflow_menu_width);
1548            assert_eq!(text_width(SHORT), overflow_menu_width);
1549        });
1550    }
1551
1552    #[test]
1553    fn items_are_ordered_right_to_left_in_rtl() {
1554        test_widgets(|tester| {
1555            const ITEM_COUNT: usize = 3;
1556            let children: Vec<WidgetRef> = (0..ITEM_COUNT)
1557                .map(|i| {
1558                    TestBox {
1559                        key: Some(ValueKey::new(format!("item_{i}")).into()),
1560                        child: Some(Text::new(format!("{i}")).into_widget()),
1561                    }
1562                    .into_widget()
1563                })
1564                .collect();
1565
1566            pump_in_scaffold(
1567                tester,
1568                Directionality::new(
1569                    TextDirection::Rtl,
1570                    TextSelectionToolbar::new(
1571                        Offset::new(50.0, 100.0),
1572                        Offset::new(50.0, 200.0),
1573                        children,
1574                    ),
1575                )
1576                .into_widget(),
1577            );
1578
1579            // Verify all items are visible.
1580            assert_eq!(
1581                find::by_type::<TestBox>().evaluate(tester).len(),
1582                ITEM_COUNT
1583            );
1584
1585            // Find all text widgets by their content and get their positions.
1586            let text_rects: Vec<Rect> = (0..ITEM_COUNT)
1587                .map(|i| tester.get_rect(find::text(&format!("{i}"))))
1588                .collect();
1589
1590            // In RTL, items should be in reverse order (2, 1, 0).
1591            // So item 2 should be leftmost, then 1, then 0.
1592            for i in 0..ITEM_COUNT - 1 {
1593                let current = text_rects[i];
1594                let next = text_rects[i + 1];
1595
1596                // In RTL, each item should be to the left of the previous one.
1597                assert!(
1598                    next.right <= current.left,
1599                    "In RTL, item {} should be to the left of item {i}",
1600                    i + 1
1601                );
1602            }
1603
1604            // Verify the visual order by checking the rightmost position.
1605            let right_edges: Vec<f64> = text_rects.iter().map(|rect| rect.right).collect();
1606            let mut sorted_right_edges = right_edges.clone();
1607            sorted_right_edges.sort_by(|a, b| b.total_cmp(a));
1608            assert_eq!(
1609                right_edges, sorted_right_edges,
1610                "Items should be ordered right-to-left in RTL"
1611            );
1612        });
1613    }
1614
1615    #[test]
1616    fn puts_children_in_an_overflow_menu_if_they_overflow_in_rtl() {
1617        test_widgets(|tester| overflows_into_a_menu(tester, TextDirection::Rtl));
1618    }
1619
1620    #[test]
1621    fn the_overflow_button_is_keyed_as_a_standard_more_and_back_button() {
1622        test_widgets(|tester| {
1623            pump_in_scaffold(
1624                tester,
1625                TextSelectionToolbar::new(
1626                    Offset::new(50.0, 100.0),
1627                    Offset::new(50.0, 200.0),
1628                    test_boxes(8),
1629                )
1630                .into_widget(),
1631            );
1632            let more = StandardComponentType::MoreButton.key();
1633            let back = StandardComponentType::BackButton.key();
1634            expect(tester, &find::by_key(more.clone()), finds_one_widget());
1635            expect(tester, &find::by_key(back.clone()), finds_nothing());
1636
1637            tap_overflow_button(tester);
1638            expect(tester, &find::by_key(more.clone()), finds_nothing());
1639            expect(tester, &find::by_key(back.clone()), finds_one_widget());
1640            let back_button = tester.element(find::by_key(back.clone()));
1641            let app = tester.cell.borrow();
1642            assert!(
1643                downcast_widget::<TextSelectionToolbarOverflowButton>(&**back_button.widget(&app))
1644                    .is_some()
1645            );
1646        });
1647    }
1648
1649    /// Dart's `_RenderTextSelectionToolbarItemsLayout` fills no properties of its own; its
1650    /// `ContainerRenderObjectMixin` names the children `child 1`, `child 2`, ….
1651    #[test]
1652    fn a_toolbar_items_layout_describes_its_children_in_order() {
1653        use waft_foundation::{AppCell, DiagnosticsNode};
1654        use waft_rendering::{BoxConstraints, RenderConstrainedBox};
1655
1656        let cell = AppCell::new();
1657        let mut app = cell.borrow_mut();
1658        let items =
1659            RenderTextSelectionToolbarItemsLayout::new(&mut app, true, false, TextDirection::Ltr);
1660        let child = |app: &mut App| {
1661            RenderConstrainedBox::new(app, BoxConstraints::tight(Size::new(10.0, 10.0)), None)
1662                .as_box()
1663        };
1664        let first = child(&mut app);
1665        let second = child(&mut app);
1666        items.insert(&mut app, first, None);
1667        items.insert(&mut app, second, None);
1668
1669        let node = items.as_object().to_diagnostics_node(&app, None);
1670        let names: Vec<&str> = node
1671            .children()
1672            .iter()
1673            .filter_map(|child| child.name())
1674            .collect();
1675        assert_eq!(names, ["child 1", "child 2"]);
1676    }
1677}