Skip to main content

waft_winui/controls/
drop_down_button.rs

1//! DropDownButton.xaml: Button interaction with a content column and dropdown chevron.
2
3use crate::*;
4use std::fmt;
5use waft_embedder::FontWeight;
6use waft_foundation::{App, Listener, Ref};
7use waft_painting::EdgeInsetsGeometry;
8use waft_widgets::*;
9
10/// A button that displays a chevron and opens its associated flyout after Click.
11#[derive(Clone)]
12pub struct DropDownButton {
13    /// Content in the first template column.
14    pub content: WidgetRef,
15
16    /// Associated persistent flyout, owned and disposed by the caller.
17    pub flyout: Option<Ref<Flyout>>,
18
19    /// Called before opening the associated flyout.
20    pub click: Option<Listener>,
21
22    /// Whether pointer and keyboard input can activate the button.
23    pub is_enabled: bool,
24
25    /// Whether keyboard traversal stops at the button.
26    pub is_tab_stop: bool,
27
28    /// Optional caller-owned focus node.
29    pub focus_node: Option<FocusNodeRef>,
30
31    /// Widget identity across parent rebuilds.
32    pub key: Option<KeyRef>,
33}
34
35impl fmt::Debug for DropDownButton {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.debug_struct("DropDownButton")
38            .field("flyout", &self.flyout)
39            .field("is_enabled", &self.is_enabled)
40            .finish_non_exhaustive()
41    }
42}
43
44impl DropDownButton {
45    /// Creates a button with the default DropDownButton template.
46    #[cfg_attr(debug_assertions, track_caller)]
47    pub fn new<K>(content: impl IntoWidget<K>) -> Self {
48        Self {
49            content: content.into_widget(),
50            flyout: None,
51            click: None,
52            is_enabled: true,
53            is_tab_stop: true,
54            focus_node: None,
55            key: None,
56        }
57    }
58
59    /// Creates a button with a text label.
60    pub fn text(text: impl Into<String>) -> Self {
61        Self::new(Text::new(text))
62    }
63
64    /// Associates a reusable flyout with the button.
65    pub fn flyout(mut self, flyout: Ref<Flyout>) -> Self {
66        self.flyout = Some(flyout);
67        self
68    }
69
70    /// Sets the callback raised before opening the flyout.
71    pub fn click(mut self, click: Listener) -> Self {
72        self.click = Some(click);
73        self
74    }
75
76    /// Enables or disables activation.
77    pub fn is_enabled(mut self, value: bool) -> Self {
78        self.is_enabled = value;
79        self
80    }
81
82    /// Includes or excludes this button from sequential keyboard traversal.
83    pub fn is_tab_stop(mut self, value: bool) -> Self {
84        self.is_tab_stop = value;
85        self
86    }
87
88    /// Supplies a caller-owned focus node.
89    pub fn focus_node(mut self, node: FocusNodeRef) -> Self {
90        self.focus_node = Some(node);
91        self
92    }
93
94    /// Sets widget identity.
95    pub fn key(mut self, key: KeyRef) -> Self {
96        self.key = Some(key);
97        self
98    }
99}
100
101impl StatelessWidget for DropDownButton {
102    fn key(&self) -> Option<&KeyRef> {
103        self.key.as_ref()
104    }
105
106    fn build(&self, _: &mut App, _: BuildContext) -> WidgetRef {
107        let widget = self.clone();
108        FlyoutTarget::new(Builder::new(move |_, context| {
109            let flyout = widget.flyout.clone();
110            let click = widget.click.clone();
111            let mut button = Button::new(
112                widget.content.clone(),
113                Listener::new(move |app| {
114                    if let Some(click) = &click {
115                        click.call(app);
116                    }
117                    if let Some(flyout) = &flyout {
118                        flyout.show_at(app, context);
119                    }
120                }),
121            )
122            .is_enabled(widget.is_enabled)
123            .is_tab_stop(widget.is_tab_stop)
124            .template(template);
125            if let Some(focus) = widget.focus_node.clone() {
126                button = button.focus_node(focus);
127            }
128            button.into_widget()
129        }))
130        .into_widget()
131    }
132}
133
134/// RootGrid, ContentPresenter and ChevronIcon in DefaultDropDownButtonStyle.
135fn template(
136    app: &mut App,
137    context: BuildContext,
138    states: ControlStates,
139    content: WidgetRef,
140) -> WidgetRef {
141    let theme = ThemeResources::of(app, context);
142    let resources = &theme;
143    let brushes = ButtonStyle::Default.brushes(&theme, states.common);
144    let chevron = match states.common {
145        CommonState::Normal => resources.drop_down_button_foreground_secondary,
146        CommonState::PointerOver => resources.drop_down_button_foreground_secondary_pointer_over,
147        CommonState::Pressed => resources.drop_down_button_foreground_secondary_pressed,
148        CommonState::Disabled => resources.button_foreground_disabled,
149    };
150    let content = Grid::new()
151        .column_definitions([
152            ColumnDefinition::new(GridLength::STAR),
153            ColumnDefinition::new(GridLength::AUTO),
154        ])
155        .children([
156            GridCell::new(Center::new().width_factor(1.0).height_factor(1.0).child(
157                DefaultTextStyle::new(
158                    control_text_style(
159                        &theme,
160                        theme.control_content_theme_font_size,
161                        FontWeight::NORMAL,
162                        brushes.foreground,
163                    ),
164                    content,
165                ),
166            ))
167            .into_widget(),
168            GridCell::new(
169                Padding::new(EdgeInsetsGeometry::from_ltrb(8.0, 0.0, 0.0, 0.0)).child(
170                    SizedBox::new().width(12.0).height(12.0).child(
171                        Center::new().child(
172                            FontIcon::symbol(FluentSymbol::ChevronDown)
173                                .font_size(8.0)
174                                .foreground(chevron),
175                        ),
176                    ),
177                ),
178            )
179            .column(1)
180            .into_widget(),
181        ])
182        .into_widget();
183    let (corner_radius, padding) = (theme.control_corner_radius, theme.button_padding);
184    let root = ColorTransition::new(
185        brushes.background,
186        theme.control_faster_animation_duration,
187        move |_, background| {
188            ControlBorder::new(Brush::Solid(background), brushes.border)
189                .border_thickness(BUTTON_BORDER_THICKNESS)
190                .corner_radius_corners(corner_radius)
191                .padding(padding)
192                .child(content.clone())
193                .into_widget()
194        },
195    );
196    FocusVisual::new(root, theme.theme)
197        .visible(states.focused)
198        .margin(BUTTON_FOCUS_VISUAL_MARGIN)
199        .corner_radius(corner_radius[0])
200        .into_widget()
201}