makeover-layout 0.52.1

The renderer-agnostic half of the make-family design system: what a thing IS, named as intents and relationships and never as values. Colour defers to makeover, spacing to makeover-geometry; what is left is composition, plus which affordances exist at a given input class and window size.
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
// Names this module's prose links to, resolved for rustdoc.
#[allow(unused_imports)]
use crate::{FieldKind, Fill, Region, RowPart};

/// How much room a placement asks for.
///
/// A column says it, and so does a form field. An intent, so the actual floor
/// stays with `makeover-geometry`. goingson's task table spells these as
/// `minmax(200px, 1fr)`, `140px` and content-sized; only the first three words
/// of that survive deferral.
/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
/// renderer matches on this and a vocabulary that grows must not break every
/// renderer when it does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Width {
    /// Takes what it needs and no more.
    Content,
    /// A fixed share, the same at every width.
    Fixed,
    /// Absorbs whatever is left over.
    ///
    /// **Several fills divide what is left equally.** Stated because it would
    /// otherwise be undefined and each renderer would invent something, and
    /// stated this way because equal division is the only sharing rule that
    /// answers to "Any width, one answer" without a tiebreak: allocating in
    /// declaration order makes the result depend on the order the description
    /// was written in, which is a fact about the source file and not about the
    /// screen. It documents what both renderers already do (CSS grid gives
    /// `1fr 1fr`, ratatui gives each a `Constraint::Fill(1)`) rather than
    /// changing anything.
    ///
    /// So a row of fills is a legal thing to describe, and there is no rule
    /// against it.
    Fill,
}

/// What a member is worth when there is not room for all of them.
///
/// Written for table columns and no longer only theirs. Three shapes ask the
/// same question and this answers all three: a table too narrow for its
/// columns, a row too narrow for its parts (see [`RowPart::priority`]), and a
/// group of regions sharing one run of room, goingson's tab strip and the
/// [`Region::Band`] beside it, which is the case wiki `layout-room-and-fallback`
/// was ruled on. It is what any member of a group is worth, not a table
/// concept, and [`Fallback::Shed`] is what reads it.
///
/// The doc below is the column argument, which is where the type was measured;
/// the sentence that gave it away is [`Priority::Essential`]'s, which was
/// already written about a row.
///
/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
/// drops. This replaces addressing columns by position, which is what both
/// webview apps do today and is a live bug rather than only verbosity. goingson
/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
/// inserting a column silently hides the wrong one.
/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
/// whole point of the type, so a new tier has to be declared in its place in
/// the sequence rather than appended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Priority {
    /// Dropped first.
    Optional,
    /// Dropped once the optional members are gone.
    Secondary,
    /// Never dropped. Without it the group does not identify itself.
    Essential,
}

impl Priority {
    /// Every cutoff, weakest first: the order a narrowing renderer raises
    /// through.
    ///
    /// The one list of tiers. A renderer walks this rather than writing its
    /// own, so a tier added here is one every renderer narrows to.
    pub const RAISING: &'static [Self] = &[Self::Optional, Self::Secondary, Self::Essential];
}

/// What the columns kept at a cutoff ask for.
///
/// Counted in `ch` and in columns, and never in a host's unit: each renderer
/// turns it into its own with [`Budget::width`], which is the one gap model
/// every native renderer budgets by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct Budget {
    /// How many columns are kept.
    pub columns: u32,
    /// Their [`floor`](ColumnRoom::floor)s, summed, in `ch`.
    pub floors: u32,
}

impl Budget {
    /// The width these columns need, at `ch` per `ch` and `gap` between
    /// adjacent columns and at each edge.
    ///
    /// `floors * ch + gap * (columns + 1)`. A terminal passes one cell per `ch`
    /// and its column spacing; an immediate-mode painter passes the width of a
    /// figure and its cell padding on both sides. One formula, so a table
    /// drops a column at the same declared width in both.
    #[must_use]
    pub fn width(self, ch: f32, gap: f32) -> f32 {
        self.floors as f32 * ch + gap * (self.columns + 1) as f32
    }
}

/// The lengths a description deferred, in a renderer's own unit.
///
/// [`Width`] says `Content`, `Fixed` or `Fill` and carries no magnitude,
/// because a magnitude is an answer for one renderer. Each renderer holds this
/// over its own unit (cells, points, CSS lengths) and looks a column up by
/// name, because an app's columns are not all one size.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct Sizing<'a, L> {
    /// `(column name, length)`: the track for a [`Width::Fixed`] column and the
    /// floor for a [`Width::Fill`] one.
    pub lengths: &'a [(&'a str, L)],
    /// Used for a column with no entry above.
    pub fallback: L,
}

impl<'a, L: Copy> Sizing<'a, L> {
    /// These lengths, and `fallback` for a column not among them.
    #[must_use]
    pub const fn new(lengths: &'a [(&'a str, L)], fallback: L) -> Self {
        Self { lengths, fallback }
    }

    /// The length for a named column.
    #[must_use]
    pub fn length_for(&self, name: &str) -> L {
        self.lengths
            .iter()
            .find(|(column, _)| *column == name)
            .map_or(self.fallback, |(_, length)| *length)
    }
}

/// What a group does when it runs out of room.
///
/// Authored, and required: the field carrying this has no `Default` and a group
/// cannot be described without saying what it does when it runs out of room.
/// More intentionality from layout designers is acceptable so long as the constraints are solvable, because the goal is
/// enabling good layouts rather than rescuing bad ones. A default here would be
/// the crate guessing, and the guess would be silently wrong on the screens
/// that matter.
///
/// Relief resolves inside-out. A group asks its children to fall back before
/// falling back itself, or an outer group collapses while an inner one still
/// had slack.
///
/// # No `Swap`
///
/// An authored alternate group for the tight case is deliberately out of the
/// first cut. It doubles the description for that group and the two halves can
/// drift, which is the failure this vocabulary exists to end. Add it when a
/// site proves it needs one.
///
/// `#[non_exhaustive]`, [`Width`]'s reasoning. Unlike [`Priority`] there is no
/// order to preserve, so a member can be appended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Fallback {
    /// One row becomes two. Every member stays, in the order described.
    Wrap,
    /// A row becomes a column. Every member stays, full width.
    Stack,
    /// Members drop by [`Priority`], down to [`Priority::Essential`].
    ///
    /// What a narrow table already does with its columns, applied to a group.
    /// What drops is gone from the screen, so this is right when the dropped
    /// members are facts the reader can do without and wrong when they are the
    /// only way to act.
    Shed,
    /// The members [`Shed`](Self::Shed) would drop move into one overflow
    /// control instead.
    ///
    /// The answer when a group holds actions. A control is not a fact: dropping
    /// it does not cost the reader a detail, it costs them the only way to act,
    /// which is [`RowPart::priority`]'s argument one level up.
    Menu,
}

/// The widest a column's [`floor`](ColumnRoom::floor) may be, in `ch`.
///
/// A bound so a webview can name every floor as a class from a fixed ladder:
/// a container condition cannot read a custom property, so the length a
/// column hides its contents under has to be written into the stylesheet.
/// Wider than any column the tree declares, and a column wanting more is a
/// [`Width::Fill`] with this as its floor.
pub const MIN_CEILING: u16 = 64;

/// The floor an undeclared [`Width::Fill`] column takes, in `ch`.
const FILL_FLOOR: u16 = 16;

/// The number of characters in a heading, for a `ch`-based floor.
///
/// `str::chars().count()` is not const and [`ColumnRoom::floor`] is, so this counts
/// UTF-8 code points by hand. `len()` counts bytes, which over-reserves a
/// multi-byte heading: a Cyrillic `Статус` reads as 12 `ch` rather than 6.
const fn char_len(s: &str) -> usize {
    let bytes = s.as_bytes();
    let mut chars = 0;
    let mut i = 0;
    while i < bytes.len() {
        chars += 1;
        let byte = bytes[i];
        i += if byte < 0x80 {
            1
        } else if byte < 0xE0 {
            2
        } else if byte < 0xF0 {
            3
        } else {
            4
        };
    }
    chars
}

/// What a column holds.
///
/// wiki `table-model`: the kind is what carries a column's look, and four of
/// the reference table's six rules were per kind rather than per table. A
/// description states what the column is; each renderer decides what that
/// looks like in its host, from the facts below rather than from the name.
///
/// `#[non_exhaustive]`, [`Width`]'s reasoning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum ColumnKind {
    /// Prose. Wraps. What a column is when it says nothing else.
    #[default]
    Text,
    /// A name a machine made: a fingerprint, a hash, a slug. Monospace, and
    /// breaks mid-string rather than widening the table.
    Identifier,
    /// A point in time. Never wraps, so a date cannot print over its
    /// neighbour, and its figures line up down the column.
    Date,
    /// A quantity. Figures line up and the column aligns to its end, so
    /// magnitudes compare by length.
    Number,
    /// Source text, one row per line. Monospace and never wrapped. A table
    /// holding one is read as code, so its rows are not striped or spaced as
    /// records.
    Code,
    /// A state the row is in, drawn as a chip rather than as coloured text.
    Status,
    /// The row's controls. Aligns to its end and shrinks to what it holds.
    Actions,
}

impl ColumnKind {
    /// The narrowest a column of this kind reads at, in `ch`, when it declares
    /// nothing narrower.
    ///
    /// A date is ten characters in the form every host writes, and a number
    /// cut short is a different number, so the kinds that cannot truncate
    /// floor at what they hold. Prose and identifiers wrap or break, so theirs
    /// is only enough to be recognisable.
    #[must_use]
    pub const fn floor(self) -> u16 {
        match self {
            Self::Text | Self::Code | Self::Status | Self::Actions => 8,
            Self::Identifier => 12,
            Self::Date => 10,
            Self::Number => 6,
        }
    }

    /// Whether the column aligns to its end rather than its start.
    #[must_use]
    pub const fn aligns_end(self) -> bool {
        matches!(self, Self::Number | Self::Actions)
    }

    /// Whether the column's text may wrap onto a second line.
    ///
    /// An identifier wraps by breaking mid-string, which is still a wrap: the
    /// alternative is a fingerprint forcing the table wider than its pane.
    #[must_use]
    pub const fn wraps(self) -> bool {
        matches!(self, Self::Text | Self::Identifier)
    }

    /// Whether the column is set in the monospace face.
    #[must_use]
    pub const fn monospace(self) -> bool {
        matches!(self, Self::Identifier | Self::Code)
    }

    /// Whether figures in the column take equal widths.
    #[must_use]
    pub const fn tabular(self) -> bool {
        matches!(self, Self::Date | Self::Number)
    }
}

/// Which way a column is ordered.
///
/// Two, because there is no third. "Unsorted" is a column with no direction
/// at all, and folding it in here would be the same absence said twice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Sort {
    /// Smallest, earliest or first alphabetically at the top.
    Ascending,
    /// The other way.
    Descending,
}

impl Sort {
    /// The other direction, for a header that flips when pressed.
    #[must_use]
    pub const fn reversed(self) -> Self {
        match self {
            Self::Ascending => Self::Descending,
            Self::Descending => Self::Ascending,
        }
    }

    /// What a webview writes into `aria-sort`.
    ///
    /// Named here rather than in the webview renderer because a terminal and an
    /// immediate-mode painter both want the same two words for a caret's label,
    /// and three renderers picking their own is the drift this crate ends.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Ascending => "ascending",
            Self::Descending => "descending",
        }
    }

    /// The caret a renderer draws for this direction.
    ///
    /// Here for [`as_str`](Self::as_str)'s reason, said about a glyph rather
    /// than a word: three renderers picking their own is the drift this crate
    /// ends. They had picked their own (two on the solid triangles and
    /// `makeover-webview` on the arrows U+2191/U+2193) and agreeing by
    /// coincidence in three files is not agreement.
    ///
    /// The reason generalizes past this pair and is the house rule now,
    /// prefer the bolder, simpler glyph over the thinner or more complicated
    /// one. A third spelling is not open for re-argument.
    ///
    /// **Bare, with no spacing.** Where the gap goes is each renderer's
    /// business: `makeover-tui` and `makeover-immediate` carry a leading space
    /// inside their `TableStyle` string and a webview emits its own in
    /// `content`, so folding a space in here would make one of the two wrong.
    ///
    /// Neither face the web apps self-host carries these (IBM Plex Mono has one
    /// glyph in the whole geometric-shapes block and Lato has none) so a
    /// browser falls back per glyph until the in-house face ships with them
    /// drawn in (wiki `typography-standard`). Cosmetic
    /// drift in one renderer, not a reason to spell it three ways.
    #[must_use]
    pub const fn glyph(self) -> &'static str {
        match self {
            Self::Ascending => "\u{25B2}",
            Self::Descending => "\u{25BC}",
        }
    }
}

/// What one column asks of the sizer: the room it needs and what it is worth.
///
/// A layout record and nothing else. It holds the heading only because the
/// heading is what a column must at least fit, and it says whether a sort caret
/// sits beside it for the same reason; what the column holds, how it is
/// ordered and what pressing it does are its describer's. Every renderer sizes
/// a table from these, so the floor and the cutoff are one rule on every host
/// whatever type the columns were described in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ColumnRoom<'a> {
    /// The heading the column must at least fit.
    pub heading: &'a str,
    /// How much room it asks for.
    pub width: Width,
    /// What it is worth when room runs out.
    pub priority: Priority,
    /// What it holds, which carries a floor of its own.
    pub kind: ColumnKind,
    /// The narrowest it may be before it drops, in `ch`, when declared.
    ///
    /// wiki `frontend-unification`: collapse points derive from declared
    /// minimums only, so every host narrows at the same declared width rather
    /// than at its own breakpoints. `ch` because every host has a direct
    /// answer for it: a terminal cell is one, an immediate-mode painter
    /// measures one off its face, and a webview draws one as nine sixteenths
    /// of the base, a figure at a table's text size with room to spare. Not
    /// the CSS `ch` itself, because a container condition resolves
    /// font-relative units against a different font than the cell's, and the
    /// column would hide at one width and be sized at another.
    ///
    /// `None` derives it from the kind and the heading, which is what most
    /// columns want. Read it through [`floor`](Self::floor), never directly:
    /// that is where the derivation, the rounding and the ceiling live, and a
    /// host reading this field would narrow somewhere the other two do not.
    pub min: Option<u16>,
    /// Whether a sort caret sits beside the heading: the column is sortable,
    /// or is the one the table is ordered by.
    pub caret: bool,
}

impl<'a> ColumnRoom<'a> {
    /// A text column under `heading` that fills and is essential, the defaults
    /// a column takes when it says nothing.
    #[must_use]
    pub const fn new(heading: &'a str) -> Self {
        Self {
            heading,
            width: Width::Fill,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            caret: false,
        }
    }

    /// The narrowest this column may be before it drops, in `ch`.
    ///
    /// What every host narrows by: a column is kept at a cutoff only while the
    /// floors of every column kept there fit. The declared [`min`](Self::min),
    /// or else the widest of the kind's [`floor`](ColumnKind::floor), the
    /// heading with two for its capitals and two more for a caret, and sixteen
    /// for a [`Width::Fill`] column. Rounded up to an even count and held under
    /// [`MIN_CEILING`], so a webview can carry the whole range as a fixed ladder
    /// of classes and the other two hosts round the same way.
    #[must_use]
    pub const fn floor(&self) -> u16 {
        let raw = match self.min {
            Some(ch) => ch,
            None => {
                let caret = if self.caret { 2 } else { 0 };
                // Characters, not bytes: `ch` is the width of a glyph, so a
                // multi-byte heading counted by `len()` over-reserves (`Статус`
                // reads as 12 ch rather than 6) and a non-Latin table drops
                // columns sooner than the same table in another locale. Two more
                // for the heading's capitals and tracking, which run wider than
                // the figures a `ch` is measured off: `AMOUNT` at six ch is cut.
                let chars = char_len(self.heading);
                let heading = if chars > MIN_CEILING as usize {
                    MIN_CEILING
                } else {
                    chars as u16 + 2 + caret
                };
                let kind = self.kind.floor();
                // A column that takes the slack is the one holding prose, and
                // floored at its kind it wraps a title onto three lines while
                // the columns worth less still stand at full width.
                let fill = if matches!(self.width, Width::Fill) {
                    FILL_FLOOR
                } else {
                    0
                };
                let wider = if heading > kind { heading } else { kind };
                if fill > wider { fill } else { wider }
            }
        };
        // Clamped before rounding, so a declared `min(u16::MAX)` cannot
        // overflow on its way to being held under the ceiling.
        let raw = if raw > MIN_CEILING { MIN_CEILING } else { raw };
        let even = raw + raw % 2;
        if even < 2 {
            2
        } else if even > MIN_CEILING {
            MIN_CEILING
        } else {
            even
        }
    }

    /// Whether this column is kept at `cutoff`.
    ///
    /// A renderer narrows by raising the cutoff, and never by counting
    /// positions.
    #[must_use]
    pub const fn kept_at(&self, cutoff: Priority) -> bool {
        (self.priority as u8) >= (cutoff as u8)
    }

    /// What the columns kept at `cutoff` ask for.
    #[must_use]
    pub fn budget(rooms: &[Self], cutoff: Priority) -> Budget {
        rooms
            .iter()
            .filter(|room| room.kept_at(cutoff))
            .fold(Budget::default(), |budget, room| Budget {
                columns: budget.columns + 1,
                floors: budget.floors + u32::from(room.floor()),
            })
    }

    /// The weakest cutoff whose kept columns `fits` accepts.
    ///
    /// Raised through [`Priority::RAISING`] until the columns fit, and never
    /// past the strongest priority any column declares: the essential columns
    /// are what makes a row identify itself, so a window too narrow for them
    /// gets them squeezed rather than dropped. A table with no essential column
    /// therefore never rises to [`Priority::Essential`], where the budget would
    /// keep no column at all. Nothing here counts positions, so which column
    /// drops is a property of the column.
    #[must_use]
    pub fn cutoff_for(rooms: &[Self], fits: impl Fn(Budget) -> bool) -> Priority {
        let strongest = rooms
            .iter()
            .map(|room| room.priority)
            .max()
            .unwrap_or(Priority::Essential);
        Priority::RAISING
            .iter()
            .copied()
            .take_while(|&cutoff| cutoff <= strongest)
            .find(|&cutoff| fits(Self::budget(rooms, cutoff)))
            .unwrap_or(strongest)
    }
}

/// What a table cell holds.
///
/// [`RowPart`] for tables, and it exists for the same reason: a part that
/// carries a control is not text, and a renderer with one class for the whole
/// cell paints it as though it were: a button in a cell inherits the cell's
/// content colour, which is the drift [`RowPart::intent`] prevents for rows.
///
/// Four members, and the count is what quasi's `Cell` was measured to carry: a
/// value, tokens, actions and a link. Nothing was added past what something
/// holds.
///
/// `#[non_exhaustive]` for [`RowPart`]'s reason: growth here must not be a
/// lockstep event across three renderers.
///
/// # No hover-reveal
///
/// This enum never gets one. A cell's actions are shown at rest in every
/// consumer measured, and a member nothing uses is one three renderers owe an
/// answer for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CellPart {
    /// The cell's own text.
    Value,
    /// Small labelled things in the cell: a status badge, a chip.
    Tokens,
    /// Controls that act on what the row is about.
    Actions,
    /// The cell's value, where the value is itself a link.
    Link,
}

impl CellPart {
    /// The content intent the part takes.
    ///
    /// One part is text and three are not, so three answer with the intent
    /// inheriting already gives. That is [`RowPart::intent`]'s shape with the
    /// text side narrower: a cell's secondary and muted readings are the
    /// column's business, not the cell's.
    #[must_use]
    pub const fn intent(self) -> &'static str {
        match self {
            Self::Value => "content",
            // A token carries its own tone, and a part-level intent underneath
            // it would fight the token sitting on it.
            Self::Tokens => "content",
            // Actions carry controls rather than text.
            Self::Actions => "content",
            // A link in a cell is its row's title, so it reads in the ink the
            // values beside it do.
            Self::Link => "content",
        }
    }
}