Skip to main content

makeover_layout/
column.rs

1// Names this module's prose links to, resolved for rustdoc.
2#[allow(unused_imports)]
3use crate::{Field, FieldKind, Fill, Region, RowPart};
4
5/// How much room a placement asks for.
6///
7/// A column says it, and so does a [`Field`]. An intent, so the actual floor
8/// stays with `makeover-geometry`. goingson's task table spells these as
9/// `minmax(200px, 1fr)`, `140px` and content-sized; only the first three words
10/// of that survive deferral.
11/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
12/// renderer matches on this and a vocabulary that grows must not break every
13/// renderer when it does.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum Width {
17    /// Takes what it needs and no more.
18    Content,
19    /// A fixed share, the same at every width.
20    Fixed,
21    /// Absorbs whatever is left over.
22    ///
23    /// **Several fills divide what is left equally.** Stated because it would
24    /// otherwise be undefined and each renderer would invent something, and
25    /// stated this way because equal division is the only sharing rule that
26    /// answers to "Any width, one answer" without a tiebreak: allocating in
27    /// declaration order makes the result depend on the order the description
28    /// was written in, which is a fact about the source file and not about the
29    /// screen. It documents what both renderers already do — CSS grid gives
30    /// `1fr 1fr`, ratatui gives each a `Constraint::Fill(1)` — rather than
31    /// changing anything.
32    ///
33    /// So a row of fills is a legal thing to describe, and there is no rule
34    /// against it.
35    Fill,
36}
37
38/// What a member is worth when there is not room for all of them.
39///
40/// Written for table columns and no longer only theirs. Three shapes ask the
41/// same question and this answers all three: a table too narrow for its
42/// columns, a row too narrow for its parts (see [`RowPart::priority`]), and a
43/// group of regions sharing one run of room -- goingson's tab strip and the
44/// [`Region::Band`] beside it, which is the case wiki `layout-room-and-fallback`
45/// was ruled on. It is what any member of a group is worth, not a table
46/// concept, and [`Fallback::Shed`] is what reads it.
47///
48/// The doc below is the column argument, which is where the type was measured;
49/// the sentence that gave it away is [`Priority::Essential`]'s, which was
50/// already written about a row.
51///
52/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
53/// drops. This replaces addressing columns by position, which is what both
54/// webview apps do today and is a live bug rather than only verbosity. goingson
55/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
56/// inserting a column silently hides the wrong one.
57/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
58/// whole point of the type, so a new tier has to be declared in its place in
59/// the sequence rather than appended.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
61#[non_exhaustive]
62pub enum Priority {
63    /// Dropped first.
64    Optional,
65    /// Dropped once the optional members are gone.
66    Secondary,
67    /// Never dropped. Without it the group does not identify itself.
68    Essential,
69}
70
71/// What a group does when it runs out of room.
72///
73/// Authored, and required: the field carrying this has no `Default` and a group
74/// cannot be described without saying what it does when it runs out of room.
75/// Max ruled on that: more intentionality from layout designers is
76/// acceptable so long as the constraints are solvable, because the goal is
77/// enabling good layouts rather than rescuing bad ones. A default here would be
78/// the crate guessing, and the guess would be silently wrong on the screens
79/// that matter.
80///
81/// Relief resolves inside-out. A group asks its children to fall back before
82/// falling back itself, or an outer group collapses while an inner one still
83/// had slack.
84///
85/// # No `Swap`
86///
87/// An authored alternate group for the tight case is deliberately out of the
88/// first cut. It doubles the description for that group and the two halves can
89/// drift, which is the failure this vocabulary exists to end. Add it when a
90/// site proves it needs one.
91///
92/// `#[non_exhaustive]`, [`Width`]'s reasoning. Unlike [`Priority`] there is no
93/// order to preserve, so a member can be appended.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95#[non_exhaustive]
96pub enum Fallback {
97    /// One row becomes two. Every member stays, in the order described.
98    Wrap,
99    /// A row becomes a column. Every member stays, full width.
100    Stack,
101    /// Members drop by [`Priority`], down to [`Priority::Essential`].
102    ///
103    /// What a narrow table already does with its columns, applied to a group.
104    /// What drops is gone from the screen, so this is right when the dropped
105    /// members are facts the reader can do without and wrong when they are the
106    /// only way to act.
107    Shed,
108    /// The members [`Shed`](Self::Shed) would drop move into one overflow
109    /// control instead.
110    ///
111    /// The answer when a group holds actions. A control is not a fact: dropping
112    /// it does not cost the reader a detail, it costs them the only way to act,
113    /// which is [`RowPart::priority`]'s argument one level up.
114    Menu,
115}
116
117/// The widest a column's [`floor`](Column::floor) may be, in `ch`.
118///
119/// A bound so a webview can name every floor as a class from a fixed ladder:
120/// a container condition cannot read a custom property, so the length a
121/// column hides its contents under has to be written into the stylesheet.
122/// Wider than any column the tree declares, and a column wanting more is a
123/// [`Width::Fill`] with this as its floor.
124pub const MIN_CEILING: u16 = 64;
125
126/// The floor an undeclared [`Width::Fill`] column takes, in `ch`.
127const FILL_FLOOR: u16 = 16;
128
129/// One column of a table.
130///
131/// Described once. The grid track, the cell order and the drop behaviour are
132/// all derived from this, rather than being three hand-written encodings that
133/// must agree and are never checked against each other.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
135pub struct Column<'a> {
136    /// The heading, and the name the cell is addressed by.
137    pub name: &'a str,
138    /// How much room it asks for.
139    pub width: Width,
140    /// What it is worth when room runs out.
141    pub priority: Priority,
142    /// What the column holds, which is what carries its look.
143    pub kind: ColumnKind,
144    /// The narrowest the column may be before it drops, in `ch`.
145    ///
146    /// wiki `frontend-unification`: collapse points derive from declared
147    /// minimums only, so every host narrows at the same declared width rather
148    /// than at its own breakpoints. `ch` because every host has a direct
149    /// answer for it: a terminal cell is one, an immediate-mode painter
150    /// measures one off its face, and a webview draws one as nine sixteenths
151    /// of the base, a figure at a table's text size with room to spare. Not
152    /// the CSS `ch`
153    /// itself, because a container condition resolves font-relative units
154    /// against a different font than the cell's, and the column would hide at
155    /// one width and be sized at another.
156    ///
157    /// `None` derives it from the kind and the heading, which is what most
158    /// columns want. Read it through [`floor`](Self::floor), never directly:
159    /// that is where the derivation, the rounding and the ceiling live, and a
160    /// host reading this field would narrow somewhere the other two do not.
161    pub min: Option<u16>,
162    /// Whether the user can reorder the table by this column.
163    ///
164    /// What reordering *calls* is not here — that is an address, and this
165    /// crate names none — so a host pairs this with the route the way it pairs
166    /// a row's parts with the row's activation. This says the affordance
167    /// exists, which is what a renderer needs to draw a header a user can
168    /// press rather than a heading they cannot.
169    pub sortable: bool,
170    /// Which way the table is ordered by this column, if it is.
171    ///
172    /// `None` on every column but the one in force. A renderer draws the caret
173    /// from this and a webview sets `aria-sort`, which is why it is per column
174    /// rather than a single fact on the table: the host idiom is a property of
175    /// the header cell.
176    ///
177    /// Independent of [`sortable`](Self::sortable) rather than implied by it,
178    /// because both combinations mean something. A column sorted and not
179    /// sortable is a list ordered by a key the user cannot change, which is a
180    /// real thing to describe and a caret worth drawing.
181    pub sorted: Option<Sort>,
182}
183
184/// What a column holds.
185///
186/// wiki `table-model`: the kind is what carries a column's look, and four of
187/// the reference table's six rules were per kind rather than per table. A
188/// description states what the column is; each renderer decides what that
189/// looks like in its host, from the facts below rather than from the name.
190///
191/// `#[non_exhaustive]`, [`Width`]'s reasoning.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
193#[non_exhaustive]
194pub enum ColumnKind {
195    /// Prose. Wraps. What a column is when it says nothing else.
196    #[default]
197    Text,
198    /// A name a machine made: a fingerprint, a hash, a slug. Monospace, and
199    /// breaks mid-string rather than widening the table.
200    Identifier,
201    /// A point in time. Never wraps, so a date cannot print over its
202    /// neighbour, and its figures line up down the column.
203    Date,
204    /// A quantity. Figures line up and the column aligns to its end, so
205    /// magnitudes compare by length.
206    Number,
207    /// Source text, one row per line. Monospace and never wrapped. A table
208    /// holding one is read as code, so its rows are not striped or spaced as
209    /// records.
210    Code,
211    /// A state the row is in, drawn as a chip rather than as coloured text.
212    Status,
213    /// The row's controls. Aligns to its end and shrinks to what it holds.
214    Actions,
215}
216
217impl ColumnKind {
218    /// The narrowest a column of this kind reads at, in `ch`, when it declares
219    /// nothing narrower.
220    ///
221    /// A date is ten characters in the form every host writes, and a number
222    /// cut short is a different number, so the kinds that cannot truncate
223    /// floor at what they hold. Prose and identifiers wrap or break, so theirs
224    /// is only enough to be recognisable.
225    #[must_use]
226    pub const fn floor(self) -> u16 {
227        match self {
228            Self::Text | Self::Code | Self::Status | Self::Actions => 8,
229            Self::Identifier => 12,
230            Self::Date => 10,
231            Self::Number => 6,
232        }
233    }
234
235    /// Whether a column of this kind keeps its minimum rather than truncating
236    /// when it is essential and room runs out.
237    ///
238    /// A control, a figure, a date or a state cut short is wrong rather than
239    /// short. Prose and identifiers end in an ellipsis and stay what they were.
240    #[must_use]
241    pub const fn holds_minimum(self) -> bool {
242        matches!(
243            self,
244            Self::Date | Self::Number | Self::Status | Self::Actions
245        )
246    }
247
248    /// Whether the column aligns to its end rather than its start.
249    #[must_use]
250    pub const fn aligns_end(self) -> bool {
251        matches!(self, Self::Number | Self::Actions)
252    }
253
254    /// Whether the column's text may wrap onto a second line.
255    ///
256    /// An identifier wraps by breaking mid-string, which is still a wrap: the
257    /// alternative is a fingerprint forcing the table wider than its pane.
258    #[must_use]
259    pub const fn wraps(self) -> bool {
260        matches!(self, Self::Text | Self::Identifier)
261    }
262
263    /// Whether the column is set in the monospace face.
264    #[must_use]
265    pub const fn monospace(self) -> bool {
266        matches!(self, Self::Identifier | Self::Code)
267    }
268
269    /// Whether figures in the column take equal widths.
270    #[must_use]
271    pub const fn tabular(self) -> bool {
272        matches!(self, Self::Date | Self::Number)
273    }
274}
275
276/// Which way a column is ordered.
277///
278/// Two, because there is no third. "Unsorted" is [`Column::sorted`] being
279/// `None`, and folding it in here would be the same absence said twice.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
281pub enum Sort {
282    /// Smallest, earliest or first alphabetically at the top.
283    Ascending,
284    /// The other way.
285    Descending,
286}
287
288impl Sort {
289    /// The other direction, for a header that flips when pressed.
290    #[must_use]
291    pub const fn reversed(self) -> Self {
292        match self {
293            Self::Ascending => Self::Descending,
294            Self::Descending => Self::Ascending,
295        }
296    }
297
298    /// What a webview writes into `aria-sort`.
299    ///
300    /// Named here rather than in the webview renderer because a terminal and an
301    /// immediate-mode painter both want the same two words for a caret's label,
302    /// and three renderers picking their own is the drift this crate ends.
303    #[must_use]
304    pub const fn as_str(self) -> &'static str {
305        match self {
306            Self::Ascending => "ascending",
307            Self::Descending => "descending",
308        }
309    }
310
311    /// The caret a renderer draws for this direction.
312    ///
313    /// Here for [`as_str`](Self::as_str)'s reason, said about a glyph rather
314    /// than a word: three renderers picking their own is the drift this crate
315    /// ends. They had picked their own — two on the solid triangles and
316    /// `makeover-webview` on the arrows U+2191/U+2193 — and agreeing by
317    /// coincidence in three files is not agreement.
318    ///
319    /// The reason generalizes past this pair and is the house rule now —
320    /// prefer the bolder, simpler glyph over the thinner or more complicated
321    /// one. A third spelling is not open for re-argument.
322    ///
323    /// **Bare, with no spacing.** Where the gap goes is each renderer's
324    /// business: `makeover-tui` and `makeover-immediate` carry a leading space
325    /// inside their `TableStyle` string and a webview emits its own in
326    /// `content`, so folding a space in here would make one of the two wrong.
327    ///
328    /// Neither face the web apps self-host carries these — IBM Plex Mono has one
329    /// glyph in the whole geometric-shapes block and Lato has none — so a
330    /// browser falls back per glyph until the in-house face ships with them
331    /// drawn in (wiki `typography-standard`). Cosmetic
332    /// drift in one renderer, not a reason to spell it three ways.
333    #[must_use]
334    pub const fn glyph(self) -> &'static str {
335        match self {
336            Self::Ascending => "\u{25B2}",
337            Self::Descending => "\u{25BC}",
338        }
339    }
340}
341
342impl<'a> Column<'a> {
343    /// A column that absorbs slack and drops after the optional ones.
344    #[must_use]
345    pub const fn new(name: &'a str) -> Self {
346        Self {
347            name,
348            width: Width::Fill,
349            priority: Priority::Secondary,
350            kind: ColumnKind::Text,
351            min: None,
352            sortable: false,
353            sorted: None,
354        }
355    }
356
357    /// The same column, declaring the narrowest it may be before it drops.
358    #[must_use]
359    pub const fn min(mut self, ch: u16) -> Self {
360        self.min = Some(ch);
361        self
362    }
363
364    /// The narrowest this column may be before it drops, in `ch`.
365    ///
366    /// What every host narrows by: a column is kept at a cutoff only while the
367    /// floors of every column kept there fit. The declared [`min`](Self::min),
368    /// or else the widest of the kind's [`floor`](ColumnKind::floor), the
369    /// heading with two for its capitals and two more for a caret, and sixteen
370    /// for a [`Width::Fill`] column. Rounded up to an even count and held under
371    /// [`MIN_CEILING`], so a webview can carry the whole range as a fixed ladder
372    /// of classes and the other two hosts round the same way.
373    #[must_use]
374    pub const fn floor(&self) -> u16 {
375        let raw = match self.min {
376            Some(ch) => ch,
377            None => {
378                let caret = if self.sortable || self.sorted.is_some() {
379                    2
380                } else {
381                    0
382                };
383                // Bytes, not characters: const, and a heading is a short word
384                // in every table in the tree. A multi-byte heading reads a
385                // little wide, which errs toward keeping it legible. Two more
386                // for the heading's capitals and tracking, which run wider than
387                // the figures a `ch` is measured off: `AMOUNT` at six ch is cut.
388                let heading = if self.name.len() > MIN_CEILING as usize {
389                    MIN_CEILING
390                } else {
391                    self.name.len() as u16 + 2 + caret
392                };
393                let kind = self.kind.floor();
394                // A column that takes the slack is the one holding prose, and
395                // floored at its kind it wraps a title onto three lines while
396                // the columns worth less still stand at full width.
397                let fill = if matches!(self.width, Width::Fill) {
398                    FILL_FLOOR
399                } else {
400                    0
401                };
402                let wider = if heading > kind { heading } else { kind };
403                if fill > wider { fill } else { wider }
404            }
405        };
406        let even = raw + raw % 2;
407        if even < 2 {
408            2
409        } else if even > MIN_CEILING {
410            MIN_CEILING
411        } else {
412            even
413        }
414    }
415
416    /// Whether this column survives at the given cutoff.
417    ///
418    /// A renderer narrows by raising the cutoff, and never by counting
419    /// positions.
420    #[must_use]
421    pub const fn kept_at(&self, cutoff: Priority) -> bool {
422        (self.priority as u8) >= (cutoff as u8)
423    }
424}
425
426/// What a table cell holds.
427///
428/// [`RowPart`] for tables, and it exists for the same reason: a part that
429/// carries a control is not text, and a renderer with one class for the whole
430/// cell paints it as though it were: a button in a cell inherits the cell's
431/// content colour, which is the drift [`RowPart::intent`] prevents for rows.
432///
433/// Four members, and the count is what quasi's `Cell` was measured to carry: a
434/// value, tokens, actions and a link. Nothing was added past what something
435/// holds.
436///
437/// `#[non_exhaustive]` for [`RowPart`]'s reason: growth here must not be a
438/// lockstep event across three renderers.
439///
440/// # No hover-reveal
441///
442/// This enum never gets one. A cell's actions are shown at rest in every
443/// consumer measured, and a member nothing uses is one three renderers owe an
444/// answer for.
445#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
446#[non_exhaustive]
447pub enum CellPart {
448    /// The cell's own text.
449    Value,
450    /// Small labelled things in the cell: a status badge, a chip.
451    Tokens,
452    /// Controls that act on what the row is about.
453    Actions,
454    /// The cell's value, where the value is itself a link.
455    Link,
456}
457
458impl CellPart {
459    /// The content intent the part takes.
460    ///
461    /// One part is text and three are not, so three answer with the intent
462    /// inheriting already gives. That is [`RowPart::intent`]'s shape with the
463    /// text side narrower: a cell's secondary and muted readings are the
464    /// column's business, not the cell's.
465    #[must_use]
466    pub const fn intent(self) -> &'static str {
467        match self {
468            Self::Value => "content",
469            // A token carries its own tone, and a part-level intent underneath
470            // it would fight the token sitting on it.
471            Self::Tokens => "content",
472            // Actions carry controls rather than text.
473            Self::Actions => "content",
474            // A link in a cell is its row's title, so it reads in the ink the
475            // values beside it do.
476            Self::Link => "content",
477        }
478    }
479}