gilt 0.5.0

A fast, rich terminal formatting library — Rust port of Python's rich
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
//! True color gradient rendering across text.
//!
//! This module provides the [`Gradient`] widget that creates smoothly
//! interpolated color gradients across text, supporting multi-stop
//! gradients, rainbow presets, and per-character color blending.
//!
//! # Example
//!
//! ```rust
//! use gilt::gradient::Gradient;
//! use gilt::color::Color;
//!
//! // Two-color gradient from red to blue
//! let g = Gradient::two_color("Hello, world!", Color::from_rgb(255, 0, 0), Color::from_rgb(0, 0, 255));
//!
//! // Rainbow gradient
//! let g = Gradient::rainbow("All the colors!");
//! ```

use crate::color::Color;
use crate::console::{Console, ConsoleOptions, Renderable};
use crate::segment::Segment;
use crate::style::Style;
use crate::text::JustifyMethod;

// ---------------------------------------------------------------------------
// Color interpolation
// ---------------------------------------------------------------------------

/// Linearly interpolates between two colors at parameter `t` (0.0 = c1, 1.0 = c2).
///
/// Both colors are resolved to RGB triplets (truecolor) and each channel is
/// interpolated independently.  The result is always a `Color::TrueColor`.
fn interpolate_color(c1: &Color, c2: &Color, t: f64) -> Color {
    let t = t.clamp(0.0, 1.0);
    let t1 = c1.get_truecolor(None, true);
    let t2 = c2.get_truecolor(None, true);

    let r = (t1.red as f64 + (t2.red as f64 - t1.red as f64) * t).round() as u8;
    let g = (t1.green as f64 + (t2.green as f64 - t1.green as f64) * t).round() as u8;
    let b = (t1.blue as f64 + (t2.blue as f64 - t1.blue as f64) * t).round() as u8;

    Color::from_rgb(r, g, b)
}

// ---------------------------------------------------------------------------
// Gradient
// ---------------------------------------------------------------------------

/// A text widget that renders with a smooth color gradient across characters.
///
/// The gradient distributes the given color stops evenly across the text
/// length and interpolates between adjacent stops for each character.
#[derive(Debug, Clone)]
pub struct Gradient {
    /// The plain text to render.
    pub text: String,
    /// Gradient color stops (at least 2 for a visible gradient).
    pub colors: Vec<Color>,
    /// Base style applied to every character (bold, italic, etc.).
    /// The foreground color in this style is *overridden* by the gradient.
    pub style: Style,
    /// Optional text justification.
    pub justify: Option<JustifyMethod>,
}

impl Gradient {
    // -- constructors -------------------------------------------------------

    /// Creates a new `Gradient` with the given text and color stops.
    ///
    /// At least two colors should be provided; with fewer than two the text
    /// will render in a single color (the first stop, or default if empty).
    pub fn new(text: &str, colors: Vec<Color>) -> Self {
        Self {
            text: text.to_string(),
            colors,
            style: Style::null(),
            justify: None,
        }
    }

    /// Creates a simple two-color gradient.
    pub fn two_color(text: &str, start: Color, end: Color) -> Self {
        Self::new(text, vec![start, end])
    }

    /// Creates a rainbow gradient (red -> orange -> yellow -> green -> cyan -> blue -> violet).
    pub fn rainbow(text: &str) -> Self {
        Self::new(
            text,
            vec![
                Color::from_rgb(255, 0, 0),   // red
                Color::from_rgb(255, 165, 0), // orange
                Color::from_rgb(255, 255, 0), // yellow
                Color::from_rgb(0, 255, 0),   // green
                Color::from_rgb(0, 255, 255), // cyan
                Color::from_rgb(0, 0, 255),   // blue
                Color::from_rgb(148, 0, 211), // violet
            ],
        )
    }

    // -- builder methods ----------------------------------------------------

    /// Sets the base style for the gradient text.
    #[must_use]
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Sets the text justification.
    #[must_use]
    pub fn with_justify(mut self, justify: JustifyMethod) -> Self {
        self.justify = Some(justify);
        self
    }

    // -- internal helpers ---------------------------------------------------

    /// Computes the interpolated color for position `index` out of `total`
    /// characters, distributing `self.colors` evenly.
    fn color_at(&self, index: usize, total: usize) -> Color {
        if self.colors.is_empty() {
            return Color::default_color();
        }
        if self.colors.len() == 1 || total <= 1 {
            return self.colors[0].clone();
        }

        let t = index as f64 / (total - 1) as f64; // 0.0 .. 1.0
        let segments = self.colors.len() - 1;
        let scaled = t * segments as f64;
        let seg = (scaled.floor() as usize).min(segments - 1);
        let local_t = scaled - seg as f64;

        interpolate_color(&self.colors[seg], &self.colors[seg + 1], local_t)
    }

    /// Renders a single line of text into gradient-colored segments.
    fn render_line(&self, line: &str, style: &Style) -> Vec<Segment> {
        let chars: Vec<char> = line.chars().collect();
        let total = chars.len();
        if total == 0 {
            return Vec::new();
        }

        let mut segments = Vec::with_capacity(total);
        for (i, ch) in chars.iter().enumerate() {
            let fg = self.color_at(i, total);
            let char_style = Style::from_color(Some(fg), None) + style.clone();
            segments.push(Segment::styled(&ch.to_string(), char_style));
        }
        segments
    }
}

// ---------------------------------------------------------------------------
// Renderable
// ---------------------------------------------------------------------------

impl Renderable for Gradient {
    fn rich_console(&self, _console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        let justify = self.justify.or(options.justify);

        let lines: Vec<&str> = self.text.split('\n').collect();
        let mut all_segments = Vec::new();

        for (line_idx, line) in lines.iter().enumerate() {
            let mut line_segs = self.render_line(line, &self.style);

            // Apply justification if requested
            if let Some(just) = justify {
                let line_len = line.chars().count();
                if line_len < options.max_width {
                    let padding = options.max_width - line_len;
                    match just {
                        JustifyMethod::Center => {
                            let left = padding / 2;
                            let right = padding - left;
                            let mut padded =
                                vec![Segment::styled(&" ".repeat(left), self.style.clone())];
                            padded.append(&mut line_segs);
                            padded.push(Segment::styled(&" ".repeat(right), self.style.clone()));
                            line_segs = padded;
                        }
                        JustifyMethod::Right => {
                            let mut padded =
                                vec![Segment::styled(&" ".repeat(padding), self.style.clone())];
                            padded.append(&mut line_segs);
                            line_segs = padded;
                        }
                        JustifyMethod::Left | JustifyMethod::Full | JustifyMethod::Default => {
                            // Left-align: pad on the right
                            line_segs
                                .push(Segment::styled(&" ".repeat(padding), self.style.clone()));
                        }
                    }
                }
            }

            all_segments.append(&mut line_segs);

            // Add newline between lines (and after the last line)
            if line_idx < lines.len() - 1 {
                all_segments.push(Segment::line());
            }
        }

        // Trailing newline
        all_segments.push(Segment::new("\n", None, None));

        all_segments
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

impl std::fmt::Display for Gradient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut console = Console::builder()
            .width(f.width().unwrap_or(80))
            .force_terminal(true)
            .no_color(true)
            .build();
        console.begin_capture();
        console.print(self);
        let output = console.end_capture();
        write!(f, "{}", output.trim_end_matches('\n'))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_two_color_gradient_segment_count() {
        let g = Gradient::two_color(
            "Hello",
            Color::from_rgb(255, 0, 0),
            Color::from_rgb(0, 0, 255),
        );
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);
        // 5 char segments + 1 trailing newline
        assert_eq!(segments.len(), 6);
        // First 5 segments should each be one character
        for seg in &segments[..5] {
            assert_eq!(seg.text.chars().count(), 1);
        }
    }

    #[test]
    fn test_rainbow_gradient_works() {
        let g = Gradient::rainbow("Rainbow!");
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);
        // 8 characters + 1 trailing newline
        assert_eq!(segments.len(), 9);
    }

    #[test]
    fn test_interpolation_at_zero() {
        let c1 = Color::from_rgb(255, 0, 0);
        let c2 = Color::from_rgb(0, 0, 255);
        let result = interpolate_color(&c1, &c2, 0.0);
        let triplet = result.get_truecolor(None, true);
        assert_eq!(triplet, ColorTriplet::new(255, 0, 0));
    }

    #[test]
    fn test_interpolation_at_one() {
        let c1 = Color::from_rgb(255, 0, 0);
        let c2 = Color::from_rgb(0, 0, 255);
        let result = interpolate_color(&c1, &c2, 1.0);
        let triplet = result.get_truecolor(None, true);
        assert_eq!(triplet, ColorTriplet::new(0, 0, 255));
    }

    #[test]
    fn test_interpolation_at_midpoint() {
        let c1 = Color::from_rgb(0, 0, 0);
        let c2 = Color::from_rgb(254, 100, 200);
        let result = interpolate_color(&c1, &c2, 0.5);
        let triplet = result.get_truecolor(None, true);
        assert_eq!(triplet, ColorTriplet::new(127, 50, 100));
    }

    #[test]
    fn test_multi_stop_gradient_distributes_evenly() {
        // Red -> Green -> Blue, 5 characters
        let g = Gradient::new(
            "ABCDE",
            vec![
                Color::from_rgb(255, 0, 0),
                Color::from_rgb(0, 255, 0),
                Color::from_rgb(0, 0, 255),
            ],
        );
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);

        // First character should be red
        let first_style = segments[0].style.as_ref().unwrap();
        let first_fg = first_style.color().unwrap().get_truecolor(None, true);
        assert_eq!(first_fg, ColorTriplet::new(255, 0, 0));

        // Middle character (index 2, t=0.5) should be green
        let mid_style = segments[2].style.as_ref().unwrap();
        let mid_fg = mid_style.color().unwrap().get_truecolor(None, true);
        assert_eq!(mid_fg, ColorTriplet::new(0, 255, 0));

        // Last character should be blue
        let last_style = segments[4].style.as_ref().unwrap();
        let last_fg = last_style.color().unwrap().get_truecolor(None, true);
        assert_eq!(last_fg, ColorTriplet::new(0, 0, 255));
    }

    #[test]
    fn test_empty_text_produces_empty_segments() {
        let g = Gradient::two_color("", Color::from_rgb(255, 0, 0), Color::from_rgb(0, 0, 255));
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);
        // Only the trailing newline
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0].text, "\n");
    }

    #[test]
    fn test_single_character_text() {
        let g = Gradient::two_color(
            "X",
            Color::from_rgb(100, 200, 50),
            Color::from_rgb(0, 0, 255),
        );
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);
        // 1 char segment + 1 trailing newline
        assert_eq!(segments.len(), 2);
        assert_eq!(segments[0].text, "X");
        // Single char: uses the first color stop
        let fg = segments[0]
            .style
            .as_ref()
            .unwrap()
            .color()
            .unwrap()
            .get_truecolor(None, true);
        assert_eq!(fg, ColorTriplet::new(100, 200, 50));
    }

    #[test]
    fn test_gradient_with_newlines() {
        let g = Gradient::two_color(
            "AB\nCD",
            Color::from_rgb(255, 0, 0),
            Color::from_rgb(0, 0, 255),
        );
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);

        // Line 1: A, B | newline | Line 2: C, D | trailing newline
        // = 2 + 1 + 2 + 1 = 6
        assert_eq!(segments.len(), 6);
        assert_eq!(segments[0].text, "A");
        assert_eq!(segments[1].text, "B");
        assert_eq!(segments[2].text, "\n");
        assert_eq!(segments[3].text, "C");
        assert_eq!(segments[4].text, "D");
        assert_eq!(segments[5].text, "\n");

        // Each line has its own gradient: A is red(ish), B is blue(ish)
        let a_fg = segments[0]
            .style
            .as_ref()
            .unwrap()
            .color()
            .unwrap()
            .get_truecolor(None, true);
        let b_fg = segments[1]
            .style
            .as_ref()
            .unwrap()
            .color()
            .unwrap()
            .get_truecolor(None, true);
        assert_eq!(a_fg, ColorTriplet::new(255, 0, 0));
        assert_eq!(b_fg, ColorTriplet::new(0, 0, 255));
    }

    #[test]
    fn test_display_trait_works() {
        let g = Gradient::two_color("Hi", Color::from_rgb(255, 0, 0), Color::from_rgb(0, 0, 255));
        // Display with no_color=true via the fmt implementation
        let output = format!("{}", g);
        assert_eq!(output, "Hi");
    }

    #[test]
    fn test_builder_methods() {
        let g = Gradient::rainbow("test")
            .with_style(
                Style::new(
                    None,
                    None,
                    Some(true),
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                .unwrap(),
            )
            .with_justify(JustifyMethod::Center);

        assert_eq!(g.text, "test");
        assert_eq!(g.colors.len(), 7);
        assert_eq!(g.justify, Some(JustifyMethod::Center));
        assert_eq!(g.style.bold(), Some(true));
    }

    #[test]
    fn test_no_colors_uses_default() {
        let g = Gradient::new("Hi", vec![]);
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);
        // 2 chars + trailing newline
        assert_eq!(segments.len(), 3);
    }

    #[test]
    fn test_single_color_stop() {
        let g = Gradient::new("ABC", vec![Color::from_rgb(0, 128, 255)]);
        let console = Console::builder().width(80).force_terminal(true).build();
        let options = console.options();
        let segments = g.rich_console(&console, &options);
        // All chars get the same color
        for seg in &segments[..3] {
            let fg = seg
                .style
                .as_ref()
                .unwrap()
                .color()
                .unwrap()
                .get_truecolor(None, true);
            assert_eq!(fg, ColorTriplet::new(0, 128, 255));
        }
    }

    #[test]
    fn test_interpolation_clamped() {
        let c1 = Color::from_rgb(255, 0, 0);
        let c2 = Color::from_rgb(0, 0, 255);
        // Out-of-range t values should be clamped
        let below = interpolate_color(&c1, &c2, -0.5);
        let above = interpolate_color(&c1, &c2, 1.5);
        assert_eq!(
            below.get_truecolor(None, true),
            ColorTriplet::new(255, 0, 0)
        );
        assert_eq!(
            above.get_truecolor(None, true),
            ColorTriplet::new(0, 0, 255)
        );
    }
}