1pub(crate) mod palette;
26mod theme;
27mod utilities;
28
29use std::{rc::Rc, sync::Arc};
30
31use rustc_hash::FxHashMap;
32
33pub use self::theme::{Theme, ThemeError};
34pub(crate) use self::utilities::{Decl, Len, Part, PropDecl};
35use self::{theme::ClassTokens, utilities::Parts};
36use crate::{
37 geometry::{Points, Size},
38 props::PointerEvents,
39 style::{Color, EllipsizeMode, PropertyValue, Style, TextShadow},
40};
41
42pub mod state {
44 pub const PRESSED: u16 = 1;
46 pub const HOVERED: u16 = 2;
48 pub const FOCUSED: u16 = 4;
50 pub const DISABLED: u16 = 8;
52 pub const FOCUS_WITHIN: u16 = 16;
54 pub const SELECTED: u16 = 32;
58 pub const CHECKED: u16 = 64;
62 pub const INDETERMINATE: u16 = 128;
67 pub const EXPANDED: u16 = 256;
71 pub const ARIA_PRESSED: u16 = 512;
76 pub const BUSY: u16 = 1024;
79 pub const FOCUS_VISIBLE: u16 = 2048;
85 pub const INVALID: u16 = 4096;
89 pub(super) const INTERACTION: u16 = PRESSED | HOVERED | FOCUSED | FOCUS_WITHIN | FOCUS_VISIBLE;
91 pub(crate) const ACCESSIBILITY: u16 =
94 SELECTED | CHECKED | INDETERMINATE | EXPANDED | ARIA_PRESSED | BUSY | INVALID;
95}
96
97pub mod position {
99 pub const FIRST: u8 = 1;
101 pub const LAST: u8 = 2;
103 pub const ODD: u8 = 4;
105 pub const EVEN: u8 = 8;
107 pub const ONLY: u8 = 16;
109}
110
111pub mod deps {
114 pub const DARK: u16 = 1;
116 pub const WIDTH: u16 = 2;
118 pub const HEIGHT: u16 = 4;
120 pub const RTL: u16 = 8;
122 pub const STATE: u16 = 16;
124 pub const GROUP: u16 = 32;
126 pub const POSITION: u16 = 64;
128 pub const MOTION: u16 = 128;
130 pub const THEME: u16 = 256;
133 pub const CURRENT_COLOR: u16 = 512;
136 pub const CH: u16 = 1024;
138 pub const DATA: u16 = 2048;
141 pub const DEVICE: u16 = 4096;
144 pub const PLATFORM: u16 = 8192;
146}
147
148pub(crate) const DEFAULT_CH: f32 = 8.0;
151
152#[derive(Debug, Clone, Copy, Default, PartialEq)]
156pub(crate) struct CurrentColor {
157 pub(crate) inherited: Option<Color>,
159 pub(crate) inline: Option<Color>,
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
165pub enum Platform {
166 #[default]
168 Ios,
169 Android,
171 Web,
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
178pub enum Pointer {
179 #[default]
181 Coarse,
182 Fine,
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Default)]
189pub struct ClassEnvironment {
190 pub dark: bool,
192 pub platform: Platform,
194 pub reduce_motion: bool,
196 pub pointer: Pointer,
198 pub terminal: bool,
200}
201
202pub struct Context<'a> {
205 pub env: ClassEnvironment,
207 pub window: Size<Points>,
209 pub rtl: bool,
211 pub states: u16,
213 pub position: u8,
215 pub group: &'a dyn Fn(&str) -> u16,
218}
219
220pub(crate) type Data<'a> = &'a dyn Fn(Option<&str>, &str) -> bool;
226
227pub(crate) fn no_data(_: Option<&str>, _: &str) -> bool {
229 false
230}
231
232#[derive(Debug, Clone, Default, PartialEq)]
234pub(crate) struct Condition {
235 dark: Option<bool>,
236 min_width: Option<f32>,
237 max_width: Option<f32>,
238 landscape: Option<bool>,
239 platform: Option<Platform>,
240 rtl: Option<bool>,
241 reduce_motion: Option<bool>,
242 pointer: Option<Pointer>,
243 terminal: Option<bool>,
244 states: u16,
246 not_states: u16,
248 group: Option<(Box<str>, u16)>,
250 data: Vec<Box<str>>,
252 group_data: Vec<Box<str>>,
255 position: u8,
257 placeholder: bool,
259 selection: bool,
261}
262
263impl Condition {
264 fn matches(&self, cx: &Context<'_>, data: Data<'_>) -> bool {
265 if self.dark.is_some_and(|d| d != cx.env.dark)
266 || self.platform.is_some_and(|p| p != cx.env.platform)
267 || self.pointer.is_some_and(|p| p != cx.env.pointer)
268 || self.terminal.is_some_and(|t| t != cx.env.terminal)
269 || self.rtl.is_some_and(|r| r != cx.rtl)
270 || self
271 .reduce_motion
272 .is_some_and(|r| r != cx.env.reduce_motion)
273 || self.min_width.is_some_and(|w| cx.window.width.0 < w)
274 || self.max_width.is_some_and(|w| cx.window.width.0 >= w)
275 || self
276 .landscape
277 .is_some_and(|l| l != (cx.window.width > cx.window.height))
278 || cx.states & self.states != self.states
279 || cx.states & self.not_states != 0
280 {
281 return false;
282 }
283 if self.position != 0 && cx.position & self.position == 0 {
284 return false;
285 }
286 if !self.data.iter().all(|d| data(None, d)) {
287 return false;
288 }
289 if let Some((name, states)) = &self.group
290 && ((cx.group)(name) & states != *states
291 || !self.group_data.iter().all(|d| data(Some(name), d)))
292 {
293 return false;
294 }
295 true
296 }
297
298 fn pseudo(&self) -> bool {
301 self.placeholder || self.selection
302 }
303
304 fn pseudo_color(&self, decls: &[Decl]) -> Option<Color> {
309 match decls {
310 [decl] if self.placeholder => decl.text_color(),
311 [decl] if self.selection => decl.background_color(),
312 _ => None,
313 }
314 }
315
316 fn interactive(&self) -> bool {
319 self.states & state::INTERACTION != 0
320 || self
321 .group
322 .as_ref()
323 .is_some_and(|(_, states)| states & state::INTERACTION != 0)
324 }
325
326 fn deps(&self) -> u16 {
327 let mut d = 0;
328 if self.dark.is_some() {
329 d |= deps::DARK;
330 }
331 if self.min_width.is_some() || self.max_width.is_some() {
332 d |= deps::WIDTH;
333 }
334 if self.landscape.is_some() {
335 d |= deps::WIDTH | deps::HEIGHT;
336 }
337 if self.rtl.is_some() {
338 d |= deps::RTL;
339 }
340 if self.reduce_motion.is_some() {
341 d |= deps::MOTION;
342 }
343 if self.pointer.is_some() || self.terminal.is_some() {
344 d |= deps::DEVICE;
345 }
346 if self.platform.is_some() {
347 d |= deps::PLATFORM;
348 }
349 if self.states != 0 || self.not_states != 0 {
350 d |= deps::STATE;
351 }
352 if self.group.is_some() {
353 d |= deps::GROUP;
354 }
355 if !self.data.is_empty() {
356 d |= deps::DATA;
357 }
358 if self.position != 0 {
359 d |= deps::POSITION;
360 }
361 d
362 }
363}
364
365#[derive(Debug, Clone, PartialEq)]
366pub(crate) struct Rule {
367 cond: Condition,
368 decls: Rc<[Decl]>,
369 rank: Rank,
371 important: bool,
373 theme: bool,
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
381pub(crate) struct Key {
382 order: u16,
384 unit: u8,
386 value: i64,
389 name: Option<Box<str>>,
392}
393
394impl Key {
395 const fn new(order: u16) -> Self {
396 Self {
397 order,
398 unit: 0,
399 value: 0,
400 name: None,
401 }
402 }
403
404 fn data(name: &str) -> Self {
406 Self {
407 name: Some(name.into()),
408 ..Self::new(rank::DATA)
409 }
410 }
411}
412
413const BREAKPOINT_UNITS: [&str; 4] = ["", "pt", "px", "rem"];
415
416#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
421pub(crate) struct Rank(Vec<Key>);
422
423impl Rank {
424 pub(crate) fn add(&mut self, key: Key) {
426 if let Err(i) = self.0.binary_search_by(|k| key.cmp(k)) {
427 self.0.insert(i, key);
428 }
429 }
430
431 pub(crate) fn add_group(&mut self, inner: &Key, name: &str) {
433 self.add(Key {
434 order: rank::GROUP,
435 unit: 0,
436 value: inner.order.into(),
437 name: (!name.is_empty()).then(|| name.into()),
438 });
439 }
440}
441
442impl From<Key> for Rank {
443 fn from(key: Key) -> Self {
444 Rank(vec![key])
445 }
446}
447
448pub(crate) mod rank {
451 use super::Key;
452
453 pub(crate) const GROUP: u16 = 1;
455 pub(crate) const SELECTION: Key = Key::new(10);
456 pub(crate) const PLACEHOLDER: Key = Key::new(11);
457 pub(crate) const FIRST: Key = Key::new(20);
458 pub(crate) const LAST: Key = Key::new(21);
459 pub(crate) const ONLY: Key = Key::new(22);
460 pub(crate) const ODD: Key = Key::new(23);
461 pub(crate) const EVEN: Key = Key::new(24);
462 pub(crate) const CHECKED: Key = Key::new(30);
463 pub(crate) const INDETERMINATE: Key = Key::new(31);
464 pub(crate) const SELECTED: Key = Key::new(32);
466 pub(crate) const FOCUS_WITHIN: Key = Key::new(33);
467 pub(crate) const HOVER: Key = Key::new(34);
468 pub(crate) const FOCUS: Key = Key::new(35);
469 pub(crate) const FOCUS_VISIBLE: Key = Key::new(36);
470 pub(crate) const ACTIVE: Key = Key::new(37);
471 pub(crate) const ENABLED: Key = Key::new(38);
472 pub(crate) const DISABLED: Key = Key::new(39);
473 pub(crate) const ARIA_BUSY: Key = Key::new(40);
476 pub(crate) const ARIA_CHECKED: Key = Key::new(41);
477 pub(crate) const EXPANDED: Key = Key::new(42);
478 pub(crate) const ARIA_INVALID: Key = Key::new(43);
479 pub(crate) const ARIA_PRESSED: Key = Key::new(44);
480 pub(crate) const ARIA_SELECTED: Key = Key::new(45);
481 pub(crate) const DATA: u16 = 46;
484 pub(crate) const MOTION_SAFE: Key = Key::new(47);
485 pub(crate) const MOTION_REDUCE: Key = Key::new(48);
486 pub(crate) const MAX: u16 = 50;
488 pub(crate) const MIN: u16 = 51;
490 pub(crate) const PORTRAIT: Key = Key::new(60);
491 pub(crate) const LANDSCAPE: Key = Key::new(61);
492 pub(crate) const LTR: Key = Key::new(62);
493 pub(crate) const RTL: Key = Key::new(63);
494 pub(crate) const DARK: Key = Key::new(64);
495 pub(crate) const POINTER_COARSE: Key = Key::new(65);
497 pub(crate) const POINTER_FINE: Key = Key::new(66);
498 pub(crate) const IOS: Key = Key::new(70);
500 pub(crate) const ANDROID: Key = Key::new(71);
501 pub(crate) const WEB: Key = Key::new(72);
502 pub(crate) const TERMINAL: Key = Key::new(73);
503}
504
505impl Rule {
506 pub(crate) fn new(states: u16, rank: impl Into<Rank>, decls: Vec<Decl>) -> Self {
509 Self {
510 cond: Condition {
511 states,
512 ..Condition::default()
513 },
514 decls: Rc::from(decls),
515 rank: rank.into(),
516 important: false,
517 theme: false,
518 }
519 }
520
521 pub(crate) fn state_style(
525 states: u16,
526 rank: impl Into<Rank>,
527 decls: Vec<crate::StyleDecl>,
528 ) -> Self {
529 let decls = decls
532 .into_iter()
533 .map(|d| match d {
534 crate::StyleDecl::Default(key, value) => Decl::Default(key, value),
535 crate::StyleDecl::CurrentColor(key) => Decl::CurrentColor(key),
536 d => Decl::Style(d),
537 })
538 .collect();
539 let mut rule = Self::new(states, rank, decls);
540 if states & state::DISABLED == 0 {
541 rule.cond.not_states = state::DISABLED;
542 }
543 rule.important = true;
544 rule
545 }
546
547 pub(crate) fn with(
550 states: u16,
551 group: Option<(&str, u16)>,
552 dark: bool,
553 rank: Rank,
554 decls: Vec<Decl>,
555 ) -> Self {
556 let mut rule = Self::new(states, rank, decls);
557 rule.cond.group = group.map(|(name, states)| (name.into(), states));
558 rule.cond.dark = dark.then_some(true);
559 rule
560 }
561}
562
563#[derive(Debug, Clone, Default, PartialEq)]
568pub struct ClassProps {
569 pub number_of_lines: Option<u32>,
571 pub ellipsize: Option<EllipsizeMode>,
573 pub no_wrap: Option<bool>,
576 pub pretty: bool,
579 pub pointer_events: Option<PointerEvents>,
581 pub selectable: Option<bool>,
585 pub placeholder_color: Option<Color>,
587 pub selection_color: Option<Color>,
590 pub caret_color: Option<Color>,
592 pub text_shadows: Option<Vec<TextShadow>>,
594 pub space: Option<Space>,
596}
597
598#[derive(Debug, Clone, Default, PartialEq)]
602#[non_exhaustive]
603pub struct Space {
604 pub x: Option<PropertyValue>,
607 pub y: Option<PropertyValue>,
610 pub reverse_x: bool,
612 pub reverse_y: bool,
614 pub important_x: bool,
616 pub important_y: bool,
618}
619
620impl Space {
621 pub(crate) fn apply(&self, style: &mut Style, important: bool, rtl: bool) {
625 use crate::style::StyleKey as K;
626 if let Some(v) = &self.x
627 && self.important_x == important
628 {
629 let (end, start) = if rtl {
630 (K::MarginLeft, K::MarginRight)
631 } else {
632 (K::MarginRight, K::MarginLeft)
633 };
634 let (key, other) = if self.reverse_x {
635 (start, end)
636 } else {
637 (end, start)
638 };
639 let _ = style.set_key(other, crate::style::StyleValue::Number(0.0));
640 let _ = style.apply_value(key, v);
641 }
642 if let Some(v) = &self.y
643 && self.important_y == important
644 {
645 let key = if self.reverse_y {
646 K::MarginTop
647 } else {
648 K::MarginBottom
649 };
650 let other = if self.reverse_y {
651 K::MarginBottom
652 } else {
653 K::MarginTop
654 };
655 let _ = style.set_key(other, crate::style::StyleValue::Number(0.0));
656 let _ = style.apply_value(key, v);
657 }
658 }
659}
660
661mod rule_flags {
664 pub(super) const DEFAULTS: u8 = 1 << 0;
665 pub(super) const PSEUDO: u8 = 1 << 1;
666 pub(super) const PARTS: u8 = 1 << 2;
667 pub(super) const INTERACTIVE_BG: u8 = 1 << 3;
668}
669
670#[derive(Debug, Clone, Default, PartialEq)]
672pub struct ClassList {
673 rules: Vec<Rule>,
674 deps: u16,
676 tracked: u16,
678 flags: u8,
680 groups: Vec<Box<str>>,
682 unknown: Vec<Box<str>>,
684}
685
686fn normalized(mut rule: Rule) -> Rule {
688 if rule.cond.states & state::INTERACTION != 0 {
689 rule.cond.not_states |= state::DISABLED;
690 }
691 rule
692}
693
694impl ClassList {
695 #[inline]
697 pub fn deps(&self) -> u16 {
698 self.deps
699 }
700
701 #[inline]
703 pub fn tracked_states(&self) -> u16 {
704 self.tracked
705 }
706
707 pub fn groups(&self) -> &[Box<str>] {
709 &self.groups
710 }
711
712 pub fn unknown(&self) -> &[Box<str>] {
714 &self.unknown
715 }
716
717 pub fn is_empty(&self) -> bool {
719 self.rules.is_empty()
720 }
721
722 pub fn apply(
727 &self,
728 cx: &Context<'_>,
729 theme: &Theme,
730 style: &mut Style,
731 props: &mut ClassProps,
732 inline: impl FnOnce(&mut Style),
733 ) {
734 self.apply_with(
735 cx,
736 &no_data,
737 theme,
738 CurrentColor::default(),
739 DEFAULT_CH,
740 style,
741 props,
742 inline,
743 );
744 }
745
746 #[allow(clippy::too_many_arguments)]
749 pub(crate) fn apply_with(
750 &self,
751 cx: &Context<'_>,
752 data: Data<'_>,
753 theme: &Theme,
754 current: CurrentColor,
755 ch: f32,
756 style: &mut Style,
757 props: &mut ClassProps,
758 inline: impl FnOnce(&mut Style),
759 ) {
760 self.apply_with_current(cx, data, theme, current, None, ch, style, props, inline);
761 }
762
763 #[allow(clippy::too_many_arguments)]
766 pub(crate) fn apply_with_current(
767 &self,
768 cx: &Context<'_>,
769 data: Data<'_>,
770 theme: &Theme,
771 current: CurrentColor,
772 resolved_current: Option<Color>,
773 ch: f32,
774 style: &mut Style,
775 props: &mut ClassProps,
776 inline: impl FnOnce(&mut Style),
777 ) {
778 let mut parts = (self.flags & rule_flags::PARTS != 0).then(Parts::default);
779 let mut important = false;
780 let current = if self.deps & deps::CURRENT_COLOR != 0 {
781 resolved_current.unwrap_or_else(|| self.current_color(cx, data, current))
782 } else {
783 Color::BLACK
784 };
785 if let Some(p) = parts.as_mut() {
786 p.current = current;
787 p.ch = ch;
788 }
789 if self.flags & rule_flags::DEFAULTS != 0 {
790 for rule in &self.rules {
791 if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
792 continue;
793 }
794 for decl in rule.decls.iter() {
795 match decl {
796 Decl::Default(key, value) => {
797 let _ = style.apply_value(*key, value);
798 }
799 Decl::CurrentColor(key) => style.set_color(*key, current),
800 _ => {}
801 }
802 }
803 }
804 }
805 let track_interactive_bg = self.flags & rule_flags::INTERACTIVE_BG != 0;
809 let mut state_background = false;
810 let mut state_image = false;
811 for rule in &self.rules {
812 if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
813 continue;
814 }
815 important |= rule.important;
816 for decl in rule.decls.iter() {
817 decl.apply(
818 cx.env.dark,
819 rule.important,
820 current,
821 ch,
822 style,
823 props,
824 parts.as_mut(),
825 );
826 }
827 if track_interactive_bg {
828 let background = rule.decls.iter().any(Decl::sets_background_color);
829 if rule.cond.interactive() {
830 if background {
831 state_background = true;
832 state_image = false;
833 }
834 state_image |= rule.decls.iter().any(Decl::sets_background_image);
835 } else if background {
836 state_background = false;
838 }
839 }
840 }
841 let state_color = if state_background {
842 style.view.background_color
843 } else {
844 Color::TRANSPARENT
845 };
846 if self.flags & rule_flags::PSEUDO != 0 {
847 for rule in self.rules.iter().filter(|r| r.cond.pseudo()) {
849 if !rule.cond.matches(cx, data) {
850 continue;
851 }
852 if let Some(c) = rule.cond.pseudo_color(&rule.decls) {
853 if rule.cond.placeholder {
854 props.placeholder_color = Some(c);
855 } else {
856 props.selection_color = Some(c);
857 }
858 }
859 }
860 }
861 if let Some(p) = parts.as_ref()
862 && p.touched != 0
863 {
864 p.finish(style, props, theme, cx.window, p.touched);
865 }
866 inline(style);
867 if self.deps & deps::CURRENT_COLOR != 0 {
868 style.apply_current_color(current);
870 }
871 if important {
872 if let Some(p) = parts.as_mut() {
877 p.touched = 0;
878 p.transform_parts = 0;
879 p.screen.clear();
880 }
881 for rule in self
882 .rules
883 .iter()
884 .filter(|r| r.important && !r.cond.pseudo())
885 {
886 if rule.cond.matches(cx, data) {
887 for decl in rule.decls.iter() {
888 decl.apply(
889 cx.env.dark,
890 rule.important,
891 current,
892 ch,
893 style,
894 props,
895 parts.as_mut(),
896 );
897 }
898 }
899 }
900 if let Some(p) = parts.as_ref()
901 && p.touched != 0
902 {
903 p.finish(style, props, theme, cx.window, p.touched);
904 }
905 if self.deps & deps::CURRENT_COLOR != 0 {
906 style.apply_current_color(current);
907 }
908 }
909 if state_background && !state_image && style.view.background_color == state_color {
911 style.view.clear_background_images();
912 }
913 }
914}
915
916impl ClassList {
917 pub(crate) fn current_color(
921 &self,
922 cx: &Context<'_>,
923 data: Data<'_>,
924 current: CurrentColor,
925 ) -> Color {
926 let [plain, important] = self.text_colors(cx, data);
927 important
928 .or(current.inline)
929 .or(plain)
930 .or(current.inherited)
931 .unwrap_or(Color::BLACK)
932 }
933
934 fn text_colors(&self, cx: &Context<'_>, data: Data<'_>) -> [Option<Color>; 2] {
937 let mut out = [None; 2];
938 for rule in &self.rules {
939 if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
940 continue;
941 }
942 for decl in rule.decls.iter() {
943 if let Some(c) = decl.sets_text_color(cx.env.dark) {
944 out[usize::from(rule.important)] = c;
945 }
946 }
947 }
948 out
949 }
950
951 pub(crate) fn from_rules(rules: Vec<Rule>, groups: Vec<Box<str>>) -> Self {
954 let mut list = ClassList::default();
955 for rule in rules {
956 list.add(rule);
957 }
958 if !groups.is_empty() {
959 list.tracked |= state::PRESSED | state::HOVERED | state::FOCUS_WITHIN;
960 list.groups = groups;
961 }
962 list.rules
963 .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
964 list
965 }
966
967 fn add(&mut self, rule: Rule) {
968 let rule = normalized(rule);
969 self.deps |= rule.cond.deps();
970 self.tracked |= rule.cond.states & !(state::DISABLED | state::ACCESSIBILITY);
971 if rule.cond.states & state::FOCUS_WITHIN != 0 {
972 self.tracked |= state::FOCUS_WITHIN;
973 }
974 let pseudo = rule.cond.pseudo();
975 if pseudo {
976 self.flags |= rule_flags::PSEUDO;
977 }
978 let interactive = !pseudo && rule.cond.interactive();
979 for d in rule.decls.iter() {
980 self.deps |= d.deps();
981 if !pseudo {
982 if d.is_default() {
983 self.flags |= rule_flags::DEFAULTS;
984 }
985 if d.needs_parts() {
986 self.flags |= rule_flags::PARTS;
987 }
988 if interactive && d.sets_background_color() {
989 self.flags |= rule_flags::INTERACTIVE_BG;
990 }
991 }
992 }
993 if rule.theme {
994 self.deps |= deps::THEME;
995 }
996 self.rules.push(rule);
997 }
998
999 pub(crate) fn merged(&self, over: &ClassList) -> ClassList {
1002 let mut list = self.clone();
1003 for rule in &over.rules {
1004 list.add(rule.clone());
1005 }
1006 list.groups.extend(over.groups.iter().cloned());
1007 list.unknown.extend(over.unknown.iter().cloned());
1008 list.tracked |= over.tracked;
1009 list.rules
1010 .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
1011 list
1012 }
1013}
1014
1015const TOKEN_CACHE: usize = 4096;
1017
1018#[derive(Debug, Default)]
1020struct TokenCache {
1021 entries: FxHashMap<Box<str>, Option<Token>>,
1022}
1023
1024impl TokenCache {
1025 fn parse(&mut self, theme: &Theme, token: &str) -> Option<Token> {
1026 if let Some(parsed) = self.entries.get(token) {
1027 return parsed.clone();
1028 }
1029 let parsed = parse_token(theme, token);
1030 if self.entries.len() >= TOKEN_CACHE {
1031 self.entries.clear();
1032 }
1033 self.entries.insert(token.into(), parsed.clone());
1034 parsed
1035 }
1036
1037 fn retain_token_independent(&mut self) {
1041 self.entries.retain(|_, parsed| {
1042 matches!(
1043 parsed,
1044 Some(Token::Rule(_) | Token::Group(_) | Token::Ignored)
1045 )
1046 });
1047 }
1048}
1049
1050#[derive(Debug, Default)]
1052pub struct Tailwind {
1053 theme: Theme,
1054 cache: FxHashMap<Box<str>, std::rc::Rc<ClassList>>,
1055 token_cache: TokenCache,
1056}
1057
1058impl Tailwind {
1059 pub fn new() -> Self {
1061 Self::default()
1062 }
1063
1064 pub fn set_theme(&mut self, mut theme: Theme) {
1067 theme.share_tokens(&self.theme);
1068 self.theme = theme;
1069 self.cache.clear();
1070 self.token_cache.entries.clear();
1071 }
1072
1073 pub(crate) fn set_tokens(&mut self, theme: &crate::element::Tokens) -> Option<u16> {
1078 let tokens = ClassTokens::new(theme);
1079 let current = self.theme.tokens();
1080 if *current == tokens {
1081 return None;
1082 }
1083 let changed = if current.same_names(&tokens) {
1084 self.cache.retain(|_, list| list.deps & deps::THEME == 0);
1085 self.token_cache.retain_token_independent();
1086 deps::THEME
1087 } else {
1088 self.cache.clear();
1089 self.token_cache.entries.clear();
1090 u16::MAX
1091 };
1092 self.theme.replace_tokens(Arc::new(tokens));
1093 Some(changed)
1094 }
1095
1096 pub fn theme(&self) -> &Theme {
1098 &self.theme
1099 }
1100
1101 pub fn classes(&mut self, classes: &str) -> std::rc::Rc<ClassList> {
1103 self.get(classes).0
1104 }
1105
1106 pub fn get(&mut self, classes: &str) -> (std::rc::Rc<ClassList>, bool) {
1109 if let Some(c) = self.cache.get(classes) {
1110 return (c.clone(), false);
1111 }
1112 let parsed = std::rc::Rc::new(parse_with_cache(
1113 &self.theme,
1114 classes,
1115 &mut self.token_cache,
1116 ));
1117 if self.cache.len() >= 4096 {
1120 self.cache.clear();
1121 }
1122 self.cache.insert(classes.into(), parsed.clone());
1123 (parsed, true)
1124 }
1125}
1126
1127pub fn parse(theme: &Theme, classes: &str) -> ClassList {
1129 parse_tokens(classes, |token| parse_token(theme, token))
1130}
1131
1132fn parse_with_cache(theme: &Theme, classes: &str, cache: &mut TokenCache) -> ClassList {
1134 parse_tokens(classes, |token| cache.parse(theme, token))
1135}
1136
1137fn parse_tokens(classes: &str, mut parse_token: impl FnMut(&str) -> Option<Token>) -> ClassList {
1138 let mut list = ClassList::default();
1139 for token in classes.split_ascii_whitespace() {
1140 match parse_token(token) {
1141 Some(Token::Rule(rule)) => list.add(rule),
1142 Some(Token::Themed(rule, dark)) => {
1143 list.add(rule);
1144 if let Some(dark) = dark {
1145 list.add(*dark);
1146 }
1147 }
1148 Some(Token::Group(name)) => {
1149 list.tracked |= state::PRESSED | state::HOVERED | state::FOCUS_WITHIN;
1150 list.groups.push(name);
1151 }
1152 Some(Token::Ignored) => {}
1153 Some(Token::UnknownThemed) => {
1154 list.deps |= deps::THEME;
1155 list.unknown.push(token.into());
1156 }
1157 None => list.unknown.push(token.into()),
1158 }
1159 }
1160 list.rules
1162 .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
1163 list
1164}
1165
1166#[derive(Debug, Clone)]
1167enum Token {
1168 Rule(Rule),
1169 Themed(Rule, Option<Box<Rule>>),
1171 Group(Box<str>),
1172 Ignored,
1174 UnknownThemed,
1176}
1177
1178struct VariantSplit<'a> {
1181 utility: &'a str,
1182 variants: Variants<'a>,
1183 has_variants: bool,
1184}
1185
1186struct Variants<'a> {
1187 rest: &'a str,
1188 done: bool,
1189}
1190
1191impl<'a> Iterator for Variants<'a> {
1192 type Item = &'a str;
1193
1194 fn next(&mut self) -> Option<Self::Item> {
1195 if self.done {
1196 return None;
1197 }
1198 let mut depth = 0i32;
1199 for (i, b) in self.rest.bytes().enumerate() {
1200 match b {
1201 b'[' | b'(' => depth += 1,
1202 b']' | b')' => depth -= 1,
1203 b':' if depth == 0 => {
1204 let part = &self.rest[..i];
1205 self.rest = &self.rest[i + 1..];
1206 return Some(part);
1207 }
1208 _ => {}
1209 }
1210 }
1211 self.done = true;
1212 Some(self.rest)
1213 }
1214}
1215
1216fn split_variants(token: &str) -> VariantSplit<'_> {
1218 let mut depth = 0i32;
1219 let mut utility_start = 0;
1220 for (i, b) in token.bytes().enumerate() {
1221 match b {
1222 b'[' | b'(' => depth += 1,
1223 b']' | b')' => depth -= 1,
1224 b':' if depth == 0 => utility_start = i + 1,
1225 _ => {}
1226 }
1227 }
1228 let has_variants = utility_start != 0;
1229 let variants = if has_variants {
1230 &token[..utility_start - 1]
1231 } else {
1232 ""
1233 };
1234 VariantSplit {
1235 utility: &token[utility_start..],
1236 variants: Variants {
1237 rest: variants,
1238 done: !has_variants,
1239 },
1240 has_variants,
1241 }
1242}
1243
1244fn parse_token(theme: &Theme, token: &str) -> Option<Token> {
1245 let split = split_variants(token);
1246 let mut utility = split.utility;
1247 let mut important = false;
1249 if let Some(u) = utility.strip_prefix('!') {
1250 utility = u;
1251 important = true;
1252 } else if let Some(u) = utility.strip_suffix('!') {
1253 utility = u;
1254 important = true;
1255 }
1256 if !split.has_variants {
1257 if utility == "group" {
1258 return Some(Token::Group("".into()));
1259 }
1260 if let Some(name) = utility.strip_prefix("group/") {
1261 return Some(Token::Group(name.into()));
1262 }
1263 }
1264 let mut cond = Condition::default();
1265 let mut rank = Rank::default();
1266 for v in split.variants {
1267 rank.add(variant(theme, v, &mut cond)?);
1268 }
1269 if ignored(utility) {
1270 return Some(Token::Ignored);
1271 }
1272 if theme.tokens().replaces(utility) {
1273 return themed(theme, cond, rank, important, utility);
1274 }
1275 let Some(decls) = utilities::parse(theme, utility) else {
1276 return themed(theme, cond, rank, important, utility);
1277 };
1278 if cond.pseudo() && cond.pseudo_color(&decls).is_none() {
1279 return None;
1280 }
1281 Some(Token::Rule(Rule {
1282 cond,
1283 decls: Rc::from(decls),
1284 rank,
1285 important,
1286 theme: false,
1287 }))
1288}
1289
1290fn ignored(utility: &str) -> bool {
1294 matches!(
1295 utility,
1296 "antialiased"
1297 | "subpixel-antialiased"
1298 | "isolation-auto"
1299 | "appearance-none"
1300 | "appearance-auto"
1301 | "will-change-auto"
1302 | "will-change-scroll"
1303 | "will-change-contents"
1304 | "will-change-transform"
1305 ) || utility
1306 .strip_prefix("will-change-[")
1307 .is_some_and(|v| v.len() > 1 && v.ends_with(']'))
1308}
1309
1310fn themed(
1314 theme: &Theme,
1315 cond: Condition,
1316 rank: Rank,
1317 important: bool,
1318 utility: &str,
1319) -> Option<Token> {
1320 let tokens = theme.tokens();
1321 let pseudo = Condition {
1322 placeholder: cond.placeholder,
1323 selection: cond.selection,
1324 ..Condition::default()
1325 };
1326 let dark_only = cond.dark == Some(true);
1329 let light_substitution = if dark_only {
1330 None
1331 } else {
1332 tokens.substitute(utility, false)
1333 };
1334 let dark_substitution = tokens.substitute(utility, true);
1335 if light_substitution.is_none() && dark_substitution.is_none() {
1336 return None;
1337 }
1338 let parse = |substituted: Option<String>| {
1339 let decls = utilities::parse(theme, &substituted?)?;
1340 (!pseudo.pseudo() || pseudo.pseudo_color(&decls).is_some()).then_some(decls)
1341 };
1342 let rule = |cond: Condition, decls: Vec<Decl>| Rule {
1343 cond,
1344 decls: Rc::from(decls),
1345 rank: rank.clone(),
1346 important,
1347 theme: true,
1348 };
1349 if dark_only {
1351 return Some(match parse(dark_substitution) {
1352 Some(decls) => Token::Themed(rule(cond, decls), None),
1353 None => Token::UnknownThemed,
1354 });
1355 }
1356 let (Some(light), Some(dark)) = (parse(light_substitution), parse(dark_substitution)) else {
1357 return Some(Token::UnknownThemed);
1358 };
1359 if light == dark {
1360 return Some(Token::Themed(rule(cond, light), None));
1361 }
1362 let mut dark_cond = cond.clone();
1363 dark_cond.dark = Some(true);
1364 let mut light_cond = cond;
1365 light_cond.dark = Some(false);
1366 Some(Token::Themed(
1367 rule(light_cond, light),
1368 Some(Box::new(rule(dark_cond, dark))),
1369 ))
1370}
1371
1372fn data_name(name: &str) -> bool {
1376 !name.is_empty()
1377 && name
1378 .bytes()
1379 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1380}
1381
1382fn variant(theme: &Theme, v: &str, cond: &mut Condition) -> Option<Key> {
1384 use state::*;
1385 let states = |cond: &mut Condition, s: u16| {
1386 cond.states |= s;
1387 };
1388 Some(match v {
1391 "selection" => {
1392 cond.selection = true;
1393 rank::SELECTION
1394 }
1395 "placeholder" => {
1396 cond.placeholder = true;
1397 rank::PLACEHOLDER
1398 }
1399 "first" => {
1400 cond.position |= position::FIRST;
1401 rank::FIRST
1402 }
1403 "last" => {
1404 cond.position |= position::LAST;
1405 rank::LAST
1406 }
1407 "only" => {
1408 cond.position |= position::ONLY;
1409 rank::ONLY
1410 }
1411 "odd" => {
1412 cond.position |= position::ODD;
1413 rank::ODD
1414 }
1415 "even" => {
1416 cond.position |= position::EVEN;
1417 rank::EVEN
1418 }
1419 "checked" => {
1420 states(cond, CHECKED);
1421 rank::CHECKED
1422 }
1423 "indeterminate" => {
1424 states(cond, INDETERMINATE);
1425 rank::INDETERMINATE
1426 }
1427 "selected" => {
1428 states(cond, SELECTED);
1429 rank::SELECTED
1430 }
1431 "focus-within" => {
1432 states(cond, FOCUS_WITHIN);
1433 rank::FOCUS_WITHIN
1434 }
1435 "hover" => {
1436 states(cond, HOVERED);
1437 rank::HOVER
1438 }
1439 "focus" => {
1440 states(cond, FOCUSED);
1441 rank::FOCUS
1442 }
1443 "focus-visible" => {
1444 states(cond, FOCUS_VISIBLE);
1445 rank::FOCUS_VISIBLE
1446 }
1447 "active" => {
1448 states(cond, PRESSED);
1449 rank::ACTIVE
1450 }
1451 "enabled" => {
1452 cond.not_states |= DISABLED;
1453 rank::ENABLED
1454 }
1455 "disabled" => {
1456 states(cond, DISABLED);
1457 rank::DISABLED
1458 }
1459 "aria-busy" => {
1460 states(cond, BUSY);
1461 rank::ARIA_BUSY
1462 }
1463 "aria-checked" => {
1464 states(cond, CHECKED);
1465 rank::ARIA_CHECKED
1466 }
1467 "aria-expanded" => {
1468 states(cond, EXPANDED);
1469 rank::EXPANDED
1470 }
1471 "aria-invalid" => {
1472 states(cond, INVALID);
1473 rank::ARIA_INVALID
1474 }
1475 "aria-pressed" => {
1476 states(cond, ARIA_PRESSED);
1477 rank::ARIA_PRESSED
1478 }
1479 "aria-selected" => {
1480 states(cond, SELECTED);
1481 rank::ARIA_SELECTED
1482 }
1483 "motion-safe" => {
1484 cond.reduce_motion = Some(false);
1485 rank::MOTION_SAFE
1486 }
1487 "motion-reduce" => {
1488 cond.reduce_motion = Some(true);
1489 rank::MOTION_REDUCE
1490 }
1491 "portrait" => {
1492 cond.landscape = Some(false);
1493 rank::PORTRAIT
1494 }
1495 "landscape" => {
1496 cond.landscape = Some(true);
1497 rank::LANDSCAPE
1498 }
1499 "ltr" => {
1500 cond.rtl = Some(false);
1501 rank::LTR
1502 }
1503 "rtl" => {
1504 cond.rtl = Some(true);
1505 rank::RTL
1506 }
1507 "dark" => {
1508 cond.dark = Some(true);
1509 rank::DARK
1510 }
1511 "ios" => {
1512 cond.platform = Some(Platform::Ios);
1513 rank::IOS
1514 }
1515 "android" => {
1516 cond.platform = Some(Platform::Android);
1517 rank::ANDROID
1518 }
1519 "web" => {
1520 cond.platform = Some(Platform::Web);
1521 rank::WEB
1522 }
1523 "pointer-coarse" => {
1524 cond.pointer = Some(Pointer::Coarse);
1525 rank::POINTER_COARSE
1526 }
1527 "pointer-fine" => {
1528 cond.pointer = Some(Pointer::Fine);
1529 rank::POINTER_FINE
1530 }
1531 "terminal" => {
1532 cond.terminal = Some(true);
1533 rank::TERMINAL
1534 }
1535 v => {
1536 if let Some(name) = v.strip_prefix("data-").filter(|n| data_name(n)) {
1538 if !cond.data.iter().any(|d| **d == *name) {
1539 cond.data.push(name.into());
1540 }
1541 return Some(Key::data(name));
1542 }
1543 if let Some(rest) = v.strip_prefix("group-") {
1544 let (s, name) = match rest.split_once('/') {
1546 Some((s, n)) => (s, n),
1547 None => (rest, ""),
1548 };
1549 if let Some(data) = s.strip_prefix("data-").filter(|n| data_name(n)) {
1550 let entry = cond.group.get_or_insert_with(|| (name.into(), 0));
1551 if *entry.0 != *name {
1552 return None;
1553 }
1554 if !cond.group_data.iter().any(|d| **d == *data) {
1555 cond.group_data.push(data.into());
1556 }
1557 let mut group = Rank::default();
1558 group.add_group(&Key::data(data), name);
1559 return group.0.pop();
1560 }
1561 let (bit, inner) = match s {
1562 "hover" => (HOVERED, rank::HOVER),
1563 "active" => (PRESSED, rank::ACTIVE),
1564 "focus" => (FOCUSED, rank::FOCUS),
1565 "focus-visible" => (FOCUS_VISIBLE, rank::FOCUS_VISIBLE),
1566 "focus-within" => (FOCUS_WITHIN, rank::FOCUS_WITHIN),
1567 "disabled" => (DISABLED, rank::DISABLED),
1568 "selected" => (SELECTED, rank::SELECTED),
1569 "checked" => (CHECKED, rank::CHECKED),
1570 "indeterminate" => (INDETERMINATE, rank::INDETERMINATE),
1571 "aria-busy" => (BUSY, rank::ARIA_BUSY),
1572 "aria-checked" => (CHECKED, rank::ARIA_CHECKED),
1573 "aria-expanded" => (EXPANDED, rank::EXPANDED),
1574 "aria-invalid" => (INVALID, rank::ARIA_INVALID),
1575 "aria-pressed" => (ARIA_PRESSED, rank::ARIA_PRESSED),
1576 "aria-selected" => (SELECTED, rank::ARIA_SELECTED),
1577 _ => return None,
1578 };
1579 let entry = cond.group.get_or_insert_with(|| (name.into(), 0));
1580 if *entry.0 != *name {
1581 return None;
1582 }
1583 entry.1 |= bit;
1584 let mut group = Rank::default();
1585 group.add_group(&inner, name);
1586 return group.0.pop();
1587 }
1588 let (max, name) = match v.strip_prefix("max-") {
1590 Some(n) => (true, n),
1591 None => (false, v.strip_prefix("min-").unwrap_or(v)),
1592 };
1593 let (width, unit, value) =
1596 match name.strip_prefix('[').and_then(|n| n.strip_suffix(']')) {
1597 Some(arbitrary) => {
1598 let arbitrary = arbitrary.trim();
1599 let digits = arbitrary
1600 .find(|c: char| !(c.is_ascii_digit() || c == '.'))
1601 .unwrap_or(arbitrary.len());
1602 let unit = BREAKPOINT_UNITS
1603 .iter()
1604 .position(|u| *u == &arbitrary[digits..])?;
1605 let value = crate::css::number(&arbitrary[..digits])?;
1606 (crate::css::length(arbitrary)?, unit, value)
1607 }
1608 None => {
1609 let b = theme.breakpoints.iter().find(|b| *b.0 == *name)?;
1610 match b.2 {
1611 true => (b.1, 3, b.1 / theme.rem),
1612 false => (b.1, 2, b.1),
1613 }
1614 }
1615 };
1616 let thousandths = (f64::from(value) * 1000.0).round() as i64;
1617 let key = |order, value| Key {
1618 order,
1619 unit: unit as u8,
1620 value,
1621 name: None,
1622 };
1623 if max {
1624 cond.max_width = Some(cond.max_width.map_or(width, |w| w.min(width)));
1625 key(rank::MAX, -thousandths)
1626 } else {
1627 cond.min_width = Some(cond.min_width.map_or(width, |w| w.max(width)));
1628 key(rank::MIN, thousandths)
1629 }
1630 }
1631 })
1632}
1633
1634#[cfg(test)]
1635mod tests;