makeover_tui/piece.rs
1//! The pieces every terminal app draws, drawn once.
2//!
3//! # Not `widget`
4//!
5//! `makeover-layout` owns that word for something else, and the two meanings do
6//! not sit together. A `Region::Widget` there is host-agnostic: a named
7//! assembly of primitives that every renderer draws its own way. What is in
8//! this module is the opposite end, renderer-local, the answer to *what a badge
9//! looks like in cells*, taking a description plus what only a terminal knows.
10//!
11//! What is here is the ink every terminal drawing resolves once per frame
12//! ([`Ink`]), a badge or chip ([`token`]), and the wait marks ([`activity`] and
13//! [`awaiting`], out of wiki `loading-and-progress-standard`). The vocabulary's
14//! members (a meter, a control, a figure, facts, a form field, a chart) are
15//! drawn by `quasi-tui`, which owns those types, on top of this ink.
16//!
17//! # What these take, and what they leave alone
18//!
19//! Each takes a `makeover-layout` description, an [`Ink`], and whatever the
20//! *host* knows that a description never carries: a wait's [`Progress`] is the
21//! host's count, never the description's.
22//!
23//! Focus is the same. Nothing in a description says which control the user is
24//! on, so a drawing that can be focused takes `focused` as an argument and the
25//! caller is what counts. What focus *looks like* is this crate's answer and
26//! not the caller's, which is the point of it being here: see [`Ink::focused`].
27//!
28//! # What they do not do
29//!
30//! No layout. Each answers a span or a line, and nothing here places anything
31//! relative to anything else, because the moment it did it would be a layout
32//! engine with one consumer's flow baked into it.
33
34use makeover_layout::{Awaiting, HEAT_BANDS, Heading, Heat, Token, Tone};
35use ratatui::style::{Color, Modifier, Style};
36use ratatui::text::{Line, Span};
37
38use crate::Palette;
39use std::time::Duration;
40
41/// What a badge of one tone is drawn in, when it is drawn filled.
42///
43/// Two styles and not one, because a filled badge is three spans: an edge, the
44/// label, an edge. The label takes [`fill`](Self::fill) whole. An edge takes
45/// the fill's background with [`edge`](Self::edge)'s foreground over it, so
46/// the half of the cell the glyph leaves empty is the badge's own ground.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48pub struct BadgeStyle {
49 /// The ground and the ink.
50 pub fill: Style,
51 /// The edge, as a foreground.
52 pub edge: Style,
53}
54
55/// The metrics and marks the drawings below use.
56///
57/// No colours: those are the [`Palette`]'s, and [`Ink`] is the two resolved
58/// together. What is here is what a terminal says with glyphs and cell counts.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct PieceStyle {
62 /// What "you are on this one" adds to whatever it lands on.
63 ///
64 /// Reversed video by default, which is the affordance a cell has left once
65 /// colour is spent on tone and bold on weight. A terminal has no outline
66 /// that is not four more cells.
67 pub focus: Modifier,
68 /// How many cells a bar spends: [`awaiting`]'s, and the meter a host draws.
69 pub meter_cells: u16,
70 /// The filled part of a bar.
71 pub meter_full: char,
72 /// The empty part of a bar.
73 pub meter_empty: char,
74 /// What marks a compulsory field, appended to its label. The one piece of
75 /// copy here, and copy is not a renderer's call.
76 pub required_marker: &'static str,
77 /// The glyphs either side of a badge drawn filled.
78 ///
79 /// Half blocks by default: the outer half of each end cell is the edge and
80 /// the inner half is fill, so the label sits half a cell in. The same two
81 /// cells the parentheses of an unfilled badge take, so a badge gaining its
82 /// fill moves nothing beside it.
83 pub badge_edges: [&'static str; 2],
84}
85
86impl Default for PieceStyle {
87 fn default() -> Self {
88 Self {
89 focus: Modifier::REVERSED,
90 meter_cells: 10,
91 meter_full: '#',
92 meter_empty: '-',
93 required_marker: "*",
94 badge_edges: ["\u{258C}", "\u{2590}"],
95 }
96 }
97}
98
99/// A [`Palette`] and a [`PieceStyle`], resolved into the styles every drawing
100/// here takes.
101///
102/// Resolved once and handed to every piece of a frame, rather than per call.
103/// Its fields are public for a caller drawing something of its own in the same
104/// tones: a caption in [`muted`](Self::muted), a line in a [`tone`](Self::tone).
105///
106/// A role the palette has no colour for is drawn in the terminal's own ink and
107/// carried by a modifier instead: muted text is dim, danger is bold, an action
108/// is underlined, a filled control is reversed, a sunken run is dim. That is
109/// what survives a terminal with two colours, and it is the whole of
110/// [`Tones::NONE`](crate::Tones::NONE).
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112#[non_exhaustive]
113pub struct Ink {
114 /// Ordinary content, and what [`Tone::Neutral`] reads as.
115 pub content: Style,
116 /// Content one step back: a field's label, a quoted run.
117 pub secondary: Style,
118 /// Content two steps back: a caption, a hint, a meter's reading.
119 pub muted: Style,
120 /// Something worth knowing and nothing to do about it.
121 pub info: Style,
122 /// Something finished and it worked.
123 pub success: Style,
124 /// Something the user should look at.
125 pub warning: Style,
126 /// Something broken, or about to be destroyed.
127 pub danger: Style,
128 /// A page title.
129 pub page: Style,
130 /// A section title.
131 pub section: Style,
132 /// A subsection title.
133 pub subsection: Style,
134 /// Text that goes somewhere, and a control's label.
135 pub action: Style,
136 /// A control filled with the action colour, for the one on a screen that is
137 /// the thing to press.
138 pub filled: Style,
139 /// A surface set back from the one it sits on, by colour and nothing else:
140 /// what a code run takes.
141 pub sunken: Style,
142 /// A badge of each tone drawn filled, in [`Tone`]'s order, or `None` where
143 /// the palette has no fill for it and the badge is drawn in round brackets
144 /// in its tone. Read through [`badge`](Self::badge).
145 pub badges: [Option<BadgeStyle>; 5],
146 /// The background each measure band adds, quietest first. Read through
147 /// [`heat`](Self::heat).
148 pub heats: [Style; HEAT_BANDS as usize],
149 /// The metrics and marks.
150 pub style: PieceStyle,
151}
152
153impl Ink {
154 /// Resolve `palette`'s tones under `style`'s marks.
155 #[must_use]
156 pub fn new(palette: &Palette, style: &PieceStyle) -> Self {
157 let t = &palette.tones;
158 let fg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().fg(c));
159 // A role with no colour says it with a modifier instead.
160 let or = |c: Option<Color>, missing: Modifier| match c {
161 Some(c) => Style::new().fg(c),
162 None => Style::new().add_modifier(missing),
163 };
164 let badge = |fill: Option<Color>, edge: Option<Color>| {
165 fill.map(|fill| BadgeStyle {
166 fill: fg(t.content).bg(fill),
167 edge: fg(edge),
168 })
169 };
170 Self {
171 content: fg(t.content),
172 secondary: fg(t.secondary),
173 muted: or(t.muted, Modifier::DIM),
174 info: fg(t.info),
175 success: fg(t.success),
176 warning: fg(t.warning),
177 danger: or(t.danger, Modifier::BOLD),
178 // Three depths and two of them are bold, which is the whole of what
179 // a terminal has: there is no type scale in a grid of one cell
180 // size. A page title takes bold and the accent, a section bold, a
181 // subsection the secondary colour.
182 page: fg(t.action).add_modifier(Modifier::BOLD),
183 section: fg(t.content).add_modifier(Modifier::BOLD),
184 subsection: fg(t.secondary),
185 action: or(t.action, Modifier::UNDERLINED),
186 filled: match t.action {
187 Some(action) => fg(t.on_action).bg(action),
188 None => Style::new().add_modifier(Modifier::REVERSED),
189 },
190 sunken: match t.sunken {
191 Some(sunken) => Style::new().bg(sunken),
192 None => Style::new().add_modifier(Modifier::DIM),
193 },
194 badges: [
195 badge(t.neutral_surface, t.border),
196 badge(t.info_surface, t.info),
197 badge(t.success_surface, t.success),
198 badge(t.warning_surface, t.warning),
199 badge(t.danger_surface, t.danger),
200 ],
201 // Band 0 is the ground, so it adds nothing whatever the cell
202 // sits on. A band with no colour adds nothing either: every
203 // modifier a terminal has already says something a band must not
204 // (dim is muted, bold is danger, reversed is the filled control),
205 // and the value is still printed.
206 heats: [None, t.heat_1, t.heat_2, t.heat_3, t.heat_4]
207 .map(|c| c.map_or(Style::new(), |c| Style::new().bg(c))),
208 style: *style,
209 }
210 }
211
212 /// The style a tone reads as. A tone this renderer has not learned reads
213 /// as content.
214 #[must_use]
215 pub const fn tone(&self, tone: Tone) -> Style {
216 match tone {
217 Tone::Info => self.info,
218 Tone::Success => self.success,
219 Tone::Warning => self.warning,
220 Tone::Danger => self.danger,
221 _ => self.content,
222 }
223 }
224
225 /// The background a measure band adds, to patch over the text's own
226 /// style. A band past the last reads as the last.
227 #[must_use]
228 pub const fn heat(&self, heat: Heat) -> Style {
229 let last = HEAT_BANDS - 1;
230 self.heats[(if heat.0 > last { last } else { heat.0 }) as usize]
231 }
232
233 /// What a badge of this tone is drawn in when it is filled, or `None` when
234 /// the palette has no fill for it.
235 #[must_use]
236 pub const fn badge(&self, tone: Tone) -> Option<BadgeStyle> {
237 self.badges[match tone {
238 Tone::Info => 1,
239 Tone::Success => 2,
240 Tone::Warning => 3,
241 Tone::Danger => 4,
242 _ => 0,
243 }]
244 }
245
246 /// The style a heading reads as. A level this renderer has not learned
247 /// reads as a subsection.
248 #[must_use]
249 pub const fn heading(&self, level: Heading) -> Style {
250 match level {
251 Heading::Page => self.page,
252 Heading::Section => self.section,
253 _ => self.subsection,
254 }
255 }
256
257 /// `style`, plus the mark that says the user is on this one.
258 ///
259 /// Takes the flag rather than being called behind an `if`, because every
260 /// caller has a bool in hand and the branch is the part that gets forgotten.
261 #[must_use]
262 pub fn focused(&self, focused: bool, style: Style) -> Style {
263 if focused {
264 style.add_modifier(self.style.focus)
265 } else {
266 style
267 }
268 }
269}
270
271/// What a host can see about a wait that is running.
272///
273/// Neither half is derivable from a description, which is why both are here and
274/// not on [`Awaiting`]. That type says how big the payload is; how much of it
275/// has landed is a fact about a transfer in flight, and only whoever is running
276/// the transfer knows it.
277///
278/// The same shape `makeover-immediate` carries, deliberately: a wait is one
279/// reading on every surface and the two renderers should not disagree about
280/// what a host owes them.
281#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
282pub struct Progress {
283 /// How much has arrived, in whatever unit the description counted.
284 pub delivered: Option<u64>,
285 /// How long the wait has lasted so far.
286 ///
287 /// The one time value a wait may show. See [`awaiting`] for the three it
288 /// may not.
289 pub elapsed: Option<Duration>,
290}
291
292/// The activity mark: one cell, lit or dark.
293///
294/// Rule 2 of wiki `loading-and-progress-standard`, and the surface the metaphor
295/// came from. A hard-disk light is one cell that blinks, and a terminal draws
296/// that with no metaphor in the way: where a webview needs a keyframe and egui
297/// needs a repaint schedule, this is a character.
298///
299/// The two glyphs are [`PieceStyle::meter_full`] and
300/// [`PieceStyle::meter_empty`], not a third pair. A bar's filled cell and a lit
301/// mark are the same statement in the same alphabet, and a terminal that had to
302/// render two vocabularies of "on" would be saying there are two kinds of on.
303///
304/// **Dark, not absent.** A mark that is drawn half the time is a hole in the
305/// line, and the line reflows around it or the reader loses where to look. It
306/// occupies its cell either way.
307///
308/// `lit` is the caller's: this module holds no clock. [`crate::activity_lit`]
309/// is the one place the phase is worked out from the cadence, so a caller
310/// should reach for that rather than dividing by 500 itself.
311#[must_use]
312pub fn activity(lit: bool, ink: &Ink) -> Span<'static> {
313 if lit {
314 Span::styled(ink.style.meter_full.to_string(), ink.action)
315 } else {
316 Span::styled(ink.style.meter_empty.to_string(), ink.muted)
317 }
318}
319
320/// A wait as one line, drawn from what is actually known about it.
321///
322/// [`Awaiting::is_determinate`] is the first branch and there is a second the
323/// description cannot answer: whether anything is watching the transfer. A bar
324/// wants a total and a numerator both, so a described amount with no
325/// [`Progress::delivered`] beside it draws the mark and the size it is waiting
326/// on, rather than an empty trough implying somebody is counting.
327///
328/// So three drawings for three states, which is the point:
329///
330/// ```text
331/// unmeasured # a blinking cell
332/// measured, nothing watching # 41943040 the cell, and how much there is
333/// measured and observed ####------ 17825792/41943040 4s
334/// ```
335///
336/// **What the bar may not do**, from rule 1 of the standard and from
337/// [`Awaiting`]'s own docs: what is done over what there is, plus the time it
338/// has taken. Never a remaining time, an arrival time, or a rate extrapolated
339/// forward. A prediction is wrong the moment the transfer stalls, and being
340/// confidently wrong is worse than being honestly indeterminate.
341///
342/// The numbers are raw. The unit is the app's (bytes for an upload, rows for
343/// an import), and a renderer that formatted one as a file size would be
344/// dressing up a quantity it was deliberately not told about.
345#[must_use]
346pub fn awaiting(awaiting: Awaiting, progress: Progress, lit: bool, ink: &Ink) -> Line<'static> {
347 let Some(total) = awaiting.amount else {
348 return Line::from(vec![activity(lit, ink)]);
349 };
350 let Some(done) = progress.delivered else {
351 return Line::from(vec![
352 activity(lit, ink),
353 Span::styled(format!(" {total}"), ink.muted),
354 ]);
355 };
356 let cells = u32::from(ink.style.meter_cells);
357 // In cells rather than in floating point: a terminal's bar has ten states
358 // and rounding through an f64 to reach one of ten is arithmetic nobody
359 // needs. Saturating rather than wrapping, because
360 // a transfer that over-delivers is a real case and a panicking bar is not
361 // the way to report it.
362 let filled = u32::try_from(
363 done.saturating_mul(u64::from(cells))
364 .checked_div(total)
365 .unwrap_or(0),
366 )
367 .unwrap_or(cells)
368 .min(cells);
369 let bar = format!(
370 "{}{}",
371 ink.style.meter_full.to_string().repeat(filled as usize),
372 ink.style
373 .meter_empty
374 .to_string()
375 .repeat((cells - filled) as usize)
376 );
377 let reading = match progress.elapsed {
378 Some(elapsed) => format!(" {done}/{total} {}s", elapsed.as_secs()),
379 None => format!(" {done}/{total}"),
380 };
381 Line::from(vec![
382 Span::styled(bar, ink.action),
383 Span::styled(reading, ink.muted),
384 ])
385}
386
387/// A badge or a chip as a line.
388///
389/// A chip is its label in square brackets, in its tone: it answers a press, and
390/// the bracket says so. A badge answers nothing and is drawn filled where the
391/// palette has a fill for its tone, as an edge, the label on the fill, and an
392/// edge ([`badge_edges`](PieceStyle::badge_edges), wiki `table-model`), and in
393/// round brackets in its tone where it has none. Every spelling is the label and two cells, so the width
394/// does not depend on which one a terminal gets.
395///
396/// `latched` is a chip that is switched on, and it reads as reversed. So does
397/// focus, which is a collision a terminal cannot avoid: latched is "this filter
398/// is on" and focused is "you are here", and there is one spare axis for two
399/// facts. Said here rather than resolved by inventing a third look nobody would
400/// read.
401///
402/// A chip's removable half is not drawn. The `x` a webview hangs on a chip is a
403/// second control inside one span, and a terminal reaches a control by focusing
404/// it; two targets in one cell run is a question for whoever owns the
405/// interaction, not for a drawing.
406#[must_use]
407pub fn token(
408 label: &str,
409 kind: Token,
410 tone: Tone,
411 latched: bool,
412 focused: bool,
413 ink: &Ink,
414) -> Line<'static> {
415 let mark = |painted: Style| {
416 if latched {
417 painted.add_modifier(ink.style.focus)
418 } else {
419 ink.focused(focused, painted)
420 }
421 };
422 match (kind, ink.badge(tone)) {
423 (Token::Chip { .. }, _) => bracketed(label, ["[", "]"], tone, ink, mark),
424 (Token::Badge, Some(badge)) => {
425 let [open, close] = ink.style.badge_edges;
426 let edge = mark(badge.fill.patch(badge.edge));
427 Line::from(vec![
428 Span::styled(open, edge),
429 Span::styled(label.to_owned(), mark(badge.fill)),
430 Span::styled(close, edge),
431 ])
432 }
433 // A badge with no fill to spend, and a token kind this renderer has
434 // not learned: round brackets, which answer no press.
435 _ => bracketed(label, ["(", ")"], tone, ink, mark),
436 }
437}
438
439/// A token's label between two brackets, the brackets carrying its tone.
440///
441/// The label is drawn in content ink. A status colour is an edge or a glyph
442/// and never the colour of words (wiki `quasi-vocabulary-findings`, toned
443/// text): the status inks are held at the UI floor, which is under what a word
444/// needs. A neutral token's brackets are content too, so it reads as before.
445fn bracketed(
446 label: &str,
447 [open, close]: [&'static str; 2],
448 tone: Tone,
449 ink: &Ink,
450 mark: impl Fn(Style) -> Style,
451) -> Line<'static> {
452 let edge = mark(ink.tone(tone));
453 Line::from(vec![
454 Span::styled(open, edge),
455 Span::styled(label.to_owned(), mark(ink.content)),
456 Span::styled(close, edge),
457 ])
458}
459
460#[cfg(test)]
461mod tests;