superlighttui 0.18.2

Super Light TUI - A lightweight, ergonomic terminal UI library
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
/// Terminal color.
///
/// Covers the standard 16 named colors, 256-color palette indices, and
/// 24-bit RGB true color. Use [`Color::Reset`] to restore the terminal's
/// default foreground or background.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Color {
    /// Reset to the terminal's default color.
    Reset,
    /// Standard black (color index 0).
    Black,
    /// Standard red (color index 1).
    Red,
    /// Standard green (color index 2).
    Green,
    /// Standard yellow (color index 3).
    Yellow,
    /// Standard blue (color index 4).
    Blue,
    /// Standard magenta (color index 5).
    Magenta,
    /// Standard cyan (color index 6).
    Cyan,
    /// Standard white (color index 7).
    White,
    /// Bright black / dark gray (color index 8).
    DarkGray,
    /// Bright red (color index 9).
    LightRed,
    /// Bright green (color index 10).
    LightGreen,
    /// Bright yellow (color index 11).
    LightYellow,
    /// Bright blue (color index 12).
    LightBlue,
    /// Bright magenta (color index 13).
    LightMagenta,
    /// Bright cyan (color index 14).
    LightCyan,
    /// Bright white (color index 15).
    LightWhite,
    /// 24-bit true color.
    Rgb(u8, u8, u8),
    /// 256-color palette index.
    Indexed(u8),
}

impl Color {
    /// Resolve to `(r, g, b)` for luminance and blending operations.
    ///
    /// Named colors map to their typical terminal palette values.
    /// [`Color::Reset`] maps to black; [`Color::Indexed`] maps to the xterm-256 palette.
    fn to_rgb(self) -> (u8, u8, u8) {
        match self {
            Color::Rgb(r, g, b) => (r, g, b),
            Color::Black => (0, 0, 0),
            Color::Red => (205, 49, 49),
            Color::Green => (13, 188, 121),
            Color::Yellow => (229, 229, 16),
            Color::Blue => (36, 114, 200),
            Color::Magenta => (188, 63, 188),
            Color::Cyan => (17, 168, 205),
            Color::White => (229, 229, 229),
            Color::DarkGray => (128, 128, 128),
            Color::LightRed => (255, 0, 0),
            Color::LightGreen => (0, 255, 0),
            Color::LightYellow => (255, 255, 0),
            Color::LightBlue => (0, 0, 255),
            Color::LightMagenta => (255, 0, 255),
            Color::LightCyan => (0, 255, 255),
            Color::LightWhite => (255, 255, 255),
            Color::Reset => (0, 0, 0),
            Color::Indexed(idx) => xterm256_to_rgb(idx),
        }
    }

    /// Compute relative luminance using ITU-R BT.709 coefficients.
    ///
    /// Returns a value in `[0.0, 1.0]` where 0 is darkest and 1 is brightest.
    /// Use this to determine whether text on a given background should be
    /// light or dark.
    ///
    /// # Example
    ///
    /// ```
    /// use slt::Color;
    ///
    /// let dark = Color::Rgb(30, 30, 46);
    /// assert!(dark.luminance() < 0.15);
    ///
    /// let light = Color::Rgb(205, 214, 244);
    /// assert!(light.luminance() > 0.6);
    /// ```
    pub fn luminance(self) -> f32 {
        let (r, g, b) = self.to_rgb();
        let rf = r as f32 / 255.0;
        let gf = g as f32 / 255.0;
        let bf = b as f32 / 255.0;
        0.2126 * rf + 0.7152 * gf + 0.0722 * bf
    }

    /// Return a contrasting foreground color for the given background.
    ///
    /// Uses the BT.709 luminance threshold (0.5) to decide between white
    /// and black text. For theme-aware contrast, prefer using this over
    /// hardcoding `theme.bg` as the foreground.
    ///
    /// # Example
    ///
    /// ```
    /// use slt::Color;
    ///
    /// let bg = Color::Rgb(189, 147, 249); // Dracula purple
    /// let fg = Color::contrast_fg(bg);
    /// // Purple is mid-bright → returns black for readable text
    /// ```
    pub fn contrast_fg(bg: Color) -> Color {
        if bg.luminance() > 0.5 {
            Color::Rgb(0, 0, 0)
        } else {
            Color::Rgb(255, 255, 255)
        }
    }

    /// Blend this color over another with the given alpha.
    ///
    /// `alpha` is in `[0.0, 1.0]` where 0.0 returns `other` unchanged and
    /// 1.0 returns `self` unchanged. Both colors are resolved to RGB.
    ///
    /// # Example
    ///
    /// ```
    /// use slt::Color;
    ///
    /// let white = Color::Rgb(255, 255, 255);
    /// let black = Color::Rgb(0, 0, 0);
    /// let gray = white.blend(black, 0.5);
    /// // ≈ Rgb(128, 128, 128)
    /// ```
    pub fn blend(self, other: Color, alpha: f32) -> Color {
        let alpha = alpha.clamp(0.0, 1.0);
        let (r1, g1, b1) = self.to_rgb();
        let (r2, g2, b2) = other.to_rgb();
        let r = (r1 as f32 * alpha + r2 as f32 * (1.0 - alpha)).round() as u8;
        let g = (g1 as f32 * alpha + g2 as f32 * (1.0 - alpha)).round() as u8;
        let b = (b1 as f32 * alpha + b2 as f32 * (1.0 - alpha)).round() as u8;
        Color::Rgb(r, g, b)
    }

    /// Lighten this color by the given amount (0.0–1.0).
    ///
    /// Blends toward white. `amount = 0.0` returns the original color;
    /// `amount = 1.0` returns white.
    pub fn lighten(self, amount: f32) -> Color {
        Color::Rgb(255, 255, 255).blend(self, 1.0 - amount.clamp(0.0, 1.0))
    }

    /// Darken this color by the given amount (0.0–1.0).
    ///
    /// Blends toward black. `amount = 0.0` returns the original color;
    /// `amount = 1.0` returns black.
    pub fn darken(self, amount: f32) -> Color {
        Color::Rgb(0, 0, 0).blend(self, 1.0 - amount.clamp(0.0, 1.0))
    }

    /// Compute the WCAG 2.1 contrast ratio between two colors.
    ///
    /// Returns a value >= 1.0. A ratio >= 4.5 meets WCAG AA for normal text;
    /// >= 3.0 meets AA for large text.
    ///
    /// # Example
    ///
    /// ```
    /// use slt::Color;
    ///
    /// let ratio = Color::contrast_ratio(Color::White, Color::Black);
    /// assert!(ratio > 15.0);
    /// ```
    pub fn contrast_ratio(a: Color, b: Color) -> f32 {
        let la = a.luminance() + 0.05;
        let lb = b.luminance() + 0.05;
        if la > lb {
            la / lb
        } else {
            lb / la
        }
    }

    /// Returns `true` if the contrast ratio between two colors meets WCAG AA
    /// for normal text (ratio >= 4.5).
    pub fn meets_contrast_aa(fg: Color, bg: Color) -> bool {
        Self::contrast_ratio(fg, bg) >= 4.5
    }

    /// Downsample this color to fit the given color depth.
    ///
    /// - `TrueColor`: returns self unchanged.
    /// - `EightBit`: converts `Rgb` to the nearest `Indexed` color.
    /// - `Basic`: converts `Rgb` and `Indexed` to the nearest named color.
    /// - `NoColor`: returns [`Color::Reset`] — emit no ANSI color at all.
    ///
    /// Named colors (`Red`, `Green`, etc.) and `Reset` pass through at
    /// depths other than `NoColor`.
    pub fn downsampled(self, depth: ColorDepth) -> Color {
        match depth {
            ColorDepth::TrueColor => self,
            ColorDepth::EightBit => match self {
                Color::Rgb(r, g, b) => Color::Indexed(rgb_to_ansi256(r, g, b)),
                other => other,
            },
            ColorDepth::Basic => match self {
                Color::Rgb(r, g, b) => rgb_to_ansi16(r, g, b),
                Color::Indexed(i) => {
                    let (r, g, b) = xterm256_to_rgb(i);
                    rgb_to_ansi16(r, g, b)
                }
                other => other,
            },
            ColorDepth::NoColor => Color::Reset,
        }
    }
}

/// Terminal color depth capability.
///
/// Determines the maximum number of colors a terminal can display.
/// Use [`ColorDepth::detect`] for automatic detection via environment
/// variables, or specify explicitly in [`crate::RunConfig`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ColorDepth {
    /// 24-bit true color (16 million colors).
    TrueColor,
    /// 256-color palette (xterm-256color).
    EightBit,
    /// 16 basic ANSI colors.
    Basic,
    /// No color output — every color is downsampled to [`Color::Reset`] and
    /// the terminal emits no SGR color codes. Selected automatically by
    /// [`ColorDepth::detect`] when the `NO_COLOR` environment variable is
    /// set to any non-empty value, per <https://no-color.org>.
    NoColor,
}

#[cfg(test)]
mod color_depth_tests {
    use super::{Color, ColorDepth};

    #[test]
    fn no_color_downsamples_everything_to_reset() {
        assert_eq!(Color::Red.downsampled(ColorDepth::NoColor), Color::Reset);
        assert_eq!(
            Color::Rgb(10, 20, 30).downsampled(ColorDepth::NoColor),
            Color::Reset
        );
        assert_eq!(
            Color::Indexed(44).downsampled(ColorDepth::NoColor),
            Color::Reset
        );
    }
}

impl ColorDepth {
    /// Detect the terminal's color depth from environment variables.
    ///
    /// Order of precedence:
    /// 1. `NO_COLOR` (any non-empty value) → [`ColorDepth::NoColor`]
    /// 2. `COLORTERM=truecolor|24bit` → [`ColorDepth::TrueColor`]
    /// 3. `TERM` contains `256color` → [`ColorDepth::EightBit`]
    /// 4. Fallback → [`ColorDepth::Basic`] (16 colors)
    pub fn detect() -> Self {
        // https://no-color.org — ANY non-empty value disables color.
        if std::env::var("NO_COLOR")
            .ok()
            .is_some_and(|v| !v.is_empty())
        {
            return Self::NoColor;
        }
        if let Ok(ct) = std::env::var("COLORTERM") {
            let ct = ct.to_lowercase();
            if ct == "truecolor" || ct == "24bit" {
                return Self::TrueColor;
            }
        }
        if let Ok(term) = std::env::var("TERM") {
            if term.contains("256color") {
                return Self::EightBit;
            }
        }
        Self::Basic
    }
}

fn rgb_to_ansi256(r: u8, g: u8, b: u8) -> u8 {
    if r == g && g == b {
        if r < 8 {
            return 16;
        }
        if r > 248 {
            return 231;
        }
        return 232 + (((r as u16 - 8) * 24 / 240) as u8);
    }

    let ri = if r < 48 {
        0
    } else {
        ((r as u16 - 35) / 40) as u8
    };
    let gi = if g < 48 {
        0
    } else {
        ((g as u16 - 35) / 40) as u8
    };
    let bi = if b < 48 {
        0
    } else {
        ((b as u16 - 35) / 40) as u8
    };
    16 + 36 * ri.min(5) + 6 * gi.min(5) + bi.min(5)
}

fn rgb_to_ansi16(r: u8, g: u8, b: u8) -> Color {
    let lum =
        0.2126 * (r as f32 / 255.0) + 0.7152 * (g as f32 / 255.0) + 0.0722 * (b as f32 / 255.0);

    let max = r.max(g).max(b);
    let min = r.min(g).min(b);
    let saturation = if max == 0 {
        0.0
    } else {
        (max - min) as f32 / max as f32
    };

    if saturation < 0.2 {
        return if lum < 0.15 {
            Color::Black
        } else {
            Color::White
        };
    }

    let rf = r as f32;
    let gf = g as f32;
    let bf = b as f32;

    if rf >= gf && rf >= bf {
        if gf > bf * 1.5 {
            Color::Yellow
        } else if bf > gf * 1.5 {
            Color::Magenta
        } else {
            Color::Red
        }
    } else if gf >= rf && gf >= bf {
        if bf > rf * 1.5 {
            Color::Cyan
        } else {
            Color::Green
        }
    } else if rf > gf * 1.5 {
        Color::Magenta
    } else if gf > rf * 1.5 {
        Color::Cyan
    } else {
        Color::Blue
    }
}

fn xterm256_to_rgb(idx: u8) -> (u8, u8, u8) {
    match idx {
        0 => (0, 0, 0),
        1 => (128, 0, 0),
        2 => (0, 128, 0),
        3 => (128, 128, 0),
        4 => (0, 0, 128),
        5 => (128, 0, 128),
        6 => (0, 128, 128),
        7 => (192, 192, 192),
        8 => (128, 128, 128),
        9 => (255, 0, 0),
        10 => (0, 255, 0),
        11 => (255, 255, 0),
        12 => (0, 0, 255),
        13 => (255, 0, 255),
        14 => (0, 255, 255),
        15 => (255, 255, 255),
        16..=231 => {
            let n = idx - 16;
            let b_idx = n % 6;
            let g_idx = (n / 6) % 6;
            let r_idx = n / 36;
            let to_val = |i: u8| if i == 0 { 0u8 } else { 55 + 40 * i };
            (to_val(r_idx), to_val(g_idx), to_val(b_idx))
        }
        232..=255 => {
            let v = 8 + 10 * (idx - 232);
            (v, v, v)
        }
    }
}

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

    #[test]
    fn blend_halfway_rounds_to_128() {
        assert_eq!(
            Color::Rgb(255, 255, 255).blend(Color::Rgb(0, 0, 0), 0.5),
            Color::Rgb(128, 128, 128)
        );
    }

    #[test]
    fn contrast_ratio_white_on_black_is_high() {
        let ratio = Color::contrast_ratio(Color::White, Color::Black);
        assert!(ratio > 15.0);
    }

    #[test]
    fn contrast_ratio_same_color_is_one() {
        let ratio = Color::contrast_ratio(Color::Rgb(100, 100, 100), Color::Rgb(100, 100, 100));
        assert!((ratio - 1.0).abs() < 0.01);
    }

    #[test]
    fn meets_contrast_aa_white_on_black() {
        assert!(Color::meets_contrast_aa(Color::White, Color::Black));
    }

    #[test]
    fn meets_contrast_aa_low_contrast_fails() {
        assert!(!Color::meets_contrast_aa(
            Color::Rgb(180, 180, 180),
            Color::Rgb(200, 200, 200)
        ));
    }
}