Skip to main content

waft_material/
badge.rs

1//! Flutter counterpart: material_ui's `badge.dart`.
2
3use waft_embedder::{Clip, Color, Offset, Size, TextBaseline};
4use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty};
5use waft_painting::{
6    AlignmentGeometry, BorderSide, EdgeInsetsGeometry, ShapeDecoration, StadiumBorder,
7    TextDirection, TextStyle,
8};
9use waft_rendering::{
10    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ChildLayoutHelper,
11    ChildLayouter, PaintingContext, RenderAligningShiftedBox, RenderAligningShiftedBoxData,
12    RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectData,
13    RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin, RenderShiftedBox,
14};
15use waft_widgets::{
16    BuildContext, Container, DefaultTextStyle, Directionality, IntoWidget, KeyRef, Positioned,
17    RenderObjectWidget, SingleChildRenderObjectWidget, SizedBox, Stack, StatelessWidget, Text,
18    WidgetRef,
19};
20
21use crate::badge_theme::BadgeTheme;
22use crate::badge_theme::BadgeThemeDataGetters;
23use crate::generated::badge_defaults_m3::BadgeDefaultsM3;
24
25/// A Material Design "badge".
26///
27/// A badge's [`label`](Self::label) conveys a small amount of information about its
28/// [`child`](Self::child), like a count or status. If the label is null then this is
29/// a "small" badge that's displayed as a [`small_size`](Self::small_size) diameter filled
30/// circle. Otherwise this is a [`StadiumBorder`] shaped "large" badge
31/// with height [`large_size`](Self::large_size).
32///
33/// Badges are typically used to decorate the icon within a
34/// `BottomNavigationBarItem` or a `NavigationRailDestination`
35/// or a button's icon, as in `TextButton::icon`. The badge's default
36/// configuration is intended to work well with a default sized (24)
37/// `Icon`.
38#[derive(Debug)]
39pub struct Badge {
40    pub key: Option<KeyRef>,
41
42    /// The badge's fill color.
43    ///
44    /// Defaults to the [`BadgeTheme`]'s background color, or
45    /// `ColorScheme::error` if the theme value is null.
46    pub background_color: Option<Color>,
47
48    /// The color of the badge's [`label`](Self::label) text.
49    ///
50    /// This color overrides the color of the label's [`text_style`](Self::text_style).
51    ///
52    /// Defaults to the [`BadgeTheme`]'s foreground color, or
53    /// `ColorScheme::on_error` if the theme value is null.
54    pub text_color: Option<Color>,
55
56    /// The diameter of the badge if [`label`](Self::label) is null.
57    ///
58    /// Defaults to the [`BadgeTheme`]'s small size, or 6 if the theme value
59    /// is null.
60    pub small_size: Option<f64>,
61
62    /// The badge's height if [`label`](Self::label) is non-null.
63    ///
64    /// Defaults to the [`BadgeTheme`]'s large size, or 16 if the theme value
65    /// is null. If the default value is overridden then it may be useful to
66    /// also override [`padding`](Self::padding) and [`alignment`](Self::alignment).
67    pub large_size: Option<f64>,
68
69    /// The `DefaultTextStyle` for the badge's label.
70    ///
71    /// The text style's color is overwritten by the [`text_color`](Self::text_color).
72    ///
73    /// This value is only used if [`label`](Self::label) is non-null.
74    ///
75    /// Defaults to the [`BadgeTheme`]'s text style, or the overall theme's
76    /// `TextTheme::label_small` if the badge theme's value is null. If
77    /// the default text style is overridden then it may be useful to
78    /// also override [`large_size`](Self::large_size), [`padding`](Self::padding), and
79    /// [`alignment`](Self::alignment).
80    pub text_style: Option<TextStyle>,
81
82    /// The padding added to the badge's label.
83    ///
84    /// This value is only used if [`label`](Self::label) is non-null.
85    ///
86    /// Defaults to the [`BadgeTheme`]'s padding, or 4 pixels on the
87    /// left and right if the theme's value is null.
88    pub padding: Option<EdgeInsetsGeometry>,
89
90    /// Combined with [`offset`](Self::offset) to determine the location of the
91    /// [`label`](Self::label) relative to the [`child`](Self::child).
92    ///
93    /// The alignment positions the label in the same way a child of an
94    /// `Align` widget is positioned, except that, the alignment is
95    /// resolved as if the label was a [`large_size`](Self::large_size) square and
96    /// [`offset`](Self::offset) is added to the result.
97    ///
98    /// This value is only used if [`label`](Self::label) is non-null.
99    ///
100    /// Defaults to the [`BadgeTheme`]'s alignment, or
101    /// `AlignmentDirectional::TOP_END` if the theme's value is null.
102    pub alignment: Option<AlignmentGeometry>,
103
104    /// Combined with [`alignment`](Self::alignment) to determine the location of the
105    /// [`label`](Self::label) relative to the [`child`](Self::child).
106    ///
107    /// This value is only used if [`label`](Self::label) is non-null.
108    ///
109    /// Defaults to the [`BadgeTheme`]'s offset, or
110    /// if the theme's value is null then `Offset(4, -4)` for
111    /// [`TextDirection::Ltr`] or `Offset(-4, -4)` for [`TextDirection::Rtl`].
112    pub offset: Option<Offset>,
113
114    /// The badge's content, typically a `Text` widget that contains 1 to 4
115    /// characters.
116    ///
117    /// If the label is null then this is a "small" badge that's
118    /// displayed as a [`small_size`](Self::small_size) diameter filled circle. Otherwise
119    /// this is a [`StadiumBorder`] shaped "large" badge with height
120    /// [`large_size`](Self::large_size).
121    ///
122    /// A [`Badge::count`] has no label of its own: read it through
123    /// [`effective_label`](Self::effective_label).
124    pub label: Option<WidgetRef>,
125
126    /// If false, the badge's [`label`](Self::label) is not included.
127    ///
128    /// This flag is true by default. It's intended to make it convenient
129    /// to create a badge that's only shown under certain conditions.
130    pub is_label_visible: bool,
131
132    /// The widget that the badge is stacked on top of.
133    ///
134    /// Typically this is an default sized `Icon` that's part of a
135    /// `BottomNavigationBarItem` or a `NavigationRailDestination`.
136    pub child: Option<WidgetRef>,
137
138    count: Option<i64>,
139    max_count: i64,
140}
141
142impl Badge {
143    /// Create a Badge that stacks [`label`](Self::label) on top of [`child`](Self::child).
144    ///
145    /// If [`label`](Self::label) is null then just a filled circle is displayed. Otherwise
146    /// the [`label`](Self::label) is displayed within a [`StadiumBorder`] shaped area.
147    pub fn new() -> Badge {
148        Badge {
149            key: None,
150            background_color: None,
151            text_color: None,
152            small_size: None,
153            large_size: None,
154            text_style: None,
155            padding: None,
156            alignment: None,
157            offset: None,
158            label: None,
159            is_label_visible: true,
160            child: None,
161            count: None,
162            max_count: 999,
163        }
164    }
165
166    /// Convenience constructor for creating a badge with a numeric label based on `count`.
167    ///
168    /// The label is a `Text` widget that shows:
169    /// - the `count` value if it is less than or equal to [`max_count`](Self::max_count),
170    /// - otherwise, shows '`max_count`+'.
171    ///
172    /// For example, if `count` is 1000 and [`max_count`](Self::max_count) is 99, the label
173    /// will display '99+'.
174    ///
175    /// The `count` must be non-negative.
176    pub fn count(count: i64) -> Badge {
177        debug_assert!(count >= 0, "count must be non-negative");
178        Badge {
179            count: Some(count),
180            ..Badge::new()
181        }
182    }
183
184    /// Dart `Badge.count(maxCount:)`: the largest count the label shows, 999 unless given. It
185    /// only has a say in a [`Badge::count`].
186    ///
187    /// The `max_count` must be positive.
188    pub fn max_count(mut self, max_count: i64) -> Badge {
189        debug_assert!(max_count > 0, "maxCount must be positive");
190        self.max_count = max_count;
191        self
192    }
193
194    /// Dart `Badge(key:)`.
195    pub fn key(mut self, key: KeyRef) -> Badge {
196        self.key = Some(key);
197        self
198    }
199
200    /// Dart `Badge(backgroundColor:)`.
201    pub fn background_color(mut self, background_color: Color) -> Badge {
202        self.background_color = Some(background_color);
203        self
204    }
205
206    /// Dart `Badge(textColor:)`.
207    pub fn text_color(mut self, text_color: Color) -> Badge {
208        self.text_color = Some(text_color);
209        self
210    }
211
212    /// Dart `Badge(smallSize:)`.
213    pub fn small_size(mut self, small_size: f64) -> Badge {
214        self.small_size = Some(small_size);
215        self
216    }
217
218    /// Dart `Badge(largeSize:)`.
219    pub fn large_size(mut self, large_size: f64) -> Badge {
220        self.large_size = Some(large_size);
221        self
222    }
223
224    /// Dart `Badge(textStyle:)`.
225    pub fn text_style(mut self, text_style: TextStyle) -> Badge {
226        self.text_style = Some(text_style);
227        self
228    }
229
230    /// Dart `Badge(padding:)`.
231    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Badge {
232        let padding = padding.into();
233        self.padding = Some(padding);
234        self
235    }
236
237    /// Dart `Badge(alignment:)`.
238    pub fn alignment(mut self, alignment: AlignmentGeometry) -> Badge {
239        self.alignment = Some(alignment);
240        self
241    }
242
243    /// Dart `Badge(offset:)`.
244    pub fn offset(mut self, offset: Offset) -> Badge {
245        self.offset = Some(offset);
246        self
247    }
248
249    /// Dart `Badge(label:)`.
250    #[cfg_attr(debug_assertions, track_caller)]
251    pub fn label<K>(mut self, label: impl IntoWidget<K>) -> Badge {
252        self.label = Some(label.into_widget());
253        self
254    }
255
256    /// Dart `Badge(isLabelVisible:)`.
257    pub fn is_label_visible(mut self, is_label_visible: bool) -> Badge {
258        self.is_label_visible = is_label_visible;
259        self
260    }
261
262    /// Dart `Badge(child:)`.
263    #[cfg_attr(debug_assertions, track_caller)]
264    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Badge {
265        self.child = Some(child.into_widget());
266        self
267    }
268
269    /// Dart's `label` field, as `Badge.count` fills it: a `Text` of the count, or of
270    /// `maxCount+` once the count is over it.
271    pub fn effective_label(&self) -> Option<WidgetRef> {
272        match self.count {
273            Some(count) if count > self.max_count => {
274                Some(Text::new(format!("{}+", self.max_count)).into_widget())
275            }
276            Some(count) => Some(Text::new(count.to_string()).into_widget()),
277            None => self.label.clone(),
278        }
279    }
280}
281
282impl Default for Badge {
283    fn default() -> Badge {
284        Badge::new()
285    }
286}
287
288impl StatelessWidget for Badge {
289    fn key(&self) -> Option<&KeyRef> {
290        self.key.as_ref()
291    }
292
293    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
294        if !self.is_label_visible {
295            return self
296                .child
297                .clone()
298                .unwrap_or_else(|| SizedBox::new().into_widget());
299        }
300
301        let badge_theme = BadgeTheme::of(app, context);
302        let defaults = BadgeDefaultsM3::new(context);
303        let effective_decoration = ShapeDecoration::new(StadiumBorder::new(BorderSide::NONE))
304            .color(
305                self.background_color
306                    .or(badge_theme.background_color)
307                    .or_else(|| defaults.background_color(app))
308                    .expect("the defaults give a background color"),
309            );
310        let effective_width_offset;
311        let badge;
312        let label = self.effective_label();
313        let has_label = label.is_some();
314        if let Some(label) = label {
315            let min_size = self
316                .large_size
317                .or(badge_theme.large_size)
318                .or_else(|| defaults.large_size(app))
319                .expect("the defaults give a large size");
320            effective_width_offset = min_size;
321            let text_style = self
322                .text_style
323                .clone()
324                .or(badge_theme.text_style.clone())
325                .or_else(|| defaults.text_style(app))
326                .expect("the defaults give a text style");
327            let mut container = Container::new()
328                .clip_behavior(Clip::AntiAlias)
329                .decoration(effective_decoration)
330                .padding(
331                    self.padding
332                        .or(badge_theme.padding)
333                        .or_else(|| defaults.padding(app))
334                        .expect("the defaults give a padding"),
335                )
336                .alignment(AlignmentGeometry::CENTER);
337            container = container.child(label);
338            badge = DefaultTextStyle::new(
339                text_style.copy_with().color(
340                    self.text_color
341                        .or(badge_theme.text_color)
342                        .or_else(|| defaults.text_color(app))
343                        .expect("the defaults give a text color"),
344                ),
345                IntrinsicHorizontalStadium {
346                    min_size,
347                    child: Some(container.into_widget()),
348                },
349            )
350            .into_widget();
351        } else {
352            let effective_small_size = self
353                .small_size
354                .or(badge_theme.small_size)
355                .or_else(|| defaults.small_size(app))
356                .expect("the defaults give a small size");
357            effective_width_offset = effective_small_size;
358            badge = Container::new()
359                .width(effective_small_size)
360                .height(effective_small_size)
361                .clip_behavior(Clip::AntiAlias)
362                .decoration(effective_decoration)
363                .into_widget();
364        }
365
366        let Some(child) = self.child.clone() else {
367            return badge;
368        };
369
370        let effective_alignment = self
371            .alignment
372            .or(badge_theme.alignment)
373            .or_else(|| defaults.alignment(app))
374            .expect("the defaults give an alignment");
375        let text_direction = Directionality::of(app, context);
376        let default_offset = if text_direction == TextDirection::Ltr {
377            Offset::new(4.0, -4.0)
378        } else {
379            Offset::new(-4.0, -4.0)
380        };
381        // Adds a offset const Offset(0, 8) to avoiding breaking customers after
382        // the offset calculation changes.
383        // See https://github.com/flutter/flutter/pull/146853.
384        let effective_offset =
385            self.offset.or(badge_theme.offset).unwrap_or(default_offset) + Offset::new(0.0, 8.0);
386
387        Stack::new()
388            .clip_behavior(Clip::None)
389            .children([
390                child,
391                Positioned::fill(BadgeLayout {
392                    alignment: effective_alignment,
393                    offset: if has_label {
394                        effective_offset
395                    } else {
396                        Offset::ZERO
397                    },
398                    width_offset: effective_width_offset,
399                    has_label,
400                    child: Some(badge),
401                })
402                .into_widget(),
403            ])
404            .into_widget()
405    }
406}
407
408/// Dart's `_Badge`, without its `textDirection`, which Dart passes and never reads.
409#[derive(Debug)]
410struct BadgeLayout {
411    alignment: AlignmentGeometry,
412    offset: Offset,
413    width_offset: f64,
414    has_label: bool,
415    // the badge
416    child: Option<WidgetRef>,
417}
418
419impl RenderObjectWidget for BadgeLayout {
420    type RenderObject = RenderBadge;
421
422    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
423        properties.add(DiagnosticsProperty::<AlignmentGeometry>::new(
424            "alignment",
425            self.alignment,
426        ));
427        properties.add(DiagnosticsProperty::<Offset>::new("offset", self.offset));
428    }
429
430    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
431        let text_direction = Directionality::maybe_of(app, context);
432        RenderBadge::new(
433            app,
434            self.alignment,
435            self.width_offset,
436            self.has_label,
437            self.offset,
438            text_direction,
439        )
440        .as_object()
441    }
442
443    fn update_render_object(
444        &self,
445        app: &mut App,
446        context: BuildContext,
447        render_object: RenderHandle<RenderBadge>,
448    ) {
449        let text_direction = Directionality::maybe_of(app, context);
450        render_object.set_alignment(app, self.alignment);
451        render_object.set_offset(app, self.offset);
452        render_object.set_width_offset(app, self.width_offset);
453        render_object.set_has_label(app, self.has_label);
454        render_object.set_text_direction(app, text_direction);
455    }
456}
457
458impl SingleChildRenderObjectWidget for BadgeLayout {
459    fn child(&self) -> Option<&WidgetRef> {
460        self.child.as_ref()
461    }
462}
463
464/// Dart's `_RenderBadge`.
465struct RenderBadge {
466    render_object: RenderObjectData,
467    render_box: RenderBoxData,
468    child: RenderObjectWithChildData<AnyRenderBox>,
469    aligning: RenderAligningShiftedBoxData,
470    offset: Offset,
471    has_label: bool,
472    width_offset: f64,
473}
474
475impl RenderBadge {
476    fn new(
477        app: &mut App,
478        alignment: AlignmentGeometry,
479        width_offset: f64,
480        has_label: bool,
481        offset: Offset,
482        text_direction: Option<TextDirection>,
483    ) -> RenderHandle<RenderBadge> {
484        RenderHandle::new_box(
485            app,
486            RenderBadge {
487                render_object: RenderObjectData::new(),
488                render_box: RenderBoxData::new(),
489                child: RenderObjectWithChildData::new(),
490                aligning: RenderAligningShiftedBoxData::new(alignment, text_direction),
491                offset,
492                has_label,
493                width_offset,
494            },
495        )
496    }
497
498    fn set_offset(self: RenderHandle<Self>, app: &mut App, value: Offset) {
499        if self.get(app).offset == value {
500            return;
501        }
502        self.get_mut(app).offset = value;
503        self.mark_needs_layout(app);
504    }
505
506    fn set_has_label(self: RenderHandle<Self>, app: &mut App, value: bool) {
507        if self.get(app).has_label == value {
508            return;
509        }
510        self.get_mut(app).has_label = value;
511        self.mark_needs_layout(app);
512    }
513
514    fn set_width_offset(self: RenderHandle<Self>, app: &mut App, value: f64) {
515        if self.get(app).width_offset == value {
516            return;
517        }
518        self.get_mut(app).width_offset = value;
519        self.mark_needs_layout(app);
520    }
521}
522
523impl RenderObjectWithChildMixin for RenderBadge {
524    type ChildType = AnyRenderBox;
525
526    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
527        &self.get(app).child
528    }
529
530    fn child_data_mut(
531        self: RenderHandle<Self>,
532        app: &mut App,
533    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
534        &mut self.get_mut(app).child
535    }
536}
537
538impl RenderShiftedBox for RenderBadge {}
539
540impl RenderAligningShiftedBox for RenderBadge {
541    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
542        &self.get(app).aligning
543    }
544
545    fn aligning_data_mut(
546        self: RenderHandle<Self>,
547        app: &mut App,
548    ) -> &mut RenderAligningShiftedBoxData {
549        &mut self.get_mut(app).aligning
550    }
551}
552
553impl RenderObject for RenderBadge {
554    waft_rendering::render_object_accessors!();
555
556    fn debug_fill_properties(
557        self: RenderHandle<Self>,
558        app: &App,
559        properties: &mut DiagnosticPropertiesBuilder,
560    ) {
561        // Dart's `_RenderBadge` inherits `RenderAligningShiftedBox.debugFillProperties`.
562        RenderAligningShiftedBox::debug_fill_properties(self, app, properties);
563    }
564
565    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
566        let constraints = self.constraints(app);
567        debug_assert!(constraints.has_bounded_width());
568        debug_assert!(constraints.has_bounded_height());
569        self.set_size(app, constraints.biggest());
570        let size = self.size(app);
571
572        let child = self.child(app).expect("a badge has its child");
573        child.layout(app, BoxConstraints::new(), true);
574        let badge_size = child.size(app).height();
575        let resolved_alignment = self.alignment(app).resolve(self.text_direction(app));
576        let (offset, width_offset, has_label) = {
577            let this = self.get(app);
578            (this.offset, this.width_offset, this.has_label)
579        };
580        let mut badge_location = offset
581            + resolved_alignment
582                .along_offset(Offset::new(size.width() - width_offset, size.height()));
583        if has_label {
584            // Adjust for label height.
585            badge_location = badge_location - Offset::new(0.0, badge_size / 2.0);
586        }
587        child
588            .as_object()
589            .parent_data_of_mut::<waft_rendering::BoxParentData>(app)
590            .offset = badge_location;
591    }
592
593    fn paint(
594        self: RenderHandle<Self>,
595        app: &mut App,
596        context: &mut PaintingContext,
597        offset: Offset,
598    ) {
599        RenderShiftedBox::paint(self, app, context, offset);
600    }
601
602    fn visit_children(
603        self: RenderHandle<Self>,
604        app: &App,
605        visitor: &mut dyn FnMut(AnyRenderObject),
606    ) {
607        if let Some(child) = self.child(app) {
608            visitor(child.as_object());
609        }
610    }
611}
612
613impl RenderBox for RenderBadge {
614    waft_rendering::render_box_accessors!();
615
616    fn hit_test_children(
617        self: RenderHandle<Self>,
618        app: &mut App,
619        result: &mut BoxHitTestResult<'_>,
620        position: Offset,
621    ) -> bool {
622        RenderShiftedBox::hit_test_children(self, app, result, position)
623    }
624
625    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
626        RenderShiftedBox::compute_min_intrinsic_width(self, app, height)
627    }
628
629    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
630        RenderShiftedBox::compute_max_intrinsic_width(self, app, height)
631    }
632
633    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
634        RenderShiftedBox::compute_min_intrinsic_height(self, app, width)
635    }
636
637    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
638        RenderShiftedBox::compute_max_intrinsic_height(self, app, width)
639    }
640
641    fn compute_distance_to_actual_baseline(
642        self: RenderHandle<Self>,
643        app: &mut App,
644        baseline: TextBaseline,
645    ) -> Option<f64> {
646        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
647    }
648
649    fn compute_dry_layout(
650        self: RenderHandle<Self>,
651        _app: &mut App,
652        constraints: BoxConstraints,
653    ) -> Size {
654        // Mirrors performLayout: size is the tightest allowed (biggest) under bounded constraints.
655        // Callers (e.g., Stack) pass in tight constraints for Positioned.fill; otherwise, this
656        // is still consistent with performLayout which asserts bounded constraints.
657        constraints.biggest()
658    }
659
660    fn compute_dry_baseline(
661        self: RenderHandle<Self>,
662        app: &mut App,
663        constraints: BoxConstraints,
664        baseline: TextBaseline,
665    ) -> Option<f64> {
666        let child = self.child(app)?;
667
668        // Child is laid out with unconstrained BoxConstraints in performLayout.
669        let child_constraints = BoxConstraints::new();
670        let child_baseline = child.get_dry_baseline(app, child_constraints, baseline)?;
671
672        // Mirror the paint offset logic from performLayout using dry sizes only.
673        let my_size = self.get_dry_layout(app, constraints);
674        let resolved_alignment = self.alignment(app).resolve(self.text_direction(app));
675        let child_size = child.get_dry_layout(app, child_constraints);
676
677        let (offset, width_offset, has_label) = {
678            let this = self.get(app);
679            (this.offset, this.width_offset, this.has_label)
680        };
681        let mut badge_location = offset
682            + resolved_alignment.along_offset(Offset::new(
683                my_size.width() - width_offset,
684                my_size.height(),
685            ));
686        if has_label {
687            // Subtract half of the badge height when we have a label (as in performLayout).
688            badge_location = badge_location - Offset::new(0.0, child_size.height() / 2.0);
689        }
690
691        Some(child_baseline + badge_location.dy())
692    }
693}
694
695/// Dart's `_IntrinsicHorizontalStadium`.
696#[derive(Debug)]
697struct IntrinsicHorizontalStadium {
698    min_size: f64,
699    child: Option<WidgetRef>,
700}
701
702impl RenderObjectWidget for IntrinsicHorizontalStadium {
703    type RenderObject = RenderIntrinsicHorizontalStadium;
704
705    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
706        RenderIntrinsicHorizontalStadium::new(app, self.min_size).as_object()
707    }
708}
709
710impl SingleChildRenderObjectWidget for IntrinsicHorizontalStadium {
711    fn child(&self) -> Option<&WidgetRef> {
712        self.child.as_ref()
713    }
714}
715
716/// Dart's `_RenderIntrinsicHorizontalStadium`.
717struct RenderIntrinsicHorizontalStadium {
718    render_object: RenderObjectData,
719    render_box: RenderBoxData,
720    child: RenderObjectWithChildData<AnyRenderBox>,
721    min_size: f64,
722}
723
724impl RenderIntrinsicHorizontalStadium {
725    fn new(app: &mut App, min_size: f64) -> RenderHandle<RenderIntrinsicHorizontalStadium> {
726        RenderHandle::new_box(
727            app,
728            RenderIntrinsicHorizontalStadium {
729                render_object: RenderObjectData::new(),
730                render_box: RenderBoxData::new(),
731                child: RenderObjectWithChildData::new(),
732                min_size,
733            },
734        )
735    }
736
737    fn child_constraints(
738        self: RenderHandle<Self>,
739        app: &mut App,
740        child: AnyRenderBox,
741        constraints: BoxConstraints,
742    ) -> BoxConstraints {
743        let min_size = self.get(app).min_size;
744        let child_height = min_size.max(child.get_max_intrinsic_height(app, constraints.max_width));
745        let child_width = child.get_max_intrinsic_width(app, constraints.max_height);
746        constraints.tighten(Some(child_width.max(child_height)), Some(child_height))
747    }
748
749    fn compute_size(
750        self: RenderHandle<Self>,
751        app: &mut App,
752        layout_child: ChildLayouter,
753        constraints: BoxConstraints,
754    ) -> Size {
755        let child = self.child(app).expect("the badge label has its child");
756        let child_constraints = self.child_constraints(app, child, constraints);
757        let child_size = layout_child(app, child, child_constraints);
758        if child_size.height() > child_size.width() {
759            return Size::new(child_size.height(), child_size.height());
760        }
761        child_size
762    }
763}
764
765impl RenderObjectWithChildMixin for RenderIntrinsicHorizontalStadium {
766    type ChildType = AnyRenderBox;
767
768    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
769        &self.get(app).child
770    }
771
772    fn child_data_mut(
773        self: RenderHandle<Self>,
774        app: &mut App,
775    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
776        &mut self.get_mut(app).child
777    }
778}
779
780impl RenderProxyBoxMixin for RenderIntrinsicHorizontalStadium {}
781
782impl RenderObject for RenderIntrinsicHorizontalStadium {
783    waft_rendering::render_object_accessors!();
784
785    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
786        let constraints = self.constraints(app);
787        let size = self.compute_size(app, ChildLayoutHelper::layout_child, constraints);
788        self.set_size(app, size);
789    }
790
791    fn paint(
792        self: RenderHandle<Self>,
793        app: &mut App,
794        context: &mut PaintingContext,
795        offset: Offset,
796    ) {
797        RenderProxyBoxMixin::paint(self, app, context, offset);
798    }
799
800    fn visit_children(
801        self: RenderHandle<Self>,
802        app: &App,
803        visitor: &mut dyn FnMut(AnyRenderObject),
804    ) {
805        if let Some(child) = self.child(app) {
806            visitor(child.as_object());
807        }
808    }
809}
810
811impl RenderBox for RenderIntrinsicHorizontalStadium {
812    waft_rendering::render_box_accessors!();
813
814    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
815        RenderProxyBoxMixin::setup_parent_data(self, app, child);
816    }
817
818    fn apply_paint_transform(
819        self: RenderHandle<Self>,
820        app: &App,
821        child: AnyRenderObject,
822        transform: &mut waft_embedder::Matrix4,
823    ) {
824        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
825    }
826
827    fn hit_test_children(
828        self: RenderHandle<Self>,
829        app: &mut App,
830        result: &mut BoxHitTestResult<'_>,
831        position: Offset,
832    ) -> bool {
833        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
834    }
835
836    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
837        self.get_max_intrinsic_width(app, height)
838    }
839
840    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
841        self.get_max_intrinsic_height(app, f64::INFINITY).max(
842            RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height),
843        )
844    }
845
846    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
847        self.get_max_intrinsic_height(app, width)
848    }
849
850    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
851        let min_size = self.get(app).min_size;
852        min_size.max(RenderProxyBoxMixin::compute_max_intrinsic_height(
853            self, app, width,
854        ))
855    }
856
857    fn compute_distance_to_actual_baseline(
858        self: RenderHandle<Self>,
859        app: &mut App,
860        baseline: TextBaseline,
861    ) -> Option<f64> {
862        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
863    }
864
865    fn compute_dry_layout(
866        self: RenderHandle<Self>,
867        app: &mut App,
868        constraints: BoxConstraints,
869    ) -> Size {
870        self.compute_size(app, ChildLayoutHelper::dry_layout_child, constraints)
871    }
872
873    fn compute_dry_baseline(
874        self: RenderHandle<Self>,
875        app: &mut App,
876        constraints: BoxConstraints,
877        baseline: TextBaseline,
878    ) -> Option<f64> {
879        let child = self.child(app).expect("the badge label has its child");
880        let child_constraints = self.child_constraints(app, child, constraints);
881        child.get_dry_baseline(app, child_constraints, baseline)
882    }
883}
884
885#[cfg(test)]
886pub(crate) mod tests {
887    //! Ported from `test/badge_test.dart`. flutter_test lays text out in FlutterTest, whose glyphs
888    //! are squares of the font size; a case that reads a label's style reads the style of the
889    //! `RenderParagraph`, as Dart does.
890
891    use std::cell::RefCell;
892    use std::rc::Rc;
893
894    use waft_embedder::{Offset, RRect, Radius, Rect, Size, TextDirection};
895    use waft_painting::Alignment;
896    use waft_widgets::{
897        Align, Builder, Center, Container, CustomScrollView, Directionality, GlobalKey, Icon,
898        LayoutBuilder, SliverList, SliverToBoxAdapter,
899    };
900
901    use crate::material::Material;
902    use crate::tab_controller::DefaultTabController;
903
904    use waft_widgets::testing::{WidgetTester, find, test_widgets};
905
906    use super::*;
907    use crate::bottom_navigation_bar::tests::paragraph_style;
908    use crate::colors::Colors;
909    use crate::icons::Icons;
910    use crate::test_support::{PaintInspection, path_like};
911    use crate::theme::Theme;
912    use crate::theme_data::ThemeData;
913    use crate::tooltip::tests::{m3, pump_app};
914
915    /// What a case reads from the build of its widgets.
916    #[derive(Clone, Default)]
917    pub(crate) struct Seen {
918        theme: Rc<RefCell<Option<Rc<ThemeData>>>>,
919    }
920
921    impl Seen {
922        fn theme(&self) -> Rc<ThemeData> {
923            self.theme.borrow().clone().expect("the probe was built")
924        }
925    }
926
927    /// Dart's `Builder(builder: (context) { theme = Theme.of(context); return badge; })`.
928    fn badge_reading_theme(seen: &Seen, badge: Badge) -> WidgetRef {
929        let theme = Rc::clone(&seen.theme);
930        let badge = badge.into_widget();
931        Builder::new(move |app, context| {
932            *theme.borrow_mut() = Some(Theme::of(app, context));
933            badge.clone()
934        })
935        .into_widget()
936    }
937
938    pub(crate) fn add_icon() -> WidgetRef {
939        Icon::new(Some(Icons::add())).into_widget()
940    }
941
942    fn top_left_aligned<K>(child: impl IntoWidget<K>) -> WidgetRef {
943        Align::new()
944            .alignment(AlignmentGeometry::TOP_LEFT)
945            .child(child)
946            .into_widget()
947    }
948
949    pub(crate) fn badge_rect(tester: &WidgetTester) -> Rect {
950        let badge = find::by_type::<Badge>().evaluate(tester)[0];
951        tester.get_rect(badge)
952    }
953
954    pub(crate) fn badge_paints_rrect(
955        tester: &WidgetTester,
956        rrect: RRect,
957        color: Option<Color>,
958    ) -> bool {
959        let badge = find::by_type::<Badge>().evaluate(tester)[0];
960        waft_rendering::testing::paints(
961            &tester.painted_ops(tester.render_object(badge)),
962            &[waft_rendering::testing::PaintCall::rrect_at(rrect, color)],
963        )
964        .is_ok()
965    }
966
967    fn stadium(left: f64, top: f64, right: f64, bottom: f64, radius: f64) -> RRect {
968        RRect::from_ltrbr(left, top, right, bottom, Radius::circular(radius))
969    }
970
971    #[test]
972    fn large_badge_defaults() {
973        test_widgets(|tester| {
974            let seen = Seen::default();
975            pump_app(tester, m3, |_app| {
976                top_left_aligned(badge_reading_theme(
977                    &seen,
978                    Badge::new().label(Text::new("0")).child(add_icon()),
979                ))
980            });
981            let theme = seen.theme();
982
983            assert_eq!(
984                paragraph_style(tester, "0"),
985                theme
986                    .text_theme
987                    .label_small
988                    .clone()
989                    .expect("a label small style")
990                    .copy_with()
991                    .color(theme.color_scheme.on_error())
992            );
993
994            // default badge alignment = AlignmentDirection.topEnd
995            // default offset for LTR = Offset(4, -4)
996            // default padding = EdgeInsets.symmetric(horizontal: 4)
997            // default largeSize = 16
998            // '0'.width = 11.5 (a 11 square and its letter spacing of 0.5)
999            // icon.width = 24
1000
1001            // default Icon size
1002            assert_eq!(badge_rect(tester).size(), Size::new(24.0, 24.0));
1003            assert_eq!(badge_rect(tester).top_left(), Offset::ZERO);
1004
1005            assert_eq!(
1006                tester.get_rect(find::text("0")).top_left(),
1007                Offset::new(16.0, -4.0)
1008            );
1009
1010            assert!(badge_paints_rrect(
1011                tester,
1012                stadium(12.0, -4.0, 31.5, 12.0, 8.0),
1013                Some(theme.color_scheme.error()),
1014            ));
1015        });
1016    }
1017
1018    #[test]
1019    fn large_badge_defaults_with_rtl() {
1020        test_widgets(|tester| {
1021            let seen = Seen::default();
1022            pump_app(tester, m3, |_app| {
1023                Directionality::new(
1024                    TextDirection::Rtl,
1025                    top_left_aligned(badge_reading_theme(
1026                        &seen,
1027                        Badge::new().label(Text::new("0")).child(add_icon()),
1028                    )),
1029                )
1030                .into_widget()
1031            });
1032            let theme = seen.theme();
1033
1034            assert_eq!(
1035                paragraph_style(tester, "0"),
1036                theme
1037                    .text_theme
1038                    .label_small
1039                    .clone()
1040                    .expect("a label small style")
1041                    .copy_with()
1042                    .color(theme.color_scheme.on_error())
1043            );
1044
1045            assert_eq!(badge_rect(tester).size(), Size::new(24.0, 24.0));
1046            assert_eq!(badge_rect(tester).top_left(), Offset::ZERO);
1047
1048            assert_eq!(
1049                tester.get_rect(find::text("0")).top_left(),
1050                Offset::new(0.0, -4.0)
1051            );
1052
1053            assert!(badge_paints_rrect(
1054                tester,
1055                stadium(-4.0, -4.0, 15.5, 12.0, 8.0),
1056                Some(theme.color_scheme.error()),
1057            ));
1058        });
1059    }
1060
1061    // Essentially the same as 'Large Badge defaults'.
1062    #[test]
1063    fn badge_count() {
1064        test_widgets(|tester| {
1065            let seen = Seen::default();
1066            let build_frame = |count: i64, seen: &Seen| {
1067                top_left_aligned(badge_reading_theme(
1068                    seen,
1069                    Badge::count(count).child(add_icon()),
1070                ))
1071            };
1072            pump_app(tester, m3, |_app| build_frame(0, &seen));
1073            let theme = seen.theme();
1074
1075            // default badge alignment = AlignmentDirectional(12, -4)
1076            // default padding = EdgeInsets.symmetric(horizontal: 4)
1077            // default largeSize = 16
1078            // icon.width = 24
1079
1080            // default Icon size
1081            assert_eq!(badge_rect(tester).size(), Size::new(24.0, 24.0));
1082            assert_eq!(badge_rect(tester).top_left(), Offset::ZERO);
1083
1084            // The font's '0' is narrower than the badge is tall, where FlutterTest
1085            // gives it 11.5: the stadium is as wide as it is tall, and centers the text.
1086            let label = find::text("0").evaluate(tester);
1087            assert_eq!(label.len(), 1);
1088            let text_rect = tester.get_rect(label[0]);
1089            let badge_width = (text_rect.width() + 8.0).max(16.0);
1090            // x = alignment.start + the space around the text
1091            waft_widgets::testing::assert_more_or_less_equals(
1092                text_rect.left,
1093                12.0 + (badge_width - text_rect.width()) / 2.0,
1094            );
1095            waft_widgets::testing::assert_more_or_less_equals_within(text_rect.top, -4.0, 0.05);
1096
1097            // L = alignment.start
1098            // T = alignment.top
1099            // R = L + '0'.width + padding.width
1100            // B = T + largeSize, R = largeSize/2
1101            assert!(badge_paints_rrect(
1102                tester,
1103                stadium(12.0, -4.0, 12.0 + badge_width, 12.0, 8.0),
1104                Some(theme.color_scheme.error()),
1105            ));
1106
1107            pump_app(tester, m3, |_app| build_frame(1000, &seen));
1108            assert_eq!(find::text("999+").evaluate(tester).len(), 1);
1109        });
1110    }
1111
1112    #[test]
1113    fn small_badge_defaults() {
1114        test_widgets(|tester| {
1115            pump_app(tester, m3, |_app| {
1116                top_left_aligned(Badge::new().child(add_icon()))
1117            });
1118            let colors = ThemeData::new(&tester.cell.borrow()).color_scheme;
1119
1120            // default badge location is end=0, top=0
1121            // default padding = EdgeInsets.symmetric(horizontal: 4)
1122            // default smallSize = 6
1123            // icon.width = 24
1124
1125            // default Icon size
1126            assert_eq!(badge_rect(tester).size(), Size::new(24.0, 24.0));
1127            assert_eq!(badge_rect(tester).top_left(), Offset::ZERO);
1128
1129            // L = icon.size.width - smallSize
1130            // T = 0
1131            // R = icon.size.width
1132            // B = smallSize
1133            assert!(badge_paints_rrect(
1134                tester,
1135                stadium(18.0, 0.0, 24.0, 6.0, 3.0),
1136                Some(colors.error()),
1137            ));
1138        });
1139    }
1140
1141    #[test]
1142    fn small_badge_rtl_defaults() {
1143        test_widgets(|tester| {
1144            pump_app(tester, m3, |_app| {
1145                Directionality::new(
1146                    TextDirection::Rtl,
1147                    top_left_aligned(Badge::new().child(add_icon())),
1148                )
1149                .into_widget()
1150            });
1151            let colors = ThemeData::new(&tester.cell.borrow()).color_scheme;
1152
1153            // default badge location is end=0, top=0
1154            // default smallSize = 6
1155            // icon.width = 24
1156
1157            // default Icon size
1158            assert_eq!(badge_rect(tester).size(), Size::new(24.0, 24.0));
1159            assert_eq!(badge_rect(tester).top_left(), Offset::ZERO);
1160
1161            // L = 0
1162            // T = 0
1163            // R = smallSize
1164            // B = smallSize
1165            assert!(badge_paints_rrect(
1166                tester,
1167                stadium(0.0, 0.0, 6.0, 6.0, 3.0),
1168                Some(colors.error()),
1169            ));
1170        });
1171    }
1172
1173    #[test]
1174    fn large_badge_text_style_and_colors() {
1175        test_widgets(|tester| {
1176            let green = Color::new(0xff00ff00);
1177            let black = Color::new(0xff000000);
1178            pump_app(tester, m3, |_app| {
1179                top_left_aligned(
1180                    Badge::new()
1181                        .text_color(green)
1182                        .background_color(black)
1183                        .text_style(TextStyle::new().font_size(10.0))
1184                        .label(Text::new("0"))
1185                        .child(add_icon()),
1186                )
1187            });
1188
1189            let text_style = paragraph_style(tester, "0");
1190            assert_eq!(text_style.font_size, Some(10.0));
1191            assert_eq!(
1192                text_style.color.as_ref().map(|color| color.color()),
1193                Some(green)
1194            );
1195            let badge = find::by_type::<Badge>().evaluate(tester)[0];
1196            let drawn = tester.painted_calls(tester.render_object(badge));
1197            assert!(drawn.iter().any(|call| {
1198                path_like(call).is_some_and(|(color, _)| color.to_argb32() == 0xff000000)
1199            }));
1200        });
1201    }
1202
1203    #[test]
1204    fn is_label_visible() {
1205        test_widgets(|tester| {
1206            pump_app(tester, m3, |_app| {
1207                top_left_aligned(
1208                    Badge::new()
1209                        .label(Text::new("0"))
1210                        .is_label_visible(false)
1211                        .child(add_icon()),
1212                )
1213            });
1214
1215            assert!(find::text("0").evaluate(tester).is_empty());
1216            assert_eq!(find::by_type::<Icon>().evaluate(tester).len(), 1);
1217
1218            // default Icon size
1219            assert_eq!(badge_rect(tester).size(), Size::new(24.0, 24.0));
1220            assert_eq!(badge_rect(tester).top_left(), Offset::ZERO);
1221            let badge = find::by_type::<Badge>().evaluate(tester)[0];
1222            let drawn = tester.painted_calls(tester.render_object(badge));
1223            assert!(!drawn.iter().any(|drawn| path_like(drawn).is_some()));
1224        });
1225    }
1226
1227    /// The eight alignments of [`Alignment`] a badge `width` wide takes on a 200 square, as
1228    /// `(alignment, left, top)` of the badge's box, whose top is its alignment's, the box being
1229    /// the same height as the badge's label sits at.
1230    fn aligned_corners(width: f64) -> [(Alignment, f64, f64); 8] {
1231        [
1232            (Alignment::TOP_LEFT, 0.0, 0.0),
1233            (Alignment::TOP_CENTER, 100.0 - width / 2.0, 0.0),
1234            (Alignment::TOP_RIGHT, 200.0 - width, 0.0),
1235            (Alignment::CENTER_LEFT, 0.0, 100.0),
1236            (Alignment::CENTER_RIGHT, 200.0 - width, 100.0),
1237            (Alignment::BOTTOM_LEFT, 0.0, 200.0),
1238            (Alignment::BOTTOM_CENTER, 100.0 - width / 2.0, 200.0),
1239            (Alignment::BOTTOM_RIGHT, 200.0 - width, 200.0),
1240        ]
1241    }
1242
1243    #[test]
1244    fn large_badge_alignment() {
1245        test_widgets(|tester| {
1246            let build_frame = |alignment: Alignment, offset: Offset| {
1247                top_left_aligned(
1248                    Badge::new()
1249                        // Default largeSize = 16, badge with label is "large".
1250                        .label(
1251                            Container::new()
1252                                .width(8.0)
1253                                .height(8.0)
1254                                .color(Colors::BLUE.primary()),
1255                        )
1256                        .alignment(alignment.into())
1257                        .offset(offset)
1258                        .child(
1259                            Container::new()
1260                                .color(Color::new(0xFF00FF00))
1261                                .width(200.0)
1262                                .height(200.0),
1263                        ),
1264                )
1265            };
1266
1267            for offset in [Offset::ZERO, Offset::new(5.0, 10.0)] {
1268                for (alignment, left, top) in aligned_corners(16.0) {
1269                    pump_app(tester, m3, |_app| build_frame(alignment, offset));
1270                    assert!(
1271                        badge_paints_rrect(
1272                            tester,
1273                            stadium(left, top, left + 16.0, top + 16.0, 8.0).shift(offset),
1274                            None,
1275                        ),
1276                        "{alignment:?} with {offset:?}"
1277                    );
1278                }
1279            }
1280        });
1281    }
1282
1283    #[test]
1284    fn small_badge_alignment() {
1285        test_widgets(|tester| {
1286            let build_frame = |alignment: Alignment, offset: Offset| {
1287                top_left_aligned(
1288                    Badge::new()
1289                        // Default smallSize = 6, badge without label is "small".
1290                        .alignment(alignment.into())
1291                        // Not used for smallSize badges.
1292                        .offset(offset)
1293                        .child(
1294                            Container::new()
1295                                .color(Color::new(0xFF00FF00))
1296                                .width(200.0)
1297                                .height(200.0),
1298                        ),
1299                )
1300            };
1301
1302            for offset in [Offset::ZERO, Offset::new(5.0, 10.0)] {
1303                for (alignment, left, top) in aligned_corners(6.0) {
1304                    pump_app(tester, m3, |_app| build_frame(alignment, offset));
1305                    assert!(
1306                        badge_paints_rrect(
1307                            tester,
1308                            stadium(left, top, left + 6.0, top + 6.0, 3.0),
1309                            None,
1310                        ),
1311                        "{alignment:?} with {offset:?}"
1312                    );
1313                }
1314            }
1315        });
1316    }
1317
1318    #[test]
1319    fn badge_larger_than_large_size() {
1320        test_widgets(|tester| {
1321            pump_app(tester, m3, |_app| {
1322                top_left_aligned(
1323                    Badge::new()
1324                        // LargeSize = 16, make content of badge bigger than the default.
1325                        .label(
1326                            Container::new()
1327                                .width(30.0)
1328                                .height(30.0)
1329                                .color(Colors::BLUE.primary()),
1330                        )
1331                        .alignment(Alignment::TOP_LEFT.into())
1332                        .offset(Offset::ZERO)
1333                        .child(
1334                            Container::new()
1335                                .color(Color::new(0xFF00FF00))
1336                                .width(200.0)
1337                                .height(200.0),
1338                        ),
1339                )
1340            });
1341
1342            // Badge should scale with content
1343            assert!(badge_paints_rrect(
1344                tester,
1345                stadium(0.0, -7.0, 30.0 + 8.0, 23.0, 15.0),
1346                None,
1347            ));
1348        });
1349    }
1350
1351    #[test]
1352    fn badge_renders_at_zero_area() {
1353        test_widgets(|tester| {
1354            pump_app(tester, m3, |_app| {
1355                Center::new()
1356                    .child(SizedBox::shrink().child(Badge::new().label(Text::new("X"))))
1357                    .into_widget()
1358            });
1359            let label = find::text("X").evaluate(tester);
1360            assert_eq!(label.len(), 1);
1361            let rect = tester.get_rect(label[0]);
1362            assert_eq!(rect.size(), Size::ZERO);
1363        });
1364    }
1365
1366    #[test]
1367    fn badge_count_max_count_limits_displayed_value() {
1368        test_widgets(|tester| {
1369            let mut shows = |count: i64, max_count: Option<i64>, text: &str| {
1370                let badge = match max_count {
1371                    Some(max_count) => Badge::count(count).max_count(max_count),
1372                    None => Badge::count(count),
1373                };
1374                pump_app(tester, m3, |_app| top_left_aligned(badge.child(add_icon())));
1375                assert_eq!(find::text(text).evaluate(tester).len(), 1, "{text}");
1376            };
1377
1378            shows(5, Some(99), "5");
1379            shows(99, Some(99), "99");
1380            shows(100, Some(99), "99+");
1381            shows(999, None, "999");
1382            shows(1000, None, "999+");
1383            // Test default maxCount (999)
1384            shows(1001, None, "999+");
1385        });
1386    }
1387
1388    #[test]
1389    #[should_panic(expected = "count must be non-negative")]
1390    fn badge_count_asserts_on_negative_count() {
1391        let _ = Badge::count(-1).max_count(999).child(add_icon());
1392    }
1393
1394    #[test]
1395    #[should_panic(expected = "maxCount must be positive")]
1396    fn badge_count_asserts_on_non_positive_max_count() {
1397        let _ = Badge::count(5).max_count(0).child(add_icon());
1398    }
1399
1400    #[test]
1401    fn badge_count_displays_0_when_count_is_zero() {
1402        test_widgets(|tester| {
1403            pump_app(tester, m3, |_app| {
1404                top_left_aligned(Badge::count(0).max_count(5).child(add_icon()))
1405            });
1406            assert_eq!(find::text("0").evaluate(tester).len(), 1);
1407        });
1408    }
1409
1410    /// Dart's `_RenderBadge` fills no properties of its own; it inherits
1411    /// `RenderAligningShiftedBox.debugFillProperties`.
1412    #[test]
1413    fn a_badge_fills_the_properties_it_inherits() {
1414        use waft_foundation::{AppCell, DiagnosticPropertiesBuilder, DiagnosticsNode};
1415
1416        let cell = AppCell::new();
1417        let mut app = cell.borrow_mut();
1418        let badge = RenderBadge::new(
1419            &mut app,
1420            AlignmentGeometry::TOP_LEFT,
1421            0.0,
1422            false,
1423            Offset::ZERO,
1424            Some(TextDirection::Ltr),
1425        );
1426        let mut properties = DiagnosticPropertiesBuilder::new();
1427        RenderObject::debug_fill_properties(badge, &app, &mut properties);
1428        let names: Vec<&str> = properties
1429            .properties
1430            .iter()
1431            .filter_map(|property| property.name())
1432            .collect();
1433        assert_eq!(names, ["alignment", "textDirection"]);
1434    }
1435    /// Every widget names the line of the app's code that made it: a child passed to a setter, a
1436    /// child passed to a constructor, a sliver list built from its builder, and a widget that is
1437    /// its own tree node.
1438    #[test]
1439    fn each_widget_names_the_line_that_made_it() {
1440        let mut tester = WidgetTester::new();
1441        let setter_key = GlobalKey::new();
1442        let constructor_key = GlobalKey::new();
1443        let builder_key = GlobalKey::new();
1444        let tree_node_key = GlobalKey::new();
1445
1446        let setter_line = line!() + 1;
1447        let setter = Material::new().child(SizedBox::new().key(setter_key.clone().into()));
1448        let setter = setter.into_widget();
1449
1450        let constructor_child = SizedBox::new().key(constructor_key.clone().into());
1451        let constructor_line = line!() + 1;
1452        let constructor = DefaultTabController::new(1, constructor_child).into_widget();
1453
1454        let builder = SliverList::builder(|_app, _context, index| {
1455            (index < 1).then(|| SizedBox::new().height(10.0).into_widget())
1456        })
1457        .item_count(1)
1458        .key(builder_key.clone().into());
1459        let builder_line = line!() + 1;
1460        let builder = builder.into_widget();
1461
1462        let tree_node =
1463            LayoutBuilder::new(|_app, _context, _constraints| SizedBox::new().into_widget())
1464                .key(tree_node_key.clone().into());
1465        let tree_node_line = line!() + 1;
1466        let tree_node = tree_node.into_widget();
1467
1468        pump_app(&mut tester, m3, move |_app| {
1469            Directionality::new(
1470                TextDirection::Ltr,
1471                CustomScrollView::new().slivers([
1472                    SliverToBoxAdapter::new().child(setter).into_widget(),
1473                    SliverToBoxAdapter::new().child(constructor).into_widget(),
1474                    builder,
1475                    SliverToBoxAdapter::new().child(tree_node).into_widget(),
1476                ]),
1477            )
1478            .into_widget()
1479        });
1480
1481        for (key, line) in [
1482            (setter_key, setter_line),
1483            (constructor_key, constructor_line),
1484            (builder_key, builder_line),
1485            (tree_node_key, tree_node_line),
1486        ] {
1487            let app = tester.cell.borrow();
1488            let context = key
1489                .current_context(&app)
1490                .expect("the widget is in the tree");
1491            let location = context
1492                .widget(&app)
1493                .creation_location()
1494                .expect("a creation location");
1495            assert_eq!(location.file(), file!());
1496            assert_eq!(location.line(), line);
1497        }
1498    }
1499}