makeover 5.2.0

Shared theme loading for the make-family apps: TOML theme files parsed into intent-based color tokens, with perceptual derivations and WCAG contrast.
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
//! Intent resolution

use crate::{
    DISTINCT, Rgb, Rgba, STEP_FLOOR, ThemeColors, ThemeMeta, darken, lighten, mix, readable_on,
    wcag_contrast,
};
use serde::Serialize;
use std::collections::BTreeMap;

// Names this module's prose links to, resolved for rustdoc.
#[allow(unused_imports)]
use crate::derive_tonal_steps;

/// Declares [`Token`]: each variant with its CSS stem, and the list of all of
/// them. One table, so a stem cannot be spelled two ways.
macro_rules! tokens {
    ($($(#[$doc:meta])* $variant:ident => $stem:literal,)*) => {
        /// One resolved intent, by name.
        ///
        /// The CSS stem ([`as_str`](Self::as_str)) is the custom property a
        /// stylesheet reads, `--{stem}`, and the spelling a stored or
        /// serialised token uses. Ordered by that stem, so a
        /// [`SemanticTokens`] emits in the same order whichever way it is read.
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        pub enum Token {
            $($(#[$doc])* $variant,)*
        }

        impl Token {
            /// Every token, in declaration order.
            pub const ALL: &'static [Token] = &[$(Token::$variant,)*];

            /// The CSS stem: `--{stem}` in a stylesheet.
            pub const fn as_str(self) -> &'static str {
                match self {
                    $(Token::$variant => $stem,)*
                }
            }
        }
    };
}

tokens! {
    /// The page ground.
    SurfacePage => "surface-page",
    /// A surface raised off the page.
    SurfaceRaised => "surface-raised",
    /// A surface sunk into the page.
    SurfaceSunken => "surface-sunken",
    /// A surface floating over the page.
    SurfaceOverlay => "surface-overlay",
    /// The ink.
    Content => "content",
    /// The ink, one tonal step back.
    ContentSecondary => "content-secondary",
    /// The ink, two tonal steps back.
    ContentMuted => "content-muted",
    /// The interactive colour.
    Action => "action",
    Danger => "danger",
    Success => "success",
    Warning => "warning",
    Info => "info",
    Border => "border",
    CategoryOne => "category-one",
    CategoryTwo => "category-two",
    CategoryThree => "category-three",
    CategoryFour => "category-four",
    CategoryFive => "category-five",
    CategorySix => "category-six",
    /// [`Action`](Self::Action) under a pointer.
    ActionHover => "action-hover",
    /// Text that reads on [`Action`](Self::Action).
    ContentOnAction => "content-on-action",
    /// The keyboard focus ring.
    FocusRing => "focus-ring",
    /// The modal scrim. Translucent.
    Overlay => "overlay",
    /// The cast a floating surface throws on the page. Translucent.
    Elevation => "elevation",
    /// A bevel's lit edge.
    BevelLight => "bevel-light",
    /// A bevel's shadowed edge.
    BevelDark => "bevel-dark",
    /// An inset well in a raised surface.
    SurfaceWell => "surface-well",
    InfoSurface => "info-surface",
    SuccessSurface => "success-surface",
    WarningSurface => "warning-surface",
    DangerSurface => "danger-surface",
    InfoSurfaceHover => "info-surface-hover",
    SuccessSurfaceHover => "success-surface-hover",
    WarningSurfaceHover => "warning-surface-hover",
    DangerSurfaceHover => "danger-surface-hover",
    /// A table row under a pointer.
    RowHover => "row-hover",
    /// The hairline between table rows.
    RowRule => "row-rule",
    /// The row a keyboard cursor is on.
    RowSelected => "row-selected",
    /// A plain surface under a pointer.
    HoverSurface => "hover-surface",
    /// The emphatic border tier.
    BorderStrong => "border-strong",
}

impl Token {
    /// The token with this CSS stem, or `None`.
    pub fn parse(stem: &str) -> Option<Self> {
        Self::ALL
            .iter()
            .copied()
            .find(|token| token.as_str() == stem)
    }
}

impl Ord for Token {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_str().cmp(other.as_str())
    }
}

impl PartialOrd for Token {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl std::fmt::Display for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for Token {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// The look ratios the derivations use, one place.
///
/// Lightness deltas are OKLab L units and mix ratios interpolate in OKLab.
/// These are look decisions, measured against specimens rather than derived,
/// which is why each is named and documented rather than written inline.
pub mod ratio {
    /// How much lighter [`Token::ActionHover`](super::Token::ActionHover) is than the action.
    pub const ACTION_HOVER: f32 = 0.05;
    /// OKLab L the scrim and the elevation cast are pinned to: dark enough to
    /// read as absence of light on a light theme and a dark one alike.
    pub const SHADOW_L: f32 = 0.08;
    /// The scrim's opacity.
    pub const SCRIM_ALPHA: f32 = 0.5;
    /// The elevation cast's opacity. Between the two literal shadow scales it
    /// replaced: 0.10 read as nothing under a menu, 0.15 was invisible at
    /// plate size.
    pub const ELEVATION_ALPHA: f32 = 0.18;
    /// How far a bevel's lit edge is raised off its face.
    pub const BEVEL_LIGHT: f32 = 0.14;
    /// How far a bevel's shadowed edge is cut below its face. Deeper than the
    /// highlight, because an equal step down reads as a smaller change.
    pub const BEVEL_DARK: f32 = 0.18;
    /// A well's step toward lighter, on a theme whose text is darker than its
    /// face. The specimen's, measured: #D9DDF4 to #F3F5FD.
    pub const WELL_LIGHTER: f32 = 0.07;
    /// A well's step toward darker, on a theme whose text is lighter.
    pub const WELL_DARKER: f32 = 0.09;
    /// How much of a status tone a toned surface carries.
    pub const TONE_SURFACE: f32 = 0.12;
    /// The ink mixed into a table row under a pointer.
    pub const ROW_HOVER: f32 = 0.09;
    /// The ink mixed into the hairline between table rows.
    pub const ROW_RULE: f32 = 0.26;
    /// The action mixed into the cursor row: the most that keeps content at
    /// the text floor on every theme whose raised surface clears it.
    pub const ROW_SELECTED: f32 = 0.18;
    /// How far [`Token::BorderStrong`](super::Token::BorderStrong) steps away from the page.
    pub const BORDER_STRONG: f32 = 0.05;
}

/// Base intents: the TOML dotted source key each is read from, and its token.
///
/// Read straight from the loaded theme, which is not quite the same as read
/// from the file: `content.secondary` and `content.muted` are tonal steps of
/// `content.primary` and are filled in at load by [`derive_tonal_steps`], so
/// they arrive here already computed and take this path like any other.
pub const BASE_INTENTS: &[(&str, Token)] = &[
    ("surface.page", Token::SurfacePage),
    ("surface.raised", Token::SurfaceRaised),
    ("surface.sunken", Token::SurfaceSunken),
    ("surface.overlay", Token::SurfaceOverlay),
    ("content.primary", Token::Content),
    ("content.secondary", Token::ContentSecondary),
    ("content.muted", Token::ContentMuted),
    ("action.primary", Token::Action),
    ("status.danger", Token::Danger),
    ("status.success", Token::Success),
    ("status.warning", Token::Warning),
    ("status.info", Token::Info),
    ("line.border", Token::Border),
    ("category.one", Token::CategoryOne),
    ("category.two", Token::CategoryTwo),
    ("category.three", Token::CategoryThree),
    ("category.four", Token::CategoryFour),
    ("category.five", Token::CategoryFive),
    ("category.six", Token::CategorySix),
];

/// The four status tones, each with its resting and hovered surface.
const TONES: [(Token, Token, Token); 4] = [
    (Token::Info, Token::InfoSurface, Token::InfoSurfaceHover),
    (
        Token::Success,
        Token::SuccessSurface,
        Token::SuccessSurfaceHover,
    ),
    (
        Token::Warning,
        Token::WarningSurface,
        Token::WarningSurfaceHover,
    ),
    (
        Token::Danger,
        Token::DangerSurface,
        Token::DangerSurfaceHover,
    ),
];

/// A floor [`lift_to_floors`] could not clear, with how far it got.
///
/// Lifting converges for every palette a shipped theme carries, but an
/// imported palette owes the depth model nothing and can land an ink on
/// grounds that split it or exhaust the ramp, so an ink can stay under its
/// floor no matter how it is moved. Resolution records those rather than
/// shipping them silent.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UnmetFloor {
    /// The ink that missed.
    pub token: Token,
    /// The floor it was owed.
    pub floor: f32,
    /// The best contrast it reached against its grounds.
    pub achieved: f32,
}

/// A fully resolved intent layer: every token present, as a colour.
/// Includes both authored base intents and the computed derived intents.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticTokens {
    pub meta: ThemeMeta,
    /// Every token this theme resolved, in stem order.
    pub intents: BTreeMap<Token, Rgba>,
    /// Floors that could not be cleared, empty for every shipped theme.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unmet_floors: Vec<UnmetFloor>,
}

impl SemanticTokens {
    /// The resolved colour, alpha included.
    pub fn get(&self, token: Token) -> Option<Rgba> {
        self.intents.get(&token).copied()
    }

    /// The resolved colour, if it is opaque.
    ///
    /// `None` for a translucent token as for a missing one: `overlay` and
    /// `elevation` dropped to opaque would hand a native consumer a
    /// near-black where it asked for a scrim. Those want [`get`](Self::get)
    /// or [`rgba`](Self::rgba).
    pub fn color(&self, token: Token) -> Option<Rgb> {
        self.get(token).and_then(Rgba::opaque_rgb)
    }

    /// `#rrggbb` for an opaque token. `None` for a translucent one, as
    /// [`color`](Self::color).
    pub fn hex(&self, token: Token) -> Option<String> {
        self.color(token).map(Rgb::to_hex)
    }

    /// The CSS value a stylesheet gets: `#rrggbb`, or `rgba(...)` for a
    /// translucent token.
    pub fn css(&self, token: Token) -> Option<String> {
        self.get(token).map(Rgba::css)
    }

    /// `(r, g, b)` for an opaque token.
    pub fn rgb(&self, token: Token) -> Option<(u8, u8, u8)> {
        self.color(token).map(Rgb::tuple)
    }

    /// `(r, g, b, a)` with the alpha as 0-255, for any token. An opaque one
    /// comes back at 255, so a caller need not know which kind it asked for.
    pub fn rgba(&self, token: Token) -> Option<(u8, u8, u8, u8)> {
        self.get(token).map(Rgba::tuple)
    }
}

/// Resolve an authored theme into the full intent token set.
///
/// 1. Copy each present base intent from the authored colors.
/// 2. Compute the derived interactive states from the base intents, so every
///    consumer gets identical output.
///
/// Each derived token is emitted only when its source intents exist, mirroring
/// the skip-missing behavior of the rest of the crate.
pub fn resolve(theme: &ThemeColors) -> SemanticTokens {
    let mut base: BTreeMap<Token, Rgba> = BTreeMap::new();

    // 1. Base intents (authored). Only values that parse as a hex colour are
    // kept, so an authored value can never carry arbitrary bytes into the
    // emitted CSS (the resolved tokens are inlined into a `<style>` block by
    // the web server). A malformed value is skipped, like an absent one.
    for (src, token) in BASE_INTENTS {
        if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) {
            base.insert(*token, Rgba::opaque(rgb));
        }
    }

    let (intents, unmet_floors) = lift_to_floors(base);

    SemanticTokens {
        meta: theme.meta.clone(),
        intents,
        unmet_floors,
    }
}

/// Every derived token, computed from the base intents.
fn derive(base: &BTreeMap<Token, Rgba>) -> BTreeMap<Token, Rgba> {
    use ratio::{
        ACTION_HOVER, BEVEL_DARK, BEVEL_LIGHT, BORDER_STRONG, ELEVATION_ALPHA, ROW_HOVER, ROW_RULE,
        ROW_SELECTED, SCRIM_ALPHA, SHADOW_L, TONE_SURFACE, WELL_DARKER, WELL_LIGHTER,
    };

    let mut intents = base.clone();
    let get = |m: &BTreeMap<Token, Rgba>, token: Token| m.get(&token).and_then(|c| c.opaque_rgb());

    // 2. Derived intents: perceptual (OKLab) steps and WCAG-picked text.
    let mut derived: Vec<(Token, Rgba)> = Vec::new();
    let mut put = |token: Token, rgb: Rgb| derived.push((token, Rgba::opaque(rgb)));
    if let Some(action) = get(&intents, Token::Action) {
        put(Token::ActionHover, lighten(action, ACTION_HOVER));
        put(Token::ContentOnAction, readable_on(action));
        // The focus ring is the action colour itself, not a tint of it: a ring
        // is a statement that the keyboard is here, and a faded one reads as a
        // disabled control rather than an emphatic one.
        //
        // One ring, not one per primitive. Where the ring sits is a depth
        // question and not a per-component choice: a well takes it inside its
        // own edge and a raised surface takes it outside. That is one decision
        // with two renderings. This token is the one shared artifact; which
        // thing wears it, and how it is drawn, is each renderer's own (see
        // `makeover_layout`'s crate header, "reach, focus and the focus ring").
        //
        // A ring is a boundary between two areas, so it answers to the 3:1 two
        // areas need against every surface it is drawn on. An accent that misses
        // that keeps its hue and has its lightness moved until it clears.
        let grounds: Vec<Rgb> = [Token::SurfacePage, Token::SurfaceRaised]
            .into_iter()
            .filter_map(|ground| get(&intents, ground))
            .collect();
        put(Token::FocusRing, cleared(action, &grounds, DISTINCT));
    }
    if let Some(page) = get(&intents, Token::SurfacePage) {
        // Modal scrim and elevation cast: one near-black tone carrying a faint
        // hint of the theme's hue, at two weights. Anchored very dark so it
        // dims the page on light and dark themes alike.
        //
        // The cast is what a surface that FLOATS OVER the page throws on it:
        // menus, toasts, popovers and dropdowns. A card, a plate and a framed
        // image are IN the page and take a bevel instead. Geometry stays with
        // the consumer, the way bevel thickness does.
        let mut o = page.to_oklab();
        o.l = SHADOW_L;
        let shadow = Rgb::from_oklab(o);
        intents.insert(Token::Overlay, Rgba::translucent(shadow, SCRIM_ALPHA));
        intents.insert(Token::Elevation, Rgba::translucent(shadow, ELEVATION_ALPHA));
    }
    if let Some(raised) = get(&intents, Token::SurfaceRaised) {
        // The two edges of a bevel: a raised control is lit from the top left,
        // so its top and left edges take `bevel-light` and its bottom and right
        // edges `bevel-dark`. Inverting the pair gives a pressed state and an
        // inset well. Geometry (thickness, radius, which side gets which) stays
        // app-side.
        //
        // A face already at the top of the ramp cannot hold a highlight: the
        // lightening clamps. That is a property of the theme, not of this
        // derivation; `bevel_edges_are_distinct_from_their_face` names the
        // shipped themes it bites.
        put(Token::BevelLight, lighten(raised, BEVEL_LIGHT));
        put(Token::BevelDark, darken(raised, BEVEL_DARK));

        // An inset well: the content surface inside a raised container.
        // `surface-sunken` cannot serve, because a theme is free to author it
        // darker than raised and a well has to go the other way.
        //
        // The direction is read off `content` rather than off `Variant`: a
        // theme whose text is dark is a theme whose surfaces are light, whatever
        // its `variant` field claims. A face with no room in the requested
        // direction takes the other one (see `step_with_room`); `bevel-light`
        // does not, since a highlight darker than its face is a second shadow.
        if let Some(content) = get(&intents, Token::Content) {
            let content_is_darker = content.to_oklab().l < raised.to_oklab().l;
            let well = if content_is_darker {
                step_with_room(raised, WELL_LIGHTER)
            } else {
                step_with_room(raised, -WELL_DARKER)
            };
            put(Token::SurfaceWell, well);

            // A status chip's fill, wiki `table-model`: the raised ground with
            // some of the tone in it, edged in the tone, inked in `content`.
            // The hovered fill is built off the sunken ground the way
            // `hover-surface` is, so a toned control and a plain one travel the
            // same distance under a pointer.
            let sunken = get(&intents, Token::SurfaceSunken);
            for (tone, surface, hover) in TONES {
                if let Some(color) = get(&intents, tone) {
                    put(surface, mix(raised, color, TONE_SURFACE));
                    if let Some(sunken) = sunken {
                        put(hover, mix(sunken, color, TONE_SURFACE));
                    }
                }
            }

            // The table model's row tones, wiki `table-model`: the ink mixed
            // into the raised surface a table sits on. Toward `content` rather
            // than darker, for the reason the well reads its direction off
            // `content`. The hairline stays under the 3:1 that separates two
            // areas on purpose, since a row is not a region.
            //
            // No stripe tone. Alternate rows sit on `surface-page`, a step of
            // the theme's own neutral ramp, so the table separates its rows
            // with colours the theme already authored rather than a fourth
            // mix of its ink.
            put(Token::RowHover, mix(raised, content, ROW_HOVER));
            put(Token::RowRule, mix(raised, content, ROW_RULE));

            // The row a keyboard cursor is on, for a host that has one. The
            // accent rather than the ink, and a fill and never a foreground, so
            // a failed row stays red under it.
            if let Some(action) = get(&intents, Token::Action) {
                put(Token::RowSelected, mix(raised, action, ROW_SELECTED));
            }
        }
    }
    if let Some(sunken) = get(&intents, Token::SurfaceSunken) {
        put(Token::HoverSurface, sunken);
    }
    if let Some(border) = get(&intents, Token::Border) {
        // The emphatic border tier: one step further from the page than
        // `border` is, which is not the same as one step darker. Direction is
        // read off `content` against `surface-page`, because a dark theme's
        // ground is at the bottom of the ramp. A theme with no page or no
        // content keeps the darkening, the light-theme answer.
        let away_from_page = match (
            get(&intents, Token::Content),
            get(&intents, Token::SurfacePage),
        ) {
            (Some(content), Some(page)) => content.to_oklab().l > page.to_oklab().l,
            _ => false,
        };
        let strong = if away_from_page {
            lighten(border, BORDER_STRONG)
        } else {
            darken(border, BORDER_STRONG)
        };
        put(Token::BorderStrong, strong);
    }

    intents.extend(derived);
    intents
}

/// WCAG AA for normal text.
const TEXT: f32 = 4.5;

/// The muted tier's floor: present and readable, deliberately under body text.
const QUIET_TEXT: f32 = 3.0;

/// Each ink, the grounds it is set on, and the contrast it owes every one.
///
/// Resolution lifts each ink toward these floors along the theme's own ramp,
/// and leaves every ink that already clears exactly as authored. An imported
/// palette was drawn for syntax highlighting and owes the depth model nothing,
/// so its ink can land on grounds that split it or exhaust the ramp; when no
/// lift clears a floor, [`UnmetFloor`] records the shortfall instead of
/// shipping it silent. `tests/contrast_floors.rs` is the independent check,
/// and carries these rows.
const INK_FLOORS: &[(Token, &[Token], f32)] = &[
    (
        Token::Content,
        &[
            Token::SurfacePage,
            Token::SurfaceRaised,
            Token::SurfaceSunken,
            Token::SurfaceWell,
            Token::RowHover,
            Token::RowSelected,
            Token::InfoSurface,
            Token::SuccessSurface,
            Token::WarningSurface,
            Token::DangerSurface,
        ],
        TEXT,
    ),
    (
        Token::ContentSecondary,
        &[Token::SurfacePage, Token::SurfaceSunken, Token::SurfaceWell],
        TEXT,
    ),
    (
        Token::ContentMuted,
        &[Token::SurfacePage, Token::SurfaceWell],
        QUIET_TEXT,
    ),
];

/// How far one lift moves an ink, in OKLab lightness. Finer than 8-bit sRGB
/// resolves on the shortest ramp in the corpus, so no lift overshoots the
/// first value that clears by more than a code point.
const LIFT: f32 = 0.005;

/// The derived tokens, with every ink in [`INK_FLOORS`] clearing its floor.
///
/// A fixed point rather than one pass, because the grounds move with the inks:
/// the row tones are mixed toward `content`, so lifting it changes what it is
/// then measured against. Each round lifts every ink still under its floor one
/// [`LIFT`] and derives again. A theme with nothing under a floor leaves on the
/// first round with its tokens exactly as a single derivation gives them.
///
/// `content-secondary` and `content-muted` are tonal steps of `content`, so
/// they travel toward it, which is along the theme's own ramp. `content` has
/// no ink to travel toward and moves its lightness away from its grounds,
/// stepping in whichever direction raises its worst contrast. A secondary
/// that would come to sit closer to `content` than a tonal step may
/// ([`STEP_FLOOR`]) lifts `content` instead, which widens the room between
/// them.
///
/// The returned [`UnmetFloor`] list is empty whenever every floor cleared. A
/// theme whose ramp exhausted with a floor still under it is reported there
/// rather than shipped silent.
fn lift_to_floors(mut base: BTreeMap<Token, Rgba>) -> (BTreeMap<Token, Rgba>, Vec<UnmetFloor>) {
    // More rounds than the longest lift in the corpus needs: the whole ramp is
    // 1.0 of lightness, crossed at [`LIFT`] a round.
    const ROUNDS: usize = 400;

    let opaque =
        |m: &BTreeMap<Token, Rgba>, token: Token| m.get(&token).and_then(|c| c.opaque_rgb());
    for _ in 0..ROUNDS {
        let tokens = derive(&base);
        let mut moved = false;
        for &(ink, grounds, floor) in INK_FLOORS {
            let Some(color) = opaque(&tokens, ink) else {
                continue;
            };
            let grounds: Vec<Rgb> = grounds.iter().filter_map(|g| opaque(&tokens, *g)).collect();
            if worst(color, &grounds) >= floor {
                continue;
            }
            let lifted = match (ink, opaque(&tokens, Token::Content)) {
                (Token::Content, _) | (_, None) => away_from(color, &grounds, LIFT),
                (_, Some(content)) => {
                    if wcag_contrast(mix(color, content, 0.05), content) < STEP_FLOOR {
                        // No room left between this step and the ink: move the ink.
                        let ink_grounds: Vec<Rgb> = INK_FLOORS[0]
                            .1
                            .iter()
                            .filter_map(|g| opaque(&tokens, *g))
                            .collect();
                        let content_lifted = away_from(content, &ink_grounds, LIFT);
                        if content_lifted != content {
                            base.insert(Token::Content, Rgba::opaque(content_lifted));
                            moved = true;
                        }
                        continue;
                    }
                    mix(color, content, 0.05)
                }
            };
            if lifted != color {
                base.insert(ink, Rgba::opaque(lifted));
                moved = true;
            }
        }
        if !moved {
            let unmet = unmet_floors(&tokens);
            return (tokens, unmet);
        }
    }
    let tokens = derive(&base);
    let unmet = unmet_floors(&tokens);
    (tokens, unmet)
}

/// The [`INK_FLOORS`] entries `tokens` still misses, in floor order.
fn unmet_floors(tokens: &BTreeMap<Token, Rgba>) -> Vec<UnmetFloor> {
    let opaque =
        |m: &BTreeMap<Token, Rgba>, token: Token| m.get(&token).and_then(|c| c.opaque_rgb());
    INK_FLOORS
        .iter()
        .filter_map(|&(ink, grounds, floor)| {
            let color = opaque(tokens, ink)?;
            let grounds: Vec<Rgb> = grounds.iter().filter_map(|g| opaque(tokens, *g)).collect();
            let achieved = worst(color, &grounds);
            (achieved < floor).then_some(UnmetFloor {
                token: ink,
                floor,
                achieved,
            })
        })
        .collect()
}

/// The lowest contrast `ink` makes against any of `grounds`; infinite for none.
fn worst(ink: Rgb, grounds: &[Rgb]) -> f32 {
    grounds
        .iter()
        .map(|ground| wcag_contrast(ink, *ground))
        .fold(f32::INFINITY, f32::min)
}

/// `color` moved `step` away from the ground it reads worst against.
///
/// The ground the ink fails hardest on is the one that decides the floor, so it
/// is the one to move away from, not the mean of all of them. When the grounds
/// split the ink (half darker, half lighter) the mean sits beside it and the
/// step can run toward the very ground that is failing. When the binding ground
/// is the ink itself, "away" has no direction and the two endpoints are not
/// equal: WCAG's `+0.05` makes the darker direction the higher-ceiling one
/// below a mid-grey, so the tie is settled the same way a text picker settles
/// black against white.
fn away_from(color: Rgb, grounds: &[Rgb], step: f32) -> Rgb {
    let Some(binding) = grounds
        .iter()
        .min_by(|a, b| wcag_contrast(color, **a).total_cmp(&wcag_contrast(color, **b)))
    else {
        return color;
    };
    let darker = match binding.to_oklab().l.partial_cmp(&color.to_oklab().l) {
        Some(std::cmp::Ordering::Greater) => true,
        Some(std::cmp::Ordering::Less) => false,
        // The binding ground is the ink itself: settle black against white.
        _ => readable_on(*binding) == Rgb { r: 0, g: 0, b: 0 },
    };
    if darker {
        darken(color, step)
    } else {
        lighten(color, step)
    }
}

/// `color`, or the nearest lightness of its hue that clears `floor` against
/// every ground. Unchanged when it already does.
fn cleared(color: Rgb, grounds: &[Rgb], floor: f32) -> Rgb {
    let mut color = color;
    while worst(color, grounds) < floor {
        let next = away_from(color, grounds, LIFT);
        if next == color {
            break;
        }
        color = next;
    }
    color
}

/// The smallest OKLab L difference at which two fills read as two surfaces.
///
/// Below it a well and the face it is cut into are the same area to a reader,
/// and a derivation landing this close to the end of the ramp lands on anything
/// else that clamped there.
pub(crate) const MIN_VISIBLE_DELTA_L: f32 = 0.02;

/// Shift `c`'s OKLab lightness by `delta`, or by `-delta` when the requested
/// direction has no room.
///
/// "No room" is landing within [`MIN_VISIBLE_DELTA_L`] of either end of the
/// ramp. For a derivation whose only job is to differ from its base: a step
/// that clamps is indistinguishable from every other step that clamped.
fn step_with_room(c: Rgb, delta: f32) -> Rgb {
    let target = c.to_oklab().l + delta;
    if (MIN_VISIBLE_DELTA_L..=1.0 - MIN_VISIBLE_DELTA_L).contains(&target) {
        lighten(c, delta)
    } else {
        lighten(c, -delta)
    }
}

/// Emit the resolved intent layer as CSS declarations (no selector), one
/// `  --token: value;` line each, in stem order. The only place a token
/// becomes CSS text.
pub fn intent_css_declarations(tokens: &SemanticTokens) -> String {
    use std::fmt::Write as _;

    let mut out = String::new();
    for (token, color) in &tokens.intents {
        let _ = writeln!(out, "  --{token}: {color};");
    }
    out
}

/// Emit the resolved intent layer as a `:root { … }` block — the single TOML →
/// CSS mapping every web surface injects.
pub fn intent_css_vars(tokens: &SemanticTokens) -> String {
    format!(":root {{\n{}}}\n", intent_css_declarations(tokens))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fixture::nord_toml;
    use crate::{Emphasis, embedded_themes, emphasized, parse_theme_str};
    #[allow(unused_imports)]
    use crate::{ThemeDirs, ThemeId, Token};

    #[test]
    fn away_from_moves_away_from_the_binding_ground_not_the_mean() {
        // A mid-grey ink on one light and several dark grounds. The mean sits
        // below the ink, so the old rule lightened it toward the light ground
        // it already failed. The binding ground is the light one, so it has to
        // darken.
        let color = Rgb::from_hex("#808080").unwrap();
        let grounds = [
            Rgb::from_hex("#ffffff").unwrap(),
            Rgb::from_hex("#202020").unwrap(),
            Rgb::from_hex("#202020").unwrap(),
            Rgb::from_hex("#202020").unwrap(),
        ];
        let moved = away_from(color, &grounds, 0.05);
        assert!(
            moved.to_oklab().l < color.to_oklab().l,
            "moved {moved:?} lighter than {color:?}"
        );
    }

    #[test]
    fn away_from_darkens_when_the_binding_ground_is_the_ink() {
        // Everything one grey: darkening is the only direction that reaches
        // 4.5, since white on #808080 tops out around 3.95:1. The tie has to
        // settle on dark, the way a text picker settles black against white.
        let color = Rgb::from_hex("#808080").unwrap();
        let moved = away_from(color, &[color], 0.05);
        assert!(
            moved.to_oklab().l < color.to_oklab().l,
            "an all-#808080 ink must darken, got {moved:?}"
        );
    }

    #[test]
    fn resolve_base_intents_passthrough() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let t = resolve(&theme);
        assert_eq!(t.hex(Token::SurfacePage).as_deref(), Some("#2e3440"));
        assert_eq!(t.hex(Token::Content).as_deref(), Some("#d8dee9")); // content.primary -> content
        // Not a passthrough: a tonal step of the ink, whatever the file said.
        assert_eq!(
            t.hex(Token::ContentMuted).unwrap(),
            emphasized(
                Rgb::from_hex("#d8dee9").unwrap(),
                Rgb::from_hex("#2e3440").unwrap(),
                Emphasis::Muted
            )
            .to_hex()
        );
        assert_eq!(t.hex(Token::Action).as_deref(), Some("#81a1c1"));
        assert_eq!(t.hex(Token::Danger).as_deref(), Some("#bf616a"));
        assert_eq!(t.hex(Token::Border).as_deref(), Some("#4c566a"));
        assert_eq!(t.hex(Token::CategoryFive).as_deref(), Some("#b48ead"));
    }

    #[test]
    fn resolve_derived_intents() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let action = Rgb::from_hex("#81a1c1").unwrap();
        let page = Rgb::from_hex("#2e3440").unwrap();
        let _ = page;
        assert_eq!(
            t.hex(Token::ActionHover).unwrap(),
            lighten(action, 0.05).to_hex()
        );
        assert_eq!(
            t.hex(Token::ContentOnAction).unwrap(),
            readable_on(action).to_hex()
        );
        assert_eq!(t.hex(Token::FocusRing).as_deref(), Some("#81a1c1"));
        assert_eq!(t.hex(Token::HoverSurface).as_deref(), Some("#434c5e")); // = surface.sunken
        // The toned pair a pressable tinted surface needs: the resting tint off
        // the raised ground, the hover tint off the sunken one, so a toned
        // control travels the same distance under a pointer as a plain one.
        let raised = Rgb::from_hex("#3b4252").unwrap();
        let sunken = Rgb::from_hex("#434c5e").unwrap();
        let danger = Rgb::from_hex("#bf616a").unwrap();
        assert_eq!(
            t.hex(Token::DangerSurface).unwrap(),
            mix(raised, danger, 0.12).to_hex()
        );
        assert_eq!(
            t.hex(Token::DangerSurfaceHover).unwrap(),
            mix(sunken, danger, 0.12).to_hex()
        );
        assert_ne!(
            t.hex(Token::DangerSurface),
            t.hex(Token::DangerSurfaceHover)
        );
        // Pruned by the usage audit (0 consumers): action-active and selection.
        // Apps that need them derive inline via the shared mix().
        assert!(Token::parse("action-active").is_none());
        assert!(Token::parse("selection").is_none());
    }

    #[test]
    fn resolve_bevel_intents() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let raised = Rgb::from_hex("#3b4252").unwrap();
        assert_eq!(
            t.hex(Token::BevelLight).unwrap(),
            lighten(raised, 0.14).to_hex()
        );
        assert_eq!(
            t.hex(Token::BevelDark).unwrap(),
            darken(raised, 0.18).to_hex()
        );
    }

    // A bevel is two edges around one face, so both edges have to be visibly off
    // that face or the control never resolves as lit. The lightening clamps at
    // the top of the ramp, which means a theme authoring a white raised surface
    // gets a highlight identical to the surface it is meant to sit on.
    //
    // The list is asserted rather than merely reported so that changing a theme
    // has to come here and say so. Shrinking it is the fix; growing it is a
    // regression in the theme, not in this derivation.
    #[test]
    fn bevel_edges_are_distinct_from_their_face() {
        const CANNOT_BEVEL: &[&str] = &["neobrute", "oxocarbon-light"];

        let mut degenerate: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), source, false).unwrap();
            let t = resolve(&theme);
            let Some(raised) = t.hex(Token::SurfaceRaised) else {
                continue;
            };
            let light = t
                .hex(Token::BevelLight)
                .expect("raised implies bevel-light");
            let dark = t.hex(Token::BevelDark).expect("raised implies bevel-dark");
            if light == raised || dark == raised {
                degenerate.push(id.to_string());
            }
        }
        degenerate.sort();

        assert_eq!(
            degenerate, CANNOT_BEVEL,
            "themes whose raised surface cannot hold both bevel edges"
        );
    }

    // The well inverts by theme, so assert both directions explicitly rather
    // than only the one the light themes happen to take.
    #[test]
    fn resolve_well_intent_follows_the_content_direction() {
        // nord is dark: light text on a dark raised surface, so the well goes
        // down and away from the text.
        let dark =
            resolve(&parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap());
        let dark_raised = Rgb::from_hex("#3b4252").unwrap();
        assert_eq!(
            dark.hex(Token::SurfaceWell).unwrap(),
            darken(dark_raised, 0.09).to_hex()
        );

        // The shipped light themes take the other branch.
        let goingson = embedded_themes()
            .into_iter()
            .find(|(id, _)| *id == "goingson")
            .expect("goingson is embedded")
            .1;
        let light =
            resolve(&parse_theme_str(&ThemeId::from_static("goingson"), goingson, false).unwrap());
        let light_raised = light
            .color(Token::SurfaceRaised)
            .expect("goingson authors a raised surface");
        assert_eq!(
            light.hex(Token::SurfaceWell).unwrap(),
            lighten(light_raised, 0.07).to_hex()
        );
    }

    // A well is a fill, not an edge, so the only thing that makes it read is
    // being a different color from the surface it is cut into.
    //
    // Same shape and the same asserted-list discipline as
    // `bevel_edges_are_distinct_from_their_face`. It used to bite the same two
    // themes, whose raised surface sits at the top of the ramp; the well now
    // goes the other way when it has no room, so no bundled theme is exempt.
    #[test]
    fn well_is_distinct_from_its_face() {
        const CANNOT_WELL: &[&str] = &[];

        let mut degenerate: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), source, false).unwrap();
            let t = resolve(&theme);
            let Some(raised) = t.hex(Token::SurfaceRaised) else {
                continue;
            };
            let well = t
                .hex(Token::SurfaceWell)
                .expect("raised implies surface-well");
            if well == raised {
                degenerate.push(id.to_string());
            }
        }
        degenerate.sort();

        assert_eq!(
            degenerate, CANNOT_WELL,
            "themes whose raised surface cannot hold a well"
        );
    }

    // Distinct is not the same as visible. A face near the top of the ramp
    // clamps partway rather than exactly, which yields a well that differs from
    // its face by a hex digit and by nothing the eye can find. `rosepine-dawn`
    // authors raised at L=0.987 and got 0.009 of the 0.07 it asked for, until
    // a step without room started travelling the other way.
    //
    // Kept separate from the test above because a partial clamp passes that
    // one, and the list stays asserted so a theme that defeats the fallback has
    // to come here and say so.
    #[test]
    fn well_is_visible_against_its_face() {
        const CANNOT_HOLD_A_VISIBLE_WELL: &[&str] = &[];

        let mut invisible: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), source, false).unwrap();
            let t = resolve(&theme);
            let (Some(raised), Some(well)) =
                (t.color(Token::SurfaceRaised), t.color(Token::SurfaceWell))
            else {
                continue;
            };
            if (well.to_oklab().l - raised.to_oklab().l).abs() < MIN_VISIBLE_DELTA_L {
                invisible.push(id.to_string());
            }
        }
        invisible.sort();

        assert_eq!(
            invisible, CANNOT_HOLD_A_VISIBLE_WELL,
            "themes whose well is too close to its face to read as one"
        );
    }

    // The collision the fallback exists for. A light face near the top of the
    // ramp sends both the well and `bevel-light` into the same clamp, so the
    // well measured against its face alone can pass while being the exact
    // colour of the lit edge drawn around it. Ten of the 31 bundled themes did.
    #[test]
    fn well_is_visible_against_the_highlight() {
        let mut collided: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), source, false).unwrap();
            let t = resolve(&theme);
            let (Some(well), Some(light)) =
                (t.color(Token::SurfaceWell), t.color(Token::BevelLight))
            else {
                continue;
            };
            if (well.to_oklab().l - light.to_oklab().l).abs() < MIN_VISIBLE_DELTA_L {
                collided.push(id.to_string());
            }
        }
        collided.sort();
        assert!(
            collided.is_empty(),
            "themes whose well reads as the lit edge around it: {collided:?}"
        );
    }

    // The table model's row tones, pinned to the specimen they were measured
    // from: treatment C on akari-dawn, artifact d081c72d.
    #[test]
    fn row_tones_reproduce_the_chosen_table_specimen() {
        let source = embedded_themes()
            .into_iter()
            .find(|(id, _)| *id == "akari-dawn")
            .expect("akari-dawn is embedded")
            .1;
        let t =
            resolve(&parse_theme_str(&ThemeId::from_static("akari-dawn"), source, false).unwrap());
        assert_eq!(
            t.hex(Token::RowHover)
                .map(|h| h.to_ascii_lowercase())
                .as_deref(),
            Some("#dedad5")
        );
        assert_eq!(
            t.hex(Token::RowRule)
                .map(|h| h.to_ascii_lowercase())
                .as_deref(),
            Some("#b0ada9")
        );
    }

    // The fallback's direction, pinned on the theme that found it. akari-dawn
    // authors raised at L=0.966, where the well's step up would land in the
    // clamp, so the well goes down instead.
    #[test]
    fn well_without_room_travels_the_other_way() {
        let source = embedded_themes()
            .into_iter()
            .find(|(id, _)| *id == "akari-dawn")
            .expect("akari-dawn is embedded")
            .1;
        let t =
            resolve(&parse_theme_str(&ThemeId::from_static("akari-dawn"), source, false).unwrap());
        let raised = t
            .color(Token::SurfaceRaised)
            .expect("akari-dawn authors a raised surface");
        assert_eq!(
            t.hex(Token::SurfaceWell).unwrap(),
            darken(raised, 0.07).to_hex()
        );
    }

    // The three tests above each measure a derived color against the face it was
    // derived from, so a theme can pass all of them and still have nothing lift
    // off anything: the face itself sits on the page, and that relationship is
    // the one a bevel needs in order to read as an object rather than as a
    // rectangle with decorated edges. makenot.work passed all three and could
    // not hold a bevel, which is what this covers.
    //
    // The threshold is picked against the ramps already ruled on rather than
    // against a round number. makenot.work shipped at 0.024 and was invisible,
    // was tried at 0.036 and rejected as marginal on badges and chips, and was
    // accepted at 0.058; goingson and audiofiles sit at 0.119 and 0.065. Every
    // ramp judged inadequate is below 0.036 and every one judged adequate is
    // above 0.058, so the line goes in the gap between them. Note the unit: this
    // is oklab L on 0 to 1, not the CIE L* on 0 to 100 that the theme files quote
    // in their comments, and the two are not interchangeable.
    //
    // Most of the list is imported palettes, which were authored for syntax
    // highlighting and owe our depth model nothing. Failing here says a theme
    // cannot hold a bevel, not that it is wrong. Shrinking the list is the fix;
    // growing it is a regression in the theme, not in this derivation.
    //
    // An imported palette leaves this list only when the fix is upstream's own,
    // never a color we picked, or the list becomes a record of what we were
    // willing to repaint rather than of what cannot hold a bevel. The remaining
    // entries are shallow ramps in published palettes, deferred until every app
    // is migrated and eyeballed.
    //
    // The akari pair is not an imported palette in that sense and is exempt.
    // Upstream ships no file in this schema, so its surface ramp was ours to
    // choose from the start, and it is the pair every app defaults to: a depth
    // model the default theme cannot render is a broken default, not a palette
    // we are borrowing on someone else's terms.
    #[test]
    fn raised_is_distinct_from_page() {
        // Below this, a raised surface and the page under it are one surface to
        // a reader, whichever direction the theme ramps in.
        const MIN_DELTA_L: f32 = 0.05;
        const CANNOT_LIFT_OFF_THE_PAGE: &[&str] = &[
            "ayu-light",
            "ayu-mirage",
            "catppuccin-latte",
            "catppuccin-mocha",
            "dawnfox",
            "dracula",
            "everforest",
            "flatwhite",
            "gruvbox-light",
            "neobrute",
            "one-dark",
            "oxocarbon-dark",
            "oxocarbon-light",
            "poimandres",
            "rosepine",
            "rosepine-dawn",
            "solarized-dark",
            "solarized-light",
        ];

        let mut flat: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), source, false).unwrap();
            let t = resolve(&theme);
            let (Some(page), Some(raised)) =
                (t.color(Token::SurfacePage), t.color(Token::SurfaceRaised))
            else {
                continue;
            };
            if (raised.to_oklab().l - page.to_oklab().l).abs() < MIN_DELTA_L {
                flat.push(id.to_string());
            }
        }
        flat.sort();

        assert_eq!(
            flat, CANNOT_LIFT_OFF_THE_PAGE,
            "themes whose raised surface is too close to the page to lift off it"
        );
    }

    #[test]
    fn resolve_overlay_is_dark_translucent_scrim() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let overlay = t.css(Token::Overlay).unwrap();
        assert!(
            overlay.starts_with("rgba("),
            "overlay is translucent: {overlay}"
        );
        assert!(overlay.ends_with(", 0.5)"));
        // The scrim tone is anchored very dark regardless of theme.
        let inner = overlay
            .trim_start_matches("rgba(")
            .trim_end_matches(", 0.5)");
        let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
        let scrim = Rgb {
            r: parts[0],
            g: parts[1],
            b: parts[2],
        };
        assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black");
    }

    /// Every shipped theme derives it, on both polarities, and it is always a
    /// near-black translucent tone. A shadow tinted to a dark theme's own
    /// lightness would not read as one.
    #[test]
    fn elevation_is_a_near_black_cast_on_every_theme() {
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::new(id).unwrap(), source, false).unwrap();
            let t = resolve(&theme);
            let Some(elevation) = t.css(Token::Elevation) else {
                panic!("{id} derives no elevation");
            };
            assert!(
                elevation.starts_with("rgba(") && elevation.ends_with(", 0.18)"),
                "{id}: elevation is translucent: {elevation}"
            );
            let inner = elevation
                .trim_start_matches("rgba(")
                .trim_end_matches(", 0.18)");
            let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
            let cast = Rgb {
                r: parts[0],
                g: parts[1],
                b: parts[2],
            };
            assert!(
                cast.to_oklab().l < 0.2,
                "{id}: a cast shadow must be near-black, got {elevation}"
            );
        }
    }

    /// The scrim and the cast share an anchor and differ only in weight. Stated
    /// as a test because the two are easy to drift apart, and a scrim that
    /// stopped matching the shadow under the thing it dims would show.
    #[test]
    fn elevation_and_the_scrim_are_the_same_tone() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let scrim = t.css(Token::Overlay).unwrap();
        let cast = t.css(Token::Elevation).unwrap();
        assert_eq!(
            scrim.trim_end_matches(", 0.5)"),
            cast.trim_end_matches(", 0.18)"),
        );
    }

    /// The accessor that makes a translucent intent reachable from something
    /// that is not a stylesheet. Both spellings, and an opaque token answers
    /// 255 so a caller need not know which kind it asked for.
    #[test]
    fn rgba_reads_both_spellings() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let t = resolve(&theme);

        let (_, _, _, opaque) = t.rgba(Token::SurfacePage).expect("page is a hex token");
        assert_eq!(opaque, 255);

        let (r, g, b, alpha) = t.rgba(Token::Elevation).expect("elevation is translucent");
        assert_eq!(alpha, 46, "0.18 of 255");
        assert_eq!(
            t.rgb(Token::Elevation),
            None,
            "rgb declines to drop the alpha"
        );

        let (sr, sg, sb, scrim) = t.rgba(Token::Overlay).expect("overlay is translucent");
        assert_eq!((sr, sg, sb), (r, g, b), "one tone, two weights");
        assert_eq!(scrim, 128);
    }

    #[test]
    fn resolve_drops_non_hex_base_intent() {
        // A base intent that isn't a hex color must never reach the resolved
        // token set (it would otherwise be inlined verbatim into a <style>
        // block). Skipped like a missing intent; valid siblings survive.
        let theme = parse_theme_str(&ThemeId::from_static("x"),
            "[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n",
            false,
        )
        .unwrap();
        let t = resolve(&theme);
        assert!(
            t.hex(Token::SurfacePage).is_none(),
            "non-hex base intent leaked"
        );
        assert_eq!(t.hex(Token::Content).unwrap(), "#111111");
        // The injected markup appears in no resolved value.
        assert!(!t.intents.values().any(|v| v.css().contains('<')));
    }

    #[test]
    fn resolve_skips_derived_when_source_missing() {
        // No [action] => no action-derived tokens.
        let theme = parse_theme_str(
            &ThemeId::from_static("x"),
            "[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n",
            false,
        )
        .unwrap();
        let t = resolve(&theme);
        assert!(t.hex(Token::Action).is_none());
        assert!(t.hex(Token::ActionHover).is_none());
        assert_eq!(
            t.hex(Token::BorderStrong).unwrap(),
            darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex()
        );
    }

    #[test]
    fn rgb_accessor_for_native_consumers() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let t = resolve(&theme);
        assert_eq!(t.rgb(Token::Action), Some((0x81, 0xa1, 0xc1)));
        assert_eq!(Token::parse("nonexistent"), None);
    }

    // ---- the token vocabulary ----

    #[test]
    fn every_token_has_one_stem_and_reads_back_from_it() {
        let mut stems: Vec<&str> = Token::ALL.iter().map(|t| t.as_str()).collect();
        for token in Token::ALL {
            assert_eq!(Token::parse(token.as_str()), Some(*token));
        }
        let count = stems.len();
        stems.sort_unstable();
        stems.dedup();
        assert_eq!(stems.len(), count, "a stem is spelled twice");
    }

    #[test]
    fn tokens_order_by_stem_so_emission_is_alphabetical() {
        let t =
            resolve(&parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap());
        let order: Vec<&str> = t.intents.keys().map(|k| k.as_str()).collect();
        let mut sorted = order.clone();
        sorted.sort_unstable();
        assert_eq!(order, sorted);
    }

    #[test]
    fn a_full_theme_resolves_every_token() {
        let t =
            resolve(&parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap());
        let missing: Vec<&str> = Token::ALL
            .iter()
            .filter(|token| t.get(**token).is_none())
            .map(|token| token.as_str())
            .collect();
        assert!(missing.is_empty(), "{missing:?}");
    }

    #[test]
    fn serialised_tokens_keep_the_css_spelling() {
        let t =
            resolve(&parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap());
        let text = toml::to_string(&t.intents).unwrap();
        assert!(text.contains("surface-page = \"#2e3440\""), "{text}");
        assert!(text.contains("overlay = \"rgba("), "{text}");
    }

    // ---- css emit ----

    #[test]
    fn intent_css_vars_wraps_root_and_includes_tokens() {
        let theme = parse_theme_str(&ThemeId::from_static("nord"), nord_toml(), false).unwrap();
        let css = intent_css_vars(&resolve(&theme));
        assert!(css.starts_with(":root {\n"));
        assert!(css.contains("  --surface-page: #2e3440;\n"));
        assert!(css.contains("  --danger: #bf616a;\n"));
        assert!(css.contains("  --action-hover: "));
        assert!(css.trim_end().ends_with('}'));
    }
}