Skip to main content

waft_material/
tab_indicator.rs

1//! Flutter counterpart: material_ui's `tab_indicator.dart`.
2
3use std::any::Any;
4use std::fmt;
5
6use waft_embedder::{
7    Canvas, Offset, Paint, PaintStyle, Path, PathBuilder, RRect, Rect, StrokeCap,
8    rrect_radii_elliptical,
9};
10use waft_foundation::{App, VoidCallback};
11use waft_painting::{
12    BorderRadius, BorderSide, BorderStyle, BoxPainter, Decoration, DecorationRef,
13    EdgeInsetsGeometry, ImageConfiguration, TextDirection, draw_line, draw_rrect,
14};
15
16use crate::colors::Colors;
17
18/// Used with `TabBar::indicator` to draw a horizontal line below the
19/// selected tab.
20///
21/// The selected tab underline is inset from the tab's boundary by [`insets`](Self::insets).
22/// The [`border_side`](Self::border_side) defines the line's color and weight.
23///
24/// The `TabBar::indicator_size` property can be used to define the indicator's
25/// bounds in terms of its (centered) widget with `TabBarIndicatorSize::Label`,
26/// or the entire tab with `TabBarIndicatorSize::Tab`.
27#[derive(Clone)]
28pub struct UnderlineTabIndicator {
29    /// The radius of the indicator's corners.
30    ///
31    /// If this value is non-null, rounded rectangular tab indicator is
32    /// drawn, otherwise rectangular tab indicator is drawn.
33    pub border_radius: Option<BorderRadius>,
34
35    /// The color and weight of the horizontal line drawn below the selected tab.
36    pub border_side: BorderSide,
37
38    /// Locates the selected tab's underline relative to the tab's boundary.
39    ///
40    /// The `TabBar::indicator_size` property can be used to define the tab
41    /// indicator's bounds in terms of its (centered) tab widget with
42    /// `TabBarIndicatorSize::Label`, or the entire tab with
43    /// `TabBarIndicatorSize::Tab`.
44    pub insets: EdgeInsetsGeometry,
45}
46
47impl Default for UnderlineTabIndicator {
48    fn default() -> UnderlineTabIndicator {
49        UnderlineTabIndicator {
50            border_radius: None,
51            border_side: BorderSide::new(
52                Colors::WHITE,
53                2.0,
54                BorderStyle::Solid,
55                BorderSide::STROKE_ALIGN_INSIDE,
56            ),
57            insets: EdgeInsetsGeometry::ZERO,
58        }
59    }
60}
61
62impl UnderlineTabIndicator {
63    /// Create an underline style selected tab indicator; Dart's named arguments are the
64    /// setters.
65    pub fn new() -> UnderlineTabIndicator {
66        UnderlineTabIndicator::default()
67    }
68
69    /// Dart `UnderlineTabIndicator(borderRadius:)`.
70    pub fn border_radius(mut self, border_radius: BorderRadius) -> UnderlineTabIndicator {
71        self.border_radius = Some(border_radius);
72        self
73    }
74
75    /// Dart `UnderlineTabIndicator(borderSide:)`.
76    pub fn border_side(mut self, border_side: BorderSide) -> UnderlineTabIndicator {
77        self.border_side = border_side;
78        self
79    }
80
81    /// Dart `UnderlineTabIndicator(insets:)`.
82    pub fn insets(mut self, insets: impl Into<EdgeInsetsGeometry>) -> UnderlineTabIndicator {
83        self.insets = insets.into();
84        self
85    }
86
87    fn indicator_rect_for(&self, rect: Rect, text_direction: TextDirection) -> Rect {
88        let indicator = self.insets.resolve(Some(text_direction)).deflate_rect(rect);
89        Rect::from_ltwh(
90            indicator.left,
91            indicator.bottom - self.border_side.width,
92            indicator.width(),
93            self.border_side.width,
94        )
95    }
96}
97
98impl Decoration for UnderlineTabIndicator {
99    fn lerp_from(&self, a: Option<&dyn Decoration>, t: f64) -> Option<DecorationRef> {
100        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<UnderlineTabIndicator>()) {
101            return Some(DecorationRef::new(
102                UnderlineTabIndicator::new()
103                    .border_side(BorderSide::lerp(a.border_side, self.border_side, t))
104                    .insets(
105                        EdgeInsetsGeometry::lerp(Some(a.insets), Some(self.insets), t)
106                            .expect("two insets lerp to insets"),
107                    ),
108            ));
109        }
110        None
111    }
112
113    fn lerp_to(&self, b: Option<&dyn Decoration>, t: f64) -> Option<DecorationRef> {
114        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<UnderlineTabIndicator>()) {
115            return Some(DecorationRef::new(
116                UnderlineTabIndicator::new()
117                    .border_side(BorderSide::lerp(self.border_side, b.border_side, t))
118                    .insets(
119                        EdgeInsetsGeometry::lerp(Some(self.insets), Some(b.insets), t)
120                            .expect("two insets lerp to insets"),
121                    ),
122            ));
123        }
124        None
125    }
126
127    fn create_box_painter(&self, on_changed: Option<VoidCallback>) -> Box<dyn BoxPainter> {
128        Box::new(UnderlinePainter::new(
129            self.clone(),
130            self.border_radius,
131            on_changed,
132        ))
133    }
134
135    fn get_clip_path(&self, rect: Rect, text_direction: TextDirection) -> Path {
136        let indicator = self.indicator_rect_for(rect, text_direction);
137        let mut path = PathBuilder::new();
138        if let Some(border_radius) = self.border_radius {
139            let rrect = border_radius.to_rrect(indicator);
140            path.rrect_radii_elliptical(rrect.outer_rect(), rrect_radii_elliptical(rrect));
141            return path.build().into();
142        }
143        path.rect(indicator.into());
144        path.build().into()
145    }
146
147    fn as_any(&self) -> &dyn Any {
148        self
149    }
150}
151
152impl fmt::Debug for UnderlineTabIndicator {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.debug_struct("UnderlineTabIndicator")
155            .field("border_radius", &self.border_radius)
156            .field("border_side", &self.border_side)
157            .field("insets", &self.insets)
158            .finish()
159    }
160}
161
162/// Dart's `_UnderlinePainter`.
163struct UnderlinePainter {
164    decoration: UnderlineTabIndicator,
165    border_radius: Option<BorderRadius>,
166    on_changed: Option<VoidCallback>,
167}
168
169impl UnderlinePainter {
170    fn new(
171        decoration: UnderlineTabIndicator,
172        border_radius: Option<BorderRadius>,
173        on_changed: Option<VoidCallback>,
174    ) -> UnderlinePainter {
175        UnderlinePainter {
176            decoration,
177            border_radius,
178            on_changed,
179        }
180    }
181}
182
183impl BoxPainter for UnderlinePainter {
184    fn paint(&mut self, canvas: &mut Canvas, offset: Offset, configuration: &ImageConfiguration) {
185        debug_assert!(configuration.size.is_some());
186        let rect = offset & configuration.size.expect("asserted above");
187        let text_direction = configuration
188            .text_direction
189            .expect("an indicator is painted with a text direction");
190        if let Some(border_radius) = self.border_radius {
191            let paint = Paint::from_color(self.decoration.border_side.color.into());
192            let indicator = self.decoration.indicator_rect_for(rect, text_direction);
193            let rrect = RRect::from_rect_and_corners(
194                indicator,
195                border_radius.top_left,
196                border_radius.top_right,
197                border_radius.bottom_right,
198                border_radius.bottom_left,
199            );
200            draw_rrect(canvas, rrect, &paint);
201        } else {
202            let mut paint = self.decoration.border_side.to_paint();
203            if let PaintStyle::Stroke(stroke) = &mut paint.style {
204                stroke.cap = StrokeCap::Square;
205            }
206            let indicator = self
207                .decoration
208                .indicator_rect_for(rect, text_direction)
209                .deflate(self.decoration.border_side.width / 2.0);
210            draw_line(
211                canvas,
212                indicator.bottom_left(),
213                indicator.bottom_right(),
214                &paint,
215            );
216        }
217    }
218
219    fn on_changed(&self) -> Option<&dyn Fn(&mut App)> {
220        self.on_changed.as_deref()
221    }
222}