tinsel 0.1.0

Clean, pink-hued terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and more. Zero dependencies.
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
use std::fmt;
use std::io::IsTerminal;
use std::sync::atomic::{AtomicU8, Ordering};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// A colour as red, green and blue, 0-255 each.
pub struct Rgb(pub u8, pub u8, pub u8);

/// The palette everything in tinsel is drawn from: pinks for accent, quiet greys for the rest.
pub mod palette {
    use super::Rgb;

    /// Deep pink: the dark end of the ramp.
    pub const BERRY: Rgb = Rgb(190, 80, 124);
    /// The accent: done marks, headings, the spinner's rest colour.
    pub const ROSE: Rgb = Rgb(236, 122, 164);
    /// Light pink: secondary accents and values.
    pub const BLUSH: Rgb = Rgb(246, 172, 200);
    /// Palest pink: the peak of the shimmer.
    pub const PETAL: Rgb = Rgb(252, 218, 231);
    /// The brightest point of a glint or a twinkle - near white, pinked.
    pub const SHINE: Rgb = Rgb(255, 242, 248);
    /// Main text: a warm, pinkish white.
    pub const TEXT: Rgb = Rgb(236, 230, 234);
    /// Secondary text: details and notes.
    pub const SOFT: Rgb = Rgb(172, 160, 168);
    /// Quiet text: timings, keys, hints.
    pub const MUTED: Rgb = Rgb(118, 106, 114);
    /// Card borders: a grey with a hint of rose.
    pub const LINE: Rgb = Rgb(120, 92, 106);
    /// Unfilled progress track.
    pub const TRACK: Rgb = Rgb(66, 58, 64);
    /// Green, for additions and tips.
    pub const SAGE: Rgb = Rgb(140, 200, 160);
    /// Amber, for warnings.
    pub const AMBER: Rgb = Rgb(240, 184, 100);
    /// Red, for errors and removals.
    pub const RED: Rgb = Rgb(240, 96, 96);
}

/// Berry → rose → blush, for titles and filled progress.
pub const RAMP: [Rgb; 3] = [palette::BERRY, palette::ROSE, palette::BLUSH];

/// How much colour tinsel draws with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorMode {
    /// Plain text, no escape codes at all: piped output, `NO_COLOR`, or tests.
    None,
    /// The 256-colour palette, for terminals that don't advertise truecolor.
    Ansi256,
    /// Full 24-bit colour.
    TrueColor,
}

// 0 = not decided yet; otherwise 1 + the ColorMode's position
static MODE: AtomicU8 = AtomicU8::new(0);

/// The colour mode in use. Decided once, from `NO_COLOR`, whether stdout is a terminal, and
/// `COLORTERM`, unless [`set_color_mode`] has chosen one.
pub fn color_mode() -> ColorMode {
    match MODE.load(Ordering::Relaxed) {
        1 => ColorMode::None,
        2 => ColorMode::Ansi256,
        3 => ColorMode::TrueColor,
        _ => {
            let mode = detect();
            set_color_mode(mode);
            mode
        }
    }
}

/// Choose the colour mode yourself, for a `--color` flag or to get plain text in tests.
///
/// ```
/// tinsel::set_color_mode(tinsel::ColorMode::None);
/// assert_eq!(tinsel::paint(tinsel::palette::ROSE, "hi"), "hi");
/// ```
pub fn set_color_mode(mode: ColorMode) {
    let code = match mode {
        ColorMode::None => 1,
        ColorMode::Ansi256 => 2,
        ColorMode::TrueColor => 3,
    };
    MODE.store(code, Ordering::Relaxed);
}

fn detect() -> ColorMode {
    let no_color = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty());
    if no_color || !std::io::stdout().is_terminal() {
        return ColorMode::None;
    }
    crate::term::enable_escapes();
    match std::env::var("COLORTERM") {
        Ok(v) if v.eq_ignore_ascii_case("truecolor") || v.eq_ignore_ascii_case("24bit") => ColorMode::TrueColor,
        _ => ColorMode::Ansi256,
    }
}

/// Whether the terminal's background is dark or light. tinsel's palette is designed for dark
/// backgrounds; on light ones every colour is redrawn darker, keeping its hue, so pinks stay
/// pink and text stays readable.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Theme {
    /// Light text on a dark background.
    Dark,
    /// Dark text on a light background.
    Light,
}

// 0 = not decided yet, 1 = dark, 2 = light
static THEME: AtomicU8 = AtomicU8::new(0);

/// The theme in use. Decided once: from `TINSEL_THEME` (`light` or `dark`) if set, then the
/// `COLORFGBG` variable some terminals export, then by asking the terminal for its background
/// colour. Falls back to [`Theme::Dark`].
pub fn theme() -> Theme {
    match THEME.load(Ordering::Relaxed) {
        1 => Theme::Dark,
        2 => Theme::Light,
        _ => {
            let theme = detect_theme();
            set_theme(theme);
            theme
        }
    }
}

/// Choose the theme yourself, for a `--theme` flag or to preview the other one.
pub fn set_theme(theme: Theme) {
    THEME.store(if theme == Theme::Light { 2 } else { 1 }, Ordering::Relaxed);
}

fn detect_theme() -> Theme {
    match std::env::var("TINSEL_THEME").as_deref() {
        Ok("light") => return Theme::Light,
        Ok("dark") => return Theme::Dark,
        _ => {}
    }
    // "fg;bg" in the 16-colour palette: 7 and 9-15 are light backgrounds
    if let Some(bg) = std::env::var("COLORFGBG")
        .ok()
        .and_then(|v| v.rsplit(';').next()?.parse::<u8>().ok())
    {
        return if bg == 7 || bg > 8 { Theme::Light } else { Theme::Dark };
    }
    if color_mode() == ColorMode::None {
        return Theme::Dark;
    }
    match crate::term::query_background() {
        Some((r, g, b)) if luminance(Rgb(r, g, b)) > 0.5 => Theme::Light,
        _ => Theme::Dark,
    }
}

fn luminance(Rgb(r, g, b): Rgb) -> f32 {
    (0.2126 * r as f32 + 0.7152 * g as f32 + 0.0722 * b as f32) / 255.0
}

/// A colour redrawn for a light background: same hue, a touch more saturated, and its
/// lightness flipped so what was bright on dark (text, glints) is now the strongest contrast.
fn for_light(rgb: Rgb) -> Rgb {
    let (h, s, l) = to_hsl(rgb);
    from_hsl(h, (s * 1.1).min(1.0), 0.15 + (1.0 - l) * 0.75)
}

fn to_hsl(Rgb(r, g, b): Rgb) -> (f32, f32, f32) {
    let (r, g, b) = (r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0);
    let (max, min) = (r.max(g).max(b), r.min(g).min(b));
    let l = (max + min) / 2.0;
    if max == min {
        return (0.0, 0.0, l);
    }
    let d = max - min;
    let s = if l > 0.5 {
        d / (2.0 - max - min)
    } else {
        d / (max + min)
    };
    let h = if max == r {
        (g - b) / d + if g < b { 6.0 } else { 0.0 }
    } else if max == g {
        (b - r) / d + 2.0
    } else {
        (r - g) / d + 4.0
    };
    (h / 6.0, s, l)
}

fn from_hsl(h: f32, s: f32, l: f32) -> Rgb {
    if s == 0.0 {
        let v = (l * 255.0).round() as u8;
        return Rgb(v, v, v);
    }
    let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
    let p = 2.0 * l - q;
    let channel = |t: f32| {
        let t = t.rem_euclid(1.0);
        let v = if t < 1.0 / 6.0 {
            p + (q - p) * 6.0 * t
        } else if t < 0.5 {
            q
        } else if t < 2.0 / 3.0 {
            p + (q - p) * (2.0 / 3.0 - t) * 6.0
        } else {
            p
        };
        (v * 255.0).round() as u8
    };
    Rgb(channel(h + 1.0 / 3.0), channel(h), channel(h - 1.0 / 3.0))
}

/// Blend two colours: `t = 0` is all `a`, `t = 1` is all `b`.
pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
    let t = t.clamp(0.0, 1.0);
    let ch = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * t).round() as u8;
    Rgb(ch(a.0, b.0), ch(a.1, b.1), ch(a.2, b.2))
}

/// Sample a multi-stop gradient at t in 0..=1.
pub fn sample(stops: &[Rgb], t: f32) -> Rgb {
    match stops.len() {
        0 => palette::TEXT,
        1 => stops[0],
        n => {
            let x = t.clamp(0.0, 1.0) * (n - 1) as f32;
            let i = (x.floor() as usize).min(n - 2);
            mix(stops[i], stops[i + 1], x - i as f32)
        }
    }
}

/// The colour family tinsel's accents are drawn in. Pink is tinsel's own; the others redraw
/// every pink (accents, the spinner, the faint tint in the greys) in another hue, so a CLI can
/// match its brand. Red, amber and sage keep their meaning whatever the accent.
///
/// ```
/// tinsel::set_accent(tinsel::Accent::Blue);
/// # tinsel::set_accent(tinsel::Accent::Pink);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Accent {
    /// tinsel's own: rose, blush and berry.
    #[default]
    Pink,
    /// Lavender and plum.
    Violet,
    /// Cornflower and navy.
    Blue,
    /// Aqua and deep teal.
    Teal,
    /// Apricot and rust.
    Orange,
    /// Any hue, in degrees around the colour wheel (pink is about 338°).
    Hue(f32),
}

impl Accent {
    /// The accent with this name (`pink`, `violet`, `blue`, `teal`, `orange`), or a hue in degrees.
    pub fn from_name(name: &str) -> Option<Accent> {
        Some(match name {
            "pink" => Accent::Pink,
            "violet" | "purple" => Accent::Violet,
            "blue" => Accent::Blue,
            "teal" => Accent::Teal,
            "orange" => Accent::Orange,
            n => Accent::Hue(n.parse().ok()?),
        })
    }

    /// The hue the accent sits at, in degrees.
    fn hue(self) -> f32 {
        match self {
            Accent::Pink => PINK_HUE,
            Accent::Violet => 275.0,
            Accent::Blue => 220.0,
            Accent::Teal => 178.0,
            Accent::Orange => 24.0,
            Accent::Hue(h) => h.rem_euclid(360.0),
        }
    }
}

/// Where tinsel's pinks sit on the colour wheel.
const PINK_HUE: f32 = 338.0;

// the accent's hue in degrees as f32 bits; 0 = not decided yet
static ACCENT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// The accent in use: from `TINSEL_ACCENT` if set, otherwise [`Accent::Pink`], unless
/// [`set_accent`] has chosen one.
fn accent_hue() -> f32 {
    match ACCENT.load(Ordering::Relaxed) {
        0 => {
            let accent = std::env::var("TINSEL_ACCENT")
                .ok()
                .and_then(|n| Accent::from_name(&n))
                .unwrap_or_default();
            set_accent(accent);
            accent.hue()
        }
        bits => f32::from_bits(bits),
    }
}

/// Choose the accent colour, for a brand or a `--accent` flag.
pub fn set_accent(accent: Accent) {
    // a hue of exactly 0.0 has bits 0, which means "undecided", so nudge it
    let hue = accent.hue().max(f32::MIN_POSITIVE);
    ACCENT.store(hue.to_bits(), Ordering::Relaxed);
}

/// A colour in the accent's family. Only pinks (hues from magenta to just short of red) move;
/// everything else, red included, stays put.
fn for_accent(rgb: Rgb, hue: f32) -> Rgb {
    let (h, s, l) = to_hsl(rgb);
    let deg = h * 360.0;
    if s == 0.0 || !(295.0..354.0).contains(&deg) {
        return rgb;
    }
    from_hsl((deg + hue - PINK_HUE).rem_euclid(360.0) / 360.0, s, l)
}

/// The SGR parameters for a colour; `layer` is 38 for foreground, 48 for background.
pub(crate) fn sgr(rgb: Rgb, layer: u8) -> String {
    let hue = accent_hue();
    let rgb = if (hue - PINK_HUE).abs() > 0.5 {
        for_accent(rgb, hue)
    } else {
        rgb
    };
    let Rgb(r, g, b) = if theme() == Theme::Light { for_light(rgb) } else { rgb };
    if color_mode() == ColorMode::TrueColor {
        format!("{layer};2;{r};{g};{b}")
    } else {
        let q = |c: u8| (c as u16 * 5 + 127) / 255;
        format!("{layer};5;{}", 16 + 36 * q(r) + 6 * q(g) + q(b))
    }
}

/// Colour the text. Resets only the foreground, so it nests inside bold, backgrounds and so on.
pub fn paint(rgb: Rgb, s: &str) -> String {
    if color_mode() == ColorMode::None {
        return s.to_string();
    }
    format!("\x1b[{}m{s}\x1b[39m", sgr(rgb, 38))
}

/// Colour both the text and the cells behind it.
pub fn paint_bg(fg: Rgb, bg: Rgb, s: &str) -> String {
    if color_mode() == ColorMode::None {
        return s.to_string();
    }
    format!("\x1b[{};{}m{s}\x1b[39;49m", sgr(fg, 38), sgr(bg, 48))
}

/// Tint the cells behind the text, leaving its own colours alone.
pub(crate) fn on_bg(bg: Rgb, s: &str) -> String {
    if color_mode() == ColorMode::None {
        return s.to_string();
    }
    format!("\x1b[{}m{s}\x1b[49m", sgr(bg, 48))
}

fn attr(on: u8, off: u8, s: &str) -> String {
    if color_mode() == ColorMode::None {
        return s.to_string();
    }
    format!("\x1b[{on}m{s}\x1b[{off}m")
}

/// Bold text.
pub fn bold(s: &str) -> String {
    attr(1, 22, s)
}

/// Faint text.
pub fn dim(s: &str) -> String {
    attr(2, 22, s)
}

/// Italic text, where the terminal's font has it.
pub fn italic(s: &str) -> String {
    attr(3, 23, s)
}

/// Underlined text.
pub fn underline(s: &str) -> String {
    attr(4, 24, s)
}

/// Blinking text, animated by the terminal itself, so it keeps blinking after your program
/// has exited. Most terminals support it (iTerm2, kitty, WezTerm, Ghostty, GNOME Terminal,
/// macOS Terminal); where it's turned off or unsupported, the text simply stays still. Best
/// kept to a single mark: a whole line blinking is hard to read.
///
/// ```
/// println!("  {} ready", tinsel::blink(&tinsel::paint(tinsel::palette::ROSE, "✦")));
/// ```
pub fn blink(s: &str) -> String {
    attr(5, 25, s)
}

/// Colour s across the stops; a non-zero shift slides the gradient back and forth.
pub fn gradient(s: &str, stops: &[Rgb], shift: f32) -> String {
    let n = s.chars().count().saturating_sub(1).max(1) as f32;
    s.chars()
        .enumerate()
        .map(|(i, c)| {
            let t = (i as f32 / n + shift).rem_euclid(2.0);
            paint(
                sample(stops, if t > 1.0 { 2.0 - t } else { t }),
                c.encode_utf8(&mut [0; 4]),
            )
        })
        .collect()
}

/// A painted string that remembers its visible width, so it can be padded and aligned.
#[derive(Clone, Debug, Default)]
pub struct Line {
    text: String,
    width: usize,
}

impl Line {
    /// An empty line.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add text in a colour.
    pub fn push(mut self, s: &str, rgb: Rgb) -> Self {
        self.text += &paint(rgb, s);
        self.width += crate::text::width(s);
        self
    }

    /// Append text that's already styled (a badge, a link); its width is measured without the codes.
    pub fn raw(mut self, styled: &str) -> Self {
        self.text += styled;
        self.width += crate::text::width(styled);
        self
    }

    /// Add another line's text to the end of this one.
    pub fn append(mut self, other: Line) -> Self {
        self.text += &other.text;
        self.width += other.width;
        self
    }

    /// Add `n` spaces.
    pub fn space(mut self, n: usize) -> Self {
        self.text += &" ".repeat(n);
        self.width += n;
        self
    }

    /// A muted, aligned key followed by a value - the row shape cards are built from.
    pub fn kv(key: &str, value: &str, color: Rgb) -> Self {
        Line::new()
            .push(&format!("{key:<10}"), palette::MUTED)
            .push(value, color)
    }

    /// How many columns the line takes up on screen.
    pub fn width(&self) -> usize {
        self.width
    }
}

impl fmt::Display for Line {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hsl_round_trips() {
        for c in [
            palette::ROSE,
            palette::TEXT,
            palette::SAGE,
            palette::TRACK,
            Rgb(0, 0, 0),
            Rgb(255, 255, 255),
        ] {
            let (h, s, l) = to_hsl(c);
            let back = from_hsl(h, s, l);
            assert!(
                c.0.abs_diff(back.0) <= 1 && c.1.abs_diff(back.1) <= 1 && c.2.abs_diff(back.2) <= 1,
                "{c:?}"
            );
        }
    }

    #[test]
    fn light_theme_darkens_text_and_keeps_pinks_pink() {
        assert!(luminance(for_light(palette::TEXT)) < 0.3);
        let rose = for_light(palette::ROSE);
        assert!(rose.0 > rose.1 && rose.0 > rose.2, "still reddest: {rose:?}");
        assert!(luminance(rose) < luminance(palette::ROSE));
        // the track goes from dark grey to light grey
        assert!(luminance(for_light(palette::TRACK)) > 0.6);
    }

    #[test]
    fn accents_move_pinks_and_leave_signal_colours() {
        let blue = for_accent(palette::ROSE, 220.0);
        assert!(blue.2 > blue.0, "rose turned blue: {blue:?}");
        assert_eq!(for_accent(palette::RED, 220.0), palette::RED);
        assert_eq!(for_accent(palette::AMBER, 220.0), palette::AMBER);
        assert_eq!(for_accent(palette::SAGE, 220.0), palette::SAGE);
        assert_eq!(Accent::from_name("200"), Some(Accent::Hue(200.0)));
    }
}