makeover-tui 0.56.0

The terminal renderer for makeover-layout, on ratatui. Colour stops being the constraint above 256 entries; geometry never does, because an edge occupies a whole cell on every side.
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
//! The pieces every terminal app draws, drawn once.
//!
//! # Not `widget`
//!
//! `makeover-layout` owns that word for something else, and the two meanings do
//! not sit together. A `Region::Widget` there is host-agnostic: a named
//! assembly of primitives that every renderer draws its own way. What is in
//! this module is the opposite end, renderer-local, the answer to *what a badge
//! looks like in cells*, taking a description plus what only a terminal knows.
//!
//! What is here is the ink every terminal drawing resolves once per frame
//! ([`Ink`]), a badge or chip ([`token`]), and the wait marks ([`activity`] and
//! [`awaiting`], out of wiki `loading-and-progress-standard`). The vocabulary's
//! members (a meter, a control, a figure, facts, a form field, a chart) are
//! drawn by `quasi-tui`, which owns those types, on top of this ink.
//!
//! # What these take, and what they leave alone
//!
//! Each takes a `makeover-layout` description, an [`Ink`], and whatever the
//! *host* knows that a description never carries: a wait's [`Progress`] is the
//! host's count, never the description's.
//!
//! Focus is the same. Nothing in a description says which control the user is
//! on, so a drawing that can be focused takes `focused` as an argument and the
//! caller is what counts. What focus *looks like* is this crate's answer and
//! not the caller's, which is the point of it being here: see [`Ink::focused`].
//!
//! # What they do not do
//!
//! No layout. Each answers a span or a line, and nothing here places anything
//! relative to anything else, because the moment it did it would be a layout
//! engine with one consumer's flow baked into it.

use makeover_layout::{Awaiting, Heading, Token, Tone};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};

use crate::Palette;
use std::time::Duration;

/// What a badge of one tone is drawn in, when it is drawn filled.
///
/// Two styles and not one, because a filled badge is three spans: an edge, the
/// label, an edge. The label takes [`fill`](Self::fill) whole. An edge takes
/// the fill's background with [`edge`](Self::edge)'s foreground over it, so
/// the half of the cell the glyph leaves empty is the badge's own ground.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct BadgeStyle {
    /// The ground and the ink.
    pub fill: Style,
    /// The edge, as a foreground.
    pub edge: Style,
}

/// The metrics and marks the drawings below use.
///
/// No colours: those are the [`Palette`]'s, and [`Ink`] is the two resolved
/// together. What is here is what a terminal says with glyphs and cell counts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PieceStyle {
    /// What "you are on this one" adds to whatever it lands on.
    ///
    /// Reversed video by default, which is the affordance a cell has left once
    /// colour is spent on tone and bold on weight. A terminal has no outline
    /// that is not four more cells.
    pub focus: Modifier,
    /// How many cells a bar spends: [`awaiting`]'s, and the meter a host draws.
    pub meter_cells: u16,
    /// The filled part of a bar.
    pub meter_full: char,
    /// The empty part of a bar.
    pub meter_empty: char,
    /// What marks a compulsory field, appended to its label. The one piece of
    /// copy here, and copy is not a renderer's call.
    pub required_marker: &'static str,
    /// The glyphs either side of a badge drawn filled.
    ///
    /// Half blocks by default: the outer half of each end cell is the edge and
    /// the inner half is fill, so the label sits half a cell in. The same two
    /// cells the parentheses of an unfilled badge take, so a badge gaining its
    /// fill moves nothing beside it.
    pub badge_edges: [&'static str; 2],
}

impl Default for PieceStyle {
    fn default() -> Self {
        Self {
            focus: Modifier::REVERSED,
            meter_cells: 10,
            meter_full: '#',
            meter_empty: '-',
            required_marker: "*",
            badge_edges: ["\u{258C}", "\u{2590}"],
        }
    }
}

/// A [`Palette`] and a [`PieceStyle`], resolved into the styles every drawing
/// here takes.
///
/// Resolved once and handed to every piece of a frame, rather than per call.
/// Its fields are public for a caller drawing something of its own in the same
/// tones: a caption in [`muted`](Self::muted), a line in a [`tone`](Self::tone).
///
/// A role the palette has no colour for is drawn in the terminal's own ink and
/// carried by a modifier instead: muted text is dim, danger is bold, an action
/// is underlined, a filled control is reversed, a sunken run is dim. That is
/// what survives a terminal with two colours, and it is the whole of
/// [`Tones::NONE`](crate::Tones::NONE).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Ink {
    /// Ordinary content, and what [`Tone::Neutral`] reads as.
    pub content: Style,
    /// Content one step back: a field's label, a quoted run.
    pub secondary: Style,
    /// Content two steps back: a caption, a hint, a meter's reading.
    pub muted: Style,
    /// Something worth knowing and nothing to do about it.
    pub info: Style,
    /// Something finished and it worked.
    pub success: Style,
    /// Something the user should look at.
    pub warning: Style,
    /// Something broken, or about to be destroyed.
    pub danger: Style,
    /// A page title.
    pub page: Style,
    /// A section title.
    pub section: Style,
    /// A subsection title.
    pub subsection: Style,
    /// Text that goes somewhere, and a control's label.
    pub action: Style,
    /// A control filled with the action colour, for the one on a screen that is
    /// the thing to press.
    pub filled: Style,
    /// A surface set back from the one it sits on, by colour and nothing else:
    /// what a code run takes.
    pub sunken: Style,
    /// A badge of each tone drawn filled, in [`Tone`]'s order, or `None` where
    /// the palette has no fill for it and the badge is drawn in round brackets
    /// in its tone. Read through [`badge`](Self::badge).
    pub badges: [Option<BadgeStyle>; 5],
    /// The metrics and marks.
    pub style: PieceStyle,
}

impl Ink {
    /// Resolve `palette`'s tones under `style`'s marks.
    #[must_use]
    pub fn new(palette: &Palette, style: &PieceStyle) -> Self {
        let t = &palette.tones;
        let fg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().fg(c));
        // A role with no colour says it with a modifier instead.
        let or = |c: Option<Color>, missing: Modifier| match c {
            Some(c) => Style::new().fg(c),
            None => Style::new().add_modifier(missing),
        };
        let badge = |fill: Option<Color>, edge: Option<Color>| {
            fill.map(|fill| BadgeStyle {
                fill: fg(t.content).bg(fill),
                edge: fg(edge),
            })
        };
        Self {
            content: fg(t.content),
            secondary: fg(t.secondary),
            muted: or(t.muted, Modifier::DIM),
            info: fg(t.info),
            success: fg(t.success),
            warning: fg(t.warning),
            danger: or(t.danger, Modifier::BOLD),
            // Three depths and two of them are bold, which is the whole of what
            // a terminal has: there is no type scale in a grid of one cell
            // size. A page title takes bold and the accent, a section bold, a
            // subsection the secondary colour.
            page: fg(t.action).add_modifier(Modifier::BOLD),
            section: fg(t.content).add_modifier(Modifier::BOLD),
            subsection: fg(t.secondary),
            action: or(t.action, Modifier::UNDERLINED),
            filled: match t.action {
                Some(action) => fg(t.on_action).bg(action),
                None => Style::new().add_modifier(Modifier::REVERSED),
            },
            sunken: match t.sunken {
                Some(sunken) => Style::new().bg(sunken),
                None => Style::new().add_modifier(Modifier::DIM),
            },
            badges: [
                badge(t.neutral_surface, t.border),
                badge(t.info_surface, t.info),
                badge(t.success_surface, t.success),
                badge(t.warning_surface, t.warning),
                badge(t.danger_surface, t.danger),
            ],
            style: *style,
        }
    }

    /// The style a tone reads as. A tone this renderer has not learned reads
    /// as content.
    #[must_use]
    pub const fn tone(&self, tone: Tone) -> Style {
        match tone {
            Tone::Info => self.info,
            Tone::Success => self.success,
            Tone::Warning => self.warning,
            Tone::Danger => self.danger,
            _ => self.content,
        }
    }

    /// What a badge of this tone is drawn in when it is filled, or `None` when
    /// the palette has no fill for it.
    #[must_use]
    pub const fn badge(&self, tone: Tone) -> Option<BadgeStyle> {
        self.badges[match tone {
            Tone::Info => 1,
            Tone::Success => 2,
            Tone::Warning => 3,
            Tone::Danger => 4,
            _ => 0,
        }]
    }

    /// The style a heading reads as. A level this renderer has not learned
    /// reads as a subsection.
    #[must_use]
    pub const fn heading(&self, level: Heading) -> Style {
        match level {
            Heading::Page => self.page,
            Heading::Section => self.section,
            _ => self.subsection,
        }
    }

    /// `style`, plus the mark that says the user is on this one.
    ///
    /// Takes the flag rather than being called behind an `if`, because every
    /// caller has a bool in hand and the branch is the part that gets forgotten.
    #[must_use]
    pub fn focused(&self, focused: bool, style: Style) -> Style {
        if focused {
            style.add_modifier(self.style.focus)
        } else {
            style
        }
    }
}

/// What a host can see about a wait that is running.
///
/// Neither half is derivable from a description, which is why both are here and
/// not on [`Awaiting`]. That type says how big the payload is; how much of it
/// has landed is a fact about a transfer in flight, and only whoever is running
/// the transfer knows it.
///
/// The same shape `makeover-immediate` carries, deliberately: a wait is one
/// reading on every surface and the two renderers should not disagree about
/// what a host owes them.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Progress {
    /// How much has arrived, in whatever unit the description counted.
    pub delivered: Option<u64>,
    /// How long the wait has lasted so far.
    ///
    /// The one time value a wait may show. See [`awaiting`] for the three it
    /// may not.
    pub elapsed: Option<Duration>,
}

/// The activity mark: one cell, lit or dark.
///
/// Rule 2 of wiki `loading-and-progress-standard`, and the surface the metaphor
/// came from. A hard-disk light is one cell that blinks, and a terminal draws
/// that with no metaphor in the way: where a webview needs a keyframe and egui
/// needs a repaint schedule, this is a character.
///
/// The two glyphs are [`PieceStyle::meter_full`] and
/// [`PieceStyle::meter_empty`], not a third pair. A bar's filled cell and a lit
/// mark are the same statement in the same alphabet, and a terminal that had to
/// render two vocabularies of "on" would be saying there are two kinds of on.
///
/// **Dark, not absent.** A mark that is drawn half the time is a hole in the
/// line, and the line reflows around it or the reader loses where to look. It
/// occupies its cell either way.
///
/// `lit` is the caller's: this module holds no clock. [`crate::activity_lit`]
/// is the one place the phase is worked out from the cadence, so a caller
/// should reach for that rather than dividing by 500 itself.
#[must_use]
pub fn activity(lit: bool, ink: &Ink) -> Span<'static> {
    if lit {
        Span::styled(ink.style.meter_full.to_string(), ink.action)
    } else {
        Span::styled(ink.style.meter_empty.to_string(), ink.muted)
    }
}

/// A wait as one line, drawn from what is actually known about it.
///
/// [`Awaiting::is_determinate`] is the first branch and there is a second the
/// description cannot answer: whether anything is watching the transfer. A bar
/// wants a total and a numerator both, so a described amount with no
/// [`Progress::delivered`] beside it draws the mark and the size it is waiting
/// on, rather than an empty trough implying somebody is counting.
///
/// So three drawings for three states, which is the point:
///
/// ```text
/// unmeasured                       #            a blinking cell
/// measured, nothing watching       # 41943040   the cell, and how much there is
/// measured and observed            ####------ 17825792/41943040  4s
/// ```
///
/// **What the bar may not do**, from rule 1 of the standard and from
/// [`Awaiting`]'s own docs: what is done over what there is, plus the time it
/// has taken. Never a remaining time, an arrival time, or a rate extrapolated
/// forward. A prediction is wrong the moment the transfer stalls, and being
/// confidently wrong is worse than being honestly indeterminate.
///
/// The numbers are raw. The unit is the app's (bytes for an upload, rows for
/// an import), and a renderer that formatted one as a file size would be
/// dressing up a quantity it was deliberately not told about.
#[must_use]
pub fn awaiting(awaiting: Awaiting, progress: Progress, lit: bool, ink: &Ink) -> Line<'static> {
    let Some(total) = awaiting.amount else {
        return Line::from(vec![activity(lit, ink)]);
    };
    let Some(done) = progress.delivered else {
        return Line::from(vec![
            activity(lit, ink),
            Span::styled(format!(" {total}"), ink.muted),
        ]);
    };
    let cells = u32::from(ink.style.meter_cells);
    // In cells rather than in floating point: a terminal's bar has ten states
    // and rounding through an f64 to reach one of ten is arithmetic nobody
    // needs. Saturating rather than wrapping, because
    // a transfer that over-delivers is a real case and a panicking bar is not
    // the way to report it.
    let filled = u32::try_from(
        done.saturating_mul(u64::from(cells))
            .checked_div(total)
            .unwrap_or(0),
    )
    .unwrap_or(cells)
    .min(cells);
    let bar = format!(
        "{}{}",
        ink.style.meter_full.to_string().repeat(filled as usize),
        ink.style
            .meter_empty
            .to_string()
            .repeat((cells - filled) as usize)
    );
    let reading = match progress.elapsed {
        Some(elapsed) => format!(" {done}/{total}  {}s", elapsed.as_secs()),
        None => format!(" {done}/{total}"),
    };
    Line::from(vec![
        Span::styled(bar, ink.action),
        Span::styled(reading, ink.muted),
    ])
}

/// A badge or a chip as a line.
///
/// A chip is its label in square brackets, in its tone: it answers a press, and
/// the bracket says so. A badge answers nothing and is drawn filled where the
/// palette has a fill for its tone, as an edge, the label on the fill, and an
/// edge ([`badge_edges`](PieceStyle::badge_edges), wiki `table-model`), and in
/// round brackets in its tone where it has none. Every spelling is the label and two cells, so the width
/// does not depend on which one a terminal gets.
///
/// `latched` is a chip that is switched on, and it reads as reversed. So does
/// focus, which is a collision a terminal cannot avoid: latched is "this filter
/// is on" and focused is "you are here", and there is one spare axis for two
/// facts. Said here rather than resolved by inventing a third look nobody would
/// read.
///
/// A chip's removable half is not drawn. The `x` a webview hangs on a chip is a
/// second control inside one span, and a terminal reaches a control by focusing
/// it; two targets in one cell run is a question for whoever owns the
/// interaction, not for a drawing.
#[must_use]
pub fn token(
    label: &str,
    kind: Token,
    tone: Tone,
    latched: bool,
    focused: bool,
    ink: &Ink,
) -> Line<'static> {
    let mark = |painted: Style| {
        if latched {
            painted.add_modifier(ink.style.focus)
        } else {
            ink.focused(focused, painted)
        }
    };
    match (kind, ink.badge(tone)) {
        (Token::Chip { .. }, _) => {
            Line::from(Span::styled(format!("[{label}]"), mark(ink.tone(tone))))
        }
        (Token::Badge, Some(badge)) => {
            let [open, close] = ink.style.badge_edges;
            let edge = mark(badge.fill.patch(badge.edge));
            Line::from(vec![
                Span::styled(open, edge),
                Span::styled(label.to_owned(), mark(badge.fill)),
                Span::styled(close, edge),
            ])
        }
        // A badge with no fill to spend, and a token kind this renderer has
        // not learned: round brackets, which answer no press.
        _ => Line::from(Span::styled(format!("({label})"), mark(ink.tone(tone)))),
    }
}

#[cfg(test)]
mod tests;