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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! Material Design card primitives.
//!
//! ## Usage
//!
//! Group related content into a single, elevated or outlined container.

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

use derive_setters::Setters;
use tessera_ui::{Color, Dp, InputHandlerInput, Modifier, State, remember, tessera, use_context};

use crate::{
    column::{ColumnArgs, ColumnScope, column},
    modifier::InteractionState,
    shape_def::Shape,
    surface::{SurfaceArgs, SurfaceStyle, surface},
    theme::{ContentColor, MaterialAlpha, MaterialTheme, content_color_for},
};

const DEFAULT_SPATIAL_DAMPING_RATIO: f32 = 0.9;
const DEFAULT_SPATIAL_STIFFNESS: f32 = 700.0;

fn composite_over(base: Color, overlay: Color) -> Color {
    let overlay_a = overlay.a.clamp(0.0, 1.0);
    let base_a = base.a.clamp(0.0, 1.0);
    let out_a = overlay_a + base_a * (1.0 - overlay_a);
    if out_a <= 0.0 {
        return Color::TRANSPARENT;
    }

    let r = (overlay.r * overlay_a + base.r * base_a * (1.0 - overlay_a)) / out_a;
    let g = (overlay.g * overlay_a + base.g * base_a * (1.0 - overlay_a)) / out_a;
    let b = (overlay.b * overlay_a + base.b * base_a * (1.0 - overlay_a)) / out_a;
    Color::new(r, g, b, out_a)
}

#[derive(Clone, Copy, Debug)]
struct Spring1D {
    value: f32,
    velocity: f32,
    target: f32,
}

impl Spring1D {
    fn new(value: f32) -> Self {
        Self {
            value,
            velocity: 0.0,
            target: value,
        }
    }

    fn snap_to(&mut self, value: f32) {
        self.value = value;
        self.target = value;
        self.velocity = 0.0;
    }

    fn set_target(&mut self, target: f32) {
        self.target = target;
    }

    fn update(&mut self, dt: f32, stiffness: f32, damping_ratio: f32) {
        let dt = dt.clamp(0.0, 0.05);
        let stiffness = stiffness.max(0.0);
        if stiffness == 0.0 {
            self.snap_to(self.target);
            return;
        }

        let damping_ratio = damping_ratio.max(0.0);
        let damping = 2.0 * damping_ratio * stiffness.sqrt();
        let displacement = self.value - self.target;
        let acceleration = -stiffness * displacement - damping * self.velocity;

        self.velocity += acceleration * dt;
        self.value += self.velocity * dt;

        if (self.value - self.target).abs() < 0.01 && self.velocity.abs() < 0.01 {
            self.snap_to(self.target);
        }
    }
}

#[derive(Clone, Debug)]
struct CardElevationSpring {
    last_frame_time: Option<Instant>,
    spring: Spring1D,
}

impl CardElevationSpring {
    fn new(initial: Dp) -> Self {
        Self {
            last_frame_time: None,
            spring: Spring1D::new(initial.0 as f32),
        }
    }

    fn set_target(&mut self, target: Dp) {
        self.spring.set_target(target.0 as f32);
    }

    fn snap_to(&mut self, target: Dp) {
        self.spring.snap_to(target.0 as f32);
    }

    fn tick(&mut self, now: Instant) {
        let dt = if let Some(last) = self.last_frame_time {
            now.saturating_duration_since(last).as_secs_f32()
        } else {
            1.0 / 60.0
        };
        self.last_frame_time = Some(now);
        self.spring
            .update(dt, DEFAULT_SPATIAL_STIFFNESS, DEFAULT_SPATIAL_DAMPING_RATIO);
    }

    fn value_dp(&self) -> Dp {
        Dp(self.spring.value as f64)
    }
}

/// Visual variants supported by [`card`].
#[derive(Clone, Copy, Debug, Default)]
pub enum CardVariant {
    /// Filled cards provide subtle separation from the background.
    #[default]
    Filled,
    /// Elevated cards provide more emphasis via shadow elevation.
    Elevated,
    /// Outlined cards provide emphasis via a border stroke.
    Outlined,
}

/// Represents the container and content colors used in a card in different
/// states.
#[derive(Clone, Copy, Debug)]
pub struct CardColors {
    /// Container color used when enabled.
    pub container_color: Color,
    /// Content color used when enabled.
    pub content_color: Color,
    /// Container color used when disabled.
    pub disabled_container_color: Color,
    /// Content color used when disabled.
    pub disabled_content_color: Color,
}

impl CardColors {
    fn container_color(self, enabled: bool) -> Color {
        if enabled {
            self.container_color
        } else {
            self.disabled_container_color
        }
    }

    fn content_color(self, enabled: bool) -> Color {
        if enabled {
            self.content_color
        } else {
            self.disabled_content_color
        }
    }
}

/// Represents a border stroke for card containers.
#[derive(Clone, Copy, Debug)]
pub struct CardBorder {
    /// Border width.
    pub width: Dp,
    /// Border color.
    pub color: Color,
}

/// Represents the elevation for a card in different states.
#[derive(Clone, Copy, Debug)]
pub struct CardElevation {
    default_elevation: Dp,
    pressed_elevation: Dp,
    focused_elevation: Dp,
    hovered_elevation: Dp,
    dragged_elevation: Dp,
    disabled_elevation: Dp,
}

impl CardElevation {
    fn default_elevation(self) -> Dp {
        self.default_elevation
    }

    fn target(self, enabled: bool, interaction_state: Option<State<InteractionState>>) -> Dp {
        if !enabled {
            return self.disabled_elevation;
        }

        let Some(state) = interaction_state else {
            return self.default_elevation;
        };

        state.with(|s| {
            if s.is_dragged() {
                self.dragged_elevation
            } else if s.is_pressed() {
                self.pressed_elevation
            } else if s.is_focused() {
                self.focused_elevation
            } else if s.is_hovered() {
                self.hovered_elevation
            } else {
                self.default_elevation
            }
        })
    }
}

/// Default values for card components.
pub struct CardDefaults;

impl CardDefaults {
    /// Opacity applied to disabled container overlays.
    pub const DISABLED_CONTAINER_OPACITY: f32 = 0.38;
    /// Opacity applied to disabled content.
    pub const DISABLED_CONTENT_ALPHA: f32 = MaterialAlpha::DISABLED_CONTENT;
    /// Border opacity for disabled outlined cards.
    pub const DISABLED_OUTLINE_ALPHA: f32 = 0.12;

    /// Default filled card shape.
    pub fn shape() -> Shape {
        use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .shapes
            .medium
    }

    /// Default elevated card shape.
    pub fn elevated_shape() -> Shape {
        use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .shapes
            .medium
    }

    /// Default outlined card shape.
    pub fn outlined_shape() -> Shape {
        use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .shapes
            .medium
    }

    /// Default elevation values for filled cards.
    pub fn card_elevation() -> CardElevation {
        CardElevation {
            default_elevation: Dp(0.0),
            pressed_elevation: Dp(0.0),
            focused_elevation: Dp(0.0),
            hovered_elevation: Dp(1.0),
            dragged_elevation: Dp(3.0),
            disabled_elevation: Dp(0.0),
        }
    }

    /// Default elevation values for elevated cards.
    pub fn elevated_card_elevation() -> CardElevation {
        CardElevation {
            default_elevation: Dp(1.0),
            pressed_elevation: Dp(1.0),
            focused_elevation: Dp(1.0),
            hovered_elevation: Dp(2.0),
            dragged_elevation: Dp(4.0),
            disabled_elevation: Dp(1.0),
        }
    }

    /// Default elevation values for outlined cards.
    pub fn outlined_card_elevation() -> CardElevation {
        CardElevation {
            default_elevation: Dp(0.0),
            pressed_elevation: Dp(0.0),
            focused_elevation: Dp(0.0),
            hovered_elevation: Dp(0.0),
            dragged_elevation: Dp(3.0),
            disabled_elevation: Dp(0.0),
        }
    }

    /// Default colors for filled cards.
    pub fn card_colors() -> CardColors {
        let theme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get();
        let scheme = theme.color_scheme;
        let inherited_content = use_context::<ContentColor>()
            .map(|c| c.get().current)
            .unwrap_or(ContentColor::default().current);
        let container = scheme.surface_container_highest;
        let content = content_color_for(container, &scheme).unwrap_or(inherited_content);
        let disabled_overlay = scheme
            .surface_variant
            .with_alpha(Self::DISABLED_CONTAINER_OPACITY);
        let disabled_container = composite_over(container, disabled_overlay);
        CardColors {
            container_color: container,
            content_color: content,
            disabled_container_color: disabled_container,
            disabled_content_color: content.with_alpha(Self::DISABLED_CONTENT_ALPHA),
        }
    }

    /// Default colors for elevated cards.
    pub fn elevated_card_colors() -> CardColors {
        let theme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get();
        let scheme = theme.color_scheme;
        let inherited_content = use_context::<ContentColor>()
            .map(|c| c.get().current)
            .unwrap_or(ContentColor::default().current);
        let container = scheme.surface_container_low;
        let content = content_color_for(container, &scheme).unwrap_or(inherited_content);
        CardColors {
            container_color: container,
            content_color: content,
            disabled_container_color: scheme.surface,
            disabled_content_color: content.with_alpha(Self::DISABLED_CONTENT_ALPHA),
        }
    }

    /// Default colors for outlined cards.
    pub fn outlined_card_colors() -> CardColors {
        let theme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get();
        let scheme = theme.color_scheme;
        let inherited_content = use_context::<ContentColor>()
            .map(|c| c.get().current)
            .unwrap_or(ContentColor::default().current);
        let container = scheme.surface;
        let content = content_color_for(container, &scheme).unwrap_or(inherited_content);
        CardColors {
            container_color: container,
            content_color: content,
            disabled_container_color: container,
            disabled_content_color: content.with_alpha(Self::DISABLED_CONTENT_ALPHA),
        }
    }

    /// Default border stroke for outlined cards.
    pub fn outlined_card_border(enabled: bool) -> CardBorder {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        let color = if enabled {
            scheme.outline_variant
        } else {
            composite_over(
                scheme.surface_container_low,
                scheme.outline.with_alpha(Self::DISABLED_OUTLINE_ALPHA),
            )
        };
        CardBorder {
            width: Dp(1.0),
            color,
        }
    }
}

/// Arguments for the [`card`] component.
#[derive(Clone, Setters)]
pub struct CardArgs {
    /// Optional modifier chain applied to the card subtree.
    pub modifier: Modifier,
    /// Card variant controlling default tokens.
    pub variant: CardVariant,
    /// Whether the card is enabled for user interaction.
    pub enabled: bool,
    /// Optional click handler for a clickable card.
    #[setters(skip)]
    pub on_click: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Optional shared interaction state for elevation and state layers.
    #[setters(strip_option)]
    pub interaction_state: Option<State<InteractionState>>,
    /// Optional container shape override.
    #[setters(strip_option)]
    pub shape: Option<Shape>,
    /// Optional colors override.
    #[setters(strip_option)]
    pub colors: Option<CardColors>,
    /// Optional elevation override.
    #[setters(strip_option)]
    pub elevation: Option<CardElevation>,
    /// Optional border stroke for the card container.
    #[setters(strip_option)]
    pub border: Option<CardBorder>,
}

impl CardArgs {
    /// 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 CardArgs {
    /// Creates a filled card configuration using default tokens.
    pub fn filled() -> Self {
        CardArgs::default().variant(CardVariant::Filled)
    }

    /// Creates an elevated card configuration using default tokens.
    pub fn elevated() -> Self {
        CardArgs::default().variant(CardVariant::Elevated)
    }

    /// Creates an outlined card configuration using default tokens.
    pub fn outlined() -> Self {
        CardArgs::default()
            .variant(CardVariant::Outlined)
            .border(CardDefaults::outlined_card_border(true))
    }
}

impl Default for CardArgs {
    fn default() -> Self {
        Self {
            modifier: Modifier::new(),
            variant: CardVariant::default(),
            enabled: true,
            on_click: None,
            interaction_state: None,
            shape: None,
            colors: None,
            elevation: None,
            border: None,
        }
    }
}

/// # card
///
/// Renders a Material card container, optionally clickable and with animated
/// elevation.
///
/// ## Usage
///
/// Group related information and actions into a visually distinct container.
///
/// ## Parameters
///
/// - `args` — configures the card variant, colors, elevation, and interaction;
///   see [`CardArgs`].
/// - `content` — builds the card body as a [`Column`] using a [`ColumnScope`].
///
/// ## Examples
///
/// ```
/// use tessera_components::card::{CardArgs, card};
/// use tessera_ui::tessera;
/// # use tessera_components::theme::{MaterialTheme, material_theme};
///
/// #[tessera]
/// fn component() {
/// #     material_theme(
/// #         || MaterialTheme::default(),
/// #         || {
///     card(CardArgs::filled(), |_scope| {});
/// #         },
/// #     );
/// }
///
/// component();
/// ```
#[tessera]
pub fn card<F>(args: impl Into<CardArgs>, content: F)
where
    F: FnOnce(&mut ColumnScope) + Send + Sync + 'static,
{
    let args: CardArgs = args.into();

    let shape = args.shape.unwrap_or_else(|| match args.variant {
        CardVariant::Filled => CardDefaults::shape(),
        CardVariant::Elevated => CardDefaults::elevated_shape(),
        CardVariant::Outlined => CardDefaults::outlined_shape(),
    });

    let colors = args.colors.unwrap_or_else(|| match args.variant {
        CardVariant::Filled => CardDefaults::card_colors(),
        CardVariant::Elevated => CardDefaults::elevated_card_colors(),
        CardVariant::Outlined => CardDefaults::outlined_card_colors(),
    });

    let elevation = args.elevation.unwrap_or_else(|| match args.variant {
        CardVariant::Filled => CardDefaults::card_elevation(),
        CardVariant::Elevated => CardDefaults::elevated_card_elevation(),
        CardVariant::Outlined => CardDefaults::outlined_card_elevation(),
    });

    let border = match args.border {
        Some(border) => Some(border),
        None if matches!(args.variant, CardVariant::Outlined) => {
            Some(CardDefaults::outlined_card_border(args.enabled))
        }
        None => None,
    };

    let clickable = args.on_click.is_some();
    let interaction_state = if clickable {
        Some(
            args.interaction_state
                .unwrap_or_else(|| remember(InteractionState::new)),
        )
    } else {
        None
    };

    let elevation_spring = remember(|| CardElevationSpring::new(elevation.default_elevation()));

    let enabled = args.enabled;
    input_handler(move |_input: InputHandlerInput| {
        let now = Instant::now();
        let target = elevation.target(enabled, interaction_state);
        elevation_spring.with_mut(|spring| {
            spring.set_target(target);
            if !enabled {
                spring.snap_to(target);
            }
            spring.tick(now);
        });
    });

    let shadow_elevation = if clickable {
        elevation_spring.with(|s| s.value_dp())
    } else {
        elevation.default_elevation()
    };

    let container_color = colors.container_color(args.enabled);
    let content_color = colors.content_color(args.enabled);

    let mut surface_args = SurfaceArgs::default()
        .shape(shape)
        .modifier(args.modifier)
        .content_color(content_color)
        .elevation(shadow_elevation)
        .tonal_elevation(shadow_elevation)
        .enabled(args.enabled);

    let style = match border {
        Some(border) => SurfaceStyle::FilledOutlined {
            fill_color: container_color,
            border_color: border.color,
            border_width: border.width,
        },
        None => SurfaceStyle::Filled {
            color: container_color,
        },
    };
    surface_args = surface_args.style(style);

    if let Some(state) = interaction_state {
        surface_args = surface_args.interaction_state(state);
    }

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

    surface(surface_args, move || {
        column(ColumnArgs::default(), content);
    });
}