Skip to main content

waft_winui/controls/
button.rs

1//! XAML `Button` with the `DefaultButtonStyle`, `AccentButtonStyle` and `SubtleButtonStyle` of `Button_themeresources.xaml`.
2//!
3//! The template is one `ContentPresenter` (`x:Name="ContentPresenter"`) carrying `Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`, `Padding` and `Foreground`, with a `BrushTransition` of 83 ms on `Background`; the `CommonStates` storyboards swap those brushes per state.
4
5use crate::{
6    BackgroundSizing, Brush, ColorTransition, CommonState, CommonStates, ControlBorder,
7    ControlStates, FocusVisual, ThemeResources, control_text_style,
8};
9use std::{fmt, rc::Rc};
10use waft_embedder::{Color, FontWeight};
11use waft_foundation::{App, Listener};
12use waft_widgets::*;
13
14/// A source control template receiving the button state and its content.
15pub type ButtonTemplate = Rc<dyn Fn(&mut App, BuildContext, ControlStates, WidgetRef) -> WidgetRef>;
16
17/// XAML `ButtonBorderThemeThickness`.
18pub const BUTTON_BORDER_THICKNESS: f64 = 1.0;
19/// The `FocusVisualMargin` the button styles set.
20pub const BUTTON_FOCUS_VISUAL_MARGIN: [f64; 4] = [-3.0; 4];
21
22/// Which `Button` style the control uses; XAML `Style="{StaticResource AccentButtonStyle}"` and its siblings.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
24pub enum ButtonStyle {
25    /// `DefaultButtonStyle`.
26    #[default]
27    Default,
28    /// `AccentButtonStyle`: the accent fill, `BackgroundSizing="OuterBorderEdge"`.
29    Accent,
30    /// `SubtleButtonStyle`: no fill or border until the pointer is over it.
31    Subtle,
32}
33
34/// The brushes a button style resolves to in one state.
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub struct ButtonBrushes {
37    pub background: Color,
38    pub border: Brush,
39    pub foreground: Color,
40}
41
42impl ButtonStyle {
43    /// The `{ThemeResource …}` values the style's `CommonStates` storyboards name for `state`.
44    pub fn brushes(self, resources: &ThemeResources, state: CommonState) -> ButtonBrushes {
45        let r = resources;
46        match (self, state) {
47            (ButtonStyle::Default, CommonState::Normal) => ButtonBrushes {
48                background: r.button_background,
49                border: Brush::ControlElevation(r.button_border_brush),
50                foreground: r.button_foreground,
51            },
52            (ButtonStyle::Default, CommonState::PointerOver) => ButtonBrushes {
53                background: r.button_background_pointer_over,
54                border: Brush::ControlElevation(r.button_border_brush_pointer_over),
55                foreground: r.button_foreground_pointer_over,
56            },
57            (ButtonStyle::Default, CommonState::Pressed) => ButtonBrushes {
58                background: r.button_background_pressed,
59                border: Brush::Solid(r.button_border_brush_pressed),
60                foreground: r.button_foreground_pressed,
61            },
62            (ButtonStyle::Default, CommonState::Disabled) => ButtonBrushes {
63                background: r.button_background_disabled,
64                border: Brush::Solid(r.button_border_brush_disabled),
65                foreground: r.button_foreground_disabled,
66            },
67            (ButtonStyle::Accent, CommonState::Normal) => ButtonBrushes {
68                background: r.accent_button_background,
69                border: Brush::ControlElevation(r.accent_button_border_brush),
70                foreground: r.accent_button_foreground,
71            },
72            (ButtonStyle::Accent, CommonState::PointerOver) => ButtonBrushes {
73                background: r.accent_button_background_pointer_over,
74                border: Brush::ControlElevation(r.accent_button_border_brush_pointer_over),
75                foreground: r.accent_button_foreground_pointer_over,
76            },
77            (ButtonStyle::Accent, CommonState::Pressed) => ButtonBrushes {
78                background: r.accent_button_background_pressed,
79                border: Brush::Solid(r.accent_button_border_brush_pressed),
80                foreground: r.accent_button_foreground_pressed,
81            },
82            (ButtonStyle::Accent, CommonState::Disabled) => ButtonBrushes {
83                background: r.accent_button_background_disabled,
84                border: Brush::Solid(r.accent_button_border_brush_disabled),
85                foreground: r.accent_button_foreground_disabled,
86            },
87            (ButtonStyle::Subtle, CommonState::Normal) => ButtonBrushes {
88                background: r.subtle_button_background,
89                border: Brush::Solid(r.subtle_button_border_brush),
90                foreground: r.subtle_button_foreground,
91            },
92            (ButtonStyle::Subtle, CommonState::PointerOver) => ButtonBrushes {
93                background: r.subtle_button_background_pointer_over,
94                border: Brush::Solid(r.subtle_button_border_brush_pointer_over),
95                foreground: r.subtle_button_foreground_pointer_over,
96            },
97            (ButtonStyle::Subtle, CommonState::Pressed) => ButtonBrushes {
98                background: r.subtle_button_background_pressed,
99                border: Brush::Solid(r.subtle_button_border_brush_pressed),
100                foreground: r.subtle_button_foreground_pressed,
101            },
102            (ButtonStyle::Subtle, CommonState::Disabled) => ButtonBrushes {
103                background: r.subtle_button_background_disabled,
104                border: Brush::Solid(r.subtle_button_border_brush_disabled),
105                foreground: r.subtle_button_foreground_disabled,
106            },
107        }
108    }
109
110    /// XAML `BackgroundSizing` of the style.
111    pub fn background_sizing(self) -> BackgroundSizing {
112        match self {
113            ButtonStyle::Accent => BackgroundSizing::OuterBorderEdge,
114            ButtonStyle::Default | ButtonStyle::Subtle => BackgroundSizing::InnerBorderEdge,
115        }
116    }
117}
118
119/// XAML `Button`: `Content` shown in the style's bezel, `Click` raised on activation.
120#[derive(Clone)]
121pub struct Button {
122    /// Content presented inside the selected control template.
123    pub content: WidgetRef,
124    /// Raised when the button activates.
125    pub click: Listener,
126    /// The standard source style used when no template override is supplied.
127    pub style: ButtonStyle,
128    /// `Padding` between the bezel and the content, in left, top, right, bottom order; the theme's
129    /// `ButtonPadding` when `None`, as the style sets it.
130    pub padding: Option<[f64; 4]>,
131    /// Whether pointer and keyboard input can activate this button.
132    pub is_enabled: bool,
133    /// Whether sequential keyboard navigation stops here.
134    pub is_tab_stop: bool,
135    /// Optional caller-owned focus node used by composite controls.
136    pub focus_node: Option<FocusNodeRef>,
137    /// An alternate source template, such as TabView's close button chrome.
138    pub template: Option<ButtonTemplate>,
139    /// Identity retained across parent rebuilds.
140    pub key: Option<KeyRef>,
141}
142
143impl Button {
144    /// Creates a button with content and a Click callback.
145    #[cfg_attr(debug_assertions, track_caller)]
146    pub fn new<K>(content: impl IntoWidget<K>, click: Listener) -> Button {
147        Button {
148            content: content.into_widget(),
149            click,
150            style: ButtonStyle::Default,
151            padding: None,
152            is_enabled: true,
153            is_tab_stop: true,
154            focus_node: None,
155            template: None,
156            key: None,
157        }
158    }
159
160    /// A text `Content`, as `<Button Content="…"/>`.
161    pub fn text(text: impl Into<String>, click: Listener) -> Button {
162        Button::new(Text::new(text), click)
163    }
164
165    /// Selects one of the standard source styles.
166    pub fn style(mut self, style: ButtonStyle) -> Button {
167        self.style = style;
168        self
169    }
170
171    /// XAML `Padding`.
172    pub fn padding(mut self, padding: [f64; 4]) -> Button {
173        self.padding = Some(padding);
174        self
175    }
176
177    /// XAML `IsEnabled`.
178    pub fn is_enabled(mut self, enabled: bool) -> Button {
179        self.is_enabled = enabled;
180        self
181    }
182
183    /// Sets the source `IsTabStop` property.
184    pub fn is_tab_stop(mut self, value: bool) -> Self {
185        self.is_tab_stop = value;
186        self
187    }
188
189    /// Uses a focus node whose lifetime is owned by the enclosing control.
190    pub fn focus_node(mut self, node: FocusNodeRef) -> Self {
191        self.focus_node = Some(node);
192        self
193    }
194
195    /// Replaces presentation while retaining ButtonBase input and activation.
196    pub fn template(
197        mut self,
198        builder: impl Fn(&mut App, BuildContext, ControlStates, WidgetRef) -> WidgetRef + 'static,
199    ) -> Self {
200        self.template = Some(Rc::new(builder));
201        self
202    }
203
204    /// Sets the identity retained across parent rebuilds.
205    pub fn key(mut self, key: KeyRef) -> Button {
206        self.key = Some(key);
207        self
208    }
209}
210
211impl fmt::Debug for Button {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.debug_struct("Button")
214            .field("style", &self.style)
215            .field("is_enabled", &self.is_enabled)
216            .finish_non_exhaustive()
217    }
218}
219
220impl StatelessWidget for Button {
221    fn key(&self) -> Option<&KeyRef> {
222        self.key.as_ref()
223    }
224
225    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
226        let (content, style, padding) = (self.content.clone(), self.style, self.padding);
227        let custom_template = self.template.clone();
228        let mut states = CommonStates::new(self.click.clone(), move |app, context, states| {
229            if let Some(builder) = &custom_template {
230                builder(app, context, states, content.clone())
231            } else {
232                template(app, context, style, padding, content.clone(), states)
233            }
234        })
235        .is_enabled(self.is_enabled)
236        .is_tab_stop(self.is_tab_stop);
237        if let Some(node) = self.focus_node.clone() {
238            states = states.focus_node(node);
239        }
240        states.into_widget()
241    }
242}
243
244/// The `ControlTemplate` of the button styles for one set of states.
245fn template(
246    app: &mut App,
247    context: BuildContext,
248    style: ButtonStyle,
249    padding: Option<[f64; 4]>,
250    content: WidgetRef,
251    states: ControlStates,
252) -> WidgetRef {
253    let r = ThemeResources::of(app, context);
254    let brushes = style.brushes(&r, states.common);
255    let padding = padding.unwrap_or(r.button_padding);
256    let corner_radius = r.control_corner_radius[0];
257    let text = control_text_style(
258        &r,
259        r.control_content_theme_font_size,
260        FontWeight::W400,
261        brushes.foreground,
262    );
263    // `ContentPresenter`: `HorizontalContentAlignment` and `VerticalContentAlignment` are Center.
264    let label = Center::new()
265        .width_factor(1.0)
266        .height_factor(1.0)
267        .child(DefaultTextStyle::new(text, content))
268        .into_widget();
269    let presenter = ColorTransition::new(
270        brushes.background,
271        r.control_faster_animation_duration,
272        move |_app, background| {
273            ControlBorder::new(Brush::Solid(background), brushes.border)
274                .border_thickness(BUTTON_BORDER_THICKNESS)
275                .corner_radius(corner_radius)
276                .background_sizing(style.background_sizing())
277                .padding(padding)
278                .child(label.clone())
279                .into_widget()
280        },
281    );
282    FocusVisual::new(presenter, r.theme)
283        .visible(states.focused)
284        .margin(BUTTON_FOCUS_VISUAL_MARGIN)
285        .corner_radius(corner_radius)
286        .into_widget()
287}