tui-lipan 0.2.0

Opinionated, component-based TUI framework for Rust - declarative components, reconciliation, layout engine, focus, overlays, and rich widgets on top of ratatui.
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
use core::fmt;

/// Terminal colors with support for ANSI 16, 256, and true color.
#[cfg_attr(
    feature = "terminal-serde",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Color {
    /// Terminal default (ANSI reset for that attribute).
    Reset,
    /// Preserve the existing background behind this surface while allowing the
    /// surface to clear or repaint foreground content.
    ///
    /// This is primarily meaningful for background-style surfaces like modal or
    /// frame fills. Unlike [`Color::Transparent`], which keeps both foreground
    /// and background beneath untouched, `Backdrop` is intended for the old
    /// overlay behavior where blank areas clear text but keep the underlying
    /// background color.
    Backdrop,
    /// Do not paint this channel: keep the existing cell / parent style underneath.
    ///
    /// Unlike [`Color::Reset`], which selects the terminal's default palette color,
    /// transparent skips setting foreground or background when converting to
    /// ratatui styles so lower layers show through. For [`crate::style::Style::patch`], a
    /// transparent overlay leaves the resolved base color unchanged for that
    /// channel.
    Transparent,
    /// Black.
    Black,
    /// Red.
    Red,
    /// Green.
    Green,
    /// Yellow.
    Yellow,
    /// Blue.
    Blue,
    /// Magenta.
    Magenta,
    /// Cyan.
    Cyan,
    /// Gray.
    Gray,
    /// Dark gray.
    DarkGray,
    /// Light red.
    LightRed,
    /// Light green.
    LightGreen,
    /// Light yellow.
    LightYellow,
    /// Light blue.
    LightBlue,
    /// Light magenta.
    LightMagenta,
    /// Light cyan.
    LightCyan,
    /// White.
    White,

    /// 256-color palette (0-255).
    Indexed(u8),
    /// True color RGB.
    Rgb(u8, u8, u8),
}

/// A color paint that may carry an alpha channel.
#[cfg_attr(
    feature = "terminal-serde",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Paint {
    /// Fully opaque paint using a terminal color.
    Solid(Color),
    /// Alpha-blended paint over the resolved background.
    Alpha {
        /// Base color to blend.
        color: Color,
        /// Alpha channel where `0` is fully transparent and `255` is fully opaque.
        alpha: u8,
    },
    /// A colour the renderer resolves while painting, from a transition the app owns.
    ///
    /// Produced by [`Context::animated_color`](crate::core::component::Context::animated_color).
    /// Because the value is named rather than embedded, this paint compares equal across a whole
    /// fade — which is what lets the runtime advance the fade with a repaint instead of re-running
    /// `view()` for every frame of it.
    Animated {
        /// Registry slot naming the transition.
        slot: u16,
        /// Colour to use when the slot no longer resolves — a paint outliving its transition, or a
        /// consumer that never reaches the renderer's resolution step.
        fallback: Color,
    },
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

impl Color {
    /// Whether this color is a semantic sentinel rather than a concrete pigment.
    ///
    /// Sentinel colors are [`Color::Reset`], [`Color::Backdrop`], and
    /// [`Color::Transparent`]. They describe terminal or compositing behavior
    /// instead of a color that can be converted directly to RGB.
    pub const fn is_sentinel(self) -> bool {
        matches!(self, Self::Reset | Self::Backdrop | Self::Transparent)
    }

    /// Replace a sentinel color with `fallback`, leaving concrete colors unchanged.
    pub const fn resolve(self, fallback: Self) -> Self {
        if self.is_sentinel() { fallback } else { self }
    }

    /// Create from a hex string (e.g., `"#FF5733"` or `"FF5733"`).
    ///
    /// Accepted formats (with or without leading `#`):
    /// - 6 chars: `RRGGBB`
    /// - 3 chars: `RGB` (each digit is doubled, e.g. `F80` → `FF8800`)
    ///
    /// Invalid input falls back to [`Color::Reset`].
    pub fn hex(s: &str) -> Self {
        Self::try_hex(s).unwrap_or(Self::Reset)
    }

    pub(crate) fn try_hex(s: &str) -> Option<Self> {
        let s = s.strip_prefix('#').unwrap_or(s);
        if !s.is_ascii() {
            return None;
        }

        match s.len() {
            6 => Some(Self::Rgb(
                parse_hex_byte(s, 0)?,
                parse_hex_byte(s, 2)?,
                parse_hex_byte(s, 4)?,
            )),
            3 => Some(Self::Rgb(
                parse_hex_nibble(s, 0)? * 17,
                parse_hex_nibble(s, 1)? * 17,
                parse_hex_nibble(s, 2)? * 17,
            )),
            _ => None,
        }
    }

    /// Create RGB color.
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self::Rgb(r, g, b)
    }

    /// Create RGB color from a `0xRRGGBB` integer literal.
    pub const fn hex_u24(rgb: u32) -> Self {
        Self::Rgb(
            ((rgb >> 16) & 0xFF) as u8,
            ((rgb >> 8) & 0xFF) as u8,
            (rgb & 0xFF) as u8,
        )
    }

    /// Create from 256-color palette index.
    pub const fn indexed(index: u8) -> Self {
        Self::Indexed(index)
    }

    /// Convert to RGB if possible.
    pub fn to_rgb(self) -> Option<(u8, u8, u8)> {
        match self {
            Color::Reset | Color::Backdrop | Color::Transparent => None,
            Color::Rgb(r, g, b) => Some((r, g, b)),
            Color::Indexed(index) => Some(indexed_to_rgb(index)),
            Color::Black => Some((0, 0, 0)),
            Color::Red => Some((205, 0, 0)),
            Color::Green => Some((0, 205, 0)),
            Color::Yellow => Some((205, 205, 0)),
            Color::Blue => Some((0, 0, 238)),
            Color::Magenta => Some((205, 0, 205)),
            Color::Cyan => Some((0, 205, 205)),
            Color::Gray => Some((229, 229, 229)),
            Color::DarkGray => Some((127, 127, 127)),
            Color::LightRed => Some((255, 0, 0)),
            Color::LightGreen => Some((0, 255, 0)),
            Color::LightYellow => Some((255, 255, 0)),
            Color::LightBlue => Some((92, 92, 255)),
            Color::LightMagenta => Some((255, 0, 255)),
            Color::LightCyan => Some((0, 255, 255)),
            Color::White => Some((255, 255, 255)),
        }
    }

    /// Convert to RGB, resolving a sentinel against `fallback` first.
    ///
    /// If both colors are sentinels, black is the final concrete fallback.
    pub fn to_rgb_or(self, fallback: Color) -> (u8, u8, u8) {
        self.to_rgb()
            .or_else(|| fallback.to_rgb())
            .unwrap_or((0, 0, 0))
    }

    /// Dim this color by the default amount.
    ///
    /// The dim level is applied uniformly to ANSI named colors, indexed colors,
    /// and truecolor values by converting to RGB and scaling channel intensity.
    pub fn dim(self) -> Self {
        self.dim_by(0.35)
    }

    /// Dim this color by an explicit amount in the `[0.0, 1.0]` range.
    ///
    /// - `0.0` keeps the color unchanged.
    /// - `1.0` yields black.
    ///
    /// `Color::Reset` is returned unchanged.
    pub fn dim_by(self, amount: f32) -> Self {
        let Some((r, g, b)) = self.to_rgb() else {
            return self;
        };

        let t = amount.clamp(0.0, 1.0);
        let scale = 1.0 - t;
        Self::Rgb(
            scale_channel(r, scale),
            scale_channel(g, scale),
            scale_channel(b, scale),
        )
    }

    /// Lighten this color by the default amount.
    ///
    /// The lightening level is applied uniformly to ANSI named colors, indexed
    /// colors, and truecolor values by converting to RGB and blending channels
    /// toward white.
    pub fn lighten(self) -> Self {
        self.lighten_by(0.35)
    }

    /// Lighten this color by an explicit amount in the `[0.0, 1.0]` range.
    ///
    /// - `0.0` keeps the color unchanged.
    /// - `1.0` yields white.
    ///
    /// `Color::Reset` is returned unchanged.
    pub fn lighten_by(self, amount: f32) -> Self {
        let Some((r, g, b)) = self.to_rgb() else {
            return self;
        };

        let t = amount.clamp(0.0, 1.0);
        Self::Rgb(
            blend_toward_white_channel(r, t),
            blend_toward_white_channel(g, t),
            blend_toward_white_channel(b, t),
        )
    }

    /// Blend this color toward `target` by `alpha` in `[0.0, 1.0]`.
    ///
    /// - `0.0` keeps this color unchanged.
    /// - `1.0` yields `target`.
    /// - `Color::Reset` is treated as black `(0, 0, 0)` for blending.
    ///
    /// Returns this color unchanged if `target` is [`Color::Reset`],
    /// [`Color::Backdrop`], or [`Color::Transparent`].
    pub fn blend_toward(self, target: Color, alpha: f32) -> Self {
        let alpha = alpha.clamp(0.0, 1.0);
        if matches!(target, Color::Reset | Color::Backdrop | Color::Transparent) {
            return self;
        }
        let (r1, g1, b1) = self.to_rgb().unwrap_or((0, 0, 0));
        let Some((r2, g2, b2)) = target.to_rgb() else {
            return self;
        };
        let blend_ch = |a: u8, b: u8| -> u8 {
            (a as f32 * (1.0 - alpha) + b as f32 * alpha)
                .round()
                .clamp(0.0, 255.0) as u8
        };
        Self::Rgb(blend_ch(r1, r2), blend_ch(g1, g2), blend_ch(b1, b2))
    }

    /// Perceived relative luminance in `[0.0, 1.0]` using Rec. 601 weights.
    ///
    /// Colors that cannot be resolved to RGB (e.g. [`Color::Reset`]) are treated
    /// as black and return `0.0`.
    pub fn luminance(self) -> f32 {
        let (r, g, b) = self.to_rgb().unwrap_or((0, 0, 0));
        (0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32) / 255.0
    }

    /// Whether this color reads as a dark surface (luminance below the midpoint).
    ///
    /// Unresolvable colors (e.g. [`Color::Reset`]) are treated as dark.
    pub fn is_dark(self) -> bool {
        self.luminance() < 0.5
    }

    /// Raise a surface off its own background by the default elevation step.
    ///
    /// One step, matching the amounts the built-in themes use for panel and menu
    /// surfaces. Elevation steps are small by nature, so this default is much
    /// smaller than [`Self::dim`] / [`Self::lighten`]: those wash a color, while
    /// this lifts a surface off the one behind it.
    pub fn elevate(self) -> Self {
        self.elevate_by(0.08)
    }

    /// Raise a surface off its own background by a perceptually even amount.
    ///
    /// Unlike [`Self::lighten_by`], this is luminance-aware: dark backgrounds are
    /// lightened toward white while light backgrounds are darkened toward black.
    /// This keeps layered surfaces (panels, inputs, menus) visible on both dark
    /// and light themes, where a one-directional lighten would collapse on a
    /// near-white background.
    ///
    /// Elevation takes the lightness of the equivalent endpoint-blended RGB
    /// color, then applies that lightness in OKLab while preserving the source
    /// hue and relative chroma as far as the sRGB gamut allows. This keeps
    /// established elevation amounts visible, avoids washing very dark tinted
    /// surfaces into gray, and remains well-defined at pure black and white.
    ///
    /// `amount` is in `[0.0, 1.0]`; `Color::Reset` and similar are returned
    /// unchanged.
    pub fn elevate_by(self, amount: f32) -> Self {
        let Some((r, g, blue)) = self.to_rgb() else {
            return self;
        };
        let amount = amount.clamp(0.0, 1.0);
        if amount == 0.0 {
            return self;
        }

        let (lightness, a, b) = rgb_to_oklab(r, g, blue);
        let endpoint_target = if self.is_dark() {
            self.lighten_by(amount)
        } else {
            self.dim_by(amount)
        };
        let (target_lightness, _, _) = rgb_to_oklab_or_black(endpoint_target);
        let relative_chroma_scale = if lightness > f32::EPSILON {
            target_lightness / lightness
        } else {
            1.0
        };
        // A one-step tint away from black does not carry enough signal to
        // justify scaling its relative chroma all the way to the elevated
        // lightness. Fade that behavior in over a small absolute channel range
        // so terminal quantization remains continuous near neutral black.
        let channel_chroma = r.max(g).max(blue) - r.min(g).min(blue);
        let chroma_confidence = (channel_chroma as f32 / 8.0).clamp(0.0, 1.0);
        let chroma_confidence = chroma_confidence * chroma_confidence;
        let elevation_weight = (amount / 0.10).clamp(0.0, 1.0);
        let chroma_retention = 1.0 - elevation_weight * (1.0 - chroma_confidence);
        let chroma_scale = relative_chroma_scale * chroma_retention;
        oklab_to_color(target_lightness, a * chroma_scale, b * chroma_scale)
    }
}

fn rgb_to_oklab_or_black(color: Color) -> (f32, f32, f32) {
    color
        .to_rgb()
        .map_or((0.0, 0.0, 0.0), |(r, g, b)| rgb_to_oklab(r, g, b))
}

fn srgb_to_linear(channel: u8) -> f32 {
    let channel = channel as f32 / 255.0;
    if channel <= 0.04045 {
        channel / 12.92
    } else {
        ((channel + 0.055) / 1.055).powf(2.4)
    }
}

fn linear_to_srgb(channel: f32) -> f32 {
    if channel <= 0.003_130_8 {
        12.92 * channel
    } else {
        1.055 * channel.powf(1.0 / 2.4) - 0.055
    }
}

fn rgb_to_oklab(r: u8, g: u8, b: u8) -> (f32, f32, f32) {
    let r = srgb_to_linear(r);
    let g = srgb_to_linear(g);
    let b = srgb_to_linear(b);

    let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt();
    let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt();
    let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt();

    (
        0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
        1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
        0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
    )
}

fn oklab_to_linear_rgb(lightness: f32, a: f32, b: f32) -> (f32, f32, f32) {
    let l = (lightness + 0.396_337_78 * a + 0.215_803_76 * b).powi(3);
    let m = (lightness - 0.105_561_346 * a - 0.063_854_17 * b).powi(3);
    let s = (lightness - 0.089_484_18 * a - 1.291_485_5 * b).powi(3);

    (
        4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
        -1.268_438 * l + 2.609_757_4 * m - 0.341_319_4 * s,
        -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
    )
}

fn linear_rgb_in_gamut((r, g, b): (f32, f32, f32)) -> bool {
    (0.0..=1.0).contains(&r) && (0.0..=1.0).contains(&g) && (0.0..=1.0).contains(&b)
}

fn linear_rgb_to_color((r, g, b): (f32, f32, f32)) -> Color {
    let channel = |value: f32| -> u8 {
        (linear_to_srgb(value.clamp(0.0, 1.0)) * 255.0)
            .round()
            .clamp(0.0, 255.0) as u8
    };
    Color::rgb(channel(r), channel(g), channel(b))
}

fn oklab_to_color(lightness: f32, a: f32, b: f32) -> Color {
    let lightness = lightness.clamp(0.0, 1.0);
    let direct = oklab_to_linear_rgb(lightness, a, b);
    if linear_rgb_in_gamut(direct) {
        return linear_rgb_to_color(direct);
    }

    // Keep the requested perceptual lightness and hue, reducing only chroma
    // until the color fits sRGB. The neutral color at this lightness is always
    // in gamut, so the search has a valid lower bound.
    let mut low = 0.0;
    let mut high = 1.0;
    let mut best = oklab_to_linear_rgb(lightness, 0.0, 0.0);
    for _ in 0..16 {
        let scale = (low + high) * 0.5;
        let candidate = oklab_to_linear_rgb(lightness, a * scale, b * scale);
        if linear_rgb_in_gamut(candidate) {
            low = scale;
            best = candidate;
        } else {
            high = scale;
        }
    }
    linear_rgb_to_color(best)
}

impl Paint {
    /// Create fully opaque paint from a terminal color.
    pub const fn solid(color: Color) -> Self {
        Self::Solid(color)
    }

    /// Create fully opaque RGB paint.
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self::Solid(Color::Rgb(r, g, b))
    }

    /// Create RGB paint with an explicit `0..=255` alpha channel.
    pub const fn rgba(r: u8, g: u8, b: u8, alpha: u8) -> Self {
        Self::from_color_alpha_u8(Color::Rgb(r, g, b), alpha)
    }

    /// Create from a hex string, falling back to opaque [`Color::Reset`] on invalid input.
    pub fn hex(s: &str) -> Self {
        Self::try_hex(s).unwrap_or(Self::Solid(Color::Reset))
    }

    /// Create from a hex string.
    ///
    /// Accepted formats (with or without leading `#`):
    /// - 6 chars: `RRGGBB`
    /// - 8 chars: `RRGGBBAA`
    /// - 3 chars: `RGB` (each digit is doubled, e.g. `F80` → `FF8800`)
    /// - 4 chars: `RGBA` (each digit is doubled)
    pub fn try_hex(s: &str) -> Option<Self> {
        let s = s.strip_prefix('#').unwrap_or(s);
        if !s.is_ascii() {
            return None;
        }

        match s.len() {
            8 => Some(Self::from_color_alpha_u8(
                Color::Rgb(
                    parse_hex_byte(s, 0)?,
                    parse_hex_byte(s, 2)?,
                    parse_hex_byte(s, 4)?,
                ),
                parse_hex_byte(s, 6)?,
            )),
            6 => Some(Self::rgb(
                parse_hex_byte(s, 0)?,
                parse_hex_byte(s, 2)?,
                parse_hex_byte(s, 4)?,
            )),
            4 => Some(Self::from_color_alpha_u8(
                Color::Rgb(
                    parse_hex_nibble(s, 0)? * 17,
                    parse_hex_nibble(s, 1)? * 17,
                    parse_hex_nibble(s, 2)? * 17,
                ),
                parse_hex_nibble(s, 3)? * 17,
            )),
            3 => Some(Self::rgb(
                parse_hex_nibble(s, 0)? * 17,
                parse_hex_nibble(s, 1)? * 17,
                parse_hex_nibble(s, 2)? * 17,
            )),
            _ => None,
        }
    }

    pub(crate) const fn from_color_alpha_u8(color: Color, alpha: u8) -> Self {
        if alpha == 255 {
            Self::Solid(color)
        } else {
            Self::Alpha { color, alpha }
        }
    }

    pub(crate) fn from_color_alpha(color: Color, alpha: f32) -> Self {
        let alpha = (alpha.clamp(0.0, 1.0) * 255.0).round() as u8;
        Self::from_color_alpha_u8(color, alpha)
    }

    /// Return the paint alpha as an exact `0..=255` byte.
    pub const fn alpha_u8(self) -> u8 {
        match self {
            Self::Solid(_) | Self::Animated { .. } => 255,
            Self::Alpha { alpha, .. } => alpha,
        }
    }

    /// Return the paint alpha as a normalized `0.0..=1.0` value.
    pub fn alpha(self) -> f32 {
        self.alpha_u8() as f32 / 255.0
    }

    /// Return the base color for this paint.
    ///
    /// An [`Animated`](Self::Animated) paint answers with its fallback: the live value needs the
    /// renderer's transition registry, which only the paint pipeline reaches.
    pub const fn color(self) -> Color {
        match self {
            Self::Solid(color)
            | Self::Alpha { color, .. }
            | Self::Animated {
                fallback: color, ..
            } => color,
        }
    }

    /// Bind an [`Animated`](Self::Animated) paint to the colour its transition currently holds.
    ///
    /// A no-op for every other variant. Called at the start of style finalization so the rest of the
    /// paint pipeline only ever sees concrete colours.
    pub(crate) fn resolved(self) -> Self {
        match self {
            Self::Animated { slot, fallback } => Self::Solid(
                crate::animation::registry::resolve_render_paint_slot(slot).unwrap_or(fallback),
            ),
            other => other,
        }
    }

    /// Return whether this paint is fully opaque.
    pub const fn is_opaque(self) -> bool {
        match self {
            Self::Solid(_) | Self::Animated { .. } => true,
            Self::Alpha { alpha, .. } => alpha == 255,
        }
    }

    /// Return whether this paint should leave the target channel transparent.
    pub const fn is_transparent_paint(self) -> bool {
        match self {
            Self::Solid(Color::Transparent) => true,
            Self::Solid(_) => false,
            Self::Alpha { alpha, .. } => alpha == 0,
            // Only concrete pigments animate, so a slot is never a transparency sentinel.
            Self::Animated { .. } => false,
        }
    }

    /// Resolve to an opaque [`Color`] by source-over compositing this paint
    /// against `backdrop`.
    ///
    /// - [`Paint::Solid`] returns its pigment unchanged.
    /// - [`Paint::Alpha`] blends the pigment over `backdrop` weighted by alpha.
    /// - If `backdrop` cannot be resolved to RGB (e.g. [`Color::Reset`],
    ///   [`Color::Transparent`], or [`Color::Backdrop`]), the pigment is
    ///   returned as a best-effort fallback so callers still receive a usable
    ///   color rather than the wrong one.
    pub fn flatten_over(self, backdrop: Color) -> Color {
        match self {
            Self::Solid(color) => color,
            Self::Alpha { color, alpha } => {
                if backdrop.to_rgb().is_none() {
                    return color;
                }
                let weight = alpha as f32 / 255.0;
                backdrop.blend_toward(color, weight)
            }
            Self::Animated { .. } => self.resolved().flatten_over(backdrop),
        }
    }

    pub(crate) const fn is_transparent_sentinel(self) -> bool {
        matches!(self, Self::Solid(Color::Transparent))
    }

    pub(crate) const fn is_backdrop_sentinel(self) -> bool {
        matches!(self, Self::Solid(Color::Backdrop))
    }
}

impl From<Color> for Paint {
    fn from(color: Color) -> Self {
        Self::Solid(color)
    }
}

#[cfg(all(test, feature = "terminal-serde"))]
mod terminal_serde_tests {
    use super::*;

    #[test]
    fn color_round_trips() {
        let color = Color::Rgb(12, 34, 56);
        let json = serde_json::to_string(&color).unwrap();
        assert_eq!(serde_json::from_str::<Color>(&json).unwrap(), color);
    }

    #[test]
    fn paint_round_trips() {
        let paint = Paint::Alpha {
            color: Color::Indexed(42),
            alpha: 128,
        };
        let json = serde_json::to_string(&paint).unwrap();
        assert_eq!(serde_json::from_str::<Paint>(&json).unwrap(), paint);
    }
}

impl PartialEq<Color> for Paint {
    fn eq(&self, other: &Color) -> bool {
        matches!(self, Self::Solid(color) if color == other)
    }
}

impl PartialEq<Paint> for Color {
    fn eq(&self, other: &Paint) -> bool {
        other == self
    }
}

fn parse_hex_byte(s: &str, start: usize) -> Option<u8> {
    u8::from_str_radix(&s[start..start + 2], 16).ok()
}

fn parse_hex_nibble(s: &str, start: usize) -> Option<u8> {
    u8::from_str_radix(&s[start..start + 1], 16).ok()
}

fn scale_channel(channel: u8, scale: f32) -> u8 {
    ((channel as f32 * scale).round()).clamp(0.0, 255.0) as u8
}

fn blend_toward_white_channel(channel: u8, t: f32) -> u8 {
    let channel = channel as f32;
    (channel + (255.0 - channel) * t).round().clamp(0.0, 255.0) as u8
}

fn indexed_to_rgb(index: u8) -> (u8, u8, u8) {
    const ANSI16: [(u8, u8, u8); 16] = [
        (0, 0, 0),
        (205, 0, 0),
        (0, 205, 0),
        (205, 205, 0),
        (0, 0, 238),
        (205, 0, 205),
        (0, 205, 205),
        (229, 229, 229),
        (127, 127, 127),
        (255, 0, 0),
        (0, 255, 0),
        (255, 255, 0),
        (92, 92, 255),
        (255, 0, 255),
        (0, 255, 255),
        (255, 255, 255),
    ];

    if index < 16 {
        return ANSI16[index as usize];
    }

    if index >= 232 {
        let gray = 8u8.saturating_add((index - 232).saturating_mul(10));
        return (gray, gray, gray);
    }

    let idx = index - 16;
    let r = idx / 36;
    let g = (idx % 36) / 6;
    let b = idx % 6;
    let to_level = |v: u8| match v {
        0 => 0,
        1 => 95,
        2 => 135,
        3 => 175,
        4 => 215,
        _ => 255,
    };
    (to_level(r), to_level(g), to_level(b))
}

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

    #[test]
    fn sentinel_classification_is_exhaustive() {
        for color in [Color::Reset, Color::Backdrop, Color::Transparent] {
            assert!(color.is_sentinel());
        }

        for color in [
            Color::Black,
            Color::Red,
            Color::Green,
            Color::Yellow,
            Color::Blue,
            Color::Magenta,
            Color::Cyan,
            Color::Gray,
            Color::DarkGray,
            Color::LightRed,
            Color::LightGreen,
            Color::LightYellow,
            Color::LightBlue,
            Color::LightMagenta,
            Color::LightCyan,
            Color::White,
            Color::Indexed(42),
            Color::Rgb(1, 2, 3),
        ] {
            assert!(!color.is_sentinel());
        }
    }

    #[test]
    fn resolve_replaces_only_sentinels() {
        let fallback = Color::Rgb(10, 20, 30);

        for color in [Color::Reset, Color::Backdrop, Color::Transparent] {
            assert_eq!(color.resolve(fallback), fallback);
        }
        for color in [
            Color::Black,
            Color::Red,
            Color::Green,
            Color::Yellow,
            Color::Blue,
            Color::Magenta,
            Color::Cyan,
            Color::Gray,
            Color::DarkGray,
            Color::LightRed,
            Color::LightGreen,
            Color::LightYellow,
            Color::LightBlue,
            Color::LightMagenta,
            Color::LightCyan,
            Color::White,
            Color::Indexed(42),
            Color::Rgb(1, 2, 3),
        ] {
            assert_eq!(color.resolve(fallback), color);
        }
    }

    #[test]
    fn to_rgb_or_uses_fallback_only_for_sentinels() {
        let fallback = Color::Rgb(10, 20, 30);

        for color in [Color::Reset, Color::Backdrop, Color::Transparent] {
            assert_eq!(color.to_rgb_or(fallback), (10, 20, 30));
        }
        for color in [
            Color::Black,
            Color::Red,
            Color::Green,
            Color::Yellow,
            Color::Blue,
            Color::Magenta,
            Color::Cyan,
            Color::Gray,
            Color::DarkGray,
            Color::LightRed,
            Color::LightGreen,
            Color::LightYellow,
            Color::LightBlue,
            Color::LightMagenta,
            Color::LightCyan,
            Color::White,
            Color::Indexed(42),
            Color::Rgb(1, 2, 3),
        ] {
            assert_eq!(color.to_rgb_or(fallback), color.to_rgb().unwrap());
        }
        assert_eq!(Color::Reset.to_rgb_or(Color::Transparent), (0, 0, 0));
    }

    #[test]
    fn dim_by_zero_keeps_color() {
        assert_eq!(
            Color::rgb(100, 120, 140).dim_by(0.0),
            Color::Rgb(100, 120, 140)
        );
    }

    #[test]
    fn dim_by_one_makes_black() {
        assert_eq!(Color::rgb(100, 120, 140).dim_by(1.0), Color::Rgb(0, 0, 0));
    }

    #[test]
    fn dim_handles_ansi_and_indexed() {
        assert_ne!(Color::LightBlue.dim(), Color::LightBlue);
        assert_ne!(Color::Indexed(214).dim(), Color::Indexed(214));
    }

    #[test]
    fn lighten_by_zero_keeps_color() {
        assert_eq!(
            Color::rgb(100, 120, 140).lighten_by(0.0),
            Color::Rgb(100, 120, 140)
        );
    }

    #[test]
    fn lighten_by_one_makes_white() {
        assert_eq!(
            Color::rgb(100, 120, 140).lighten_by(1.0),
            Color::Rgb(255, 255, 255)
        );
    }

    #[test]
    fn lighten_handles_ansi_and_indexed() {
        assert_ne!(Color::Blue.lighten(), Color::Blue);
        assert_ne!(Color::Indexed(214).lighten(), Color::Indexed(214));
    }

    #[test]
    fn is_dark_splits_on_luminance_midpoint() {
        assert!(Color::hex_u24(0x0B121F).is_dark());
        assert!(Color::Black.is_dark());
        assert!(!Color::White.is_dark());
        assert!(!Color::hex_u24(0xFDF6E3).is_dark());
    }

    #[test]
    fn elevate_lightens_dark_and_darkens_light() {
        let dark = Color::hex_u24(0x0B121F);
        let dark_up = dark.elevate_by(0.10);
        assert!(dark_up.luminance() > dark.luminance());

        let light = Color::White;
        let light_up = light.elevate_by(0.10);
        assert!(light_up.luminance() < light.luminance());
    }

    #[test]
    fn elevate_preserves_near_black_surface_cast() {
        let lipan_backdrop = Color::hex_u24(0x04090D);
        let elevated = lipan_backdrop.elevate_by(0.10).to_rgb().unwrap();

        assert!(elevated.0 < elevated.1 && elevated.1 < elevated.2);
        assert_ne!(elevated.0, elevated.2);
        assert!(
            Color::Rgb(elevated.0, elevated.1, elevated.2).luminance() > lipan_backdrop.luminance()
        );
    }

    #[test]
    fn elevate_preserves_near_black_relative_chroma() {
        let elevated = Color::hex_u24(0x04090D).elevate_by(0.02);

        assert_eq!(elevated, Color::Rgb(7, 14, 19));
    }

    #[test]
    fn elevate_fades_chroma_in_continuously_next_to_black() {
        let black = Color::Black.elevate_by(0.10).to_rgb().unwrap();
        let tinted = Color::rgb(0, 0, 1).elevate_by(0.10).to_rgb().unwrap();

        assert!(black.0.abs_diff(tinted.0) <= 3, "{black:?} -> {tinted:?}");
        assert!(black.1.abs_diff(tinted.1) <= 3, "{black:?} -> {tinted:?}");
        assert!(black.2.abs_diff(tinted.2) <= 3, "{black:?} -> {tinted:?}");
    }

    #[test]
    fn elevate_tiny_amount_keeps_low_chroma_color_stable() {
        let color = Color::rgb(20, 21, 22);

        assert_eq!(color.elevate_by(0.001), color);
    }

    #[test]
    fn elevate_is_continuous_around_old_near_black_cutoff() {
        let below = Color::rgb(4, 11, 14).elevate_by(0.10).to_rgb().unwrap();
        let above = Color::rgb(4, 12, 14).elevate_by(0.10).to_rgb().unwrap();

        assert!(below.0.abs_diff(above.0) <= 2);
        assert!(below.1.abs_diff(above.1) <= 2);
        assert!(below.2.abs_diff(above.2) <= 2);
    }

    #[test]
    fn elevate_handles_black_and_white_endpoints() {
        assert_eq!(Color::Black.elevate_by(1.0), Color::Rgb(255, 255, 255));
        assert_eq!(Color::White.elevate_by(1.0), Color::Rgb(0, 0, 0));
    }

    #[test]
    fn elevate_keeps_small_neutral_surfaces_visible() {
        assert_eq!(Color::Black.elevate_by(0.04), Color::Rgb(10, 10, 10));
        assert_eq!(Color::Black.elevate_by(0.07), Color::Rgb(18, 18, 18));
        assert_eq!(Color::White.elevate_by(0.04), Color::Rgb(245, 245, 245));
    }

    #[test]
    fn elevate_leaves_non_rgb_colors_unchanged() {
        assert_eq!(Color::Reset.elevate_by(0.2), Color::Reset);
    }

    #[test]
    fn blend_toward_zero_keeps_color() {
        assert_eq!(
            Color::rgb(100, 120, 140).blend_toward(Color::rgb(200, 0, 0), 0.0),
            Color::Rgb(100, 120, 140)
        );
    }

    #[test]
    fn blend_toward_one_yields_target() {
        assert_eq!(
            Color::rgb(100, 120, 140).blend_toward(Color::rgb(200, 10, 30), 1.0),
            Color::Rgb(200, 10, 30)
        );
    }

    #[test]
    fn blend_toward_midpoint() {
        assert_eq!(
            Color::rgb(0, 0, 0).blend_toward(Color::rgb(100, 200, 50), 0.5),
            Color::Rgb(50, 100, 25)
        );
    }

    #[test]
    fn blend_toward_reset_source_treats_as_black() {
        // Reset is treated as black (0,0,0) for blending.
        assert_eq!(
            Color::Reset.blend_toward(Color::rgb(100, 0, 200), 0.5),
            Color::Rgb(50, 0, 100)
        );
    }

    #[test]
    fn blend_toward_reset_target_returns_unchanged() {
        // Cannot blend toward Reset - original color returned.
        assert_eq!(
            Color::rgb(100, 120, 140).blend_toward(Color::Reset, 0.5),
            Color::Rgb(100, 120, 140)
        );
    }

    #[test]
    fn blend_toward_transparent_target_returns_unchanged() {
        assert_eq!(
            Color::rgb(100, 120, 140).blend_toward(Color::Transparent, 0.5),
            Color::Rgb(100, 120, 140)
        );
    }

    #[test]
    fn blend_toward_handles_ansi_and_indexed() {
        assert_ne!(
            Color::LightBlue.blend_toward(Color::rgb(200, 0, 0), 0.5),
            Color::LightBlue
        );
        assert_ne!(
            Color::Indexed(214).blend_toward(Color::rgb(0, 0, 200), 0.5),
            Color::Indexed(214)
        );
    }

    #[test]
    fn hex_6char() {
        assert_eq!(Color::hex("#FF5733"), Color::Rgb(0xFF, 0x57, 0x33));
        assert_eq!(Color::hex("a32525"), Color::Rgb(0xa3, 0x25, 0x25));
    }

    #[test]
    fn hex_u24_matches_rgb_channels() {
        assert_eq!(Color::hex_u24(0xFF_57_33), Color::Rgb(0xFF, 0x57, 0x33));
        assert_eq!(Color::hex_u24(0x00_2B_36), Color::Rgb(0x00, 0x2B, 0x36));
    }

    #[test]
    fn hex_8char_alpha_rejected() {
        assert_eq!(Color::hex("#a32525ff"), Color::Reset);
        assert_eq!(Color::hex("FF573380"), Color::Reset);
    }

    #[test]
    fn hex_3char_shorthand() {
        // #F80 → #FF8800
        assert_eq!(Color::hex("#F80"), Color::Rgb(0xFF, 0x88, 0x00));
        assert_eq!(Color::hex("abc"), Color::Rgb(0xAA, 0xBB, 0xCC));
    }

    #[test]
    fn hex_4char_shorthand_alpha_rejected() {
        assert_eq!(Color::hex("#F80A"), Color::Reset);
    }

    #[test]
    fn hex_invalid_input_falls_back_to_reset() {
        assert_eq!(Color::hex("#FF"), Color::Reset);
        assert_eq!(Color::hex("#FF573"), Color::Reset);
        assert_eq!(Color::hex("#FF57338"), Color::Reset);
        assert_eq!(Color::hex("#FF5733801"), Color::Reset);
        assert_eq!(Color::hex("#GG5733"), Color::Reset);
        assert_eq!(Color::hex("#caf🙂"), Color::Reset);
    }

    #[test]
    fn try_hex_stays_fallible_for_internal_parsers() {
        assert_eq!(
            Color::try_hex("#FF5733"),
            Some(Color::Rgb(0xFF, 0x57, 0x33))
        );
        assert_eq!(Color::try_hex("#FF"), None);
        assert_eq!(Color::try_hex("#FF573380"), None);
        assert_eq!(Color::try_hex("#F808"), None);
    }

    #[test]
    fn paint_from_color_preserves_special_colors() {
        assert_eq!(
            Paint::from(Color::Transparent),
            Paint::Solid(Color::Transparent)
        );
        assert_eq!(Paint::solid(Color::Backdrop), Paint::Solid(Color::Backdrop));
        assert!(Paint::from(Color::Transparent).is_transparent_paint());
        assert!(!Paint::solid(Color::Backdrop).is_transparent_paint());
    }

    #[test]
    fn paint_constructors_canonicalize_opaque_alpha_only() {
        assert_eq!(
            Paint::rgb(0xFF, 0x57, 0x33),
            Paint::Solid(Color::Rgb(0xFF, 0x57, 0x33))
        );
        assert_eq!(
            Paint::rgba(0xFF, 0x57, 0x33, 255),
            Paint::Solid(Color::Rgb(0xFF, 0x57, 0x33))
        );
        assert_eq!(
            Paint::rgba(0xFF, 0x57, 0x33, 0),
            Paint::Alpha {
                color: Color::Rgb(0xFF, 0x57, 0x33),
                alpha: 0,
            }
        );
    }

    #[test]
    fn paint_alpha_helpers_and_accessors() {
        let paint = Paint::rgba(205, 0, 0, 128);
        assert_eq!(
            paint,
            Paint::Alpha {
                color: Color::Rgb(205, 0, 0),
                alpha: 128
            }
        );
        assert_eq!(paint.color(), Color::Rgb(205, 0, 0));
        assert_eq!(paint.alpha_u8(), 128);
        assert!((paint.alpha() - (128.0 / 255.0)).abs() < f32::EPSILON);
        assert!(!paint.is_opaque());
        assert!(!paint.is_transparent_paint());

        assert!(Paint::rgba(0, 0, 255, 255).is_opaque());
        assert!(Paint::rgba(0, 0, 255, 0).is_transparent_paint());
    }

    #[test]
    fn paint_hex_preserves_8char_alpha() {
        assert_eq!(
            Paint::hex("#a3252500"),
            Paint::Alpha {
                color: Color::Rgb(0xa3, 0x25, 0x25),
                alpha: 0x00,
            }
        );
        assert_eq!(
            Paint::hex("FF573380"),
            Paint::Alpha {
                color: Color::Rgb(0xFF, 0x57, 0x33),
                alpha: 0x80,
            }
        );
        assert_eq!(
            Paint::hex("#a32525ff"),
            Paint::Solid(Color::Rgb(0xa3, 0x25, 0x25))
        );
    }

    #[test]
    fn paint_hex_preserves_4char_shorthand_alpha() {
        assert_eq!(
            Paint::hex("#F80A"),
            Paint::Alpha {
                color: Color::Rgb(0xFF, 0x88, 0x00),
                alpha: 0xAA,
            }
        );
        assert_eq!(
            Paint::hex("#F80F"),
            Paint::Solid(Color::Rgb(0xFF, 0x88, 0x00))
        );
    }

    #[test]
    fn paint_flatten_over_solid_returns_pigment() {
        assert_eq!(
            Paint::Solid(Color::rgb(10, 20, 30)).flatten_over(Color::rgb(200, 200, 200)),
            Color::Rgb(10, 20, 30)
        );
    }

    #[test]
    fn paint_flatten_over_alpha_blends_against_backdrop() {
        // 50% red over blue → midpoint
        assert_eq!(
            Paint::rgba(200, 0, 0, 128).flatten_over(Color::rgb(0, 0, 200)),
            Color::Rgb(100, 0, 100)
        );
        // Fully transparent → preserves backdrop
        assert_eq!(
            Paint::rgba(200, 0, 0, 0).flatten_over(Color::rgb(0, 0, 200)),
            Color::Rgb(0, 0, 200)
        );
        // Fully opaque → pigment
        assert_eq!(
            Paint::rgba(200, 0, 0, 255).flatten_over(Color::rgb(0, 0, 200)),
            Color::Rgb(200, 0, 0)
        );
    }

    #[test]
    fn paint_flatten_over_unresolvable_backdrop_returns_pigment() {
        assert_eq!(
            Paint::rgba(200, 0, 0, 128).flatten_over(Color::Reset),
            Color::Rgb(200, 0, 0)
        );
        assert_eq!(
            Paint::rgba(200, 0, 0, 128).flatten_over(Color::Transparent),
            Color::Rgb(200, 0, 0)
        );
    }

    #[test]
    fn paint_try_hex_rejects_invalid_input() {
        assert_eq!(Paint::try_hex("#FF"), None);
        assert_eq!(Paint::try_hex("#FF573"), None);
        assert_eq!(Paint::try_hex("#FF57338"), None);
        assert_eq!(Paint::try_hex("#FF5733801"), None);
        assert_eq!(Paint::try_hex("#GG5733"), None);
        assert_eq!(Paint::try_hex("#caf🙂"), None);
    }
}