Skip to main content

waft_material/
time_picker_theme.rs

1//! Flutter counterpart: material_ui's `time_picker_theme.dart`.
2
3use waft_embedder::{Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{
6    AnyColor, AnyTextStyle, BorderSide, EdgeInsetsGeometry, OutlinedBorderRef, ShapeBorderRef,
7    TextStyle,
8};
9use waft_widgets::{
10    BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef, WidgetState,
11    WidgetStateColor, WidgetStateProperty, WidgetStatePropertyRef,
12};
13
14use crate::button_style::ButtonStyle;
15use crate::colors::Colors;
16use crate::input_decorator::InputDecorationThemeData;
17use crate::theme::Theme;
18
19/// Defines the visual properties of the widget displayed with `showTimePicker`.
20///
21/// Descendant widgets obtain the current [`TimePickerThemeData`] object using
22/// [`TimePickerTheme::of`]. Instances of [`TimePickerThemeData`] can be customized with
23/// [`TimePickerThemeData::copy_with`].
24///
25/// Typically a [`TimePickerThemeData`] is specified as part of the overall `Theme` with
26/// `ThemeData::time_picker_theme`.
27///
28/// All [`TimePickerThemeData`] properties are `None` by default. When null, the time picker
29/// provides its own defaults based on the overall `Theme`'s `ThemeData::color_scheme`,
30/// `ThemeData::text_theme`, and `ThemeData::icon_theme`.
31///
32/// See also:
33///
34///  * [`TimePickerTheme`], which describes the actual configuration of a time picker theme.
35///  * `ThemeData`, which describes the overall theme information for the application.
36#[derive(Clone, Debug, Default)]
37pub struct TimePickerThemeData {
38    /// The background color of a time picker.
39    ///
40    /// If this is null, the time picker defaults to the overall theme's
41    /// `ColorScheme::surface_container_high`.
42    pub background_color: Option<AnyColor>,
43
44    /// Style of the cancel button of a time picker.
45    ///
46    /// If this is null, the time picker defaults to a `TextButton` styled with the theme's
47    /// primary color.
48    pub cancel_button_style: Option<ButtonStyle>,
49
50    /// Style of the confirm (OK) button of a time picker.
51    ///
52    /// If this is null, the time picker defaults to a `TextButton` styled with the theme's
53    /// primary color.
54    pub confirm_button_style: Option<ButtonStyle>,
55
56    /// The color and weight of the day period's outline.
57    ///
58    /// If this is null, the time picker defaults to
59    /// `BorderSide(color: Color(0xFF79747E))`.
60    pub day_period_border_side: Option<BorderSide>,
61
62    /// Dart's private `_dayPeriodColor`: the color as it was given, before
63    /// [`day_period_color_getter`](Self::day_period_color_getter) wraps a plain color.
64    ///
65    /// Keep the raw value here: the getter's wrapped color never equals another wrapped color.
66    pub day_period_color: Option<AnyColor>,
67
68    /// The shape of the day period that the time picker uses.
69    ///
70    /// If this is null, the time picker defaults to a `RoundedRectangleBorder` with a
71    /// circular corner radius of 4.0.
72    pub day_period_shape: Option<OutlinedBorderRef>,
73
74    /// The color of the day period text that represents AM/PM.
75    ///
76    /// If this is null, the time picker defaults to `ColorScheme::on_surface_variant` when the
77    /// day period is not selected, and `ColorScheme::on_tertiary_container` when it is.
78    pub day_period_text_color: Option<AnyColor>,
79
80    /// Used to configure the `TextStyle`s for the day period control.
81    ///
82    /// If this is null, the time picker defaults to the overall theme's
83    /// `TextTheme::title_medium`.
84    pub day_period_text_style: Option<AnyTextStyle>,
85
86    /// The background color of the time picker dial when the entry mode is
87    /// `TimePickerEntryMode::dial` or `TimePickerEntryMode::dialOnly`.
88    ///
89    /// If this is null and `ThemeData::use_material3` is true, the time picker dial background
90    /// color defaults to `ColorScheme::surface_container_highest`.
91    pub dial_background_color: Option<AnyColor>,
92
93    /// The color of the time picker dial's hand when the entry mode is
94    /// `TimePickerEntryMode::dial` or `TimePickerEntryMode::dialOnly`.
95    ///
96    /// If this is null and `ThemeData::use_material3` is true, the time picker dial hand color
97    /// defaults to `ColorScheme::primary`.
98    pub dial_hand_color: Option<AnyColor>,
99
100    /// The color of the dial text that represents specific hours and minutes.
101    ///
102    /// If this is null, the time picker defaults to `ColorScheme::on_surface`.
103    pub dial_text_color: Option<AnyColor>,
104
105    /// The `TextStyle` of the dial text that represents specific hours and minutes.
106    ///
107    /// If this is null, the time picker defaults to the overall theme's
108    /// `TextTheme::body_large`.
109    pub dial_text_style: Option<AnyTextStyle>,
110
111    /// The Material elevation for the time picker dialog.
112    pub elevation: Option<f64>,
113
114    /// The color of the entry mode `IconButton`.
115    ///
116    /// If this is null, the time picker defaults to `ColorScheme::on_surface_variant`.
117    pub entry_mode_icon_color: Option<AnyColor>,
118
119    /// Used to configure the `TextStyle` for the helper text in the header.
120    ///
121    /// If this is null, the time picker defaults to the overall theme's
122    /// `TextTheme::label_medium`.
123    pub help_text_style: Option<AnyTextStyle>,
124
125    /// The background color of the hour and minute controls.
126    ///
127    /// If this is null, the time picker defaults to `ColorScheme::secondary_container`.
128    pub hour_minute_color: Option<AnyColor>,
129
130    /// The shape of the hour and minute controls that the time picker uses.
131    ///
132    /// If this is null, the time picker defaults to
133    /// `RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0)))`.
134    pub hour_minute_shape: Option<ShapeBorderRef>,
135
136    /// The color of the header text that represents hours and minutes.
137    ///
138    /// If this is null, the time picker defaults to `ColorScheme::on_secondary_container`.
139    pub hour_minute_text_color: Option<AnyColor>,
140
141    /// Used to configure the text style for the hour and minute controls.
142    ///
143    /// If this is null, the time picker defaults to the overall theme's
144    /// `TextTheme::display_medium`.
145    pub hour_minute_text_style: Option<AnyTextStyle>,
146
147    /// The input decoration theme for the `TextField`s in the time picker.
148    ///
149    /// If this is null, the time picker provides its own defaults based on the overall
150    /// theme's `ColorScheme`.
151    pub input_decoration_theme: Option<InputDecorationThemeData>,
152
153    /// The padding around the time picker dialog when the entry mode is
154    /// `TimePickerEntryMode::dial` or `TimePickerEntryMode::dialOnly`.
155    pub padding: Option<EdgeInsetsGeometry>,
156
157    /// The shape of the dialog that the time picker is presented in.
158    ///
159    /// If this is null, the time picker defaults to
160    /// `RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0)))`.
161    pub shape: Option<ShapeBorderRef>,
162
163    /// The color of the time selector separator between the hour and minute controls.
164    ///
165    /// If this is null, the time picker defaults to `ColorScheme::on_surface`.
166    pub time_selector_separator_color: Option<WidgetStatePropertyRef<Option<Color>>>,
167
168    /// The text style of the time selector separator between the hour and minute controls.
169    ///
170    /// If this is null, the time picker defaults to the overall theme's
171    /// `TextTheme::display_large`, with the color of
172    /// [`time_selector_separator_color`](Self::time_selector_separator_color).
173    pub time_selector_separator_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
174}
175
176crate::theme_data_getters::theme_data_getters! {
177    /// Dart's getters of `TimePickerThemeData`, as the lazy-defaults trait: the theme data
178    /// answers with its fields, and the time picker's defaults (`_TimePickerDefaultsM3`) answer
179    /// with computed values.
180    ///
181    /// `day_period_color` answers the raw private `_dayPeriodColor`; the wrapped getter of
182    /// Dart is [`TimePickerThemeData::day_period_color_getter`].
183    pub trait TimePickerThemeDataGetters for TimePickerThemeData, fields: time_picker_theme_data {
184        background_color: Option<AnyColor>,
185        cancel_button_style: Option<ButtonStyle>,
186        confirm_button_style: Option<ButtonStyle>,
187        day_period_border_side: Option<BorderSide>,
188        day_period_color: Option<AnyColor>,
189        day_period_shape: Option<OutlinedBorderRef>,
190        day_period_text_color: Option<AnyColor>,
191        day_period_text_style: Option<AnyTextStyle>,
192        dial_background_color: Option<AnyColor>,
193        dial_hand_color: Option<AnyColor>,
194        dial_text_color: Option<AnyColor>,
195        dial_text_style: Option<AnyTextStyle>,
196        elevation: Option<f64>,
197        entry_mode_icon_color: Option<AnyColor>,
198        help_text_style: Option<AnyTextStyle>,
199        hour_minute_color: Option<AnyColor>,
200        hour_minute_shape: Option<ShapeBorderRef>,
201        hour_minute_text_color: Option<AnyColor>,
202        hour_minute_text_style: Option<AnyTextStyle>,
203        input_decoration_theme: Option<InputDecorationThemeData>,
204        padding: Option<EdgeInsetsGeometry>,
205        shape: Option<ShapeBorderRef>,
206        time_selector_separator_color: Option<WidgetStatePropertyRef<Option<Color>>>,
207        time_selector_separator_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
208    }
209}
210
211impl TimePickerThemeData {
212    /// Creates a theme that can be used for `ThemeData::time_picker_theme`.
213    ///
214    /// Dart's named arguments are the fluent setters.
215    pub fn new() -> TimePickerThemeData {
216        TimePickerThemeData::default()
217    }
218
219    /// Dart's `dayPeriodColor` getter.
220    ///
221    /// The color of the day period's background: a [`WidgetStateColor`] that is the given color
222    /// when the day period is selected and transparent otherwise, unless the given color is
223    /// already a state color, which is returned as it is.
224    pub fn day_period_color_getter(&self) -> Option<AnyColor> {
225        let day_period_color = self.day_period_color.as_ref()?;
226        if day_period_color.has_extension() {
227            return Some(day_period_color.clone());
228        }
229        let selected_color = day_period_color.color();
230        Some(AnyColor::from(WidgetStateColor::resolve_with(
231            move |states| {
232                if states.contains(&WidgetState::Selected) {
233                    return selected_color;
234                }
235                // The unselected day period should match the overall picker dialog color.
236                // Making it transparent enables that without being redundant and allows
237                // the optional elevation overlay for dark mode to be visible.
238                Colors::TRANSPARENT
239            },
240        )))
241    }
242
243    /// Dart `TimePickerThemeData(backgroundColor:)`.
244    pub fn background_color(mut self, background_color: impl Into<AnyColor>) -> Self {
245        self.background_color = Some(background_color.into());
246        self
247    }
248
249    /// Dart `TimePickerThemeData(cancelButtonStyle:)`.
250    pub fn cancel_button_style(mut self, cancel_button_style: ButtonStyle) -> Self {
251        self.cancel_button_style = Some(cancel_button_style);
252        self
253    }
254
255    /// Dart `TimePickerThemeData(confirmButtonStyle:)`.
256    pub fn confirm_button_style(mut self, confirm_button_style: ButtonStyle) -> Self {
257        self.confirm_button_style = Some(confirm_button_style);
258        self
259    }
260
261    /// Dart `TimePickerThemeData(dayPeriodBorderSide:)`.
262    pub fn day_period_border_side(mut self, day_period_border_side: BorderSide) -> Self {
263        self.day_period_border_side = Some(day_period_border_side);
264        self
265    }
266
267    /// Dart `TimePickerThemeData(dayPeriodColor:)`.
268    pub fn day_period_color(mut self, day_period_color: impl Into<AnyColor>) -> Self {
269        self.day_period_color = Some(day_period_color.into());
270        self
271    }
272
273    /// Dart `TimePickerThemeData(dayPeriodShape:)`.
274    pub fn day_period_shape(mut self, day_period_shape: impl Into<OutlinedBorderRef>) -> Self {
275        self.day_period_shape = Some(day_period_shape.into());
276        self
277    }
278
279    /// Dart `TimePickerThemeData(dayPeriodTextColor:)`.
280    pub fn day_period_text_color(mut self, day_period_text_color: impl Into<AnyColor>) -> Self {
281        self.day_period_text_color = Some(day_period_text_color.into());
282        self
283    }
284
285    /// Dart `TimePickerThemeData(dayPeriodTextStyle:)`.
286    pub fn day_period_text_style(mut self, day_period_text_style: impl Into<AnyTextStyle>) -> Self {
287        self.day_period_text_style = Some(day_period_text_style.into());
288        self
289    }
290
291    /// Dart `TimePickerThemeData(dialBackgroundColor:)`.
292    pub fn dial_background_color(mut self, dial_background_color: impl Into<AnyColor>) -> Self {
293        self.dial_background_color = Some(dial_background_color.into());
294        self
295    }
296
297    /// Dart `TimePickerThemeData(dialHandColor:)`.
298    pub fn dial_hand_color(mut self, dial_hand_color: impl Into<AnyColor>) -> Self {
299        self.dial_hand_color = Some(dial_hand_color.into());
300        self
301    }
302
303    /// Dart `TimePickerThemeData(dialTextColor:)`.
304    pub fn dial_text_color(mut self, dial_text_color: impl Into<AnyColor>) -> Self {
305        self.dial_text_color = Some(dial_text_color.into());
306        self
307    }
308
309    /// Dart `TimePickerThemeData(dialTextStyle:)`.
310    pub fn dial_text_style(mut self, dial_text_style: impl Into<AnyTextStyle>) -> Self {
311        self.dial_text_style = Some(dial_text_style.into());
312        self
313    }
314
315    /// Dart `TimePickerThemeData(elevation:)`.
316    pub fn elevation(mut self, elevation: f64) -> Self {
317        self.elevation = Some(elevation);
318        self
319    }
320
321    /// Dart `TimePickerThemeData(entryModeIconColor:)`.
322    pub fn entry_mode_icon_color(mut self, entry_mode_icon_color: impl Into<AnyColor>) -> Self {
323        self.entry_mode_icon_color = Some(entry_mode_icon_color.into());
324        self
325    }
326
327    /// Dart `TimePickerThemeData(helpTextStyle:)`.
328    pub fn help_text_style(mut self, help_text_style: impl Into<AnyTextStyle>) -> Self {
329        self.help_text_style = Some(help_text_style.into());
330        self
331    }
332
333    /// Dart `TimePickerThemeData(hourMinuteColor:)`.
334    pub fn hour_minute_color(mut self, hour_minute_color: impl Into<AnyColor>) -> Self {
335        self.hour_minute_color = Some(hour_minute_color.into());
336        self
337    }
338
339    /// Dart `TimePickerThemeData(hourMinuteShape:)`.
340    pub fn hour_minute_shape(mut self, hour_minute_shape: impl Into<ShapeBorderRef>) -> Self {
341        self.hour_minute_shape = Some(hour_minute_shape.into());
342        self
343    }
344
345    /// Dart `TimePickerThemeData(hourMinuteTextColor:)`.
346    pub fn hour_minute_text_color(mut self, hour_minute_text_color: impl Into<AnyColor>) -> Self {
347        self.hour_minute_text_color = Some(hour_minute_text_color.into());
348        self
349    }
350
351    /// Dart `TimePickerThemeData(hourMinuteTextStyle:)`.
352    pub fn hour_minute_text_style(
353        mut self,
354        hour_minute_text_style: impl Into<AnyTextStyle>,
355    ) -> Self {
356        self.hour_minute_text_style = Some(hour_minute_text_style.into());
357        self
358    }
359
360    /// Dart `TimePickerThemeData(inputDecorationTheme:)`.
361    pub fn input_decoration_theme(
362        mut self,
363        input_decoration_theme: impl Into<InputDecorationThemeData>,
364    ) -> Self {
365        self.input_decoration_theme = Some(input_decoration_theme.into());
366        self
367    }
368
369    /// Dart `TimePickerThemeData(padding:)`.
370    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Self {
371        self.padding = Some(padding.into());
372        self
373    }
374
375    /// Dart `TimePickerThemeData(shape:)`.
376    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> Self {
377        self.shape = Some(shape.into());
378        self
379    }
380
381    /// Dart `TimePickerThemeData(timeSelectorSeparatorColor:)`.
382    pub fn time_selector_separator_color(
383        mut self,
384        time_selector_separator_color: WidgetStatePropertyRef<Option<Color>>,
385    ) -> Self {
386        self.time_selector_separator_color = Some(time_selector_separator_color);
387        self
388    }
389
390    /// Dart `TimePickerThemeData(timeSelectorSeparatorTextStyle:)`.
391    pub fn time_selector_separator_text_style(
392        mut self,
393        time_selector_separator_text_style: WidgetStatePropertyRef<Option<TextStyle>>,
394    ) -> Self {
395        self.time_selector_separator_text_style = Some(time_selector_separator_text_style);
396        self
397    }
398
399    /// Creates a copy of this object with the given fields replaced with the new values.
400    ///
401    /// Dart's named arguments are the fluent setters on the copy
402    /// (`data.copy_with().elevation(4.0)`).
403    pub fn copy_with(&self) -> TimePickerThemeData {
404        self.clone()
405    }
406
407    /// Linearly interpolate between two time picker themes.
408    pub fn lerp(
409        a: Option<&TimePickerThemeData>,
410        b: Option<&TimePickerThemeData>,
411        t: f64,
412    ) -> TimePickerThemeData {
413        if let (Some(a), Some(b)) = (a, b)
414            && std::ptr::eq(a, b)
415        {
416            return a.clone();
417        }
418        // Workaround since BorderSide's lerp does not allow for null arguments.
419        let day_period_border_side = match (
420            a.and_then(|a| a.day_period_border_side),
421            b.and_then(|b| b.day_period_border_side),
422        ) {
423            (None, None) => None,
424            (None, Some(b)) => Some(b),
425            (Some(a), None) => Some(a),
426            (Some(a), Some(b)) => Some(BorderSide::lerp(a, b, t)),
427        };
428        let lerp_color = |a: Option<&AnyColor>, b: Option<&AnyColor>| {
429            Color::lerp(a.map(AnyColor::color), b.map(AnyColor::color), t).map(AnyColor::from)
430        };
431        let lerp_text_style = |a: Option<&AnyTextStyle>, b: Option<&AnyTextStyle>| {
432            TextStyle::lerp(a.map(AnyTextStyle::value), b.map(AnyTextStyle::value), t)
433                .map(AnyTextStyle::new)
434        };
435        TimePickerThemeData {
436            background_color: lerp_color(
437                a.and_then(|a| a.background_color.as_ref()),
438                b.and_then(|b| b.background_color.as_ref()),
439            ),
440            cancel_button_style: ButtonStyle::lerp(
441                a.and_then(|a| a.cancel_button_style.as_ref()),
442                b.and_then(|b| b.cancel_button_style.as_ref()),
443                t,
444            ),
445            confirm_button_style: ButtonStyle::lerp(
446                a.and_then(|a| a.confirm_button_style.as_ref()),
447                b.and_then(|b| b.confirm_button_style.as_ref()),
448                t,
449            ),
450            day_period_border_side,
451            day_period_color: lerp_color(
452                a.and_then(|a| a.day_period_color_getter()).as_ref(),
453                b.and_then(|b| b.day_period_color_getter()).as_ref(),
454            ),
455            day_period_shape: OutlinedBorderRef::lerp(
456                a.and_then(|a| a.day_period_shape.as_ref()),
457                b.and_then(|b| b.day_period_shape.as_ref()),
458                t,
459            ),
460            day_period_text_color: lerp_color(
461                a.and_then(|a| a.day_period_text_color.as_ref()),
462                b.and_then(|b| b.day_period_text_color.as_ref()),
463            ),
464            day_period_text_style: lerp_text_style(
465                a.and_then(|a| a.day_period_text_style.as_ref()),
466                b.and_then(|b| b.day_period_text_style.as_ref()),
467            ),
468            dial_background_color: lerp_color(
469                a.and_then(|a| a.dial_background_color.as_ref()),
470                b.and_then(|b| b.dial_background_color.as_ref()),
471            ),
472            dial_hand_color: lerp_color(
473                a.and_then(|a| a.dial_hand_color.as_ref()),
474                b.and_then(|b| b.dial_hand_color.as_ref()),
475            ),
476            dial_text_color: lerp_color(
477                a.and_then(|a| a.dial_text_color.as_ref()),
478                b.and_then(|b| b.dial_text_color.as_ref()),
479            ),
480            dial_text_style: lerp_text_style(
481                a.and_then(|a| a.dial_text_style.as_ref()),
482                b.and_then(|b| b.dial_text_style.as_ref()),
483            ),
484            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
485            entry_mode_icon_color: lerp_color(
486                a.and_then(|a| a.entry_mode_icon_color.as_ref()),
487                b.and_then(|b| b.entry_mode_icon_color.as_ref()),
488            ),
489            help_text_style: lerp_text_style(
490                a.and_then(|a| a.help_text_style.as_ref()),
491                b.and_then(|b| b.help_text_style.as_ref()),
492            ),
493            hour_minute_color: lerp_color(
494                a.and_then(|a| a.hour_minute_color.as_ref()),
495                b.and_then(|b| b.hour_minute_color.as_ref()),
496            ),
497            hour_minute_shape: ShapeBorderRef::lerp(
498                a.and_then(|a| a.hour_minute_shape.as_ref()),
499                b.and_then(|b| b.hour_minute_shape.as_ref()),
500                t,
501            ),
502            hour_minute_text_color: lerp_color(
503                a.and_then(|a| a.hour_minute_text_color.as_ref()),
504                b.and_then(|b| b.hour_minute_text_color.as_ref()),
505            ),
506            hour_minute_text_style: lerp_text_style(
507                a.and_then(|a| a.hour_minute_text_style.as_ref()),
508                b.and_then(|b| b.hour_minute_text_style.as_ref()),
509            ),
510            input_decoration_theme: if t < 0.5 {
511                a.and_then(|a| a.input_decoration_theme.clone())
512            } else {
513                b.and_then(|b| b.input_decoration_theme.clone())
514            },
515            padding: EdgeInsetsGeometry::lerp(
516                a.and_then(|a| a.padding),
517                b.and_then(|b| b.padding),
518                t,
519            ),
520            shape: ShapeBorderRef::lerp(
521                a.and_then(|a| a.shape.as_ref()),
522                b.and_then(|b| b.shape.as_ref()),
523                t,
524            ),
525            time_selector_separator_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
526                a.and_then(|a| a.time_selector_separator_color.clone()),
527                b.and_then(|b| b.time_selector_separator_color.clone()),
528                t,
529                Color::lerp,
530            ),
531            time_selector_separator_text_style:
532                <dyn WidgetStateProperty<Option<TextStyle>>>::lerp_optional(
533                    a.and_then(|a| a.time_selector_separator_text_style.clone()),
534                    b.and_then(|b| b.time_selector_separator_text_style.clone()),
535                    t,
536                    |a, b, t| TextStyle::lerp(a.as_ref(), b.as_ref(), t),
537                ),
538        }
539    }
540}
541
542impl PartialEq for TimePickerThemeData {
543    fn eq(&self, other: &TimePickerThemeData) -> bool {
544        if std::ptr::eq(self, other) {
545            return true;
546        }
547        other.background_color == self.background_color
548            && other.cancel_button_style == self.cancel_button_style
549            && other.confirm_button_style == self.confirm_button_style
550            && other.day_period_border_side == self.day_period_border_side
551            && other.day_period_color_getter() == self.day_period_color_getter()
552            && other.day_period_shape == self.day_period_shape
553            && other.day_period_text_color == self.day_period_text_color
554            && other.day_period_text_style == self.day_period_text_style
555            && other.dial_background_color == self.dial_background_color
556            && other.dial_hand_color == self.dial_hand_color
557            && other.dial_text_color == self.dial_text_color
558            && other.dial_text_style == self.dial_text_style
559            && other.elevation == self.elevation
560            && other.entry_mode_icon_color == self.entry_mode_icon_color
561            && other.help_text_style == self.help_text_style
562            && other.hour_minute_color == self.hour_minute_color
563            && other.hour_minute_shape == self.hour_minute_shape
564            && other.hour_minute_text_color == self.hour_minute_text_color
565            && other.hour_minute_text_style == self.hour_minute_text_style
566            && other.input_decoration_theme == self.input_decoration_theme
567            && other.padding == self.padding
568            && other.shape == self.shape
569            && other.time_selector_separator_color == self.time_selector_separator_color
570            && other.time_selector_separator_text_style == self.time_selector_separator_text_style
571    }
572}
573
574/// An inherited widget that defines the configuration for time pickers displayed using
575/// `showTimePicker` in this widget's subtree.
576///
577/// Values specified here are used for time picker properties that are not given an explicit
578/// non-null value.
579#[derive(Debug)]
580pub struct TimePickerTheme {
581    pub key: Option<KeyRef>,
582    /// The properties for descendant time picker widgets.
583    pub data: TimePickerThemeData,
584    pub child: WidgetRef,
585}
586
587impl TimePickerTheme {
588    /// Creates a time picker theme that controls the configurations for descendant time
589    /// pickers.
590    #[cfg_attr(debug_assertions, track_caller)]
591    pub fn new<K>(data: TimePickerThemeData, child: impl IntoWidget<K>) -> TimePickerTheme {
592        TimePickerTheme {
593            key: None,
594            data,
595            child: child.into_widget(),
596        }
597    }
598
599    /// Dart `TimePickerTheme(key:)`.
600    pub fn key(mut self, key: KeyRef) -> TimePickerTheme {
601        self.key = Some(key);
602        self
603    }
604
605    /// Retrieves the [`TimePickerThemeData`] from the closest ancestor [`TimePickerTheme`].
606    ///
607    /// If there is no enclosing [`TimePickerTheme`] widget, then
608    /// `ThemeData::time_picker_theme` is used.
609    pub fn of(app: &mut App, context: BuildContext) -> TimePickerThemeData {
610        match context.depend_on_inherited_widget_of_exact_type::<TimePickerTheme>(app) {
611            Some(time_picker_theme) => time_picker_theme.data.clone(),
612            None => Theme::of(app, context).time_picker_theme.clone(),
613        }
614    }
615}
616
617impl InheritedTheme for TimePickerTheme {
618    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
619        TimePickerTheme::new(self.data.clone(), child).into_widget()
620    }
621}
622
623impl InheritedWidget for TimePickerTheme {
624    fn key(&self) -> Option<&KeyRef> {
625        self.key.as_ref()
626    }
627
628    fn child(&self) -> &WidgetRef {
629        &self.child
630    }
631
632    fn update_should_notify(&self, old_widget: &TimePickerTheme) -> bool {
633        self.data != old_widget.data
634    }
635
636    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
637        Some(self)
638    }
639}
640
641impl waft_foundation::Diagnosticable for TimePickerThemeData {
642    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
643        properties.add(
644            DiagnosticsProperty::<AnyColor>::new("backgroundColor", self.background_color.clone())
645                .default_value(None),
646        );
647        properties.add(
648            DiagnosticsProperty::<ButtonStyle>::new(
649                "cancelButtonStyle",
650                self.cancel_button_style.clone(),
651            )
652            .default_value(None),
653        );
654        properties.add(
655            DiagnosticsProperty::<ButtonStyle>::new(
656                "confirmButtonStyle",
657                self.confirm_button_style.clone(),
658            )
659            .default_value(None),
660        );
661        properties.add(
662            DiagnosticsProperty::<BorderSide>::new(
663                "dayPeriodBorderSide",
664                self.day_period_border_side,
665            )
666            .default_value(None),
667        );
668        properties.add(
669            DiagnosticsProperty::<AnyColor>::new("dayPeriodColor", self.day_period_color.clone())
670                .default_value(None),
671        );
672        properties.add(
673            DiagnosticsProperty::<OutlinedBorderRef>::new(
674                "dayPeriodShape",
675                self.day_period_shape.clone(),
676            )
677            .default_value(None),
678        );
679        properties.add(
680            DiagnosticsProperty::<AnyColor>::new(
681                "dayPeriodTextColor",
682                self.day_period_text_color.clone(),
683            )
684            .default_value(None),
685        );
686        properties.add(
687            DiagnosticsProperty::<AnyTextStyle>::new(
688                "dayPeriodTextStyle",
689                self.day_period_text_style.clone(),
690            )
691            .default_value(None),
692        );
693        properties.add(
694            DiagnosticsProperty::<AnyColor>::new(
695                "dialBackgroundColor",
696                self.dial_background_color.clone(),
697            )
698            .default_value(None),
699        );
700        properties.add(
701            DiagnosticsProperty::<AnyColor>::new("dialHandColor", self.dial_hand_color.clone())
702                .default_value(None),
703        );
704        properties.add(
705            DiagnosticsProperty::<AnyColor>::new("dialTextColor", self.dial_text_color.clone())
706                .default_value(None),
707        );
708        properties.add(
709            DiagnosticsProperty::<AnyTextStyle>::new("dialTextStyle", self.dial_text_style.clone())
710                .default_value(None),
711        );
712        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
713        properties.add(
714            DiagnosticsProperty::<AnyColor>::new(
715                "entryModeIconColor",
716                self.entry_mode_icon_color.clone(),
717            )
718            .default_value(None),
719        );
720        properties.add(
721            DiagnosticsProperty::<AnyTextStyle>::new("helpTextStyle", self.help_text_style.clone())
722                .default_value(None),
723        );
724        properties.add(
725            DiagnosticsProperty::<AnyColor>::new("hourMinuteColor", self.hour_minute_color.clone())
726                .default_value(None),
727        );
728        properties.add(
729            DiagnosticsProperty::<ShapeBorderRef>::new(
730                "hourMinuteShape",
731                self.hour_minute_shape.clone(),
732            )
733            .default_value(None),
734        );
735        properties.add(
736            DiagnosticsProperty::<AnyColor>::new(
737                "hourMinuteTextColor",
738                self.hour_minute_text_color.clone(),
739            )
740            .default_value(None),
741        );
742        properties.add(
743            DiagnosticsProperty::<AnyTextStyle>::new(
744                "hourMinuteTextStyle",
745                self.hour_minute_text_style.clone(),
746            )
747            .default_value(None),
748        );
749        properties.add(
750            DiagnosticsProperty::<InputDecorationThemeData>::new(
751                "inputDecorationTheme",
752                self.input_decoration_theme.clone(),
753            )
754            .default_value(None),
755        );
756        properties.add(
757            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
758                .default_value(None),
759        );
760        properties.add(
761            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
762                .default_value(None),
763        );
764        properties.add(
765            DiagnosticsProperty::<String>::new(
766                "timeSelectorSeparatorColor",
767                self.time_selector_separator_color
768                    .as_deref()
769                    .map(|property| property.to_string()),
770            )
771            .default_value(None),
772        );
773        properties.add(
774            DiagnosticsProperty::<String>::new(
775                "timeSelectorSeparatorTextStyle",
776                self.time_selector_separator_text_style
777                    .as_deref()
778                    .map(|property| property.to_string()),
779            )
780            .default_value(None),
781        );
782    }
783}
784
785impl std::fmt::Display for TimePickerThemeData {
786    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
787        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
788    }
789}
790
791#[cfg(test)]
792mod tests {
793    use std::time::Duration;
794
795    use std::rc::Rc;
796
797    use waft_embedder::{Radius, Size};
798    use waft_foundation::Listener;
799    use waft_painting::{
800        BorderRadius, BorderRadiusGeometry, FontStyle, RoundedRectangleBorder, ShapeBorderRef,
801    };
802    use waft_widgets::{
803        AnyElement, Builder, Center, IntoWidget, Text, WidgetStateColor, WidgetStatePropertyAll,
804        WidgetStates,
805    };
806
807    use waft_widgets::testing::{WidgetTester, find, test_widgets};
808
809    use super::*;
810    use crate::dialog::Dialog;
811    use crate::elevated_button::ElevatedButton;
812    use crate::icon_button::IconButton;
813    use crate::input_border::OutlineInputBorder;
814    use crate::input_decorator::InputDecorationThemeData;
815    use crate::material::Material;
816    use crate::test_support::{PaintInspection, material_app};
817
818    use crate::text_button::TextButton;
819    use crate::text_field::TextField;
820    use crate::text_theme::TextTheme;
821    use crate::theme_data::ThemeData;
822    use crate::time::TimeOfDay;
823    use crate::time_picker::tests::{dial_label_styles, dial_paint};
824    use crate::time_picker::{ShowTimePicker, TimePickerEntryMode};
825    use crate::tooltip::tests::{m2, m3};
826    use crate::typography::Typography;
827    use waft_rendering::testing::{PaintCall, assert_paints};
828
829    fn resolve(color: &AnyColor, states: &WidgetStates) -> Color {
830        <dyn WidgetStateProperty<Color>>::resolve_as(color, states).color()
831    }
832
833    #[test]
834    fn time_picker_theme_data_copy_with_equals_and_hash_code_basics() {
835        assert_eq!(
836            TimePickerThemeData::new(),
837            TimePickerThemeData::new().copy_with()
838        );
839    }
840
841    #[test]
842    fn time_picker_theme_data_lerp_special_cases() {
843        let data = TimePickerThemeData::new();
844        assert_eq!(
845            TimePickerThemeData::lerp(Some(&data), Some(&data), 0.5),
846            data
847        );
848    }
849
850    #[test]
851    fn time_picker_theme_data_has_null_fields_by_default() {
852        let time_picker_theme = TimePickerThemeData::new();
853        assert_eq!(time_picker_theme.background_color, None);
854        assert!(time_picker_theme.cancel_button_style.is_none());
855        assert!(time_picker_theme.confirm_button_style.is_none());
856        assert_eq!(time_picker_theme.day_period_border_side, None);
857        assert_eq!(time_picker_theme.day_period_color_getter(), None);
858        assert!(time_picker_theme.day_period_shape.is_none());
859        assert_eq!(time_picker_theme.day_period_text_color, None);
860        assert_eq!(time_picker_theme.day_period_text_style, None);
861        assert_eq!(time_picker_theme.dial_background_color, None);
862        assert_eq!(time_picker_theme.dial_hand_color, None);
863        assert_eq!(time_picker_theme.dial_text_color, None);
864        assert_eq!(time_picker_theme.dial_text_style, None);
865        assert_eq!(time_picker_theme.elevation, None);
866        assert_eq!(time_picker_theme.entry_mode_icon_color, None);
867        assert_eq!(time_picker_theme.help_text_style, None);
868        assert_eq!(time_picker_theme.hour_minute_color, None);
869        assert!(time_picker_theme.hour_minute_shape.is_none());
870        assert_eq!(time_picker_theme.hour_minute_text_color, None);
871        assert_eq!(time_picker_theme.hour_minute_text_style, None);
872        assert!(time_picker_theme.input_decoration_theme.is_none());
873        assert_eq!(time_picker_theme.padding, None);
874        assert!(time_picker_theme.shape.is_none());
875        assert!(time_picker_theme.time_selector_separator_color.is_none());
876        assert!(
877            time_picker_theme
878                .time_selector_separator_text_style
879                .is_none()
880        );
881    }
882
883    #[test]
884    fn day_period_color_getter_is_transparent_unless_selected_for_a_plain_color() {
885        let red = Color::new(0xffff0000);
886        let theme = TimePickerThemeData::new().day_period_color(red);
887        let wrapped = theme.day_period_color_getter().expect("a color");
888        let selected: WidgetStates = [WidgetState::Selected].into_iter().collect();
889        assert_eq!(
890            resolve(&wrapped, &selected),
891            red,
892            "a selected day period shows the given color"
893        );
894        assert_eq!(
895            resolve(&wrapped, &WidgetStates::new()),
896            Colors::TRANSPARENT,
897            "an unselected day period matches the dialog"
898        );
899    }
900
901    #[test]
902    fn day_period_color_getter_keeps_a_widget_state_color_as_it_is() {
903        let state_color = WidgetStateColor::resolve_with(|_| Color::new(0xff00ff00));
904        let theme = TimePickerThemeData::new().day_period_color(state_color);
905        let wrapped = theme.day_period_color_getter().expect("a color");
906        assert_eq!(
907            resolve(&wrapped, &WidgetStates::new()),
908            Color::new(0xff00ff00)
909        );
910        assert_eq!(theme, theme.copy_with());
911    }
912
913    fn selected_color() -> Color {
914        Colors::GREEN.shade100()
915    }
916
917    fn unselected_color() -> Color {
918        Colors::GREEN.shade200()
919    }
920
921    /// Dart's `Color.withOpacity`.
922    fn opacity(color: Color, opacity: f64) -> Color {
923        color.with_alpha((255.0 * opacity).round() as i32)
924    }
925
926    fn state_color() -> WidgetStateColor {
927        WidgetStateColor::resolve_with(|states| {
928            if states.contains(&WidgetState::Selected) {
929                selected_color()
930            } else {
931                unselected_color()
932            }
933        })
934    }
935
936    fn rounded(radius: f64) -> RoundedRectangleBorder {
937        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(radius))
938    }
939
940    /// Dart's `_timePickerTheme`.
941    fn time_picker_theme(include_input_decoration: bool) -> TimePickerThemeData {
942        let color = |color: Color| BorderSide {
943            color,
944            ..BorderSide::default()
945        };
946        let outline = |side_color: Color| OutlineInputBorder::new().border_side(color(side_color));
947        let mut theme = TimePickerThemeData::new()
948            .background_color(Colors::ORANGE.primary())
949            .cancel_button_style(
950                TextButton::style_from()
951                    .foreground_color(Colors::RED.primary())
952                    .build(),
953            )
954            .confirm_button_style(
955                TextButton::style_from()
956                    .foreground_color(Colors::GREEN.primary())
957                    .build(),
958            )
959            .hour_minute_text_color(state_color())
960            .hour_minute_color(state_color())
961            .day_period_text_color(state_color())
962            .day_period_color(state_color())
963            .dial_hand_color(Colors::BROWN.primary())
964            .dial_background_color(Colors::PINK_ACCENT.primary())
965            .dial_text_color(state_color())
966            .entry_mode_icon_color(Colors::RED.primary())
967            .hour_minute_text_style(TextStyle::new().font_size(8.0))
968            .day_period_text_style(TextStyle::new().font_size(8.0))
969            .help_text_style(TextStyle::new().font_size(8.0))
970            .shape(rounded(16.0))
971            .hour_minute_shape(rounded(16.0))
972            .day_period_shape(rounded(16.0))
973            .day_period_border_side(color(Colors::BLUE_ACCENT.primary()));
974        if include_input_decoration {
975            theme = theme.input_decoration_theme(
976                InputDecorationThemeData::new()
977                    .filled(true)
978                    .fill_color(Colors::PURPLE.primary())
979                    .enabled_border(outline(Colors::BLUE.primary()))
980                    .error_border(outline(Colors::GREEN.primary()))
981                    .focused_border(outline(Colors::YELLOW.primary()))
982                    .focused_error_border(outline(Colors::RED.primary()))
983                    .hint_style(TextStyle::new().font_size(8.0)),
984            );
985        }
986        theme
987    }
988
989    /// Dart's `_TimePickerLauncher`: a button that shows the time picker at 7:15, tapped.
990    fn launch(tester: &mut WidgetTester, theme: ThemeData, entry_mode: TimePickerEntryMode) {
991        let launcher = Material::new()
992            .child(Center::new().child(Builder::new(move |_app, context| {
993                ElevatedButton::new(
994                    Some(Listener::new(move |app| {
995                        drop({
996                            let mut show = ShowTimePicker::new(TimeOfDay::new(7, 15));
997                            show = show.initial_entry_mode(entry_mode);
998                            show.show(app, context)
999                        });
1000                    })),
1001                    Some(Text::new("X")),
1002                )
1003                .into_widget()
1004            })))
1005            .into_widget();
1006        tester.pump_widget(material_app(theme, launcher));
1007        let x = *find::text("X")
1008            .evaluate(tester)
1009            .first()
1010            .expect("the X button");
1011        let center = tester.get_center(x);
1012        tester.tap_at(center, 1);
1013        tester.pump_and_settle_by(Duration::from_secs(1));
1014    }
1015
1016    fn text_element(tester: &WidgetTester, text: &str) -> AnyElement {
1017        tester.element(find::text(text).first())
1018    }
1019
1020    /// Dart's `_dialogMaterial`.
1021    fn dialog_material(tester: &WidgetTester) -> (Option<Color>, Option<ShapeBorderRef>) {
1022        let material = tester.element(
1023            find::descendant(find::by_type::<Dialog>().at(0), find::by_type::<Material>()).first(),
1024        );
1025        tester.widget(material, |material: &Material| {
1026            (material.color, material.shape.clone())
1027        })
1028    }
1029
1030    /// Dart's `_textMaterial`: the first `Material` above the text.
1031    fn text_material(tester: &WidgetTester, text: &str) -> (Option<Color>, Option<ShapeBorderRef>) {
1032        let material =
1033            tester.element(find::ancestor(find::text(text), find::by_type::<Material>()).first());
1034        tester.widget(material, |material: &Material| {
1035            (material.color, material.shape.clone())
1036        })
1037    }
1038
1039    fn paragraph_style(tester: &WidgetTester, text: &str) -> TextStyle {
1040        crate::bottom_navigation_bar::tests::paragraph_style(tester, text)
1041    }
1042
1043    /// Dart's `_textField(tester, text).decoration` and `.style`.
1044    fn text_field(tester: &WidgetTester, text: &str) -> TextField {
1045        let field =
1046            tester.element(find::ancestor(find::text(text), find::by_type::<TextField>()).first());
1047        tester.widget(field, |field: &TextField| field.clone())
1048    }
1049
1050    fn entry_mode_icon_color(tester: &WidgetTester) -> Option<Color> {
1051        let button = tester.element(
1052            find::descendant(
1053                find::by_type::<Dialog>().at(0),
1054                find::by_type::<IconButton>(),
1055            )
1056            .first(),
1057        );
1058        tester.widget(button, |button: &IconButton| button.color)
1059    }
1060
1061    /// Dart's `_actionButtonStyle`.
1062    fn action_button_style(tester: &WidgetTester, text: &str) -> ButtonStyle {
1063        let button =
1064            tester.element(find::ancestor(find::text(text), find::by_type::<TextButton>()).first());
1065        tester.widget(button, |button: &TextButton| {
1066            crate::button_style_button::ButtonStyleButton::button_style_button_data(button)
1067                .style
1068                .clone()
1069                .expect("a styled button")
1070        })
1071    }
1072
1073    /// What the dial's `CustomPaint` paints: Dart's `paints` on its render object.
1074    fn dial_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
1075        tester.painted_ops_deep(tester.render_object(dial_paint(tester)))
1076    }
1077
1078    /// The style a text gets from a typography: Dart's
1079    /// `typography.englishLike.x!.merge(typography.black.x)`.
1080    fn base_style(
1081        typography: &Typography,
1082        white: bool,
1083        field: fn(&TextTheme) -> &Option<TextStyle>,
1084    ) -> TextStyle {
1085        let tint = if white {
1086            &typography.white
1087        } else {
1088            &typography.black
1089        };
1090        field(&typography.english_like)
1091            .as_ref()
1092            .expect("an english-like style")
1093            .merge(field(tint).as_ref())
1094    }
1095
1096    fn color_of(style: &TextStyle) -> Option<Color> {
1097        style.color.as_ref().map(|color| color.color())
1098    }
1099
1100    fn rounded_with_side(side_color: Color, top_left: bool, radius: f64) -> Option<ShapeBorderRef> {
1101        let radius = Radius::circular(radius);
1102        let none = Radius::ZERO;
1103        let border_radius = if top_left {
1104            BorderRadius::only(radius, none, radius, none)
1105        } else {
1106            BorderRadius::only(none, radius, none, radius)
1107        };
1108        Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
1109            BorderSide {
1110                color: side_color,
1111                ..BorderSide::default()
1112            },
1113            BorderRadiusGeometry::from(border_radius),
1114        )))
1115    }
1116
1117    #[test]
1118    fn material2_passing_no_time_picker_theme_data_uses_defaults() {
1119        test_widgets(|tester| {
1120            let default_theme = m2(&tester.cell.borrow());
1121            launch(tester, default_theme.clone(), TimePickerEntryMode::Dial);
1122            let scheme = &default_theme.color_scheme;
1123            let typography = Typography::material2014().build();
1124
1125            let (color, shape) = dialog_material(tester);
1126            assert_eq!(color, Some(scheme.surface()));
1127            assert_eq!(shape, Some(ShapeBorderRef::new(rounded(4.0))));
1128
1129            assert_paints(
1130                &dial_ops(tester),
1131                &[
1132                    PaintCall::circle(Some(opacity(scheme.on_surface(), 0.08))),
1133                    PaintCall::circle(Some(scheme.primary())),
1134                ],
1135            );
1136
1137            let display_medium =
1138                |white| base_style(&typography, white, |theme| &theme.display_medium);
1139            let title_medium = base_style(&typography, false, |theme| &theme.title_medium);
1140            assert_eq!(
1141                paragraph_style(tester, "7"),
1142                display_medium(false).copy_with().color(scheme.primary())
1143            );
1144            assert_eq!(
1145                paragraph_style(tester, "15"),
1146                display_medium(false).copy_with().color(scheme.on_surface())
1147            );
1148            assert_eq!(
1149                paragraph_style(tester, "AM"),
1150                title_medium.copy_with().color(scheme.primary())
1151            );
1152            assert_eq!(
1153                paragraph_style(tester, "PM"),
1154                title_medium
1155                    .copy_with()
1156                    .color(opacity(scheme.on_surface(), 0.6))
1157            );
1158            assert_eq!(
1159                paragraph_style(tester, "SELECT TIME"),
1160                base_style(&typography, false, |theme| &theme.label_small)
1161            );
1162
1163            let (primary, selected) = dial_label_styles(tester);
1164            assert_eq!(
1165                primary,
1166                base_style(&typography, false, |theme| &theme.body_large)
1167                    .copy_with()
1168                    .color(scheme.on_surface())
1169            );
1170            assert_eq!(
1171                selected,
1172                base_style(&typography, true, |theme| &theme.body_large)
1173                    .copy_with()
1174                    .color(scheme.on_primary())
1175            );
1176
1177            let (color, shape) = text_material(tester, "7");
1178            assert_eq!(color, Some(opacity(scheme.primary(), 0.12)));
1179            assert_eq!(shape, Some(ShapeBorderRef::new(rounded(4.0))));
1180            let (color, shape) = text_material(tester, "15");
1181            assert_eq!(color, Some(opacity(scheme.on_surface(), 0.12)));
1182            assert_eq!(shape, Some(ShapeBorderRef::new(rounded(4.0))));
1183
1184            let (am_color, am_shape) = text_material(tester, "AM");
1185            assert_eq!(am_color, Some(opacity(scheme.primary(), 0.12)));
1186            let (pm_color, pm_shape) = text_material(tester, "PM");
1187            assert_eq!(pm_color, Some(Colors::TRANSPARENT));
1188
1189            let border_color =
1190                Color::alpha_blend(opacity(scheme.on_surface(), 0.38), scheme.surface());
1191            assert_eq!(am_shape, rounded_with_side(border_color, true, 4.0));
1192            assert_eq!(pm_shape, rounded_with_side(border_color, false, 4.0));
1193
1194            assert_eq!(
1195                entry_mode_icon_color(tester),
1196                Some(opacity(scheme.on_surface(), 0.6))
1197            );
1198
1199            let default_style = TextButton::style_from().build();
1200            assert_eq!(action_button_style(tester, "CANCEL"), default_style);
1201            assert_eq!(action_button_style(tester, "OK"), default_style);
1202        });
1203    }
1204
1205    /// The style an M3 text gets: the typography's, with the colors the dialog gives it.
1206    fn m3_style(
1207        typography: &Typography,
1208        field: fn(&TextTheme) -> &Option<TextStyle>,
1209        color: Color,
1210        decoration_color: Color,
1211    ) -> TextStyle {
1212        base_style(typography, false, field)
1213            .copy_with()
1214            .color(color)
1215            .decoration_color(decoration_color)
1216    }
1217
1218    #[test]
1219    fn material3_passing_no_time_picker_theme_data_uses_defaults() {
1220        test_widgets(|tester| {
1221            let default_theme = m3(&tester.cell.borrow());
1222            launch(tester, default_theme.clone(), TimePickerEntryMode::Dial);
1223            let scheme = &default_theme.color_scheme;
1224            let typography = Typography::material2021().build();
1225            let decoration = scheme.on_surface();
1226
1227            let (color, shape) = dialog_material(tester);
1228            assert_eq!(color, Some(scheme.surface_container_high()));
1229            assert_eq!(shape, Some(ShapeBorderRef::new(rounded(28.0))));
1230
1231            assert_paints(
1232                &dial_ops(tester),
1233                &[
1234                    PaintCall::circle(Some(scheme.surface_container_highest())),
1235                    PaintCall::circle(Some(scheme.primary())),
1236                ],
1237            );
1238
1239            assert_eq!(
1240                paragraph_style(tester, "7"),
1241                m3_style(
1242                    &typography,
1243                    |theme| &theme.display_large,
1244                    scheme.on_primary_container(),
1245                    decoration
1246                )
1247            );
1248            assert_eq!(
1249                paragraph_style(tester, "15"),
1250                m3_style(
1251                    &typography,
1252                    |theme| &theme.display_large,
1253                    scheme.on_surface(),
1254                    decoration
1255                )
1256            );
1257            assert_eq!(
1258                paragraph_style(tester, "AM"),
1259                m3_style(
1260                    &typography,
1261                    |theme| &theme.title_medium,
1262                    scheme.on_tertiary_container(),
1263                    decoration
1264                )
1265            );
1266            assert_eq!(
1267                paragraph_style(tester, "PM"),
1268                m3_style(
1269                    &typography,
1270                    |theme| &theme.title_medium,
1271                    scheme.on_surface_variant(),
1272                    decoration
1273                )
1274            );
1275            assert_eq!(
1276                paragraph_style(tester, "Select time"),
1277                m3_style(
1278                    &typography,
1279                    |theme| &theme.body_medium,
1280                    scheme.on_surface(),
1281                    decoration
1282                )
1283            );
1284
1285            let (primary, selected) = dial_label_styles(tester);
1286            assert_eq!(
1287                primary,
1288                m3_style(
1289                    &typography,
1290                    |theme| &theme.body_large,
1291                    scheme.on_surface(),
1292                    decoration
1293                )
1294            );
1295            assert_eq!(
1296                selected,
1297                m3_style(
1298                    &typography,
1299                    |theme| &theme.body_large,
1300                    scheme.on_primary(),
1301                    decoration
1302                )
1303            );
1304
1305            let (color, shape) = text_material(tester, "7");
1306            assert_eq!(color, Some(scheme.primary_container()));
1307            assert_eq!(shape, Some(ShapeBorderRef::new(rounded(8.0))));
1308            let (color, shape) = text_material(tester, "15");
1309            assert_eq!(color, Some(scheme.surface_container_highest()));
1310            assert_eq!(shape, Some(ShapeBorderRef::new(rounded(8.0))));
1311
1312            let (am_color, am_shape) = text_material(tester, "AM");
1313            assert_eq!(am_color, Some(scheme.tertiary_container()));
1314            let (pm_color, pm_shape) = text_material(tester, "PM");
1315            assert_eq!(pm_color, Some(Colors::TRANSPARENT));
1316            assert_eq!(am_shape, rounded_with_side(scheme.outline(), true, 8.0));
1317            assert_eq!(pm_shape, rounded_with_side(scheme.outline(), false, 8.0));
1318
1319            assert_eq!(entry_mode_icon_color(tester), None);
1320
1321            let default_style = TextButton::style_from().build();
1322            assert_eq!(action_button_style(tester, "Cancel"), default_style);
1323            assert_eq!(action_button_style(tester, "OK"), default_style);
1324        });
1325    }
1326
1327    fn outline_border(side_color: Color, width: f64, radius: Option<f64>) -> OutlineInputBorder {
1328        let border = OutlineInputBorder::new().border_side(BorderSide {
1329            color: side_color,
1330            width,
1331            ..BorderSide::default()
1332        });
1333        match radius {
1334            Some(radius) => border.border_radius(BorderRadius::circular(radius)),
1335            None => border,
1336        }
1337    }
1338
1339    fn assert_borders(
1340        decoration: &crate::input_decorator::InputDecoration,
1341        scheme: &crate::color_scheme::ColorScheme,
1342        radius: Option<f64>,
1343    ) {
1344        assert_eq!(
1345            decoration.enabled_border,
1346            Some(outline_border(Colors::TRANSPARENT, 1.0, radius).into())
1347        );
1348        assert_eq!(
1349            decoration.error_border,
1350            Some(outline_border(scheme.error(), 2.0, radius).into())
1351        );
1352        assert_eq!(
1353            decoration.focused_border,
1354            Some(outline_border(scheme.primary(), 2.0, radius).into())
1355        );
1356        assert_eq!(
1357            decoration.focused_error_border,
1358            Some(outline_border(scheme.error(), 2.0, radius).into())
1359        );
1360    }
1361
1362    fn resolved(color: &Option<AnyColor>) -> Option<Color> {
1363        color
1364            .as_ref()
1365            .map(|color| resolve(color, &WidgetStates::new()))
1366    }
1367
1368    #[test]
1369    fn material2_passing_no_time_picker_theme_data_uses_defaults_input_mode() {
1370        test_widgets(|tester| {
1371            let default_theme = m2(&tester.cell.borrow());
1372            launch(tester, default_theme.clone(), TimePickerEntryMode::Input);
1373            let scheme = &default_theme.color_scheme;
1374            let typography = Typography::material2014().build();
1375
1376            let decoration = text_field(tester, "7")
1377                .decoration
1378                .expect("a decorated field");
1379            assert_eq!(decoration.filled, Some(true));
1380            assert_eq!(
1381                resolved(&decoration.fill_color),
1382                Some(opacity(scheme.on_surface(), 0.12))
1383            );
1384            assert_borders(&decoration, scheme, None);
1385            let hint_style = typography
1386                .english_like
1387                .display_medium
1388                .as_ref()
1389                .expect("a display medium")
1390                .merge(Some(
1391                    &default_theme
1392                        .text_theme
1393                        .display_medium
1394                        .as_ref()
1395                        .expect("a display medium")
1396                        .copy_with()
1397                        .color(opacity(scheme.on_surface(), 0.36)),
1398                ));
1399            assert_eq!(
1400                decoration
1401                    .hint_style
1402                    .as_ref()
1403                    .map(|style| style.value().clone()),
1404                Some(hint_style)
1405            );
1406
1407            let default_style = TextButton::style_from().build();
1408            assert_eq!(action_button_style(tester, "CANCEL"), default_style);
1409            assert_eq!(action_button_style(tester, "OK"), default_style);
1410        });
1411    }
1412
1413    #[test]
1414    fn material3_passing_no_time_picker_theme_data_uses_defaults_input_mode() {
1415        test_widgets(|tester| {
1416            let default_theme = m3(&tester.cell.borrow());
1417            launch(tester, default_theme.clone(), TimePickerEntryMode::Input);
1418            let scheme = &default_theme.color_scheme;
1419            let typography = Typography::material2021().build();
1420
1421            let expected = m3_style(
1422                &typography,
1423                |theme| &theme.display_medium,
1424                scheme.on_surface(),
1425                scheme.on_surface(),
1426            );
1427            let field = text_field(tester, "7");
1428            assert_eq!(
1429                field.style.as_ref().map(|style| style.value().clone()),
1430                Some(expected.clone())
1431            );
1432            assert_eq!(
1433                text_field(tester, "15")
1434                    .style
1435                    .as_ref()
1436                    .map(|style| style.value().clone()),
1437                Some(expected)
1438            );
1439
1440            let decoration = field.decoration.expect("a decorated field");
1441            assert_eq!(decoration.filled, Some(true));
1442            assert_eq!(
1443                resolved(&decoration.fill_color),
1444                Some(scheme.surface_container_highest())
1445            );
1446            assert_borders(&decoration, scheme, Some(8.0));
1447            assert_eq!(
1448                decoration
1449                    .hint_style
1450                    .as_ref()
1451                    .map(|style| style.value().clone()),
1452                Some(TextStyle::new().color(opacity(scheme.on_surface(), 0.36)))
1453            );
1454
1455            let default_style = TextButton::style_from().build();
1456            assert_eq!(action_button_style(tester, "Cancel"), default_style);
1457            assert_eq!(action_button_style(tester, "OK"), default_style);
1458        });
1459    }
1460
1461    fn themed(theme_data: ThemeData, time_picker_theme: &TimePickerThemeData) -> ThemeData {
1462        theme_data
1463            .copy_with()
1464            .time_picker_theme(time_picker_theme.clone())
1465            .build()
1466    }
1467
1468    fn resolved_color(color: &Option<AnyColor>) -> Option<Color> {
1469        color.as_ref().map(|color| color.color())
1470    }
1471
1472    fn style_value(style: &Option<AnyTextStyle>) -> TextStyle {
1473        style.as_ref().expect("a text style").value().clone()
1474    }
1475
1476    /// What "Time picker uses values from TimePickerThemeData" asserts of both designs: the
1477    /// dialog, the dial, the hour and minute and day period materials, the entry mode icon and
1478    /// the action buttons.
1479    fn assert_theme_values(
1480        tester: &WidgetTester,
1481        theme: &TimePickerThemeData,
1482        entry_mode_icon_color_expected: Option<Color>,
1483        cancel: &str,
1484    ) {
1485        let (color, shape) = dialog_material(tester);
1486        assert_eq!(color, resolved_color(&theme.background_color));
1487        assert_eq!(shape, theme.shape.clone());
1488
1489        assert_paints(
1490            &dial_ops(tester),
1491            &[
1492                PaintCall::circle(Some(
1493                    resolved_color(&theme.dial_background_color).expect("a dial color"),
1494                )),
1495                PaintCall::circle(Some(
1496                    resolved_color(&theme.dial_hand_color).expect("a hand color"),
1497                )),
1498            ],
1499        );
1500
1501        let (color, shape) = text_material(tester, "7");
1502        assert_eq!(color, Some(selected_color()));
1503        assert_eq!(shape, theme.hour_minute_shape.clone());
1504        let (color, shape) = text_material(tester, "15");
1505        assert_eq!(color, Some(unselected_color()));
1506        assert_eq!(shape, theme.hour_minute_shape.clone());
1507
1508        let (am_color, am_shape) = text_material(tester, "AM");
1509        assert_eq!(am_color, Some(selected_color()));
1510        let (pm_color, pm_shape) = text_material(tester, "PM");
1511        assert_eq!(pm_color, Some(unselected_color()));
1512        let side = theme.day_period_border_side.expect("a border side").color;
1513        assert_eq!(am_shape, rounded_with_side(side, true, 16.0));
1514        assert_eq!(pm_shape, rounded_with_side(side, false, 16.0));
1515
1516        assert_eq!(
1517            entry_mode_icon_color(tester),
1518            entry_mode_icon_color_expected
1519        );
1520        assert_eq!(
1521            action_button_style(tester, cancel),
1522            theme.cancel_button_style.clone().expect("a cancel style")
1523        );
1524        assert_eq!(
1525            action_button_style(tester, "OK"),
1526            theme.confirm_button_style.clone().expect("a confirm style")
1527        );
1528    }
1529
1530    #[test]
1531    fn material2_time_picker_uses_values_from_time_picker_theme_data() {
1532        test_widgets(|tester| {
1533            let theme = time_picker_theme(false);
1534            let theme_data = themed(m2(&tester.cell.borrow()), &theme);
1535            launch(tester, theme_data, TimePickerEntryMode::Dial);
1536            let typography = Typography::material2014().build();
1537
1538            assert_theme_values(
1539                tester,
1540                &theme,
1541                resolved_color(&theme.entry_mode_icon_color),
1542                "CANCEL",
1543            );
1544
1545            let with_theme = |field: fn(&TextTheme) -> &Option<TextStyle>,
1546                              themed_style: &Option<AnyTextStyle>,
1547                              color: Color| {
1548                base_style(&typography, false, field)
1549                    .merge(Some(&style_value(themed_style)))
1550                    .copy_with()
1551                    .color(color)
1552            };
1553            assert_eq!(
1554                paragraph_style(tester, "7"),
1555                with_theme(
1556                    |theme| &theme.body_medium,
1557                    &theme.hour_minute_text_style,
1558                    selected_color()
1559                )
1560            );
1561            assert_eq!(
1562                paragraph_style(tester, "15"),
1563                with_theme(
1564                    |theme| &theme.body_medium,
1565                    &theme.hour_minute_text_style,
1566                    unselected_color()
1567                )
1568            );
1569            assert_eq!(
1570                paragraph_style(tester, "AM"),
1571                with_theme(
1572                    |theme| &theme.title_medium,
1573                    &theme.day_period_text_style,
1574                    selected_color()
1575                )
1576            );
1577            assert_eq!(
1578                paragraph_style(tester, "PM"),
1579                with_theme(
1580                    |theme| &theme.title_medium,
1581                    &theme.day_period_text_style,
1582                    unselected_color()
1583                )
1584            );
1585            assert_eq!(
1586                paragraph_style(tester, "SELECT TIME"),
1587                base_style(&typography, false, |theme| &theme.body_medium)
1588                    .merge(Some(&style_value(&theme.help_text_style)))
1589            );
1590
1591            let (primary, selected) = dial_label_styles(tester);
1592            assert_eq!(
1593                primary,
1594                base_style(&typography, false, |theme| &theme.body_large)
1595                    .copy_with()
1596                    .color(unselected_color())
1597            );
1598            assert_eq!(
1599                selected,
1600                base_style(&typography, true, |theme| &theme.body_large)
1601                    .copy_with()
1602                    .color(selected_color())
1603            );
1604        });
1605    }
1606
1607    #[test]
1608    fn material3_time_picker_uses_values_from_time_picker_theme_data() {
1609        test_widgets(|tester| {
1610            let theme = time_picker_theme(false);
1611            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1612            launch(tester, theme_data.clone(), TimePickerEntryMode::Dial);
1613            let typography = Typography::material2021().build();
1614            let decoration_color = Color::new(0xff1d1b20);
1615            let on_surface = theme_data.color_scheme.on_surface();
1616
1617            assert_theme_values(tester, &theme, None, "Cancel");
1618
1619            let hour_minute = |color: Color| {
1620                base_style(&typography, false, |theme| &theme.body_medium)
1621                    .merge(Some(&style_value(&theme.hour_minute_text_style)))
1622                    .copy_with()
1623                    .color(color)
1624                    .decoration_color(decoration_color)
1625            };
1626            assert_eq!(paragraph_style(tester, "7"), hour_minute(selected_color()));
1627            assert_eq!(
1628                paragraph_style(tester, "15"),
1629                hour_minute(unselected_color())
1630            );
1631            assert_eq!(paragraph_style(tester, "AM"), hour_minute(selected_color()));
1632            assert_eq!(
1633                paragraph_style(tester, "PM"),
1634                hour_minute(unselected_color())
1635            );
1636            assert_eq!(
1637                paragraph_style(tester, "Select time"),
1638                base_style(&typography, false, |theme| &theme.body_medium)
1639                    .merge(Some(&style_value(&theme.help_text_style)))
1640                    .copy_with()
1641                    .color(on_surface)
1642                    .decoration_color(on_surface)
1643            );
1644
1645            let (primary, selected) = dial_label_styles(tester);
1646            assert_eq!(
1647                primary,
1648                base_style(&typography, false, |theme| &theme.body_large)
1649                    .copy_with()
1650                    .color(unselected_color())
1651                    .decoration_color(on_surface)
1652            );
1653            assert_eq!(
1654                selected,
1655                base_style(&typography, false, |theme| &theme.body_large)
1656                    .copy_with()
1657                    .color(selected_color())
1658                    .decoration_color(on_surface)
1659            );
1660        });
1661    }
1662
1663    #[test]
1664    fn time_picker_uses_values_from_time_picker_theme_data_when_input_decoration_theme_is_provided_input_mode()
1665     {
1666        test_widgets(|tester| {
1667            let theme = time_picker_theme(true);
1668            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1669            launch(tester, theme_data, TimePickerEntryMode::Input);
1670
1671            let decoration = text_field(tester, "7")
1672                .decoration
1673                .expect("a decorated field");
1674            let input = theme
1675                .input_decoration_theme
1676                .expect("an input decoration theme");
1677            assert_eq!(decoration.filled, Some(input.filled));
1678            assert_eq!(decoration.fill_color, input.fill_color);
1679            assert_eq!(decoration.enabled_border, input.enabled_border);
1680            assert_eq!(decoration.error_border, input.error_border);
1681            assert_eq!(decoration.focused_border, input.focused_border);
1682            assert_eq!(decoration.focused_error_border, input.focused_error_border);
1683            assert_eq!(decoration.hint_style, input.hint_style);
1684        });
1685    }
1686
1687    #[test]
1688    fn time_picker_uses_values_from_time_picker_theme_data_when_input_decoration_theme_is_not_provided_input_mode()
1689     {
1690        test_widgets(|tester| {
1691            let theme = time_picker_theme(false);
1692            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1693            launch(tester, theme_data, TimePickerEntryMode::Input);
1694
1695            let decoration = text_field(tester, "7")
1696                .decoration
1697                .expect("a decorated field");
1698            let fill = decoration.fill_color.expect("a fill color");
1699            let hour_minute = theme.hour_minute_color.expect("an hour minute color");
1700            // Dart compares the `value`s of the two colors; the picker resolves the theme's
1701            // color with the focus states, so the unfocused color is compared.
1702            let states = WidgetStates::new();
1703            assert_eq!(resolve(&fill, &states), resolve(&hour_minute, &states));
1704        });
1705    }
1706
1707    #[test]
1708    fn time_picker_day_period_color_does_the_right_thing_with_non_widget_state_color() {
1709        test_widgets(|tester| {
1710            let theme = time_picker_theme(false).day_period_color(Colors::RED.primary());
1711            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1712            launch(tester, theme_data, TimePickerEntryMode::Input);
1713
1714            assert_eq!(text_material(tester, "AM").0, Some(Colors::RED.primary()));
1715            assert_eq!(text_material(tester, "PM").0, Some(Colors::TRANSPARENT));
1716        });
1717    }
1718
1719    #[test]
1720    fn time_picker_day_period_color_does_the_right_thing_with_widget_state_color() {
1721        test_widgets(|tester| {
1722            let test_color = WidgetStateColor::resolve_with(|states| {
1723                if states.contains(&WidgetState::Selected) {
1724                    Colors::GREEN.primary()
1725                } else {
1726                    Colors::BLUE.primary()
1727                }
1728            });
1729            let theme = time_picker_theme(false).day_period_color(test_color);
1730            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1731            launch(tester, theme_data, TimePickerEntryMode::Input);
1732
1733            assert_eq!(text_material(tester, "AM").0, Some(Colors::GREEN.primary()));
1734            assert_eq!(text_material(tester, "PM").0, Some(Colors::BLUE.primary()));
1735        });
1736    }
1737
1738    #[test]
1739    fn time_selector_separator_color_uses_the_time_selector_separator_color_value() {
1740        test_widgets(|tester| {
1741            let theme = time_picker_theme(false).time_selector_separator_color(Rc::new(
1742                WidgetStatePropertyAll::new(Some(Color::new(0xff00ff00))),
1743            ));
1744            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1745            launch(tester, theme_data, TimePickerEntryMode::Input);
1746
1747            assert_eq!(
1748                color_of(&paragraph_style(tester, ":")),
1749                Some(Color::new(0xff00ff00))
1750            );
1751        });
1752    }
1753
1754    #[test]
1755    fn time_selector_separator_text_style_uses_the_time_selector_separator_text_style_value() {
1756        test_widgets(|tester| {
1757            let theme = time_picker_theme(false).time_selector_separator_text_style(Rc::new(
1758                WidgetStatePropertyAll::new(Some(
1759                    TextStyle::new()
1760                        .font_size(35.0)
1761                        .font_style(FontStyle::Italic),
1762                )),
1763            ));
1764            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1765            launch(tester, theme_data, TimePickerEntryMode::Input);
1766
1767            let style = paragraph_style(tester, ":");
1768            assert_eq!(style.font_size, Some(35.0));
1769            assert_eq!(style.font_style, Some(FontStyle::Italic));
1770        });
1771    }
1772
1773    fn border_painter_size(tester: &WidgetTester) -> Size {
1774        tester.get_size(
1775            find::descendant(
1776                find::by_type::<crate::input_decorator::InputDecorator>().first(),
1777                find::by_type::<waft_widgets::CustomPaint>(),
1778            )
1779            .first(),
1780        )
1781    }
1782
1783    fn enter_invalid_hour_and_tap_ok(tester: &mut WidgetTester) {
1784        tester.enter_text(find::by_type::<waft_widgets::EditableText>().at(0), "AB");
1785        let ok = text_element(tester, "OK");
1786        let center = tester.get_center(ok);
1787        tester.tap_at(center, 1);
1788    }
1789
1790    #[test]
1791    fn time_picker_hour_minute_does_not_resize_on_error() {
1792        test_widgets(|tester| {
1793            let theme = time_picker_theme(true);
1794            let theme_data = themed(m3(&tester.cell.borrow()), &theme);
1795            launch(tester, theme_data, TimePickerEntryMode::Input);
1796
1797            assert_eq!(border_painter_size(tester), Size::new(96.0, 72.0));
1798
1799            enter_invalid_hour_and_tap_ok(tester);
1800
1801            assert_eq!(border_painter_size(tester), Size::new(96.0, 72.0));
1802        });
1803    }
1804
1805    #[test]
1806    fn material2_time_picker_hour_minute_does_not_resize_on_error() {
1807        test_widgets(|tester| {
1808            let theme = time_picker_theme(true);
1809            let theme_data = themed(m2(&tester.cell.borrow()), &theme);
1810            launch(tester, theme_data, TimePickerEntryMode::Input);
1811
1812            assert_eq!(border_painter_size(tester), Size::new(96.0, 70.0));
1813
1814            enter_invalid_hour_and_tap_ok(tester);
1815
1816            assert_eq!(border_painter_size(tester), Size::new(96.0, 70.0));
1817        });
1818    }
1819    // Flutter's "Default TimePickerThemeData debugFillProperties".
1820    #[test]
1821    fn a_time_picker_theme_data_describes_nothing_by_default() {
1822        assert_eq!(
1823            waft_widgets::testing::describe_properties(|properties| {
1824                waft_foundation::Diagnosticable::debug_fill_properties(
1825                    &TimePickerThemeData::new(),
1826                    properties,
1827                )
1828            }),
1829            Vec::<String>::new()
1830        );
1831    }
1832}