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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! A horizontal layout component.
//!
//! ## Usage
//!
//! Use to stack children horizontally.
use derive_setters::Setters;
use tessera_ui::{
    ComputedData, Constraint, DimensionValue, LayoutInput, LayoutOutput, LayoutSpec,
    MeasurementError, Modifier, NodeId, Px, PxPosition, tessera,
};

use crate::{
    alignment::{CrossAxisAlignment, MainAxisAlignment},
    modifier::ModifierExt as _,
};

/// Arguments for the `row` component.
#[derive(Clone, Debug, Setters)]
pub struct RowArgs {
    /// Modifier chain applied to the row subtree.
    pub modifier: Modifier,
    /// Main axis alignment (horizontal alignment).
    pub main_axis_alignment: MainAxisAlignment,
    /// Cross axis alignment (vertical alignment).
    pub cross_axis_alignment: CrossAxisAlignment,
}

impl Default for RowArgs {
    fn default() -> Self {
        Self {
            modifier: Modifier::new()
                .constrain(Some(DimensionValue::WRAP), Some(DimensionValue::WRAP)),
            main_axis_alignment: MainAxisAlignment::Start,
            cross_axis_alignment: CrossAxisAlignment::Start,
        }
    }
}

/// A scope for declaratively adding children to a `row` component.
pub struct RowScope<'a> {
    child_closures: &'a mut Vec<Box<dyn FnOnce() + Send + Sync>>,
    child_weights: &'a mut Vec<Option<f32>>,
}

impl<'a> RowScope<'a> {
    /// Adds a child component to the row.
    pub fn child<F>(&mut self, child_closure: F)
    where
        F: FnOnce() + Send + Sync + 'static,
    {
        self.child_closures.push(Box::new(child_closure));
        self.child_weights.push(None);
    }

    /// Adds a child component to the row with a specified weight for flexible
    /// space distribution.
    pub fn child_weighted<F>(&mut self, child_closure: F, weight: f32)
    where
        F: FnOnce() + Send + Sync + 'static,
    {
        self.child_closures.push(Box::new(child_closure));
        self.child_weights.push(Some(weight));
    }
}

struct PlaceChildrenArgs<'a> {
    children_sizes: &'a [Option<ComputedData>],
    children_ids: &'a [NodeId],
    final_row_width: Px,
    final_row_height: Px,
    total_children_width: Px,
    main_axis_alignment: MainAxisAlignment,
    cross_axis_alignment: CrossAxisAlignment,
    child_count: usize,
}

struct MeasureWeightedChildrenArgs<'a> {
    input: &'a LayoutInput<'a>,
    weighted_indices: &'a [usize],
    children_sizes: &'a mut [Option<ComputedData>],
    max_child_height: &'a mut Px,
    remaining_width: Px,
    total_weight: f32,
    row_effective_constraint: &'a Constraint,
    child_weights: &'a [Option<f32>],
}

#[derive(Clone, PartialEq)]
struct RowLayout {
    main_axis_alignment: MainAxisAlignment,
    cross_axis_alignment: CrossAxisAlignment,
    child_weights: Vec<Option<f32>>,
}

impl LayoutSpec for RowLayout {
    fn measure(
        &self,
        input: &LayoutInput<'_>,
        output: &mut LayoutOutput<'_>,
    ) -> Result<ComputedData, MeasurementError> {
        let n = self.child_weights.len();
        assert_eq!(
            input.children_ids().len(),
            n,
            "Mismatch between children defined in scope and runtime children count"
        );

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

        let has_weighted_children = self.child_weights.iter().any(|w| w.unwrap_or(0.0) > 0.0);
        let should_use_weight_for_width = has_weighted_children
            && matches!(
                row_effective_constraint.width,
                DimensionValue::Fixed(_)
                    | DimensionValue::Fill { max: Some(_), .. }
                    | DimensionValue::Wrap { max: Some(_), .. }
            );

        if should_use_weight_for_width {
            measure_weighted_row(
                input,
                output,
                self.main_axis_alignment,
                self.cross_axis_alignment,
                &self.child_weights,
                &row_effective_constraint,
            )
        } else {
            measure_unweighted_row(
                input,
                output,
                self.main_axis_alignment,
                self.cross_axis_alignment,
                &row_effective_constraint,
            )
        }
    }
}

/// # row
///
/// A layout component that arranges its children in a horizontal row.
///
/// ## Usage
///
/// Stack components horizontally, with options for alignment and flexible
/// spacing.
///
/// ## Parameters
///
/// - `args` — configures alignment and modifiers; see [`RowArgs`].
/// - `scope_config` — a closure that receives a [`RowScope`] for adding
///   children.
///
/// ## Examples
///
/// ```
/// use tessera_components::{
///     row::{RowArgs, row},
///     spacer::spacer,
///     text::{TextArgs, text},
/// };
/// use tessera_ui::Modifier;
///
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// row(RowArgs::default(), |scope| {
///     scope.child(|| text(TextArgs::default().text("First")));
///     scope.child_weighted(|| spacer(Modifier::new()), 1.0); // Flexible space
///     scope.child(|| text(TextArgs::default().text("Last")));
/// });
/// # }
/// # component();
/// ```
#[tessera]
pub fn row<F>(args: RowArgs, scope_config: F)
where
    F: FnOnce(&mut RowScope),
{
    let modifier = args.modifier;

    let mut child_closures: Vec<Box<dyn FnOnce() + Send + Sync>> = Vec::new();
    let mut child_weights: Vec<Option<f32>> = Vec::new();

    {
        let mut scope = RowScope {
            child_closures: &mut child_closures,
            child_weights: &mut child_weights,
        };
        scope_config(&mut scope);
    }

    modifier.run(move || row_inner(args, child_closures, child_weights));
}

#[tessera]
fn row_inner(
    args: RowArgs,
    child_closures: Vec<Box<dyn FnOnce() + Send + Sync>>,
    child_weights: Vec<Option<f32>>,
) {
    layout(RowLayout {
        main_axis_alignment: args.main_axis_alignment,
        cross_axis_alignment: args.cross_axis_alignment,
        child_weights,
    });

    for child_closure in child_closures {
        child_closure();
    }
}

fn measure_weighted_row(
    input: &LayoutInput<'_>,
    output: &mut LayoutOutput<'_>,
    main_axis_alignment: MainAxisAlignment,
    cross_axis_alignment: CrossAxisAlignment,
    child_weights: &[Option<f32>],
    row_effective_constraint: &Constraint,
) -> Result<ComputedData, MeasurementError> {
    // Prepare buffers and metadata for measurement:
    // - `children_sizes` stores each child's measurement result (width, height).
    // - `max_child_height` tracks the maximum height among children to compute the
    //   row's final height.
    // - `available_width_for_children` is the total width available to allocate to
    //   children under the current constraint (present only for
    //   Fill/Fixed/Wrap(max)).
    let mut children_sizes = vec![None; child_weights.len()];
    let mut max_child_height = Px(0);
    let available_width_for_children = row_effective_constraint
        .width
        .get_max()
        .expect("Row width Fill expected with finite max constraint");

    // Classify children into weighted and unweighted and compute the total weight.
    let (weighted_indices, unweighted_indices, total_weight) = classify_children(child_weights);

    let total_width_of_unweighted_children = measure_unweighted_children(
        input,
        &unweighted_indices,
        &mut children_sizes,
        &mut max_child_height,
        row_effective_constraint,
    )?;

    measure_weighted_children(&mut MeasureWeightedChildrenArgs {
        input,
        weighted_indices: &weighted_indices,
        children_sizes: &mut children_sizes,
        max_child_height: &mut max_child_height,
        remaining_width: available_width_for_children - total_width_of_unweighted_children,
        total_weight,
        row_effective_constraint,
        child_weights,
    })?;

    let final_row_width = available_width_for_children;
    let final_row_height = calculate_final_row_height(row_effective_constraint, max_child_height);

    let total_measured_children_width: Px = children_sizes
        .iter()
        .filter_map(|s| s.map(|s| s.width))
        .fold(Px(0), |acc, w| acc + w);

    place_children_with_alignment(
        &PlaceChildrenArgs {
            children_sizes: &children_sizes,
            children_ids: input.children_ids(),
            final_row_width,
            final_row_height,
            total_children_width: total_measured_children_width,
            main_axis_alignment,
            cross_axis_alignment,
            child_count: child_weights.len(),
        },
        output,
    );

    Ok(ComputedData {
        width: final_row_width,
        height: final_row_height,
    })
}

fn measure_unweighted_row(
    input: &LayoutInput<'_>,
    output: &mut LayoutOutput<'_>,
    main_axis_alignment: MainAxisAlignment,
    cross_axis_alignment: CrossAxisAlignment,
    row_effective_constraint: &Constraint,
) -> Result<ComputedData, MeasurementError> {
    let mut children_sizes = vec![None; input.children_ids().len()];
    let mut total_children_measured_width = Px(0);
    let mut max_child_height = Px(0);

    let parent_offered_constraint_for_child = Constraint::new(
        match row_effective_constraint.width {
            DimensionValue::Fixed(v) => DimensionValue::Wrap {
                min: None,
                max: Some(v),
            },
            DimensionValue::Fill { max, .. } => DimensionValue::Wrap { min: None, max },
            DimensionValue::Wrap { max, .. } => DimensionValue::Wrap { min: None, max },
        },
        row_effective_constraint.height,
    );

    let children_to_measure: Vec<_> = input
        .children_ids()
        .iter()
        .map(|&child_id| (child_id, parent_offered_constraint_for_child))
        .collect();

    let children_results = input.measure_children(children_to_measure)?;

    for (i, &child_id) in input.children_ids().iter().enumerate() {
        if let Some(child_result) = children_results.get(&child_id) {
            children_sizes[i] = Some(*child_result);
            total_children_measured_width += child_result.width;
            max_child_height = max_child_height.max(child_result.height);
        }
    }

    let final_row_width =
        calculate_final_row_width(row_effective_constraint, total_children_measured_width);
    let final_row_height = calculate_final_row_height(row_effective_constraint, max_child_height);

    place_children_with_alignment(
        &PlaceChildrenArgs {
            children_sizes: &children_sizes,
            children_ids: input.children_ids(),
            final_row_width,
            final_row_height,
            total_children_width: total_children_measured_width,
            main_axis_alignment,
            cross_axis_alignment,
            child_count: children_sizes.len(),
        },
        output,
    );

    Ok(ComputedData {
        width: final_row_width,
        height: final_row_height,
    })
}

fn classify_children(child_weights: &[Option<f32>]) -> (Vec<usize>, Vec<usize>, f32) {
    // Split children into weighted and unweighted categories and compute the total
    // weight of weighted children. Returns: (weighted_indices,
    // unweighted_indices, total_weight)
    let mut weighted_indices = Vec::new();
    let mut unweighted_indices = Vec::new();
    let mut total_weight = 0.0;

    for (i, weight) in child_weights.iter().enumerate() {
        if let Some(w) = weight {
            if *w > 0.0 {
                weighted_indices.push(i);
                total_weight += w;
            } else {
                // weight == 0.0 is treated as an unweighted item (it won't participate in
                // remaining-space allocation)
                unweighted_indices.push(i);
            }
        } else {
            unweighted_indices.push(i);
        }
    }
    (weighted_indices, unweighted_indices, total_weight)
}

fn measure_unweighted_children(
    input: &LayoutInput<'_>,
    unweighted_indices: &[usize],
    children_sizes: &mut [Option<ComputedData>],
    max_child_height: &mut Px,
    row_effective_constraint: &Constraint,
) -> Result<Px, MeasurementError> {
    let mut total_width = Px(0);

    let parent_offered_constraint_for_child = Constraint::new(
        DimensionValue::Wrap {
            min: None,
            max: row_effective_constraint.width.get_max(),
        },
        row_effective_constraint.height,
    );

    let children_to_measure: Vec<_> = unweighted_indices
        .iter()
        .map(|&child_idx| {
            (
                input.children_ids()[child_idx],
                parent_offered_constraint_for_child,
            )
        })
        .collect();

    let children_results = input.measure_children(children_to_measure)?;

    for &child_idx in unweighted_indices {
        let child_id = input.children_ids()[child_idx];
        if let Some(child_result) = children_results.get(&child_id) {
            children_sizes[child_idx] = Some(*child_result);
            total_width += child_result.width;
            *max_child_height = (*max_child_height).max(child_result.height);
        }
    }

    Ok(total_width)
}

fn measure_weighted_children(
    args: &mut MeasureWeightedChildrenArgs,
) -> Result<(), MeasurementError> {
    if args.total_weight <= 0.0 {
        return Ok(());
    }

    let children_to_measure: Vec<_> = args
        .weighted_indices
        .iter()
        .map(|&child_idx| {
            let child_weight = args.child_weights[child_idx].unwrap_or(0.0);
            let allocated_width =
                Px((args.remaining_width.0 as f32 * (child_weight / args.total_weight)) as i32);
            let child_id = args.input.children_ids()[child_idx];
            let parent_offered_constraint_for_child = Constraint::new(
                DimensionValue::Fixed(allocated_width),
                args.row_effective_constraint.height,
            );
            (child_id, parent_offered_constraint_for_child)
        })
        .collect();

    let children_results = args.input.measure_children(children_to_measure)?;

    for &child_idx in args.weighted_indices {
        let child_id = args.input.children_ids()[child_idx];
        if let Some(child_result) = children_results.get(&child_id) {
            args.children_sizes[child_idx] = Some(*child_result);
            *args.max_child_height = (*args.max_child_height).max(child_result.height);
        }
    }

    Ok(())
}

fn calculate_final_row_width(
    row_effective_constraint: &Constraint,
    total_children_measured_width: Px,
) -> Px {
    // Decide the final width based on the row's width constraint type:
    // - Fixed: use the fixed width
    // - Fill: try to occupy the parent's available maximum width (limited by min)
    // - Wrap: use the total width of children, limited by min/max constraints
    match row_effective_constraint.width {
        DimensionValue::Fixed(w) => w,
        DimensionValue::Fill { min, max } => {
            if let Some(max) = max {
                let w = max;
                if let Some(min) = min { w.max(min) } else { w }
            } else {
                panic!(
                    "Seem that you are using Fill without max constraint, which is not supported in Row width."
                );
            }
        }
        DimensionValue::Wrap { min, max } => {
            let mut w = total_children_measured_width;
            if let Some(min_w) = min {
                w = w.max(min_w);
            }
            if let Some(max_w) = max {
                w = w.min(max_w);
            }
            w
        }
    }
}

fn calculate_final_row_height(row_effective_constraint: &Constraint, max_child_height: Px) -> Px {
    // Calculate the final height based on the height constraint type:
    // - Fixed: use the fixed height
    // - Fill: use the maximum height available from the parent (limited by min)
    // - Wrap: use the maximum child height, limited by min/max
    match row_effective_constraint.height {
        DimensionValue::Fixed(h) => h,
        DimensionValue::Fill { min, max } => {
            if let Some(max_h) = max {
                let h = max_h;
                if let Some(min_h) = min {
                    h.max(min_h)
                } else {
                    h
                }
            } else {
                panic!(
                    "Seem that you are using Fill without max constraint, which is not supported in Row height."
                );
            }
        }
        DimensionValue::Wrap { min, max } => {
            let mut h = max_child_height;
            if let Some(min_h) = min {
                h = h.max(min_h);
            }
            if let Some(max_h) = max {
                h = h.min(max_h);
            }
            h
        }
    }
}

fn place_children_with_alignment(args: &PlaceChildrenArgs, output: &mut LayoutOutput<'_>) {
    // Compute the initial x and spacing between children according to the main axis
    // (horizontal), then iterate measured children:
    // - use calculate_cross_axis_offset to compute each child's offset on the cross
    //   axis (vertical)
    // - place each child with place_node at the computed coordinates
    let (mut current_x, spacing) = calculate_main_axis_layout(args);

    for (i, child_size_opt) in args.children_sizes.iter().enumerate() {
        if let Some(child_actual_size) = child_size_opt {
            let child_id = args.children_ids[i];
            let y_offset = calculate_cross_axis_offset(
                child_actual_size,
                args.final_row_height,
                args.cross_axis_alignment,
            );

            output.place_child(child_id, PxPosition::new(current_x, y_offset));
            current_x += child_actual_size.width;
            if i < args.child_count - 1 {
                current_x += spacing;
            }
        }
    }
}

fn calculate_main_axis_layout(args: &PlaceChildrenArgs) -> (Px, Px) {
    // Calculate the start position on the main axis and the spacing between
    // children: Returns (start_x, spacing_between_children)
    let available_space = (args.final_row_width - args.total_children_width).max(Px(0));
    match args.main_axis_alignment {
        MainAxisAlignment::Start => (Px(0), Px(0)),
        MainAxisAlignment::Center => (available_space / 2, Px(0)),
        MainAxisAlignment::End => (available_space, Px(0)),
        MainAxisAlignment::SpaceEvenly => calculate_space_evenly(available_space, args.child_count),
        MainAxisAlignment::SpaceBetween => {
            calculate_space_between(available_space, args.child_count)
        }
        MainAxisAlignment::SpaceAround => calculate_space_around(available_space, args.child_count),
    }
}

fn calculate_space_evenly(available_space: Px, child_count: usize) -> (Px, Px) {
    if child_count > 0 {
        let s = available_space / (child_count as i32 + 1);
        (s, s)
    } else {
        (Px(0), Px(0))
    }
}

fn calculate_space_between(available_space: Px, child_count: usize) -> (Px, Px) {
    if child_count > 1 {
        (Px(0), available_space / (child_count as i32 - 1))
    } else if child_count == 1 {
        (available_space / 2, Px(0))
    } else {
        (Px(0), Px(0))
    }
}

fn calculate_space_around(available_space: Px, child_count: usize) -> (Px, Px) {
    if child_count > 0 {
        let s = available_space / (child_count as i32);
        (s / 2, s)
    } else {
        (Px(0), Px(0))
    }
}

fn calculate_cross_axis_offset(
    child_actual_size: &ComputedData,
    final_row_height: Px,
    cross_axis_alignment: CrossAxisAlignment,
) -> Px {
    // Compute child's offset on the cross axis (vertical):
    // - Start: align to top (0)
    // - Center: center (remaining_height / 2)
    // - End: align to bottom (remaining_height)
    // - Stretch: no offset (the child will be stretched to fill height; stretching
    //   handled in measurement)
    match cross_axis_alignment {
        CrossAxisAlignment::Start => Px(0),
        CrossAxisAlignment::Center => (final_row_height - child_actual_size.height).max(Px(0)) / 2,
        CrossAxisAlignment::End => (final_row_height - child_actual_size.height).max(Px(0)),
        CrossAxisAlignment::Stretch => Px(0),
    }
}