Skip to main content

next_rust_view/
css_split.rs

1//! Per-page utility CSS.
2//!
3//! The app-wide Tailwind stylesheet holds every utility the whole app uses.
4//! A page needs only the rules for the classes it renders, so the renderer
5//! splits the stylesheet into pieces once and sends, per document, the
6//! pieces that page needs:
7//!
8//! * everything outside `@layer utilities` (layer order, theme variables,
9//!   the base reset) is always sent, once;
10//! * `@property` registrations, their `@layer properties` fallbacks and
11//!   `@keyframes` are sent once something sent refers to them;
12//! * inside `@layer utilities`, a rule is sent when the class its selector
13//!   starts with is used on the page (Tailwind writes one rule per class,
14//!   possibly grouped in `@media`/`@supports`).
15//!
16//! Each `<style>` gets the id `<sheet id>~<bitset of pieces>`, so the client
17//! runtime can report what it already has and later navigations and
18//! streamed chunks send only what is missing. Utilities depend on their
19//! order (`px-2` must follow `p-4`), so when new rules are sent, already-sent
20//! rules that come after them are sent again to keep the order intact.
21
22use std::collections::{HashMap, HashSet};
23use std::sync::{Mutex, OnceLock};
24
25use crate::style::Stylesheet;
26
27/// One piece of a split stylesheet.
28#[derive(Debug)]
29enum Item {
30    /// Outside the utilities layer: always sent.
31    Text { index: usize, css: String },
32    /// A utility rule, sent when one of `owners` is used (always when empty).
33    /// `props`: the property families it sets (see [`families`]).
34    Rule { index: usize, owners: Vec<String>, css: String, props: Vec<String> },
35    /// `@property --x{…}`, a `--x:…;` fallback or `@keyframes x{…}`: sent
36    /// when a sent piece refers to `name`.
37    Var { index: usize, name: String, css: String },
38    /// `@layer utilities{…}` or an at-rule inside it: written only around
39    /// pieces that are sent.
40    Group { open: String, items: Vec<Item> },
41}
42
43#[derive(Debug)]
44pub(crate) struct Split {
45    items: Vec<Item>,
46    len: usize,
47    /// For each `Var` piece, the pieces that refer to it.
48    refs: Vec<(usize, Vec<usize>)>,
49}
50
51/// Pieces of a split stylesheet, as a bit set.
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub(crate) struct Pieces(Vec<u8>);
54
55impl Pieces {
56    fn with_len(len: usize) -> Self {
57        Pieces(vec![0; len.div_ceil(8)])
58    }
59
60    fn insert(&mut self, i: usize) {
61        if let Some(b) = self.0.get_mut(i / 8) {
62            *b |= 1 << (i % 8);
63        }
64    }
65
66    fn contains(&self, i: usize) -> bool {
67        self.0.get(i / 8).is_some_and(|b| b & (1 << (i % 8)) != 0)
68    }
69
70    fn union(&mut self, other: &Pieces) {
71        for (a, b) in self.0.iter_mut().zip(&other.0) {
72            *a |= b;
73        }
74    }
75
76    fn is_empty(&self) -> bool {
77        self.0.iter().all(|b| *b == 0)
78    }
79
80    fn encode(&self) -> String {
81        const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
82        let mut bytes = self.0.as_slice();
83        while let [rest @ .., 0] = bytes {
84            bytes = rest;
85        }
86        let mut out = String::with_capacity(bytes.len() * 4 / 3 + 2);
87        for chunk in bytes.chunks(3) {
88            let n = chunk.iter().enumerate().fold(0u32, |acc, (i, &b)| acc | (u32::from(b) << (16 - 8 * i)));
89            for i in 0..=chunk.len() {
90                out.push(B64[((n >> (18 - 6 * i)) & 63) as usize] as char);
91            }
92        }
93        out
94    }
95
96    fn decode(s: &str, len: usize) -> Option<Pieces> {
97        let mut bytes = Vec::with_capacity(s.len() * 3 / 4);
98        for chunk in s.as_bytes().chunks(4) {
99            if chunk.len() == 1 {
100                return None;
101            }
102            let mut n = 0u32;
103            for (i, &c) in chunk.iter().enumerate() {
104                let v = match c {
105                    b'A'..=b'Z' => c - b'A',
106                    b'a'..=b'z' => c - b'a' + 26,
107                    b'0'..=b'9' => c - b'0' + 52,
108                    b'-' => 62,
109                    b'_' => 63,
110                    _ => return None,
111                };
112                n |= u32::from(v) << (18 - 6 * i);
113            }
114            for i in 0..chunk.len() - 1 {
115                bytes.push((n >> (16 - 8 * i)) as u8);
116            }
117        }
118        let mut pieces = Pieces::with_len(len);
119        for (a, b) in pieces.0.iter_mut().zip(bytes) {
120            *a = b;
121        }
122        Some(pieces)
123    }
124}
125
126/// Split form of `sheet`, parsed on first use.
127pub(crate) fn split(sheet: &'static Stylesheet) -> &'static Split {
128    let mut cache = SPLITS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
129    // Keyed by address: stylesheets are statics, and ids may repeat in tests.
130    cache
131        .entry(sheet as *const Stylesheet as usize)
132        .or_insert_with(|| (sheet, Box::leak(Box::new(Split::parse(sheet.css)))))
133        .1
134}
135
136type SplitCache = Mutex<HashMap<usize, (&'static Stylesheet, &'static Split)>>;
137
138/// Every per-class stylesheet rendered so far, split.
139static SPLITS: OnceLock<SplitCache> = OnceLock::new();
140
141impl Split {
142    fn parse(css: &str) -> Split {
143        let mut len = 0;
144        let mut items = Vec::new();
145        let mut text = String::new();
146        let mut rest = css;
147        let flush = |text: &mut String, items: &mut Vec<Item>, len: &mut usize| {
148            if !text.is_empty() {
149                items.push(Item::Text { index: *len, css: std::mem::take(text) });
150                *len += 1;
151            }
152        };
153        while !rest.is_empty() {
154            let (prelude, block, after) = next_block(rest);
155            // A leading comment (the license notice) stays as it is.
156            let (comment, prelude) = split_comments(prelude);
157            text.push_str(comment);
158            let head = normalize(prelude);
159            match block {
160                // Tailwind's utilities, and component libraries' rules.
161                Some(body) if head == "@layer utilities" || head == "@layer components" => {
162                    flush(&mut text, &mut items, &mut len);
163                    let inner = parse_utilities(body, &mut len);
164                    items.push(Item::Group { open: format!("{}{{", prelude.trim()), items: inner });
165                }
166                Some(body) if head == "@layer properties" => {
167                    flush(&mut text, &mut items, &mut len);
168                    items.push(Item::Group {
169                        open: format!("{}{{", prelude.trim()),
170                        items: parse_fallbacks(body, &mut len),
171                    });
172                }
173                Some(body) if head.starts_with("@property --") || head.starts_with("@keyframes ") => {
174                    flush(&mut text, &mut items, &mut len);
175                    let name = head.split_once(' ').map(|(_, n)| n.trim().to_owned()).unwrap_or_default();
176                    items.push(Item::Var { index: len, name, css: format!("{}{{{}}}", prelude.trim(), body) });
177                    len += 1;
178                }
179                Some(body) => {
180                    text.push_str(prelude);
181                    text.push('{');
182                    text.push_str(body);
183                    text.push('}');
184                }
185                None => text.push_str(prelude),
186            }
187            rest = after;
188        }
189        flush(&mut text, &mut items, &mut len);
190        let refs = references(&items);
191        Split { items, len, refs }
192    }
193
194    /// The bit set encoded in a known `<style>` id for `sheet`, if it is one.
195    pub(crate) fn known(&self, sheet: &Stylesheet, ids: &HashSet<String>) -> Pieces {
196        let mut known = Pieces::with_len(self.len);
197        let prefix = format!("{}~", sheet.id);
198        for id in ids {
199            if id == sheet.id {
200                // The whole sheet (an older page, or pruning was off).
201                (0..self.len).for_each(|i| known.insert(i));
202            } else if let Some(bits) = id.strip_prefix(&prefix).and_then(|b| Pieces::decode(b, self.len)) {
203                known.union(&bits);
204            }
205        }
206        known
207    }
208
209    /// Pieces needed for `used` classes (all rules when `all`) that are not
210    /// in `sent`, plus sent rules that must be repeated to keep the order.
211    pub(crate) fn delta(&self, used: &dyn Fn(&str) -> bool, all: bool, sent: &Pieces) -> Pieces {
212        let mut wanted = Pieces::with_len(self.len);
213        visit(&self.items, &mut |item| match item {
214            Item::Text { index, .. } => wanted.insert(*index),
215            Item::Rule { index, owners, .. } if all || owners.is_empty() || owners.iter().any(|o| used(o)) => {
216                wanted.insert(*index)
217            }
218            _ => {}
219        });
220        for (var, by) in &self.refs {
221            if all || by.iter().any(|p| wanted.contains(*p) || sent.contains(*p)) {
222                wanted.insert(*var);
223            }
224        }
225        self.missing(&wanted, sent)
226    }
227
228    /// Pieces of `wanted` not in `sent`, plus the sent rules that must be
229    /// repeated after them. Invariant kept for the browser: for any two rules
230    /// it has that set the same property, the last copies are in the
231    /// stylesheet's own order. So a sent rule is repeated only when it
232    /// follows (in stylesheet order) a rule being sent that it could conflict with.
233    fn missing(&self, wanted: &Pieces, sent: &Pieces) -> Pieces {
234        let mut needed = Pieces::with_len(self.len);
235        // Property families of the rules sent in this piece, so far.
236        let mut sending: HashSet<&str> = HashSet::new();
237        visit(&self.items, &mut |item| match item {
238            Item::Text { index, .. } | Item::Var { index, .. } if wanted.contains(*index) && !sent.contains(*index) => {
239                needed.insert(*index)
240            }
241            Item::Rule { index, props, .. } => {
242                let new = wanted.contains(*index) && !sent.contains(*index);
243                let conflicts =
244                    || sending.contains("*") || props.iter().any(|p| p == "*" || sending.contains(p.as_str()));
245                if new || (sent.contains(*index) && !sending.is_empty() && conflicts()) {
246                    needed.insert(*index);
247                    sending.extend(props.iter().map(String::as_str));
248                }
249            }
250            _ => {}
251        });
252        needed
253    }
254
255    /// `<style>` element with the given pieces, or nothing when empty.
256    pub(crate) fn style(&self, sheet: &Stylesheet, pieces: &Pieces) -> String {
257        if pieces.is_empty() {
258            return String::new();
259        }
260        let mut css = String::new();
261        write_items(&self.items, pieces, &mut css);
262        format!(
263            "<style data-nr-css=\"{}~{}\">{}</style>",
264            sheet.id,
265            pieces.encode(),
266            crate::escape::escape_raw_text(&css)
267        )
268    }
269
270    #[cfg(test)]
271    fn empty(&self) -> Pieces {
272        Pieces::with_len(self.len)
273    }
274
275    pub(crate) fn record(&self, sent: &mut Pieces, pieces: &Pieces) {
276        sent.union(pieces);
277    }
278}
279
280/// Rewrite the per-class `<style>` elements of a rendered document (a cached
281/// static page) for a browser that already has the style ids `known`: only
282/// what it is missing is kept.
283/// Every per-class stylesheet rendered so far (component libraries' too) is
284/// considered, besides `sheets`.
285pub fn restyle_document(html: &str, sheets: &[&'static Stylesheet], known: &[&str]) -> String {
286    let known: HashSet<String> = known.iter().map(|s| (*s).to_owned()).collect();
287    let mut all: Vec<&'static Stylesheet> = sheets.iter().map(|s| crate::style::resolve(s)).collect();
288    if let Some(cache) = SPLITS.get() {
289        for (sheet, _) in cache.lock().unwrap_or_else(|e| e.into_inner()).values() {
290            if !all.iter().any(|s| std::ptr::eq(*s, *sheet)) {
291                all.push(sheet);
292            }
293        }
294    }
295    let mut out = html.to_owned();
296    for sheet in all.into_iter().filter(|s| s.per_class.is_some()) {
297        let open = format!("<style data-nr-css=\"{}~", sheet.id);
298        let Some(at) = out.find(&open) else { continue };
299        let bits_start = at + open.len();
300        let Some(bits_len) = out[bits_start..].find('"') else { continue };
301        let Some(close) = out[at..].find("</style>").map(|c| at + c + "</style>".len()) else { continue };
302        let split = split(sheet);
303        let Some(page) = Pieces::decode(&out[bits_start..bits_start + bits_len], split.len) else { continue };
304        let sent = split.known(sheet, &known);
305        let style = split.style(sheet, &split.missing(&page, &sent));
306        out.replace_range(at..close, &style);
307    }
308    out
309}
310
311fn visit<'a>(items: &'a [Item], f: &mut dyn FnMut(&'a Item)) {
312    for item in items {
313        match item {
314            Item::Group { items, .. } => visit(items, f),
315            other => f(other),
316        }
317    }
318}
319
320/// Write the selected pieces; returns whether anything was written.
321fn write_items(items: &[Item], pieces: &Pieces, out: &mut String) -> bool {
322    let start = out.len();
323    for item in items {
324        match item {
325            Item::Text { index, css } | Item::Rule { index, css, .. } | Item::Var { index, css, .. } => {
326                if pieces.contains(*index) {
327                    out.push_str(css);
328                }
329            }
330            Item::Group { open, items } => {
331                let at = out.len();
332                out.push_str(open);
333                if write_items(items, pieces, out) {
334                    out.push('}');
335                } else {
336                    out.truncate(at);
337                }
338            }
339        }
340    }
341    out.len() > start
342}
343
344/// `@layer properties{@supports …{*,…{--tw-x:initial;…}}}`: each custom
345/// property fallback becomes a `Var` piece.
346fn parse_fallbacks(css: &str, len: &mut usize) -> Vec<Item> {
347    let mut items = Vec::new();
348    let mut rest = css;
349    while !rest.trim().is_empty() {
350        let (prelude, block, after) = next_block(rest);
351        match block {
352            Some(body) => {
353                items.push(Item::Group { open: format!("{}{{", prelude.trim()), items: parse_fallbacks(body, len) })
354            }
355            None => {
356                let decl = prelude.trim().trim_end_matches(';');
357                let name = decl.split_once(':').map(|(n, _)| n.trim()).filter(|n| n.starts_with("--"));
358                let css = format!("{decl};");
359                items.push(match name {
360                    Some(name) => Item::Var { index: *len, name: name.to_owned(), css },
361                    None => Item::Text { index: *len, css },
362                });
363                *len += 1;
364            }
365        }
366        rest = after;
367    }
368    items
369}
370
371/// For each `Var`, the other pieces whose CSS mentions its name.
372fn references(items: &[Item]) -> Vec<(usize, Vec<usize>)> {
373    let mut vars = Vec::new();
374    let mut others = Vec::new();
375    visit(items, &mut |item| match item {
376        Item::Var { index, name, .. } => vars.push((*index, name.as_str())),
377        Item::Text { index, css } | Item::Rule { index, css, .. } => others.push((*index, css.as_str())),
378        Item::Group { .. } => {}
379    });
380    vars.into_iter()
381        .map(|(var, name)| (var, others.iter().filter(|(_, css)| mentions(css, name)).map(|(i, _)| *i).collect()))
382        .collect()
383}
384
385/// Whether `css` contains `name` as a whole identifier.
386fn mentions(css: &str, name: &str) -> bool {
387    let ident = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '-' || c == '_');
388    css.match_indices(name)
389        .any(|(at, _)| !ident(css[..at].chars().next_back()) && !ident(css[at + name.len()..].chars().next()))
390}
391
392/// Leading `/* … */` comments of a prelude, and the rest.
393fn split_comments(prelude: &str) -> (&str, &str) {
394    let mut end = 0;
395    loop {
396        let rest = &prelude[end..];
397        let trimmed = rest.trim_start();
398        match trimmed.strip_prefix("/*").and_then(|c| c.find("*/")) {
399            Some(close) => end += rest.len() - trimmed.len() + 2 + close + 2,
400            None => return prelude.split_at(end),
401        }
402    }
403}
404
405fn parse_utilities(css: &str, len: &mut usize) -> Vec<Item> {
406    let mut items = Vec::new();
407    let mut rest = css;
408    while !rest.trim().is_empty() {
409        let (prelude, block, after) = next_block(rest);
410        let head = prelude.trim_start();
411        match block {
412            Some(body) if head.starts_with('@') && !head.starts_with("@font-face") => {
413                items.push(Item::Group { open: format!("{}{{", prelude.trim()), items: parse_utilities(body, len) });
414            }
415            Some(body) => {
416                items.push(Item::Rule {
417                    index: *len,
418                    owners: owner_classes(head),
419                    css: format!("{}{{{}}}", prelude.trim(), body),
420                    props: families(body),
421                });
422                *len += 1;
423            }
424            None => {
425                // A statement such as `@apply …;`: keep it.
426                items.push(Item::Rule {
427                    index: *len,
428                    owners: Vec::new(),
429                    css: prelude.trim().to_owned(),
430                    props: vec!["*".into()],
431                });
432                *len += 1;
433            }
434        }
435        rest = after;
436    }
437    items
438}
439
440/// Split off the next `prelude{body}` (or `statement;`) from `css`.
441/// Returns (prelude, body, rest). Escapes and strings are respected.
442fn next_block(css: &str) -> (&str, Option<&str>, &str) {
443    let bytes = css.as_bytes();
444    let mut i = 0;
445    let mut quote = None;
446    let mut open = None;
447    let mut depth = 0usize;
448    while i < bytes.len() {
449        let b = bytes[i];
450        match (quote, b) {
451            (_, b'\\') => i += 1,
452            (None, b'/') if bytes.get(i + 1) == Some(&b'*') => {
453                i += css[i + 2..].find("*/").map_or(bytes.len(), |end| end + 3);
454                continue;
455            }
456            (Some(q), _) if b == q => quote = None,
457            (Some(_), _) => {}
458            (None, b'"' | b'\'') => quote = Some(b),
459            (None, b'{') => {
460                if depth == 0 {
461                    open = Some(i);
462                }
463                depth += 1;
464            }
465            (None, b'}') => {
466                depth = depth.saturating_sub(1);
467                if depth == 0
468                    && let Some(o) = open
469                {
470                    return (&css[..o], Some(&css[o + 1..i]), &css[i + 1..]);
471                }
472            }
473            (None, b';') if depth == 0 => return (&css[..=i], None, &css[i + 1..]),
474            _ => {}
475        }
476        i += 1;
477    }
478    (css, None, "")
479}
480
481/// Owners of a selector list: the first class of each selector. Empty (the
482/// rule is always needed) when one of them has no class.
483fn owner_classes(selectors: &str) -> Vec<String> {
484    let mut parts = Vec::new();
485    let (mut depth, mut start) = (0i32, 0);
486    let mut chars = selectors.char_indices();
487    while let Some((i, c)) = chars.next() {
488        match c {
489            '\\' => {
490                chars.next();
491            }
492            '(' | '[' => depth += 1,
493            ')' | ']' => depth -= 1,
494            ',' if depth == 0 => {
495                parts.push(&selectors[start..i]);
496                start = i + 1;
497            }
498            _ => {}
499        }
500    }
501    parts.push(&selectors[start..]);
502    parts.into_iter().map(owner_class).collect::<Option<Vec<_>>>().unwrap_or_default()
503}
504
505/// The class a utility selector starts with, unescaped (`.sm\:p-4:hover` → `sm:p-4`).
506fn owner_class(selector: &str) -> Option<String> {
507    let bytes = selector.as_bytes();
508    let dot = (0..bytes.len()).find(|&i| bytes[i] == b'.' && (i == 0 || bytes[i - 1] != b'\\'))?;
509    let mut name = String::new();
510    let mut chars = selector[dot + 1..].chars();
511    while let Some(c) = chars.next() {
512        match c {
513            '\\' => name.push(chars.next()?),
514            c if c.is_alphanumeric() || c == '-' || c == '_' || !c.is_ascii() => name.push(c),
515            _ => break,
516        }
517    }
518    (!name.is_empty()).then_some(name)
519}
520
521/// Property families a rule body sets, for deciding which rules can
522/// override each other: `padding-inline` → `padding`, `-webkit-mask` →
523/// `mask`; custom properties by full name. `*` when nothing was recognized.
524fn families(body: &str) -> Vec<String> {
525    let mut out: Vec<String> = Vec::new();
526    let mut rest = body;
527    while !rest.trim().is_empty() {
528        let (prelude, block, after) = next_block(rest);
529        match block {
530            // A nested rule or at-rule: its declarations count too.
531            Some(inner) => {
532                for f in families(inner) {
533                    if !out.contains(&f) {
534                        out.push(f);
535                    }
536                }
537            }
538            None => {
539                for decl in prelude.split(';') {
540                    let Some((name, _)) = decl.split_once(':') else { continue };
541                    let name = name.trim().to_ascii_lowercase();
542                    let family = if name.starts_with("--") {
543                        name
544                    } else {
545                        let bare =
546                            ["-webkit-", "-moz-", "-ms-"].iter().find_map(|v| name.strip_prefix(v)).unwrap_or(&name);
547                        match bare {
548                            // Shorthands whose longhands are named differently.
549                            "all" => "*".to_owned(),
550                            "row-gap" | "column-gap" => "gap".to_owned(),
551                            "column-count" | "column-width" => "columns".to_owned(),
552                            _ => match bare.split('-').next().unwrap_or(bare) {
553                                "top" | "right" | "bottom" | "left" => "inset".to_owned(),
554                                "align" | "justify" => "place".to_owned(),
555                                first => first.to_owned(),
556                            },
557                        }
558                    };
559                    if !family.is_empty() && !out.contains(&family) {
560                        out.push(family);
561                    }
562                }
563            }
564        }
565        rest = after;
566    }
567    if out.is_empty() {
568        out.push("*".into());
569    }
570    out
571}
572
573fn normalize(prelude: &str) -> String {
574    prelude.split_whitespace().collect::<Vec<_>>().join(" ")
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    const CSS: &str = "@layer theme,base,components,utilities;@layer theme{:root{--c:red}}@layer base{*{margin:0}}\
582@layer utilities{.p-4{padding:1rem}.px-2{padding-inline:.5rem}.hover\\:underline{&:hover{@media (hover:hover){text-decoration:underline}}}\
583@media (width>=40rem){.sm\\:p-10{padding:2.5rem}.sm\\:w-\\[1\\.5rem\\]{width:1.5rem}}\
584:where(.space-y-2>:not(:last-child)){margin-block:.5rem}}@property --tw-x{syntax:\"*\";inherits:false}@keyframes spin{to{rotate:1turn}}";
585
586    static SHEET: Stylesheet = Stylesheet { id: "tw", css: CSS, per_class: Some(&[]) };
587
588    fn css_of(style: &str) -> &str {
589        &style[style.find('>').unwrap() + 1..style.rfind("</style>").unwrap()]
590    }
591
592    #[test]
593    fn owners() {
594        assert_eq!(owner_class(".p-4").as_deref(), Some("p-4"));
595        assert_eq!(owner_class(".sm\\:w-\\[1\\.5rem\\]").as_deref(), Some("sm:w-[1.5rem]"));
596        assert_eq!(owner_class(":where(.space-y-2>:not(:last-child))").as_deref(), Some("space-y-2"));
597        assert_eq!(owner_class(".dark\\:x:where(.dark,.dark *)").as_deref(), Some("dark:x"));
598        assert_eq!(owner_class("input"), None);
599        assert_eq!(owner_classes(".a:hover,.b\\,c:where(.x,.y)"), ["a", "b,c"]);
600        assert!(owner_classes(".a,input").is_empty(), "a part without a class: always needed");
601    }
602
603    #[test]
604    fn sends_only_used_rules_and_everything_outside_utilities() {
605        let split = Split::parse(CSS);
606        let used = |c: &str| ["px-2", "sm:p-10"].contains(&c);
607        let pieces = split.delta(&used, false, &split.empty());
608        let css = split.style(&SHEET, &pieces);
609        assert_eq!(
610            css_of(&css),
611            "@layer theme,base,components,utilities;@layer theme{:root{--c:red}}@layer base{*{margin:0}}\
612@layer utilities{.px-2{padding-inline:.5rem}@media (width>=40rem){.sm\\:p-10{padding:2.5rem}}}",
613            "`@property` and `@keyframes` nothing refers to are left out"
614        );
615        // All pieces: the original stylesheet, byte for byte.
616        let all = split.delta(&|_| false, true, &split.empty());
617        assert_eq!(css_of(&split.style(&SHEET, &all)), CSS);
618    }
619
620    #[test]
621    fn property_families() {
622        assert_eq!(families("padding-inline:.5rem"), ["padding"]);
623        assert_eq!(families("--tw-shadow:0 0;box-shadow:var(--tw-shadow)"), ["--tw-shadow", "box"]);
624        assert_eq!(families("&:hover{@media (hover:hover){-webkit-text-decoration:underline}}"), ["text"]);
625        assert_eq!(families(""), ["*"]);
626        assert_eq!(families("top:0;align-items:center;row-gap:1rem"), ["inset", "place", "gap"]);
627    }
628
629    #[test]
630    fn unrelated_rules_are_not_repeated() {
631        // `.p-4` is new; `.px-2` (same family) is repeated, `.mt-2` isn't.
632        let css = "@layer utilities{.p-4{padding:1rem}.mt-2{margin-top:.5rem}.px-2{padding-inline:.5rem}}";
633        let split = Split::parse(css);
634        let mut sent = split.empty();
635        let first = split.delta(&|c| c == "px-2" || c == "mt-2", false, &sent);
636        split.record(&mut sent, &first);
637        let next = split.delta(&|c| c == "p-4", false, &sent);
638        assert_eq!(
639            css_of(&split.style(&SHEET, &next)),
640            "@layer utilities{.p-4{padding:1rem}.px-2{padding-inline:.5rem}}"
641        );
642    }
643
644    #[test]
645    fn registrations_follow_the_rules_that_use_them() {
646        let css = "/*! notice */@layer properties{@supports (x:y){*,:before{--tw-a:initial;--tw-b:0}}}\
647@layer utilities{.a{--tw-a:1px;width:var(--tw-a)}.b{height:var(--tw-b)}.c{color:red}}\
648@property --tw-a{syntax:\"*\";inherits:false}@property --tw-b{syntax:\"*\";inherits:false}@keyframes spin{to{rotate:1turn}}";
649        let split = Split::parse(css);
650        let mut sent = split.empty();
651        let first = split.delta(&|c| c == "a" || c == "c", false, &sent);
652        assert_eq!(
653            css_of(&split.style(&SHEET, &first)),
654            "/*! notice */@layer properties{@supports (x:y){*,:before{--tw-a:initial;}}}\
655@layer utilities{.a{--tw-a:1px;width:var(--tw-a)}.c{color:red}}@property --tw-a{syntax:\"*\";inherits:false}"
656        );
657        split.record(&mut sent, &first);
658        let next = split.delta(&|c| c == "b", false, &sent);
659        assert_eq!(
660            css_of(&split.style(&SHEET, &next)),
661            "@layer properties{@supports (x:y){*,:before{--tw-b:0;}}}@layer utilities{.b{height:var(--tw-b)}}\
662@property --tw-b{syntax:\"*\";inherits:false}"
663        );
664        assert!(mentions("a{animation:spin 1s}", "spin") && !mentions("a{animation:spinner}", "spin"));
665    }
666
667    #[test]
668    fn later_chunks_send_what_is_missing_in_order() {
669        let split = Split::parse(CSS);
670        let mut sent = split.empty();
671        let first = split.delta(&|c| c == "px-2", false, &sent);
672        split.record(&mut sent, &first);
673        // `p-4` comes before `px-2`: `px-2` is repeated after it so it still wins.
674        let next = split.delta(&|c| c == "p-4" || c == "px-2", false, &sent);
675        assert_eq!(
676            css_of(&split.style(&SHEET, &next)),
677            "@layer utilities{.p-4{padding:1rem}.px-2{padding-inline:.5rem}}"
678        );
679        split.record(&mut sent, &next);
680        assert!(split.delta(&|c| c == "p-4", false, &sent).is_empty(), "nothing new");
681    }
682
683    #[test]
684    fn cached_documents_are_restyled_for_the_browser() {
685        let split = Split::parse(CSS);
686        let page = split.delta(&|c| c == "p-4" || c == "px-2", false, &split.empty());
687        let html = format!("<head>{}</head>", split.style(&SHEET, &page));
688        let had = split.delta(&|c| c == "px-2", false, &split.empty());
689        let had_id = split.style(&SHEET, &had).split('"').nth(1).unwrap().to_owned();
690        let out = restyle_document(&html, &[&SHEET], &[&had_id]);
691        assert_eq!(
692            css_of(&out.replace("<head>", "").replace("</head>", "")),
693            "@layer utilities{.p-4{padding:1rem}.px-2{padding-inline:.5rem}}"
694        );
695        let all_id = split.style(&SHEET, &page).split('"').nth(1).unwrap().to_owned();
696        assert_eq!(restyle_document(&html, &[&SHEET], &[&all_id]), "<head></head>", "nothing missing");
697    }
698
699    #[test]
700    fn ids_round_trip_through_the_client() {
701        let split = Split::parse(CSS);
702        let pieces = split.delta(&|c| c == "sm:w-[1.5rem]" || c == "hover:underline", false, &split.empty());
703        let style = split.style(&SHEET, &pieces);
704        let id = style.split('"').nth(1).unwrap().to_owned();
705        let known = split.known(&SHEET, &HashSet::from([id]));
706        assert_eq!(known, pieces);
707        let whole = split.known(&SHEET, &HashSet::from(["tw".to_owned()]));
708        assert!((0..split.len).all(|i| whole.contains(i)), "the whole sheet");
709        assert_eq!(split.known(&SHEET, &HashSet::from(["tw~!!".to_owned()])), split.empty(), "garbage ignored");
710    }
711}