urushi 0.1.1

Composable styling, components, and terminal rendering for Rust CLIs
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! The arithmetic resolution is made of: how large a box is, before anything
//! is drawn.
//!
//! Every function here maps sizes to sizes. None of them touches a [`View`], so
//! none can walk a tree, and the rules of `docs/design/box-sizing.md` and
//! `docs/design/area-sharing.md` can be checked on their own. The phases that
//! apply them to a tree are [`width`](super::width) and
//! [`height`](super::height); the rectangle they describe is built in
//! [`assemble`](super::assemble).
//!
//! [`View`]: crate::View

use std::num::NonZeroU16;

use crate::text::{PrintableLines, PrintableText};
use crate::{BlockStyle, Length, Sides};

use super::geometry::{Constraint, Size};

/// Returns the smaller of two optional bounds, or whichever one exists.
pub(super) fn tighter(left: Option<usize>, right: Option<usize>) -> Option<usize> {
    match (left, right) {
        (Some(left), Some(right)) => Some(left.min(right)),
        (bound, None) | (None, bound) => bound,
    }
}

/// Applies the clamp the sizing model defines: a base size, capped by the
/// tighter of the maximum and the area, then floored — the floor wins.
pub(super) fn clamp_size(base: usize, cap: Option<usize>, floor: usize) -> usize {
    cap.map_or(base, |cap| base.min(cap)).max(floor)
}

/// One axis of a box, as its style states it.
///
/// The style fixes the frame and the bounds; the content supplies the extents
/// they are clamped against. Both axes use the same rule — they differ only
/// in what they pass as those extents, which is where the model's asymmetry
/// lives rather than in two separate formulas.
#[derive(Debug, Clone, Copy)]
pub(super) struct Axis {
    /// Enabled border edges plus padding on this axis, after degradation.
    pub frame: usize,
    pub length: Option<Length>,
    pub min: Option<u16>,
    pub max: Option<u16>,
}

impl Axis {
    /// The outer size this axis resolves to under `area`.
    ///
    /// `intrinsic` is the content's extent when nothing bounds it, and
    /// `min_content` the extent below which the content cannot go. The width
    /// axis passes the widest unsplittable grapheme as `min_content`; the
    /// height axis passes zero, because a row can simply be absent.
    pub fn used(&self, constraint: Constraint, intrinsic: usize, min_content: usize) -> usize {
        let base = match self.length {
            Some(Length::Cells(cells)) => usize::from(cells),
            // A Fill length needs an area to divide; with none it contributes
            // the intrinsic size.
            Some(Length::Fill(_)) => constraint.reference.unwrap_or(self.frame + intrinsic),
            None => self.frame + intrinsic,
        };
        clamp_size(
            base,
            tighter(self.max.map(usize::from), constraint.cap),
            self.min
                .map_or(0, usize::from)
                .max(self.frame + min_content),
        )
    }

    /// The bound the content is laid out under, before its own extent is
    /// known: the tightest of a stated size, the maximum, and the area.
    pub fn content_constraint(&self, constraint: Constraint) -> Constraint {
        let stated = match self.length {
            Some(Length::Cells(cells)) => Some(usize::from(cells)),
            Some(Length::Fill(_)) => constraint.reference,
            None => None,
        };
        let local = tighter(stated, self.max.map(usize::from));
        Constraint {
            reference: tighter(local, constraint.reference)
                .map(|bound| bound.saturating_sub(self.frame)),
            cap: tighter(local, constraint.cap).map(|bound| bound.saturating_sub(self.frame)),
        }
    }
}

/// How a child claims space on its container's main axis.
///
/// The three kinds are the distribution rule's three cases, and their order in
/// this enum is also the order a deficit shrinks them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
    /// A weighted share of whatever the other children leave.
    Fill(NonZeroU16),
    /// No stated length: the intrinsic size.
    Auto,
    /// A stated size in cells.
    Cells,
}

impl Kind {
    pub(crate) const fn fill(weight: u16) -> Self {
        match NonZeroU16::new(weight) {
            Some(weight) => Self::Fill(weight),
            None => panic!("internal fill weight must be greater than zero"),
        }
    }
}

/// One child's claim on its container's main axis.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Claim {
    pub kind: Kind,
    /// The size the child asks for. A `Fill` child's is decided by
    /// [`distribute`], so its value here is unused.
    pub demand: usize,
    /// The size below which this child cannot be shrunk.
    pub floor: usize,
}

/// Divides `area` among the children that claim it.
///
/// Stated and intrinsic children take their demand; `Fill` children divide
/// what remains in proportion to their weights. When the claims exceed the
/// area, they shrink in the order `Fill`, then auto, then `Cells` —
/// proportionally to their current size within each group, each floored at its
/// own floor, and a floor that binds freezes that child so the shortfall falls
/// on the rest. That freeze loop is an iteration over numbers, settled here
/// before any child is assembled.
///
/// The returned sizes sum to `area` unless a floor prevented it, in which case
/// the container resolves larger than its area and the degenerate safety net
/// is what finally bounds it.
pub(crate) fn distribute(area: usize, claims: &[Claim]) -> Vec<usize> {
    distribute_constraints(Some(area), Some(area), claims)
}

/// Divides a finite reference among area-dependent claims, shrinking only
/// when a content cap exists.
pub(super) fn distribute_constraints(
    reference: Option<usize>,
    cap: Option<usize>,
    claims: &[Claim],
) -> Vec<usize> {
    let Some(reference) = reference else {
        return claims
            .iter()
            .map(|claim| claim.demand.max(claim.floor))
            .collect();
    };
    let stated: usize = claims
        .iter()
        .filter(|claim| !matches!(claim.kind, Kind::Fill(_)))
        .map(|claim| claim.demand)
        .sum();
    let weights: usize = claims.iter().map(|claim| claim.weight()).sum();
    let remaining = reference.saturating_sub(stated);

    // Shares are cut from a running prefix of the remainder, so they sum to it
    // exactly: three equal weights over ten cells are 3, 3, 4, not 3, 3, 3
    // with a cell lost to rounding.
    let mut assigned = Vec::with_capacity(claims.len());
    let (mut weighted, mut given) = (0, 0);
    for claim in claims {
        assigned.push(match claim.kind {
            Kind::Fill(_) => {
                weighted += claim.weight();
                let upto = remaining
                    .saturating_mul(weighted)
                    .checked_div(weights)
                    .unwrap_or(0);
                let share = upto - given;
                given = upto;
                // A share below the child's own floor is not a share it can
                // take; the deficit pass below settles the shortfall.
                share.max(claim.floor)
            }
            _ => claim.demand,
        });
    }

    let Some(cap) = cap else {
        return assigned;
    };
    let mut excess = assigned.iter().sum::<usize>().saturating_sub(cap);
    for group in [Kind::fill(1), Kind::Auto, Kind::Cells] {
        if excess == 0 {
            break;
        }
        excess = shrink(&mut assigned, claims, group, excess);
    }
    assigned
}

impl Claim {
    const fn weight(&self) -> usize {
        match self.kind {
            Kind::Fill(weight) => weight.get() as usize,
            _ => 0,
        }
    }
}

/// Takes `excess` cells from one group, proportionally, and returns what it
/// could not take because every member sat on its floor.
fn shrink(assigned: &mut [usize], claims: &[Claim], group: Kind, mut excess: usize) -> usize {
    let holds = |kind: Kind| match group {
        Kind::Fill(_) => matches!(kind, Kind::Fill(_)),
        other => kind == other,
    };
    while excess > 0 {
        let active: Vec<usize> = (0..claims.len())
            .filter(|&index| holds(claims[index].kind) && assigned[index] > claims[index].floor)
            .collect();
        let total: usize = active.iter().map(|&index| assigned[index]).sum();
        if total == 0 {
            break;
        }
        let mut removed = 0;
        for &index in &active {
            if removed == excess {
                break;
            }
            // Rounding up keeps every pass making progress, and the remaining
            // excess caps what the last children give.
            let cut = (excess * assigned[index])
                .div_ceil(total)
                .min(excess - removed)
                .min(assigned[index] - claims[index].floor);
            assigned[index] -= cut;
            removed += cut;
        }
        if removed == 0 {
            break;
        }
        excess -= removed;
    }
    excess
}

pub(super) const fn kind_of(length: Option<Length>) -> Kind {
    match length {
        Some(Length::Fill(weight)) => Kind::Fill(weight),
        Some(Length::Cells(_)) => Kind::Cells,
        None => Kind::Auto,
    }
}

/// Which parts of the frame an area forces away, on one axis.
///
/// Margin collapses first, then padding, and only by what the area cannot
/// hold. Below that the content gives way, and only an area that cannot hold
/// the frame itself reaches the safety net.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Degraded {
    pub margin: bool,
    pub padding: bool,
}

/// Decides that degradation for one axis.
pub(super) fn degrade(
    area: Option<usize>,
    margin: usize,
    border: usize,
    padding: usize,
    min_content: usize,
) -> Degraded {
    let Some(area) = area else {
        return Degraded {
            margin: false,
            padding: false,
        };
    };
    if margin + border + padding + min_content <= area {
        return Degraded {
            margin: false,
            padding: false,
        };
    }
    Degraded {
        margin: true,
        padding: border + padding + min_content > area,
    }
}

/// The cells the enabled border edges contribute, per axis.
pub(super) fn border_extent(style: &BlockStyle) -> Size {
    match style.get_border() {
        Some(_) => Size::new(
            usize::from(style.get_border_left()) + usize::from(style.get_border_right()),
            usize::from(style.get_border_top()) + usize::from(style.get_border_bottom()),
        ),
        None => Size::ZERO,
    }
}

pub(super) const fn horizontal(sides: Sides) -> usize {
    sides.left as usize + sides.right as usize
}

pub(super) const fn vertical(sides: Sides) -> usize {
    sides.top as usize + sides.bottom as usize
}

/// The width axis a block's style states, for a frame of `frame` cells.
pub(super) fn width_axis(style: &BlockStyle, frame: usize) -> Axis {
    Axis {
        frame,
        length: style.get_width(),
        min: style.get_min_width(),
        max: style.get_max_width(),
    }
}

/// The height axis a block's style states, for a frame of `frame` cells.
pub(super) fn height_axis(style: &BlockStyle, frame: usize) -> Axis {
    Axis {
        frame,
        length: style.get_height(),
        min: style.get_min_height(),
        max: style.get_max_height(),
    }
}

/// Splits a view's text into lines, keeping one empty line for empty text so a
/// box always has a content row to place.
///
/// The argument is plain text: a [`View::Text`] node never holds escape
/// sequences, which is what lets the layout pass measure without scanning.
pub(super) fn text_lines(text: &str) -> Vec<&PrintableText> {
    PrintableLines::new(text).lines()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Border;

    #[test]
    fn the_floor_wins_over_the_cap() {
        assert_eq!(clamp_size(10, Some(4), 0), 4, "the cap binds");
        assert_eq!(clamp_size(2, Some(4), 0), 2, "neither binds");
        assert_eq!(clamp_size(2, None, 6), 6, "the floor binds");
        assert_eq!(clamp_size(10, Some(4), 6), 6, "the floor beats the cap");
    }

    #[test]
    fn the_tighter_bound_wins_and_an_absent_one_never_binds() {
        assert_eq!(tighter(Some(4), Some(9)), Some(4));
        assert_eq!(tighter(Some(9), Some(4)), Some(4));
        assert_eq!(tighter(Some(4), None), Some(4));
        assert_eq!(tighter(None, Some(4)), Some(4));
        assert_eq!(tighter(None, None), None);
    }

    #[test]
    fn an_axis_sizes_from_the_content_when_no_length_is_stated() {
        let axis = Axis {
            frame: 2,
            length: None,
            min: None,
            max: None,
        };

        assert_eq!(
            axis.used(Constraint::unbounded(), 5, 1),
            7,
            "the frame is inside the size"
        );
        assert_eq!(
            axis.used(Constraint::available(Some(4)), 5, 1),
            4,
            "the area caps it"
        );
        assert_eq!(
            axis.used(Constraint::available(Some(9)), 5, 1),
            7,
            "a wider area does not pad it"
        );
    }

    #[test]
    fn a_stated_length_is_the_base_the_bounds_clamp() {
        let axis = |length, min, max| Axis {
            frame: 0,
            length,
            min,
            max,
        };

        assert_eq!(
            axis(Some(Length::Cells(6)), None, None).used(Constraint::unbounded(), 2, 0),
            6,
            "a stated size ignores the content"
        );
        assert_eq!(
            axis(Some(Length::Cells(6)), None, Some(4)).used(Constraint::unbounded(), 2, 0),
            4,
            "the maximum caps the stated size"
        );
        assert_eq!(
            axis(Some(Length::Cells(6)), Some(8), None).used(Constraint::unbounded(), 2, 0),
            8,
            "the minimum floors it"
        );
        assert_eq!(
            axis(None, None, Some(4)).used(Constraint::available(Some(9)), 2, 0),
            2,
            "a maximum alone is shrink-to-fit with a cap"
        );
    }

    #[test]
    fn a_fill_length_takes_the_area_and_falls_back_to_the_content() {
        let axis = Axis {
            frame: 2,
            length: Some(Length::fill(1)),
            min: None,
            max: None,
        };

        assert_eq!(
            axis.used(Constraint::available(Some(10)), 3, 1),
            10,
            "it spans the area"
        );
        assert_eq!(
            axis.used(Constraint::unbounded(), 3, 1),
            5,
            "with no area it contributes the intrinsic size"
        );
    }

    #[test]
    fn the_content_floor_is_the_axis_asymmetry() {
        let axis = Axis {
            frame: 2,
            length: Some(Length::Cells(1)),
            min: None,
            max: None,
        };

        // Width passes the widest unsplittable grapheme, so the box cannot
        // reach the stated size.
        assert_eq!(axis.used(Constraint::available(Some(1)), 4, 2), 4);
        // Height passes zero, so it can: the frame alone is a valid box.
        assert_eq!(axis.used(Constraint::available(Some(1)), 4, 0), 2);
    }

    #[test]
    fn the_content_bound_is_the_tightest_of_the_size_the_maximum_and_the_area() {
        let axis = |length, max| Axis {
            frame: 2,
            length,
            min: None,
            max,
        };

        assert_eq!(
            axis(None, None).content_constraint(Constraint::unbounded()),
            Constraint::unbounded(),
            "nothing bounds"
        );
        assert_eq!(
            axis(None, None).content_constraint(Constraint::available(Some(9))),
            Constraint::available(Some(7))
        );
        assert_eq!(
            axis(Some(Length::Cells(5)), None).content_constraint(Constraint::unbounded()),
            Constraint::available(Some(3))
        );
        assert_eq!(
            axis(Some(Length::Cells(5)), Some(4))
                .content_constraint(Constraint::available(Some(9))),
            Constraint::available(Some(2)),
            "the maximum is tighter than the stated size"
        );
        assert_eq!(
            axis(Some(Length::fill(1)), None).content_constraint(Constraint::available(Some(6))),
            Constraint::available(Some(4)),
            "a Fill length is bounded by the area it fills"
        );
        assert_eq!(
            axis(Some(Length::Cells(1)), None).content_constraint(Constraint::unbounded()),
            Constraint::available(Some(0)),
            "a size below the frame leaves no content, not a negative one"
        );
    }

    #[test]
    fn degradation_collapses_margin_before_padding_and_only_under_pressure() {
        // 2 margin + 2 border + 2 padding + 1 content = 7.
        let at = |area| degrade(area, 2, 2, 2, 1);

        assert_eq!(
            at(None),
            Degraded {
                margin: false,
                padding: false
            },
            "an unbounded axis never degrades"
        );
        assert_eq!(
            at(Some(7)),
            Degraded {
                margin: false,
                padding: false
            },
            "exactly enough is enough"
        );
        assert_eq!(
            at(Some(6)),
            Degraded {
                margin: true,
                padding: false
            },
            "the margin goes first"
        );
        assert_eq!(
            at(Some(5)),
            Degraded {
                margin: true,
                padding: false
            },
            "the box itself still fits"
        );
        assert_eq!(
            at(Some(4)),
            Degraded {
                margin: true,
                padding: true
            },
            "then the padding"
        );
        assert_eq!(
            at(Some(1)),
            Degraded {
                margin: true,
                padding: true
            },
            "below that the content and the safety net take over"
        );
    }

    fn claim(kind: Kind, demand: usize, floor: usize) -> Claim {
        Claim {
            kind,
            demand,
            floor,
        }
    }

    #[test]
    fn fill_children_divide_what_the_others_leave() {
        let stated = claim(Kind::Cells, 6, 0);
        let auto = claim(Kind::Auto, 4, 0);
        let fill = |weight| claim(Kind::fill(weight), 0, 0);

        assert_eq!(distribute(20, &[stated, fill(1)]), vec![6, 14]);
        assert_eq!(distribute(20, &[stated, auto, fill(1)]), vec![6, 4, 10]);
        assert_eq!(distribute(10, &[fill(1), fill(1)]), vec![5, 5]);
        assert_eq!(distribute(9, &[fill(1), fill(2)]), vec![3, 6]);
    }

    #[test]
    fn a_share_never_loses_a_cell_to_rounding() {
        let fill = claim(Kind::fill(1), 0, 0);

        // Three equal weights over ten cells: the odd cell goes to the last,
        // and the shares still sum to the area.
        assert_eq!(distribute(10, &[fill, fill, fill]), vec![3, 3, 4]);
        for area in 0..40 {
            let shares = distribute(area, &[fill, fill, fill]);
            assert_eq!(shares.iter().sum::<usize>(), area, "at {area}");
        }
    }

    #[test]
    fn nothing_is_redistributed_when_a_child_leaves_slack() {
        // A capped Fill child is capped by its own clamp, not by distribution:
        // the share is handed over whole and the remainder simply goes unused.
        assert_eq!(
            distribute(20, &[claim(Kind::fill(1), 0, 0), claim(Kind::Cells, 4, 0)]),
            vec![16, 4]
        );
    }

    #[test]
    fn a_deficit_shrinks_fill_then_auto_then_stated() {
        let claims = [
            claim(Kind::Cells, 6, 3),
            claim(Kind::Auto, 6, 3),
            claim(Kind::fill(1), 0, 3),
        ];

        assert_eq!(distribute(16, &claims), vec![6, 6, 4], "no deficit at all");
        // The Fill child is already at its floor, so the automatic child gives
        // way next, and the stated one only once that floor binds too.
        assert_eq!(distribute(14, &claims), vec![6, 5, 3]);
        assert_eq!(distribute(12, &claims), vec![6, 3, 3]);
        assert_eq!(distribute(10, &claims), vec![4, 3, 3]);
        // Below the sum of the floors every child is frozen and the container
        // resolves larger than its area, where the safety net takes over.
        assert_eq!(distribute(4, &claims), vec![3, 3, 3]);
    }

    #[test]
    fn a_deficit_within_one_group_is_proportional_and_freezes_at_a_floor() {
        let claims = [claim(Kind::Auto, 12, 0), claim(Kind::Auto, 4, 3)];

        // Twice the size gives twice the cells, until the smaller child hits
        // its floor and the rest of the shortfall falls on the larger one.
        assert_eq!(distribute(12, &claims), vec![9, 3]);
        assert_eq!(distribute(8, &claims), vec![5, 3]);
    }

    #[test]
    fn border_extent_counts_only_enabled_edges_of_a_present_border() {
        assert_eq!(border_extent(&BlockStyle::new()), Size::ZERO);

        let full = BlockStyle::new().border(Border::NORMAL);
        assert_eq!(border_extent(&full), Size::new(2, 2));

        let sides = full.clone().border_top(false).border_left(false);
        assert_eq!(border_extent(&sides), Size::new(1, 1));

        let none = BlockStyle::new()
            .border(Border::NORMAL)
            .border_top(false)
            .border_right(false)
            .border_bottom(false)
            .border_left(false);
        assert_eq!(border_extent(&none), Size::ZERO);
    }
}