Skip to main content

repose_material/material3/
advbuttons.rs

1#![allow(non_snake_case)]
2
3use std::rc::Rc;
4
5use super::{ButtonGroupDefaults, SplitButtonDefaults};
6use repose_core::{locals::with_content_color, *};
7use repose_ui::{Box, Row, Text, TextStyle, ViewExt};
8
9/// Configuration for [`SplitButtonLayout`].
10#[derive(Clone)]
11pub struct SplitButtonConfig {
12    pub modifier: Modifier,
13    pub spacing: f32,
14}
15
16impl Default for SplitButtonConfig {
17    fn default() -> Self {
18        Self {
19            modifier: Modifier::new(),
20            spacing: SplitButtonDefaults::SPACING,
21        }
22    }
23}
24
25/// M3 SplitButtonLayout -> places leading and trailing buttons side by side.
26///
27/// Pass styled buttons (via [`Button`], [`FilledTonalButton`], etc.) or use
28/// the factory helpers below for properly-shaped split button parts.
29pub fn SplitButtonLayout(
30    leading_button: View,
31    trailing_button: View,
32    config: SplitButtonConfig,
33) -> View {
34    Row(config
35        .modifier
36        .gap(config.spacing)
37        .align_items(AlignItems::CENTER))
38    .child((leading_button, trailing_button))
39}
40
41fn split_leading_shape_radii() -> [f32; 4] {
42    [
43        SplitButtonDefaults::OUTER_CORNER_SIZE,
44        SplitButtonDefaults::SMALL_INNER_CORNER_SIZE,
45        SplitButtonDefaults::SMALL_INNER_CORNER_SIZE,
46        SplitButtonDefaults::OUTER_CORNER_SIZE,
47    ]
48}
49
50fn split_trailing_shape_radii() -> [f32; 4] {
51    [
52        SplitButtonDefaults::SMALL_INNER_CORNER_SIZE,
53        SplitButtonDefaults::OUTER_CORNER_SIZE,
54        SplitButtonDefaults::OUTER_CORNER_SIZE,
55        SplitButtonDefaults::SMALL_INNER_CORNER_SIZE,
56    ]
57}
58
59fn split_button_impl(
60    outer_modifier: Modifier,
61    on_click: impl Fn() + 'static,
62    content: impl FnOnce() -> View,
63    content_color: Color,
64    container_color: Option<Color>,
65    state_colors: StateColors,
66    state_elevation: Option<StateElevation>,
67    border: Option<(f32, Color, f32)>,
68    pad_left: f32,
69    pad_right: f32,
70    height: f32,
71    enabled: bool,
72    interaction_source: Option<MutableInteractionSource>,
73) -> View {
74    let mut m = Modifier::new()
75        .height(height)
76        .min_width(48.0)
77        .padding_values(PaddingValues {
78            left: pad_left,
79            right: pad_right,
80            top: 0.0,
81            bottom: 0.0,
82        })
83        .align_items(AlignItems::CENTER)
84        .justify_content(JustifyContent::CENTER);
85    if let Some(bg) = container_color {
86        m = m.background(bg);
87    }
88    m = m.state_colors(if enabled {
89        state_colors
90    } else {
91        StateColors {
92            default: Color::TRANSPARENT,
93            hovered: Color::TRANSPARENT,
94            pressed: Color::TRANSPARENT,
95            disabled: state_colors.disabled,
96        }
97    });
98    if let Some(se) = state_elevation {
99        m = m.state_elevation(se);
100    }
101    if let Some((w, c, r)) = border {
102        m = m.border(w, c, r);
103    }
104    let source: Rc<MutableInteractionSource> = interaction_source
105        .map(Rc::new)
106        .unwrap_or_else(|| remember(MutableInteractionSource::new));
107    m = m.interaction_source(&*source);
108    m = m.indication(crate::ripple::ripple(crate::ripple::RippleConfig {
109        color: Some(content_color),
110        bounded: true,
111        ..Default::default()
112    }));
113    if enabled {
114        m = m.clickable().on_click(move || on_click());
115    }
116    m = m.then(outer_modifier);
117    let effective = if enabled {
118        content_color
119    } else {
120        content_color.with_alpha_f32(0.38)
121    };
122    with_content_color(effective, || Box(m).child(content()))
123}
124
125
126pub fn SplitButtonLeadingButton(
127    modifier: Modifier,
128    on_click: impl Fn() + 'static,
129    config: super::ButtonConfig,
130    content: impl FnOnce() -> View,
131) -> View {
132    let def = super::ButtonColors {
133        container_color: super::ButtonDefaults::container_color(),
134        content_color: super::ButtonDefaults::content_color(),
135        disabled_container_color: super::ButtonDefaults::container_color()
136            .with_alpha_f32(0.12)
137            .composite_over(theme().surface_container_low),
138        disabled_content_color: super::ButtonDefaults::content_color().with_alpha_f32(0.38),
139    };
140    let (cc, bg, sc, se) = resolve_button_colors(&config, def);
141    let pad = config
142        .content_padding
143        .unwrap_or(SplitButtonDefaults::small_leading_content_padding());
144    split_button_impl(
145        modifier.clip_rounded_radii(split_leading_shape_radii()),
146        on_click,
147        content,
148        cc,
149        bg,
150        sc,
151        se.or(Some(super::ButtonDefaults::state_elevation_default())),
152        config.border,
153        pad.left,
154        pad.right,
155        config.height,
156        config.enabled,
157        config.interaction_source.clone(),
158    )
159}
160
161pub fn SplitButtonTrailingButton(
162    modifier: Modifier,
163    on_click: impl Fn() + 'static,
164    config: super::ButtonConfig,
165    content: impl FnOnce() -> View,
166) -> View {
167    let def = super::ButtonColors {
168        container_color: super::ButtonDefaults::container_color(),
169        content_color: super::ButtonDefaults::content_color(),
170        disabled_container_color: super::ButtonDefaults::container_color()
171            .with_alpha_f32(0.12)
172            .composite_over(theme().surface_container_low),
173        disabled_content_color: super::ButtonDefaults::content_color().with_alpha_f32(0.38),
174    };
175    let (cc, bg, sc, se) = resolve_button_colors(&config, def);
176    let pad = config
177        .content_padding
178        .unwrap_or(SplitButtonDefaults::small_trailing_content_padding());
179    split_button_impl(
180        modifier.clip_rounded_radii(split_trailing_shape_radii()),
181        on_click,
182        content,
183        cc,
184        bg,
185        sc,
186        se.or(Some(super::ButtonDefaults::state_elevation_default())),
187        config.border,
188        pad.left,
189        pad.right,
190        config.height,
191        config.enabled,
192        config.interaction_source.clone(),
193    )
194}
195
196pub fn SplitButtonTrailingToggleButton(
197    checked: bool,
198    on_checked_change: impl Fn(bool) + 'static,
199    modifier: Modifier,
200    config: super::ToggleButtonConfig,
201    content: impl FnOnce(bool) -> View,
202) -> View {
203    let th = theme();
204    let cc = config
205        .content_color
206        .unwrap_or_else(super::ToggleButtonDefaults::content_color);
207    let checked_cc = config
208        .checked_content_color
209        .unwrap_or_else(super::ToggleButtonDefaults::checked_content_color);
210    let checked_bg = config
211        .checked_container_color
212        .unwrap_or_else(super::ToggleButtonDefaults::checked_container_color);
213    let bg = if checked {
214        checked_bg
215    } else {
216        config.container_color.unwrap_or(Color::TRANSPARENT)
217    };
218    let fg = if checked { checked_cc } else { cc };
219    let se = config
220        .state_elevation
221        .unwrap_or_else(super::ToggleButtonDefaults::state_elevation_default);
222    let pad_l = config
223        .content_padding
224        .map(|p| p.left)
225        .unwrap_or(super::ToggleButtonDefaults::HORIZONTAL_PADDING);
226    let pad_r = config
227        .content_padding
228        .map(|p| p.right)
229        .unwrap_or(super::ToggleButtonDefaults::HORIZONTAL_PADDING);
230    let mut m = Modifier::new()
231        .height(config.height)
232        .min_width(48.0)
233        .padding_values(PaddingValues {
234            left: pad_l,
235            right: pad_r,
236            top: 0.0,
237            bottom: 0.0,
238        })
239        .background(bg)
240        .align_items(AlignItems::CENTER)
241        .justify_content(JustifyContent::CENTER)
242        .state_colors(config.state_colors)
243        .state_elevation(se);
244    let tg_source: Rc<MutableInteractionSource> = config
245        .interaction_source
246        .clone()
247        .map(Rc::new)
248        .unwrap_or_else(|| remember(MutableInteractionSource::new));
249    m = m.interaction_source(&*tg_source);
250    if let Some((w, c, r)) = config.border {
251        m = m.border(w, c, r);
252    }
253    if config.enabled {
254        let cb = on_checked_change;
255        m = m.clickable().on_click(move || cb(!checked));
256    } else {
257        m = m.alpha(0.38);
258    }
259    m = m.then(modifier.clip_rounded_radii(split_trailing_shape_radii()));
260    with_content_color(fg, || Box(m).child(content(checked)))
261}
262
263
264pub fn SplitButtonTonalLeadingButton(
265    modifier: Modifier,
266    on_click: impl Fn() + 'static,
267    config: super::ButtonConfig,
268    content: impl FnOnce() -> View,
269) -> View {
270    let def = super::ButtonColors {
271        container_color: super::ButtonDefaults::tonal_container_color(),
272        content_color: super::ButtonDefaults::tonal_content_color(),
273        disabled_container_color: theme()
274            .on_surface
275            .with_alpha_f32(0.12)
276            .composite_over(theme().surface_container_low),
277        disabled_content_color: theme().on_surface.with_alpha_f32(0.38),
278    };
279    let (cc, bg, sc, se) = resolve_button_colors(&config, def);
280    let pad = config
281        .content_padding
282        .unwrap_or(SplitButtonDefaults::small_leading_content_padding());
283    split_button_impl(
284        modifier.clip_rounded_radii(split_leading_shape_radii()),
285        on_click,
286        content,
287        cc,
288        bg,
289        sc,
290        se.or(Some(super::ButtonDefaults::elevated_state_elevation())),
291        config.border,
292        pad.left,
293        pad.right,
294        config.height,
295        config.enabled,
296        config.interaction_source.clone(),
297    )
298}
299
300pub fn SplitButtonTonalTrailingToggleButton(
301    checked: bool,
302    on_checked_change: impl Fn(bool) + 'static,
303    modifier: Modifier,
304    config: super::ToggleButtonConfig,
305    content: impl FnOnce(bool) -> View,
306) -> View {
307    let th = theme();
308    let cc = config
309        .content_color
310        .unwrap_or_else(super::ToggleButtonDefaults::tonal_content_color);
311    let checked_cc = config
312        .checked_content_color
313        .unwrap_or_else(super::ToggleButtonDefaults::tonal_checked_content_color);
314    let checked_bg = config
315        .checked_container_color
316        .unwrap_or_else(super::ToggleButtonDefaults::tonal_checked_container_color);
317    let bg = if checked {
318        checked_bg
319    } else {
320        config.container_color.unwrap_or(Color::TRANSPARENT)
321    };
322    let fg = if checked { checked_cc } else { cc };
323    let se = config
324        .state_elevation
325        .unwrap_or_else(super::ToggleButtonDefaults::state_elevation_default);
326    let pad_l = config
327        .content_padding
328        .map(|p| p.left)
329        .unwrap_or(super::ToggleButtonDefaults::HORIZONTAL_PADDING);
330    let pad_r = config
331        .content_padding
332        .map(|p| p.right)
333        .unwrap_or(super::ToggleButtonDefaults::HORIZONTAL_PADDING);
334    let mut m = Modifier::new()
335        .height(config.height)
336        .min_width(48.0)
337        .padding_values(PaddingValues {
338            left: pad_l,
339            right: pad_r,
340            top: 0.0,
341            bottom: 0.0,
342        })
343        .background(bg)
344        .align_items(AlignItems::CENTER)
345        .justify_content(JustifyContent::CENTER)
346        .state_colors(config.state_colors)
347        .state_elevation(se);
348    let tg_source: Rc<MutableInteractionSource> = config
349        .interaction_source
350        .clone()
351        .map(Rc::new)
352        .unwrap_or_else(|| remember(MutableInteractionSource::new));
353    m = m.interaction_source(&*tg_source);
354    if let Some((w, c, r)) = config.border {
355        m = m.border(w, c, r);
356    }
357    if config.enabled {
358        let cb = on_checked_change;
359        m = m.clickable().on_click(move || cb(!checked));
360    } else {
361        m = m.alpha(0.38);
362    }
363    m = m.then(modifier.clip_rounded_radii(split_trailing_shape_radii()));
364    with_content_color(fg, || Box(m).child(content(checked)))
365}
366
367/// State for the overflow menu in [`ButtonGroup`].
368pub struct ButtonGroupMenuState {
369    pub is_showing: bool,
370}
371
372impl ButtonGroupMenuState {
373    pub fn dismiss(&mut self) {
374        self.is_showing = false;
375    }
376    pub fn show(&mut self) {
377        self.is_showing = true;
378    }
379}
380
381/// Scope passed to [`ButtonGroup`]'s content closure.
382pub struct ButtonGroupScope {
383    items: Vec<ButtonGroupItem>,
384    connected: bool,
385}
386
387/// Internal item held by `ButtonGroupScope`.
388struct ButtonGroupItem {
389    button_group_content: Box<dyn FnOnce() -> View>,
390    menu_content: Option<Box<dyn FnOnce(&mut ButtonGroupMenuState) -> View>>,
391}
392
393impl ButtonGroupScope {
394    fn new() -> Self {
395        Self {
396            items: Vec::new(),
397            connected: false,
398        }
399    }
400
401    /// Add a clickable item (rendered as a [`Button`] internally).
402    pub fn clickable_item(
403        &mut self,
404        on_click: impl Fn() + 'static,
405        label: String,
406        icon: Option<View>,
407    ) {
408        let cb = Rc::new(on_click);
409        let cb2 = cb.clone();
410        self.items.push(ButtonGroupItem {
411            button_group_content: Box::new(move || {
412                let cb = cb2.clone();
413                let config = super::ButtonConfig {
414                    shape_radius: 0.0,
415                    ..Default::default()
416                };
417                super::Button(
418                    Modifier::new().flex_grow(1.0),
419                    move || (cb)(),
420                    config,
421                    move || {
422                        let label = label.clone();
423                        let t = Text(label).single_line();
424                        match icon.clone() {
425                            Some(ic) => Box(Modifier::new()).child((ic, t)),
426                            None => t,
427                        }
428                    },
429                )
430            }),
431            menu_content: None,
432        });
433    }
434
435    /// Add a toggleable item (rendered as a [`ToggleButton`] internally).
436    pub fn toggleable_item(
437        &mut self,
438        checked: bool,
439        on_checked_change: impl Fn(bool) + 'static,
440        label: String,
441        icon: Option<View>,
442    ) {
443        let cb = Rc::new(on_checked_change);
444        let cb2 = cb.clone();
445        self.items.push(ButtonGroupItem {
446            button_group_content: Box::new(move || {
447                let cb = cb2.clone();
448                let config = super::ToggleButtonConfig {
449                    shape_radius: 0.0,
450                    ..Default::default()
451                };
452                super::ToggleButton(
453                    checked,
454                    move |b| (cb)(b),
455                    config,
456                    move |_| {
457                        let label = label.clone();
458                        let t = Text(label).single_line();
459                        match icon.clone() {
460                            Some(ic) => Box(Modifier::new()).child((ic, t)),
461                            None => t,
462                        }
463                    },
464                )
465            }),
466            menu_content: None,
467        });
468    }
469
470    /// Add a custom item with a button group composable and an optional overflow menu content.
471    pub fn custom_item(
472        &mut self,
473        button_group_content: impl FnOnce() -> View + 'static,
474        menu_content: Option<impl FnOnce(&mut ButtonGroupMenuState) -> View + 'static>,
475    ) {
476        self.items.push(ButtonGroupItem {
477            button_group_content: Box::new(button_group_content),
478            menu_content: menu_content.map(|f| {
479                let b: Box<dyn FnOnce(&mut ButtonGroupMenuState) -> View> = Box::new(f);
480                b
481            }),
482        });
483    }
484}
485
486/// M3 ButtonGroup -> a horizontal sequence of related action items.
487///
488/// Items are added via [`ButtonGroupScope::clickable_item`] and
489/// [`ButtonGroupScope::toggleable_item`].
490pub fn ButtonGroup(
491    modifier: Modifier,
492    gap: f32,
493    content: impl FnOnce(&mut ButtonGroupScope),
494) -> View {
495    let mut scope = ButtonGroupScope::new();
496    content(&mut scope);
497    Row(modifier.gap(gap).align_items(AlignItems::CENTER)).with_children(
498        scope
499            .items
500            .into_iter()
501            .map(|item| (item.button_group_content)())
502            .collect::<Vec<View>>(),
503    )
504}
505
506fn resolve_button_colors(
507    config: &super::ButtonConfig,
508    def: super::ButtonColors,
509) -> (Color, Option<Color>, StateColors, Option<StateElevation>) {
510    if let Some(colors) = &config.colors {
511        let bg = if config.enabled {
512            colors.container_color
513        } else {
514            colors.disabled_container_color
515        };
516        let cc = if config.enabled {
517            colors.content_color
518        } else {
519            colors.disabled_content_color
520        };
521        let sc = StateColors {
522            default: Color::TRANSPARENT,
523            hovered: colors.content_color.with_alpha_f32(0.08),
524            pressed: colors.content_color.with_alpha_f32(0.12),
525            disabled: Color::TRANSPARENT,
526        };
527        let se = config.elevation.map(|e| StateElevation {
528            default: e.default,
529            hovered: e.hovered,
530            pressed: e.pressed,
531            disabled: e.disabled,
532        });
533        (cc, Some(bg), sc, se)
534    } else {
535        let cc = config.content_color.unwrap_or(def.content_color);
536        let bg = Some(config.container_color.unwrap_or(def.container_color));
537        let sc = if config.enabled {
538            config.state_colors
539        } else {
540            StateColors {
541                default: Color::TRANSPARENT,
542                hovered: Color::TRANSPARENT,
543                pressed: Color::TRANSPARENT,
544                disabled: config.state_colors.disabled,
545            }
546        };
547        let se = config.state_elevation;
548        (cc, bg, sc, se)
549    }
550}