Skip to main content

waft_material/
user_accounts_drawer_header.rs

1//! Flutter counterpart: material_ui's `user_accounts_drawer_header.dart`.
2
3use std::any::Any;
4use std::f64::consts::PI;
5use std::fmt;
6use std::rc::Rc;
7use std::time::Duration;
8
9use waft_animation::{
10    Animation, AnimationBehavior, AnimationController, Curve, CurvedAnimation, Curves,
11};
12use waft_embedder::{Color, Offset, Size, TextDirection};
13use waft_foundation::{App, Handle, Listener, Ref, ValueKey};
14use waft_painting::{
15    BoxDecoration, DecorationRef, EdgeInsets, EdgeInsetsDirectional, EdgeInsetsGeometry,
16    TextOverflow,
17};
18use waft_rendering::{
19    BoxConstraints, ChildLayoutId, MultiChildLayoutChildren, MultiChildLayoutDelegate,
20};
21use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
22use waft_widgets::{
23    BuildContext, Center, Column, CrossAxisAlignment, CustomMultiChildLayout, DefaultTextStyle,
24    Directionality, Expanded, Icon, IntoWidget, KeyRef, LayoutId, Padding, Positioned,
25    PositionedDirectional, Row, SafeArea, Semantics, SingleTickerProviderStateMixin,
26    SingleTickerProviderStateMixinData, SizedBox, Stack, State, StateData, StatefulWidget,
27    StatelessWidget, Transform, WidgetRef, debug_check_has_directionality,
28};
29
30use crate::colors::Colors;
31use crate::debug::{debug_check_has_material, debug_check_has_material_localizations};
32use crate::drawer_header::DrawerHeader;
33use crate::icons::Icons;
34use crate::ink_well::InkWell;
35use crate::material_localizations::MaterialLocalizations;
36use crate::theme::Theme;
37
38const K_ACCOUNT_DETAILS_HEIGHT: f64 = 56.0;
39
40fn account_name_id() -> ChildLayoutId {
41    Rc::new(ValueKey::new("accountName"))
42}
43
44fn account_email_id() -> ChildLayoutId {
45    Rc::new(ValueKey::new("accountEmail"))
46}
47
48fn dropdown_icon_id() -> ChildLayoutId {
49    Rc::new(ValueKey::new("dropdownIcon"))
50}
51
52/// Dart's `_AccountPictures`.
53struct AccountPictures {
54    current_account_picture: Option<WidgetRef>,
55    other_accounts_pictures: Option<Vec<WidgetRef>>,
56    current_account_picture_size: Option<Size>,
57    other_accounts_pictures_size: Option<Size>,
58}
59
60impl AccountPictures {
61    fn new(
62        current_account_picture: Option<WidgetRef>,
63        other_accounts_pictures: Option<Vec<WidgetRef>>,
64        current_account_picture_size: Option<Size>,
65        other_accounts_pictures_size: Option<Size>,
66    ) -> AccountPictures {
67        AccountPictures {
68            current_account_picture,
69            other_accounts_pictures,
70            current_account_picture_size,
71            other_accounts_pictures_size,
72        }
73    }
74}
75
76impl fmt::Debug for AccountPictures {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.debug_struct("AccountPictures").finish_non_exhaustive()
79    }
80}
81
82impl StatelessWidget for AccountPictures {
83    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
84        let other_pictures = self
85            .other_accounts_pictures
86            .clone()
87            .unwrap_or_default()
88            .into_iter()
89            .take(3)
90            .map(|picture| {
91                Padding::new(EdgeInsetsDirectional::only(8.0, 0.0, 0.0, 0.0))
92                    .child(Semantics::new().container(true).child(
93                        Padding::new(EdgeInsets::from_ltrb(8.0, 0.0, 0.0, 8.0)).child(
94                            SizedBox::from_size(self.other_accounts_pictures_size).child(picture),
95                        ),
96                    ))
97                    .into_widget()
98            })
99            .collect::<Vec<_>>();
100
101        let mut current_picture = SizedBox::from_size(self.current_account_picture_size);
102        if let Some(current_account_picture) = &self.current_account_picture {
103            current_picture = current_picture.child(current_account_picture.clone());
104        }
105
106        Stack::new()
107            .children(vec![
108                PositionedDirectional::new(Row::new().children(other_pictures))
109                    .top(0.0)
110                    .end(0.0)
111                    .into_widget(),
112                Positioned::new(
113                    Semantics::new()
114                        .explicit_child_nodes(true)
115                        .child(current_picture),
116                )
117                .top(0.0)
118                .into_widget(),
119            ])
120            .into_widget()
121    }
122}
123
124/// Dart's `_AccountDetails`.
125struct AccountDetails {
126    account_name: Option<WidgetRef>,
127    account_email: Option<WidgetRef>,
128    on_tap: Option<Listener>,
129    is_open: bool,
130    arrow_color: Option<Color>,
131}
132
133impl AccountDetails {
134    fn new(
135        account_name: Option<WidgetRef>,
136        account_email: Option<WidgetRef>,
137        on_tap: Option<Listener>,
138        is_open: bool,
139        arrow_color: Option<Color>,
140    ) -> AccountDetails {
141        AccountDetails {
142            account_name,
143            account_email,
144            on_tap,
145            is_open,
146            arrow_color,
147        }
148    }
149}
150
151impl fmt::Debug for AccountDetails {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_struct("AccountDetails").finish_non_exhaustive()
154    }
155}
156
157impl StatefulWidget for AccountDetails {
158    type State = AccountDetailsState;
159
160    fn create_state(&self) -> AccountDetailsState {
161        AccountDetailsState {
162            state: StateData::new(),
163            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
164            controller: None,
165            animation: None,
166        }
167    }
168}
169
170/// Dart's `_AccountDetailsState`.
171struct AccountDetailsState {
172    state: StateData<AccountDetails>,
173    single_ticker_provider: SingleTickerProviderStateMixinData,
174    controller: Option<Ref<AnimationController>>,
175    animation: Option<Ref<CurvedAnimation>>,
176}
177
178impl AccountDetailsState {
179    fn controller(self: Handle<Self>, app: &App) -> Ref<AnimationController> {
180        app.get(self)
181            .controller
182            .clone()
183            .expect("created in init_state")
184    }
185
186    fn animation(self: Handle<Self>, app: &App) -> Ref<CurvedAnimation> {
187        app.get(self)
188            .animation
189            .clone()
190            .expect("created in init_state")
191    }
192
193    fn handle_animation_changed(self: Handle<Self>, app: &mut App) {
194        self.set_state(app, |_state| {});
195    }
196}
197
198impl fmt::Debug for AccountDetailsState {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        f.debug_struct("AccountDetailsState")
201            .finish_non_exhaustive()
202    }
203}
204
205impl SingleTickerProviderStateMixin for AccountDetailsState {
206    fn single_ticker_provider_data(
207        self: Handle<Self>,
208        app: &App,
209    ) -> &SingleTickerProviderStateMixinData {
210        &app.get(self).single_ticker_provider
211    }
212
213    fn single_ticker_provider_data_mut(
214        self: Handle<Self>,
215        app: &mut App,
216    ) -> &mut SingleTickerProviderStateMixinData {
217        &mut app.get_mut(self).single_ticker_provider
218    }
219}
220
221/// Dart's `vsync: this`.
222impl TickerProviderObject for AccountDetailsState {
223    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
224        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
225    }
226}
227
228impl State for AccountDetailsState {
229    type Widget = AccountDetails;
230    waft_widgets::state_accessors!();
231
232    fn init_state(self: Handle<Self>, app: &mut App) {
233        let is_open = self.widget(app).is_open;
234        let controller = AnimationController::new(
235            app,
236            Some(if is_open { 1.0 } else { 0.0 }),
237            Some(Duration::from_millis(200)),
238            None,
239            0.0,
240            1.0,
241            AnimationBehavior::Normal,
242            self,
243        );
244        let animation = CurvedAnimation::new(
245            app,
246            controller.erase(),
247            Curves::fast_out_slow_in(),
248            Some(Rc::new(Curves::fast_out_slow_in().flipped()) as Rc<dyn Curve>),
249        );
250        animation.add_listener(
251            app,
252            Listener::handle_method(self, Self::handle_animation_changed),
253        );
254        let state = app.get_mut(self);
255        state.controller = Some(controller);
256        state.animation = Some(animation);
257    }
258
259    fn dispose(self: Handle<Self>, app: &mut App) {
260        let animation = self.animation(app);
261        let controller = self.controller(app);
262        controller.dispose(app);
263        animation.dispose(app);
264        SingleTickerProviderStateMixin::dispose(self, app);
265    }
266
267    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AccountDetails) {
268        if old_widget.is_open == self.widget(app).is_open {
269            return;
270        }
271        let controller = self.controller(app);
272        if self.widget(app).is_open {
273            controller.forward(app, None);
274        } else {
275            controller.reverse(app, None);
276        }
277    }
278
279    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
280        debug_assert!(debug_check_has_directionality(
281            app, context, None, None, None
282        ));
283        debug_assert!(debug_check_has_material_localizations(app, context));
284
285        let theme = Theme::of(app, context);
286        let localizations = <dyn MaterialLocalizations>::of(app, context);
287        let is_open = self.widget(app).is_open;
288        let arrow_color = self.widget(app).arrow_color;
289
290        let mut children: Vec<WidgetRef> = Vec::new();
291        if let Some(account_name) = &self.widget(app).account_name {
292            children.push(
293                LayoutId::new(
294                    account_name_id(),
295                    Padding::new(EdgeInsets::symmetric(2.0, 0.0)).child(
296                        DefaultTextStyle::new(
297                            theme
298                                .primary_text_theme
299                                .body_large
300                                .clone()
301                                .expect("the primary text theme has a body large"),
302                            account_name.clone(),
303                        )
304                        .overflow(TextOverflow::Ellipsis),
305                    ),
306                )
307                .into_widget(),
308            );
309        }
310        if let Some(account_email) = &self.widget(app).account_email {
311            children.push(
312                LayoutId::new(
313                    account_email_id(),
314                    Padding::new(EdgeInsets::symmetric(2.0, 0.0)).child(
315                        DefaultTextStyle::new(
316                            theme
317                                .primary_text_theme
318                                .body_medium
319                                .clone()
320                                .expect("the primary text theme has a body medium"),
321                            account_email.clone(),
322                        )
323                        .overflow(TextOverflow::Ellipsis),
324                    ),
325                )
326                .into_widget(),
327            );
328        }
329        if let Some(on_tap) = self.widget(app).on_tap.clone() {
330            let semantic_label = if is_open {
331                localizations.hide_accounts_label()
332            } else {
333                localizations.show_accounts_label()
334            };
335            let on_tap_for_semantics: waft_foundation::VoidCallback = Rc::new(move |app| {
336                on_tap.call(app);
337            });
338            let mut icon = Icon::new(Some(Icons::arrow_drop_down())).semantic_label(semantic_label);
339            if let Some(arrow_color) = arrow_color {
340                icon = icon.color(arrow_color);
341            }
342            children.push(
343                LayoutId::new(
344                    dropdown_icon_id(),
345                    Semantics::new()
346                        .container(true)
347                        .button(true)
348                        .on_tap(on_tap_for_semantics)
349                        .child(SizedBox::square(Some(K_ACCOUNT_DETAILS_HEIGHT)).child(
350                            Center::new().child(
351                                Transform::rotate(self.animation(app).value(app) * PI).child(icon),
352                            ),
353                        )),
354                )
355                .into_widget(),
356            );
357        }
358
359        let mut account_details = CustomMultiChildLayout::new(Rc::new(AccountDetailsLayout {
360            text_direction: Directionality::of(app, context),
361        }))
362        .children(children)
363        .into_widget();
364
365        if let Some(on_tap) = self.widget(app).on_tap.clone() {
366            account_details = InkWell::new()
367                .on_tap(on_tap)
368                .exclude_from_semantics(true)
369                .child(account_details)
370                .into_widget();
371        }
372
373        SizedBox::new()
374            .height(K_ACCOUNT_DETAILS_HEIGHT)
375            .child(account_details)
376            .into_widget()
377    }
378}
379
380/// Dart's `_AccountDetailsLayout`.
381#[derive(Debug)]
382struct AccountDetailsLayout {
383    text_direction: TextDirection,
384}
385
386impl AccountDetailsLayout {
387    fn offset_for_icon(&self, size: Size, icon_size: Size) -> Offset {
388        match self.text_direction {
389            TextDirection::Ltr => Offset::new(
390                size.width() - icon_size.width(),
391                size.height() - icon_size.height(),
392            ),
393            TextDirection::Rtl => Offset::new(0.0, size.height() - icon_size.height()),
394        }
395    }
396
397    fn offset_for_bottom_line(
398        &self,
399        size: Size,
400        icon_size: Size,
401        bottom_line_size: Size,
402    ) -> Offset {
403        let y = size.height() - 0.5 * icon_size.height() - 0.5 * bottom_line_size.height();
404        match self.text_direction {
405            TextDirection::Ltr => Offset::new(0.0, y),
406            TextDirection::Rtl => Offset::new(size.width() - bottom_line_size.width(), y),
407        }
408    }
409
410    fn offset_for_name(&self, size: Size, name_size: Size, bottom_line_offset: Offset) -> Offset {
411        let y = bottom_line_offset.dy() - name_size.height();
412        match self.text_direction {
413            TextDirection::Ltr => Offset::new(0.0, y),
414            TextDirection::Rtl => Offset::new(size.width() - name_size.width(), y),
415        }
416    }
417}
418
419impl MultiChildLayoutDelegate for AccountDetailsLayout {
420    fn perform_layout(&self, app: &mut App, children: &mut MultiChildLayoutChildren, size: Size) {
421        let mut icon_size = None;
422        if children.has_child(&dropdown_icon_id()) {
423            let size_of_icon =
424                children.layout_child(app, &dropdown_icon_id(), BoxConstraints::loose(size));
425            children.position_child(
426                app,
427                &dropdown_icon_id(),
428                self.offset_for_icon(size, size_of_icon),
429            );
430            icon_size = Some(size_of_icon);
431        }
432
433        let bottom_line = if children.has_child(&account_email_id()) {
434            Some(account_email_id())
435        } else if children.has_child(&account_name_id()) {
436            Some(account_name_id())
437        } else {
438            None
439        };
440
441        if let Some(bottom_line) = bottom_line {
442            let constraint_size = match icon_size {
443                Some(icon_size) => Size::new(size.width() - icon_size.width(), size.height()),
444                None => size,
445            };
446            let icon_size = icon_size.unwrap_or(Size::new(
447                K_ACCOUNT_DETAILS_HEIGHT,
448                K_ACCOUNT_DETAILS_HEIGHT,
449            ));
450
451            let bottom_line_size =
452                children.layout_child(app, &bottom_line, BoxConstraints::loose(constraint_size));
453            let bottom_line_offset = self.offset_for_bottom_line(size, icon_size, bottom_line_size);
454            children.position_child(app, &bottom_line, bottom_line_offset);
455
456            if bottom_line == account_email_id() && children.has_child(&account_name_id()) {
457                let name_size = children.layout_child(
458                    app,
459                    &account_name_id(),
460                    BoxConstraints::loose(constraint_size),
461                );
462                children.position_child(
463                    app,
464                    &account_name_id(),
465                    self.offset_for_name(size, name_size, bottom_line_offset),
466                );
467            }
468        }
469    }
470
471    fn should_relayout(&self, _old_delegate: &dyn MultiChildLayoutDelegate) -> bool {
472        true
473    }
474
475    fn as_any(&self) -> &dyn Any {
476        self
477    }
478}
479
480/// A Material Design drawer header that identifies the app's user.
481///
482/// Requires one of its ancestors to be a `Material` widget.
483///
484/// See also:
485///
486///  * `DrawerHeader`, for a drawer header that doesn't show user accounts.
487///  * <https://material.io/design/components/navigation-drawer.html#anatomy>
488pub struct UserAccountsDrawerHeader {
489    pub key: Option<KeyRef>,
490    /// The header's background. If decoration is null then a `BoxDecoration`
491    /// with its background color set to the current theme's primaryColor is used.
492    pub decoration: Option<DecorationRef>,
493    /// The margin around the drawer header.
494    pub margin: Option<EdgeInsetsGeometry>,
495    /// A widget placed in the upper-left corner that represents the current
496    /// user's account. Normally a `CircleAvatar`.
497    pub current_account_picture: Option<WidgetRef>,
498    /// A list of widgets that represent the current user's other accounts.
499    ///
500    /// Up to three of these widgets will be arranged in a row in the header's
501    /// upper-right corner. Normally a list of `CircleAvatar` widgets.
502    pub other_accounts_pictures: Option<Vec<WidgetRef>>,
503    /// The size of the `currentAccountPicture`.
504    pub current_account_picture_size: Size,
505    /// The size of each widget in `otherAccountsPicturesSize`.
506    pub other_accounts_pictures_size: Size,
507    /// A widget that represents the user's current account name. It is
508    /// displayed on the left, below the `currentAccountPicture`.
509    pub account_name: Option<WidgetRef>,
510    /// A widget that represents the email address of the user's current account.
511    /// It is displayed on the left, below the `accountName`.
512    pub account_email: Option<WidgetRef>,
513    /// A callback that is called when the horizontal area which contains the
514    /// `accountName` and `accountEmail` is tapped.
515    pub on_details_pressed: Option<Listener>,
516    /// The `Color` of the arrow icon.
517    pub arrow_color: Color,
518}
519
520impl UserAccountsDrawerHeader {
521    /// Creates a Material Design drawer header; Dart's optional named arguments are the setters.
522    ///
523    /// Requires one of its ancestors to be a `Material` widget.
524    pub fn new(
525        account_name: Option<WidgetRef>,
526        account_email: Option<WidgetRef>,
527    ) -> UserAccountsDrawerHeader {
528        UserAccountsDrawerHeader {
529            key: None,
530            decoration: None,
531            margin: Some(EdgeInsets::only(0.0, 0.0, 0.0, 8.0).into()),
532            current_account_picture: None,
533            other_accounts_pictures: None,
534            current_account_picture_size: Size::square(72.0),
535            other_accounts_pictures_size: Size::square(40.0),
536            account_name,
537            account_email,
538            on_details_pressed: None,
539            arrow_color: Colors::WHITE,
540        }
541    }
542
543    /// Dart `UserAccountsDrawerHeader(key:)`.
544    pub fn key(mut self, key: KeyRef) -> UserAccountsDrawerHeader {
545        self.key = Some(key);
546        self
547    }
548
549    /// Dart `UserAccountsDrawerHeader(decoration:)`.
550    pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> UserAccountsDrawerHeader {
551        self.decoration = Some(decoration.into());
552        self
553    }
554
555    /// Dart `UserAccountsDrawerHeader(margin:)`.
556    pub fn margin(mut self, margin: Option<EdgeInsetsGeometry>) -> UserAccountsDrawerHeader {
557        self.margin = margin;
558        self
559    }
560
561    /// Dart `UserAccountsDrawerHeader(currentAccountPicture:)`.
562    #[cfg_attr(debug_assertions, track_caller)]
563    pub fn current_account_picture<K>(
564        mut self,
565        current_account_picture: impl IntoWidget<K>,
566    ) -> UserAccountsDrawerHeader {
567        self.current_account_picture = Some(current_account_picture.into_widget());
568        self
569    }
570
571    /// Dart `UserAccountsDrawerHeader(otherAccountsPictures:)`.
572    pub fn other_accounts_pictures(
573        mut self,
574        other_accounts_pictures: impl IntoIterator<Item = WidgetRef>,
575    ) -> UserAccountsDrawerHeader {
576        self.other_accounts_pictures = Some(other_accounts_pictures.into_iter().collect());
577        self
578    }
579
580    /// Dart `UserAccountsDrawerHeader(currentAccountPictureSize:)`.
581    pub fn current_account_picture_size(
582        mut self,
583        current_account_picture_size: Size,
584    ) -> UserAccountsDrawerHeader {
585        self.current_account_picture_size = current_account_picture_size;
586        self
587    }
588
589    /// Dart `UserAccountsDrawerHeader(otherAccountsPicturesSize:)`.
590    pub fn other_accounts_pictures_size(
591        mut self,
592        other_accounts_pictures_size: Size,
593    ) -> UserAccountsDrawerHeader {
594        self.other_accounts_pictures_size = other_accounts_pictures_size;
595        self
596    }
597
598    /// Dart `UserAccountsDrawerHeader(onDetailsPressed:)`.
599    pub fn on_details_pressed(mut self, on_details_pressed: Listener) -> UserAccountsDrawerHeader {
600        self.on_details_pressed = Some(on_details_pressed);
601        self
602    }
603
604    /// Dart `UserAccountsDrawerHeader(arrowColor:)`.
605    pub fn arrow_color(mut self, arrow_color: Color) -> UserAccountsDrawerHeader {
606        self.arrow_color = arrow_color;
607        self
608    }
609}
610
611impl fmt::Debug for UserAccountsDrawerHeader {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        f.debug_struct("UserAccountsDrawerHeader")
614            .finish_non_exhaustive()
615    }
616}
617
618impl StatefulWidget for UserAccountsDrawerHeader {
619    type State = UserAccountsDrawerHeaderState;
620
621    fn create_state(&self) -> UserAccountsDrawerHeaderState {
622        UserAccountsDrawerHeaderState {
623            state: StateData::new(),
624            is_open: false,
625        }
626    }
627}
628
629/// Dart's `_UserAccountsDrawerHeaderState`.
630pub struct UserAccountsDrawerHeaderState {
631    state: StateData<UserAccountsDrawerHeader>,
632    is_open: bool,
633}
634
635impl UserAccountsDrawerHeaderState {
636    fn handle_details_pressed(self: Handle<Self>, app: &mut App) {
637        self.set_state(app, |state| state.is_open = !state.is_open);
638        let on_details_pressed = self
639            .widget(app)
640            .on_details_pressed
641            .clone()
642            .expect("the tap handler is only used when one is set");
643        on_details_pressed.call(app);
644    }
645}
646
647impl fmt::Debug for UserAccountsDrawerHeaderState {
648    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649        f.debug_struct("UserAccountsDrawerHeaderState")
650            .field("is_open", &self.is_open)
651            .finish_non_exhaustive()
652    }
653}
654
655impl State for UserAccountsDrawerHeaderState {
656    type Widget = UserAccountsDrawerHeader;
657    waft_widgets::state_accessors!();
658
659    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
660        debug_assert!(debug_check_has_material(app, context));
661        debug_assert!(debug_check_has_material_localizations(app, context));
662
663        let theme = Theme::of(app, context);
664        let localizations = <dyn MaterialLocalizations>::of(app, context);
665        let widget = self.widget(app);
666        let decoration = widget.decoration.clone().unwrap_or_else(|| {
667            BoxDecoration::new()
668                .color(theme.color_scheme.primary())
669                .into()
670        });
671        let is_open = app.get(self).is_open;
672        let on_tap = widget
673            .on_details_pressed
674            .as_ref()
675            .map(|_| Listener::handle_method(self, Self::handle_details_pressed));
676
677        let details = AccountDetails::new(
678            widget.account_name.clone(),
679            widget.account_email.clone(),
680            on_tap,
681            is_open,
682            Some(widget.arrow_color),
683        );
684        let pictures = AccountPictures::new(
685            widget.current_account_picture.clone(),
686            widget.other_accounts_pictures.clone(),
687            Some(widget.current_account_picture_size),
688            Some(widget.other_accounts_pictures_size),
689        );
690
691        let child = SafeArea::new(
692            Column::new()
693                .cross_axis_alignment(CrossAxisAlignment::Stretch)
694                .children(vec![
695                    Expanded::new(
696                        Padding::new(EdgeInsetsDirectional::only(0.0, 0.0, 16.0, 0.0))
697                            .child(pictures),
698                    )
699                    .into_widget(),
700                    details.into_widget(),
701                ]),
702        )
703        .bottom(false);
704
705        Semantics::new()
706            .container(true)
707            .label(localizations.signed_in_label())
708            .child(
709                DrawerHeader::new(Some(child.into_widget()))
710                    .decoration(decoration)
711                    .margin(widget.margin)
712                    .padding(EdgeInsetsDirectional::only(16.0, 16.0, 0.0, 0.0)),
713            )
714            .into_widget()
715    }
716}
717
718#[cfg(test)]
719mod tests {
720    use std::cell::RefCell;
721    use std::rc::Rc;
722
723    use waft_embedder::{Size, TextDirection};
724    use waft_widgets::testing::{WidgetTester, find, test_widgets};
725    use waft_widgets::{
726        Center, Directionality, ExcludeSemantics, IntoWidget, MediaQuery, MediaQueryData, SizedBox,
727        StateSetter, StatefulBuilder, Text,
728    };
729
730    use super::*;
731    use crate::circle_avatar::CircleAvatar;
732    use crate::color_scheme::ColorScheme;
733    use crate::material::Material;
734    use crate::scaffold::Scaffold as MaterialScaffold;
735    use crate::test_support::material_app;
736    use crate::theme_data::ThemeData;
737
738    /// Dart's `pumpTestWidget`.
739    struct Options {
740        with_name: bool,
741        with_email: bool,
742        with_on_details_pressed_handler: bool,
743        other_accounts_picture_size: Size,
744        current_account_picture_size: Size,
745        primary_color: Option<Color>,
746        color_scheme_primary: Option<Color>,
747    }
748
749    impl Default for Options {
750        fn default() -> Options {
751            Options {
752                with_name: true,
753                with_email: true,
754                with_on_details_pressed_handler: true,
755                other_accounts_picture_size: Size::square(40.0),
756                current_account_picture_size: Size::square(72.0),
757                primary_color: None,
758                color_scheme_primary: None,
759            }
760        }
761    }
762
763    fn avatar(name: &'static str) -> CircleAvatar {
764        CircleAvatar::new().child(Text::new(name))
765    }
766
767    fn keyed_avatar(name: &'static str) -> CircleAvatar {
768        avatar(name).key(key(name))
769    }
770
771    fn header(options: &Options) -> UserAccountsDrawerHeader {
772        let mut header = UserAccountsDrawerHeader::new(
773            options.with_name.then(|| Text::new("name").into_widget()),
774            options.with_email.then(|| Text::new("email").into_widget()),
775        )
776        .current_account_picture_size(options.current_account_picture_size)
777        .other_accounts_pictures_size(options.other_accounts_picture_size)
778        .current_account_picture(ExcludeSemantics::new().child(keyed_avatar("A")))
779        .other_accounts_pictures(vec![
780            avatar("B").into_widget(),
781            keyed_avatar("C").into_widget(),
782            keyed_avatar("D").into_widget(),
783            avatar("E").into_widget(),
784        ]);
785        if options.with_on_details_pressed_handler {
786            header = header.on_details_pressed(Listener::new(|_app| {}));
787        }
788        header
789    }
790
791    fn pump_test_widget(tester: &mut WidgetTester, options: Options) {
792        let mut builder = ThemeData::builder();
793        if let Some(primary_color) = options.primary_color {
794            builder = builder.primary_color(primary_color);
795        }
796        let mut color_scheme = ColorScheme::light();
797        if let Some(color_scheme_primary) = options.color_scheme_primary {
798            color_scheme = color_scheme.with_primary(color_scheme_primary);
799        }
800        let theme = builder
801            .color_scheme(color_scheme)
802            .build(&tester.cell.borrow());
803
804        let mut data = MediaQueryData::new();
805        data.padding = EdgeInsets::only(10.0, 20.0, 30.0, 40.0);
806        let home = MediaQuery::new(
807            data,
808            Material::new()
809                .child(Center::new().child(header(&options)))
810                .into_widget(),
811        );
812        tester.pump_widget(material_app(theme, home.into_widget()));
813    }
814
815    fn key(key: &'static str) -> KeyRef {
816        KeyRef::from(ValueKey::new(key))
817    }
818
819    #[test]
820    fn the_header_inherits_the_color_scheme_primary() {
821        test_widgets(|tester| {
822            let primary_color = Color::new(0xFF00FF00);
823            let color_scheme_primary = Color::new(0xFF0000FF);
824            pump_test_widget(
825                tester,
826                Options {
827                    primary_color: Some(primary_color),
828                    color_scheme_primary: Some(color_scheme_primary),
829                    ..Options::default()
830                },
831            );
832
833            let decoration = tester
834                .widget(find::by_type::<DrawerHeader>(), |header: &DrawerHeader| {
835                    header.decoration.clone()
836                })
837                .expect("the header has a decoration");
838            let decoration = decoration
839                .as_any()
840                .downcast_ref::<BoxDecoration>()
841                .expect("a box decoration");
842            let color = decoration.color.as_ref().map(|color| color.color());
843            assert_ne!(color, Some(primary_color));
844            assert_eq!(color, Some(color_scheme_primary));
845        });
846    }
847
848    #[test]
849    fn the_header_lays_out_the_pictures_and_the_account() {
850        test_widgets(|tester| {
851            pump_test_widget(tester, Options::default());
852
853            for text in ["A", "B", "C", "D"] {
854                assert!(
855                    !find::text(text).evaluate(tester).is_empty(),
856                    "{text} is shown"
857                );
858            }
859            assert!(
860                find::text("E").evaluate(tester).is_empty(),
861                "only three others"
862            );
863            assert_eq!(find::text("name").evaluate(tester).len(), 1);
864            assert_eq!(find::text("email").evaluate(tester).len(), 1);
865            assert_eq!(tester.get_size(find::by_key(key("A"))), Size::square(72.0));
866            assert_eq!(tester.get_size(find::by_key(key("C"))), Size::square(40.0));
867            assert_eq!(
868                tester
869                    .get_size(find::by_type::<UserAccountsDrawerHeader>())
870                    .height(),
871                160.0 + 20.0 + 8.0 + 1.0
872            );
873
874            let top_left = tester.get_top_left(find::by_type::<UserAccountsDrawerHeader>());
875            let top_right = tester.get_top_right(find::by_type::<UserAccountsDrawerHeader>());
876            let a = tester.get_top_left(find::by_key(key("A")));
877            let d = tester.get_top_right(find::by_key(key("D")));
878            let c = tester.get_top_right(find::by_key(key("C")));
879
880            assert_eq!(a.dx() - top_left.dx(), 16.0 + 10.0);
881            assert_eq!(a.dy() - top_left.dy(), 16.0 + 20.0);
882            assert_eq!(top_right.dx() - d.dx(), 16.0 + 30.0);
883            assert_eq!(d.dy() - top_right.dy(), 16.0 + 20.0);
884            assert_eq!(d.dx() - c.dx(), 40.0 + 16.0);
885        });
886    }
887
888    #[test]
889    fn the_picture_sizes_can_change() {
890        test_widgets(|tester| {
891            pump_test_widget(
892                tester,
893                Options {
894                    current_account_picture_size: Size::square(60.0),
895                    other_accounts_picture_size: Size::square(30.0),
896                    ..Options::default()
897                },
898            );
899            assert_eq!(tester.get_size(find::by_key(key("A"))), Size::square(60.0));
900            assert_eq!(tester.get_size(find::by_key(key("C"))), Size::square(30.0));
901        });
902    }
903
904    /// Dart's `transform.getRotation()[0]` and `[4]` of the first transform in the header: the
905    /// cosine of the arrow's turn, twice.
906    fn rotation(tester: &WidgetTester) -> (f32, f32) {
907        tester.widget(
908            find::descendant(
909                find::by_type::<UserAccountsDrawerHeader>(),
910                find::by_type::<Transform>(),
911            )
912            .first(),
913            |transform: &Transform| {
914                let storage = transform.transform.to_flutter_array();
915                (storage[0], storage[5])
916            },
917        )
918    }
919
920    const RIGHT_SIDE_UP: (f32, f32) = (1.0, 1.0);
921    const UPSIDE_DOWN: (f32, f32) = (-1.0, -1.0);
922
923    #[test]
924    fn the_arrow_turns_half_a_turn_and_back() {
925        test_widgets(|tester| {
926            pump_test_widget(tester, Options::default());
927
928            // Icon is right side up.
929            assert_eq!(rotation(tester), RIGHT_SIDE_UP);
930
931            tester.tap(find::by_type::<Icon>());
932            tester.pump();
933            tester.pump_by(Duration::from_millis(10));
934            assert!(tester.has_running_animations());
935
936            tester.pump_and_settle();
937            tester.pump();
938
939            // Icon has rotated 180 degrees.
940            assert_eq!(rotation(tester), UPSIDE_DOWN);
941
942            tester.tap(find::by_type::<Icon>());
943            tester.pump();
944            tester.pump_by(Duration::from_millis(10));
945            assert!(tester.has_running_animations());
946
947            tester.pump_and_settle();
948            tester.pump();
949
950            // Icon has rotated 180 degrees back to the original position.
951            assert_eq!(rotation(tester), RIGHT_SIDE_UP);
952        });
953    }
954
955    #[test]
956    fn the_arrow_keeps_turning_through_four_mid_animation_taps() {
957        test_widgets(|tester| {
958            pump_test_widget(tester, Options::default());
959            assert_eq!(rotation(tester), RIGHT_SIDE_UP);
960
961            // Down, up, down again and back up, each mid animation.
962            for _ in 0..4 {
963                tester.tap(find::by_type::<Icon>());
964                tester.pump();
965                tester.pump_by(Duration::from_millis(100));
966                assert!(tester.has_running_animations());
967            }
968
969            tester.pump_and_settle();
970            tester.pump();
971            assert_eq!(rotation(tester), RIGHT_SIDE_UP);
972        });
973    }
974
975    #[test]
976    fn a_rebuild_does_not_turn_the_arrow() {
977        test_widgets(|tester| {
978            let set_state: Rc<RefCell<Option<StateSetter>>> = Rc::default();
979            let captured = Rc::clone(&set_state);
980            let home = StatefulBuilder::new(move |_app, _context, set_state| {
981                *captured.borrow_mut() = Some(set_state);
982                UserAccountsDrawerHeader::new(
983                    Some(Text::new("name").into_widget()),
984                    Some(Text::new("email").into_widget()),
985                )
986                .on_details_pressed(Listener::new(|_app| {}))
987                .into_widget()
988            });
989            let theme = ThemeData::builder().build(&tester.cell.borrow());
990            tester.pump_widget(material_app(
991                theme,
992                Material::new().child(home).into_widget(),
993            ));
994            assert_eq!(rotation(tester), RIGHT_SIDE_UP);
995
996            let set_state = set_state.borrow().clone().expect("the builder ran");
997            set_state(&mut tester.cell.borrow_mut(), &mut |_app: &mut App| {});
998            tester.pump_by(Duration::from_millis(10));
999            assert!(!tester.has_running_animations());
1000
1001            assert_eq!(tester.pump_and_settle(), 1);
1002
1003            // Icon has not rotated.
1004            assert_eq!(rotation(tester), RIGHT_SIDE_UP);
1005        });
1006    }
1007
1008    #[test]
1009    fn the_arrow_color_defaults_to_white_and_can_be_set() {
1010        test_widgets(|tester| {
1011            let theme = ThemeData::builder().build(&tester.cell.borrow());
1012            tester.pump_widget(material_app(
1013                theme,
1014                Material::new()
1015                    .child(
1016                        UserAccountsDrawerHeader::new(
1017                            Some(Text::new("name").into_widget()),
1018                            Some(Text::new("email").into_widget()),
1019                        )
1020                        .on_details_pressed(Listener::new(|_app| {})),
1021                    )
1022                    .into_widget(),
1023            ));
1024            let color = tester.widget(find::by_type::<Icon>(), |icon: &Icon| {
1025                icon.color.as_ref().map(|color| color.color())
1026            });
1027            assert_eq!(color, Some(Colors::WHITE));
1028
1029            let theme = ThemeData::builder().build(&tester.cell.borrow());
1030            tester.pump_widget(material_app(
1031                theme,
1032                Material::new()
1033                    .child(
1034                        UserAccountsDrawerHeader::new(
1035                            Some(Text::new("name").into_widget()),
1036                            Some(Text::new("email").into_widget()),
1037                        )
1038                        .on_details_pressed(Listener::new(|_app| {}))
1039                        .arrow_color(Colors::RED.primary()),
1040                    )
1041                    .into_widget(),
1042            ));
1043            let color = tester.widget(find::by_type::<Icon>(), |icon: &Icon| {
1044                icon.color.as_ref().map(|color| color.color())
1045            });
1046            assert_eq!(color, Some(Colors::RED.primary()));
1047        });
1048    }
1049
1050    /// The arguments of the null parameters cases' `buildFrame`; `margin` is always null.
1051    #[derive(Default)]
1052    struct Frame {
1053        current_account_picture: Option<WidgetRef>,
1054        other_accounts_pictures: Option<Vec<WidgetRef>>,
1055        account_name: Option<&'static str>,
1056        account_email: Option<&'static str>,
1057        on_details_pressed: bool,
1058    }
1059
1060    fn pump_frame(tester: &mut WidgetTester, direction: TextDirection, frame: Frame) {
1061        let mut header = UserAccountsDrawerHeader::new(
1062            frame.account_name.map(|name| Text::new(name).into_widget()),
1063            frame
1064                .account_email
1065                .map(|email| Text::new(email).into_widget()),
1066        )
1067        .margin(None);
1068        if let Some(current_account_picture) = frame.current_account_picture {
1069            header = header.current_account_picture(current_account_picture);
1070        }
1071        if let Some(other_accounts_pictures) = frame.other_accounts_pictures {
1072            header = header.other_accounts_pictures(other_accounts_pictures);
1073        }
1074        if frame.on_details_pressed {
1075            header = header.on_details_pressed(Listener::new(|_app| {}));
1076        }
1077        let theme = ThemeData::builder().build(&tester.cell.borrow());
1078        tester.pump_widget(material_app(
1079            theme,
1080            Directionality::new(
1081                direction,
1082                Material::new().child(Center::new().child(header)),
1083            )
1084            .into_widget(),
1085        ));
1086    }
1087
1088    /// Dart's `UserAccountsDrawerHeader null parameters LTR` and `RTL`: `before` is whether
1089    /// the start of `direction` has the smaller x.
1090    fn check_null_parameters(tester: &mut WidgetTester, direction: TextDirection) {
1091        let ltr = direction == TextDirection::Ltr;
1092        let before = |a: f64, b: f64| if ltr { a < b } else { a > b };
1093        let icon = find::by_type::<Icon>;
1094
1095        pump_frame(tester, direction, Frame::default());
1096        assert_eq!(
1097            tester
1098                .get_size(find::by_type::<UserAccountsDrawerHeader>())
1099                .height(),
1100            160.0 + 1.0 // height + bottom edge
1101        );
1102        assert!(icon().evaluate(tester).is_empty());
1103
1104        pump_frame(
1105            tester,
1106            direction,
1107            Frame {
1108                on_details_pressed: true,
1109                ..Frame::default()
1110            },
1111        );
1112        assert_eq!(icon().evaluate(tester).len(), 1);
1113
1114        for (account_name, account_email) in
1115            [(Some("accountName"), None), (None, Some("accountEmail"))]
1116        {
1117            pump_frame(
1118                tester,
1119                direction,
1120                Frame {
1121                    account_name,
1122                    account_email,
1123                    on_details_pressed: true,
1124                    ..Frame::default()
1125                },
1126            );
1127            let line =
1128                tester.get_center(find::text(account_name.or(account_email).expect("a line")));
1129            let arrow = tester.get_center(icon());
1130            assert_eq!(line.dy(), arrow.dy());
1131            assert!(before(line.dx(), arrow.dx()));
1132        }
1133
1134        pump_frame(
1135            tester,
1136            direction,
1137            Frame {
1138                account_name: Some("accountName"),
1139                account_email: Some("accountEmail"),
1140                on_details_pressed: true,
1141                ..Frame::default()
1142            },
1143        );
1144        let email = tester.get_center(find::text("accountEmail"));
1145        let arrow = tester.get_center(icon());
1146        assert_eq!(email.dy(), arrow.dy());
1147        assert!(before(email.dx(), arrow.dx()));
1148        assert!(
1149            tester.get_bottom_left(find::text("accountEmail")).dy()
1150                > tester.get_bottom_left(find::text("accountName")).dy()
1151        );
1152        if ltr {
1153            assert_eq!(
1154                tester.get_bottom_left(find::text("accountEmail")).dx(),
1155                tester.get_bottom_left(find::text("accountName")).dx()
1156            );
1157        } else {
1158            assert_eq!(
1159                tester.get_bottom_right(find::text("accountEmail")).dx(),
1160                tester.get_bottom_right(find::text("accountName")).dx()
1161            );
1162        }
1163
1164        pump_frame(
1165            tester,
1166            direction,
1167            Frame {
1168                current_account_picture: Some(avatar("A").into_widget()),
1169                ..Frame::default()
1170            },
1171        );
1172        assert_eq!(find::text("A").evaluate(tester).len(), 1);
1173
1174        pump_frame(
1175            tester,
1176            direction,
1177            Frame {
1178                other_accounts_pictures: Some(vec![avatar("A").into_widget()]),
1179                ..Frame::default()
1180            },
1181        );
1182        assert_eq!(find::text("A").evaluate(tester).len(), 1);
1183
1184        pump_frame(
1185            tester,
1186            direction,
1187            Frame {
1188                current_account_picture: Some(keyed_avatar("A").into_widget()),
1189                account_name: Some("accountName"),
1190                ..Frame::default()
1191            },
1192        );
1193        if ltr {
1194            assert_eq!(
1195                tester.get_bottom_left(find::by_key(key("A"))).dx(),
1196                tester.get_bottom_left(find::text("accountName")).dx()
1197            );
1198        } else {
1199            assert_eq!(
1200                tester.get_bottom_right(find::by_key(key("A"))).dx(),
1201                tester.get_bottom_right(find::text("accountName")).dx()
1202            );
1203        }
1204        assert!(
1205            tester.get_bottom_left(find::text("accountName")).dy()
1206                > tester.get_bottom_left(find::by_key(key("A"))).dy()
1207        );
1208    }
1209
1210    #[test]
1211    fn user_accounts_drawer_header_null_parameters_ltr() {
1212        test_widgets(|tester| check_null_parameters(tester, TextDirection::Ltr));
1213    }
1214
1215    #[test]
1216    fn user_accounts_drawer_header_null_parameters_rtl() {
1217        test_widgets(|tester| check_null_parameters(tester, TextDirection::Rtl));
1218    }
1219
1220    #[test]
1221    fn the_header_does_not_crash_at_zero_area() {
1222        test_widgets(|tester| {
1223            let theme = ThemeData::builder().build(&tester.cell.borrow());
1224            tester.pump_widget(material_app(
1225                theme,
1226                MaterialScaffold::new()
1227                    .body(Center::new().child(SizedBox::shrink().child(
1228                        UserAccountsDrawerHeader::new(
1229                            Some(Text::new("X").into_widget()),
1230                            Some(Text::new("Y").into_widget()),
1231                        ),
1232                    )))
1233                    .into_widget(),
1234            ));
1235            assert_eq!(
1236                tester.get_size(find::by_type::<UserAccountsDrawerHeader>()),
1237                Size::ZERO
1238            );
1239        });
1240    }
1241}