1use 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
42pub struct TextSelectionToolbar {
57 pub key: Option<KeyRef>,
58 pub anchor_above: Offset,
64 pub anchor_below: Offset,
67 pub children: Vec<WidgetRef>,
77 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 pub const K_HANDLE_SIZE: f64 = 22.0;
101
102 pub const K_TOOLBAR_CONTENT_DISTANCE_BELOW: f64 = Self::K_HANDLE_SIZE - 2.0;
104
105 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 pub fn key(mut self, key: KeyRef) -> TextSelectionToolbar {
124 self.key = Some(key);
125 self
126 }
127
128 pub fn toolbar_builder(mut self, toolbar_builder: ToolbarBuilder) -> TextSelectionToolbar {
130 self.toolbar_builder = toolbar_builder;
131 self
132 }
133
134 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 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 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
187struct TextSelectionToolbarOverflowable {
191 children: Vec<WidgetRef>,
192 is_above: bool,
194 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 overflow_open: bool,
226 container_key: KeyRef,
228}
229
230impl TextSelectionToolbarOverflowableState {
231 fn reset(self: Handle<Self>, app: &mut App) {
235 let this = app.get_mut(self);
236 this.container_key = UniqueKey::new().into();
241 this.overflow_open = false;
245 }
246
247 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 !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 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 child: AnimatedSize::new(Duration::from_millis(140))
332 .child(toolbar)
333 .into_widget(),
334 }
335 .into_widget()
336 }
337}
338
339#[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 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 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 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 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 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 fn hit_test_children(
556 self: RenderHandle<Self>,
557 app: &mut App,
558 result: &mut BoxHitTestResult<'_>,
559 position: Offset,
560 ) -> bool {
561 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#[derive(Debug)]
615struct TextSelectionToolbarItemsLayout {
616 is_above: bool,
617 overflow_open: bool,
618 text_direction: TextDirection,
619 children: Vec<WidgetRef>,
620}
621
622fn 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 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
676pub(crate) struct RenderTextSelectionToolbarItemsLayout {
679 render_object: RenderObjectData,
680 render_box: RenderBoxData,
681 container: ContainerRenderObjectData<AnyRenderBox>,
682 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 fn layout_children(self: RenderHandle<Self>, app: &mut App) {
761 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 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 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 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 if Some(render_object_child) == self.first_child(app) {
813 return last_index_that_fits != -1;
814 }
815
816 if last_index_that_fits == -1 {
818 return true;
819 }
820
821 (index > last_index_that_fits) == self.overflow_open(app)
826 }
827
828 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 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 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 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 if show_nav_button {
865 Self::parent_data_of_mut(app, nav_button).set_offset(Offset::ZERO);
866 }
867
868 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 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 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 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 if child == nav_button {
915 continue;
916 }
917
918 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 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 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 if child == nav_button {
966 continue;
967 }
968
969 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 let child_parent_data = Self::parent_data_of(app, current);
1080
1081 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#[derive(Debug)]
1105struct TextSelectionToolbarContainer {
1106 child: WidgetRef,
1107}
1108
1109impl TextSelectionToolbarContainer {
1110 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 .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#[derive(Debug)]
1153struct TextSelectionToolbarOverflowButton {
1154 key: Option<KeyRef>,
1155 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 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 #[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 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 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 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 fn find_overflow_button(tester: &WidgetTester) -> Vec<AnyElement> {
1291 find::by_type::<TextSelectionToolbarOverflowButton>().evaluate(tester)
1292 }
1293
1294 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 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 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 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_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_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 assert_eq!(
1393 toolbar_y(tester),
1394 ANCHOR_BELOW_Y + TextSelectionToolbar::K_TOOLBAR_CONTENT_DISTANCE_BELOW
1395 );
1396
1397 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 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 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 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 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 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 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 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_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 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 assert_eq!(
1581 find::by_type::<TestBox>().evaluate(tester).len(),
1582 ITEM_COUNT
1583 );
1584
1585 let text_rects: Vec<Rect> = (0..ITEM_COUNT)
1587 .map(|i| tester.get_rect(find::text(&format!("{i}"))))
1588 .collect();
1589
1590 for i in 0..ITEM_COUNT - 1 {
1593 let current = text_rects[i];
1594 let next = text_rects[i + 1];
1595
1596 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 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 #[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}