Skip to main content

waft_widgets/widgets/
icon.rs

1//! Flutter counterpart: `widgets/icon.dart`.
2//!
3//! `debugCheckHasDirectionality` waits on diagnostics.
4
5use waft_embedder::{
6    BlendMode, FontVariation, FontWeight, Matrix4, Paint, Shadow, TextDirection,
7    TextLeadingDistribution,
8};
9use waft_foundation::{
10    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty,
11    StringProperty,
12};
13use waft_painting::{
14    AlignmentGeometry, AnyColor, ColorProperty, K_DEFAULT_FONT_SIZE, TextOverflow, TextSpan,
15    TextStyle,
16};
17
18use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
19use crate::widgets::basic::{
20    Center, Directionality, ExcludeSemantics, Semantics, SizedBox, Transform,
21};
22use crate::widgets::icon_data::IconData;
23use crate::widgets::icon_theme::IconTheme;
24use crate::widgets::icon_theme_data::describe_shadows;
25use crate::widgets::media_query::MediaQuery;
26use crate::widgets::text::RichText;
27
28/// A graphical icon widget drawn with a glyph from a font described in
29/// an [`IconData`] such as material's predefined `IconData`s in `Icons`.
30///
31/// Icons are not interactive. For an interactive icon, consider material's
32/// `IconButton`.
33///
34/// There must be an ambient [`Directionality`] widget when using [`Icon`].
35/// Typically this is introduced automatically by the `WidgetsApp` or
36/// `MaterialApp`.
37///
38/// This widget assumes that the rendered icon is squared. Non-squared icons may
39/// render incorrectly.
40///
41/// This example shows how to create a `Row` of [`Icon`]s in different colors and
42/// sizes:
43///
44/// ```text
45/// Row::new().children(vec![
46///     Icon::new(Some(Icons::FAVORITE)).color(PINK).size(24.0).into_widget(),
47///     Icon::new(Some(Icons::AUDIOTRACK)).color(GREEN).size(30.0).into_widget(),
48///     Icon::new(Some(Icons::BEACH_ACCESS)).color(BLUE).size(36.0).into_widget(),
49/// ])
50/// ```
51///
52/// See also:
53///
54///  * `IconButton`, for interactive icons.
55///  * `Icons`, for the list of available Material Icons for use with this class.
56///  * [`IconTheme`], which provides ambient configuration for icons.
57///  * `ImageIcon`, for showing icons from `AssetImage`s or other `ImageProvider`s.
58#[derive(Debug)]
59pub struct Icon {
60    pub key: Option<KeyRef>,
61    /// The icon to display. The available icons are described in `Icons`.
62    ///
63    /// The icon can be `None`, in which case the widget will render as an empty
64    /// space of the specified [`size`](Self::size).
65    pub icon: Option<IconData>,
66    /// The size of the icon in logical pixels.
67    ///
68    /// Icons occupy a square with width and height equal to size.
69    ///
70    /// Defaults to the nearest [`IconTheme`]'s `IconThemeData::size`.
71    ///
72    /// If this [`Icon`] is being placed inside an `IconButton`, then use
73    /// `IconButton.iconSize` instead, so that the `IconButton` can make the splash
74    /// area the appropriate size as well. The `IconButton` uses an [`IconTheme`] to
75    /// pass down the size to the [`Icon`].
76    pub size: Option<f64>,
77    /// The fill for drawing the icon.
78    ///
79    /// Requires the underlying icon font to support the `FILL` [`FontVariation`]
80    /// axis, otherwise has no effect. Variable font filenames often indicate
81    /// the supported axes. Must be between 0.0 (unfilled) and 1.0 (filled),
82    /// inclusive.
83    ///
84    /// Can be used to convey a state transition for animation or interaction.
85    ///
86    /// Defaults to nearest [`IconTheme`]'s `IconThemeData::fill`.
87    ///
88    /// See also:
89    ///  * [`weight`](Self::weight), for controlling stroke weight.
90    ///  * [`grade`](Self::grade), for controlling stroke weight in a more granular way.
91    ///  * [`optical_size`](Self::optical_size), for controlling optical size.
92    pub fill: Option<f64>,
93    /// The stroke weight for drawing the icon.
94    ///
95    /// Requires the underlying icon font to support the `wght` [`FontVariation`]
96    /// axis, otherwise has no effect. Variable font filenames often indicate
97    /// the supported axes. Must be greater than 0.
98    ///
99    /// Defaults to nearest [`IconTheme`]'s `IconThemeData::weight`.
100    ///
101    /// See also:
102    ///  * [`fill`](Self::fill), for controlling fill.
103    ///  * [`grade`](Self::grade), for controlling stroke weight in a more granular way.
104    ///  * [`optical_size`](Self::optical_size), for controlling optical size.
105    pub weight: Option<f64>,
106    /// The grade (granular stroke weight) for drawing the icon.
107    ///
108    /// Requires the underlying icon font to support the `GRAD` [`FontVariation`]
109    /// axis, otherwise has no effect. Variable font filenames often indicate
110    /// the supported axes. Can be negative.
111    ///
112    /// Grade and [`weight`](Self::weight) both affect a symbol's stroke weight
113    /// (thickness), but grade has a smaller impact on the size of the symbol.
114    ///
115    /// Grade is also available in some text fonts. One can match grade levels
116    /// between text and symbols for a harmonious visual effect. For example, if
117    /// the text font has a -25 grade value, the symbols can match it with a
118    /// suitable value, say -25.
119    ///
120    /// Defaults to nearest [`IconTheme`]'s `IconThemeData::grade`.
121    ///
122    /// See also:
123    ///  * [`fill`](Self::fill), for controlling fill.
124    ///  * [`weight`](Self::weight), for controlling stroke weight in a less granular way.
125    ///  * [`optical_size`](Self::optical_size), for controlling optical size.
126    pub grade: Option<f64>,
127    /// The optical size for drawing the icon.
128    ///
129    /// Requires the underlying icon font to support the `opsz` [`FontVariation`]
130    /// axis, otherwise has no effect. Variable font filenames often indicate
131    /// the supported axes. Must be greater than 0.
132    ///
133    /// For an icon to look the same at different sizes, the stroke weight
134    /// (thickness) must change as the icon size scales. Optical size offers a way
135    /// to automatically adjust the stroke weight as icon size changes.
136    ///
137    /// Defaults to nearest [`IconTheme`]'s `IconThemeData::optical_size`.
138    ///
139    /// See also:
140    ///  * [`fill`](Self::fill), for controlling fill.
141    ///  * [`weight`](Self::weight), for controlling stroke weight.
142    ///  * [`grade`](Self::grade), for controlling stroke weight in a more granular way.
143    pub optical_size: Option<f64>,
144    /// The color to use when drawing the icon.
145    ///
146    /// Defaults to the nearest [`IconTheme`]'s `IconThemeData::color`.
147    ///
148    /// The color (whether specified explicitly here or obtained from the
149    /// [`IconTheme`]) will be further adjusted by the nearest [`IconTheme`]'s
150    /// `IconThemeData::opacity`.
151    pub color: Option<AnyColor>,
152    /// A list of [`Shadow`]s that will be painted underneath the icon.
153    ///
154    /// Multiple shadows are supported to replicate lighting from multiple light
155    /// sources.
156    ///
157    /// Shadows must be in the same order for [`Icon`] to be considered as
158    /// equivalent as order produces differing transparency.
159    ///
160    /// Defaults to the nearest [`IconTheme`]'s `IconThemeData::shadows`.
161    pub shadows: Option<Vec<Shadow>>,
162    /// Semantic label for the icon.
163    ///
164    /// Announced by assistive technologies (e.g TalkBack/VoiceOver).
165    /// This label does not show in the UI.
166    ///
167    ///  * [`SemanticsProperties::label`](waft_rendering::SemanticsProperties::label), which is
168    ///    set to [`semantic_label`](Self::semantic_label) in the underlying [`Semantics`]
169    ///    widget.
170    pub semantic_label: Option<String>,
171    /// The text direction to use for rendering the icon.
172    ///
173    /// If this is `None`, the ambient [`Directionality`] is used instead.
174    ///
175    /// Some icons follow the reading direction. For example, "back" buttons point
176    /// left in left-to-right environments and right in right-to-left
177    /// environments. Such icons have their [`IconData::match_text_direction`] field
178    /// set to true, and the [`Icon`] widget uses the
179    /// [`text_direction`](Self::text_direction) to determine the orientation in which to draw
180    /// the icon.
181    ///
182    /// This property has no effect if the [`icon`](Self::icon)'s
183    /// [`IconData::match_text_direction`] field is false, but for consistency a text direction
184    /// value must always be specified, either directly using this property or using
185    /// [`Directionality`].
186    pub text_direction: Option<TextDirection>,
187    /// Whether to scale the size of this widget using the ambient [`MediaQuery`]'s
188    /// `TextScaler`.
189    ///
190    /// This is specially useful when you have an icon associated with a text, as
191    /// scaling the text without scaling the icon would result in a confusing
192    /// interface.
193    ///
194    /// Defaults to the nearest [`IconTheme`]'s `IconThemeData::apply_text_scaling`.
195    pub apply_text_scaling: Option<bool>,
196    /// The [`BlendMode`] to apply to the foreground of the icon.
197    ///
198    /// Defaults to [`BlendMode::SrcOver`].
199    pub blend_mode: Option<BlendMode>,
200    /// The typeface thickness to use when painting the text (e.g., bold).
201    pub font_weight: Option<FontWeight>,
202}
203
204impl Icon {
205    /// Creates an icon; Dart's optional named arguments are the setters.
206    pub fn new(icon: Option<IconData>) -> Icon {
207        Icon {
208            key: None,
209            icon,
210            size: None,
211            fill: None,
212            weight: None,
213            grade: None,
214            optical_size: None,
215            color: None,
216            shadows: None,
217            semantic_label: None,
218            text_direction: None,
219            apply_text_scaling: None,
220            blend_mode: None,
221            font_weight: None,
222        }
223    }
224
225    /// Dart `Icon(key:)`.
226    pub fn key(mut self, key: KeyRef) -> Icon {
227        self.key = Some(key);
228        self
229    }
230
231    /// Dart `Icon(size:)`.
232    pub fn size(mut self, size: f64) -> Icon {
233        self.size = Some(size);
234        self
235    }
236
237    /// Dart `Icon(fill:)`; must be between 0.0 and 1.0, inclusive.
238    pub fn fill(mut self, fill: f64) -> Icon {
239        debug_assert!((0.0..=1.0).contains(&fill));
240        self.fill = Some(fill);
241        self
242    }
243
244    /// Dart `Icon(weight:)`; must be greater than 0.
245    pub fn weight(mut self, weight: f64) -> Icon {
246        debug_assert!(weight > 0.0);
247        self.weight = Some(weight);
248        self
249    }
250
251    /// Dart `Icon(grade:)`.
252    pub fn grade(mut self, grade: f64) -> Icon {
253        self.grade = Some(grade);
254        self
255    }
256
257    /// Dart `Icon(opticalSize:)`; must be greater than 0.
258    pub fn optical_size(mut self, optical_size: f64) -> Icon {
259        debug_assert!(optical_size > 0.0);
260        self.optical_size = Some(optical_size);
261        self
262    }
263
264    /// Dart `Icon(color:)`.
265    pub fn color(mut self, color: impl Into<AnyColor>) -> Icon {
266        self.color = Some(color.into());
267        self
268    }
269
270    /// Dart `Icon(shadows:)`.
271    pub fn shadows(mut self, shadows: Vec<Shadow>) -> Icon {
272        self.shadows = Some(shadows);
273        self
274    }
275
276    /// Dart `Icon(semanticLabel:)`.
277    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> Icon {
278        self.semantic_label = Some(semantic_label.into());
279        self
280    }
281
282    /// Dart's `Semantics(label: semanticLabel)` around what the icon builds.
283    fn semantics(&self) -> Semantics {
284        let semantics = Semantics::new();
285        match &self.semantic_label {
286            Some(semantic_label) => semantics.label(semantic_label.clone()),
287            None => semantics,
288        }
289    }
290
291    /// Dart `Icon(textDirection:)`.
292    pub fn text_direction(mut self, text_direction: TextDirection) -> Icon {
293        self.text_direction = Some(text_direction);
294        self
295    }
296
297    /// Dart `Icon(applyTextScaling:)`.
298    pub fn apply_text_scaling(mut self, apply_text_scaling: bool) -> Icon {
299        self.apply_text_scaling = Some(apply_text_scaling);
300        self
301    }
302
303    /// Dart `Icon(blendMode:)`.
304    pub fn blend_mode(mut self, blend_mode: BlendMode) -> Icon {
305        self.blend_mode = Some(blend_mode);
306        self
307    }
308
309    /// Dart `Icon(fontWeight:)`.
310    pub fn font_weight(mut self, font_weight: FontWeight) -> Icon {
311        self.font_weight = Some(font_weight);
312        self
313    }
314
315    /// The glyph's `TextStyle`: the variable-font axes, the resolved color or foreground
316    /// paint, and the metrics that centre the body in the icon's square.
317    fn font_style(&self, icon: &IconData, resolved: ResolvedIcon) -> TextStyle {
318        let axes = [
319            ("FILL", resolved.fill),
320            ("wght", resolved.weight),
321            ("GRAD", resolved.grade),
322            ("opsz", resolved.optical_size),
323        ];
324        let font_variations = axes
325            .into_iter()
326            .filter_map(|(axis, value)| value.map(|value| FontVariation::new(axis, value)))
327            .collect();
328        let mut style = TextStyle::new()
329            .font_variations(font_variations)
330            .inherit(false)
331            .font_size(resolved.size)
332            // Makes sure the font's body is vertically centered within the
333            // size x size square.
334            .height(1.0)
335            .leading_distribution(TextLeadingDistribution::Even);
336        if let Some(color) = resolved.color {
337            style = style.color(color);
338        }
339        if let Some(font_family) = &icon.font_family {
340            style = style.font_family(font_family.clone());
341        }
342        if let Some(font_weight) = self.font_weight {
343            style = style.font_weight(font_weight);
344        }
345        if let Some(font_package) = &icon.font_package {
346            style = style.package(font_package.clone());
347        }
348        if let Some(font_family_fallback) = &icon.font_family_fallback {
349            style = style.font_family_fallback(font_family_fallback.clone());
350        }
351        if let Some(shadows) = resolved.shadows {
352            style = style.shadows(shadows);
353        }
354        if let Some(foreground) = resolved.foreground {
355            style = style.foreground(foreground);
356        }
357        style
358    }
359}
360
361/// What `Icon.build` resolves from the widget and the ambient [`IconTheme`] before it
362/// composes the glyph's [`TextStyle`]. Dart's locals, grouped so they travel together.
363struct ResolvedIcon {
364    size: f64,
365    fill: Option<f64>,
366    weight: Option<f64>,
367    grade: Option<f64>,
368    optical_size: Option<f64>,
369    shadows: Option<Vec<Shadow>>,
370    color: Option<AnyColor>,
371    foreground: Option<Paint>,
372}
373
374/// Dart's `Widget.==`, which is identity: an `Icon` equals only itself, so an `Rc<Icon>`
375/// compares as the Dart reference does.
376impl PartialEq for Icon {
377    fn eq(&self, other: &Icon) -> bool {
378        std::ptr::eq(self, other)
379    }
380}
381
382impl StatelessWidget for Icon {
383    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
384        properties.add(
385            DiagnosticsProperty::<String>::new(
386                "icon",
387                self.icon.as_ref().map(|icon| format!("{icon:?}")),
388            )
389            .if_null("<empty>")
390            .with_show_name(false),
391        );
392        properties.add(DoubleProperty::new("size", self.size).default_value(None));
393        properties.add(DoubleProperty::new("fill", self.fill).default_value(None));
394        properties.add(DoubleProperty::new("weight", self.weight).default_value(None));
395        properties.add(DoubleProperty::new("grade", self.grade).default_value(None));
396        properties.add(DoubleProperty::new("opticalSize", self.optical_size).default_value(None));
397        properties.add(
398            ColorProperty::new("color", self.color.as_ref().map(|color| color.color()))
399                .default_value(None),
400        );
401        properties.add(
402            DiagnosticsProperty::<String>::new(
403                "shadows",
404                self.shadows.as_deref().map(describe_shadows),
405            )
406            .default_value(None),
407        );
408        properties.add(
409            StringProperty::new("semanticLabel", self.semantic_label.clone()).default_value(None),
410        );
411        properties.add(
412            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
413                .default_value(None),
414        );
415        properties.add(
416            DiagnosticsProperty::<bool>::new("applyTextScaling", self.apply_text_scaling)
417                .default_value(None),
418        );
419    }
420
421    fn key(&self) -> Option<&KeyRef> {
422        self.key.as_ref()
423    }
424
425    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
426        let text_direction = self
427            .text_direction
428            .unwrap_or_else(|| Directionality::of(app, context));
429
430        let icon_theme = IconTheme::of(app, context);
431
432        let apply_text_scaling = self
433            .apply_text_scaling
434            .or(icon_theme.apply_text_scaling)
435            .unwrap_or(false);
436
437        let tentative_icon_size = self.size.or(icon_theme.size).unwrap_or(K_DEFAULT_FONT_SIZE);
438
439        let icon_size = if apply_text_scaling {
440            MediaQuery::text_scaler_of(app, context).scale(tentative_icon_size)
441        } else {
442            tentative_icon_size
443        };
444
445        let icon_fill = self.fill.or(icon_theme.fill);
446        let icon_weight = self.weight.or(icon_theme.weight);
447        let icon_grade = self.grade.or(icon_theme.grade);
448        let icon_optical_size = self.optical_size.or(icon_theme.optical_size);
449        let icon_shadows = self.shadows.clone().or(icon_theme.shadows.clone());
450
451        let Some(icon) = &self.icon else {
452            return self
453                .semantics()
454                .child(SizedBox::new().width(icon_size).height(icon_size))
455                .into_widget();
456        };
457
458        let icon_opacity = icon_theme.opacity.unwrap_or(1.0);
459        let mut icon_color = Some(self.color.clone().unwrap_or_else(|| {
460            icon_theme
461                .color
462                .clone()
463                .expect("IconTheme::of returns a concrete theme")
464        }));
465        let mut foreground = None;
466        if icon_opacity != 1.0 {
467            let color = icon_color.as_ref().expect("the color is resolved above");
468            // Dart's `withOpacity`, deprecated there too: its rounding to an 8-bit alpha is
469            // part of the behaviour being ported.
470            #[allow(deprecated)]
471            let faded = color.with_opacity(color.opacity() * icon_opacity);
472            icon_color = Some(faded.into());
473        }
474        if let Some(blend_mode) = self.blend_mode {
475            foreground = Some(Paint {
476                blend_mode,
477                color: icon_color
478                    .as_ref()
479                    .expect("the color is resolved above")
480                    .color()
481                    .into(),
482                ..Paint::default()
483            });
484            // Cannot provide both a color and a foreground.
485            icon_color = None;
486        }
487
488        let font_style = self.font_style(
489            icon,
490            ResolvedIcon {
491                size: icon_size,
492                fill: icon_fill,
493                weight: icon_weight,
494                grade: icon_grade,
495                optical_size: icon_optical_size,
496                shadows: icon_shadows,
497                color: icon_color,
498                foreground,
499            },
500        );
501
502        let code_point = char::from_u32(icon.code_point)
503            .expect("an IconData code point is a Unicode scalar value");
504        let mut icon_widget = RichText::new(
505            TextSpan::new()
506                .text(code_point.to_string())
507                .style(font_style)
508                .into_span(),
509        )
510        // Never clip.
511        .overflow(TextOverflow::Visible)
512        // Since we already fetched it for the assert...
513        .text_direction(text_direction)
514        .into_widget();
515
516        if icon.match_text_direction {
517            match text_direction {
518                TextDirection::Rtl => {
519                    icon_widget = Transform::new(Matrix4::scale(-1.0, 1.0))
520                        .alignment(AlignmentGeometry::CENTER)
521                        .transform_hit_tests(false)
522                        .child(icon_widget)
523                        .into_widget();
524                }
525                TextDirection::Ltr => {}
526            }
527        }
528
529        self.semantics()
530            .child(
531                ExcludeSemantics::new().child(
532                    SizedBox::new()
533                        .width(icon_size)
534                        .height(icon_size)
535                        .child(Center::new().child(icon_widget)),
536                ),
537            )
538            .into_widget()
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use waft_embedder::Color;
545    use waft_embedder::Size;
546    use waft_foundation::AppCell;
547    use waft_painting::{PaintingBinding, TextScaler};
548    use waft_rendering::{
549        AnyRenderBox, BoxConstraints, RenderBox, RenderConstrainedBox, RenderConstrainedBoxBase,
550        RenderExcludeSemantics, RenderHandle, RenderObject, RenderObjectWithChildMixin,
551        RenderParagraph, RenderPositionedBox, RenderSemanticsAnnotations, RenderTransform,
552        SemanticsAnnotationsMixin,
553    };
554
555    use super::*;
556    use crate::test_harness::Harness;
557    use crate::widgets::icon_theme_data::IconThemeData;
558    use crate::widgets::media_query::{MediaQuery, MediaQueryData};
559
560    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
561    fn install_fonts(app: &mut App) {
562        let binding = PaintingBinding::instance(app);
563        if !binding.has_fonts(app) {
564            binding.install_fonts(app, |fonts| {
565                fonts.add_source(valo_system_fonts::SystemFonts::load());
566            });
567        }
568    }
569
570    fn glyph() -> IconData {
571        IconData::new(0xe900)
572            .font_family("TestIcons")
573            .font_package("test_icons")
574    }
575
576    fn typed_child<P, C: RenderObject>(parent: RenderHandle<P>, app: &App) -> RenderHandle<C>
577    where
578        P: RenderObject + RenderObjectWithChildMixin<ChildType = AnyRenderBox>,
579    {
580        parent
581            .child(app)
582            .expect("a child")
583            .as_object()
584            .downcast::<C>(app)
585            .expect("the expected render object")
586    }
587
588    /// The `Semantics` under the root: what an `Icon` builds around everything else.
589    fn semantics_under_root(
590        harness: &Harness,
591        app: &App,
592    ) -> RenderHandle<RenderSemanticsAnnotations> {
593        harness
594            .render_root(app)
595            .child(app)
596            .expect("a child")
597            .as_object()
598            .downcast::<RenderSemanticsAnnotations>(app)
599            .expect("Icon builds a Semantics")
600    }
601
602    /// The square inside the icon's `Semantics`, and its `ExcludeSemantics` when it has a glyph.
603    fn square_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderConstrainedBox> {
604        let semantics = semantics_under_root(harness, app);
605        let child = semantics.child(app).expect("a child").as_object();
606        match child.downcast::<RenderExcludeSemantics>(app) {
607            Some(exclude) => typed_child(exclude, app),
608            None => child
609                .downcast::<RenderConstrainedBox>(app)
610                .expect("Icon builds a SizedBox"),
611        }
612    }
613
614    /// Mounts `icon` under an ambient `Directionality` and `IconTheme`, and pumps a frame.
615    fn mount(
616        app: &mut App,
617        text_direction: TextDirection,
618        theme: IconThemeData,
619        icon: Icon,
620    ) -> Harness {
621        install_fonts(app);
622        let harness = Harness::mount(
623            app,
624            Directionality::new(text_direction, IconTheme::new(theme, icon)).into_widget(),
625        );
626        harness.pump(app);
627        harness
628    }
629
630    #[test]
631    fn an_icon_builds_a_centred_glyph_in_a_square_of_its_size() {
632        let cell = AppCell::new();
633        let mut app = cell.borrow_mut();
634        let theme = IconThemeData::fallback().color(Color::from_argb(255, 255, 0, 0));
635        let harness = mount(
636            &mut app,
637            TextDirection::Ltr,
638            theme,
639            Icon::new(Some(glyph())).size(30.0),
640        );
641
642        let square = square_under_root(&harness, &app);
643        assert_eq!(
644            square.additional_constraints(&app),
645            BoxConstraints::tight_for(Some(30.0), Some(30.0))
646        );
647        assert_eq!(square.size(&app), Size::new(30.0, 30.0));
648
649        let center = typed_child::<_, RenderPositionedBox>(square, &app);
650        let paragraph = typed_child::<_, RenderParagraph>(center, &app);
651        assert_eq!(
652            paragraph.text(&app).to_plain_text(true, true),
653            "\u{e900}",
654            "the code point is the glyph's text"
655        );
656        let style = paragraph
657            .text(&app)
658            .style()
659            .cloned()
660            .expect("Icon always styles its span");
661        assert!(!style.inherit);
662        assert_eq!(style.font_size, Some(30.0));
663        assert_eq!(style.height, Some(1.0));
664        assert_eq!(
665            style.font_family.as_deref(),
666            Some("packages/test_icons/TestIcons"),
667            "the icon's font package prefixes its family"
668        );
669        assert_eq!(
670            style.color.as_ref().map(AnyColor::color),
671            Some(Color::from_argb(255, 255, 0, 0)),
672            "the ambient IconTheme's color"
673        );
674        assert_eq!(style.font_variations.as_deref().map(<[_]>::len), Some(4));
675        assert!(style.foreground.is_none());
676    }
677
678    #[test]
679    fn an_icon_defaults_its_size_and_axes_to_the_ambient_theme() {
680        let cell = AppCell::new();
681        let mut app = cell.borrow_mut();
682        let theme = IconThemeData::fallback().size(18.0).weight(700.0);
683        let harness = mount(
684            &mut app,
685            TextDirection::Ltr,
686            theme,
687            Icon::new(Some(glyph())),
688        );
689        let square = square_under_root(&harness, &app);
690        assert_eq!(square.size(&app), Size::new(18.0, 18.0));
691
692        let center = typed_child::<_, RenderPositionedBox>(square, &app);
693        let paragraph = typed_child::<_, RenderParagraph>(center, &app);
694        let style = paragraph
695            .text(&app)
696            .style()
697            .cloned()
698            .expect("Icon always styles its span");
699        assert_eq!(style.font_size, Some(18.0));
700        let weight = style
701            .font_variations
702            .as_ref()
703            .expect("the axes are always written")
704            .iter()
705            .find(|variation| variation.axis == "wght")
706            .expect("the theme's weight");
707        assert_eq!(weight.value, 700.0);
708    }
709
710    // icon_test.dart: 'Icon with semantic label', as the annotation keeps it.
711    #[test]
712    fn an_icon_labels_its_semantics_and_excludes_its_glyph() {
713        let cell = AppCell::new();
714        let mut app = cell.borrow_mut();
715        let harness = mount(
716            &mut app,
717            TextDirection::Ltr,
718            IconThemeData::fallback(),
719            Icon::new(Some(glyph())).semantic_label("a label"),
720        );
721        let semantics = semantics_under_root(&harness, &app);
722        assert_eq!(semantics.properties(&app).label.as_deref(), Some("a label"));
723        let exclude = semantics
724            .child(&app)
725            .expect("a child")
726            .as_object()
727            .downcast::<RenderExcludeSemantics>(&app)
728            .expect("the glyph sits in an ExcludeSemantics");
729        assert!(exclude.excluding(&app));
730    }
731
732    // icon_test.dart: 'Null icon with semantic label', as the annotation keeps it.
733    #[test]
734    fn an_icon_without_an_icon_data_still_labels_its_semantics() {
735        let cell = AppCell::new();
736        let mut app = cell.borrow_mut();
737        let harness = mount(
738            &mut app,
739            TextDirection::Ltr,
740            IconThemeData::fallback(),
741            Icon::new(None).semantic_label("a label"),
742        );
743        let semantics = semantics_under_root(&harness, &app);
744        assert_eq!(semantics.properties(&app).label.as_deref(), Some("a label"));
745        assert!(
746            semantics
747                .child(&app)
748                .expect("a child")
749                .as_object()
750                .downcast::<RenderConstrainedBox>(&app)
751                .is_some(),
752            "no ExcludeSemantics without a glyph"
753        );
754    }
755
756    #[test]
757    fn an_icon_without_an_icon_data_is_an_empty_square() {
758        let cell = AppCell::new();
759        let mut app = cell.borrow_mut();
760        let harness = mount(
761            &mut app,
762            TextDirection::Ltr,
763            IconThemeData::fallback(),
764            Icon::new(None).size(42.0),
765        );
766        let square = square_under_root(&harness, &app);
767        assert_eq!(square.size(&app), Size::new(42.0, 42.0));
768        assert!(square.child(&app).is_none(), "no glyph is built");
769    }
770
771    #[test]
772    fn a_direction_matching_icon_is_mirrored_in_rtl() {
773        let cell = AppCell::new();
774        let mut app = cell.borrow_mut();
775        let mirrored = glyph().match_text_direction(true);
776        let cell_ltr = AppCell::new();
777        let mut app_ltr = cell_ltr.borrow_mut();
778        let ltr = mount(
779            &mut app_ltr,
780            TextDirection::Ltr,
781            IconThemeData::fallback(),
782            Icon::new(Some(mirrored.clone())),
783        );
784        let square = square_under_root(&ltr, &app_ltr);
785        let center = typed_child::<_, RenderPositionedBox>(square, &app_ltr);
786        assert!(
787            center
788                .child(&app_ltr)
789                .expect("a child")
790                .as_object()
791                .downcast::<RenderParagraph>(&app_ltr)
792                .is_some(),
793            "no transform in left-to-right"
794        );
795
796        let rtl = mount(
797            &mut app,
798            TextDirection::Rtl,
799            IconThemeData::fallback(),
800            Icon::new(Some(mirrored)),
801        );
802        let square = square_under_root(&rtl, &app);
803        let center = typed_child::<_, RenderPositionedBox>(square, &app);
804        let transform = typed_child::<_, RenderTransform>(center, &app);
805        assert!(!transform.transform_hit_tests(&app));
806        assert_eq!(transform.alignment(&app), Some(AlignmentGeometry::CENTER));
807        typed_child::<_, RenderParagraph>(transform, &app);
808    }
809
810    #[test]
811    fn apply_text_scaling_scales_the_square_with_the_media_query() {
812        let cell = AppCell::new();
813        let mut app = cell.borrow_mut();
814        install_fonts(&mut app);
815        let media = MediaQueryData::new().text_scaler(TextScaler::linear(2.0));
816        let harness = Harness::mount(
817            &mut app,
818            Directionality::new(
819                TextDirection::Ltr,
820                MediaQuery::new(
821                    media,
822                    IconTheme::new(
823                        IconThemeData::fallback().size(10.0),
824                        Icon::new(Some(glyph())).apply_text_scaling(true),
825                    ),
826                )
827                .into_widget(),
828            )
829            .into_widget(),
830        );
831        harness.pump(&mut app);
832        let square = square_under_root(&harness, &app);
833        assert_eq!(
834            square.size(&app),
835            Size::new(20.0, 20.0),
836            "the text scaler doubles the icon's size"
837        );
838    }
839
840    #[test]
841    fn a_blend_mode_moves_the_color_into_a_foreground_paint() {
842        let cell = AppCell::new();
843        let mut app = cell.borrow_mut();
844        let theme = IconThemeData::fallback().color(Color::from_argb(255, 0, 0, 255));
845        let harness = mount(
846            &mut app,
847            TextDirection::Ltr,
848            theme,
849            Icon::new(Some(glyph())).blend_mode(BlendMode::Multiply),
850        );
851        let square = square_under_root(&harness, &app);
852        let center = typed_child::<_, RenderPositionedBox>(square, &app);
853        let paragraph = typed_child::<_, RenderParagraph>(center, &app);
854        let style = paragraph
855            .text(&app)
856            .style()
857            .cloned()
858            .expect("Icon always styles its span");
859        assert!(
860            style.color.is_none(),
861            "a color and a foreground are exclusive"
862        );
863        let foreground = style.foreground.expect("the blend mode makes a paint");
864        assert_eq!(foreground.blend_mode, BlendMode::Multiply);
865        assert_eq!(foreground.color, Color::from_argb(255, 0, 0, 255).into());
866    }
867
868    #[test]
869    fn the_theme_s_opacity_fades_the_glyph_color() {
870        let cell = AppCell::new();
871        let mut app = cell.borrow_mut();
872        let theme = IconThemeData::fallback()
873            .color(Color::from_argb(255, 0, 0, 255))
874            .opacity(0.5);
875        let harness = mount(
876            &mut app,
877            TextDirection::Ltr,
878            theme,
879            Icon::new(Some(glyph())),
880        );
881        let square = square_under_root(&harness, &app);
882        let center = typed_child::<_, RenderPositionedBox>(square, &app);
883        let paragraph = typed_child::<_, RenderParagraph>(center, &app);
884        let style = paragraph
885            .text(&app)
886            .style()
887            .cloned()
888            .expect("Icon always styles its span");
889        assert_eq!(
890            style.color.as_ref().map(AnyColor::color),
891            Some(Color::from_argb(128, 0, 0, 255))
892        );
893    }
894}