Skip to main content

waft_material/
dialog_theme.rs

1//! Flutter counterpart: material_ui's `dialog_theme.dart`.
2
3use waft_embedder::{Clip, Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{
6    AlignmentGeometry, ColorProperty, EdgeInsets, EdgeInsetsGeometry, ShapeBorderRef, TextStyle,
7};
8use waft_rendering::BoxConstraints;
9use waft_widgets::{
10    BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, SizedBox, WidgetRef,
11};
12
13use crate::theme::Theme;
14
15/// Defines a theme for `Dialog` widgets.
16///
17/// Descendant widgets obtain the current [`DialogThemeData`] object using
18/// [`DialogTheme::of`]. Instances of [`DialogThemeData`] can be customized with
19/// [`DialogThemeData::copy_with`].
20///
21/// [`title_text_style`](Self::title_text_style) and
22/// [`content_text_style`](Self::content_text_style) are used in `AlertDialog`s and
23/// `SimpleDialog`s.
24///
25/// Dart's `DialogTheme` constructor takes either the properties or a [`data`](Self::data);
26/// here the properties are the `with_*` setters and [`with_data`](Self::with_data) the other,
27/// and each setter that breaks Dart's constructor assert (a `data` together with any property)
28/// fails in a debug build. The getters are methods, as Dart's, hence the `with_` prefix.
29///
30/// See also:
31///
32///  * `Dialog`, a dialog that can be customized using this [`DialogTheme`].
33///  * `AlertDialog`, a dialog that can be customized using this [`DialogTheme`].
34///  * `SimpleDialog`, a dialog that can be customized using this [`DialogTheme`].
35///  * `ThemeData`, which describes the overall theme information for the
36///    application.
37#[derive(Clone, Debug)]
38pub struct DialogTheme {
39    pub key: Option<KeyRef>,
40    data: Option<DialogThemeData>,
41    background_color: Option<Color>,
42    elevation: Option<f64>,
43    shadow_color: Option<Color>,
44    surface_tint_color: Option<Color>,
45    shape: Option<ShapeBorderRef>,
46    alignment: Option<AlignmentGeometry>,
47    title_text_style: Option<TextStyle>,
48    content_text_style: Option<TextStyle>,
49    actions_padding: Option<EdgeInsetsGeometry>,
50    icon_color: Option<Color>,
51    barrier_color: Option<Color>,
52    inset_padding: Option<EdgeInsets>,
53    clip_behavior: Option<Clip>,
54    child: WidgetRef,
55}
56
57impl DialogTheme {
58    /// Creates a dialog theme that can be used for `ThemeData::dialog_theme`.
59    pub fn new() -> DialogTheme {
60        DialogTheme {
61            key: None,
62            data: None,
63            background_color: None,
64            elevation: None,
65            shadow_color: None,
66            surface_tint_color: None,
67            shape: None,
68            alignment: None,
69            title_text_style: None,
70            content_text_style: None,
71            actions_padding: None,
72            icon_color: None,
73            barrier_color: None,
74            inset_padding: None,
75            clip_behavior: None,
76            child: SizedBox::new().into_widget(),
77        }
78    }
79
80    /// Dart `DialogTheme(key:)`.
81    pub fn key(mut self, key: KeyRef) -> DialogTheme {
82        self.key = Some(key);
83        self
84    }
85
86    /// Dart `DialogTheme(child:)`; the default is an empty `SizedBox`.
87    #[cfg_attr(debug_assertions, track_caller)]
88    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> DialogTheme {
89        self.child = child.into_widget();
90        self
91    }
92
93    /// Dart `DialogTheme(data:)`.
94    pub fn with_data(mut self, data: DialogThemeData) -> DialogTheme {
95        debug_assert!(self.has_no_property());
96        self.data = Some(data);
97        self
98    }
99
100    /// Dart `DialogTheme(backgroundColor:)`.
101    pub fn with_background_color(mut self, background_color: Color) -> DialogTheme {
102        debug_assert!(self.data.is_none());
103        self.background_color = Some(background_color);
104        self
105    }
106
107    /// Dart `DialogTheme(elevation:)`.
108    pub fn with_elevation(mut self, elevation: f64) -> DialogTheme {
109        debug_assert!(self.data.is_none());
110        self.elevation = Some(elevation);
111        self
112    }
113
114    /// Dart `DialogTheme(shadowColor:)`.
115    pub fn with_shadow_color(mut self, shadow_color: Color) -> DialogTheme {
116        debug_assert!(self.data.is_none());
117        self.shadow_color = Some(shadow_color);
118        self
119    }
120
121    /// Dart `DialogTheme(surfaceTintColor:)`.
122    pub fn with_surface_tint_color(mut self, surface_tint_color: Color) -> DialogTheme {
123        debug_assert!(self.data.is_none());
124        self.surface_tint_color = Some(surface_tint_color);
125        self
126    }
127
128    /// Dart `DialogTheme(shape:)`.
129    pub fn with_shape(mut self, shape: impl Into<ShapeBorderRef>) -> DialogTheme {
130        debug_assert!(self.data.is_none());
131        self.shape = Some(shape.into());
132        self
133    }
134
135    /// Dart `DialogTheme(alignment:)`.
136    pub fn with_alignment(mut self, alignment: AlignmentGeometry) -> DialogTheme {
137        debug_assert!(self.data.is_none());
138        self.alignment = Some(alignment);
139        self
140    }
141
142    /// Dart `DialogTheme(iconColor:)`.
143    pub fn with_icon_color(mut self, icon_color: Color) -> DialogTheme {
144        debug_assert!(self.data.is_none());
145        self.icon_color = Some(icon_color);
146        self
147    }
148
149    /// Dart `DialogTheme(titleTextStyle:)`.
150    pub fn with_title_text_style(mut self, title_text_style: TextStyle) -> DialogTheme {
151        debug_assert!(self.data.is_none());
152        self.title_text_style = Some(title_text_style);
153        self
154    }
155
156    /// Dart `DialogTheme(contentTextStyle:)`.
157    pub fn with_content_text_style(mut self, content_text_style: TextStyle) -> DialogTheme {
158        debug_assert!(self.data.is_none());
159        self.content_text_style = Some(content_text_style);
160        self
161    }
162
163    /// Dart `DialogTheme(actionsPadding:)`.
164    pub fn with_actions_padding(
165        mut self,
166        actions_padding: impl Into<EdgeInsetsGeometry>,
167    ) -> DialogTheme {
168        let actions_padding = actions_padding.into();
169        debug_assert!(self.data.is_none());
170        self.actions_padding = Some(actions_padding);
171        self
172    }
173
174    /// Dart `DialogTheme(barrierColor:)`.
175    pub fn with_barrier_color(mut self, barrier_color: Color) -> DialogTheme {
176        debug_assert!(self.data.is_none());
177        self.barrier_color = Some(barrier_color);
178        self
179    }
180
181    /// Dart `DialogTheme(insetPadding:)`.
182    pub fn with_inset_padding(mut self, inset_padding: EdgeInsets) -> DialogTheme {
183        debug_assert!(self.data.is_none());
184        self.inset_padding = Some(inset_padding);
185        self
186    }
187
188    /// Dart `DialogTheme(clipBehavior:)`.
189    pub fn with_clip_behavior(mut self, clip_behavior: Clip) -> DialogTheme {
190        debug_assert!(self.data.is_none());
191        self.clip_behavior = Some(clip_behavior);
192        self
193    }
194
195    /// Overrides the default value for `Dialog::background_color`.
196    ///
197    /// This property is obsolete and will be deprecated in a future release:
198    /// please use the [`DialogThemeData::background_color`] property in [`data`](Self::data)
199    /// instead.
200    pub fn background_color(&self) -> Option<Color> {
201        match &self.data {
202            Some(data) => data.background_color,
203            None => self.background_color,
204        }
205    }
206
207    /// Overrides the default value for `Dialog::elevation`.
208    ///
209    /// This property is obsolete and will be deprecated in a future release:
210    /// please use the [`DialogThemeData::elevation`] property in [`data`](Self::data) instead.
211    pub fn elevation(&self) -> Option<f64> {
212        match &self.data {
213            Some(data) => data.elevation,
214            None => self.elevation,
215        }
216    }
217
218    /// Overrides the default value for `Dialog::shadow_color`.
219    ///
220    /// This property is obsolete and will be deprecated in a future release:
221    /// please use the [`DialogThemeData::shadow_color`] property in [`data`](Self::data) instead.
222    pub fn shadow_color(&self) -> Option<Color> {
223        match &self.data {
224            Some(data) => data.shadow_color,
225            None => self.shadow_color,
226        }
227    }
228
229    /// Overrides the default value for `Dialog::surface_tint_color`.
230    ///
231    /// This property is obsolete and will be deprecated in a future release:
232    /// please use the [`DialogThemeData::surface_tint_color`] property in [`data`](Self::data)
233    /// instead.
234    pub fn surface_tint_color(&self) -> Option<Color> {
235        match &self.data {
236            Some(data) => data.surface_tint_color,
237            None => self.surface_tint_color,
238        }
239    }
240
241    /// Overrides the default value for `Dialog::shape`.
242    ///
243    /// This property is obsolete and will be deprecated in a future release:
244    /// please use the [`DialogThemeData::shape`] property in [`data`](Self::data) instead.
245    pub fn shape(&self) -> Option<&ShapeBorderRef> {
246        match &self.data {
247            Some(data) => data.shape.as_ref(),
248            None => self.shape.as_ref(),
249        }
250    }
251
252    /// Overrides the default value for `Dialog::alignment`.
253    ///
254    /// This property is obsolete and will be deprecated in a future release:
255    /// please use the [`DialogThemeData::alignment`] property in [`data`](Self::data) instead.
256    pub fn alignment(&self) -> Option<AlignmentGeometry> {
257        match &self.data {
258            Some(data) => data.alignment,
259            None => self.alignment,
260        }
261    }
262
263    /// Overrides the default value for `DefaultTextStyle` for `SimpleDialog::title` and
264    /// `AlertDialog::title`.
265    ///
266    /// This property is obsolete and will be deprecated in a future release:
267    /// please use the [`DialogThemeData::title_text_style`] property in [`data`](Self::data)
268    /// instead.
269    pub fn title_text_style(&self) -> Option<&TextStyle> {
270        match &self.data {
271            Some(data) => data.title_text_style.as_ref(),
272            None => self.title_text_style.as_ref(),
273        }
274    }
275
276    /// Overrides the default value for `DefaultTextStyle` for `SimpleDialog::children` and
277    /// `AlertDialog::content`.
278    ///
279    /// This property is obsolete and will be deprecated in a future release:
280    /// please use the [`DialogThemeData::content_text_style`] property in [`data`](Self::data)
281    /// instead.
282    pub fn content_text_style(&self) -> Option<&TextStyle> {
283        match &self.data {
284            Some(data) => data.content_text_style.as_ref(),
285            None => self.content_text_style.as_ref(),
286        }
287    }
288
289    /// Overrides the default value for `AlertDialog::actions_padding`.
290    ///
291    /// This property is obsolete and will be deprecated in a future release:
292    /// please use the [`DialogThemeData::actions_padding`] property in [`data`](Self::data)
293    /// instead.
294    pub fn actions_padding(&self) -> Option<EdgeInsetsGeometry> {
295        match &self.data {
296            Some(data) => data.actions_padding,
297            None => self.actions_padding,
298        }
299    }
300
301    /// Used to configure the `IconTheme` for the `AlertDialog::icon` widget.
302    ///
303    /// This property is obsolete and will be deprecated in a future release:
304    /// please use the [`DialogThemeData::icon_color`] property in [`data`](Self::data) instead.
305    pub fn icon_color(&self) -> Option<Color> {
306        match &self.data {
307            Some(data) => data.icon_color,
308            None => self.icon_color,
309        }
310    }
311
312    /// Overrides the default value for `barrier_color` in `ShowDialog`.
313    ///
314    /// This property is obsolete and will be deprecated in a future release:
315    /// please use the [`DialogThemeData::barrier_color`] property in [`data`](Self::data)
316    /// instead.
317    pub fn barrier_color(&self) -> Option<Color> {
318        match &self.data {
319            Some(data) => data.barrier_color,
320            None => self.barrier_color,
321        }
322    }
323
324    /// Overrides the default value for `Dialog::inset_padding`.
325    pub fn inset_padding(&self) -> Option<EdgeInsets> {
326        match &self.data {
327            Some(data) => data.inset_padding,
328            None => self.inset_padding,
329        }
330    }
331
332    /// Overrides the default value of `Dialog::clip_behavior`.
333    ///
334    /// This property is obsolete and will be deprecated in a future release:
335    /// please use the [`DialogThemeData::clip_behavior`] property in [`data`](Self::data)
336    /// instead.
337    pub fn clip_behavior(&self) -> Option<Clip> {
338        match &self.data {
339            Some(data) => data.clip_behavior,
340            None => self.clip_behavior,
341        }
342    }
343
344    /// The properties used for all descendant `Dialog` widgets.
345    pub fn data(&self) -> DialogThemeData {
346        self.data.clone().unwrap_or_else(|| DialogThemeData {
347            background_color: self.background_color,
348            elevation: self.elevation,
349            shadow_color: self.shadow_color,
350            surface_tint_color: self.surface_tint_color,
351            shape: self.shape.clone(),
352            alignment: self.alignment,
353            icon_color: self.icon_color,
354            title_text_style: self.title_text_style.clone(),
355            content_text_style: self.content_text_style.clone(),
356            actions_padding: self.actions_padding,
357            barrier_color: self.barrier_color,
358            inset_padding: self.inset_padding,
359            clip_behavior: self.clip_behavior,
360            constraints: None,
361        })
362    }
363
364    /// Retrieves the [`DialogThemeData`] from the closest ancestor [`DialogTheme`].
365    ///
366    /// If there is no enclosing [`DialogTheme`] widget, then
367    /// `Theme::of(context).dialog_theme` is used.
368    pub fn of(app: &mut App, context: BuildContext) -> DialogThemeData {
369        match context.depend_on_inherited_widget_of_exact_type::<DialogTheme>(app) {
370            Some(dialog_theme) => dialog_theme.data(),
371            None => Theme::of(app, context).dialog_theme.clone(),
372        }
373    }
374
375    /// Creates a copy of this object but with the given fields replaced with the
376    /// new values.
377    ///
378    /// This method is obsolete and will be deprecated in a future release:
379    /// please use the [`DialogThemeData::copy_with`] instead.
380    ///
381    /// Dart's named arguments are the fluent setters on the copy
382    /// (`theme.copy_with().with_elevation(2.0)`). As in Dart, the copy carries neither the key
383    /// nor the child, and holds the properties, never a [`data`](Self::data).
384    pub fn copy_with(&self) -> DialogTheme {
385        DialogTheme {
386            key: None,
387            data: None,
388            background_color: self.background_color(),
389            elevation: self.elevation(),
390            shadow_color: self.shadow_color(),
391            surface_tint_color: self.surface_tint_color(),
392            shape: self.shape().cloned(),
393            alignment: self.alignment(),
394            title_text_style: self.title_text_style().cloned(),
395            content_text_style: self.content_text_style().cloned(),
396            actions_padding: self.actions_padding(),
397            icon_color: self.icon_color(),
398            barrier_color: self.barrier_color(),
399            inset_padding: self.inset_padding(),
400            clip_behavior: self.clip_behavior(),
401            child: SizedBox::new().into_widget(),
402        }
403    }
404
405    /// Linearly interpolate between two dialog themes.
406    ///
407    /// {@macro dart.ui.shadow.lerp}
408    ///
409    /// This method is obsolete and will be deprecated in a future release:
410    /// please use the [`DialogThemeData::lerp`] instead.
411    pub fn lerp(a: Option<&DialogTheme>, b: Option<&DialogTheme>, t: f64) -> DialogTheme {
412        if let (Some(a), Some(b)) = (a, b)
413            && std::ptr::eq(a, b)
414        {
415            return a.clone();
416        }
417        DialogTheme {
418            key: None,
419            data: None,
420            background_color: Color::lerp(
421                a.and_then(|a| a.background_color()),
422                b.and_then(|b| b.background_color()),
423                t,
424            ),
425            elevation: lerp_double(
426                a.and_then(|a| a.elevation()),
427                b.and_then(|b| b.elevation()),
428                t,
429            ),
430            shadow_color: Color::lerp(
431                a.and_then(|a| a.shadow_color()),
432                b.and_then(|b| b.shadow_color()),
433                t,
434            ),
435            surface_tint_color: Color::lerp(
436                a.and_then(|a| a.surface_tint_color()),
437                b.and_then(|b| b.surface_tint_color()),
438                t,
439            ),
440            shape: ShapeBorderRef::lerp(a.and_then(|a| a.shape()), b.and_then(|b| b.shape()), t),
441            alignment: AlignmentGeometry::lerp(
442                a.and_then(|a| a.alignment()),
443                b.and_then(|b| b.alignment()),
444                t,
445            ),
446            icon_color: Color::lerp(
447                a.and_then(|a| a.icon_color()),
448                b.and_then(|b| b.icon_color()),
449                t,
450            ),
451            title_text_style: TextStyle::lerp(
452                a.and_then(|a| a.title_text_style()),
453                b.and_then(|b| b.title_text_style()),
454                t,
455            ),
456            content_text_style: TextStyle::lerp(
457                a.and_then(|a| a.content_text_style()),
458                b.and_then(|b| b.content_text_style()),
459                t,
460            ),
461            actions_padding: EdgeInsetsGeometry::lerp(
462                a.and_then(|a| a.actions_padding()),
463                b.and_then(|b| b.actions_padding()),
464                t,
465            ),
466            barrier_color: Color::lerp(
467                a.and_then(|a| a.barrier_color()),
468                b.and_then(|b| b.barrier_color()),
469                t,
470            ),
471            inset_padding: EdgeInsets::lerp(
472                a.and_then(|a| a.inset_padding()),
473                b.and_then(|b| b.inset_padding()),
474                t,
475            ),
476            clip_behavior: if t < 0.5 {
477                a.and_then(|a| a.clip_behavior())
478            } else {
479                b.and_then(|b| b.clip_behavior())
480            },
481            child: SizedBox::new().into_widget(),
482        }
483    }
484
485    /// Dart's constructor assert: a `data` takes the place of every property.
486    fn has_no_property(&self) -> bool {
487        self.background_color.is_none()
488            && self.elevation.is_none()
489            && self.shadow_color.is_none()
490            && self.surface_tint_color.is_none()
491            && self.shape.is_none()
492            && self.alignment.is_none()
493            && self.icon_color.is_none()
494            && self.title_text_style.is_none()
495            && self.content_text_style.is_none()
496            && self.actions_padding.is_none()
497            && self.barrier_color.is_none()
498            && self.inset_padding.is_none()
499            && self.clip_behavior.is_none()
500    }
501}
502
503impl Default for DialogTheme {
504    fn default() -> DialogTheme {
505        DialogTheme::new()
506    }
507}
508
509impl InheritedTheme for DialogTheme {
510    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
511        DialogTheme::new()
512            .with_data(self.data())
513            .child(child)
514            .into_widget()
515    }
516}
517
518impl InheritedWidget for DialogTheme {
519    fn key(&self) -> Option<&KeyRef> {
520        self.key.as_ref()
521    }
522
523    fn debug_fill_properties(
524        &self,
525        _app: &App,
526        properties: &mut waft_foundation::DiagnosticPropertiesBuilder,
527    ) {
528        self.data()
529            .debug_fill_properties_without_constraints(properties);
530    }
531
532    fn child(&self) -> &WidgetRef {
533        &self.child
534    }
535
536    fn update_should_notify(&self, old_widget: &DialogTheme) -> bool {
537        self.data() != old_widget.data()
538    }
539
540    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
541        Some(self)
542    }
543}
544
545/// Defines default property values for descendant `Dialog` widgets.
546///
547/// Descendant widgets obtain the current [`DialogThemeData`] object using
548/// [`DialogTheme::of`]. Instances of [`DialogThemeData`] can be
549/// customized with [`DialogThemeData::copy_with`].
550///
551/// Typically a [`DialogThemeData`] is specified as part of the overall `Theme`
552/// with `ThemeData::dialog_theme`.
553///
554/// All [`DialogThemeData`] properties are `null` by default. When null, the `Dialog`
555/// will use the values from `ThemeData` if they exist, otherwise it will
556/// provide its own defaults. See the individual `Dialog` properties for details.
557///
558/// See also:
559///
560///  * `Dialog`, a dialog that can be customized using this [`DialogTheme`].
561///  * `AlertDialog`, a dialog that can be customized using this [`DialogTheme`].
562///  * `SimpleDialog`, a dialog that can be customized using this [`DialogTheme`].
563///  * `ThemeData`, which describes the overall theme information for the
564///    application.
565#[derive(Clone, Debug, Default, PartialEq)]
566pub struct DialogThemeData {
567    /// Overrides the default value for `Dialog::background_color`.
568    pub background_color: Option<Color>,
569
570    /// Overrides the default value for `Dialog::elevation`.
571    pub elevation: Option<f64>,
572
573    /// Overrides the default value for `Dialog::shadow_color`.
574    pub shadow_color: Option<Color>,
575
576    /// Overrides the default value for `Dialog::surface_tint_color`.
577    pub surface_tint_color: Option<Color>,
578
579    /// Overrides the default value for `Dialog::shape`.
580    pub shape: Option<ShapeBorderRef>,
581
582    /// Overrides the default value for `Dialog::alignment`.
583    pub alignment: Option<AlignmentGeometry>,
584
585    /// Overrides the default value for `DefaultTextStyle` for `SimpleDialog::title` and
586    /// `AlertDialog::title`.
587    pub title_text_style: Option<TextStyle>,
588
589    /// Overrides the default value for `DefaultTextStyle` for `SimpleDialog::children` and
590    /// `AlertDialog::content`.
591    pub content_text_style: Option<TextStyle>,
592
593    /// Overrides the default value for `AlertDialog::actions_padding`.
594    pub actions_padding: Option<EdgeInsetsGeometry>,
595
596    /// Used to configure the `IconTheme` for the `AlertDialog::icon` widget.
597    pub icon_color: Option<Color>,
598
599    /// Overrides the default value for `barrier_color` in `ShowDialog`.
600    pub barrier_color: Option<Color>,
601
602    /// Overrides the default value for `Dialog::inset_padding`.
603    pub inset_padding: Option<EdgeInsets>,
604
605    /// Overrides the default value of `Dialog::clip_behavior`.
606    pub clip_behavior: Option<Clip>,
607
608    /// Constrains the size of the `Dialog`.
609    ///
610    /// If null, the bottom sheet's size will be unconstrained.
611    pub constraints: Option<BoxConstraints>,
612}
613
614crate::theme_data_getters::theme_data_getters! {
615    /// Dart's getters of `DialogThemeData`: the theme data answers with its fields, and a defaults
616    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
617    /// are read.
618    pub trait DialogThemeDataGetters for DialogThemeData, fields: dialog_theme_data {
619        background_color: Option<Color>,
620        elevation: Option<f64>,
621        shadow_color: Option<Color>,
622        surface_tint_color: Option<Color>,
623        shape: Option<ShapeBorderRef>,
624        alignment: Option<AlignmentGeometry>,
625        title_text_style: Option<TextStyle>,
626        content_text_style: Option<TextStyle>,
627        actions_padding: Option<EdgeInsetsGeometry>,
628        icon_color: Option<Color>,
629        barrier_color: Option<Color>,
630        inset_padding: Option<EdgeInsets>,
631        clip_behavior: Option<Clip>,
632        constraints: Option<BoxConstraints>,
633    }
634}
635
636impl DialogThemeData {
637    /// Creates a dialog theme that can be used for `ThemeData::dialog_theme`.
638    pub fn new() -> DialogThemeData {
639        DialogThemeData::default()
640    }
641
642    /// Dart `DialogThemeData(backgroundColor:)`.
643    pub fn background_color(mut self, background_color: Color) -> DialogThemeData {
644        self.background_color = Some(background_color);
645        self
646    }
647
648    /// Dart `DialogThemeData(elevation:)`.
649    pub fn elevation(mut self, elevation: f64) -> DialogThemeData {
650        self.elevation = Some(elevation);
651        self
652    }
653
654    /// Dart `DialogThemeData(shadowColor:)`.
655    pub fn shadow_color(mut self, shadow_color: Color) -> DialogThemeData {
656        self.shadow_color = Some(shadow_color);
657        self
658    }
659
660    /// Dart `DialogThemeData(surfaceTintColor:)`.
661    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> DialogThemeData {
662        self.surface_tint_color = Some(surface_tint_color);
663        self
664    }
665
666    /// Dart `DialogThemeData(shape:)`.
667    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> DialogThemeData {
668        self.shape = Some(shape.into());
669        self
670    }
671
672    /// Dart `DialogThemeData(alignment:)`.
673    pub fn alignment(mut self, alignment: AlignmentGeometry) -> DialogThemeData {
674        self.alignment = Some(alignment);
675        self
676    }
677
678    /// Dart `DialogThemeData(iconColor:)`.
679    pub fn icon_color(mut self, icon_color: Color) -> DialogThemeData {
680        self.icon_color = Some(icon_color);
681        self
682    }
683
684    /// Dart `DialogThemeData(titleTextStyle:)`.
685    pub fn title_text_style(mut self, title_text_style: TextStyle) -> DialogThemeData {
686        self.title_text_style = Some(title_text_style);
687        self
688    }
689
690    /// Dart `DialogThemeData(contentTextStyle:)`.
691    pub fn content_text_style(mut self, content_text_style: TextStyle) -> DialogThemeData {
692        self.content_text_style = Some(content_text_style);
693        self
694    }
695
696    /// Dart `DialogThemeData(actionsPadding:)`.
697    pub fn actions_padding(
698        mut self,
699        actions_padding: impl Into<EdgeInsetsGeometry>,
700    ) -> DialogThemeData {
701        let actions_padding = actions_padding.into();
702        self.actions_padding = Some(actions_padding);
703        self
704    }
705
706    /// Dart `DialogThemeData(barrierColor:)`.
707    pub fn barrier_color(mut self, barrier_color: Color) -> DialogThemeData {
708        self.barrier_color = Some(barrier_color);
709        self
710    }
711
712    /// Dart `DialogThemeData(insetPadding:)`.
713    pub fn inset_padding(mut self, inset_padding: EdgeInsets) -> DialogThemeData {
714        self.inset_padding = Some(inset_padding);
715        self
716    }
717
718    /// Dart `DialogThemeData(clipBehavior:)`.
719    pub fn clip_behavior(mut self, clip_behavior: Clip) -> DialogThemeData {
720        self.clip_behavior = Some(clip_behavior);
721        self
722    }
723
724    /// Dart `DialogThemeData(constraints:)`.
725    pub fn constraints(mut self, constraints: BoxConstraints) -> DialogThemeData {
726        self.constraints = Some(constraints);
727        self
728    }
729
730    /// Creates a copy of this object but with the given fields replaced with the
731    /// new values.
732    ///
733    /// Dart's named arguments are the fluent setters on the copy
734    /// (`data.copy_with().elevation(2.0)`).
735    pub fn copy_with(&self) -> DialogThemeData {
736        self.clone()
737    }
738
739    /// Linearly interpolate between two dialog themes.
740    ///
741    /// {@macro dart.ui.shadow.lerp}
742    pub fn lerp(
743        a: Option<&DialogThemeData>,
744        b: Option<&DialogThemeData>,
745        t: f64,
746    ) -> DialogThemeData {
747        if let (Some(a), Some(b)) = (a, b)
748            && std::ptr::eq(a, b)
749        {
750            return a.clone();
751        }
752        DialogThemeData {
753            background_color: Color::lerp(
754                a.and_then(|a| a.background_color),
755                b.and_then(|b| b.background_color),
756                t,
757            ),
758            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
759            shadow_color: Color::lerp(
760                a.and_then(|a| a.shadow_color),
761                b.and_then(|b| b.shadow_color),
762                t,
763            ),
764            surface_tint_color: Color::lerp(
765                a.and_then(|a| a.surface_tint_color),
766                b.and_then(|b| b.surface_tint_color),
767                t,
768            ),
769            shape: ShapeBorderRef::lerp(
770                a.and_then(|a| a.shape.as_ref()),
771                b.and_then(|b| b.shape.as_ref()),
772                t,
773            ),
774            alignment: AlignmentGeometry::lerp(
775                a.and_then(|a| a.alignment),
776                b.and_then(|b| b.alignment),
777                t,
778            ),
779            icon_color: Color::lerp(
780                a.and_then(|a| a.icon_color),
781                b.and_then(|b| b.icon_color),
782                t,
783            ),
784            title_text_style: TextStyle::lerp(
785                a.and_then(|a| a.title_text_style.as_ref()),
786                b.and_then(|b| b.title_text_style.as_ref()),
787                t,
788            ),
789            content_text_style: TextStyle::lerp(
790                a.and_then(|a| a.content_text_style.as_ref()),
791                b.and_then(|b| b.content_text_style.as_ref()),
792                t,
793            ),
794            actions_padding: EdgeInsetsGeometry::lerp(
795                a.and_then(|a| a.actions_padding),
796                b.and_then(|b| b.actions_padding),
797                t,
798            ),
799            barrier_color: Color::lerp(
800                a.and_then(|a| a.barrier_color),
801                b.and_then(|b| b.barrier_color),
802                t,
803            ),
804            inset_padding: EdgeInsets::lerp(
805                a.and_then(|a| a.inset_padding),
806                b.and_then(|b| b.inset_padding),
807                t,
808            ),
809            clip_behavior: if t < 0.5 {
810                a.and_then(|a| a.clip_behavior)
811            } else {
812                b.and_then(|b| b.clip_behavior)
813            },
814            constraints: BoxConstraints::lerp(
815                a.and_then(|a| a.constraints),
816                b.and_then(|b| b.constraints),
817                t,
818            ),
819        }
820    }
821}
822
823impl DialogThemeData {
824    /// Dart's `DialogTheme.debugFillProperties`: the properties `DialogThemeData` adds, without
825    /// the `constraints` only the data class has.
826    fn debug_fill_properties_without_constraints(
827        &self,
828        properties: &mut waft_foundation::DiagnosticPropertiesBuilder,
829    ) {
830        properties
831            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
832        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
833        properties.add(ColorProperty::new("shadowColor", self.shadow_color).default_value(None));
834        properties.add(
835            ColorProperty::new("surfaceTintColor", self.surface_tint_color).default_value(None),
836        );
837        properties.add(
838            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
839                .default_value(None),
840        );
841        properties.add(
842            DiagnosticsProperty::<AlignmentGeometry>::new("alignment", self.alignment)
843                .default_value(None),
844        );
845        properties.add(ColorProperty::new("iconColor", self.icon_color).default_value(None));
846        properties.add(
847            DiagnosticsProperty::<TextStyle>::new("titleTextStyle", self.title_text_style.clone())
848                .default_value(None),
849        );
850        properties.add(
851            DiagnosticsProperty::<TextStyle>::new(
852                "contentTextStyle",
853                self.content_text_style.clone(),
854            )
855            .default_value(None),
856        );
857        properties.add(
858            DiagnosticsProperty::<EdgeInsetsGeometry>::new("actionsPadding", self.actions_padding)
859                .default_value(None),
860        );
861        properties.add(ColorProperty::new("barrierColor", self.barrier_color).default_value(None));
862        properties.add(
863            DiagnosticsProperty::<EdgeInsetsGeometry>::new(
864                "insetPadding",
865                self.inset_padding.map(EdgeInsetsGeometry::from),
866            )
867            .default_value(None),
868        );
869        properties.add(
870            DiagnosticsProperty::<waft_foundation::DartEnum<Clip>>::new(
871                "clipBehavior",
872                self.clip_behavior.map(waft_foundation::DartEnum),
873            )
874            .default_value(None),
875        );
876    }
877}
878
879impl waft_foundation::Diagnosticable for DialogThemeData {
880    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
881        self.debug_fill_properties_without_constraints(properties);
882        properties.add(
883            DiagnosticsProperty::<BoxConstraints>::new("constraints", self.constraints)
884                .default_value(None),
885        );
886    }
887}
888
889impl std::fmt::Display for DialogThemeData {
890    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
892    }
893}
894
895#[cfg(test)]
896mod tests {
897    //! Ported from `test/dialog_theme_test.dart`; the `debugFillProperties` cases wait for
898    //! diagnostics, `hashCode` for `Hash`, and the goldens are not ported.
899
900    use std::rc::Rc;
901    use waft_painting::ShapeBorder;
902
903    use waft_embedder::{Offset, Radius, Rect};
904    use waft_painting::{
905        Alignment, BeveledRectangleBorder, BorderRadiusGeometry, BorderSide, RoundedRectangleBorder,
906    };
907    use waft_widgets::{
908        Builder, Center, Container, GlobalKey, Icon, IconThemeData, Padding, Text, WidgetBuilder,
909    };
910
911    use waft_widgets::testing::{WidgetTester, find, test_widgets};
912
913    use super::*;
914    use crate::colors::Colors;
915    use crate::dialog::tests::{
916        dialog_material, last_barrier_color, material_from_dialog, open, placeholder, rect_of_key,
917        text_style_in_dialog,
918    };
919    use crate::dialog::{AlertDialog, Dialog, ShowDialog, SimpleDialog};
920    use crate::elevated_button::ElevatedButton;
921    use crate::icons::Icons;
922    use crate::material::Material;
923    use crate::test_support::material_app;
924    use crate::text_theme::TextTheme;
925    use crate::theme_data::ThemeData;
926
927    /// Dart's `_appWithDialog(tester, dialog, theme:, dialogTheme:)`.
928    fn app_with_dialog<K>(
929        tester: &mut WidgetTester,
930        dialog: impl IntoWidget<K>,
931        theme: impl FnOnce(&App) -> ThemeData,
932        dialog_theme: Option<DialogThemeData>,
933    ) {
934        let dialog = dialog.into_widget();
935        let root = {
936            let app = tester.cell.borrow();
937            let theme = theme(&app);
938            let mut dialog_builder = Builder::new(move |_app, context| {
939                let dialog = dialog.clone();
940                Center::new()
941                    .child(ElevatedButton::new(
942                        Some(waft_foundation::Listener::new(move |app| {
943                            let dialog = dialog.clone();
944                            let builder: WidgetBuilder =
945                                Rc::new(move |_app, _context| dialog.clone());
946                            drop(ShowDialog::new(builder).show(app, context));
947                        })),
948                        Some(Text::new("X")),
949                    ))
950                    .into_widget()
951            })
952            .into_widget();
953            if let Some(dialog_theme) = dialog_theme {
954                dialog_builder = DialogTheme::new()
955                    .with_data(dialog_theme)
956                    .child(dialog_builder)
957                    .into_widget();
958            }
959            material_app(theme, Material::new().child(dialog_builder).into_widget())
960        };
961        tester.pump_widget(root);
962    }
963
964    fn m3(app: &App) -> ThemeData {
965        ThemeData::new(app)
966    }
967
968    fn with_dialog_theme(dialog_theme: DialogThemeData) -> impl FnOnce(&App) -> ThemeData {
969        move |app| ThemeData::builder().dialog_theme(dialog_theme).build(app)
970    }
971
972    fn m2_with_dialog_theme(dialog_theme: DialogThemeData) -> impl FnOnce(&App) -> ThemeData {
973        move |app| {
974            ThemeData::builder()
975                .use_material3(false)
976                .dialog_theme(dialog_theme)
977                .build(app)
978        }
979    }
980
981    /// Dart's `_getMaterialAlertDialog(tester)`.
982    fn material_alert_dialog<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
983        let dialog = find::by_type::<AlertDialog>().evaluate(tester)[0];
984        let material = tester.descendants_of_type::<Material>(dialog)[0];
985        tester.widget::<Material, R>(material, read)
986    }
987
988    /// Dart's `_getIconRenderObject(tester, icon).text.style?.color`.
989    fn icon_color(tester: &WidgetTester, icon: &waft_widgets::IconData) -> Option<Color> {
990        tester
991            .glyph_style(tester.element(find::by_icon(icon).first()))
992            .color
993            .map(|color| color.color())
994    }
995
996    /// Dart's `_getTextRenderObject(tester, text).text.style?.color`.
997    fn text_color(tester: &WidgetTester, text: &str) -> Option<Color> {
998        text_style_in_dialog(tester, text)
999            .and_then(|style| style.color)
1000            .map(|color| color.color())
1001    }
1002
1003    fn dialog_bottom_left(tester: &WidgetTester) -> Offset {
1004        tester.get_rect(dialog_material(tester)).bottom_left()
1005    }
1006
1007    #[test]
1008    fn dialog_theme_data_copy_with_equality_basics() {
1009        assert_eq!(DialogThemeData::new(), DialogThemeData::new().copy_with());
1010    }
1011
1012    #[test]
1013    fn dialog_theme_data_lerp_special_cases() {
1014        assert_eq!(
1015            DialogThemeData::lerp(None, None, 0.0),
1016            DialogThemeData::new()
1017        );
1018        let theme = DialogThemeData::new();
1019        assert_eq!(
1020            DialogThemeData::lerp(Some(&theme), Some(&theme), 0.5),
1021            theme
1022        );
1023    }
1024
1025    #[test]
1026    fn dialog_theme_data_defaults() {
1027        let dialog_theme_data = DialogThemeData::new();
1028
1029        assert_eq!(dialog_theme_data.background_color, None);
1030        assert_eq!(dialog_theme_data.elevation, None);
1031        assert_eq!(dialog_theme_data.shadow_color, None);
1032        assert_eq!(dialog_theme_data.surface_tint_color, None);
1033        assert!(dialog_theme_data.shape.is_none());
1034        assert_eq!(dialog_theme_data.alignment, None);
1035        assert_eq!(dialog_theme_data.icon_color, None);
1036        assert_eq!(dialog_theme_data.title_text_style, None);
1037        assert_eq!(dialog_theme_data.content_text_style, None);
1038        assert_eq!(dialog_theme_data.actions_padding, None);
1039        assert_eq!(dialog_theme_data.barrier_color, None);
1040        assert_eq!(dialog_theme_data.inset_padding, None);
1041        assert_eq!(dialog_theme_data.clip_behavior, None);
1042        assert_eq!(dialog_theme_data.constraints, None);
1043
1044        let dialog_theme = DialogTheme::new()
1045            .with_data(DialogThemeData::new())
1046            .child(waft_widgets::SizedBox::new());
1047        assert_eq!(dialog_theme.background_color(), None);
1048        assert_eq!(dialog_theme.elevation(), None);
1049        assert_eq!(dialog_theme.shadow_color(), None);
1050        assert_eq!(dialog_theme.surface_tint_color(), None);
1051        assert!(dialog_theme.shape().is_none());
1052        assert_eq!(dialog_theme.alignment(), None);
1053        assert_eq!(dialog_theme.icon_color(), None);
1054        assert_eq!(dialog_theme.title_text_style(), None);
1055        assert_eq!(dialog_theme.content_text_style(), None);
1056        assert_eq!(dialog_theme.actions_padding(), None);
1057        assert_eq!(dialog_theme.barrier_color(), None);
1058        assert_eq!(dialog_theme.inset_padding(), None);
1059        assert_eq!(dialog_theme.clip_behavior(), None);
1060        assert_eq!(dialog_theme_data.constraints, None);
1061    }
1062
1063    /// The theme both "Local DialogThemeData" cases give the `DialogTheme`.
1064    fn local_dialog_theme() -> DialogThemeData {
1065        DialogThemeData::new()
1066            .background_color(Color::new(0xff123456))
1067            .elevation(8.0)
1068            .shadow_color(Color::new(0xff000001))
1069            .surface_tint_color(Color::new(0xff000002))
1070            .shape(BeveledRectangleBorder::new(
1071                BorderSide::NONE,
1072                BorderRadiusGeometry::all(Radius::circular(20.5)),
1073            ))
1074            .alignment(AlignmentGeometry::BOTTOM_LEFT)
1075            .icon_color(Color::new(0xff654321))
1076            .title_text_style(TextStyle::new().color(Color::new(0xffffffff)))
1077            .content_text_style(TextStyle::new().color(Color::new(0xff000000)))
1078            .actions_padding(EdgeInsetsGeometry::all(8.0))
1079            .barrier_color(Color::new(0xff000005))
1080            .inset_padding(EdgeInsets::all(30.0))
1081            .clip_behavior(Clip::AntiAlias)
1082    }
1083
1084    fn icon_title_content_dialog() -> AlertDialog {
1085        AlertDialog::new()
1086            .title(Text::new("Title"))
1087            .content(Text::new("Content"))
1088            .icon(Icon::new(Some(Icons::search())))
1089            .actions([Icon::new(Some(Icons::cancel())).into_widget()])
1090    }
1091
1092    /// The expectations both "Local DialogThemeData" cases share: the local theme wins.
1093    fn expect_local_theme(tester: &WidgetTester) {
1094        let theme = local_dialog_theme();
1095        material_alert_dialog(tester, |material| {
1096            assert_eq!(material.color, theme.background_color);
1097            assert_eq!(material.elevation, 8.0);
1098            assert_eq!(material.shadow_color, theme.shadow_color);
1099            assert_eq!(material.surface_tint_color, theme.surface_tint_color);
1100            assert_eq!(material.shape, theme.shape);
1101            assert_eq!(material.clip_behavior, Clip::AntiAlias);
1102        });
1103        let bottom_left = dialog_bottom_left(tester);
1104        assert_eq!(bottom_left.dx(), 30.0); // 30 is the padding value.
1105        assert_eq!(bottom_left.dy(), 570.0); // 600 - 30
1106        assert_eq!(icon_color(tester, &Icons::search()), theme.icon_color);
1107        assert_eq!(text_color(tester, "Title"), Some(Color::new(0xffffffff)));
1108        assert_eq!(text_color(tester, "Content"), Some(Color::new(0xff000000)));
1109        assert_eq!(last_barrier_color(tester), theme.barrier_color);
1110
1111        let cancel = tester.element(find::by_icon(&Icons::cancel()).first());
1112        let padding = tester.ancestor_of_type::<Padding>(cancel);
1113        assert_eq!(
1114            tester.widget::<Padding, _>(padding, |padding| padding.padding),
1115            EdgeInsetsGeometry::all(8.0)
1116        );
1117    }
1118
1119    #[test]
1120    fn local_dialog_theme_data_overrides_dialog_defaults() {
1121        test_widgets(|tester| {
1122            app_with_dialog(
1123                tester,
1124                icon_title_content_dialog(),
1125                m3,
1126                Some(local_dialog_theme()),
1127            );
1128            open(tester);
1129
1130            expect_local_theme(tester);
1131        });
1132    }
1133
1134    #[test]
1135    fn local_dialog_theme_data_overrides_global_dialog_theme() {
1136        test_widgets(|tester| {
1137            let global_dialog_theme = DialogThemeData::new()
1138                .background_color(Color::new(0xff654321))
1139                .elevation(7.0)
1140                .shadow_color(Color::new(0xff200001))
1141                .surface_tint_color(Color::new(0xff222002))
1142                .shape(BeveledRectangleBorder::new(
1143                    BorderSide::NONE,
1144                    BorderRadiusGeometry::all(Radius::circular(25.5)),
1145                ))
1146                .alignment(AlignmentGeometry::CENTER_RIGHT)
1147                .icon_color(Color::new(0xff666666))
1148                .title_text_style(TextStyle::new().color(Color::new(0xff000000)))
1149                .content_text_style(TextStyle::new().color(Color::new(0xffdddddd)))
1150                .actions_padding(EdgeInsetsGeometry::all(18.0))
1151                .barrier_color(Color::new(0xff111115))
1152                .inset_padding(EdgeInsets::all(35.0))
1153                .clip_behavior(Clip::HardEdge);
1154            app_with_dialog(
1155                tester,
1156                icon_title_content_dialog(),
1157                with_dialog_theme(global_dialog_theme),
1158                Some(local_dialog_theme()),
1159            );
1160            open(tester);
1161
1162            expect_local_theme(tester);
1163        });
1164    }
1165
1166    fn title_dialog() -> AlertDialog {
1167        AlertDialog::new().title(Text::new("Title")).actions([])
1168    }
1169
1170    #[test]
1171    fn dialog_background_color() {
1172        test_widgets(|tester| {
1173            let custom_color = Colors::PINK.primary();
1174            app_with_dialog(
1175                tester,
1176                title_dialog(),
1177                with_dialog_theme(DialogThemeData::new().background_color(custom_color)),
1178                None,
1179            );
1180            open(tester);
1181
1182            assert_eq!(
1183                material_alert_dialog(tester, |material| material.color),
1184                Some(custom_color)
1185            );
1186        });
1187    }
1188
1189    #[test]
1190    fn custom_dialog_elevation() {
1191        test_widgets(|tester| {
1192            let custom_elevation = 12.0;
1193            let shadow_color = Color::new(0xFF000001);
1194            let surface_tint_color = Color::new(0xFF000002);
1195            app_with_dialog(
1196                tester,
1197                title_dialog(),
1198                with_dialog_theme(
1199                    DialogThemeData::new()
1200                        .elevation(custom_elevation)
1201                        .shadow_color(shadow_color)
1202                        .surface_tint_color(surface_tint_color),
1203                ),
1204                None,
1205            );
1206            open(tester);
1207
1208            material_alert_dialog(tester, |material| {
1209                assert_eq!(material.elevation, custom_elevation);
1210                assert_eq!(material.shadow_color, Some(shadow_color));
1211                assert_eq!(material.surface_tint_color, Some(surface_tint_color));
1212            });
1213        });
1214    }
1215
1216    #[test]
1217    fn custom_dialog_shape() {
1218        test_widgets(|tester| {
1219            let custom_border = RoundedRectangleBorder::new(
1220                BorderSide::NONE,
1221                BorderRadiusGeometry::all(Radius::circular(16.0)),
1222            );
1223            app_with_dialog(
1224                tester,
1225                title_dialog(),
1226                with_dialog_theme(DialogThemeData::new().shape(custom_border)),
1227                None,
1228            );
1229            open(tester);
1230
1231            material_alert_dialog(tester, |material| {
1232                assert_eq!(
1233                    material.shape.as_deref(),
1234                    Some(&custom_border as &dyn ShapeBorder)
1235                );
1236            });
1237        });
1238    }
1239
1240    #[test]
1241    fn custom_dialog_alignment() {
1242        test_widgets(|tester| {
1243            app_with_dialog(
1244                tester,
1245                title_dialog(),
1246                with_dialog_theme(DialogThemeData::new().alignment(AlignmentGeometry::BOTTOM_LEFT)),
1247                None,
1248            );
1249            open(tester);
1250
1251            let bottom_left = dialog_bottom_left(tester);
1252            assert_eq!(bottom_left.dx(), 40.0);
1253            assert_eq!(bottom_left.dy(), 576.0);
1254        });
1255    }
1256
1257    fn alignment_takes_priority(
1258        tester: &mut WidgetTester,
1259        theme: impl FnOnce(&App) -> ThemeData,
1260        dy: f64,
1261    ) {
1262        app_with_dialog(
1263            tester,
1264            title_dialog().alignment(AlignmentGeometry::Alignment(Alignment::TOP_RIGHT)),
1265            theme,
1266            None,
1267        );
1268        open(tester);
1269
1270        let bottom_left = dialog_bottom_left(tester);
1271        assert_eq!(bottom_left.dx(), 480.0);
1272        assert_eq!(bottom_left.dy(), dy);
1273    }
1274
1275    #[test]
1276    fn material3_dialog_alignment_takes_priority_over_theme() {
1277        test_widgets(|tester| {
1278            alignment_takes_priority(
1279                tester,
1280                with_dialog_theme(DialogThemeData::new().alignment(AlignmentGeometry::BOTTOM_LEFT)),
1281                124.0,
1282            );
1283        });
1284    }
1285
1286    #[test]
1287    fn material2_dialog_alignment_takes_priority_over_theme() {
1288        test_widgets(|tester| {
1289            alignment_takes_priority(
1290                tester,
1291                m2_with_dialog_theme(
1292                    DialogThemeData::new().alignment(AlignmentGeometry::BOTTOM_LEFT),
1293                ),
1294                104.0,
1295            );
1296        });
1297    }
1298
1299    fn icon_dialog() -> AlertDialog {
1300        AlertDialog::new()
1301            .icon(Icon::new(Some(Icons::ac_unit())))
1302            .actions([])
1303    }
1304
1305    #[test]
1306    fn custom_icon_color_constructor_param_highest_preference() {
1307        test_widgets(|tester| {
1308            let (icon_color_, dialog_theme_color, icon_theme_color) = (
1309                Colors::PINK.primary(),
1310                Colors::GREEN.primary(),
1311                Colors::YELLOW.primary(),
1312            );
1313            app_with_dialog(
1314                tester,
1315                icon_dialog().icon_color(icon_color_),
1316                move |app| {
1317                    ThemeData::builder()
1318                        .icon_theme(IconThemeData::new().color(icon_theme_color))
1319                        .dialog_theme(DialogThemeData::new().icon_color(dialog_theme_color))
1320                        .build(app)
1321                },
1322                None,
1323            );
1324            open(tester);
1325
1326            assert_eq!(icon_color(tester, &Icons::ac_unit()), Some(icon_color_));
1327        });
1328    }
1329
1330    #[test]
1331    fn custom_icon_color_dialog_theme_preference_over_theme() {
1332        test_widgets(|tester| {
1333            let (dialog_theme_color, icon_theme_color) =
1334                (Colors::GREEN.primary(), Colors::YELLOW.primary());
1335            app_with_dialog(
1336                tester,
1337                icon_dialog(),
1338                move |app| {
1339                    ThemeData::builder()
1340                        .icon_theme(IconThemeData::new().color(icon_theme_color))
1341                        .dialog_theme(DialogThemeData::new().icon_color(dialog_theme_color))
1342                        .build(app)
1343                },
1344                None,
1345            );
1346            open(tester);
1347
1348            assert_eq!(
1349                icon_color(tester, &Icons::ac_unit()),
1350                Some(dialog_theme_color)
1351            );
1352        });
1353    }
1354
1355    #[test]
1356    fn material3_custom_icon_color_theme_lowest_preference() {
1357        test_widgets(|tester| {
1358            let secondary = m3(&tester.cell.borrow()).color_scheme.secondary();
1359            app_with_dialog(tester, icon_dialog(), m3, None);
1360            open(tester);
1361
1362            assert_eq!(icon_color(tester, &Icons::ac_unit()), Some(secondary));
1363        });
1364    }
1365
1366    #[test]
1367    fn material2_custom_icon_color_theme_lowest_preference() {
1368        test_widgets(|tester| {
1369            let icon_theme_color = Colors::YELLOW.primary();
1370            app_with_dialog(
1371                tester,
1372                icon_dialog(),
1373                move |app| {
1374                    ThemeData::builder()
1375                        .use_material3(false)
1376                        .icon_theme(IconThemeData::new().color(icon_theme_color))
1377                        .build(app)
1378                },
1379                None,
1380            );
1381            open(tester);
1382
1383            assert_eq!(
1384                icon_color(tester, &Icons::ac_unit()),
1385                Some(icon_theme_color)
1386            );
1387        });
1388    }
1389
1390    fn pink() -> TextStyle {
1391        TextStyle::new().color(Colors::PINK.primary())
1392    }
1393
1394    /// The text style cases: `dialog` shows `text`, and its style is `expected` whole, or
1395    /// only its color where `color_only`.
1396    fn expect_text_style<K>(
1397        tester: &mut WidgetTester,
1398        dialog: impl IntoWidget<K>,
1399        theme: impl FnOnce(&App) -> ThemeData,
1400        text: &str,
1401        color_only: bool,
1402    ) {
1403        app_with_dialog(tester, dialog, theme, None);
1404        open(tester);
1405
1406        let style = text_style_in_dialog(tester, text);
1407        if color_only {
1408            assert_eq!(style.and_then(|style| style.color), pink().color);
1409        } else {
1410            assert_eq!(style, Some(pink()));
1411        }
1412    }
1413
1414    #[test]
1415    fn custom_title_text_style_constructor_param() {
1416        test_widgets(|tester| {
1417            expect_text_style(
1418                tester,
1419                AlertDialog::new()
1420                    .title(Text::new("Title"))
1421                    .title_text_style(pink())
1422                    .actions([]),
1423                m3,
1424                "Title",
1425                false,
1426            );
1427        });
1428    }
1429
1430    #[test]
1431    fn custom_title_text_style_dialog_theme() {
1432        test_widgets(|tester| {
1433            expect_text_style(
1434                tester,
1435                title_dialog(),
1436                with_dialog_theme(DialogThemeData::new().title_text_style(pink())),
1437                "Title",
1438                false,
1439            );
1440        });
1441    }
1442
1443    #[test]
1444    fn material3_custom_title_text_style_theme() {
1445        test_widgets(|tester| {
1446            expect_text_style(
1447                tester,
1448                AlertDialog::new().title(Text::new("Title")),
1449                |app| {
1450                    ThemeData::builder()
1451                        .text_theme(TextTheme::new().headline_small(pink()))
1452                        .build(app)
1453                },
1454                "Title",
1455                true,
1456            );
1457        });
1458    }
1459
1460    #[test]
1461    fn material2_custom_title_text_style_theme() {
1462        test_widgets(|tester| {
1463            expect_text_style(
1464                tester,
1465                AlertDialog::new().title(Text::new("Title")),
1466                |app| {
1467                    ThemeData::builder()
1468                        .use_material3(false)
1469                        .text_theme(TextTheme::new().title_large(pink()))
1470                        .build(app)
1471                },
1472                "Title",
1473                true,
1474            );
1475        });
1476    }
1477
1478    #[test]
1479    fn simple_dialog_custom_title_text_style_constructor_param() {
1480        test_widgets(|tester| {
1481            expect_text_style(
1482                tester,
1483                SimpleDialog::new()
1484                    .title(Text::new("Title"))
1485                    .title_text_style(pink()),
1486                m3,
1487                "Title",
1488                false,
1489            );
1490        });
1491    }
1492
1493    #[test]
1494    fn simple_dialog_custom_title_text_style_dialog_theme() {
1495        test_widgets(|tester| {
1496            expect_text_style(
1497                tester,
1498                SimpleDialog::new().title(Text::new("Title")),
1499                with_dialog_theme(DialogThemeData::new().title_text_style(pink())),
1500                "Title",
1501                false,
1502            );
1503        });
1504    }
1505
1506    #[test]
1507    fn simple_dialog_custom_title_text_style_theme() {
1508        test_widgets(|tester| {
1509            expect_text_style(
1510                tester,
1511                SimpleDialog::new().title(Text::new("Title")),
1512                |app| {
1513                    ThemeData::builder()
1514                        .text_theme(TextTheme::new().title_large(pink()))
1515                        .build(app)
1516                },
1517                "Title",
1518                true,
1519            );
1520        });
1521    }
1522
1523    #[test]
1524    fn custom_content_text_style_constructor_param() {
1525        test_widgets(|tester| {
1526            expect_text_style(
1527                tester,
1528                AlertDialog::new()
1529                    .content(Text::new("Content"))
1530                    .content_text_style(pink())
1531                    .actions([]),
1532                m3,
1533                "Content",
1534                false,
1535            );
1536        });
1537    }
1538
1539    #[test]
1540    fn custom_content_text_style_dialog_theme() {
1541        test_widgets(|tester| {
1542            expect_text_style(
1543                tester,
1544                AlertDialog::new().content(Text::new("Content")).actions([]),
1545                with_dialog_theme(DialogThemeData::new().content_text_style(pink())),
1546                "Content",
1547                false,
1548            );
1549        });
1550    }
1551
1552    #[test]
1553    fn material3_custom_content_text_style_theme() {
1554        test_widgets(|tester| {
1555            expect_text_style(
1556                tester,
1557                AlertDialog::new().content(Text::new("Content")),
1558                |app| {
1559                    ThemeData::builder()
1560                        .text_theme(TextTheme::new().body_medium(pink()))
1561                        .build(app)
1562                },
1563                "Content",
1564                true,
1565            );
1566        });
1567    }
1568
1569    #[test]
1570    fn material2_custom_content_text_style_theme() {
1571        test_widgets(|tester| {
1572            expect_text_style(
1573                tester,
1574                AlertDialog::new().content(Text::new("Content")),
1575                |app| {
1576                    ThemeData::builder()
1577                        .use_material3(false)
1578                        .text_theme(TextTheme::new().title_medium(pink()))
1579                        .build(app)
1580                },
1581                "Content",
1582                true,
1583            );
1584        });
1585    }
1586
1587    #[test]
1588    fn custom_barrier_color_theme() {
1589        test_widgets(|tester| {
1590            let barrier_color = Colors::BLUE.primary();
1591            app_with_dialog(
1592                tester,
1593                SimpleDialog::new(),
1594                with_dialog_theme(DialogThemeData::new().barrier_color(barrier_color)),
1595                None,
1596            );
1597            open(tester);
1598
1599            assert_eq!(last_barrier_color(tester), Some(barrier_color));
1600        });
1601    }
1602
1603    #[test]
1604    fn dialog_theme_inset_padding_updates_dialog_inset_padding() {
1605        test_widgets(|tester| {
1606            let key = GlobalKey::new();
1607            // The default testing screen (800, 600)
1608            let screen_rect = Rect::from_ltrb(0.0, 0.0, 800.0, 600.0);
1609            let inset_padding = EdgeInsets::from_ltrb(10.0, 15.0, 20.0, 25.0);
1610            app_with_dialog(
1611                tester,
1612                Dialog::new().child(placeholder(&key)),
1613                with_dialog_theme(DialogThemeData::new().inset_padding(inset_padding)),
1614                None,
1615            );
1616            tester.tap(find::text("X"));
1617            tester.pump_by(std::time::Duration::ZERO);
1618
1619            assert_eq!(
1620                rect_of_key(tester, &key),
1621                Rect::from_ltrb(
1622                    screen_rect.left + inset_padding.left,
1623                    screen_rect.top + inset_padding.top,
1624                    screen_rect.right - inset_padding.right,
1625                    screen_rect.bottom - inset_padding.bottom,
1626                )
1627            );
1628        });
1629    }
1630
1631    fn clip_of_dialog(
1632        tester: &mut WidgetTester,
1633        theme: impl FnOnce(&App) -> ThemeData,
1634        dialog: Dialog,
1635    ) -> Clip {
1636        app_with_dialog(tester, dialog, theme, None);
1637        open(tester);
1638        material_from_dialog(tester, |material| material.clip_behavior)
1639    }
1640
1641    #[test]
1642    fn dialog_theme_clip_behavior_updates_the_dialogs_clip_behavior() {
1643        test_widgets(|tester| {
1644            let key = GlobalKey::new();
1645            assert_eq!(
1646                clip_of_dialog(
1647                    tester,
1648                    with_dialog_theme(DialogThemeData::new().clip_behavior(Clip::HardEdge)),
1649                    Dialog::new().child(placeholder(&key)),
1650                ),
1651                Clip::HardEdge
1652            );
1653        });
1654    }
1655
1656    #[test]
1657    fn dialog_clip_behavior_takes_priority_over_theme() {
1658        test_widgets(|tester| {
1659            let key = GlobalKey::new();
1660            assert_eq!(
1661                clip_of_dialog(
1662                    tester,
1663                    with_dialog_theme(DialogThemeData::new().clip_behavior(Clip::HardEdge)),
1664                    Dialog::new()
1665                        .clip_behavior(Clip::AntiAlias)
1666                        .child(placeholder(&key)),
1667                ),
1668                Clip::AntiAlias
1669            );
1670        });
1671    }
1672
1673    #[test]
1674    fn material2_dialog_clip_behavior_takes_priority_over_theme() {
1675        test_widgets(|tester| {
1676            let key = GlobalKey::new();
1677            assert_eq!(
1678                clip_of_dialog(
1679                    tester,
1680                    m2_with_dialog_theme(DialogThemeData::new().clip_behavior(Clip::HardEdge)),
1681                    Dialog::new()
1682                        .clip_behavior(Clip::AntiAlias)
1683                        .child(placeholder(&key)),
1684                ),
1685                Clip::AntiAlias
1686            );
1687        });
1688    }
1689
1690    #[test]
1691    fn dialog_theme_data_constraints_is_respected_if_dialog_constraints_is_null() {
1692        test_widgets(|tester| {
1693            let theme_constraints = BoxConstraints::new().max_width(500.0).max_height(500.0);
1694            let key = GlobalKey::new();
1695            app_with_dialog(
1696                tester,
1697                Dialog::new().child(
1698                    waft_widgets::SizedBox::expand().child(
1699                        Container::new()
1700                            .key(key.clone().into())
1701                            .color(Colors::AMBER.primary()),
1702                    ),
1703                ),
1704                with_dialog_theme(
1705                    DialogThemeData::new()
1706                        .alignment(AlignmentGeometry::CENTER)
1707                        .constraints(theme_constraints),
1708                ),
1709                None,
1710            );
1711            open(tester);
1712
1713            // Verify that the dialog respects the constraints from the theme
1714            let render_box = tester.render_object(&key).as_box().expect("a render box");
1715            let constraints = render_box.constraints(&tester.cell.borrow());
1716            assert_eq!(constraints.max_width, theme_constraints.max_width);
1717            assert_eq!(constraints.max_height, theme_constraints.max_height);
1718        });
1719    }
1720
1721    #[test]
1722    fn the_legacy_properties_make_the_data_and_a_data_answers_them() {
1723        let theme = DialogTheme::new()
1724            .with_elevation(3.0)
1725            .with_barrier_color(Colors::RED.primary())
1726            .with_inset_padding(EdgeInsets::all(4.0));
1727        assert_eq!(theme.elevation(), Some(3.0));
1728        assert_eq!(
1729            theme.data(),
1730            DialogThemeData::new()
1731                .elevation(3.0)
1732                .barrier_color(Colors::RED.primary())
1733                .inset_padding(EdgeInsets::all(4.0))
1734        );
1735        assert_eq!(theme.copy_with().with_elevation(5.0).elevation(), Some(5.0));
1736
1737        let from_data = DialogTheme::new().with_data(DialogThemeData::new().elevation(9.0));
1738        assert_eq!(from_data.elevation(), Some(9.0));
1739        assert_eq!(
1740            from_data.copy_with().data(),
1741            DialogThemeData::new().elevation(9.0)
1742        );
1743    }
1744
1745    #[test]
1746    fn dialog_theme_data_lerps_each_field() {
1747        let a = DialogThemeData::new()
1748            .background_color(Colors::BLACK)
1749            .elevation(2.0)
1750            .inset_padding(EdgeInsets::all(10.0))
1751            .constraints(BoxConstraints::new().max_width(100.0))
1752            .clip_behavior(Clip::HardEdge);
1753        let b = DialogThemeData::new()
1754            .background_color(Colors::WHITE)
1755            .elevation(6.0)
1756            .inset_padding(EdgeInsets::all(30.0))
1757            .constraints(BoxConstraints::new().max_width(300.0))
1758            .clip_behavior(Clip::AntiAlias);
1759
1760        let halfway = DialogThemeData::lerp(Some(&a), Some(&b), 0.5);
1761
1762        assert_eq!(
1763            halfway.background_color,
1764            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
1765        );
1766        assert_eq!(halfway.elevation, Some(4.0));
1767        assert_eq!(halfway.inset_padding, Some(EdgeInsets::all(20.0)));
1768        assert_eq!(
1769            halfway.constraints,
1770            BoxConstraints::lerp(a.constraints, b.constraints, 0.5)
1771        );
1772        assert_eq!(halfway.clip_behavior, Some(Clip::AntiAlias));
1773        assert_eq!(
1774            DialogThemeData::lerp(Some(&a), Some(&b), 0.4).clip_behavior,
1775            Some(Clip::HardEdge)
1776        );
1777    }
1778
1779    #[test]
1780    fn update_should_notify_only_when_the_data_differs() {
1781        let theme = |data: DialogThemeData| DialogTheme::new().with_data(data);
1782        let old = theme(DialogThemeData::new().elevation(1.0));
1783
1784        assert!(!theme(DialogThemeData::new().elevation(1.0)).update_should_notify(&old));
1785        assert!(theme(DialogThemeData::new().elevation(2.0)).update_should_notify(&old));
1786    }
1787
1788    #[test]
1789    fn theme_data_holds_the_dialog_theme() {
1790        test_widgets(|tester| {
1791            let app = tester.cell.borrow();
1792            let theme = ThemeData::new(&app);
1793            assert_eq!(theme.dialog_theme, DialogThemeData::new());
1794
1795            let raised = ThemeData::builder()
1796                .dialog_theme(DialogThemeData::new().elevation(8.0))
1797                .build(&app);
1798            assert_eq!(raised.dialog_theme.elevation, Some(8.0));
1799            assert_ne!(theme, raised);
1800            assert_eq!(
1801                theme
1802                    .copy_with()
1803                    .dialog_theme(raised.dialog_theme.clone())
1804                    .build(),
1805                raised
1806            );
1807
1808            let flat = ThemeData::builder()
1809                .dialog_theme(DialogThemeData::new().elevation(0.0))
1810                .build(&app);
1811            assert_eq!(
1812                ThemeData::lerp(&flat, &raised, 0.5).dialog_theme.elevation,
1813                Some(4.0)
1814            );
1815        });
1816    }
1817    // Flutter's "Default DialogThemeData debugFillProperties".
1818    #[test]
1819    fn a_dialog_theme_data_describes_nothing_by_default() {
1820        assert_eq!(
1821            waft_widgets::testing::describe_properties(|properties| {
1822                waft_foundation::Diagnosticable::debug_fill_properties(
1823                    &DialogThemeData::new(),
1824                    properties,
1825                )
1826            }),
1827            Vec::<String>::new()
1828        );
1829    }
1830
1831    // dialog_theme_test.dart 'DialogThemeData implements debugFillProperties'.
1832    #[test]
1833    fn an_assigned_dialog_theme_describes_every_property() {
1834        let theme = DialogThemeData::new()
1835            .background_color(Color::new(0xff123456))
1836            .elevation(8.0)
1837            .shadow_color(Color::new(0xff000001))
1838            .surface_tint_color(Color::new(0xff000002))
1839            .shape(BeveledRectangleBorder::new(
1840                BorderSide::NONE,
1841                BorderRadiusGeometry::circular(20.5),
1842            ))
1843            .alignment(AlignmentGeometry::BOTTOM_LEFT)
1844            .icon_color(Color::new(0xff654321))
1845            .title_text_style(TextStyle::new().color(Color::new(0xffffffff)))
1846            .content_text_style(TextStyle::new().color(Color::new(0xff000000)))
1847            .actions_padding(EdgeInsetsGeometry::all(8.0))
1848            .barrier_color(Color::new(0xff000005))
1849            .inset_padding(EdgeInsets::all(20.0))
1850            .clip_behavior(Clip::AntiAlias);
1851        let description = waft_widgets::testing::describe_properties(|properties| {
1852            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
1853        });
1854        let description: Vec<String> = description
1855            .iter()
1856            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
1857            .collect();
1858        assert_eq!(
1859            description,
1860            [
1861                format!("backgroundColor: {}", Color::new(0xff123456)),
1862                "elevation: 8.0".to_string(),
1863                format!("shadowColor: {}", Color::new(0xff000001)),
1864                format!("surfaceTintColor: {}", Color::new(0xff000002)),
1865                format!(
1866                    "shape: {}",
1867                    ShapeBorderRef::from(BeveledRectangleBorder::new(
1868                        BorderSide::NONE,
1869                        BorderRadiusGeometry::circular(20.5)
1870                    ))
1871                ),
1872                "alignment: Alignment.bottomLeft".to_string(),
1873                format!("iconColor: {}", Color::new(0xff654321)),
1874                format!(
1875                    "titleTextStyle: {}",
1876                    TextStyle::new().color(Color::new(0xffffffff))
1877                ),
1878                format!(
1879                    "contentTextStyle: {}",
1880                    TextStyle::new().color(Color::new(0xff000000))
1881                ),
1882                "actionsPadding: EdgeInsets.all(8.0)".to_string(),
1883                format!("barrierColor: {}", Color::new(0xff000005)),
1884                "insetPadding: EdgeInsets.all(20.0)".to_string(),
1885                "clipBehavior: Clip.antiAlias".to_string(),
1886            ]
1887        );
1888    }
1889}