makeover-tui 0.68.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
//! The pieces every terminal app draws, drawn once: 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`).
//!
//! These are renderer-local, distinct from `makeover-layout`'s
//! `Region::Widget`, which every renderer draws its own way. 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 and
//! [`text`](crate::text).
//!
//! # What these take
//!
//! Each takes a `makeover-layout` description, an [`Ink`], and what the host
//! knows that a description does not carry: a wait's [`Progress`], and
//! whether a drawing is focused, as a `focused` argument. What focus looks
//! like is [`Ink::focused`]'s answer.
//!
//! # No layout
//!
//! Each answers a span or a line. Nothing here places anything relative to
//! anything else.

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

use crate::Palette;

/// What a badge of one tone is drawn in, when it is drawn filled.
///
/// 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.
#[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.
    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. `"*"` by default.
    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 two cells
    /// are the ones the parentheses of an unfilled badge take.
    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 per frame and handed to every piece of it. 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 some are carried by a modifier instead: muted and disabled text are
/// dim, danger is bold, an action is underlined, a filled control is reversed,
/// a sunken run is dim. Under [`Tones::NONE`](crate::Tones::NONE) that is
/// every role.
#[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,
    /// A control that will not answer: `State::Disabled`'s tier. Dim where
    /// the terminal has no colour for it, as muted is.
    pub disabled: 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 background each measure band adds, quietest first. Read through
    /// [`heat`](Self::heat). Band 0 adds nothing, and neither does a band whose
    /// tone the palette leaves empty.
    pub heats: [Style; HEAT_BANDS as usize],
    /// 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),
            disabled: or(t.disabled, 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),
            ],
            // Band 0 is the ground, so it adds nothing whatever the cell
            // sits on. A band with no colour adds nothing either: every
            // modifier a terminal has already says something a band must not
            // (dim is muted, bold is danger, reversed is the filled control),
            // and the value is still printed.
            heats: [None, t.heat_1, t.heat_2, t.heat_3, t.heat_4]
                .map(|c| c.map_or(Style::new(), |c| Style::new().bg(c))),
            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,
        }
    }

    /// The background a measure band adds, to patch over the text's own
    /// style. Band 0 is always an empty style. A band past the last reads as
    /// the last.
    #[must_use]
    pub const fn heat(&self, heat: Heat) -> Style {
        let band = heat.0 as usize;
        if band < self.heats.len() {
            self.heats[band]
        } else {
            self.heats[self.heats.len() - 1]
        }
    }

    /// 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 [`PieceStyle::focus`] when `focused`.
    #[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.
pub use makeover_layout::Progress;

/// The activity mark (rule 2 of wiki `loading-and-progress-standard`): one
/// cell, [`PieceStyle::meter_full`] in the action ink when lit and
/// [`PieceStyle::meter_empty`] in muted ink when dark. It occupies its cell
/// either way.
///
/// `lit` is the caller's, since this module holds no clock;
/// [`crate::activity_lit`] works it out from the time a wait has run.
#[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.
///
/// Three drawings for three states:
///
/// ```text
/// unmeasured                       #            a blinking cell
/// measured, nothing watching       # 41943040   the cell, and how much there is
/// measured and observed            ####------ 17825792/41943040  4s
/// ```
///
/// The bar's reading is what is done over what there is, plus the time it
/// has taken (rule 1 of the standard): no remaining time, arrival time or
/// rate. The numbers are raw, with no unit; the unit is the app's.
#[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 = format!(" {}", progress_reading(done, total, progress.elapsed));
    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.
///
/// `latched` is a chip that is switched on, and it takes
/// [`PieceStyle::focus`], the same modifier as focus, so a latched chip and a
/// focused one look alike. A chip's removable half is not drawn.
#[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 { .. }, _) => bracketed(label, ["[", "]"], tone, ink, mark),
        (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.
        _ => bracketed(label, ["(", ")"], tone, ink, mark),
    }
}

/// A token's label between two brackets, the brackets carrying its tone.
///
/// The label is drawn in content ink and the brackets in the tone's ink (wiki
/// `quasi-vocabulary-findings`, toned text); a neutral token's brackets are
/// content ink too.
fn bracketed(
    label: &str,
    [open, close]: [&'static str; 2],
    tone: Tone,
    ink: &Ink,
    mark: impl Fn(Style) -> Style,
) -> Line<'static> {
    let edge = mark(ink.tone(tone));
    Line::from(vec![
        Span::styled(open, edge),
        Span::styled(label.to_owned(), mark(ink.content)),
        Span::styled(close, edge),
    ])
}

#[cfg(test)]
mod tests;