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
//! Material Design badge primitives.
//!
//! ## Usage
//!
//! Highlight counts or status markers on top of icons and other UI elements.

use derive_setters::Setters;
use tessera_ui::{
    Color, ComputedData, Constraint, DimensionValue, Dp, LayoutInput, LayoutOutput, LayoutSpec,
    MeasurementError, Px, PxPosition, PxSize, RenderInput, provide_context, tessera, use_context,
};

use crate::{
    alignment::{CrossAxisAlignment, MainAxisAlignment},
    pipelines::shape::command::ShapeCommand,
    row::{RowArgs, RowScope, row},
    shape_def::{ResolvedShape, Shape},
    theme::{ContentColor, MaterialTheme, content_color_for, provide_text_style},
};

fn clamp_wrap(min: Option<Px>, max: Option<Px>, measure: Px) -> Px {
    min.unwrap_or(Px(0))
        .max(measure)
        .min(max.unwrap_or(Px::MAX))
}

fn fill_value(min: Option<Px>, max: Option<Px>, measure: Px) -> Px {
    max.expect("Seems that you are trying to fill an infinite dimension, which is not allowed")
        .max(measure)
        .max(min.unwrap_or(Px(0)))
}

fn resolve_dimension(dim: DimensionValue, measure: Px) -> Px {
    match dim {
        DimensionValue::Fixed(v) => v,
        DimensionValue::Wrap { min, max } => clamp_wrap(min, max, measure),
        DimensionValue::Fill { min, max } => fill_value(min, max, measure),
    }
}

fn dimension_max(dim: DimensionValue) -> Option<Px> {
    match dim {
        DimensionValue::Fixed(v) => Some(v),
        DimensionValue::Wrap { max, .. } | DimensionValue::Fill { max, .. } => max,
    }
}

fn relax_min_constraint(dim: DimensionValue) -> DimensionValue {
    match dim {
        DimensionValue::Fixed(v) => DimensionValue::Wrap {
            min: Some(Px(0)),
            max: Some(v),
        },
        DimensionValue::Wrap { max, .. } => DimensionValue::Wrap {
            min: Some(Px(0)),
            max,
        },
        DimensionValue::Fill { max, .. } => DimensionValue::Fill {
            min: Some(Px(0)),
            max,
        },
    }
}

#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
struct BadgedBoxLayout;

impl LayoutSpec for BadgedBoxLayout {
    fn measure(
        &self,
        input: &LayoutInput<'_>,
        output: &mut LayoutOutput<'_>,
    ) -> Result<ComputedData, MeasurementError> {
        debug_assert_eq!(
            input.children_ids().len(),
            2,
            "badged_box expects exactly two children: anchor and badge",
        );

        let parent_constraint = Constraint::new(
            input.parent_constraint().width(),
            input.parent_constraint().height(),
        );

        let badge_constraint = Constraint::new(
            input.parent_constraint().width(),
            relax_min_constraint(input.parent_constraint().height()),
        );

        let anchor_id = input.children_ids()[0];
        let badge_id = input.children_ids()[1];

        let to_measure = vec![(badge_id, badge_constraint), (anchor_id, parent_constraint)];

        let results = input.measure_children(to_measure)?;
        let anchor = results
            .get(&anchor_id)
            .copied()
            .expect("badged_box anchor must be measured");
        let badge_data = results
            .get(&badge_id)
            .copied()
            .expect("badged_box badge must be measured");

        output.place_child(anchor_id, PxPosition::new(Px(0), Px(0)));

        let badge_size_px = BadgeDefaults::SIZE.to_px();
        let has_content = badge_data.width > badge_size_px;

        let horizontal_offset = if has_content {
            BadgeDefaults::WITH_CONTENT_HORIZONTAL_OFFSET
        } else {
            BadgeDefaults::OFFSET
        }
        .to_px();

        let vertical_offset = if has_content {
            BadgeDefaults::WITH_CONTENT_VERTICAL_OFFSET
        } else {
            BadgeDefaults::OFFSET
        }
        .to_px();

        let badge_x = anchor.width - horizontal_offset;
        let badge_y = -badge_data.height + vertical_offset;

        output.place_child(badge_id, PxPosition::new(badge_x, badge_y));

        Ok(ComputedData {
            width: anchor.width,
            height: anchor.height,
        })
    }
}

#[derive(Clone, Copy, PartialEq)]
struct BadgeLayout {
    container_color: Color,
}

impl LayoutSpec for BadgeLayout {
    fn measure(
        &self,
        input: &LayoutInput<'_>,
        _output: &mut LayoutOutput<'_>,
    ) -> Result<ComputedData, MeasurementError> {
        let size_px = BadgeDefaults::SIZE.to_px();
        let intrinsic = Constraint::new(
            DimensionValue::Wrap {
                min: Some(size_px),
                max: None,
            },
            DimensionValue::Wrap {
                min: Some(size_px),
                max: None,
            },
        );
        let effective = intrinsic.merge(input.parent_constraint());

        let width = resolve_dimension(effective.width, size_px);
        let height = resolve_dimension(effective.height, size_px);

        Ok(ComputedData { width, height })
    }

    fn record(&self, input: &RenderInput<'_>) {
        let mut metadata = input.metadata_mut();
        let size = metadata
            .computed_data
            .expect("badge must have computed size before record");

        let ResolvedShape::Rounded {
            corner_radii,
            corner_g2,
        } = BadgeDefaults::SHAPE.resolve_for_size(PxSize::new(size.width, size.height))
        else {
            unreachable!("badge shape must resolve to a rounded rectangle");
        };

        metadata.push_draw_command(ShapeCommand::Rect {
            color: self.container_color,
            corner_radii,
            corner_g2,
            shadow: None,
        });
    }
}

#[derive(Clone, Copy, PartialEq)]
struct BadgeWithContentLayout {
    container_color: Color,
    padding_px: Px,
}

impl LayoutSpec for BadgeWithContentLayout {
    fn measure(
        &self,
        input: &LayoutInput<'_>,
        output: &mut LayoutOutput<'_>,
    ) -> Result<ComputedData, MeasurementError> {
        debug_assert_eq!(
            input.children_ids().len(),
            1,
            "badge_with_content expects a single row child",
        );

        let min_size_px = BadgeDefaults::LARGE_SIZE.to_px();
        let intrinsic = Constraint::new(
            DimensionValue::Wrap {
                min: Some(min_size_px),
                max: None,
            },
            DimensionValue::Wrap {
                min: Some(min_size_px),
                max: None,
            },
        );
        let effective = intrinsic.merge(input.parent_constraint());

        let max_width =
            dimension_max(effective.width).map(|v| (v - self.padding_px * 2).max(Px(0)));
        let max_height = dimension_max(effective.height);

        let child_constraint = Constraint::new(
            DimensionValue::Wrap {
                min: None,
                max: max_width,
            },
            DimensionValue::Wrap {
                min: None,
                max: max_height,
            },
        );

        let row_id = input.children_ids()[0];
        let row_data = input.measure_child(row_id, &child_constraint)?;

        let measured_width = (row_data.width + self.padding_px * 2).max(min_size_px);
        let measured_height = row_data.height.max(min_size_px);

        let width = resolve_dimension(effective.width, measured_width);
        let height = resolve_dimension(effective.height, measured_height);

        let x = (width - row_data.width).max(Px(0)) / 2;
        let y = (height - row_data.height).max(Px(0)) / 2;
        output.place_child(row_id, PxPosition::new(x, y));

        Ok(ComputedData { width, height })
    }

    fn record(&self, input: &RenderInput<'_>) {
        let mut metadata = input.metadata_mut();
        let size = metadata
            .computed_data
            .expect("badge_with_content must have computed size before record");

        let ResolvedShape::Rounded {
            corner_radii,
            corner_g2,
        } = BadgeDefaults::SHAPE.resolve_for_size(PxSize::new(size.width, size.height))
        else {
            unreachable!("badge shape must resolve to a rounded rectangle");
        };

        metadata.push_draw_command(ShapeCommand::Rect {
            color: self.container_color,
            corner_radii,
            corner_g2,
            shadow: None,
        });
    }
}

/// Default values for [`badge`], [`badge_with_content`], and [`badged_box`].
pub struct BadgeDefaults;

impl BadgeDefaults {
    /// Default badge size when it has no content.
    pub const SIZE: Dp = Dp(6.0);
    /// Default badge size when it has content.
    pub const LARGE_SIZE: Dp = Dp(16.0);

    /// Default badge shape.
    pub const SHAPE: Shape = Shape::capsule();

    /// Horizontal padding for badges with content.
    pub const WITH_CONTENT_HORIZONTAL_PADDING: Dp = Dp(4.0);

    /// Horizontal offset for badges with content relative to the anchor.
    pub const WITH_CONTENT_HORIZONTAL_OFFSET: Dp = Dp(12.0);
    /// Vertical offset for badges with content relative to the anchor.
    pub const WITH_CONTENT_VERTICAL_OFFSET: Dp = Dp(14.0);

    /// Offset for badges without content relative to the anchor.
    pub const OFFSET: Dp = Dp(6.0);

    /// Default container color for a badge.
    pub fn container_color() -> Color {
        use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme
            .error
    }
}

/// Arguments for [`badge`] and [`badge_with_content`].
#[derive(Clone, Debug, Setters)]
pub struct BadgeArgs {
    /// Background color of the badge.
    pub container_color: Color,
    /// Preferred content color for badge descendants.
    ///
    /// When `None`, the badge derives a matching content color from the theme.
    #[setters(strip_option)]
    pub content_color: Option<Color>,
}

impl Default for BadgeArgs {
    fn default() -> Self {
        Self {
            container_color: BadgeDefaults::container_color(),
            content_color: None,
        }
    }
}

/// # badged_box
///
/// Positions a badge relative to an anchor element.
///
/// ## Usage
///
/// Display counts or status indicators on top of icons in navigation or
/// toolbars.
///
/// ## Parameters
///
/// - `badge` — draws the badge content, typically [`badge`] or
///   [`badge_with_content`].
/// - `content` — draws the anchor the badge should be positioned against.
///
/// ## Examples
///
/// ```
/// use tessera_components::badge::BadgeDefaults;
/// use tessera_ui::Dp;
/// assert_eq!(BadgeDefaults::OFFSET, Dp(6.0));
/// ```
#[tessera]
pub fn badged_box<F1, F2>(badge: F1, content: F2)
where
    F1: FnOnce() + Send + Sync + 'static,
    F2: FnOnce() + Send + Sync + 'static,
{
    layout(BadgedBoxLayout);

    content();
    badge();
}

/// # badge
///
/// Renders an icon-only badge.
///
/// ## Usage
///
/// Mark an icon as having new activity without showing a numeric count.
///
/// ## Parameters
///
/// - `args` — configures badge colors; see [`BadgeArgs`].
///
/// ## Examples
///
/// ```
/// use tessera_components::badge::BadgeArgs;
/// use tessera_ui::Color;
///
/// let args = BadgeArgs {
///     container_color: Color::RED,
///     content_color: None,
/// }
/// .content_color(Color::WHITE);
/// assert_eq!(args.content_color, Some(Color::WHITE));
/// ```
#[tessera]
pub fn badge(args: impl Into<BadgeArgs>) {
    let args: BadgeArgs = args.into();
    let container_color = args.container_color;

    layout(BadgeLayout { container_color });
}

/// # badge_with_content
///
/// Renders a badge that contains short content, such as a number.
///
/// ## Usage
///
/// Display compact counts (for example, unread messages) on top of navigation
/// icons.
///
/// ## Parameters
///
/// - `args` — configures badge colors; see [`BadgeArgs`].
/// - `content` — adds children inside the badge using a [`RowScope`].
///
/// ## Examples
///
/// ```
/// use tessera_components::badge::BadgeArgs;
/// use tessera_ui::Color;
///
/// let args = BadgeArgs {
///     container_color: Color::RED,
///     content_color: None,
/// }
/// .content_color(Color::WHITE);
/// assert_eq!(args.container_color, Color::RED);
/// ```
#[tessera]
pub fn badge_with_content<F>(args: impl Into<BadgeArgs>, content: F)
where
    F: FnOnce(&mut RowScope),
{
    let args: BadgeArgs = args.into();
    let theme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get();
    let scheme = theme.color_scheme;
    let typography = theme.typography;

    let container_color = args.container_color;
    let content_color = args.content_color.unwrap_or_else(|| {
        content_color_for(container_color, &scheme).unwrap_or(
            use_context::<ContentColor>()
                .map(|c| c.get().current)
                .unwrap_or(ContentColor::default().current),
        )
    });

    let padding_px = BadgeDefaults::WITH_CONTENT_HORIZONTAL_PADDING.to_px();
    layout(BadgeWithContentLayout {
        container_color,
        padding_px,
    });

    provide_context(
        || ContentColor {
            current: content_color,
        },
        || {
            provide_text_style(typography.label_small, || {
                row(
                    RowArgs::default()
                        .main_axis_alignment(MainAxisAlignment::Center)
                        .cross_axis_alignment(CrossAxisAlignment::Center),
                    content,
                );
            });
        },
    );
}