1use std::fmt::Debug;
8use std::rc::Rc;
9
10use waft_embedder::Clip;
11use waft_foundation::{
12 App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty,
13 FlagProperty,
14};
15use waft_gestures::DragStartBehavior;
16use waft_painting::{Axis, AxisDirection, EdgeInsetsGeometry};
17use waft_rendering::{
18 HitTestBehavior, ItemExtentBuilder, ScrollCacheExtent, SliverGridDelegate,
19 SliverGridDelegateWithFixedCrossAxisCount, SliverGridDelegateWithMaxCrossAxisExtent,
20 SliverPaintOrder, ViewportOffsetRef,
21};
22
23use crate::framework::{
24 BuildContext, IntoWidget, KeyRef, StatelessKind, StatelessWidget, WidgetRef,
25};
26use crate::widgets::basic::{
27 SliverPadding, get_axis_direction_from_axis_reverse_and_directionality,
28};
29use crate::widgets::focus_manager::{FocusNodeLeaf, UnfocusDisposition, primary_focus};
30use crate::widgets::focus_scope::FocusScope;
31use crate::widgets::media_query::MediaQuery;
32use crate::widgets::notification_listener::NotificationListener;
33use crate::widgets::primary_scroll_controller::PrimaryScrollController;
34use crate::widgets::scroll_configuration::{ScrollBehaviorRef, ScrollConfiguration};
35use crate::widgets::scroll_controller::ScrollControllerRef;
36use crate::widgets::scroll_delegate::{
37 ChildIndexGetter, NullableIndexedWidgetBuilder, SliverChildBuilderDelegate,
38 SliverChildDelegateRef, SliverChildListDelegate,
39};
40use crate::widgets::scroll_notification::ScrollUpdateNotification;
41use crate::widgets::scroll_physics::{AlwaysScrollableScrollPhysics, ScrollPhysicsRef};
42use crate::widgets::scrollable::{Scrollable, ViewportBuilder};
43use crate::widgets::sliver::{
44 SliverFixedExtentList, SliverGrid, SliverList, SliverVariedExtentList,
45};
46use crate::widgets::sliver_prototype_extent_list::SliverPrototypeExtentList;
47use crate::widgets::viewport::{ShrinkWrappingViewport, Viewport};
48
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum ScrollViewKeyboardDismissBehavior {
53 #[default]
56 Manual,
57
58 OnDrag,
60}
61
62#[derive(Clone, Debug)]
69pub struct ScrollViewData {
70 pub key: Option<KeyRef>,
71
72 pub scroll_direction: Axis,
79
80 pub reverse: bool,
89
90 pub controller: Option<ScrollControllerRef>,
95
96 pub primary: Option<bool>,
113
114 pub physics: Option<ScrollPhysicsRef>,
128
129 pub scroll_behavior: Option<ScrollBehaviorRef>,
134
135 pub shrink_wrap: bool,
150
151 pub center: Option<KeyRef>,
165
166 pub anchor: f64,
175
176 #[deprecated(note = "Use scroll_cache_extent instead.")]
181 pub cache_extent: Option<f64>,
182
183 pub scroll_cache_extent: Option<ScrollCacheExtent>,
186
187 pub semantic_child_count: Option<i32>,
197
198 pub paint_order: SliverPaintOrder,
202
203 pub drag_start_behavior: DragStartBehavior,
205
206 pub keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,
213
214 pub restoration_id: Option<String>,
216
217 pub clip_behavior: Clip,
221
222 pub hit_test_behavior: HitTestBehavior,
227}
228
229impl ScrollViewData {
230 pub fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
233 properties.add(EnumProperty::new("scrollDirection", self.scroll_direction));
234 properties.add(
235 FlagProperty::new("reverse", Some(self.reverse))
236 .if_true("reversed")
237 .with_show_name(true),
238 );
239 properties.add(
240 DiagnosticsProperty::<String>::new(
241 "controller",
242 self.controller
243 .as_ref()
244 .map(|controller| controller.to_string(app)),
245 )
246 .with_show_name(false)
247 .default_value(None),
248 );
249 properties.add(
250 FlagProperty::new("primary", self.primary)
251 .if_true("using primary controller")
252 .with_show_name(true),
253 );
254 properties.add(
255 DiagnosticsProperty::<String>::new(
256 "physics",
257 self.physics.as_ref().map(|physics| format!("{physics:?}")),
258 )
259 .with_show_name(false)
260 .default_value(None),
261 );
262 properties.add(
263 FlagProperty::new("shrinkWrap", Some(self.shrink_wrap))
264 .if_true("shrink-wrapping")
265 .with_show_name(true),
266 );
267 properties.add(
268 DiagnosticsProperty::<ScrollCacheExtent>::new(
269 "scrollCacheExtent",
270 self.scroll_cache_extent,
271 )
272 .default_value(None),
273 );
274 }
275
276 pub fn new() -> ScrollViewData {
278 #[allow(deprecated)]
279 ScrollViewData {
280 key: None,
281 scroll_direction: Axis::Vertical,
282 reverse: false,
283 controller: None,
284 primary: None,
285 physics: None,
286 scroll_behavior: None,
287 shrink_wrap: false,
288 center: None,
289 anchor: 0.0,
290 cache_extent: None,
291 scroll_cache_extent: None,
292 semantic_child_count: None,
293 paint_order: SliverPaintOrder::FirstIsTop,
294 drag_start_behavior: DragStartBehavior::Start,
295 keyboard_dismiss_behavior: None,
296 restoration_id: None,
297 clip_behavior: Clip::HardEdge,
298 hit_test_behavior: HitTestBehavior::Opaque,
299 }
300 }
301}
302
303impl Default for ScrollViewData {
304 fn default() -> ScrollViewData {
305 ScrollViewData::new()
306 }
307}
308
309#[macro_export]
312macro_rules! scroll_view_accessors {
313 () => {
314 fn scroll_view_data(&self) -> &$crate::ScrollViewData {
315 &self.scroll_view
316 }
317
318 fn scroll_view_data_mut(&mut self) -> &mut $crate::ScrollViewData {
319 &mut self.scroll_view
320 }
321 };
322}
323
324#[macro_export]
328macro_rules! scroll_view_setters {
329 ($name:ident) => {
330 pub fn key(mut self, key: $crate::KeyRef) -> $name {
332 self.scroll_view.key = Some(key);
333 self
334 }
335
336 pub fn scroll_direction(mut self, scroll_direction: waft_painting::Axis) -> $name {
338 self.scroll_view.scroll_direction = scroll_direction;
339 self
340 }
341
342 pub fn reverse(mut self, reverse: bool) -> $name {
344 self.scroll_view.reverse = reverse;
345 self
346 }
347
348 pub fn controller(mut self, controller: $crate::ScrollControllerRef) -> $name {
350 debug_assert!(
351 !self.scroll_view.primary.unwrap_or(false),
352 "Primary ScrollViews obtain their ScrollController via inheritance from a \
353 PrimaryScrollController widget. You cannot both set primary to true and pass \
354 an explicit controller."
355 );
356 self.scroll_view.controller = Some(controller);
357 self
358 }
359
360 pub fn primary(mut self, primary: bool) -> $name {
362 debug_assert!(
363 !(self.scroll_view.controller.is_some() && primary),
364 "Primary ScrollViews obtain their ScrollController via inheritance from a \
365 PrimaryScrollController widget. You cannot both set primary to true and pass \
366 an explicit controller."
367 );
368 self.scroll_view.primary = Some(primary);
369 self
370 }
371
372 pub fn physics(mut self, physics: $crate::ScrollPhysicsRef) -> $name {
374 self.scroll_view.physics = Some(physics);
375 self
376 }
377
378 pub fn shrink_wrap(mut self, shrink_wrap: bool) -> $name {
380 debug_assert!(!shrink_wrap || self.scroll_view.center.is_none());
381 self.scroll_view.shrink_wrap = shrink_wrap;
382 self
383 }
384
385 #[deprecated(note = "Use scroll_cache_extent instead.")]
387 pub fn cache_extent(mut self, cache_extent: f64) -> $name {
388 #[allow(deprecated)]
389 {
390 self.scroll_view.cache_extent = Some(cache_extent);
391 }
392 self
393 }
394
395 pub fn scroll_cache_extent(
397 mut self,
398 scroll_cache_extent: waft_rendering::ScrollCacheExtent,
399 ) -> $name {
400 self.scroll_view.scroll_cache_extent = Some(scroll_cache_extent);
401 self
402 }
403
404 pub fn semantic_child_count(mut self, semantic_child_count: i32) -> $name {
406 debug_assert!(semantic_child_count >= 0);
407 self.scroll_view.semantic_child_count = Some(semantic_child_count);
408 self
409 }
410
411 pub fn drag_start_behavior(
413 mut self,
414 drag_start_behavior: waft_gestures::DragStartBehavior,
415 ) -> $name {
416 self.scroll_view.drag_start_behavior = drag_start_behavior;
417 self
418 }
419
420 pub fn keyboard_dismiss_behavior(
422 mut self,
423 keyboard_dismiss_behavior: $crate::ScrollViewKeyboardDismissBehavior,
424 ) -> $name {
425 self.scroll_view.keyboard_dismiss_behavior = Some(keyboard_dismiss_behavior);
426 self
427 }
428
429 pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> $name {
431 self.scroll_view.restoration_id = Some(restoration_id.into());
432 self
433 }
434
435 pub fn clip_behavior(mut self, clip_behavior: waft_embedder::Clip) -> $name {
437 self.scroll_view.clip_behavior = clip_behavior;
438 self
439 }
440
441 pub fn hit_test_behavior(
443 mut self,
444 hit_test_behavior: waft_rendering::HitTestBehavior,
445 ) -> $name {
446 self.scroll_view.hit_test_behavior = hit_test_behavior;
447 self
448 }
449 };
450}
451
452pub trait ScrollView: Clone + Debug + Sized + 'static {
479 fn scroll_view_data(&self) -> &ScrollViewData;
481
482 fn scroll_view_data_mut(&mut self) -> &mut ScrollViewData;
484
485 fn get_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
493 ScrollViewBase::get_direction(self, app, context)
494 }
495
496 fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef>;
501
502 fn build_viewport(
517 &self,
518 app: &mut App,
519 context: BuildContext,
520 offset: ViewportOffsetRef,
521 axis_direction: AxisDirection,
522 slivers: Vec<WidgetRef>,
523 ) -> WidgetRef {
524 ScrollViewBase::build_viewport(self, app, context, offset, axis_direction, slivers)
525 }
526}
527
528pub struct ScrollViewBase;
530
531impl ScrollViewBase {
532 pub fn get_direction<V: ScrollView>(
534 view: &V,
535 app: &mut App,
536 context: BuildContext,
537 ) -> AxisDirection {
538 let data = view.scroll_view_data();
539 get_axis_direction_from_axis_reverse_and_directionality(
540 app,
541 context,
542 data.scroll_direction,
543 data.reverse,
544 )
545 }
546
547 pub fn build_viewport<V: ScrollView>(
549 view: &V,
550 app: &mut App,
551 context: BuildContext,
552 offset: ViewportOffsetRef,
553 axis_direction: AxisDirection,
554 slivers: Vec<WidgetRef>,
555 ) -> WidgetRef {
556 let _ = (app, context);
557 let data = view.scroll_view_data();
558 #[allow(deprecated)]
559 let effective_scroll_cache_extent = data
560 .scroll_cache_extent
561 .or(data.cache_extent.map(ScrollCacheExtent::Pixels));
562 if data.shrink_wrap {
563 let mut viewport = ShrinkWrappingViewport::new(offset)
564 .axis_direction(axis_direction)
565 .slivers(slivers)
566 .paint_order(data.paint_order)
567 .clip_behavior(data.clip_behavior);
568 if let Some(cache_extent) = effective_scroll_cache_extent {
569 viewport = viewport.scroll_cache_extent(cache_extent);
570 }
571 return viewport.into_widget();
572 }
573 let mut viewport = Viewport::new(offset)
574 .axis_direction(axis_direction)
575 .slivers(slivers)
576 .anchor(data.anchor)
577 .paint_order(data.paint_order)
578 .clip_behavior(data.clip_behavior);
579 if let Some(cache_extent) = effective_scroll_cache_extent {
580 viewport = viewport.scroll_cache_extent(cache_extent);
581 }
582 if let Some(center) = data.center.clone() {
583 viewport = viewport.center(center);
584 }
585 viewport.into_widget()
586 }
587
588 pub fn build<V: ScrollView>(view: &V, app: &mut App, context: BuildContext) -> WidgetRef {
590 let slivers = view.build_slivers(app, context);
591 let axis_direction = view.get_direction(app, context);
592
593 let data = view.scroll_view_data().clone();
594 let effective_primary = data.primary.unwrap_or_else(|| {
595 data.controller.is_none()
596 && PrimaryScrollController::should_inherit(app, context, data.scroll_direction)
597 });
598
599 let scroll_controller = if effective_primary {
600 PrimaryScrollController::maybe_of(app, context)
601 } else {
602 data.controller
603 };
604
605 let this = view.clone();
606 let viewport_builder: ViewportBuilder = Rc::new(move |app, context, offset| {
607 this.build_viewport(app, context, offset, axis_direction, slivers.clone())
608 });
609
610 let mut scrollable = Scrollable::new(viewport_builder)
611 .axis_direction(axis_direction)
612 .drag_start_behavior(data.drag_start_behavior)
613 .hit_test_behavior(data.hit_test_behavior)
614 .clip_behavior(data.clip_behavior);
615 let has_scroll_controller = scroll_controller.is_some();
616 if let Some(controller) = scroll_controller {
617 scrollable = scrollable.controller(controller);
618 }
619 if let Some(physics) = ScrollViewBase::effective_physics(view) {
620 scrollable = scrollable.physics(physics);
621 }
622 if let Some(scroll_behavior) = data.scroll_behavior.clone() {
623 scrollable = scrollable.scroll_behavior(scroll_behavior);
624 }
625 if let Some(restoration_id) = data.restoration_id.clone() {
626 scrollable = scrollable.restoration_id(restoration_id);
627 }
628
629 let scrollable_result = if effective_primary && has_scroll_controller {
630 PrimaryScrollController::none(scrollable).into_widget()
633 } else {
634 scrollable.into_widget()
635 };
636
637 let effective_keyboard_dismiss_behavior = data
638 .keyboard_dismiss_behavior
639 .or_else(|| {
640 data.scroll_behavior
641 .as_ref()
642 .map(|behavior| behavior.get_keyboard_dismiss_behavior(app, context))
643 })
644 .unwrap_or_else(|| {
645 ScrollConfiguration::of(app, context).get_keyboard_dismiss_behavior(app, context)
646 });
647
648 if effective_keyboard_dismiss_behavior == ScrollViewKeyboardDismissBehavior::OnDrag {
649 NotificationListener::<ScrollUpdateNotification>::new(scrollable_result)
650 .on_notification(move |app, notification: &ScrollUpdateNotification| {
651 let current_scope = FocusScope::of(app, context, true).as_node();
652 if notification.drag_details.is_some()
653 && !current_scope.has_primary_focus(app)
654 && current_scope.has_focus(app)
655 && let Some(primary) = primary_focus(app)
656 {
657 primary.unfocus(app, UnfocusDisposition::Scope);
658 }
659 false
660 })
661 .into_widget()
662 } else {
663 scrollable_result
664 }
665 }
666
667 fn effective_physics<V: ScrollView>(view: &V) -> Option<ScrollPhysicsRef> {
671 let data = view.scroll_view_data();
672 if let Some(physics) = data.physics.clone() {
673 return Some(physics);
674 }
675 let implied = data.primary.unwrap_or(false)
676 || (data.primary.is_none()
677 && data.controller.is_none()
678 && data.scroll_direction == Axis::Vertical);
679 implied.then(|| Rc::new(AlwaysScrollableScrollPhysics::new()) as ScrollPhysicsRef)
680 }
681}
682
683#[derive(Clone, Debug, Default)]
697pub struct CustomScrollView {
698 scroll_view: ScrollViewData,
699
700 pub slivers: Vec<WidgetRef>,
715}
716
717impl CustomScrollView {
718 pub fn new() -> CustomScrollView {
721 CustomScrollView {
722 scroll_view: ScrollViewData::new(),
723 slivers: Vec::new(),
724 }
725 }
726
727 crate::scroll_view_setters!(CustomScrollView);
728
729 pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> CustomScrollView {
731 self.scroll_view.scroll_behavior = Some(scroll_behavior);
732 self
733 }
734
735 pub fn center(mut self, center: KeyRef) -> CustomScrollView {
737 debug_assert!(!self.scroll_view.shrink_wrap);
738 self.scroll_view.center = Some(center);
739 self
740 }
741
742 pub fn anchor(mut self, anchor: f64) -> CustomScrollView {
744 debug_assert!((0.0..=1.0).contains(&anchor));
745 self.scroll_view.anchor = anchor;
746 self
747 }
748
749 pub fn paint_order(mut self, paint_order: SliverPaintOrder) -> CustomScrollView {
751 self.scroll_view.paint_order = paint_order;
752 self
753 }
754
755 pub fn slivers(mut self, slivers: impl IntoIterator<Item = WidgetRef>) -> CustomScrollView {
757 self.slivers = slivers.into_iter().collect();
758 self
759 }
760}
761
762impl ScrollView for CustomScrollView {
763 crate::scroll_view_accessors!();
764
765 fn build_slivers(&self, _app: &mut App, _context: BuildContext) -> Vec<WidgetRef> {
766 self.slivers.clone()
767 }
768}
769
770impl StatelessWidget for CustomScrollView {
771 fn key(&self) -> Option<&KeyRef> {
772 self.scroll_view.key.as_ref()
773 }
774
775 fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
776 self.scroll_view.debug_fill_properties(app, properties);
777 }
778
779 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
780 ScrollViewBase::build(self, app, context)
781 }
782}
783
784#[derive(Clone, Debug, Default)]
786pub struct BoxScrollViewData {
787 pub padding: Option<EdgeInsetsGeometry>,
789}
790
791impl BoxScrollViewData {
792 pub fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
795 properties.add(
796 DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
797 .default_value(None),
798 );
799 }
800
801 pub fn new() -> BoxScrollViewData {
803 BoxScrollViewData { padding: None }
804 }
805}
806
807#[macro_export]
810macro_rules! box_scroll_view_accessors {
811 () => {
812 fn box_scroll_view_data(&self) -> &$crate::BoxScrollViewData {
813 &self.box_scroll_view
814 }
815
816 fn box_scroll_view_data_mut(&mut self) -> &mut $crate::BoxScrollViewData {
817 &mut self.box_scroll_view
818 }
819 };
820}
821
822pub trait BoxScrollView: ScrollView {
832 fn box_scroll_view_data(&self) -> &BoxScrollViewData;
835
836 fn box_scroll_view_data_mut(&mut self) -> &mut BoxScrollViewData;
838
839 fn build_child_layout(&self, app: &mut App, context: BuildContext) -> WidgetRef;
841}
842
843pub struct BoxScrollViewBase;
845
846impl BoxScrollViewBase {
847 pub fn build_slivers<V: BoxScrollView>(
850 view: &V,
851 app: &mut App,
852 context: BuildContext,
853 ) -> Vec<WidgetRef> {
854 let mut sliver = view.build_child_layout(app, context);
855 let padding = view.box_scroll_view_data().padding;
856 let mut effective_padding = padding;
857 if padding.is_none()
858 && let Some(media_query) = MediaQuery::maybe_of(app, context)
859 {
860 let media_query_horizontal_padding =
862 media_query
863 .padding
864 .copy_with(None, Some(0.0), None, Some(0.0));
865 let media_query_vertical_padding =
866 media_query
867 .padding
868 .copy_with(Some(0.0), None, Some(0.0), None);
869 let vertical = view.scroll_view_data().scroll_direction == Axis::Vertical;
870 effective_padding = Some(EdgeInsetsGeometry::from(if vertical {
872 media_query_vertical_padding
873 } else {
874 media_query_horizontal_padding
875 }));
876 sliver = MediaQuery::new(
878 media_query.copy_with().padding(if vertical {
879 media_query_horizontal_padding
880 } else {
881 media_query_vertical_padding
882 }),
883 sliver,
884 )
885 .into_widget();
886 }
887
888 if let Some(effective_padding) = effective_padding {
889 sliver = SliverPadding::new(effective_padding)
890 .sliver(sliver)
891 .into_widget();
892 }
893 vec![sliver]
894 }
895}
896
897pub struct ListView {
948 scroll_view: ScrollViewData,
949 box_scroll_view: BoxScrollViewData,
950
951 pub item_extent: Option<f64>,
959
960 pub item_extent_builder: Option<ItemExtentBuilder>,
968
969 pub prototype_item: Option<WidgetRef>,
987
988 pub children_delegate: SliverChildDelegateRef,
992
993 list_arguments: Option<ListArguments>,
997}
998
999#[derive(Clone, Debug)]
1002struct ListArguments {
1003 children: Vec<WidgetRef>,
1004 add_automatic_keep_alives: bool,
1005 add_repaint_boundaries: bool,
1006 add_semantic_indexes: bool,
1007}
1008
1009impl ListArguments {
1010 fn new() -> ListArguments {
1011 ListArguments {
1012 children: Vec::new(),
1013 add_automatic_keep_alives: true,
1014 add_repaint_boundaries: true,
1015 add_semantic_indexes: true,
1016 }
1017 }
1018
1019 fn into_delegate(self) -> SliverChildDelegateRef {
1020 SliverChildListDelegate::new(self.children)
1021 .add_automatic_keep_alives(self.add_automatic_keep_alives)
1022 .add_repaint_boundaries(self.add_repaint_boundaries)
1023 .add_semantic_indexes(self.add_semantic_indexes)
1024 .into_delegate()
1025 }
1026}
1027
1028macro_rules! list_arguments_setters {
1031 ($name:ident) => {
1032 pub fn children(self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
1038 let children: Vec<WidgetRef> = children.into_iter().collect();
1039 let count = children.len() as i32;
1040 let mut this = self.with_list_arguments(|arguments| arguments.children = children);
1041 if this.scroll_view.semantic_child_count == Some(0) {
1042 this.scroll_view.semantic_child_count = Some(count);
1043 }
1044 this
1045 }
1046
1047 pub fn add_automatic_keep_alives(self, value: bool) -> $name {
1049 self.with_list_arguments(|arguments| arguments.add_automatic_keep_alives = value)
1050 }
1051
1052 pub fn add_repaint_boundaries(self, value: bool) -> $name {
1054 self.with_list_arguments(|arguments| arguments.add_repaint_boundaries = value)
1055 }
1056
1057 pub fn add_semantic_indexes(self, value: bool) -> $name {
1059 self.with_list_arguments(|arguments| arguments.add_semantic_indexes = value)
1060 }
1061
1062 fn with_list_arguments(mut self, apply: impl FnOnce(&mut ListArguments)) -> $name {
1065 let mut arguments = self.list_arguments.expect(concat!(
1066 "the children and add* setters belong to the ",
1067 stringify!($name),
1068 " constructors that take children"
1069 ));
1070 apply(&mut arguments);
1071 self.children_delegate = arguments.clone().into_delegate();
1072 self.list_arguments = Some(arguments);
1073 self
1074 }
1075 };
1076}
1077
1078impl ListView {
1079 pub fn new() -> ListView {
1090 let list_arguments = ListArguments::new();
1091 ListView {
1092 scroll_view: ScrollViewData {
1093 semantic_child_count: Some(0),
1094 ..ScrollViewData::new()
1095 },
1096 box_scroll_view: BoxScrollViewData::new(),
1097 item_extent: None,
1098 item_extent_builder: None,
1099 prototype_item: None,
1100 children_delegate: list_arguments.clone().into_delegate(),
1101 list_arguments: Some(list_arguments),
1102 }
1103 }
1104
1105 pub fn builder(
1114 item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1115 ) -> ListViewBuilder {
1116 ListViewBuilder::new(Rc::new(item_builder))
1117 }
1118
1119 pub fn separated(
1130 item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1131 separator_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1132 item_count: i32,
1133 ) -> ListViewSeparated {
1134 ListViewSeparated::new(
1135 Rc::new(item_builder),
1136 Rc::new(separator_builder),
1137 item_count,
1138 )
1139 }
1140
1141 pub fn custom(children_delegate: SliverChildDelegateRef) -> ListView {
1146 ListView {
1147 scroll_view: ScrollViewData::new(),
1148 box_scroll_view: BoxScrollViewData::new(),
1149 item_extent: None,
1150 item_extent_builder: None,
1151 prototype_item: None,
1152 children_delegate,
1153 list_arguments: None,
1154 }
1155 }
1156
1157 crate::scroll_view_setters!(ListView);
1158
1159 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ListView {
1161 let padding = padding.into();
1162 self.box_scroll_view.padding = Some(padding);
1163 self
1164 }
1165
1166 pub fn item_extent(mut self, item_extent: f64) -> ListView {
1168 debug_assert!(
1169 self.prototype_item.is_none() && self.item_extent_builder.is_none(),
1170 "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
1171 );
1172 self.item_extent = Some(item_extent);
1173 self
1174 }
1175
1176 pub fn item_extent_builder(mut self, item_extent_builder: ItemExtentBuilder) -> ListView {
1178 debug_assert!(
1179 self.item_extent.is_none() && self.prototype_item.is_none(),
1180 "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
1181 );
1182 self.item_extent_builder = Some(item_extent_builder);
1183 self
1184 }
1185
1186 #[cfg_attr(debug_assertions, track_caller)]
1188 pub fn prototype_item<K>(mut self, prototype_item: impl IntoWidget<K>) -> ListView {
1189 debug_assert!(
1190 self.item_extent.is_none() && self.item_extent_builder.is_none(),
1191 "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
1192 );
1193 self.prototype_item = Some(prototype_item.into_widget());
1194 self
1195 }
1196
1197 list_arguments_setters!(ListView);
1198}
1199
1200impl Default for ListView {
1201 fn default() -> ListView {
1202 ListView::new()
1203 }
1204}
1205
1206impl ScrollView for ListView {
1207 crate::scroll_view_accessors!();
1208
1209 fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef> {
1210 BoxScrollViewBase::build_slivers(self, app, context)
1211 }
1212}
1213
1214impl BoxScrollView for ListView {
1215 crate::box_scroll_view_accessors!();
1216
1217 fn build_child_layout(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1218 if let Some(item_extent) = self.item_extent {
1219 return SliverFixedExtentList::new(self.children_delegate.clone(), item_extent)
1220 .into_widget();
1221 }
1222 if let Some(item_extent_builder) = self.item_extent_builder.clone() {
1223 return SliverVariedExtentList::new(
1224 self.children_delegate.clone(),
1225 item_extent_builder,
1226 )
1227 .into_widget();
1228 }
1229 if let Some(prototype_item) = self.prototype_item.clone() {
1230 return SliverPrototypeExtentList::new(self.children_delegate.clone(), prototype_item)
1231 .into_widget();
1232 }
1233 SliverList::new(self.children_delegate.clone()).into_widget()
1234 }
1235}
1236
1237impl StatelessWidget for ListView {
1238 fn key(&self) -> Option<&KeyRef> {
1239 self.scroll_view.key.as_ref()
1240 }
1241
1242 fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1243 self.scroll_view.debug_fill_properties(app, properties);
1244 self.box_scroll_view.debug_fill_properties(properties);
1245 properties.add(DoubleProperty::new("itemExtent", self.item_extent).default_value(None));
1246 }
1247
1248 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1249 ScrollViewBase::build(self, app, context)
1250 }
1251}
1252
1253pub struct ListViewBuilder {
1255 list_view: ListView,
1256 delegate: SliverChildBuilderDelegate,
1257}
1258
1259impl ListViewBuilder {
1260 fn new(item_builder: NullableIndexedWidgetBuilder) -> ListViewBuilder {
1261 ListViewBuilder {
1262 list_view: ListView::custom(SliverChildListDelegate::new(Vec::new()).into_delegate()),
1263 delegate: SliverChildBuilderDelegate::from_builder(item_builder),
1264 }
1265 }
1266
1267 pub fn item_count(mut self, item_count: i32) -> ListViewBuilder {
1271 debug_assert!(item_count >= 0);
1272 self.delegate = self.delegate.child_count(item_count);
1273 if self.list_view.scroll_view.semantic_child_count.is_none() {
1274 self.list_view.scroll_view.semantic_child_count = Some(item_count);
1275 }
1276 self
1277 }
1278
1279 pub fn find_child_index_callback(
1281 mut self,
1282 find_child_index_callback: ChildIndexGetter,
1283 ) -> ListViewBuilder {
1284 self.delegate = self
1285 .delegate
1286 .find_child_index_callback(find_child_index_callback);
1287 self
1288 }
1289
1290 pub fn add_automatic_keep_alives(mut self, value: bool) -> ListViewBuilder {
1292 self.delegate = self.delegate.add_automatic_keep_alives(value);
1293 self
1294 }
1295
1296 pub fn add_repaint_boundaries(mut self, value: bool) -> ListViewBuilder {
1298 self.delegate = self.delegate.add_repaint_boundaries(value);
1299 self
1300 }
1301
1302 pub fn add_semantic_indexes(mut self, value: bool) -> ListViewBuilder {
1304 self.delegate = self.delegate.add_semantic_indexes(value);
1305 self
1306 }
1307
1308 pub fn build(self) -> ListView {
1310 ListView {
1311 children_delegate: self.delegate.into_delegate(),
1312 ..self.list_view
1313 }
1314 }
1315}
1316
1317pub struct ListViewSeparated {
1319 list_view: ListView,
1320 delegate: SliverChildBuilderDelegate,
1321}
1322
1323impl ListViewSeparated {
1324 fn new(
1325 item_builder: NullableIndexedWidgetBuilder,
1326 separator_builder: NullableIndexedWidgetBuilder,
1327 item_count: i32,
1328 ) -> ListViewSeparated {
1329 debug_assert!(item_count >= 0);
1330 let delegate = SliverChildBuilderDelegate::from_builder(Rc::new(
1331 move |app: &mut App, context, index: i32| {
1332 let item_index = index.div_euclid(2);
1333 if index % 2 == 0 {
1334 item_builder(app, context, item_index)
1335 } else {
1336 separator_builder(app, context, item_index)
1337 }
1338 },
1339 ))
1340 .child_count(compute_actual_child_count(item_count))
1341 .semantic_index_callback(Rc::new(|_widget, index| {
1342 (index % 2 == 0).then_some(index / 2)
1343 }));
1344 ListViewSeparated {
1345 list_view: ListView {
1346 scroll_view: ScrollViewData {
1347 semantic_child_count: Some(item_count),
1348 ..ScrollViewData::new()
1349 },
1350 ..ListView::custom(SliverChildListDelegate::new(Vec::new()).into_delegate())
1351 },
1352 delegate,
1353 }
1354 }
1355
1356 pub fn find_item_index_callback(
1358 mut self,
1359 find_item_index_callback: ChildIndexGetter,
1360 ) -> ListViewSeparated {
1361 self.delegate = self.delegate.find_child_index_callback(Rc::new(move |key| {
1362 find_item_index_callback(key).map(|item_index| item_index * 2)
1363 }));
1364 self
1365 }
1366
1367 pub fn add_automatic_keep_alives(mut self, value: bool) -> ListViewSeparated {
1369 self.delegate = self.delegate.add_automatic_keep_alives(value);
1370 self
1371 }
1372
1373 pub fn add_repaint_boundaries(mut self, value: bool) -> ListViewSeparated {
1375 self.delegate = self.delegate.add_repaint_boundaries(value);
1376 self
1377 }
1378
1379 pub fn add_semantic_indexes(mut self, value: bool) -> ListViewSeparated {
1381 self.delegate = self.delegate.add_semantic_indexes(value);
1382 self
1383 }
1384
1385 pub fn build(self) -> ListView {
1387 ListView {
1388 children_delegate: self.delegate.into_delegate(),
1389 ..self.list_view
1390 }
1391 }
1392}
1393
1394impl IntoWidget<StatelessKind> for ListViewBuilder {
1395 #[cfg_attr(debug_assertions, track_caller)]
1396 fn into_widget(self) -> WidgetRef {
1397 self.build().into_widget()
1398 }
1399}
1400
1401impl IntoWidget<StatelessKind> for ListViewSeparated {
1402 #[cfg_attr(debug_assertions, track_caller)]
1403 fn into_widget(self) -> WidgetRef {
1404 self.build().into_widget()
1405 }
1406}
1407
1408fn compute_actual_child_count(item_count: i32) -> i32 {
1410 (item_count * 2 - 1).max(0)
1411}
1412
1413impl Clone for ListView {
1414 fn clone(&self) -> ListView {
1415 ListView {
1416 scroll_view: self.scroll_view.clone(),
1417 box_scroll_view: self.box_scroll_view.clone(),
1418 item_extent: self.item_extent,
1419 item_extent_builder: self.item_extent_builder.clone(),
1420 prototype_item: self.prototype_item.clone(),
1421 children_delegate: self.children_delegate.clone(),
1422 list_arguments: self.list_arguments.clone(),
1423 }
1424 }
1425}
1426
1427impl Debug for ListView {
1428 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1429 f.debug_struct("ListView")
1430 .field("itemExtent", &self.item_extent)
1431 .field("childrenDelegate", &self.children_delegate)
1432 .finish_non_exhaustive()
1433 }
1434}
1435
1436pub struct GridView {
1468 scroll_view: ScrollViewData,
1469 box_scroll_view: BoxScrollViewData,
1470
1471 pub grid_delegate: Rc<dyn SliverGridDelegate>,
1477
1478 pub children_delegate: SliverChildDelegateRef,
1484
1485 list_arguments: Option<ListArguments>,
1487}
1488
1489impl GridView {
1490 pub fn new(grid_delegate: Rc<dyn SliverGridDelegate>) -> GridView {
1493 let list_arguments = ListArguments::new();
1494 GridView {
1495 scroll_view: ScrollViewData {
1496 semantic_child_count: Some(0),
1497 ..ScrollViewData::new()
1498 },
1499 box_scroll_view: BoxScrollViewData::new(),
1500 grid_delegate,
1501 children_delegate: list_arguments.clone().into_delegate(),
1502 list_arguments: Some(list_arguments),
1503 }
1504 }
1505
1506 pub fn builder(
1518 grid_delegate: Rc<dyn SliverGridDelegate>,
1519 item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1520 ) -> GridViewBuilder {
1521 GridViewBuilder::new(grid_delegate, Rc::new(item_builder))
1522 }
1523
1524 pub fn custom(
1530 grid_delegate: Rc<dyn SliverGridDelegate>,
1531 children_delegate: SliverChildDelegateRef,
1532 ) -> GridView {
1533 GridView {
1534 scroll_view: ScrollViewData::new(),
1535 box_scroll_view: BoxScrollViewData::new(),
1536 grid_delegate,
1537 children_delegate,
1538 list_arguments: None,
1539 }
1540 }
1541
1542 pub fn count(cross_axis_count: i32) -> GridViewCount {
1551 let grid_delegate = SliverGridDelegateWithFixedCrossAxisCount::new(cross_axis_count);
1552 GridViewCount {
1553 grid_view: GridView::new(Rc::new(grid_delegate.clone())),
1554 grid_delegate,
1555 }
1556 }
1557
1558 pub fn extent(max_cross_axis_extent: f64) -> GridViewExtent {
1568 let grid_delegate = SliverGridDelegateWithMaxCrossAxisExtent::new(max_cross_axis_extent);
1569 GridViewExtent {
1570 grid_view: GridView::new(Rc::new(grid_delegate.clone())),
1571 grid_delegate,
1572 }
1573 }
1574
1575 crate::scroll_view_setters!(GridView);
1576
1577 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> GridView {
1579 let padding = padding.into();
1580 self.box_scroll_view.padding = Some(padding);
1581 self
1582 }
1583
1584 list_arguments_setters!(GridView);
1585}
1586
1587impl ScrollView for GridView {
1588 crate::scroll_view_accessors!();
1589
1590 fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef> {
1591 BoxScrollViewBase::build_slivers(self, app, context)
1592 }
1593}
1594
1595impl BoxScrollView for GridView {
1596 crate::box_scroll_view_accessors!();
1597
1598 fn build_child_layout(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1599 SliverGrid::new(
1600 self.children_delegate.clone(),
1601 Rc::clone(&self.grid_delegate),
1602 )
1603 .into_widget()
1604 }
1605}
1606
1607impl StatelessWidget for GridView {
1608 fn key(&self) -> Option<&KeyRef> {
1609 self.scroll_view.key.as_ref()
1610 }
1611
1612 fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1613 self.scroll_view.debug_fill_properties(app, properties);
1614 self.box_scroll_view.debug_fill_properties(properties);
1615 }
1616
1617 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1618 ScrollViewBase::build(self, app, context)
1619 }
1620}
1621
1622impl Clone for GridView {
1623 fn clone(&self) -> GridView {
1624 GridView {
1625 scroll_view: self.scroll_view.clone(),
1626 box_scroll_view: self.box_scroll_view.clone(),
1627 grid_delegate: Rc::clone(&self.grid_delegate),
1628 children_delegate: self.children_delegate.clone(),
1629 list_arguments: self.list_arguments.clone(),
1630 }
1631 }
1632}
1633
1634impl Debug for GridView {
1635 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1636 f.debug_struct("GridView")
1637 .field("gridDelegate", &self.grid_delegate)
1638 .field("childrenDelegate", &self.children_delegate)
1639 .finish_non_exhaustive()
1640 }
1641}
1642
1643pub struct GridViewBuilder {
1645 grid_view: GridView,
1646 delegate: SliverChildBuilderDelegate,
1647}
1648
1649impl GridViewBuilder {
1650 fn new(
1651 grid_delegate: Rc<dyn SliverGridDelegate>,
1652 item_builder: NullableIndexedWidgetBuilder,
1653 ) -> GridViewBuilder {
1654 GridViewBuilder {
1655 grid_view: GridView::custom(
1656 grid_delegate,
1657 SliverChildListDelegate::new(Vec::new()).into_delegate(),
1658 ),
1659 delegate: SliverChildBuilderDelegate::from_builder(item_builder),
1660 }
1661 }
1662
1663 pub fn item_count(mut self, item_count: i32) -> GridViewBuilder {
1666 self.delegate = self.delegate.child_count(item_count);
1667 if self.grid_view.scroll_view.semantic_child_count.is_none() {
1668 self.grid_view.scroll_view.semantic_child_count = Some(item_count);
1669 }
1670 self
1671 }
1672
1673 pub fn find_child_index_callback(
1675 mut self,
1676 find_child_index_callback: ChildIndexGetter,
1677 ) -> GridViewBuilder {
1678 self.delegate = self
1679 .delegate
1680 .find_child_index_callback(find_child_index_callback);
1681 self
1682 }
1683
1684 pub fn add_automatic_keep_alives(mut self, value: bool) -> GridViewBuilder {
1686 self.delegate = self.delegate.add_automatic_keep_alives(value);
1687 self
1688 }
1689
1690 pub fn add_repaint_boundaries(mut self, value: bool) -> GridViewBuilder {
1692 self.delegate = self.delegate.add_repaint_boundaries(value);
1693 self
1694 }
1695
1696 pub fn add_semantic_indexes(mut self, value: bool) -> GridViewBuilder {
1698 self.delegate = self.delegate.add_semantic_indexes(value);
1699 self
1700 }
1701
1702 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> GridViewBuilder {
1704 self.grid_view = self.grid_view.padding(padding);
1705 self
1706 }
1707
1708 pub fn build(self) -> GridView {
1710 GridView {
1711 children_delegate: self.delegate.into_delegate(),
1712 ..self.grid_view
1713 }
1714 }
1715}
1716
1717impl IntoWidget<StatelessKind> for GridViewBuilder {
1718 #[cfg_attr(debug_assertions, track_caller)]
1719 fn into_widget(self) -> WidgetRef {
1720 self.build().into_widget()
1721 }
1722}
1723
1724macro_rules! tiles_constructor_setters {
1727 ($name:ident) => {
1728 pub fn main_axis_spacing(mut self, value: f64) -> $name {
1730 self.grid_delegate = self.grid_delegate.main_axis_spacing(value);
1731 self
1732 }
1733
1734 pub fn cross_axis_spacing(mut self, value: f64) -> $name {
1736 self.grid_delegate = self.grid_delegate.cross_axis_spacing(value);
1737 self
1738 }
1739
1740 pub fn child_aspect_ratio(mut self, value: f64) -> $name {
1742 self.grid_delegate = self.grid_delegate.child_aspect_ratio(value);
1743 self
1744 }
1745
1746 pub fn main_axis_extent(mut self, value: f64) -> $name {
1748 self.grid_delegate = self.grid_delegate.main_axis_extent(value);
1749 self
1750 }
1751
1752 pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
1754 self.grid_view = self.grid_view.children(children);
1755 self
1756 }
1757
1758 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> $name {
1760 self.grid_view = self.grid_view.padding(padding);
1761 self
1762 }
1763
1764 pub fn add_automatic_keep_alives(mut self, value: bool) -> $name {
1766 self.grid_view = self.grid_view.add_automatic_keep_alives(value);
1767 self
1768 }
1769
1770 pub fn add_repaint_boundaries(mut self, value: bool) -> $name {
1772 self.grid_view = self.grid_view.add_repaint_boundaries(value);
1773 self
1774 }
1775
1776 pub fn add_semantic_indexes(mut self, value: bool) -> $name {
1778 self.grid_view = self.grid_view.add_semantic_indexes(value);
1779 self
1780 }
1781
1782 pub fn build(self) -> GridView {
1784 GridView {
1785 grid_delegate: Rc::new(self.grid_delegate),
1786 ..self.grid_view
1787 }
1788 }
1789 };
1790}
1791
1792pub struct GridViewCount {
1794 grid_view: GridView,
1795 grid_delegate: SliverGridDelegateWithFixedCrossAxisCount,
1796}
1797
1798impl GridViewCount {
1799 tiles_constructor_setters!(GridViewCount);
1800}
1801
1802impl IntoWidget<StatelessKind> for GridViewCount {
1803 #[cfg_attr(debug_assertions, track_caller)]
1804 fn into_widget(self) -> WidgetRef {
1805 self.build().into_widget()
1806 }
1807}
1808
1809pub struct GridViewExtent {
1811 grid_view: GridView,
1812 grid_delegate: SliverGridDelegateWithMaxCrossAxisExtent,
1813}
1814
1815impl GridViewExtent {
1816 tiles_constructor_setters!(GridViewExtent);
1817}
1818
1819impl IntoWidget<StatelessKind> for GridViewExtent {
1820 #[cfg_attr(debug_assertions, track_caller)]
1821 fn into_widget(self) -> WidgetRef {
1822 self.build().into_widget()
1823 }
1824}
1825
1826#[cfg(test)]
1827mod tests {
1828 use std::cell::RefCell;
1829 use waft_foundation::{AppCell, ValueKey};
1830
1831 use waft_embedder::{Size, TextDirection};
1832 use waft_painting::{EdgeInsets, EdgeInsetsDirectional};
1833 use waft_rendering::{AnyRenderObject, RenderSliverPadding};
1834
1835 use super::*;
1836 use crate::test_harness::{Harness, VIEW_HEIGHT};
1837 use crate::testing::{WidgetTester, find, test_widgets};
1838 use crate::widgets::basic::{Directionality, SizedBox};
1839 use crate::widgets::media_query::MediaQueryData;
1840 use crate::widgets::reorderable_list::ReorderableDragStartListener;
1841 use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
1842 use crate::widgets::text::Text;
1843
1844 const ITEM_EXTENT: f64 = 50.0;
1845 const ITEM_COUNT: usize = 40;
1846
1847 fn wrap<K>(child: impl IntoWidget<K>) -> WidgetRef {
1850 wrap_with(
1851 MediaQueryData::new().size(Size::new(300.0, VIEW_HEIGHT)),
1852 child,
1853 )
1854 }
1855
1856 fn wrap_in_tester_view<K>(child: impl IntoWidget<K>) -> WidgetRef {
1858 wrap_with(MediaQueryData::new().size(WidgetTester::SIZE), child)
1859 }
1860
1861 fn wrap_with<K>(data: MediaQueryData, child: impl IntoWidget<K>) -> WidgetRef {
1862 let query: WidgetRef = MediaQuery::new(data, child).into_widget();
1863 Directionality::new(TextDirection::Ltr, query).into_widget()
1864 }
1865
1866 fn boxes(count: usize) -> Vec<WidgetRef> {
1867 (0..count)
1868 .map(|_| SizedBox::new().height(ITEM_EXTENT).into_widget())
1869 .collect()
1870 }
1871
1872 fn count_render_objects(
1874 app: &App,
1875 object: AnyRenderObject,
1876 matches: &dyn Fn(&App, AnyRenderObject) -> bool,
1877 ) -> usize {
1878 let mut total = usize::from(matches(app, object));
1879 object.visit_children(app, &mut |child| {
1880 total += count_render_objects(app, child, matches);
1881 });
1882 total
1883 }
1884
1885 fn is_child_wrapper(app: &App, object: AnyRenderObject) -> bool {
1888 object
1889 .downcast::<waft_rendering::RenderIndexedSemantics>(app)
1890 .is_some()
1891 || object
1892 .downcast::<waft_rendering::RenderRepaintBoundary>(app)
1893 .is_some()
1894 }
1895
1896 fn item_count(app: &App, harness: &Harness) -> usize {
1897 count_render_objects(app, harness.render_root(app).as_object(), &|app, object| {
1898 !is_child_wrapper(app, object)
1899 && object
1900 .as_box()
1901 .is_some_and(|render_box| render_box.size(app).height() == ITEM_EXTENT)
1902 })
1903 }
1904
1905 #[test]
1906 fn a_list_view_lays_out_only_the_visible_children_and_scrolls_through_its_controller() {
1907 test_widgets(|tester| {
1908 let controller = tester.update(ScrollController::default);
1909 let list = ListView::new()
1910 .controller(controller.erase())
1911 .children(boxes(ITEM_COUNT));
1912 tester.pump_widget(wrap_in_tester_view(list));
1913
1914 let visible = (WidgetTester::SIZE.height() / ITEM_EXTENT) as usize;
1915 let laid_out = tester.update(item_count_under_view);
1916 assert!(
1917 laid_out >= visible && laid_out < ITEM_COUNT,
1918 "only the visible children (plus the cache) are laid out, not all of them: {laid_out}"
1919 );
1920
1921 tester.update(|app| controller.jump_to(app, 500.0));
1922 tester.pump();
1923 assert_eq!(controller.offset(&tester.cell.borrow()), 500.0);
1924 let scrolled = tester.update(item_count_under_view);
1925 assert!(
1926 scrolled >= visible && scrolled < ITEM_COUNT,
1927 "still only the visible children (plus the cache) after scrolling: {scrolled}"
1928 );
1929 });
1930 }
1931
1932 #[test]
1936 fn a_nested_scrollable_dropped_in_the_frame_it_was_laid_out_sends_no_metrics_notification() {
1937 test_widgets(|tester| {
1938 let controller = tester.update(ScrollController::default);
1939 let mut children = boxes(ITEM_COUNT);
1940 for _ in 0..4 {
1941 children.push(
1942 crate::widgets::single_child_scroll_view::SingleChildScrollView::new()
1943 .scroll_direction(waft_painting::Axis::Horizontal)
1944 .child(SizedBox::new().width(1000.0).height(ITEM_EXTENT))
1945 .into_widget(),
1946 );
1947 }
1948 let list = ListView::new()
1949 .controller(controller.erase())
1950 .children(children);
1951 tester.pump_widget(wrap_in_tester_view(list));
1952 tester.update(|app| controller.jump_to(app, 100_000.0));
1953 tester.pump();
1954 tester.pump();
1955 });
1956 }
1957
1958 fn item_count_under_view(app: &mut App) -> usize {
1959 let root = crate::binding::WidgetsBinding::instance(app)
1960 .root_element(app)
1961 .expect("a mounted root element")
1962 .find_render_object(app)
1963 .expect("a mounted view has a render object");
1964 count_render_objects(app, root, &|app, object| {
1965 !is_child_wrapper(app, object)
1966 && object.as_box().is_some_and(|render_box| {
1967 render_box.has_size(app) && render_box.size(app).height() == ITEM_EXTENT
1968 })
1969 })
1970 }
1971
1972 #[test]
1973 fn a_list_view_builder_creates_its_children_lazily() {
1974 let built: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
1975 let recorded = built.clone();
1976 let list = ListView::builder(move |_app, _context, index| {
1977 recorded.borrow_mut().push(index);
1978 Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
1979 })
1980 .item_count(1000)
1981 .build();
1982
1983 let cell = AppCell::new();
1984 let mut app = cell.borrow_mut();
1985 let harness = Harness::mount(&mut app, wrap(list));
1986 harness.pump(&mut app);
1987
1988 let built = built.borrow();
1989 assert!(!built.is_empty(), "the visible children are built");
1990 assert!(
1991 built.len() < 1000,
1992 "only the visible children are built, not all 1000: {}",
1993 built.len()
1994 );
1995 assert!(
1996 built.iter().all(|index| *index < built.len() as i32),
1997 "the builder is called for the leading indices only: {built:?}"
1998 );
1999 }
2000
2001 #[test]
2002 #[should_panic(
2003 expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2004 )]
2005 fn a_list_view_asserts_on_both_non_null_item_extent_and_prototype_item() {
2006 ListView::new()
2007 .item_extent(100.0)
2008 .prototype_item(SizedBox::new());
2009 }
2010
2011 #[test]
2012 #[should_panic(
2013 expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2014 )]
2015 fn a_list_view_builder_asserts_on_both_non_null_item_extent_and_prototype_item() {
2016 ListView::builder(|_app, _context, _index| Some(SizedBox::new().into_widget()))
2017 .build()
2018 .item_extent(100.0)
2019 .prototype_item(SizedBox::new());
2020 }
2021
2022 #[test]
2023 #[should_panic(
2024 expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2025 )]
2026 fn a_list_view_custom_asserts_on_both_non_null_item_extent_and_prototype_item() {
2027 let delegate = SliverChildBuilderDelegate::from_builder(Rc::new(
2028 |_app: &mut App, _context, _index: i32| Some(SizedBox::new().into_widget()),
2029 ))
2030 .into_delegate();
2031 ListView::custom(delegate)
2032 .item_extent(100.0)
2033 .prototype_item(SizedBox::new());
2034 }
2035
2036 #[test]
2038 #[should_panic(
2039 expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2040 )]
2041 fn a_list_view_asserts_on_both_non_null_prototype_item_and_item_extent_builder() {
2042 ListView::new()
2043 .prototype_item(SizedBox::new())
2044 .item_extent_builder(Rc::new(|_index, _dimensions| Some(30.0)));
2045 }
2046
2047 #[test]
2048 fn if_prototype_item_is_non_null_children_have_same_extent_in_the_scroll_direction() {
2049 test_widgets(|tester| {
2050 let numbers = [0, 1, 2];
2051 let list = ListView::builder(move |_app, _context, index| {
2052 let number = numbers[index as usize];
2053 Some(
2054 SizedBox::new()
2055 .key(ValueKey::new(number).into())
2056 .height(20.0 + f64::from(number) * 10.0)
2058 .child(ReorderableDragStartListener::new(
2059 Text::new(number.to_string()),
2060 index,
2061 ))
2062 .into_widget(),
2063 )
2064 })
2065 .item_count(numbers.len() as i32)
2066 .build()
2067 .prototype_item(SizedBox::new().height(30.0).child(Text::new("3")));
2068 tester.pump_widget(wrap_in_tester_view(list));
2069
2070 assert_eq!(tester.get_size(find::text("0")).height(), 30.0);
2072 assert_eq!(tester.get_size(find::text("1")).height(), 30.0);
2073 assert_eq!(tester.get_size(find::text("2")).height(), 30.0);
2074 });
2075 }
2076
2077 #[test]
2078 fn a_list_view_separated_interleaves_items_and_separators() {
2079 let calls: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2080 let items = calls.clone();
2081 let separators = calls.clone();
2082 let list = ListView::separated(
2083 move |_app, _context, index| {
2084 items.borrow_mut().push(format!("item {index}"));
2085 Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
2086 },
2087 move |_app, _context, index| {
2088 separators.borrow_mut().push(format!("separator {index}"));
2089 Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
2090 },
2091 10,
2092 )
2093 .build();
2094 assert_eq!(list.scroll_view.semantic_child_count, Some(10));
2095
2096 let cell = AppCell::new();
2097 let mut app = cell.borrow_mut();
2098 let harness = Harness::mount(&mut app, wrap(list));
2099 harness.pump(&mut app);
2100
2101 let calls = calls.borrow();
2102 assert_eq!(calls[0], "item 0");
2103 assert_eq!(calls[1], "separator 0");
2104 assert_eq!(calls[2], "item 1");
2105 assert_eq!(calls[3], "separator 1");
2106 }
2107
2108 #[test]
2109 fn a_custom_scroll_view_lays_out_a_box_adapter_above_a_sliver_list() {
2110 use crate::widgets::basic::SliverToBoxAdapter;
2111
2112 let cell = AppCell::new();
2113 let mut app = cell.borrow_mut();
2114 let view = CustomScrollView::new().slivers([
2115 SliverToBoxAdapter::new()
2116 .child(SizedBox::new().height(120.0))
2117 .into_widget(),
2118 SliverList::list(boxes(10)).into_widget(),
2119 ]);
2120 let harness = Harness::mount(&mut app, wrap(view));
2121 harness.pump(&mut app);
2122
2123 let header = count_render_objects(
2124 &app,
2125 harness.render_root(&app).as_object(),
2126 &|app, object| {
2127 object
2128 .as_box()
2129 .is_some_and(|render_box| render_box.size(app).height() == 120.0)
2130 },
2131 );
2132 assert_eq!(header, 1, "the box adapter's child is laid out");
2133 assert!(
2134 item_count(&app, &harness) > 0,
2135 "the sliver list's children are laid out below it"
2136 );
2137 }
2138
2139 #[test]
2142 fn a_grid_view_count_lays_out_the_rows_in_view() {
2143 let cell = AppCell::new();
2144 let mut app = cell.borrow_mut();
2145 let grid = GridView::count(3)
2146 .main_axis_spacing(10.0)
2147 .add_repaint_boundaries(false)
2148 .children(boxes(30))
2149 .build();
2150 assert_eq!(grid.scroll_view.semantic_child_count, Some(30));
2151 let harness = Harness::mount(&mut app, wrap(grid));
2152 harness.pump(&mut app);
2153
2154 let tiles = count_render_objects(
2157 &app,
2158 harness.render_root(&app).as_object(),
2159 &|app, object| {
2160 !is_child_wrapper(app, object)
2161 && object
2162 .as_box()
2163 .is_some_and(|render_box| render_box.size(app) == Size::new(100.0, 100.0))
2164 },
2165 );
2166 assert_eq!(tiles, 15);
2167 }
2168
2169 #[test]
2170 fn a_grid_view_builder_creates_its_tiles_lazily() {
2171 let built: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
2172 let recorded = built.clone();
2173 let tiles = SliverGridDelegateWithMaxCrossAxisExtent::new(150.0);
2174 let grid = GridView::builder(Rc::new(tiles), move |_app, _context, index| {
2175 recorded.borrow_mut().push(index);
2176 Some(SizedBox::new().into_widget())
2177 })
2178 .item_count(1000)
2179 .build();
2180
2181 let cell = AppCell::new();
2182 let mut app = cell.borrow_mut();
2183 let harness = Harness::mount(&mut app, wrap(grid));
2184 harness.pump(&mut app);
2185
2186 let mut built = built.borrow().clone();
2188 built.sort();
2189 assert_eq!(built, (0..6).collect::<Vec<i32>>());
2190 }
2191
2192 #[test]
2195 fn a_grid_view_constructor_takes_padding() {
2196 let cell = AppCell::new();
2197 let mut app = cell.borrow_mut();
2198 let extent = GridView::extent(150.0)
2199 .padding(EdgeInsets::all(8.0))
2200 .children(boxes(4));
2201 let harness = Harness::mount(&mut app, wrap(extent));
2202 harness.pump(&mut app);
2203 let sliver_padding = find_sliver_padding(&app, harness.render_root(&app).as_object())
2204 .expect("the grid wraps its sliver in a SliverPadding");
2205 assert_eq!(
2206 sliver_padding.padding(&app).resolve(None),
2207 EdgeInsets::all(8.0)
2208 );
2209
2210 let delegate = Rc::new(SliverGridDelegateWithFixedCrossAxisCount::new(2));
2211 let built = GridView::builder(delegate, |_app, _context, _index| {
2212 Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
2213 })
2214 .item_count(4)
2215 .padding(EdgeInsetsDirectional::only(4.0, 0.0, 2.0, 0.0))
2216 .build();
2217 harness.set_child(&mut app, wrap(built));
2218 harness.pump(&mut app);
2219 let sliver_padding = find_sliver_padding(&app, harness.render_root(&app).as_object())
2220 .expect("the built grid wraps its sliver in a SliverPadding");
2221 assert_eq!(
2222 sliver_padding
2223 .padding(&app)
2224 .resolve(Some(TextDirection::Ltr)),
2225 EdgeInsets::from_ltrb(4.0, 0.0, 2.0, 0.0)
2226 );
2227 }
2228
2229 #[test]
2230 fn a_box_scroll_view_consumes_the_media_query_padding_along_the_scroll_axis() {
2231 let cell = AppCell::new();
2232 let mut app = cell.borrow_mut();
2233 let padding = EdgeInsets::from_ltrb(8.0, 16.0, 24.0, 32.0);
2234 let list = ListView::new().children(boxes(10));
2235 let harness = Harness::mount(
2236 &mut app,
2237 wrap_with(
2238 MediaQueryData::new()
2239 .size(Size::new(300.0, VIEW_HEIGHT))
2240 .padding(padding),
2241 list,
2242 ),
2243 );
2244 harness.pump(&mut app);
2245
2246 let sliver_padding = find_sliver_padding(&app, harness.render_root(&app).as_object())
2247 .expect("the list wraps its sliver in a SliverPadding");
2248 assert_eq!(
2249 sliver_padding.padding(&app).resolve(None),
2250 EdgeInsets::from_ltrb(0.0, 16.0, 0.0, 32.0),
2251 "the main axis padding is consumed by the SliverPadding"
2252 );
2253 }
2254
2255 fn find_sliver_padding(
2256 app: &App,
2257 object: AnyRenderObject,
2258 ) -> Option<waft_rendering::RenderHandle<RenderSliverPadding>> {
2259 if let Some(padding) = object.downcast::<RenderSliverPadding>(app) {
2260 return Some(padding);
2261 }
2262 let mut found = None;
2263 object.visit_children(app, &mut |child| {
2264 if found.is_none() {
2265 found = find_sliver_padding(app, child);
2266 }
2267 });
2268 found
2269 }
2270}