superlighttui 0.22.0

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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
use super::*;
use crate::KeyMap;

impl Context {
    /// Render a text element. Returns `&mut Self` for style chaining.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// ui.text("hello").bold().fg(Color::Cyan);
    /// # });
    /// ```
    pub fn text(&mut self, s: impl Into<String>) -> &mut Self {
        let content = s.into();
        let default_fg = self
            .rollback
            .text_color_stack
            .iter()
            .rev()
            .find_map(|c| *c)
            .unwrap_or(self.theme.text);
        self.commands.push(Command::Text {
            content,
            cursor_offset: None,
            style: Style::new().fg(default_fg),
            grow: 0,
            align: Align::Start,
            wrap: false,
            truncate: false,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Render a clickable hyperlink.
    ///
    /// The link is interactive: clicking it (or pressing Enter/Space when
    /// focused) opens the URL in the system browser. OSC 8 is also emitted
    /// for terminals that support native hyperlinks.
    #[allow(clippy::print_stderr)]
    pub fn link(&mut self, text: impl Into<String>, url: impl Into<String>) -> &mut Self {
        let url_str = url.into();
        let focused = self.register_focusable();
        let (_interaction_id, response) = self.begin_widget_interaction(focused);

        let activated = response.clicked || self.consume_activation_keys(focused);

        if activated && let Err(e) = open_url(&url_str) {
            eprintln!("[slt] failed to open URL: {e}");
        }

        let style = if focused {
            Style::new()
                .fg(self.theme.primary)
                .bg(self.theme.surface_hover)
                .underline()
                .bold()
        } else if response.hovered {
            Style::new()
                .fg(self.theme.accent)
                .bg(self.theme.surface_hover)
                .underline()
        } else {
            Style::new().fg(self.theme.primary).underline()
        };

        self.commands.push(Command::Link {
            text: text.into(),
            url: url_str,
            style,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Render an elapsed time display.
    ///
    /// Formats as `HH:MM:SS.CC` when hours are non-zero, otherwise `MM:SS.CC`.
    pub fn timer_display(&mut self, elapsed: std::time::Duration) -> &mut Self {
        let total_centis = elapsed.as_millis() / 10;
        let centis = total_centis % 100;
        let total_seconds = total_centis / 100;
        let seconds = total_seconds % 60;
        let minutes = (total_seconds / 60) % 60;
        let hours = total_seconds / 3600;

        let content = if hours > 0 {
            format!("{hours:02}:{minutes:02}:{seconds:02}.{centis:02}")
        } else {
            format!("{minutes:02}:{seconds:02}.{centis:02}")
        };

        self.commands.push(Command::Text {
            content,
            cursor_offset: None,
            style: Style::new().fg(self.theme.text),
            grow: 0,
            align: Align::Start,
            wrap: false,
            truncate: false,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Render help bar from a KeyMap. Shows visible bindings as key-description pairs.
    pub fn help_from_keymap(&mut self, keymap: &KeyMap) -> Response {
        let pairs: Vec<(&str, &str)> = keymap
            .visible_bindings()
            .map(|binding| (binding.display.as_str(), binding.description.as_str()))
            .collect();
        self.help(&pairs)
    }

    // ── style chain (applies to last text) ───────────────────────────

    /// Apply bold to the last rendered text element.
    pub fn bold(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::BOLD);
        self
    }

    /// Apply dim styling to the last rendered text element.
    ///
    /// Also sets the foreground color to the theme's `text_dim` color if no
    /// explicit foreground has been set.
    pub fn dim(&mut self) -> &mut Self {
        let text_dim = self.theme.text_dim;
        self.modify_last_style(|s| {
            s.modifiers |= Modifiers::DIM;
            if s.fg.is_none() {
                s.fg = Some(text_dim);
            }
        });
        self
    }

    /// Apply italic to the last rendered text element.
    pub fn italic(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::ITALIC);
        self
    }

    /// Apply underline to the last rendered text element.
    pub fn underline(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::UNDERLINE);
        self
    }

    /// Apply reverse-video to the last rendered text element.
    pub fn reversed(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::REVERSED);
        self
    }

    /// Apply strikethrough to the last rendered text element.
    pub fn strikethrough(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::STRIKETHROUGH);
        self
    }

    /// Set the foreground color of the last rendered text element.
    pub fn fg(&mut self, color: Color) -> &mut Self {
        self.modify_last_style(|s| s.fg = Some(color));
        self
    }

    /// Set the background color of the last rendered text element.
    pub fn bg(&mut self, color: Color) -> &mut Self {
        self.modify_last_style(|s| s.bg = Some(color));
        self
    }

    /// Apply a per-character foreground gradient to the last rendered text.
    pub fn gradient(&mut self, from: Color, to: Color) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx {
            let replacement = match &self.commands[idx] {
                Command::Text {
                    content,
                    style,
                    wrap,
                    align,
                    margin,
                    constraints,
                    ..
                } => {
                    let chars: Vec<char> = content.chars().collect();
                    let len = chars.len();
                    let denom = len.saturating_sub(1).max(1) as f32;
                    let segments = chars
                        .into_iter()
                        .enumerate()
                        .map(|(i, ch)| {
                            let mut seg_style = *style;
                            seg_style.fg = Some(from.blend(to, i as f32 / denom));
                            (ch.to_string(), seg_style)
                        })
                        .collect();

                    Some(Command::RichText {
                        segments,
                        wrap: *wrap,
                        align: *align,
                        margin: *margin,
                        constraints: *constraints,
                    })
                }
                _ => None,
            };

            if let Some(command) = replacement {
                self.commands[idx] = command;
            }
        }

        self
    }

    /// Apply a per-character multi-stop foreground gradient to the last text.
    ///
    /// `stops` is a slice of `(position, color)` pairs where `position` lies in
    /// `0.0..=1.0`. Stops do not need to be pre-sorted. The text is colored by
    /// linearly interpolating between adjacent stops across its displayed
    /// columns, using the same column-mapping and clamping as [`gradient`].
    ///
    /// - An empty slice is a no-op (the text keeps its current style).
    /// - A single stop produces a solid color.
    ///
    /// [`gradient`]: Self::gradient
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// ui.text("rainbow").gradient_stops(&[
    ///     (0.0, Color::Red),
    ///     (0.5, Color::Yellow),
    ///     (1.0, Color::Green),
    /// ]);
    /// # });
    /// ```
    pub fn gradient_stops(&mut self, stops: &[(f32, Color)]) -> &mut Self {
        if stops.is_empty() {
            return self;
        }
        let sorted = Self::sorted_gradient_stops(stops);
        self.apply_char_gradient(false, |t| Self::sample_gradient_stops(&sorted, t));
        self
    }

    /// Apply a per-character background gradient to the last rendered text.
    ///
    /// The two-stop background analogue of [`gradient`]. Colors the cell
    /// background instead of the foreground, using identical column-mapping and
    /// clamping so width handling stays consistent.
    ///
    /// [`gradient`]: Self::gradient
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// ui.text("banner").bg_gradient(Color::Blue, Color::Magenta);
    /// # });
    /// ```
    pub fn bg_gradient(&mut self, from: Color, to: Color) -> &mut Self {
        self.apply_char_gradient(true, |t| from.blend(to, t));
        self
    }

    /// Apply a per-character multi-stop background gradient to the last text.
    ///
    /// The background analogue of [`gradient_stops`]: identical stop handling
    /// (positions in `0.0..=1.0`, unsorted-safe, empty = no-op, single stop =
    /// solid) but applied to the cell background instead of the foreground.
    ///
    /// [`gradient_stops`]: Self::gradient_stops
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// ui.text("header").bg_gradient_stops(&[
    ///     (0.0, Color::Blue),
    ///     (1.0, Color::Magenta),
    /// ]);
    /// # });
    /// ```
    pub fn bg_gradient_stops(&mut self, stops: &[(f32, Color)]) -> &mut Self {
        if stops.is_empty() {
            return self;
        }
        let sorted = Self::sorted_gradient_stops(stops);
        self.apply_char_gradient(true, |t| Self::sample_gradient_stops(&sorted, t));
        self
    }

    /// Return `stops` sorted ascending by clamped position. Positions are
    /// clamped into `0.0..=1.0` so out-of-range inputs degrade gracefully.
    fn sorted_gradient_stops(stops: &[(f32, Color)]) -> Vec<(f32, Color)> {
        let mut sorted: Vec<(f32, Color)> = stops
            .iter()
            .map(|(pos, color)| (pos.clamp(0.0, 1.0), *color))
            .collect();
        sorted.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
        sorted
    }

    /// Sample the color at position `t` (in `0.0..=1.0`) from pre-sorted,
    /// non-empty `stops`, linearly interpolating between the bracketing stops.
    fn sample_gradient_stops(stops: &[(f32, Color)], t: f32) -> Color {
        let t = t.clamp(0.0, 1.0);
        // Non-empty is guaranteed by callers; fall back defensively otherwise.
        let first = match stops.first() {
            Some(stop) => *stop,
            None => return Color::Rgb(0, 0, 0),
        };
        let last = *stops.last().unwrap_or(&first);
        if t <= first.0 {
            return first.1;
        }
        if t >= last.0 {
            return last.1;
        }
        for window in stops.windows(2) {
            let (p0, c0) = window[0];
            let (p1, c1) = window[1];
            if t >= p0 && t <= p1 {
                let span = p1 - p0;
                if span <= f32::EPSILON {
                    return c1;
                }
                let local = (t - p0) / span;
                // blend(self, other, alpha) = self*alpha + other*(1-alpha):
                // c1.blend(c0, local) yields c0 at local=0 and c1 at local=1.
                return c1.blend(c0, local);
            }
        }
        last.1
    }

    /// Replace the last `Text` command with a `RichText` gradient, mapping each
    /// character's column to a position in `0.0..=1.0` exactly like
    /// [`gradient`](Self::gradient). `is_bg` selects background vs foreground.
    fn apply_char_gradient(&mut self, is_bg: bool, color_at: impl Fn(f32) -> Color) {
        if let Some(idx) = self.rollback.last_text_idx {
            let replacement = match &self.commands[idx] {
                Command::Text {
                    content,
                    style,
                    wrap,
                    align,
                    margin,
                    constraints,
                    ..
                } => {
                    let chars: Vec<char> = content.chars().collect();
                    let len = chars.len();
                    let denom = len.saturating_sub(1).max(1) as f32;
                    let segments = chars
                        .into_iter()
                        .enumerate()
                        .map(|(i, ch)| {
                            let mut seg_style = *style;
                            let color = color_at(i as f32 / denom);
                            if is_bg {
                                seg_style.bg = Some(color);
                            } else {
                                seg_style.fg = Some(color);
                            }
                            (ch.to_string(), seg_style)
                        })
                        .collect();

                    Some(Command::RichText {
                        segments,
                        wrap: *wrap,
                        align: *align,
                        margin: *margin,
                        constraints: *constraints,
                    })
                }
                _ => None,
            };

            if let Some(command) = replacement {
                self.commands[idx] = command;
            }
        }
    }

    /// Set foreground color when the current group is hovered or focused.
    pub fn group_hover_fg(&mut self, color: Color) -> &mut Self {
        let apply_group_style = self
            .rollback
            .group_stack
            .last()
            .map(|name| self.is_group_hovered(name) || self.is_group_focused(name))
            .unwrap_or(false);
        if apply_group_style {
            self.modify_last_style(|s| s.fg = Some(color));
        }
        self
    }

    /// Set background color when the current group is hovered or focused.
    pub fn group_hover_bg(&mut self, color: Color) -> &mut Self {
        let apply_group_style = self
            .rollback
            .group_stack
            .last()
            .map(|name| self.is_group_hovered(name) || self.is_group_focused(name))
            .unwrap_or(false);
        if apply_group_style {
            self.modify_last_style(|s| s.bg = Some(color));
        }
        self
    }

    /// Render a text element with an explicit [`Style`] applied immediately.
    ///
    /// Equivalent to calling `text(s)` followed by style-chain methods, but
    /// more concise when you already have a `Style` value.
    pub fn styled(&mut self, s: impl Into<String>, style: Style) -> &mut Self {
        self.styled_with_cursor(s, style, None)
    }

    pub(crate) fn styled_with_cursor(
        &mut self,
        s: impl Into<String>,
        style: Style,
        cursor_offset: Option<usize>,
    ) -> &mut Self {
        self.commands.push(Command::Text {
            content: s.into(),
            cursor_offset,
            style,
            grow: 0,
            align: Align::Start,
            wrap: false,
            truncate: false,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Enable word-boundary wrapping on the last rendered text element.
    pub fn wrap(&mut self) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx
            && let Command::Text { wrap, .. } = &mut self.commands[idx]
        {
            *wrap = true;
        }
        self
    }

    /// Truncate the last rendered text with `…` when it exceeds its allocated width.
    /// Use with `.w()` to set a fixed width, or let the parent container constrain it.
    pub fn truncate(&mut self) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx
            && let Command::Text { truncate, .. } = &mut self.commands[idx]
        {
            *truncate = true;
        }
        self
    }

    fn modify_last_style(&mut self, f: impl FnOnce(&mut Style)) {
        if let Some(idx) = self.rollback.last_text_idx {
            match &mut self.commands[idx] {
                Command::Text { style, .. } | Command::Link { style, .. } => f(style),
                _ => {}
            }
        }
    }

    fn modify_last_constraints(&mut self, f: impl FnOnce(&mut Constraints)) {
        if let Some(idx) = self.rollback.last_text_idx {
            match &mut self.commands[idx] {
                Command::Text { constraints, .. } | Command::Link { constraints, .. } => {
                    f(constraints)
                }
                _ => {}
            }
        }
    }

    fn modify_last_margin(&mut self, f: impl FnOnce(&mut Margin)) {
        if let Some(idx) = self.rollback.last_text_idx {
            match &mut self.commands[idx] {
                Command::Text { margin, .. } | Command::Link { margin, .. } => f(margin),
                _ => {}
            }
        }
    }

    // ── containers ───────────────────────────────────────────────────

    /// Set the flex-grow factor of the last rendered text element.
    ///
    /// A value of `1` causes the element to expand and fill remaining space
    /// along the main axis.
    pub fn grow(&mut self, value: u16) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx
            && let Command::Text { grow, .. } = &mut self.commands[idx]
        {
            *grow = value;
        }
        self
    }

    /// Set the text alignment of the last rendered text element.
    pub fn align(&mut self, align: Align) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx
            && let Command::Text {
                align: text_align, ..
            } = &mut self.commands[idx]
        {
            *text_align = align;
        }
        self
    }

    /// Center-align the last rendered text element horizontally.
    /// Shorthand for `.align(Align::Center)`. Requires the text to have
    /// a width constraint (via `.w()` or parent container) to be visible.
    pub fn text_center(&mut self) -> &mut Self {
        self.align(Align::Center)
    }

    /// Right-align the last rendered text element horizontally.
    /// Shorthand for `.align(Align::End)`.
    pub fn text_right(&mut self) -> &mut Self {
        self.align(Align::End)
    }

    // ── size constraints on last text/link ──────────────────────────

    /// Set a fixed width on the last rendered text or link element.
    ///
    /// Sets the [`WidthSpec`](crate::WidthSpec) to `Fixed(value)`, making the
    /// element occupy exactly that many columns (padded with spaces or
    /// truncated).
    pub fn w(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| {
            *c = c.w(value);
        });
        self
    }

    /// Set a fixed height on the last rendered text or link element.
    ///
    /// Sets the [`HeightSpec`](crate::HeightSpec) to `Fixed(value)`.
    pub fn h(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| {
            *c = c.h(value);
        });
        self
    }

    /// Set the minimum width on the last rendered text or link element.
    pub fn min_w(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.set_min_width(Some(value)));
        self
    }

    /// Set the maximum width on the last rendered text or link element.
    pub fn max_w(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.set_max_width(Some(value)));
        self
    }

    /// Set the minimum height on the last rendered text or link element.
    pub fn min_h(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.set_min_height(Some(value)));
        self
    }

    /// Set the maximum height on the last rendered text or link element.
    pub fn max_h(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.set_max_height(Some(value)));
        self
    }

    // ── margin on last text/link ────────────────────────────────────

    /// Set uniform margin on all sides of the last rendered text or link element.
    pub fn m(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| *m = Margin::all(value));
        self
    }

    /// Set horizontal margin (left + right) on the last rendered text or link.
    pub fn mx(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| {
            m.left = value;
            m.right = value;
        });
        self
    }

    /// Set vertical margin (top + bottom) on the last rendered text or link.
    pub fn my(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| {
            m.top = value;
            m.bottom = value;
        });
        self
    }

    /// Set top margin on the last rendered text or link element.
    pub fn mt(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.top = value);
        self
    }

    /// Set right margin on the last rendered text or link element.
    pub fn mr(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.right = value);
        self
    }

    /// Set bottom margin on the last rendered text or link element.
    pub fn mb(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.bottom = value);
        self
    }

    /// Set left margin on the last rendered text or link element.
    pub fn ml(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.left = value);
        self
    }

    /// Render an invisible spacer that expands to fill available space.
    ///
    /// Useful for pushing siblings to opposite ends of a row or column.
    pub fn spacer(&mut self) -> &mut Self {
        self.commands.push(Command::Spacer { grow: 1 });
        self.rollback.last_text_idx = None;
        self
    }

    // ── conditional / grouped style helpers ─────────────────────────

    /// Apply `f` only if `cond` is true. Returns `self` so chaining continues.
    ///
    /// Use this to attach a block of style modifiers to the last rendered text
    /// without breaking the fluent chain. The closure receives the same
    /// `&mut Context`, so any style-chain method (`.bold()`, `.fg()`, etc.)
    /// applies to the most recent text element.
    ///
    /// Zero allocation: the closure is inlined and skipped entirely when
    /// `cond` is `false`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// let is_error = true;
    /// let is_selected = false;
    /// ui.text("Status")
    ///     .with_if(is_error, |t| {
    ///         t.bold().fg(Color::Red);
    ///     })
    ///     .with_if(is_selected, |t| {
    ///         t.bg(Color::DarkGray);
    ///     });
    /// # });
    /// ```
    pub fn with_if(&mut self, cond: bool, f: impl FnOnce(&mut Self)) -> &mut Self {
        if cond {
            f(self);
        }
        self
    }

    /// Apply `f` unconditionally. Useful for factoring out a block of modifier
    /// calls that should always run, while keeping the fluent chain intact.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// ui.text("hi").with(|t| {
    ///     t.bold().fg(Color::Cyan);
    /// });
    /// # });
    /// ```
    pub fn with(&mut self, f: impl FnOnce(&mut Self)) -> &mut Self {
        f(self);
        self
    }
}

#[cfg(test)]
mod gradient_tests {
    use super::*;
    use crate::TestBackend;

    #[test]
    fn gradient_stops_interpolates_fg_across_columns() {
        let red = Color::Rgb(255, 0, 0);
        let blue = Color::Rgb(0, 0, 255);
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            ui.text("ABC").gradient_stops(&[(0.0, red), (1.0, blue)]);
        });

        let buf = backend.buffer();
        // i=0 → t=0 → stop at 0.0 (red); i=2 → t=1 → stop at 1.0 (blue);
        // i=1 → t=0.5 → halfway blend.
        assert_eq!(
            buf.get(0, 0).style.fg,
            Some(red),
            "first column should be red"
        );
        assert_eq!(
            buf.get(1, 0).style.fg,
            Some(Color::Rgb(128, 0, 128)),
            "middle column should be the halfway blend"
        );
        assert_eq!(
            buf.get(2, 0).style.fg,
            Some(blue),
            "last column should be blue"
        );
    }

    #[test]
    fn gradient_stops_unsorted_input_is_sorted() {
        let red = Color::Rgb(255, 0, 0);
        let blue = Color::Rgb(0, 0, 255);
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            // Deliberately out of order — must behave identically to sorted.
            ui.text("ABC").gradient_stops(&[(1.0, blue), (0.0, red)]);
        });

        let buf = backend.buffer();
        assert_eq!(buf.get(0, 0).style.fg, Some(red));
        assert_eq!(buf.get(2, 0).style.fg, Some(blue));
    }

    #[test]
    fn gradient_stops_multi_stop_hits_middle_stop_exactly() {
        let red = Color::Rgb(255, 0, 0);
        let green = Color::Rgb(0, 255, 0);
        let blue = Color::Rgb(0, 0, 255);
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            // len=3, denom=2 → columns map to t = 0.0, 0.5, 1.0.
            ui.text("ABC")
                .gradient_stops(&[(0.0, red), (0.5, green), (1.0, blue)]);
        });

        let buf = backend.buffer();
        assert_eq!(buf.get(0, 0).style.fg, Some(red), "t=0 → first stop");
        assert_eq!(
            buf.get(1, 0).style.fg,
            Some(green),
            "t=0.5 → middle stop exactly"
        );
        assert_eq!(buf.get(2, 0).style.fg, Some(blue), "t=1 → last stop");
    }

    #[test]
    fn gradient_stops_single_stop_is_solid() {
        let cyan = Color::Rgb(0, 200, 200);
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            ui.text("ABCD").gradient_stops(&[(0.0, cyan)]);
        });

        let buf = backend.buffer();
        for x in 0..4 {
            assert_eq!(
                buf.get(x, 0).style.fg,
                Some(cyan),
                "every column should be the single solid stop"
            );
        }
    }

    #[test]
    fn gradient_stops_empty_is_noop() {
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            // Empty slice must not panic and must leave content intact.
            ui.text("HELLO").gradient_stops(&[]);
        });

        backend.assert_contains("HELLO");
    }

    #[test]
    fn bg_gradient_applies_to_background() {
        let red = Color::Rgb(255, 0, 0);
        let blue = Color::Rgb(0, 0, 255);
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            ui.text("ABC").bg_gradient(red, blue);
        });

        let buf = backend.buffer();
        // bg_gradient mirrors gradient(): from.blend(to, t) — at t=0 that is `to`
        // (blue), at t=1 that is `from` (red). Foreground stays untouched.
        assert_eq!(buf.get(0, 0).style.bg, Some(blue), "first column bg = to");
        assert_eq!(buf.get(2, 0).style.bg, Some(red), "last column bg = from");
        assert_eq!(
            buf.get(1, 0).style.bg,
            Some(Color::Rgb(128, 0, 128)),
            "middle column bg = halfway blend"
        );
    }

    #[test]
    fn bg_gradient_stops_interpolates_background() {
        let red = Color::Rgb(255, 0, 0);
        let blue = Color::Rgb(0, 0, 255);
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            ui.text("ABC").bg_gradient_stops(&[(0.0, red), (1.0, blue)]);
        });

        let buf = backend.buffer();
        assert_eq!(buf.get(0, 0).style.bg, Some(red), "first column bg = red");
        assert_eq!(
            buf.get(1, 0).style.bg,
            Some(Color::Rgb(128, 0, 128)),
            "middle column bg = halfway blend"
        );
        assert_eq!(buf.get(2, 0).style.bg, Some(blue), "last column bg = blue");
    }

    #[test]
    fn bg_gradient_stops_empty_is_noop() {
        let mut backend = TestBackend::new(20, 4);
        backend.render(|ui| {
            ui.text("WORLD").bg_gradient_stops(&[]);
        });

        backend.assert_contains("WORLD");
    }
}