tessera-components 0.0.0

Basic components for tessera-ui, using md3e design principles.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Material 3-style segmented buttons with single or multiple selection.
//!
//! ## Usage
//!
//! Used for grouping related actions.

use std::{collections::HashMap, sync::Arc, time::Instant};

use derive_setters::Setters;
use tessera_ui::{
    Color, ComputedData, Dp, LayoutInput, LayoutOutput, LayoutSpec, MeasurementError, Modifier, Px,
    PxPosition, remember, tessera, use_context,
};

use crate::{
    alignment::MainAxisAlignment,
    animation,
    button::{ButtonArgs, button},
    modifier::ModifierExt,
    row::{RowArgs, row},
    shape_def::{RoundedCorner, Shape},
    spacer::spacer,
    theme::MaterialTheme,
};

/// According to the [`ButtonGroups-Types`](https://m3.material.io/components/button-groups/specs#3b51d175-cc02-4701-b3f8-c9ffa229123a)
/// spec, the [`button_groups`] component supports two styles: `Standard` and
/// `Connected`.
///
/// ## Standard
///
/// Buttons have spacing between them and do not need to be the same width.
///
/// ## Connected
///
/// Buttons are adjacent with no spacing, and each button must be the same
/// width.
#[derive(Debug, Clone, Copy, Default)]
pub enum ButtonGroupsStyle {
    /// Buttons have spacing between them and do not need to be the same width.
    #[default]
    Standard,
    /// Buttons are adjacent with no spacing, and each button must be the same
    /// width.
    Connected,
}

/// According to the [`ButtonGroups-Configurations`](https://m3.material.io/components/button-groups/specs#0d2cf762-275c-4693-9484-fe011501439e)
/// spec, the [`button_groups`] component supports two selection modes: `Single`
/// and `Multiple`.
///
/// ## Single
///
/// Only one button can be selected at a time.
///
/// ## Multiple
///
/// Multiple buttons can be selected at the same time.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ButtonGroupsSelectionMode {
    /// Only one button can be selected at a time.
    #[default]
    Single,
    /// Multiple buttons can be selected at the same time.
    Multiple,
}

/// According to the [`ButtonGroups-Configurations`](https://m3.material.io/components/button-groups/specs#0d2cf762-275c-4693-9484-fe011501439e)
/// spec, the [`button_groups`] component supports a series of sizes.
#[derive(Debug, Clone, Copy, Default)]
pub enum ButtonGroupsSize {
    /// Extra small size.
    ExtraSmall,
    /// Small size.
    Small,
    /// Medium size.
    #[default]
    Medium,
    /// Large size.
    Large,
    /// Extra large size.
    ExtraLarge,
}

/// A scope for declaratively adding children to a [`button_groups`] component.
pub struct ButtonGroupsScope<'a> {
    child_closures: &'a mut Vec<Box<dyn FnOnce(Color) + Send + Sync>>,
    on_click_closures: &'a mut Vec<Arc<dyn Fn(bool) + Send + Sync>>,
}

impl ButtonGroupsScope<'_> {
    /// Add a child component to the button group, which will be wrapped by a
    /// [`button`] component.
    ///
    /// # Arguments
    ///
    /// - `child_closure` - A closure that takes a [`Color`] and returns a
    ///   [`button`] component. The `Color` argument should be used for the
    ///   content of the child component.
    /// - `on_click_closure` - A closure that will be called when the button is
    ///   clicked. The closure takes a `bool` argument indicating whether the
    ///   button is now active (selected) or not.
    pub fn child<F, C>(&mut self, child: F, on_click: C)
    where
        F: FnOnce(Color) + Send + Sync + 'static,
        C: Fn(bool) + Send + Sync + 'static,
    {
        self.child_closures.push(Box::new(child));
        self.on_click_closures.push(Arc::new(on_click));
    }
}

/// Arguments for the [`button_groups`] component.
#[derive(Default, Setters)]
pub struct ButtonGroupsArgs {
    /// Size of the button group.
    pub size: ButtonGroupsSize,
    /// Style of the button group.
    pub style: ButtonGroupsStyle,
    /// Selection mode of the button group.
    pub selection_mode: ButtonGroupsSelectionMode,
}

#[derive(Clone)]
struct ButtonGroupsLayout {
    container_height: Dp,
    between_space: Dp,
    active_button_shape: Shape,
    inactive_button_shape: Shape,
    inactive_button_shape_start: Shape,
    inactive_button_shape_end: Shape,
}

impl ButtonGroupsLayout {
    fn new(size: ButtonGroupsSize, style: ButtonGroupsStyle) -> Self {
        // See https://m3.material.io/components/button-groups/specs#f41a7d35-b9c2-4340-b3bb-47b34acaaf45
        let container_height = match size {
            ButtonGroupsSize::ExtraSmall => Dp(32.0),
            ButtonGroupsSize::Small => Dp(40.0),
            ButtonGroupsSize::Medium => Dp(56.0),
            ButtonGroupsSize::Large => Dp(96.0),
            ButtonGroupsSize::ExtraLarge => Dp(136.0),
        };
        let between_space = match style {
            ButtonGroupsStyle::Standard => match size {
                ButtonGroupsSize::ExtraSmall => Dp(18.0),
                ButtonGroupsSize::Small => Dp(12.0),
                _ => Dp(8.0),
            },
            ButtonGroupsStyle::Connected => Dp(2.0),
        };
        let active_button_shape = match style {
            ButtonGroupsStyle::Standard => Shape::rounded_rectangle(Dp(16.0)),
            ButtonGroupsStyle::Connected => Shape::capsule(),
        };
        let inactive_button_shape = match style {
            ButtonGroupsStyle::Standard => Shape::capsule(),
            ButtonGroupsStyle::Connected => Shape::rounded_rectangle(Dp(16.0)),
        };
        let inactive_button_shape_start = match style {
            ButtonGroupsStyle::Standard => active_button_shape,
            ButtonGroupsStyle::Connected => Shape::RoundedRectangle {
                top_left: RoundedCorner::Capsule,
                top_right: RoundedCorner::manual(Dp(16.0), 3.0),
                bottom_right: RoundedCorner::manual(Dp(16.0), 3.0),
                bottom_left: RoundedCorner::Capsule,
            },
        };
        let inactive_button_shape_end = match style {
            ButtonGroupsStyle::Standard => active_button_shape,
            ButtonGroupsStyle::Connected => Shape::RoundedRectangle {
                top_left: RoundedCorner::manual(Dp(16.0), 3.0),
                top_right: RoundedCorner::Capsule,
                bottom_right: RoundedCorner::Capsule,
                bottom_left: RoundedCorner::manual(Dp(16.0), 3.0),
            },
        };
        Self {
            container_height,
            between_space,
            active_button_shape,
            inactive_button_shape,
            inactive_button_shape_start,
            inactive_button_shape_end,
        }
    }
}

#[derive(Default)]
struct ButtonItemState {
    actived: bool,
    elastic_state: ElasticState,
}

/// Internal state of a button group.
#[derive(Default)]
struct ButtonGroupsState {
    item_states: HashMap<usize, ButtonItemState>,
}

impl ButtonGroupsState {
    fn item_state_mut(&mut self, index: usize) -> &mut ButtonItemState {
        self.item_states.entry(index).or_default()
    }
}

/// # button_groups
///
/// Button groups organize buttons and add interactions between them.
///
/// ## Usage
///
/// Used for grouping related actions.
///
/// State for selection and animations is managed internally via `remember`; no
/// external state handle is required.
///
/// ## Parameters
///
/// - `args` — configures size, style, and selection mode; see
///   [`ButtonGroupsArgs`].
/// - `scope_config` — closure that configures the children of the button group
///   using a [`ButtonGroupsScope`].
///
/// # Example
///
/// ```
/// use tessera_components::{
///     button_groups::{ButtonGroupsArgs, button_groups},
///     text::{TextArgs, text},
/// };
/// # use tessera_components::theme::{MaterialTheme, material_theme};
///
/// # material_theme(|| MaterialTheme::default(), || {
/// button_groups(ButtonGroupsArgs::default(), |scope| {
///     scope.child(
///         |color| {
///             text(TextArgs {
///                 text: "Button 1".to_string(),
///                 color,
///                 ..Default::default()
///             })
///         },
///         |_| {
///             println!("Button 1 clicked");
///         },
///     );
///
///     scope.child(
///         |color| {
///             text(TextArgs {
///                 text: "Button 2".to_string(),
///                 color,
///                 ..Default::default()
///             })
///         },
///         |actived| {
///             println!("Button 2 clicked");
///         },
///     );
///
///     scope.child(
///         |color| {
///             text(TextArgs {
///                 text: "Button 3".to_string(),
///                 color,
///                 ..Default::default()
///             })
///         },
///         |_| {
///             println!("Button 3 clicked");
///         },
///     );
/// });
/// # });
/// ```
#[tessera]
pub fn button_groups<F>(args: impl Into<ButtonGroupsArgs>, scope_config: F)
where
    F: FnOnce(&mut ButtonGroupsScope),
{
    let state = remember(ButtonGroupsState::default);
    let args = args.into();
    let mut child_closures = Vec::new();
    let mut on_click_closures = Vec::new();
    {
        let mut scope = ButtonGroupsScope {
            child_closures: &mut child_closures,
            on_click_closures: &mut on_click_closures,
        };
        scope_config(&mut scope);
    }
    let layout = ButtonGroupsLayout::new(args.size, args.style);
    let child_len = child_closures.len();
    let selection_mode = args.selection_mode;
    row(
        RowArgs {
            modifier: Modifier::new().height(layout.container_height),
            main_axis_alignment: MainAxisAlignment::SpaceBetween,
            ..Default::default()
        },
        move |scope| {
            for (index, child_closure) in child_closures.into_iter().enumerate() {
                let on_click_closure = on_click_closures[index].clone();

                scope.child(move || {
                    let actived =
                        state.with(|s| s.item_states.get(&index).is_some_and(|item| item.actived));
                    if actived {
                        let mut button_args = ButtonArgs::filled(move || {
                            on_click_closure(false);
                            state.with_mut(|s| {
                                let item = s.item_state_mut(index);
                                item.actived = false;
                                item.elastic_state.toggle();
                            });
                        });
                        button_args.shape = layout.active_button_shape;
                        let scheme = use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .color_scheme;
                        let label_color = scheme.on_primary;
                        button(button_args, move || {
                            elastic_container(state, index, move || child_closure(label_color))
                        });
                    } else {
                        let mut button_args = ButtonArgs::filled(move || {
                            on_click_closure(true);
                            state.with_mut(|s| {
                                if selection_mode == ButtonGroupsSelectionMode::Single {
                                    for (other_index, item) in s.item_states.iter_mut() {
                                        if *other_index != index && item.actived {
                                            item.actived = false;
                                            item.elastic_state.toggle();
                                        }
                                    }
                                }

                                let item = s.item_state_mut(index);
                                item.actived = true;
                                item.elastic_state.toggle();
                            });
                        });
                        let scheme = use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .color_scheme;
                        button_args.color = scheme.secondary_container;
                        if index == 0 {
                            button_args.shape = layout.inactive_button_shape_start;
                        } else if index == child_len - 1 {
                            button_args.shape = layout.inactive_button_shape_end;
                        } else {
                            button_args.shape = layout.inactive_button_shape;
                        }

                        let scheme = use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .color_scheme;
                        let label_color = scheme.on_secondary_container;
                        button(button_args, move || {
                            elastic_container(state, index, move || child_closure(label_color))
                        });
                    }
                });
                if index != child_len - 1 {
                    scope.child(move || {
                        spacer(Modifier::new().width(layout.between_space));
                    })
                }
            }
        },
    )
}

struct ElasticState {
    expended: bool,
    last_toggle: Option<Instant>,
    start_progress: f32,
}

impl Default for ElasticState {
    fn default() -> Self {
        Self {
            expended: false,
            last_toggle: None,
            start_progress: 0.0,
        }
    }
}

impl ElasticState {
    fn toggle(&mut self) {
        let current_visual_progress = self.calculate_current_progress();
        self.expended = !self.expended;
        self.last_toggle = Some(Instant::now());
        self.start_progress = current_visual_progress;
    }

    fn update(&mut self) -> f32 {
        let current_progress = self.calculate_current_progress();
        if self.expended {
            animation::spring(current_progress, 15.0, 0.35)
        } else {
            animation::easing(current_progress)
        }
    }

    fn calculate_current_progress(&self) -> f32 {
        let Some(last_toggle) = self.last_toggle else {
            return if self.expended { 1.0 } else { 0.0 };
        };

        let elapsed = last_toggle.elapsed().as_secs_f32();
        let duration = 0.25;
        let t = (elapsed / duration).clamp(0.0, 1.0);
        let start = self.start_progress;
        let target = if self.expended { 1.0 } else { 0.0 };

        start + (target - start) * t
    }
}

#[tessera]
fn elastic_container(
    state: tessera_ui::State<ButtonGroupsState>,
    index: usize,
    child: impl FnOnce(),
) {
    child();
    let progress = state.with_mut(|s| s.item_state_mut(index).elastic_state.update());
    layout(ElasticContainerLayout { progress })
}

#[derive(Clone, Copy, PartialEq)]
struct ElasticContainerLayout {
    progress: f32,
}

impl LayoutSpec for ElasticContainerLayout {
    fn measure(
        &self,
        input: &LayoutInput<'_>,
        output: &mut LayoutOutput<'_>,
    ) -> Result<ComputedData, MeasurementError> {
        let child_id = input.children_ids()[0];
        let child_size = input.measure_child_in_parent_constraint(child_id)?;
        let additional_width = child_size.width.mul_f32(0.15 * self.progress);
        output.place_child(child_id, PxPosition::new(additional_width / 2, Px::ZERO));

        Ok(ComputedData {
            width: child_size.width + additional_width,
            height: child_size.height,
        })
    }
}