clankerdiff-theme 0.1.0

Renderer-neutral themes and palettes for Diff
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
//! Renderer-neutral colors, semantic diff palettes, and syntax themes.

use arborium_theme::{HIGHLIGHTS, ThemeSlot, builtin, slot_to_highlight_index};
pub use clankerdiff_fingerprint::{Fingerprint, FingerprintError};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt};

/// An sRGB color with an explicit alpha channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Rgba {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Rgba {
    #[must_use]
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Composites this color over an opaque background.
    #[must_use]
    pub const fn over(self, background: Self) -> Self {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "weighted u8 average fits in u8"
        )]
        const fn channel(foreground: u8, background: u8, alpha: u8) -> u8 {
            let foreground = foreground as u32 * alpha as u32;
            let background = background as u32 * (u8::MAX - alpha) as u32;
            ((foreground + background + 127) / 255) as u8
        }
        Self::new(
            channel(self.r, background.r, self.a),
            channel(self.g, background.g, self.a),
            channel(self.b, background.b, self.a),
            u8::MAX,
        )
    }

    #[must_use]
    pub const fn to_bytes(self) -> [u8; 4] {
        [self.r, self.g, self.b, self.a]
    }
}

impl Default for Rgba {
    fn default() -> Self {
        Self::new(212, 221, 214, 255)
    }
}

/// Text modifiers returned by the syntax engine.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FontStyle {
    #[serde(default)]
    pub bold: bool,
    #[serde(default)]
    pub italic: bool,
    #[serde(default)]
    pub underline: bool,
}

impl FontStyle {
    #[must_use]
    pub const fn none() -> Self {
        Self {
            bold: false,
            italic: false,
            underline: false,
        }
    }

    #[must_use]
    pub const fn is_plain(self) -> bool {
        !self.bold && !self.italic && !self.underline
    }
}

/// A highlighted, UTF-8-safe byte range into the supplied source.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HighlightSpan {
    pub range: std::ops::Range<usize>,
    pub foreground: Rgba,
    pub font_style: FontStyle,
}

/// Style assigned to a Tree-sitter capture name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyntaxStyle {
    pub foreground: Rgba,
    #[serde(default)]
    pub font_style: FontStyle,
}

/// Semantic tint for a diff cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DiffTone {
    Context,
    Added,
    Removed,
    Meta,
}

impl DiffTone {
    #[must_use]
    pub const fn marker(self) -> char {
        match self {
            Self::Added => '+',
            Self::Removed => '-',
            Self::Context | Self::Meta => ' ',
        }
    }
}

/// Foreground and background colors resolved for one [`DiffTone`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ToneColors {
    pub foreground: Rgba,
    pub background: Rgba,
}

/// Colors used by diff renderers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffPalette {
    pub background: Rgba,
    pub foreground: Rgba,
    pub gutter: Rgba,
    pub addition: Rgba,
    pub deletion: Rgba,
    pub addition_background: Rgba,
    pub deletion_background: Rgba,
    pub selection: Rgba,
    pub accent: Rgba,
    pub muted: Rgba,
    pub border: Rgba,
}

impl DiffPalette {
    #[must_use]
    pub const fn tone(&self, tone: DiffTone) -> ToneColors {
        match tone {
            DiffTone::Added => ToneColors {
                foreground: self.addition,
                background: self.addition_background,
            },
            DiffTone::Removed => ToneColors {
                foreground: self.deletion,
                background: self.deletion_background,
            },
            DiffTone::Context | DiffTone::Meta => ToneColors {
                foreground: self.foreground,
                background: self.background,
            },
        }
    }

    #[must_use]
    pub const fn colors(&self) -> [Rgba; 11] {
        [
            self.background,
            self.foreground,
            self.gutter,
            self.addition,
            self.deletion,
            self.addition_background,
            self.deletion_background,
            self.selection,
            self.accent,
            self.muted,
            self.border,
        ]
    }
}

/// Alpha applied to the canvas color when it backs a modal scrim.
pub const SCRIM_ALPHA: u8 = 184;

/// Renderer-neutral application colors derived from a diff palette.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UiPalette {
    pub canvas: Rgba,
    pub surface: Rgba,
    pub surface_hover: Rgba,
    pub surface_selected: Rgba,
    pub text: Rgba,
    pub text_muted: Rgba,
    pub border: Rgba,
    pub accent: Rgba,
    pub accent_foreground: Rgba,
    pub positive: Rgba,
    pub destructive: Rgba,
    pub scrim: Rgba,
}

/// Semantic intent shared by renderer-native action controls.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ButtonVariant {
    Primary,
    Secondary,
    Destructive,
    #[default]
    Ghost,
}

/// Interaction state shared by renderer-native controls.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum InteractionState {
    #[default]
    Rest,
    Hovered,
    Disabled,
}

/// Complete semantic state for an action control.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ControlState {
    pub interaction: InteractionState,
    pub selected: bool,
}

impl ControlState {
    #[must_use]
    pub const fn new(interaction: InteractionState) -> Self {
        Self {
            interaction,
            selected: false,
        }
    }

    #[must_use]
    pub const fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }
}

/// Semantic size shared by renderer-native controls.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ControlSize {
    Small,
    #[default]
    Medium,
}

/// Semantic state for selectable content.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SelectionState {
    #[default]
    None,
    Selected,
    Focused,
    Disabled,
}

/// Semantic tone for notices and status messages.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum NoticeTone {
    #[default]
    Info,
    Positive,
    Warning,
    Error,
}

/// Cross-renderer modal size category.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ModalSize {
    Compact,
    #[default]
    Medium,
    Wide,
}

/// Renderer-neutral visual result for one semantic component state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SemanticStyle {
    pub foreground: Rgba,
    pub background: Option<Rgba>,
    pub emphasized: bool,
}

impl UiPalette {
    /// Resolves an action control without renderer-specific state ordering.
    #[must_use]
    pub const fn control_style(self, variant: ButtonVariant, state: ControlState) -> SemanticStyle {
        if matches!(state.interaction, InteractionState::Disabled) {
            return SemanticStyle {
                foreground: self.text_muted,
                background: Some(self.surface_selected),
                emphasized: false,
            };
        }
        let (foreground, background) = match (variant, state.interaction, state.selected) {
            (ButtonVariant::Primary, _, _) => (self.accent_foreground, Some(self.accent)),
            (ButtonVariant::Destructive, _, _) => (self.accent_foreground, Some(self.destructive)),
            (ButtonVariant::Ghost, _, true) => (self.accent, Some(self.surface_selected)),
            (ButtonVariant::Secondary | ButtonVariant::Ghost, InteractionState::Hovered, _) => {
                (self.text, Some(self.surface_hover))
            }
            (ButtonVariant::Secondary, _, _) => (self.text, Some(self.surface_selected)),
            (ButtonVariant::Ghost, _, false) => (self.text_muted, None),
        };
        SemanticStyle {
            foreground,
            background,
            emphasized: state.selected,
        }
    }

    /// Resolves selectable content consistently across renderers.
    #[must_use]
    pub const fn selection_style(self, state: SelectionState) -> SemanticStyle {
        match state {
            SelectionState::None => SemanticStyle {
                foreground: self.text,
                background: Some(self.surface),
                emphasized: false,
            },
            SelectionState::Selected => SemanticStyle {
                foreground: self.accent,
                background: Some(self.surface_selected),
                emphasized: false,
            },
            SelectionState::Focused => SemanticStyle {
                foreground: self.accent_foreground,
                background: Some(self.accent),
                emphasized: true,
            },
            SelectionState::Disabled => SemanticStyle {
                foreground: self.text_muted,
                background: Some(self.surface),
                emphasized: false,
            },
        }
    }

    /// Resolves the foreground used to communicate a notice tone.
    #[must_use]
    pub const fn notice_style(self, tone: NoticeTone) -> SemanticStyle {
        let foreground = match tone {
            NoticeTone::Info => self.text_muted,
            NoticeTone::Positive => self.positive,
            NoticeTone::Warning => self.accent,
            NoticeTone::Error => self.destructive,
        };
        SemanticStyle {
            foreground,
            background: None,
            emphasized: matches!(tone, NoticeTone::Warning | NoticeTone::Error),
        }
    }
}

impl From<&DiffPalette> for UiPalette {
    fn from(palette: &DiffPalette) -> Self {
        let mut scrim = palette.background;
        scrim.a = SCRIM_ALPHA;
        Self {
            canvas: palette.background,
            surface: palette.background,
            surface_hover: palette.selection,
            surface_selected: palette.selection,
            text: palette.foreground,
            text_muted: palette.muted,
            border: palette.border,
            accent: palette.accent,
            accent_foreground: palette.background,
            positive: palette.addition,
            destructive: palette.deletion,
            scrim,
        }
    }
}

impl Default for DiffPalette {
    fn default() -> Self {
        let background = Rgba::new(21, 29, 31, 255);
        let addition = Rgba::new(179, 215, 98, 255);
        let deletion = Rgba::new(223, 120, 122, 255);
        Self {
            background,
            foreground: Rgba::default(),
            gutter: Rgba::new(80, 96, 91, 255),
            addition,
            deletion,
            addition_background: diff_background(addition, background),
            deletion_background: diff_background(deletion, background),
            selection: Rgba::new(143, 188, 176, 45),
            accent: Rgba::new(143, 188, 176, 255),
            muted: Rgba::new(125, 143, 136, 255),
            border: Rgba::new(57, 73, 73, 255),
        }
    }
}

/// Stable identifiers for embedded and host-provided themes.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ThemeId {
    #[default]
    Sage,
    Ayu,
    Builtin(String),
    Custom(String),
}

impl fmt::Display for ThemeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Sage => f.write_str("sage"),
            Self::Ayu => f.write_str("ayu-dark"),
            Self::Builtin(name) | Self::Custom(name) => f.write_str(name),
        }
    }
}

/// Summary metadata for a theme offered by the built-in catalog.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThemeDescriptor {
    pub id: String,
    pub name: String,
    pub is_dark: bool,
    pub source_url: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ThemeDocument {
    version: u32,
    palette: DiffPalette,
    syntax: BTreeMap<String, SyntaxStyle>,
}

/// A capture-based syntax theme plus semantic colors for the diff UI.
#[derive(Debug, Clone)]
pub struct DiffTheme {
    id: ThemeId,
    palette: DiffPalette,
    syntax: BTreeMap<String, SyntaxStyle>,
    revision: Fingerprint,
}

impl DiffTheme {
    /// Starts a builder for a host-provided syntax theme.
    pub fn builder(id: impl Into<String>) -> SyntaxThemeBuilder {
        SyntaxThemeBuilder {
            id: ThemeId::Custom(id.into()),
            palette: DiffPalette::default(),
            syntax: BTreeMap::new(),
        }
    }

    /// Parses a versioned Diff theme JSON document.
    ///
    /// Capture lookup first tries an exact name and then progressively removes
    /// dot-separated suffixes. The full parsed palette and map affect revision.
    ///
    /// # Errors
    /// Returns an error for malformed JSON or an unsupported schema version.
    pub fn from_bytes(id: ThemeId, bytes: &[u8]) -> Result<Self, ThemeError> {
        let document: ThemeDocument =
            serde_json::from_slice(bytes).map_err(|source| ThemeError::Parse {
                message: source.to_string(),
            })?;
        if document.version != 1 {
            return Err(ThemeError::UnsupportedVersion {
                version: document.version,
            });
        }
        let canonical = serde_json::to_vec(&document).map_err(|source| ThemeError::Parse {
            message: source.to_string(),
        })?;
        let revision = Fingerprint::of([id.to_string().as_bytes(), canonical.as_slice()]);
        Ok(Self {
            id,
            palette: document.palette,
            syntax: document.syntax,
            revision,
        })
    }

    #[must_use]
    pub const fn id(&self) -> &ThemeId {
        &self.id
    }

    #[must_use]
    pub const fn palette(&self) -> &DiffPalette {
        &self.palette
    }

    #[must_use]
    pub const fn revision(&self) -> Fingerprint {
        self.revision
    }

    /// Resolves an exact capture or its nearest dot-separated parent.
    #[must_use]
    pub fn style(&self, capture: &str) -> Option<SyntaxStyle> {
        let mut candidate = capture;
        loop {
            if let Some(style) = self.syntax.get(candidate) {
                return Some(*style);
            }
            let (parent, _) = candidate.rsplit_once('.')?;
            candidate = parent;
        }
    }

    /// Returns all selectable built-in themes, with stable kebab-case identifiers.
    #[must_use]
    pub fn catalog() -> Vec<ThemeDescriptor> {
        let mut themes = vec![ThemeDescriptor {
            id: "sage".to_owned(),
            name: "Sage".to_owned(),
            is_dark: true,
            source_url: None,
        }];
        themes.extend(builtin::all().into_iter().map(|theme| ThemeDescriptor {
            id: theme_slug(&theme.name),
            name: theme.name,
            is_dark: theme.is_dark,
            source_url: theme.source_url,
        }));
        themes.sort_by(|left, right| {
            left.is_dark
                .cmp(&right.is_dark)
                .reverse()
                .then_with(|| left.name.cmp(&right.name))
        });
        themes
    }

    /// Loads a selectable built-in theme by its stable identifier.
    ///
    /// Aliases are matched case-insensitively and with spaces or underscores
    /// normalized to dashes.
    ///
    /// # Errors
    /// Returns an error when no built-in theme has the supplied identifier.
    pub fn builtin(name: &str) -> Result<Self, ThemeError> {
        let id = theme_slug(name);
        if id == "sage" {
            return Self::sage();
        }
        if id == "ayu" || id == "ayu-dark" {
            return Self::ayu();
        }
        let source = builtin::all()
            .into_iter()
            .find(|theme| theme_slug(&theme.name) == id)
            .ok_or_else(|| ThemeError::UnknownTheme {
                name: name.to_owned(),
            })?;
        Ok(Self::from_arborium(ThemeId::Builtin(id), &source))
    }

    fn from_arborium(id: ThemeId, source: &arborium_theme::Theme) -> Self {
        let palette = palette_from_arborium(source);
        let syntax = HIGHLIGHTS
            .iter()
            .zip(source.styles.iter())
            .filter_map(|(highlight, style)| {
                let foreground = style.fg?;
                Some((
                    highlight.name.to_owned(),
                    SyntaxStyle {
                        foreground: rgba(foreground),
                        font_style: FontStyle {
                            bold: style.modifiers.bold,
                            italic: style.modifiers.italic,
                            underline: style.modifiers.underline,
                        },
                    },
                ))
            })
            .collect::<BTreeMap<_, _>>();
        let mut revision_parts = vec![id.to_string().into_bytes()];
        revision_parts.extend(palette.colors().map(|color| color.to_bytes().to_vec()));
        for (capture, style) in &syntax {
            revision_parts.push(capture.as_bytes().to_vec());
            revision_parts.push(style.foreground.to_bytes().to_vec());
            revision_parts.push(vec![
                u8::from(style.font_style.bold),
                u8::from(style.font_style.italic),
                u8::from(style.font_style.underline),
            ]);
        }
        let revision = Fingerprint::of(revision_parts.iter().map(Vec::as_slice));
        Self {
            id,
            palette,
            syntax,
            revision,
        }
    }

    /// Loads the bundled Sage theme.
    ///
    /// # Errors
    /// Returns an error if the checked-in theme JSON is invalid.
    pub fn sage() -> Result<Self, ThemeError> {
        Self::from_bytes(ThemeId::Sage, include_bytes!("../assets/themes/sage.json"))
    }
    /// Loads the bundled Ayu Dark theme.
    ///
    /// # Errors
    /// Returns an error if the checked-in theme JSON is invalid.
    pub fn ayu() -> Result<Self, ThemeError> {
        Self::from_bytes(
            ThemeId::Ayu,
            include_bytes!("../assets/themes/ayu-dark.json"),
        )
    }
}

fn theme_slug(name: &str) -> String {
    name.trim()
        .chars()
        .map(|character| match character {
            ' ' | '_' => '-',
            character => character.to_ascii_lowercase(),
        })
        .collect()
}

const fn rgba(color: arborium_theme::Color) -> Rgba {
    Rgba::new(color.r, color.g, color.b, u8::MAX)
}

fn palette_from_arborium(theme: &arborium_theme::Theme) -> DiffPalette {
    let background = theme.background.map_or_else(
        || {
            if theme.is_dark {
                Rgba::new(21, 29, 31, 255)
            } else {
                Rgba::new(250, 250, 250, 255)
            }
        },
        rgba,
    );
    let foreground = theme.foreground.map_or_else(
        || {
            if theme.is_dark {
                Rgba::new(220, 220, 220, 255)
            } else {
                Rgba::new(35, 35, 35, 255)
            }
        },
        rgba,
    );
    let style_color = |slot| {
        slot_to_highlight_index(slot)
            .and_then(|index| theme.style(index))
            .and_then(|style| style.fg)
            .map(rgba)
    };
    let addition = style_color(ThemeSlot::DiffAdd).unwrap_or_else(|| {
        if theme.is_dark {
            Rgba::new(128, 190, 120, 255)
        } else {
            Rgba::new(40, 125, 55, 255)
        }
    });
    let deletion = style_color(ThemeSlot::DiffDelete).unwrap_or_else(|| {
        if theme.is_dark {
            Rgba::new(225, 115, 115, 255)
        } else {
            Rgba::new(185, 45, 45, 255)
        }
    });
    let accent = style_color(ThemeSlot::Link)
        .or_else(|| style_color(ThemeSlot::Function))
        .or_else(|| style_color(ThemeSlot::Keyword))
        .unwrap_or_else(|| mix(foreground, background, 72));
    DiffPalette {
        background,
        foreground,
        gutter: mix(foreground, background, 45),
        addition,
        deletion,
        addition_background: diff_background(addition, background),
        deletion_background: diff_background(deletion, background),
        selection: mix(accent, background, 28),
        accent,
        muted: mix(foreground, background, 62),
        border: mix(foreground, background, 25),
    }
}

const fn mix(foreground: Rgba, background: Rgba, amount: u8) -> Rgba {
    Rgba::new(foreground.r, foreground.g, foreground.b, amount).over(background)
}

const DIFF_BACKGROUND_ALPHA: u8 = 31;
const fn diff_background(foreground: Rgba, background: Rgba) -> Rgba {
    Rgba::new(
        foreground.r,
        foreground.g,
        foreground.b,
        DIFF_BACKGROUND_ALPHA,
    )
    .over(background)
}

impl Default for DiffTheme {
    fn default() -> Self {
        Self::sage().expect("bundled Sage theme JSON must parse")
    }
}

/// Builder for syntax themes without exposing the capture map representation.
pub struct SyntaxThemeBuilder {
    id: ThemeId,
    palette: DiffPalette,
    syntax: BTreeMap<String, SyntaxStyle>,
}
impl SyntaxThemeBuilder {
    /// Assigns a style to an exact capture or parent capture prefix.
    #[must_use]
    pub fn capture(mut self, name: impl Into<String>, style: SyntaxStyle) -> Self {
        self.syntax.insert(name.into(), style);
        self
    }
    /// Sets the semantic diff palette retained by compatibility aggregate themes.
    #[must_use]
    pub fn palette(mut self, palette: DiffPalette) -> Self {
        self.palette = palette;
        self
    }
    /// Builds the immutable theme and derives its stable revision.
    ///
    /// # Errors
    /// Returns an error if the internal versioned representation cannot be serialized.
    pub fn build(self) -> Result<SyntaxTheme, ThemeError> {
        let document = ThemeDocument {
            version: 1,
            palette: self.palette,
            syntax: self.syntax,
        };
        let bytes = serde_json::to_vec(&document).map_err(|error| ThemeError::Parse {
            message: error.to_string(),
        })?;
        DiffTheme::from_bytes(self.id, &bytes)
    }
}

/// A syntax-only theme view. This alias keeps the capture API compact while
/// allowing callers to depend on the syntax boundary rather than the diff UI.
pub type SyntaxTheme = DiffTheme;

/// Semantic Markdown roles used by renderer adapters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MarkdownPalette {
    pub heading: Rgba,
    pub link: Rgba,
    pub quote: Rgba,
    pub code: Rgba,
}

impl Default for MarkdownPalette {
    fn default() -> Self {
        let palette = DiffPalette::default();
        Self {
            heading: palette.accent,
            link: palette.accent,
            quote: palette.muted,
            code: palette.foreground,
        }
    }
}

/// Aggregate theme shared by terminal and desktop adapters.
#[derive(Debug, Clone)]
pub struct ReviewTheme {
    pub syntax: SyntaxTheme,
    pub markdown: MarkdownPalette,
    pub diff: DiffPalette,
}

impl ReviewTheme {
    /// Returns a stable revision derived from every renderer-visible theme value.
    ///
    /// Renderer caches should use this aggregate revision rather than the syntax
    /// revision alone so Markdown and diff palette changes also invalidate rows.
    #[must_use]
    pub fn revision(&self) -> Fingerprint {
        let mut fields = Vec::with_capacity(1 + self.diff.colors().len() + 4);
        fields.push(self.syntax.revision().as_bytes().to_vec());
        fields.extend(self.diff.colors().map(|color| color.to_bytes().to_vec()));
        fields.extend(
            [
                self.markdown.heading,
                self.markdown.link,
                self.markdown.quote,
                self.markdown.code,
            ]
            .map(|color| color.to_bytes().to_vec()),
        );
        Fingerprint::of(fields)
    }
}

impl Default for ReviewTheme {
    fn default() -> Self {
        let syntax = SyntaxTheme::default();
        Self {
            markdown: MarkdownPalette::default(),
            diff: syntax.palette().clone(),
            syntax,
        }
    }
}

impl From<DiffTheme> for ReviewTheme {
    fn from(syntax: DiffTheme) -> Self {
        Self {
            markdown: MarkdownPalette::default(),
            diff: syntax.palette().clone(),
            syntax,
        }
    }
}

/// Errors produced while loading theme JSON.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ThemeError {
    #[error("unknown built-in theme `{name}`")]
    UnknownTheme { name: String },
    #[error("failed to parse theme JSON: {message}")]
    Parse { message: String },
    #[error("unsupported theme JSON version {version}")]
    UnsupportedVersion { version: u32 },
}

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

    #[test]
    fn bundled_themes_parse_with_distinct_revisions() {
        let sage = DiffTheme::default();
        let ayu = DiffTheme::ayu().unwrap();
        assert_eq!(sage.id(), &ThemeId::Sage);
        assert_eq!(ayu.id(), &ThemeId::Ayu);
        assert_ne!(sage.revision(), ayu.revision());
    }

    #[test]
    fn arborium_catalog_loads_every_theme() {
        let catalog = DiffTheme::catalog();
        assert!(catalog.len() > 30);
        let mut ids = catalog
            .iter()
            .map(|theme| theme.id.as_str())
            .collect::<Vec<_>>();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), catalog.len());
        for descriptor in catalog {
            let theme = DiffTheme::builtin(&descriptor.id).unwrap();
            assert_eq!(theme.id().to_string(), descriptor.id);
            assert_ne!(theme.palette().foreground, theme.palette().background);
        }
    }

    #[test]
    fn capture_style_uses_parent_fallback() {
        let theme = DiffTheme::default();
        assert_eq!(
            theme.style("function.method.builtin"),
            theme.style("function.method")
        );
        assert!(theme.style("not-a-capture").is_none());
    }

    #[test]
    fn invalid_json_and_version_are_rejected() {
        assert!(matches!(
            DiffTheme::from_bytes(ThemeId::Custom("x".into()), b"{"),
            Err(ThemeError::Parse { .. })
        ));
        let bytes = include_bytes!("../assets/themes/sage.json");
        let changed =
            String::from_utf8_lossy(bytes).replacen("\"version\": 1", "\"version\": 2", 1);
        assert_eq!(
            DiffTheme::from_bytes(ThemeId::Sage, changed.as_bytes()).unwrap_err(),
            ThemeError::UnsupportedVersion { version: 2 }
        );
    }

    #[test]
    fn semantic_palette_values_remain_stable() {
        let sage = DiffTheme::default();
        let ayu = DiffTheme::ayu().unwrap();
        assert_eq!(sage.palette().addition, Rgba::new(167, 192, 128, 255));
        assert_eq!(sage.palette().deletion, Rgba::new(230, 126, 128, 255));
        assert_eq!(ayu.palette().addition, Rgba::new(194, 217, 76, 255));
        assert_eq!(ayu.palette().deletion, Rgba::new(255, 51, 51, 255));
    }

    #[test]
    fn font_style_serializes_as_named_flags() {
        let style = FontStyle {
            bold: true,
            italic: true,
            underline: false,
        };
        assert_eq!(
            serde_json::to_string(&style).unwrap(),
            r#"{"bold":true,"italic":true,"underline":false}"#
        );
    }
}