Skip to main content

next_rust_view/
css_split.rs

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