makeover 5.13.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
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
//! Intent resolution

use crate::{
    DISTINCT, Rgb, Rgba, STEP_FLOOR, ThemeColors, ThemeMeta, darken, lighten, mix, readable_on,
    tonal, 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. Held to body text's floor.
    ContentMuted => "content-muted",
    /// The label of a control that will not answer: the faint step, held only
    /// to the quiet floor. Never a hint or a caption; those are
    /// [`ContentMuted`](Self::ContentMuted).
    ContentDisabled => "content-disabled",
    /// 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",
    /// [`Danger`](Self::Danger) as text: its hue, at the lightness that reads
    /// on every text ground and on its own toned surface.
    DangerText => "danger-text",
    /// [`Success`](Self::Success) as text, as [`DangerText`](Self::DangerText).
    SuccessText => "success-text",
    /// [`Warning`](Self::Warning) as text, as [`DangerText`](Self::DangerText).
    WarningText => "warning-text",
    /// [`Info`](Self::Info) as text, as [`DangerText`](Self::DangerText).
    InfoText => "info-text",
    /// [`CategoryOne`](Self::CategoryOne) as text, on every text ground.
    CategoryOneText => "category-one-text",
    /// [`CategoryTwo`](Self::CategoryTwo) as text.
    CategoryTwoText => "category-two-text",
    /// [`CategoryThree`](Self::CategoryThree) as text.
    CategoryThreeText => "category-three-text",
    /// [`CategoryFour`](Self::CategoryFour) as text.
    CategoryFourText => "category-four-text",
    /// [`CategoryFive`](Self::CategoryFive) as text.
    CategoryFiveText => "category-five-text",
    /// [`CategorySix`](Self::CategorySix) as text.
    CategorySixText => "category-six-text",
    /// A language keyword in highlighted code.
    SyntaxKeyword => "syntax-keyword",
    /// A string literal in highlighted code.
    SyntaxString => "syntax-string",
    /// A comment in highlighted code: the muted ink, held to the text floor.
    SyntaxComment => "syntax-comment",
    /// A numeric or named constant in highlighted code.
    SyntaxConstant => "syntax-constant",
    /// A type, function or other named entity in highlighted code.
    SyntaxEntity => "syntax-entity",
    /// A variable in highlighted code.
    SyntaxVariable => "syntax-variable",
    /// A library or built-in name in highlighted code.
    SyntaxSupport => "syntax-support",
    /// [`Action`](Self::Action) as text: its hue, at the lightness that reads
    /// on every text ground.
    ActionText => "action-text",
    /// The fill of an inverted plate: the theme's [`Content`](Self::Content)
    /// ink, used as a surface.
    InverseSurface => "inverse-surface",
    /// The ink on [`InverseSurface`](Self::InverseSurface): the page ground,
    /// used as text. The two clear [`Content`](Self::Content)'s floor on the
    /// page by construction.
    InverseContent => "inverse-content",
    /// Text not yet settled, a message still sending or a draft: the muted
    /// tier, named for the job so a theme can tell it apart.
    ContentPending => "content-pending",
    /// The quietest measure band: the raised ground itself, none of it.
    Heat0 => "heat-0",
    /// The second measure band, one step of the neutral ramp toward `content`.
    Heat1 => "heat-1",
    /// The third measure band.
    Heat2 => "heat-2",
    /// The fourth measure band.
    Heat3 => "heat-3",
    /// The loudest measure band, still a ground `content` reads on.
    Heat4 => "heat-4",
}

impl Token {
    /// The measure bands, quietest first: a heatmap's fills.
    pub const HEATS: [Token; 5] = [
        Token::Heat0,
        Token::Heat1,
        Token::Heat2,
        Token::Heat3,
        Token::Heat4,
    ];

    /// 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 far a toned surface's lightness steps from its ground toward the
    /// tone.
    pub const TONE_SURFACE: f32 = 0.12;
    /// The OKLab chroma a toned surface carries, in the tone's own hue: enough
    /// to read as the tone on any ground, or the tone's own if it has less.
    pub const TONE_CHROMA: f32 = 0.05;
    /// 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 ink mixed into the cursor row: a neutral-ramp step, not the accent,
    /// which is reserved for the primary action. The marker, not this fill, is
    /// what tells the cursor row apart from the hover step.
    pub const ROW_SELECTED: f32 = 0.18;
    /// How far from `content` toward the page
    /// [`Token::ContentDisabled`](super::Token::ContentDisabled) starts, before
    /// it is lifted to its floor: past muted's step, so a disabled label is
    /// fainter than a hint wherever the theme has the room.
    pub const DISABLED: f32 = 0.6;
    /// How far [`Token::BorderStrong`](super::Token::BorderStrong) steps away from the page.
    pub const BORDER_STRONG: f32 = 0.05;
    /// The ink mixed into the raised ground at each measure band, quietest
    /// first. Even steps, so band distance reads as amount. The top band is
    /// the cursor row's mix: every ink already owes its floor there, so the
    /// ramp adds grounds without moving any ink.
    pub const HEAT: [f32; 5] = [
        0.0,
        ROW_SELECTED * 0.25,
        ROW_SELECTED * 0.5,
        ROW_SELECTED * 0.75,
        ROW_SELECTED,
    ];
}

/// 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 base intents `colors` holds as a colour that parses: exactly what
/// [`resolve`] keeps, and so what an import must offer at least one of.
pub(crate) fn base_colors(
    colors: &std::collections::HashMap<String, String>,
) -> impl Iterator<Item = (Token, Rgb)> + '_ {
    BASE_INTENTS
        .iter()
        .filter_map(|(src, token)| Some((*token, colors.get(*src).and_then(|v| Rgb::from_hex(v))?)))
}

/// 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 [`resolve`] 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 (token, rgb) in base_colors(&theme.colors) {
        base.insert(token, Rgba::opaque(rgb));
    }

    // The disabled tier is a step past muted toward the page, lifted only to
    // the quiet floor, so it stays the faint step when muted holds body
    // text's floor.
    if let (Some(content), Some(page)) = (
        opaque(&base, Token::Content),
        opaque(&base, Token::SurfacePage),
    ) {
        let disabled = tonal(content, page, ratio::DISABLED);
        base.insert(Token::ContentDisabled, Rgba::opaque(disabled));
    }

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

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

/// A surface on `ground` that reads as `tone`: lightness stepped `step` of the
/// way toward the tone, hue the tone's, chroma `chroma` or the tone's own if it
/// has less.
///
/// Not a [`mix`]: a mix carries the ground's own tint, which cancels a tone
/// opposite it in hue, so a yellow on a lavender ground came out grey.
fn toned(ground: Rgb, tone: Rgb, step: f32, chroma: f32) -> Rgb {
    let (g, t) = (ground.to_oklab(), tone.to_oklab());
    let own = t.a.hypot(t.b);
    let scale = if own > chroma { chroma / own } else { 1.0 };
    Rgb::from_oklab(crate::Oklab {
        l: g.l + (t.l - g.l) * step,
        a: t.a * scale,
        b: t.b * scale,
    })
}

/// Text on a filled `action`: whichever of the theme's page and content reads
/// better on it, when that clears [`TEXT`]; black or white otherwise.
///
/// The theme's own colour first, so a filled control stays inside the palette
/// it was authored in. An unreadable label is worse than an off-palette one, so
/// the fallback is the picker's.
fn on_action(action: Rgb, page: Option<Rgb>, content: Option<Rgb>) -> Rgb {
    // `max_by` keeps the last of equals, so page wins a tie.
    [content, page]
        .into_iter()
        .flatten()
        .map(|c| (c, wcag_contrast(c, action)))
        .max_by(|a, b| a.1.total_cmp(&b.1))
        .filter(|&(_, ratio)| ratio >= TEXT)
        .map_or_else(|| readable_on(action), |(c, _)| c)
}

/// 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, HEAT, ROW_HOVER,
        ROW_RULE, ROW_SELECTED, SCRIM_ALPHA, SHADOW_L, TONE_CHROMA, TONE_SURFACE, WELL_DARKER,
        WELL_LIGHTER,
    };

    let mut intents = base.clone();

    // 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) = opaque(&intents, Token::Action) {
        put(Token::ActionHover, lighten(action, ACTION_HOVER));
        put(
            Token::ContentOnAction,
            on_action(
                action,
                opaque(&intents, Token::SurfacePage),
                opaque(&intents, Token::Content),
            ),
        );
        // 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 = opaque_grounds(&intents, &[Token::SurfacePage, Token::SurfaceRaised]);
        put(Token::FocusRing, cleared(action, &grounds, DISTINCT));
    }
    if let Some(page) = opaque(&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) = opaque(&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) = opaque(&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's
            // lightness in the tone's hue, 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 = opaque(&intents, Token::SurfaceSunken);
            for (tone, surface, hover) in TONES {
                if let Some(color) = opaque(&intents, tone) {
                    put(surface, toned(raised, color, TONE_SURFACE, TONE_CHROMA));
                    if let Some(sunken) = sunken {
                        put(hover, toned(sunken, color, TONE_SURFACE, TONE_CHROMA));
                    }
                }
            }

            // 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. A step
            // of the neutral ramp, not the accent: accent is reserved for the
            // primary action. A fill and never a foreground, so a failed row
            // stays red under it.
            put(Token::RowSelected, mix(raised, content, ROW_SELECTED));

            // The measure ramp: how much, never what it means, so the bands
            // are steps of the neutral ramp and carry no hue. Band 0 is the
            // ground, the empty cell of a heatmap.
            for (token, step) in Token::HEATS.into_iter().zip(HEAT) {
                put(token, mix(raised, content, step));
            }
        }
    }
    if let Some(sunken) = opaque(&intents, Token::SurfaceSunken) {
        put(Token::HoverSurface, sunken);
    }
    if let Some(border) = opaque(&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 (
            opaque(&intents, Token::Content),
            opaque(&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
}

/// `tokens` with every [`TEXT_INKS`] row added: each ink keeps its source's
/// hue and moves its lightness until it reads on every ground in its row.
///
/// Run once on the settled tokens rather than inside [`derive`]: no ground is
/// derived from a text ink, so the fixed point does not need them.
fn with_text_inks(mut tokens: BTreeMap<Token, Rgba>) -> BTreeMap<Token, Rgba> {
    // The status inks are lifted here, after `derive` has built the toned
    // surfaces from the authored colours, so a chip keeps the hue its theme
    // wrote while the mark drawn with the ink reads on every ground it sits on.
    let mut lifted: Vec<(Token, Rgba)> = Vec::new();
    for &status in STATUS_INKS {
        let Some(color) = opaque(&tokens, status) else {
            continue;
        };
        let grounds = opaque_grounds(&tokens, STATUS_GROUNDS);
        lifted.push((status, Rgba::opaque(cleared(color, &grounds, DISTINCT))));
    }
    tokens.extend(lifted);

    let mut inks: Vec<(Token, Rgba)> = Vec::new();
    for &(ink, source, grounds) in TEXT_INKS {
        let Some(color) = opaque(&tokens, source) else {
            continue;
        };
        let grounds = opaque_grounds(&tokens, grounds);
        inks.push((ink, Rgba::opaque(cleared(color, &grounds, TEXT))));
    }
    tokens.extend(inks);
    for (role, source) in ROLE_ALIASES {
        if let Some(color) = tokens.get(source).copied() {
            tokens.insert(*role, color);
        }
    }
    tokens
}

/// The status colours, each drawn as a mark (an icon, a dot, an edge) that owes
/// [`DISTINCT`] on every ground in [`STATUS_GROUNDS`].
const STATUS_INKS: &[Token] = &[Token::Danger, Token::Success, Token::Warning, Token::Info];

/// The grounds a status mark is drawn on: the page, the raised ground a table
/// sits on, and the cursor row painted under every cell of it.
const STATUS_GROUNDS: &[Token] = &[Token::SurfacePage, Token::SurfaceRaised, Token::RowSelected];

/// Roles whose colour is another token's, held as their own names so a page
/// says the job rather than the colour that happens to do it.
const ROLE_ALIASES: &[(Token, Token)] = &[
    (Token::InverseSurface, Token::Content),
    (Token::InverseContent, Token::SurfacePage),
    (Token::ContentPending, Token::ContentMuted),
];

/// Every ground body-size text is set on.
const TEXT_GROUNDS: &[Token] = &[
    Token::SurfacePage,
    Token::SurfaceRaised,
    Token::SurfaceSunken,
    Token::SurfaceWell,
    Token::SurfaceOverlay,
    Token::RowHover,
    Token::RowSelected,
    Token::Heat1,
    Token::Heat2,
    Token::Heat3,
    Token::Heat4,
];

/// The text grounds plus a tone's own surface, which a toned ink is set on
/// inside its chip or row.
macro_rules! toned_grounds {
    ($surface:expr) => {
        &[
            Token::SurfacePage,
            Token::SurfaceRaised,
            Token::SurfaceSunken,
            Token::SurfaceWell,
            Token::SurfaceOverlay,
            Token::RowHover,
            Token::RowSelected,
            Token::Heat1,
            Token::Heat2,
            Token::Heat3,
            Token::Heat4,
            $surface,
        ]
    };
}

/// The text grounds plus the added and removed rows of a diff, which carry
/// highlighted code.
const CODE_GROUNDS: &[Token] = &[
    Token::SurfacePage,
    Token::SurfaceRaised,
    Token::SurfaceSunken,
    Token::SurfaceWell,
    Token::SurfaceOverlay,
    Token::RowHover,
    Token::RowSelected,
    Token::SuccessSurface,
    Token::DangerSurface,
];

/// Each derived ink, the colour it is taken from, and the grounds it owes
/// [`TEXT`] on. [`derive`] clears every row and [`unmet_floors`] reports any it
/// could not.
const TEXT_INKS: &[(Token, Token, &[Token])] = &[
    (
        Token::DangerText,
        Token::Danger,
        toned_grounds!(Token::DangerSurface),
    ),
    (
        Token::SuccessText,
        Token::Success,
        toned_grounds!(Token::SuccessSurface),
    ),
    (
        Token::WarningText,
        Token::Warning,
        toned_grounds!(Token::WarningSurface),
    ),
    (
        Token::InfoText,
        Token::Info,
        toned_grounds!(Token::InfoSurface),
    ),
    (Token::ActionText, Token::Action, TEXT_GROUNDS),
    (Token::CategoryOneText, Token::CategoryOne, TEXT_GROUNDS),
    (Token::CategoryTwoText, Token::CategoryTwo, TEXT_GROUNDS),
    (Token::CategoryThreeText, Token::CategoryThree, TEXT_GROUNDS),
    (Token::CategoryFourText, Token::CategoryFour, TEXT_GROUNDS),
    (Token::CategoryFiveText, Token::CategoryFive, TEXT_GROUNDS),
    (Token::CategorySixText, Token::CategorySix, TEXT_GROUNDS),
    // Keyword, string, entity and variable are the common four and take four
    // categories of their own; constant and support, the rarest, share the
    // two hues a theme is likeliest to author alike.
    (Token::SyntaxKeyword, Token::CategoryFour, CODE_GROUNDS),
    (Token::SyntaxString, Token::CategoryTwo, CODE_GROUNDS),
    (Token::SyntaxComment, Token::ContentMuted, CODE_GROUNDS),
    (Token::SyntaxConstant, Token::CategoryFive, CODE_GROUNDS),
    (Token::SyntaxEntity, Token::CategorySix, CODE_GROUNDS),
    (Token::SyntaxVariable, Token::CategoryOne, CODE_GROUNDS),
    (Token::SyntaxSupport, Token::CategoryThree, CODE_GROUNDS),
];

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

/// The disabled tier's floor: present, deliberately under body text, so a
/// control that will not answer reads as one.
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::Heat1,
            Token::Heat2,
            Token::Heat3,
            Token::Heat4,
            Token::InfoSurface,
            Token::SuccessSurface,
            Token::WarningSurface,
            Token::DangerSurface,
        ],
        TEXT,
    ),
    (Token::ContentSecondary, TEXT_GROUNDS, TEXT),
    (Token::ContentMuted, TEXT_GROUNDS, TEXT),
    (Token::ContentDisabled, TEXT_GROUNDS, 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;

    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 = opaque_grounds(&tokens, grounds);
            if worst(color, &grounds) >= floor {
                continue;
            }
            moved |= lift_one(&tokens, &mut base, ink, true);
        }
        if !moved {
            let tokens = with_text_inks(tokens);
            let unmet = unmet_floors(&tokens);
            return (tokens, unmet);
        }
    }
    let tokens = with_text_inks(derive(&base));
    let unmet = unmet_floors(&tokens);
    (tokens, unmet)
}

/// The tier an ink steps back from, which it must stay a visible step under.
fn above(ink: Token) -> Option<Token> {
    match ink {
        Token::ContentSecondary | Token::ContentDisabled => Some(Token::Content),
        Token::ContentMuted => Some(Token::ContentSecondary),
        _ => None,
    }
}

/// Lift `ink` one [`LIFT`] toward its floor in `base`, and report whether
/// anything moved.
///
/// A tier steps toward the tier [`above`] it. When that step would come
/// within [`STEP_FLOOR`] of it, the tier above is lifted instead, which widens
/// the room between them; `content`, at the top, moves away from its grounds.
/// Only when nothing above can move does the tier under its floor step
/// anyway (`may_converge`), converging on the one above rather than missing
/// its floor.
fn lift_one(
    tokens: &BTreeMap<Token, Rgba>,
    base: &mut BTreeMap<Token, Rgba>,
    ink: Token,
    may_converge: bool,
) -> bool {
    let Some(color) = opaque(tokens, ink) else {
        return false;
    };
    let lifted = match above(ink).and_then(|up| Some((up, opaque(tokens, up)?))) {
        None => away_from(color, &opaque_grounds(tokens, INK_FLOORS[0].1), LIFT),
        Some((up, up_color)) => {
            let step = tonal(color, up_color, 0.05);
            if wcag_contrast(step, up_color) < STEP_FLOOR {
                if lift_one(tokens, base, up, false) {
                    return true;
                }
                // The tiers above have no room left: the floor outranks the
                // visible step, so the tier under its floor converges on the
                // one above it. A tier lifted only to make room never does.
                if !may_converge {
                    return false;
                }
            }
            step
        }
    };
    if lifted == color {
        return false;
    }
    base.insert(ink, Rgba::opaque(lifted));
    true
}

/// The [`INK_FLOORS`] and [`TEXT_INKS`] entries `tokens` still misses, in
/// table order.
fn unmet_floors(tokens: &BTreeMap<Token, Rgba>) -> Vec<UnmetFloor> {
    INK_FLOORS
        .iter()
        .copied()
        .chain(
            TEXT_INKS
                .iter()
                .map(|&(ink, _, grounds)| (ink, grounds, TEXT)),
        )
        .chain(
            STATUS_INKS
                .iter()
                .map(|&ink| (ink, STATUS_GROUNDS, DISTINCT)),
        )
        .filter_map(|(ink, grounds, floor)| {
            let color = opaque(tokens, ink)?;
            let grounds = opaque_grounds(tokens, grounds);
            let achieved = worst(color, &grounds);
            (achieved < floor).then_some(UnmetFloor {
                token: ink,
                floor,
                achieved,
            })
        })
        .collect()
}

/// `token`'s colour in `m`, if present and opaque: a translucent token is
/// never a ground or an ink.
fn opaque(m: &BTreeMap<Token, Rgba>, token: Token) -> Option<Rgb> {
    m.get(&token).and_then(|c| c.opaque_rgb())
}

/// The opaque colours of `grounds` in `m`, skipping missing and translucent
/// ones.
fn opaque_grounds(m: &BTreeMap<Token, Rgba>, grounds: &[Token]) -> Vec<Rgb> {
    grounds.iter().filter_map(|g| opaque(m, *g)).collect()
}

/// The lowest contrast `ink` makes against any of `grounds`; infinite for none.
pub(crate) 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.
///
/// Both directions are walked and the shorter walk that clears is taken. One
/// direction at a time, away from whichever ground binds, cannot settle when
/// the grounds sit on both sides of the ink: each step away from one is a step
/// toward another, and the ink turns back and forth between them. When neither
/// direction clears, the lightness that came closest is kept, and
/// [`unmet_floors`] reports it.
fn cleared(color: Rgb, grounds: &[Rgb], floor: f32) -> Rgb {
    // More steps than crossing the whole ramp takes at [`LIFT`].
    const STEPS: usize = 400;

    if worst(color, grounds) >= floor {
        return color;
    }
    // The walk's end: the first lightness that clears and how many steps it
    // took, or the best one met and `None`.
    let walk = |toward_dark: bool| -> (Rgb, f32, Option<usize>) {
        let mut at = color;
        let mut best = (color, worst(color, grounds));
        for step in 1..=STEPS {
            let next = if toward_dark {
                darken(at, LIFT)
            } else {
                lighten(at, LIFT)
            };
            if next == at {
                break;
            }
            at = next;
            let reached = worst(at, grounds);
            if reached >= floor {
                return (at, reached, Some(step));
            }
            if reached > best.1 {
                best = (at, reached);
            }
        }
        (best.0, best.1, None)
    };
    let (dark, lit) = (walk(true), walk(false));
    match (dark.2, lit.2) {
        (Some(d), Some(l)) => {
            if d <= l {
                dark.0
            } else {
                lit.0
            }
        }
        (Some(_), None) => dark.0,
        (None, Some(_)) => lit.0,
        (None, None) => {
            if dark.1 >= lit.1 {
                dark.0
            } else {
                lit.0
            }
        }
    }
}

/// 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;
    #[allow(unused_imports)]
    use crate::{ThemeDirs, ThemeId, Token};
    use crate::{embedded_themes, parse_theme_str};

    #[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"));
        // content.primary -> content, lifted: nord's ink is too close to its
        // grounds to hold a muted step at body text's floor on its row tones, so
        // resolution moves it away from the page, keeping its hue.
        let authored = Rgb::from_hex("#d8dee9").unwrap().to_oklab();
        let content = t.color(Token::Content).unwrap().to_oklab();
        assert!(content.l > authored.l, "{content:?}");
        // Not a passthrough: a tonal step of the ink toward the page, whatever
        // the file said.
        let page = Rgb::from_hex("#2e3440").unwrap().to_oklab();
        let muted = t.color(Token::ContentMuted).unwrap().to_oklab();
        assert!(page.l < muted.l && muted.l < content.l, "{muted:?}");
        assert_eq!(t.hex(Token::Action).as_deref(), Some("#81a1c1"));
        // nord's danger misses 3:1 on its cursor row, so it is lifted there.
        assert_eq!(t.hex(Token::Danger).as_deref(), Some("#fb9c92"));
        assert_eq!(t.hex(Token::Border).as_deref(), Some("#4c566a"));
        assert_eq!(t.hex(Token::CategoryFive).as_deref(), Some("#b48ead"));
    }

    /// A toned surface is the tone's hue on every shipped theme, whatever the
    /// ground's own tint: goingson's yellow warning on its lavender raised
    /// ground is the case a mix turned grey.
    #[test]
    fn a_toned_surface_carries_its_tones_hue() {
        let hue = |c: Rgb| {
            let lab = c.to_oklab();
            (lab.b.atan2(lab.a).to_degrees(), lab.a.hypot(lab.b))
        };
        let mut off = Vec::new();
        for (id, toml) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::from_static(id), toml, false).unwrap();
            let t = resolve(&theme);
            // The surface is built from the authored tone, before the status
            // ink is lifted, so it is measured against that.
            let authored: BTreeMap<Token, Rgb> = base_colors(&theme.colors).collect();
            for (tone, surface, _) in TONES {
                let (Some(&tone_rgb), Some(surface_hex)) = (authored.get(&tone), t.hex(surface))
                else {
                    continue;
                };
                let (want, own) = hue(tone_rgb);
                if own < 0.02 {
                    continue;
                }
                let (got, chroma) = hue(Rgb::from_hex(&surface_hex).unwrap());
                let apart = ((got - want + 540.0) % 360.0 - 180.0).abs();
                if apart > 20.0 || chroma < 0.02 {
                    off.push(format!(
                        "{id} {surface:?}: {apart:.0} degrees off, chroma {chroma:.3}"
                    ));
                }
            }
        }
        assert!(off.is_empty(), "{off:#?}");
    }

    #[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()
        );
        // nord's page reads on its accent, so the label stays on-palette.
        assert_eq!(t.hex(Token::ContentOnAction).as_deref(), Some("#2e3440"));
        assert!(wcag_contrast(page, action) >= TEXT);
        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(),
            toned(raised, danger, 0.12, 0.05).to_hex()
        );
        assert_eq!(
            t.hex(Token::DangerSurfaceHover).unwrap(),
            toned(sunken, danger, 0.12, 0.05).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 heat_ramp_runs_from_the_ground_to_the_cursor_row_in_every_theme() {
        for (id, toml) in embedded_themes() {
            let theme = parse_theme_str(&ThemeId::from_static(id), toml, false).unwrap();
            let t = resolve(&theme);
            let l = |token| t.get(token).unwrap().rgb.to_oklab().l;
            assert_eq!(t.hex(Token::Heat0), t.hex(Token::SurfaceRaised), "{id}");
            assert_eq!(t.hex(Token::Heat4), t.hex(Token::RowSelected), "{id}");
            let toward_content = l(Token::Content) > l(Token::SurfaceRaised);
            for pair in Token::HEATS.windows(2) {
                let (a, b) = (l(pair[0]), l(pair[1]));
                assert!(
                    if toward_content { b > a } else { b < a },
                    "{id}: {} does not step past {}",
                    pair[1],
                    pair[0]
                );
            }
        }
    }

    #[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("  --action: #81a1c1;\n"));
        assert!(css.contains("  --action-hover: "));
        assert!(css.trim_end().ends_with('}'));
    }
}