nsh-core 0.8.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
//! Tailwind CSS classes (`class="flex-row gap-4 p-4 bg-white dark:bg-zinc-900"`),
//! resolved in Rust: each distinct class string is parsed once into rules
//! (cached), and applied to a node's style whenever its variants may have
//! changed (appearance, window width, press / hover / focus, group
//! states). JS only passes the string.
//!
//! Utilities later in the string win over earlier ones, so components can
//! take a `class` prop and append it (no `tailwind-merge`). Variant
//! utilities apply after plain ones, ordered by Tailwind's variant order
//! (`hover:` before `active:`, breakpoints ascending, `dark:` last).
//!
//! Each class string is parsed once into rules, cached in an LRU of up to
//! 4096 strings, with what the rules depend on (appearance, window width and
//! height, direction, the node's own states, a group's states, sibling
//! position, reduce motion, the `data-*` attributes it or a group shows): the core
//! (`core/classes.rs`) resolves a node again only when one of those changes. Interaction states are reported by the platforms
//! only for the bits a node's classes read (`MountItem::TrackStates`), and
//! `focus-within` propagates to ancestors in the core. A node's style is the
//! default, then its class rules, then its inline `style` replayed on top
//! (`Op::SetStyle` carries a `StylePatch` besides the merged `Style`). The
//! theme is Tailwind 4's (the palette converted from OKLCH to sRGB) extended
//! by `nsh.json` `"tailwind"`, compiled into the bundle as
//! `nsh:tailwind-theme` and pushed as a root prop at startup.

pub(crate) mod palette;
mod theme;
mod utilities;

use std::{rc::Rc, sync::Arc};

use rustc_hash::FxHashMap;

pub use self::theme::{Theme, ThemeError};
pub(crate) use self::utilities::{Decl, Len, Part, PropDecl};
use self::{theme::ClassTokens, utilities::Parts};
use crate::{
    geometry::{Points, Size},
    props::PointerEvents,
    style::{Color, EllipsizeMode, PropertyValue, Style, TextShadow},
};

/// Interaction states a class can depend on (`active:`, `hover:`, ...).
pub mod state {
    /// The view is pressed (`active:`).
    pub const PRESSED: u16 = 1;
    /// A pointer is over the view (`hover:`).
    pub const HOVERED: u16 = 2;
    /// The input has focus (`focus:`).
    pub const FOCUSED: u16 = 4;
    /// The view is disabled (`disabled:`).
    pub const DISABLED: u16 = 8;
    /// The view or a descendant has focus (`focus-within:`).
    pub const FOCUS_WITHIN: u16 = 16;
    /// The view is selected (`selected:`): its
    /// `accessibilityState.selected`, a `Button`'s `selected`. Set by the
    /// core, never reported by the platform.
    pub const SELECTED: u16 = 32;
    /// The view is checked (`checked:`): its `accessibilityState.checked`
    /// (a checkbox, a switch, a radio; not when mixed). Set by the core,
    /// never reported by the platform.
    pub const CHECKED: u16 = 64;
    /// The view is indeterminate (`indeterminate:`): its
    /// `accessibilityState.checked` is mixed (a checkbox that is neither
    /// checked nor unchecked, as CSS's `:indeterminate`). Set by the core,
    /// never reported by the platform.
    pub const INDETERMINATE: u16 = 128;
    /// The view's popup, menu or section is open (`aria-expanded:`): its
    /// `accessibilityState.expanded`, which `Popover` and `Menu` set on
    /// their trigger. Set by the core, never reported by the platform.
    pub const EXPANDED: u16 = 256;
    /// The view is a toggle button that is on (`aria-pressed:`): its
    /// `accessibilityState.pressed` is `true` (not mixed). Not
    /// [`PRESSED`], a press in progress (`active:`). Set by the core,
    /// never reported by the platform.
    pub const ARIA_PRESSED: u16 = 512;
    /// The view is busy (`aria-busy:`): its `accessibilityState.busy`.
    /// Set by the core, never reported by the platform.
    pub const BUSY: u16 = 1024;
    /// The view has the keyboard focus and shows it (`focus-visible:`):
    /// the keyboard moved it there, or it is an input that edits, as CSS's
    /// `:focus-visible`. Set by the core from [`FOCUSED`] and the surface's
    /// input modality (`Core::set_input_modality`), never reported by the
    /// platform.
    pub const FOCUS_VISIBLE: u16 = 2048;
    /// The view's content does not pass the app's checks
    /// (`aria-invalid:`): its `accessibilityState.invalid`. Set by the
    /// core, never reported by the platform.
    pub const INVALID: u16 = 4096;
    /// States that style a pointer or focus interaction.
    pub(super) const INTERACTION: u16 = PRESSED | HOVERED | FOCUSED | FOCUS_WITHIN | FOCUS_VISIBLE;
    /// The states the core sets from the accessibility state, which the
    /// platforms never report.
    pub(crate) const ACCESSIBILITY: u16 =
        SELECTED | CHECKED | INDETERMINATE | EXPANDED | ARIA_PRESSED | BUSY | INVALID;
}

/// The view's place among its siblings (`first:`, `odd:`, ...).
pub mod position {
    /// The first child.
    pub const FIRST: u8 = 1;
    /// The last child.
    pub const LAST: u8 = 2;
    /// An odd child (1st, 3rd, ...).
    pub const ODD: u8 = 4;
    /// An even child.
    pub const EVEN: u8 = 8;
    /// The only child.
    pub const ONLY: u8 = 16;
}

/// What resolved classes depend on, so the core knows when to resolve
/// them again.
pub mod deps {
    /// Light or dark appearance.
    pub const DARK: u16 = 1;
    /// The window width (breakpoints, `w-screen`).
    pub const WIDTH: u16 = 2;
    /// The window's orientation or height (`landscape:`, `h-screen`).
    pub const HEIGHT: u16 = 4;
    /// The layout direction.
    pub const RTL: u16 = 8;
    /// The view's own interaction states.
    pub const STATE: u16 = 16;
    /// The states of an ancestor `group`.
    pub const GROUP: u16 = 32;
    /// The position among siblings.
    pub const POSITION: u16 = 64;
    /// The reduce-motion setting.
    pub const MOTION: u16 = 128;
    /// The component theme's tokens (`bg-primary`): parsed again when they
    /// change.
    pub const THEME: u16 = 256;
    /// The text color it inherits (CSS's `currentColor`: a border, an
    /// outline or a ring without a color of its own).
    pub const CURRENT_COLOR: u16 = 512;
    /// The advance of its font's `0` (CSS's `ch`: `max-w-prose`).
    pub const CH: u16 = 1024;
    /// The view's own `data-*` attributes (`data-range-start:`); a group's
    /// are [`GROUP`].
    pub const DATA: u16 = 2048;
    /// The pointer's precision and the terminal (`pointer-fine:`,
    /// `pointer-coarse:`, `terminal:`).
    pub const DEVICE: u16 = 4096;
    /// The platform (`ios:`, `android:`, `web:`).
    pub const PLATFORM: u16 = 8192;
}

/// CSS's `ch` where no font is known ([`ClassList::apply`]): half a `rem`,
/// so `max-w-prose` is 520 points there.
pub(crate) const DEFAULT_CH: f32 = 8.0;

/// What CSS's `currentColor` is for a node: its own text color (its
/// inline style's, else its classes'), else the one it inherits, else
/// black, React Native's default.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct CurrentColor {
    /// The text color the node inherits.
    pub(crate) inherited: Option<Color>,
    /// The color its inline style sets.
    pub(crate) inline: Option<Color>,
}

/// The platform classes run on (`ios:`, `android:`, `web:`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Platform {
    /// iOS and Mac Catalyst.
    #[default]
    Ios,
    /// Android.
    Android,
    /// A web browser.
    Web,
}

/// How precise the primary pointer is (`pointer-fine:`, `pointer-coarse:`),
/// as CSS's `pointer` media feature.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Pointer {
    /// A finger on a touch screen.
    #[default]
    Coarse,
    /// A mouse or a trackpad: desktop behavior (a desktop OS, a desktop
    /// browser, a terminal).
    Fine,
}

/// The environment variants depend on, set by the engine.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ClassEnvironment {
    /// Dark appearance.
    pub dark: bool,
    /// The platform.
    pub platform: Platform,
    /// The user asked for less motion.
    pub reduce_motion: bool,
    /// The primary pointer's precision.
    pub pointer: Pointer,
    /// Drawn in a terminal (`terminal:`).
    pub terminal: bool,
}

/// What a node's classes are matched against: the core builds it per
/// node; tools resolve classes outside a tree with one of their own.
pub struct Context<'a> {
    /// The appearance, platform and motion setting.
    pub env: ClassEnvironment,
    /// The window (root view) size.
    pub window: Size<Points>,
    /// Right-to-left layout.
    pub rtl: bool,
    /// [`state`] bits of the node.
    pub states: u16,
    /// [`position`] bits of the node.
    pub position: u8,
    /// [`state`] bits of the nearest ancestor group with this name (`""`
    /// for unnamed groups).
    pub group: &'a dyn Fn(&str) -> u16,
}

/// Whether the node (`None`) or the nearest ancestor group with this name
/// (`Some`, `""` for unnamed groups) has the boolean `data-*` attribute
/// named (without `data-`): `data-range-start:`, `group-data-range-start:`.
/// Components set them on their parts (`Interactive::project_data`); only
/// the core has them, so they stay out of the public [`Context`].
pub(crate) type Data<'a> = &'a dyn Fn(Option<&str>, &str) -> bool;

/// No `data-*` attribute: what classes resolved outside a tree see.
pub(crate) fn no_data(_: Option<&str>, _: &str) -> bool {
    false
}

/// Conditions of one rule (all must hold).
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct Condition {
    dark: Option<bool>,
    min_width: Option<f32>,
    max_width: Option<f32>,
    landscape: Option<bool>,
    platform: Option<Platform>,
    rtl: Option<bool>,
    reduce_motion: Option<bool>,
    pointer: Option<Pointer>,
    terminal: Option<bool>,
    /// Required [`state`] bits.
    states: u16,
    /// [`state`] bits that must be off (`enabled:`).
    not_states: u16,
    /// A group name and its required states.
    group: Option<(Box<str>, u16)>,
    /// `data-*` attributes the node must have (`data-<name>:`), by name.
    data: Vec<Box<str>>,
    /// `data-*` attributes the group of [`Condition::group`] must have
    /// (`group-data-<name>:`).
    group_data: Vec<Box<str>>,
    /// Allowed [`position`] bits (any of them).
    position: u8,
    /// Applies to an input's placeholder.
    placeholder: bool,
    /// Applies to the selection (and caret) of an input or selectable text.
    selection: bool,
}

impl Condition {
    fn matches(&self, cx: &Context<'_>, data: Data<'_>) -> bool {
        if self.dark.is_some_and(|d| d != cx.env.dark)
            || self.platform.is_some_and(|p| p != cx.env.platform)
            || self.pointer.is_some_and(|p| p != cx.env.pointer)
            || self.terminal.is_some_and(|t| t != cx.env.terminal)
            || self.rtl.is_some_and(|r| r != cx.rtl)
            || self
                .reduce_motion
                .is_some_and(|r| r != cx.env.reduce_motion)
            || self.min_width.is_some_and(|w| cx.window.width.0 < w)
            || self.max_width.is_some_and(|w| cx.window.width.0 >= w)
            || self
                .landscape
                .is_some_and(|l| l != (cx.window.width > cx.window.height))
            || cx.states & self.states != self.states
            || cx.states & self.not_states != 0
        {
            return false;
        }
        if self.position != 0 && cx.position & self.position == 0 {
            return false;
        }
        if !self.data.iter().all(|d| data(None, d)) {
            return false;
        }
        if let Some((name, states)) = &self.group
            && ((cx.group)(name) & states != *states
                || !self.group_data.iter().all(|d| data(Some(name), d)))
        {
            return false;
        }
        true
    }

    /// Applies to a pseudo-element (`placeholder:`, `selection:`): only
    /// its color is read.
    fn pseudo(&self) -> bool {
        self.placeholder || self.selection
    }

    /// The color a pseudo-element rule's `decls` give it: the placeholder's
    /// text color (`placeholder:text-*`), the selection's background, its
    /// highlight (`selection:bg-*`). `None`: the rule sets something else,
    /// which NSH has no native counterpart for.
    fn pseudo_color(&self, decls: &[Decl]) -> Option<Color> {
        match decls {
            [decl] if self.placeholder => decl.text_color(),
            [decl] if self.selection => decl.background_color(),
            _ => None,
        }
    }

    /// Applies only while the view (or its group) is pressed, hovered or
    /// focused: press feedback.
    fn interactive(&self) -> bool {
        self.states & state::INTERACTION != 0
            || self
                .group
                .as_ref()
                .is_some_and(|(_, states)| states & state::INTERACTION != 0)
    }

    fn deps(&self) -> u16 {
        let mut d = 0;
        if self.dark.is_some() {
            d |= deps::DARK;
        }
        if self.min_width.is_some() || self.max_width.is_some() {
            d |= deps::WIDTH;
        }
        if self.landscape.is_some() {
            d |= deps::WIDTH | deps::HEIGHT;
        }
        if self.rtl.is_some() {
            d |= deps::RTL;
        }
        if self.reduce_motion.is_some() {
            d |= deps::MOTION;
        }
        if self.pointer.is_some() || self.terminal.is_some() {
            d |= deps::DEVICE;
        }
        if self.platform.is_some() {
            d |= deps::PLATFORM;
        }
        if self.states != 0 || self.not_states != 0 {
            d |= deps::STATE;
        }
        if self.group.is_some() {
            d |= deps::GROUP;
        }
        if !self.data.is_empty() {
            d |= deps::DATA;
        }
        if self.position != 0 {
            d |= deps::POSITION;
        }
        d
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Rule {
    cond: Condition,
    decls: Rc<[Decl]>,
    /// Variant order: plain utilities first, then by Tailwind's order.
    rank: Rank,
    /// `!`: applied after everything else.
    important: bool,
    /// Names theme tokens ([`deps::THEME`]).
    theme: bool,
}

/// One variant's place in Tailwind's variant order (Tailwind sorts the
/// variants it registers, the compound ones by their inner variant and
/// then by their modifier, the breakpoints by unit and then by value).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Key {
    /// The variant's (or for `group-*` the group's) place.
    order: u16,
    /// A breakpoint's unit (its index in [`BREAKPOINT_UNITS`]).
    unit: u8,
    /// A breakpoint's value (thousandths, negated for `max-*`), or a
    /// group's inner variant.
    value: i64,
    /// A group's name (`group-hover/item`), `None` unnamed; a `data-*`
    /// attribute's ([`Key::data`]).
    name: Option<Box<str>>,
}

impl Key {
    const fn new(order: u16) -> Self {
        Self {
            order,
            unit: 0,
            value: 0,
            name: None,
        }
    }

    /// `data-<name>:`'s place: [`rank::DATA`], then by name.
    fn data(name: &str) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::new(rank::DATA)
        }
    }
}

/// Breakpoint units as Tailwind orders them: by their name.
const BREAKPOINT_UNITS: [&str; 4] = ["", "pt", "px", "rem"];

/// Where a rule's variants put it: Tailwind sorts rules by the bit set of
/// their variants' places, so the highest variant decides, then the next
/// highest, and a rule with one more variant comes later. Plain
/// utilities have none and come first.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Rank(Vec<Key>);

impl Rank {
    /// Adds `key`, keeping the keys highest first.
    pub(crate) fn add(&mut self, key: Key) {
        if let Err(i) = self.0.binary_search_by(|k| key.cmp(k)) {
            self.0.insert(i, key);
        }
    }

    /// The group variant of `inner` (a [`rank`] key) on group `name`.
    pub(crate) fn add_group(&mut self, inner: &Key, name: &str) {
        self.add(Key {
            order: rank::GROUP,
            unit: 0,
            value: inner.order.into(),
            name: (!name.is_empty()).then(|| name.into()),
        });
    }
}

impl From<Key> for Rank {
    fn from(key: Key) -> Self {
        Rank(vec![key])
    }
}

/// The places of the variants (Tailwind's order, as [`variant`] gives
/// them).
pub(crate) mod rank {
    use super::Key;

    /// `group-*`: before the pseudo-elements and `first:` ... `even:`.
    pub(crate) const GROUP: u16 = 1;
    pub(crate) const SELECTION: Key = Key::new(10);
    pub(crate) const PLACEHOLDER: Key = Key::new(11);
    pub(crate) const FIRST: Key = Key::new(20);
    pub(crate) const LAST: Key = Key::new(21);
    pub(crate) const ONLY: Key = Key::new(22);
    pub(crate) const ODD: Key = Key::new(23);
    pub(crate) const EVEN: Key = Key::new(24);
    pub(crate) const CHECKED: Key = Key::new(30);
    pub(crate) const INDETERMINATE: Key = Key::new(31);
    /// NSH's (Tailwind has `aria-selected:`).
    pub(crate) const SELECTED: Key = Key::new(32);
    pub(crate) const FOCUS_WITHIN: Key = Key::new(33);
    pub(crate) const HOVER: Key = Key::new(34);
    pub(crate) const FOCUS: Key = Key::new(35);
    pub(crate) const FOCUS_VISIBLE: Key = Key::new(36);
    pub(crate) const ACTIVE: Key = Key::new(37);
    pub(crate) const ENABLED: Key = Key::new(38);
    pub(crate) const DISABLED: Key = Key::new(39);
    /// Tailwind's `aria-*` variants come after the pseudo-classes, in the
    /// order of their names.
    pub(crate) const ARIA_BUSY: Key = Key::new(40);
    pub(crate) const ARIA_CHECKED: Key = Key::new(41);
    pub(crate) const EXPANDED: Key = Key::new(42);
    pub(crate) const ARIA_INVALID: Key = Key::new(43);
    pub(crate) const ARIA_PRESSED: Key = Key::new(44);
    pub(crate) const ARIA_SELECTED: Key = Key::new(45);
    /// `data-*`, after `aria-*` as Tailwind registers them, in the order
    /// of their names ([`Key::data`]).
    pub(crate) const DATA: u16 = 46;
    pub(crate) const MOTION_SAFE: Key = Key::new(47);
    pub(crate) const MOTION_REDUCE: Key = Key::new(48);
    /// `max-*` breakpoints, widest first.
    pub(crate) const MAX: u16 = 50;
    /// Breakpoints and `min-*`, narrowest first.
    pub(crate) const MIN: u16 = 51;
    pub(crate) const PORTRAIT: Key = Key::new(60);
    pub(crate) const LANDSCAPE: Key = Key::new(61);
    pub(crate) const LTR: Key = Key::new(62);
    pub(crate) const RTL: Key = Key::new(63);
    pub(crate) const DARK: Key = Key::new(64);
    /// Tailwind's pointer variants, after `dark:` as it registers them.
    pub(crate) const POINTER_COARSE: Key = Key::new(65);
    pub(crate) const POINTER_FINE: Key = Key::new(66);
    /// NSH's platform variants, after Tailwind's.
    pub(crate) const IOS: Key = Key::new(70);
    pub(crate) const ANDROID: Key = Key::new(71);
    pub(crate) const WEB: Key = Key::new(72);
    pub(crate) const TERMINAL: Key = Key::new(73);
}

impl Rule {
    /// A rule applying `decls` while the node is in all of [`state`]
    /// `states`, ordered by `rank`.
    pub(crate) fn new(states: u16, rank: impl Into<Rank>, decls: Vec<Decl>) -> Self {
        Self {
            cond: Condition {
                states,
                ..Condition::default()
            },
            decls: Rc::from(decls),
            rank: rank.into(),
            important: false,
            theme: false,
        }
    }

    /// A state style (`activeStyle`, ...): `decls` while the node is in
    /// `states` (and, unless `disabled`, not disabled), applied over the
    /// inline style as `!` utilities are, ordered by `rank`.
    pub(crate) fn state_style(
        states: u16,
        rank: impl Into<Rank>,
        decls: Vec<crate::StyleDecl>,
    ) -> Self {
        // A style's defaults and its `currentColor` are the classes' own
        // kinds, applied before the rules and read with the text color.
        let decls = decls
            .into_iter()
            .map(|d| match d {
                crate::StyleDecl::Default(key, value) => Decl::Default(key, value),
                crate::StyleDecl::CurrentColor(key) => Decl::CurrentColor(key),
                d => Decl::Style(d),
            })
            .collect();
        let mut rule = Self::new(states, rank, decls);
        if states & state::DISABLED == 0 {
            rule.cond.not_states = state::DISABLED;
        }
        rule.important = true;
        rule
    }

    /// [`Rule::new`], also requiring the nearest ancestor group `group`
    /// (`""`: unnamed) in its states, and dark appearance when `dark`.
    pub(crate) fn with(
        states: u16,
        group: Option<(&str, u16)>,
        dark: bool,
        rank: Rank,
        decls: Vec<Decl>,
    ) -> Self {
        let mut rule = Self::new(states, rank, decls);
        rule.cond.group = group.map(|(name, states)| (name.into(), states));
        rule.cond.dark = dark.then_some(true);
        rule
    }
}

/// Node properties classes and styles set: those that are not layout or
/// drawing (the core takes them from the style, [`crate::Style`]'s
/// `numberOfLines`, `textOverflow`, `userSelect` and `pointerEvents`, and from
/// the classes for the rest).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ClassProps {
    /// `numberOfLines` (`line-clamp-*`, `truncate`); `Some(0)` removes a clamp.
    pub number_of_lines: Option<u32>,
    /// `textOverflow` (`text-ellipsis`, `text-clip`, `truncate`).
    pub ellipsize: Option<EllipsizeMode>,
    /// `whitespace-nowrap`, `text-nowrap`, `truncate`: lines never wrap.
    /// Inherited, as CSS's `white-space`: a view's reaches the texts in it.
    pub no_wrap: Option<bool>,
    /// `text-pretty`: lines wrap, and a last line of a word or two takes
    /// words from the lines above. Set with [`Self::no_wrap`].
    pub pretty: bool,
    /// `pointerEvents` (`pointer-events-none` / `-auto`).
    pub pointer_events: Option<PointerEvents>,
    /// `userSelect` (`select-none` / `select-text`; `auto`: none). A
    /// view's reach the texts in it that say none, as CSS's `user-select:
    /// auto` takes its parent's.
    pub selectable: Option<bool>,
    /// `placeholder:text-*` (inputs).
    pub placeholder_color: Option<Color>,
    /// `selection:bg-*`: the highlight of a selection (inputs, selectable
    /// texts).
    pub selection_color: Option<Color>,
    /// `caret-*` (inputs).
    pub caret_color: Option<Color>,
    /// `text-shadow-*` layers beyond the first (drawn as one shadow).
    pub text_shadows: Option<Vec<TextShadow>>,
    /// `space-x-*` / `space-y-*`: margins the view gives its children.
    pub space: Option<Space>,
}

/// `space-x-*` / `space-y-*` (and `-reverse`): the margins a view gives
/// each of its children but the last, as Tailwind CSS's `:where(& >
/// :not(:last-child))`: under the child's own margins, which win.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct Space {
    /// `space-x-*`: the end margin (`margin-inline-end`; the start one
    /// with `space-x-reverse`).
    pub x: Option<PropertyValue>,
    /// `space-y-*`: the bottom margin (`margin-block-end`; the top one
    /// with `space-y-reverse`).
    pub y: Option<PropertyValue>,
    /// `space-x-reverse`.
    pub reverse_x: bool,
    /// `space-y-reverse`.
    pub reverse_y: bool,
    /// The horizontal margins override normal child declarations.
    pub important_x: bool,
    /// The vertical margins override normal child declarations.
    pub important_y: bool,
}

impl Space {
    /// The margins of a child laid out in direction `rtl`: Tailwind's
    /// `margin-inline-end`, the right side left to right and the left side
    /// right to left (the start side when reversed).
    pub(crate) fn apply(&self, style: &mut Style, important: bool, rtl: bool) {
        use crate::style::StyleKey as K;
        if let Some(v) = &self.x
            && self.important_x == important
        {
            let (end, start) = if rtl {
                (K::MarginLeft, K::MarginRight)
            } else {
                (K::MarginRight, K::MarginLeft)
            };
            let (key, other) = if self.reverse_x {
                (start, end)
            } else {
                (end, start)
            };
            let _ = style.set_key(other, crate::style::StyleValue::Number(0.0));
            let _ = style.apply_value(key, v);
        }
        if let Some(v) = &self.y
            && self.important_y == important
        {
            let key = if self.reverse_y {
                K::MarginTop
            } else {
                K::MarginBottom
            };
            let other = if self.reverse_y {
                K::MarginBottom
            } else {
                K::MarginTop
            };
            let _ = style.set_key(other, crate::style::StyleValue::Number(0.0));
            let _ = style.apply_value(key, v);
        }
    }
}

/// Precomputed rule capabilities on [`ClassList`], maintained by [`ClassList::add`]
/// so [`ClassList::apply_with_current`] skips unnecessary passes and `Parts` allocations.
mod rule_flags {
    pub(super) const DEFAULTS: u8 = 1 << 0;
    pub(super) const PSEUDO: u8 = 1 << 1;
    pub(super) const PARTS: u8 = 1 << 2;
    pub(super) const INTERACTIVE_BG: u8 = 1 << 3;
}

/// A parsed class string.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ClassList {
    rules: Vec<Rule>,
    /// [`deps`] bits.
    deps: u16,
    /// [`state`] bits the platform must report for this view.
    tracked: u16,
    /// [`rule_flags`] bits summarizing declarations and pseudo rules.
    flags: u8,
    /// The view is a `group` (`""`) or named groups (`group/item`).
    groups: Vec<Box<str>>,
    /// Classes that are not known utilities.
    unknown: Vec<Box<str>>,
}

/// Interaction states do not match a disabled view.
fn normalized(mut rule: Rule) -> Rule {
    if rule.cond.states & state::INTERACTION != 0 {
        rule.cond.not_states |= state::DISABLED;
    }
    rule
}

impl ClassList {
    /// [`deps`] bits.
    #[inline]
    pub fn deps(&self) -> u16 {
        self.deps
    }

    /// [`state`] bits whose changes the platform must report.
    #[inline]
    pub fn tracked_states(&self) -> u16 {
        self.tracked
    }

    /// Group names this view defines (`""`: an unnamed `group`).
    pub fn groups(&self) -> &[Box<str>] {
        &self.groups
    }

    /// Classes that are not known utilities or variants.
    pub fn unknown(&self) -> &[Box<str>] {
        &self.unknown
    }

    /// Whether nothing applies.
    pub fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }

    /// Applies the rules matching `cx` to `style` and `props`, then
    /// `inline` (the node's inline style, which only `!` utilities win
    /// over). `currentColor` (a border without a color) is the node's own
    /// text color, else black.
    pub fn apply(
        &self,
        cx: &Context<'_>,
        theme: &Theme,
        style: &mut Style,
        props: &mut ClassProps,
        inline: impl FnOnce(&mut Style),
    ) {
        self.apply_with(
            cx,
            &no_data,
            theme,
            CurrentColor::default(),
            DEFAULT_CH,
            style,
            props,
            inline,
        );
    }

    /// [`ClassList::apply`] in a tree, where `current` says what the
    /// node's `currentColor` comes from and `ch` is its font's `0` advance.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn apply_with(
        &self,
        cx: &Context<'_>,
        data: Data<'_>,
        theme: &Theme,
        current: CurrentColor,
        ch: f32,
        style: &mut Style,
        props: &mut ClassProps,
        inline: impl FnOnce(&mut Style),
    ) {
        self.apply_with_current(cx, data, theme, current, None, ch, style, props, inline);
    }

    /// [`ClassList::apply_with`] taking a precomputed `resolved_current` when
    /// the caller already resolved `current_color` for an inline style.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn apply_with_current(
        &self,
        cx: &Context<'_>,
        data: Data<'_>,
        theme: &Theme,
        current: CurrentColor,
        resolved_current: Option<Color>,
        ch: f32,
        style: &mut Style,
        props: &mut ClassProps,
        inline: impl FnOnce(&mut Style),
    ) {
        let mut parts = (self.flags & rule_flags::PARTS != 0).then(Parts::default);
        let mut important = false;
        let current = if self.deps & deps::CURRENT_COLOR != 0 {
            resolved_current.unwrap_or_else(|| self.current_color(cx, data, current))
        } else {
            Color::BLACK
        };
        if let Some(p) = parts.as_mut() {
            p.current = current;
            p.ch = ch;
        }
        if self.flags & rule_flags::DEFAULTS != 0 {
            for rule in &self.rules {
                if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
                    continue;
                }
                for decl in rule.decls.iter() {
                    match decl {
                        Decl::Default(key, value) => {
                            let _ = style.apply_value(*key, value);
                        }
                        Decl::CurrentColor(key) => style.set_color(*key, current),
                        _ => {}
                    }
                }
            }
        }
        // A background color of an interaction state (`active:bg-*`) hides
        // the gradients unless that state sets one too: drawn over the
        // color, they would hide the feedback (CSS would keep them).
        let track_interactive_bg = self.flags & rule_flags::INTERACTIVE_BG != 0;
        let mut state_background = false;
        let mut state_image = false;
        for rule in &self.rules {
            if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
                continue;
            }
            important |= rule.important;
            for decl in rule.decls.iter() {
                decl.apply(
                    cx.env.dark,
                    rule.important,
                    current,
                    ch,
                    style,
                    props,
                    parts.as_mut(),
                );
            }
            if track_interactive_bg {
                let background = rule.decls.iter().any(Decl::sets_background_color);
                if rule.cond.interactive() {
                    if background {
                        state_background = true;
                        state_image = false;
                    }
                    state_image |= rule.decls.iter().any(Decl::sets_background_image);
                } else if background {
                    // A later rule's color (`dark:bg-*`) is not feedback.
                    state_background = false;
                }
            }
        }
        let state_color = if state_background {
            style.view.background_color
        } else {
            Color::TRANSPARENT
        };
        if self.flags & rule_flags::PSEUDO != 0 {
            // `placeholder:` and `selection:` rules only carry a color.
            for rule in self.rules.iter().filter(|r| r.cond.pseudo()) {
                if !rule.cond.matches(cx, data) {
                    continue;
                }
                if let Some(c) = rule.cond.pseudo_color(&rule.decls) {
                    if rule.cond.placeholder {
                        props.placeholder_color = Some(c);
                    } else {
                        props.selection_color = Some(c);
                    }
                }
            }
        }
        if let Some(p) = parts.as_ref()
            && p.touched != 0
        {
            p.finish(style, props, theme, cx.window, p.touched);
        }
        inline(style);
        if self.deps & deps::CURRENT_COLOR != 0 {
            // What the classes set to `currentColor` inside a value.
            style.apply_current_color(current);
        }
        if important {
            // `!` utilities win over the inline style too, as in CSS. The
            // parts keep every rule's values (a `!scale-*` still composes
            // with a plain `translate-*`); only the groups the important
            // rules touch are written again.
            if let Some(p) = parts.as_mut() {
                p.touched = 0;
                p.transform_parts = 0;
                p.screen.clear();
            }
            for rule in self
                .rules
                .iter()
                .filter(|r| r.important && !r.cond.pseudo())
            {
                if rule.cond.matches(cx, data) {
                    for decl in rule.decls.iter() {
                        decl.apply(
                            cx.env.dark,
                            rule.important,
                            current,
                            ch,
                            style,
                            props,
                            parts.as_mut(),
                        );
                    }
                }
            }
            if let Some(p) = parts.as_ref()
                && p.touched != 0
            {
                p.finish(style, props, theme, cx.window, p.touched);
            }
            if self.deps & deps::CURRENT_COLOR != 0 {
                style.apply_current_color(current);
            }
        }
        // Unless the inline style replaced the state's color.
        if state_background && !state_image && style.view.background_color == state_color {
            style.view.clear_background_images();
        }
    }
}

impl ClassList {
    /// CSS's `currentColor` of a node with these classes in `cx`: the text
    /// color of its `!` classes, its inline style, its classes, else the
    /// one it inherits, else black.
    pub(crate) fn current_color(
        &self,
        cx: &Context<'_>,
        data: Data<'_>,
        current: CurrentColor,
    ) -> Color {
        let [plain, important] = self.text_colors(cx, data);
        important
            .or(current.inline)
            .or(plain)
            .or(current.inherited)
            .unwrap_or(Color::BLACK)
    }

    /// The text colors the rules matching `cx` set: the plain ones' and
    /// the `!` ones' (which win over the inline style).
    fn text_colors(&self, cx: &Context<'_>, data: Data<'_>) -> [Option<Color>; 2] {
        let mut out = [None; 2];
        for rule in &self.rules {
            if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
                continue;
            }
            for decl in rule.decls.iter() {
                if let Some(c) = decl.sets_text_color(cx.env.dark) {
                    out[usize::from(rule.important)] = c;
                }
            }
        }
        out
    }

    /// The rules of a Rust component's styles (already in order), on a
    /// view that is the groups `groups` (`""`: unnamed).
    pub(crate) fn from_rules(rules: Vec<Rule>, groups: Vec<Box<str>>) -> Self {
        let mut list = ClassList::default();
        for rule in rules {
            list.add(rule);
        }
        if !groups.is_empty() {
            list.tracked |= state::PRESSED | state::HOVERED | state::FOCUS_WITHIN;
            list.groups = groups;
        }
        list.rules
            .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
        list
    }

    fn add(&mut self, rule: Rule) {
        let rule = normalized(rule);
        self.deps |= rule.cond.deps();
        self.tracked |= rule.cond.states & !(state::DISABLED | state::ACCESSIBILITY);
        if rule.cond.states & state::FOCUS_WITHIN != 0 {
            self.tracked |= state::FOCUS_WITHIN;
        }
        let pseudo = rule.cond.pseudo();
        if pseudo {
            self.flags |= rule_flags::PSEUDO;
        }
        let interactive = !pseudo && rule.cond.interactive();
        for d in rule.decls.iter() {
            self.deps |= d.deps();
            if !pseudo {
                if d.is_default() {
                    self.flags |= rule_flags::DEFAULTS;
                }
                if d.needs_parts() {
                    self.flags |= rule_flags::PARTS;
                }
                if interactive && d.sets_background_color() {
                    self.flags |= rule_flags::INTERACTIVE_BG;
                }
            }
        }
        if rule.theme {
            self.deps |= deps::THEME;
        }
        self.rules.push(rule);
    }

    /// `self`, then `over`: at equal rank `over`'s rules win (the app's
    /// classes on a Rust component).
    pub(crate) fn merged(&self, over: &ClassList) -> ClassList {
        let mut list = self.clone();
        for rule in &over.rules {
            list.add(rule.clone());
        }
        list.groups.extend(over.groups.iter().cloned());
        list.unknown.extend(over.unknown.iter().cloned());
        list.tracked |= over.tracked;
        list.rules
            .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
        list
    }
}

/// The greatest number of parsed class tokens kept before the cache is cleared.
const TOKEN_CACHE: usize = 4096;

/// Parsed class tokens shared by class strings of one engine.
#[derive(Debug, Default)]
struct TokenCache {
    entries: FxHashMap<Box<str>, Option<Token>>,
}

impl TokenCache {
    fn parse(&mut self, theme: &Theme, token: &str) -> Option<Token> {
        if let Some(parsed) = self.entries.get(token) {
            return parsed.clone();
        }
        let parsed = parse_token(theme, token);
        if self.entries.len() >= TOKEN_CACHE {
            self.entries.clear();
        }
        self.entries.insert(token.into(), parsed.clone());
        parsed
    }

    /// Token values changed under the same names: entries that cannot
    /// substitute them are still valid. Unknown entries are not: they may
    /// be substitutions whose old values did not parse.
    fn retain_token_independent(&mut self) {
        self.entries.retain(|_, parsed| {
            matches!(
                parsed,
                Some(Token::Rule(_) | Token::Group(_) | Token::Ignored)
            )
        });
    }
}

/// The class cache and theme of one engine.
#[derive(Debug, Default)]
pub struct Tailwind {
    theme: Theme,
    cache: FxHashMap<Box<str>, std::rc::Rc<ClassList>>,
    token_cache: TokenCache,
}

impl Tailwind {
    /// Classes with the default theme.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replaces the theme (cached classes are parsed again); the tokens
    /// stay.
    pub fn set_theme(&mut self, mut theme: Theme) {
        theme.share_tokens(&self.theme);
        self.theme = theme;
        self.cache.clear();
        self.token_cache.entries.clear();
    }

    /// Takes design tokens `theme`. Returns which classes
    /// to resolve again: none ([`None`]) when the tokens did not change,
    /// those that name tokens ([`deps::THEME`]) when only their values
    /// did, else all (`u16::MAX`: unknown classes may name new ones).
    pub(crate) fn set_tokens(&mut self, theme: &crate::element::Tokens) -> Option<u16> {
        let tokens = ClassTokens::new(theme);
        let current = self.theme.tokens();
        if *current == tokens {
            return None;
        }
        let changed = if current.same_names(&tokens) {
            self.cache.retain(|_, list| list.deps & deps::THEME == 0);
            self.token_cache.retain_token_independent();
            deps::THEME
        } else {
            self.cache.clear();
            self.token_cache.entries.clear();
            u16::MAX
        };
        self.theme.replace_tokens(Arc::new(tokens));
        Some(changed)
    }

    /// The theme.
    pub fn theme(&self) -> &Theme {
        &self.theme
    }

    /// The parsed form of `classes` (cached by string).
    pub fn classes(&mut self, classes: &str) -> std::rc::Rc<ClassList> {
        self.get(classes).0
    }

    /// Like [`Tailwind::classes`], and whether `classes` was parsed just
    /// now (to report its unknown classes once).
    pub fn get(&mut self, classes: &str) -> (std::rc::Rc<ClassList>, bool) {
        if let Some(c) = self.cache.get(classes) {
            return (c.clone(), false);
        }
        let parsed = std::rc::Rc::new(parse_with_cache(
            &self.theme,
            classes,
            &mut self.token_cache,
        ));
        // Class strings are static in practice; a bound keeps generated
        // ones (`w-[${n}px]`) from growing the cache forever.
        if self.cache.len() >= 4096 {
            self.cache.clear();
        }
        self.cache.insert(classes.into(), parsed.clone());
        (parsed, true)
    }
}

/// Parses a class string.
pub fn parse(theme: &Theme, classes: &str) -> ClassList {
    parse_tokens(classes, |token| parse_token(theme, token))
}

/// [`parse`] with its tokens shared through `cache`.
fn parse_with_cache(theme: &Theme, classes: &str, cache: &mut TokenCache) -> ClassList {
    parse_tokens(classes, |token| cache.parse(theme, token))
}

fn parse_tokens(classes: &str, mut parse_token: impl FnMut(&str) -> Option<Token>) -> ClassList {
    let mut list = ClassList::default();
    for token in classes.split_ascii_whitespace() {
        match parse_token(token) {
            Some(Token::Rule(rule)) => list.add(rule),
            Some(Token::Themed(rule, dark)) => {
                list.add(rule);
                if let Some(dark) = dark {
                    list.add(*dark);
                }
            }
            Some(Token::Group(name)) => {
                list.tracked |= state::PRESSED | state::HOVERED | state::FOCUS_WITHIN;
                list.groups.push(name);
            }
            Some(Token::Ignored) => {}
            Some(Token::UnknownThemed) => {
                list.deps |= deps::THEME;
                list.unknown.push(token.into());
            }
            None => list.unknown.push(token.into()),
        }
    }
    // Stable: equal ranks keep the order of the string.
    list.rules
        .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
    list
}

#[derive(Debug, Clone)]
enum Token {
    Rule(Rule),
    /// A utility naming theme tokens: one rule, or one per appearance.
    Themed(Rule, Option<Box<Rule>>),
    Group(Box<str>),
    /// Accepted, but has no effect natively (`antialiased`; [`ignored`]).
    Ignored,
    /// A utility naming theme tokens whose substituted values do not parse.
    UnknownThemed,
}

/// `token` split at `:` outside brackets: an iterator over its variants,
/// then the utility.
struct VariantSplit<'a> {
    utility: &'a str,
    variants: Variants<'a>,
    has_variants: bool,
}

struct Variants<'a> {
    rest: &'a str,
    done: bool,
}

impl<'a> Iterator for Variants<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        let mut depth = 0i32;
        for (i, b) in self.rest.bytes().enumerate() {
            match b {
                b'[' | b'(' => depth += 1,
                b']' | b')' => depth -= 1,
                b':' if depth == 0 => {
                    let part = &self.rest[..i];
                    self.rest = &self.rest[i + 1..];
                    return Some(part);
                }
                _ => {}
            }
        }
        self.done = true;
        Some(self.rest)
    }
}

/// Splits `token` at `:` outside brackets, without collecting the parts.
fn split_variants(token: &str) -> VariantSplit<'_> {
    let mut depth = 0i32;
    let mut utility_start = 0;
    for (i, b) in token.bytes().enumerate() {
        match b {
            b'[' | b'(' => depth += 1,
            b']' | b')' => depth -= 1,
            b':' if depth == 0 => utility_start = i + 1,
            _ => {}
        }
    }
    let has_variants = utility_start != 0;
    let variants = if has_variants {
        &token[..utility_start - 1]
    } else {
        ""
    };
    VariantSplit {
        utility: &token[utility_start..],
        variants: Variants {
            rest: variants,
            done: !has_variants,
        },
        has_variants,
    }
}

fn parse_token(theme: &Theme, token: &str) -> Option<Token> {
    let split = split_variants(token);
    let mut utility = split.utility;
    // `!p-4` (v3) or `p-4!` (v4): important.
    let mut important = false;
    if let Some(u) = utility.strip_prefix('!') {
        utility = u;
        important = true;
    } else if let Some(u) = utility.strip_suffix('!') {
        utility = u;
        important = true;
    }
    if !split.has_variants {
        if utility == "group" {
            return Some(Token::Group("".into()));
        }
        if let Some(name) = utility.strip_prefix("group/") {
            return Some(Token::Group(name.into()));
        }
    }
    let mut cond = Condition::default();
    let mut rank = Rank::default();
    for v in split.variants {
        rank.add(variant(theme, v, &mut cond)?);
    }
    if ignored(utility) {
        return Some(Token::Ignored);
    }
    if theme.tokens().replaces(utility) {
        return themed(theme, cond, rank, important, utility);
    }
    let Some(decls) = utilities::parse(theme, utility) else {
        return themed(theme, cond, rank, important, utility);
    };
    if cond.pseudo() && cond.pseudo_color(&decls).is_none() {
        return None;
    }
    Some(Token::Rule(Rule {
        cond,
        decls: Rc::from(decls),
        rank,
        important,
        theme: false,
    }))
}

/// Utilities whose CSS is a rendering hint or what every native view
/// already is: accepted, and they do nothing (`box-border` is preflight's
/// `box-sizing`, NSH's only one).
fn ignored(utility: &str) -> bool {
    matches!(
        utility,
        "antialiased"
            | "subpixel-antialiased"
            | "isolation-auto"
            | "appearance-none"
            | "appearance-auto"
            | "will-change-auto"
            | "will-change-scroll"
            | "will-change-contents"
            | "will-change-transform"
    ) || utility
        .strip_prefix("will-change-[")
        .is_some_and(|v| v.len() > 1 && v.ends_with(']'))
}

/// `utility` naming theme tokens (`bg-primary`, `rounded-(--radius)`):
/// parsed with their light and their dark values; two rules of the same
/// rank when those differ, so later utilities still win in both.
fn themed(
    theme: &Theme,
    cond: Condition,
    rank: Rank,
    important: bool,
    utility: &str,
) -> Option<Token> {
    let tokens = theme.tokens();
    let pseudo = Condition {
        placeholder: cond.placeholder,
        selection: cond.selection,
        ..Condition::default()
    };
    // Substituting is what makes the utility theme-dependent; whether the
    // value then parses decides only if it is a rule or an unknown class.
    let dark_only = cond.dark == Some(true);
    let light_substitution = if dark_only {
        None
    } else {
        tokens.substitute(utility, false)
    };
    let dark_substitution = tokens.substitute(utility, true);
    if light_substitution.is_none() && dark_substitution.is_none() {
        return None;
    }
    let parse = |substituted: Option<String>| {
        let decls = utilities::parse(theme, &substituted?)?;
        (!pseudo.pseudo() || pseudo.pseudo_color(&decls).is_some()).then_some(decls)
    };
    let rule = |cond: Condition, decls: Vec<Decl>| Rule {
        cond,
        decls: Rc::from(decls),
        rank: rank.clone(),
        important,
        theme: true,
    };
    // `dark:bg-primary` only needs the dark values.
    if dark_only {
        return Some(match parse(dark_substitution) {
            Some(decls) => Token::Themed(rule(cond, decls), None),
            None => Token::UnknownThemed,
        });
    }
    let (Some(light), Some(dark)) = (parse(light_substitution), parse(dark_substitution)) else {
        return Some(Token::UnknownThemed);
    };
    if light == dark {
        return Some(Token::Themed(rule(cond, light), None));
    }
    let mut dark_cond = cond.clone();
    dark_cond.dark = Some(true);
    let mut light_cond = cond;
    light_cond.dark = Some(false);
    Some(Token::Themed(
        rule(light_cond, light),
        Some(Box::new(rule(dark_cond, dark))),
    ))
}

/// Whether `name` names a boolean `data-*` attribute (`data-<name>:`):
/// lower case letters, digits and `-`. Tailwind's `data-[state=open]:`,
/// an attribute's value, is not supported.
fn data_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

/// Applies variant `v` to `cond`; returns its place in Tailwind's order.
fn variant(theme: &Theme, v: &str, cond: &mut Condition) -> Option<Key> {
    use state::*;
    let states = |cond: &mut Condition, s: u16| {
        cond.states |= s;
    };
    // Tailwind registers `group-*` first, then the pseudo-elements, then
    // the structural pseudo-classes: later ones win over earlier ones.
    Some(match v {
        "selection" => {
            cond.selection = true;
            rank::SELECTION
        }
        "placeholder" => {
            cond.placeholder = true;
            rank::PLACEHOLDER
        }
        "first" => {
            cond.position |= position::FIRST;
            rank::FIRST
        }
        "last" => {
            cond.position |= position::LAST;
            rank::LAST
        }
        "only" => {
            cond.position |= position::ONLY;
            rank::ONLY
        }
        "odd" => {
            cond.position |= position::ODD;
            rank::ODD
        }
        "even" => {
            cond.position |= position::EVEN;
            rank::EVEN
        }
        "checked" => {
            states(cond, CHECKED);
            rank::CHECKED
        }
        "indeterminate" => {
            states(cond, INDETERMINATE);
            rank::INDETERMINATE
        }
        "selected" => {
            states(cond, SELECTED);
            rank::SELECTED
        }
        "focus-within" => {
            states(cond, FOCUS_WITHIN);
            rank::FOCUS_WITHIN
        }
        "hover" => {
            states(cond, HOVERED);
            rank::HOVER
        }
        "focus" => {
            states(cond, FOCUSED);
            rank::FOCUS
        }
        "focus-visible" => {
            states(cond, FOCUS_VISIBLE);
            rank::FOCUS_VISIBLE
        }
        "active" => {
            states(cond, PRESSED);
            rank::ACTIVE
        }
        "enabled" => {
            cond.not_states |= DISABLED;
            rank::ENABLED
        }
        "disabled" => {
            states(cond, DISABLED);
            rank::DISABLED
        }
        "aria-busy" => {
            states(cond, BUSY);
            rank::ARIA_BUSY
        }
        "aria-checked" => {
            states(cond, CHECKED);
            rank::ARIA_CHECKED
        }
        "aria-expanded" => {
            states(cond, EXPANDED);
            rank::EXPANDED
        }
        "aria-invalid" => {
            states(cond, INVALID);
            rank::ARIA_INVALID
        }
        "aria-pressed" => {
            states(cond, ARIA_PRESSED);
            rank::ARIA_PRESSED
        }
        "aria-selected" => {
            states(cond, SELECTED);
            rank::ARIA_SELECTED
        }
        "motion-safe" => {
            cond.reduce_motion = Some(false);
            rank::MOTION_SAFE
        }
        "motion-reduce" => {
            cond.reduce_motion = Some(true);
            rank::MOTION_REDUCE
        }
        "portrait" => {
            cond.landscape = Some(false);
            rank::PORTRAIT
        }
        "landscape" => {
            cond.landscape = Some(true);
            rank::LANDSCAPE
        }
        "ltr" => {
            cond.rtl = Some(false);
            rank::LTR
        }
        "rtl" => {
            cond.rtl = Some(true);
            rank::RTL
        }
        "dark" => {
            cond.dark = Some(true);
            rank::DARK
        }
        "ios" => {
            cond.platform = Some(Platform::Ios);
            rank::IOS
        }
        "android" => {
            cond.platform = Some(Platform::Android);
            rank::ANDROID
        }
        "web" => {
            cond.platform = Some(Platform::Web);
            rank::WEB
        }
        "pointer-coarse" => {
            cond.pointer = Some(Pointer::Coarse);
            rank::POINTER_COARSE
        }
        "pointer-fine" => {
            cond.pointer = Some(Pointer::Fine);
            rank::POINTER_FINE
        }
        "terminal" => {
            cond.terminal = Some(true);
            rank::TERMINAL
        }
        v => {
            // `data-range-start`: Tailwind 4's boolean form, `[data-range-start]`.
            if let Some(name) = v.strip_prefix("data-").filter(|n| data_name(n)) {
                if !cond.data.iter().any(|d| **d == *name) {
                    cond.data.push(name.into());
                }
                return Some(Key::data(name));
            }
            if let Some(rest) = v.strip_prefix("group-") {
                // `group-hover`, `group-hover/item`.
                let (s, name) = match rest.split_once('/') {
                    Some((s, n)) => (s, n),
                    None => (rest, ""),
                };
                if let Some(data) = s.strip_prefix("data-").filter(|n| data_name(n)) {
                    let entry = cond.group.get_or_insert_with(|| (name.into(), 0));
                    if *entry.0 != *name {
                        return None;
                    }
                    if !cond.group_data.iter().any(|d| **d == *data) {
                        cond.group_data.push(data.into());
                    }
                    let mut group = Rank::default();
                    group.add_group(&Key::data(data), name);
                    return group.0.pop();
                }
                let (bit, inner) = match s {
                    "hover" => (HOVERED, rank::HOVER),
                    "active" => (PRESSED, rank::ACTIVE),
                    "focus" => (FOCUSED, rank::FOCUS),
                    "focus-visible" => (FOCUS_VISIBLE, rank::FOCUS_VISIBLE),
                    "focus-within" => (FOCUS_WITHIN, rank::FOCUS_WITHIN),
                    "disabled" => (DISABLED, rank::DISABLED),
                    "selected" => (SELECTED, rank::SELECTED),
                    "checked" => (CHECKED, rank::CHECKED),
                    "indeterminate" => (INDETERMINATE, rank::INDETERMINATE),
                    "aria-busy" => (BUSY, rank::ARIA_BUSY),
                    "aria-checked" => (CHECKED, rank::ARIA_CHECKED),
                    "aria-expanded" => (EXPANDED, rank::EXPANDED),
                    "aria-invalid" => (INVALID, rank::ARIA_INVALID),
                    "aria-pressed" => (ARIA_PRESSED, rank::ARIA_PRESSED),
                    "aria-selected" => (SELECTED, rank::ARIA_SELECTED),
                    _ => return None,
                };
                let entry = cond.group.get_or_insert_with(|| (name.into(), 0));
                if *entry.0 != *name {
                    return None;
                }
                entry.1 |= bit;
                let mut group = Rank::default();
                group.add_group(&inner, name);
                return group.0.pop();
            }
            // Breakpoints: `md:`, `max-md:`, `min-[600px]:`, `max-[600px]:`.
            let (max, name) = match v.strip_prefix("max-") {
                Some(n) => (true, n),
                None => (false, v.strip_prefix("min-").unwrap_or(v)),
            };
            // Tailwind orders breakpoints by their unit's name, then by
            // their value (`max-*` widest first).
            let (width, unit, value) =
                match name.strip_prefix('[').and_then(|n| n.strip_suffix(']')) {
                    Some(arbitrary) => {
                        let arbitrary = arbitrary.trim();
                        let digits = arbitrary
                            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
                            .unwrap_or(arbitrary.len());
                        let unit = BREAKPOINT_UNITS
                            .iter()
                            .position(|u| *u == &arbitrary[digits..])?;
                        let value = crate::css::number(&arbitrary[..digits])?;
                        (crate::css::length(arbitrary)?, unit, value)
                    }
                    None => {
                        let b = theme.breakpoints.iter().find(|b| *b.0 == *name)?;
                        match b.2 {
                            true => (b.1, 3, b.1 / theme.rem),
                            false => (b.1, 2, b.1),
                        }
                    }
                };
            let thousandths = (f64::from(value) * 1000.0).round() as i64;
            let key = |order, value| Key {
                order,
                unit: unit as u8,
                value,
                name: None,
            };
            if max {
                cond.max_width = Some(cond.max_width.map_or(width, |w| w.min(width)));
                key(rank::MAX, -thousandths)
            } else {
                cond.min_width = Some(cond.min_width.map_or(width, |w| w.max(width)));
                key(rank::MIN, thousandths)
            }
        }
    })
}

#[cfg(test)]
mod tests;