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
//! Material-styled button components.
//!
//! ## Usage
//!
//! Trigger actions, submit forms, or navigate.
use std::sync::Arc;

use derive_setters::Setters;
use tessera_ui::{Color, Dp, Modifier, accesskit::Role, tessera, use_context};

use crate::{
    alignment::Alignment,
    modifier::ModifierExt,
    shape_def::Shape,
    surface::{SurfaceArgs, surface},
    theme::{
        ContentColor, MaterialAlpha, MaterialColorScheme, MaterialTheme, content_color_for,
        provide_text_style,
    },
};

/// Material Design 3 defaults for [`button`].
pub struct ButtonDefaults;

impl ButtonDefaults {
    /// Default pressed alpha used for ripple feedback.
    pub const PRESSED_ALPHA: f32 = MaterialAlpha::PRESSED;
    /// Default disabled container alpha.
    pub const DISABLED_CONTAINER_ALPHA: f32 = MaterialAlpha::DISABLED_CONTAINER;
    /// Default disabled content alpha.
    pub const DISABLED_CONTENT_ALPHA: f32 = MaterialAlpha::DISABLED_CONTENT;
    /// Disabled container opacity used by filled/elevated buttons.
    pub const FILLED_DISABLED_CONTAINER_ALPHA: f32 = 0.1;
    /// Disabled content opacity used by most buttons.
    pub const DISABLED_LABEL_ALPHA: f32 = 0.38;
    /// Minimum width for buttons (Material default = 58dp).
    pub const MIN_WIDTH: Dp = Dp(58.0);
    /// Minimum height for buttons (Material default = 40dp).
    pub const MIN_HEIGHT: Dp = Dp(40.0);
    /// Horizontal padding used inside buttons.
    pub const CONTENT_HORIZONTAL_PADDING: Dp = Dp(16.0);
    /// Vertical padding used inside buttons.
    pub const CONTENT_VERTICAL_PADDING: Dp = Dp(8.0);

    /// Default disabled container color for filled buttons.
    pub fn disabled_container_color(scheme: &MaterialColorScheme) -> Color {
        scheme
            .on_surface
            .with_alpha(Self::FILLED_DISABLED_CONTAINER_ALPHA)
    }

    /// Default disabled content color for filled buttons.
    pub fn disabled_content_color(scheme: &MaterialColorScheme) -> Color {
        scheme
            .on_surface_variant
            .with_alpha(Self::DISABLED_LABEL_ALPHA)
    }

    /// Default disabled border color for outlined buttons.
    pub fn disabled_border_color(scheme: &MaterialColorScheme) -> Color {
        scheme
            .outline_variant
            .with_alpha(Self::FILLED_DISABLED_CONTAINER_ALPHA)
    }
}

/// Arguments for the `button` component.
#[derive(Clone, Setters)]
pub struct ButtonArgs {
    /// Whether the button is enabled for user interaction.
    pub enabled: bool,
    /// Optional modifier chain applied to the button subtree.
    pub modifier: Modifier,
    /// The fill color of the button (RGBA).
    pub color: Color,
    /// Optional explicit content color override for descendants.
    ///
    /// When `None`, the button derives its content color from the theme.
    #[setters(strip_option)]
    pub content_color: Option<Color>,
    /// The shape of the button.
    pub shape: Shape,
    /// The padding of the button.
    pub padding: Dp,
    /// The click callback function
    #[setters(skip)]
    pub on_click: Option<Arc<dyn Fn() + Send + Sync>>,
    /// The ripple color (RGB) for the button.
    pub ripple_color: Color,
    /// Width of the border. If > 0, an outline will be drawn.
    pub border_width: Dp,
    /// Optional color for the border (RGBA). If None and border_width > 0,
    /// `color` will be used.
    pub border_color: Option<Color>,
    /// Optional shadow elevation hint forwarded to the underlying surface.
    #[setters(strip_option)]
    pub elevation: Option<Dp>,
    /// Tonal elevation forwarded to the underlying surface.
    pub tonal_elevation: Dp,
    /// Container color used when `enabled=false`.
    pub disabled_container_color: Color,
    /// Content color used when `enabled=false`.
    pub disabled_content_color: Color,
    /// Border color used when `enabled=false` and an outline is drawn.
    pub disabled_border_color: Color,
    /// Optional label announced by assistive technologies (e.g., screen
    /// readers).
    #[setters(strip_option, into)]
    pub accessibility_label: Option<String>,
    /// Optional longer description or hint for assistive technologies.
    #[setters(strip_option, into)]
    pub accessibility_description: Option<String>,
}

impl ButtonArgs {
    /// Set the click handler.
    pub fn on_click<F>(mut self, on_click: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.on_click = Some(Arc::new(on_click));
        self
    }

    /// Set the click handler using a shared callback.
    pub fn on_click_shared(mut self, on_click: Arc<dyn Fn() + Send + Sync>) -> Self {
        self.on_click = Some(on_click);
        self
    }
}

impl Default for ButtonArgs {
    fn default() -> Self {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        Self {
            enabled: true,
            modifier: Modifier::new(),
            color: scheme.primary,
            content_color: None,
            shape: Shape::capsule(),
            padding: ButtonDefaults::CONTENT_VERTICAL_PADDING,
            on_click: Some(Arc::new(|| {})),
            ripple_color: scheme.on_primary,
            border_width: Dp(0.0),
            border_color: None,
            elevation: None,
            tonal_elevation: Dp(0.0),
            disabled_container_color: ButtonDefaults::disabled_container_color(&scheme),
            disabled_content_color: ButtonDefaults::disabled_content_color(&scheme),
            disabled_border_color: ButtonDefaults::disabled_border_color(&scheme),
            accessibility_label: None,
            accessibility_description: None,
        }
    }
}

/// # button
///
/// Provides a clickable button with customizable style and ripple feedback.
///
/// ## Usage
///
/// Use to trigger an action when the user clicks or taps.
///
/// ## Parameters
///
/// - `args` — configures the button's appearance and `on_click` handler; see
///   [`ButtonArgs`].
/// - `child` — a closure that renders the button's content (e.g., text or an
///   icon).
///
/// ## Examples
///
/// ```
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// use tessera_components::{
///     button::{ButtonArgs, button},
///     text::{TextArgs, text},
/// };
/// # use tessera_components::theme::{MaterialTheme, material_theme};
///
/// # material_theme(|| MaterialTheme::default(), || {
/// button(ButtonArgs::filled(|| {}), || {
///     text(TextArgs::default().text("Click Me"));
/// });
/// # });
/// # }
/// # component();
/// ```
#[tessera]
pub fn button(args: impl Into<ButtonArgs>, child: impl FnOnce() + Send + Sync + 'static) {
    let button_args: ButtonArgs = args.into();
    let typography = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .typography;

    // Create interactive surface for button
    surface(create_surface_args(&button_args), move || {
        Modifier::new()
            .padding_all(button_args.padding)
            .run(move || {
                provide_text_style(typography.label_large, child);
            });
    });
}

/// Create surface arguments based on button configuration
fn create_surface_args(args: &ButtonArgs) -> crate::surface::SurfaceArgs {
    let scheme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .color_scheme;
    let inherited_content_color = use_context::<ContentColor>()
        .map(|c| c.get().current)
        .unwrap_or(ContentColor::default().current);

    let container_color = if args.enabled {
        args.color
    } else {
        args.disabled_container_color
    };

    let content_color = if args.enabled {
        args.content_color.unwrap_or_else(|| {
            content_color_for(args.color, &scheme).unwrap_or(inherited_content_color)
        })
    } else {
        args.disabled_content_color
    };

    let style = if args.border_width.to_pixels_f32() > 0.0 {
        let border_color = if args.enabled {
            args.border_color.unwrap_or(container_color)
        } else {
            args.disabled_border_color
        };
        crate::surface::SurfaceStyle::FilledOutlined {
            fill_color: container_color,
            border_color,
            border_width: args.border_width,
        }
    } else {
        crate::surface::SurfaceStyle::Filled {
            color: container_color,
        }
    };

    let mut surface_args = SurfaceArgs::default();

    if let Some(elevation) = args.elevation {
        surface_args = surface_args.elevation(elevation);
    }

    // Set on_click handler if available
    if args.enabled
        && let Some(on_click) = args.on_click.clone()
    {
        surface_args = surface_args.on_click_shared(on_click);
    }

    if let Some(label) = args.accessibility_label.clone() {
        surface_args = surface_args.accessibility_label(label);
    }

    if let Some(description) = args.accessibility_description.clone() {
        surface_args = surface_args.accessibility_description(description);
    }

    surface_args
        .style(style)
        .shape(args.shape)
        .modifier(args.modifier.size_in(
            Some(ButtonDefaults::MIN_WIDTH),
            None,
            Some(ButtonDefaults::MIN_HEIGHT),
            None,
        ))
        .ripple_color(args.ripple_color)
        .content_alignment(Alignment::Center)
        .content_color(content_color)
        .enabled(args.enabled)
        .tonal_elevation(args.tonal_elevation)
        .accessibility_role(Role::Button)
        .accessibility_focusable(true)
}

/// Convenience constructors for standard Material Design 3 button styles
impl ButtonArgs {
    /// Create a standard "Filled" button (High emphasis).
    /// Uses Primary color for container and OnPrimary for content.
    pub fn filled(on_click: impl Fn() + Send + Sync + 'static) -> Self {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        ButtonArgs::default()
            .color(scheme.primary)
            .content_color(scheme.on_primary)
            .ripple_color(scheme.on_primary)
            .disabled_container_color(
                scheme
                    .on_surface
                    .with_alpha(ButtonDefaults::FILLED_DISABLED_CONTAINER_ALPHA),
            )
            .disabled_content_color(
                scheme
                    .on_surface_variant
                    .with_alpha(ButtonDefaults::DISABLED_LABEL_ALPHA),
            )
            .on_click(on_click)
    }

    /// Create an "Elevated" button (Medium emphasis).
    /// Uses Surface color (or SurfaceContainerLow if available) with a shadow.
    pub fn elevated(on_click: impl Fn() + Send + Sync + 'static) -> Self {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        ButtonArgs::default()
            .color(scheme.surface_container_low)
            .content_color(scheme.primary)
            .ripple_color(scheme.primary)
            .elevation(Dp(1.0))
            .disabled_container_color(
                scheme
                    .on_surface
                    .with_alpha(ButtonDefaults::FILLED_DISABLED_CONTAINER_ALPHA),
            )
            .disabled_content_color(
                scheme
                    .on_surface_variant
                    .with_alpha(ButtonDefaults::DISABLED_LABEL_ALPHA),
            )
            .on_click(on_click)
    }

    /// Create a "Tonal" button (Medium emphasis).
    /// Uses SecondaryContainer color for container and OnSecondaryContainer for
    /// content.
    pub fn tonal(on_click: impl Fn() + Send + Sync + 'static) -> Self {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        ButtonArgs::default()
            .color(scheme.secondary_container)
            .content_color(scheme.on_secondary_container)
            .ripple_color(scheme.on_secondary_container)
            .disabled_container_color(
                scheme
                    .on_surface
                    .with_alpha(ButtonDefaults::DISABLED_CONTAINER_ALPHA),
            )
            .disabled_content_color(
                scheme
                    .on_surface
                    .with_alpha(ButtonDefaults::DISABLED_CONTENT_ALPHA),
            )
            .on_click(on_click)
    }

    /// Create an "Outlined" button (Medium emphasis).
    /// Transparent container with an Outline border.
    pub fn outlined(on_click: impl Fn() + Send + Sync + 'static) -> Self {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        ButtonArgs::default()
            .color(Color::TRANSPARENT)
            .content_color(scheme.on_surface_variant)
            .disabled_container_color(Color::TRANSPARENT)
            .ripple_color(scheme.on_surface_variant)
            .border_width(Dp(1.0))
            .border_color(Some(scheme.outline_variant))
            .disabled_border_color(
                scheme
                    .outline_variant
                    .with_alpha(ButtonDefaults::FILLED_DISABLED_CONTAINER_ALPHA),
            )
            .disabled_content_color(
                scheme
                    .on_surface_variant
                    .with_alpha(ButtonDefaults::DISABLED_LABEL_ALPHA),
            )
            .on_click(on_click)
    }

    /// Create a "Text" button (Low emphasis).
    /// Transparent container and no border.
    pub fn text(on_click: impl Fn() + Send + Sync + 'static) -> Self {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        ButtonArgs::default()
            .color(Color::TRANSPARENT)
            .content_color(scheme.primary)
            .disabled_container_color(Color::TRANSPARENT)
            .ripple_color(scheme.primary)
            .disabled_content_color(
                scheme
                    .on_surface_variant
                    .with_alpha(ButtonDefaults::DISABLED_LABEL_ALPHA),
            )
            .on_click(on_click)
    }
}

/// Builder methods for fluent API
impl ButtonArgs {
    /// Sets the fill color for the button.
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    /// Updates the padding inside the button.
    pub fn with_padding(mut self, padding: Dp) -> Self {
        self.padding = padding;
        self
    }

    /// Overrides the button's shape.
    pub fn with_shape(mut self, shape: Shape) -> Self {
        self.shape = shape;
        self
    }

    /// Adjusts the ripple color tint.
    pub fn with_ripple_color(mut self, ripple_color: Color) -> Self {
        self.ripple_color = ripple_color;
        self
    }

    /// Configures the border width and optional color.
    pub fn with_border(mut self, width: Dp, color: Option<Color>) -> Self {
        self.border_width = width;
        self.border_color = color;
        self
    }
}