Skip to main content

max / makeover-webview

42.1 KB · 1080 lines History Blame Raw
1 //! Every class this crate is responsible for, as a set rather than one name at
2 //! a time.
3 //!
4 //! The naming functions ([`crate::class`], [`crate::option_class`],
5 //! [`crate::list::part_class`], [`crate::list::cell_part_class`]) answer "what
6 //! is this one thing called". That is half the agreement. The other half is
7 //! the set: a checker cannot ask "is this app rule
8 //! re-specifying something makeover already defines" without the list, and this
9 //! crate is the only place that knows it, because this crate writes the sheet.
10 //!
11 //! # Two sets, because there are two questions
12 //!
13 //! [`vocabulary`] is the classes the generated stylesheet writes a rule for.
14 //! That is the set a drift check wants: an app rule for one of these is a
15 //! restatement of a rule the app already gets, and unlayered app CSS beats
16 //! `@layer makeover`, so the restatement silently wins.
17 //!
18 //! [`names`] is every class this crate can put in markup, which is the first
19 //! set plus the ones it deliberately leaves unruled. `row-actions`,
20 //! `cell-actions`, `cell-tokens` and `cell-link` have no rule on purpose: only
21 //! `.cell-value` takes a colour, because a token carries its own tone and an
22 //! action is a control rather than text. A class that sets no properties is a
23 //! class that means "I thought about this", and this crate does not emit those.
24 //! So a screen renderer legitimately emits names that [`vocabulary`] does not
25 //! contain, and a test asking "is every class this renderer emits one makeover
26 //! knows about" has to read [`names`] or it fails on four correct ones.
27 //!
28 //! # Why the first set is scraped and not listed
29 //!
30 //! A hand-maintained copy of the sheet's contents is the defect being fixed,
31 //! one level up: it can disagree with the sheet, and the day it does, the
32 //! checker reads the list and the browser reads the sheet. So [`vocabulary`]
33 //! parses the CSS this crate generates. There is no second source to drift
34 //! from, and a class added to an emitter enters the vocabulary in the same
35 //! commit that adds it.
36
37 use crate::facet::FACET_CLASSES;
38 use crate::figure::FIGURE_CLASSES;
39 use crate::form::{FIELD_CLASSES, FIELD_STATE_CLASSES};
40 use crate::list::{
41 CELL_DROP_CLASSES, CELL_PART_CLASSES, CELL_WIDTH_CLASSES, FLOW_CLASSES, NESTING_CLASSES,
42 ROW_PART_CLASSES,
43 };
44 use crate::meter::METER_CLASSES;
45 use crate::placeholder::PLACEHOLDER_CLASSES;
46 use crate::{Emit, option_class};
47 use makeover_layout::Selector;
48 use std::collections::{BTreeMap, BTreeSet};
49
50 /// Every class name the generated stylesheet defines a rule for, prefixed the
51 /// way `opts` prefixes them.
52 ///
53 /// Includes the state classes a caller never spells alone (`chosen`,
54 /// `latched`). Those are deliberately unprefixed: they qualify a prefixed
55 /// component (`.mo-tab.chosen`) rather than standing on their own, so a prefix
56 /// moves the thing and not its state.
57 #[must_use]
58 pub fn vocabulary(opts: &Emit) -> BTreeSet<String> {
59 classes_in_css(&crate::stylesheet(opts))
60 }
61
62 /// Every class this crate can put in markup or in a rule.
63 ///
64 /// [`vocabulary`] plus every class an emitter here writes without the sheet
65 /// ruling it. This is the set to check a renderer's emitted markup against: a
66 /// class outside it is a name that renderer invented, which is how
67 /// quasi-webview came to spell `tabs`, `segmented` and `option` and render
68 /// every described selector flat.
69 ///
70 /// # The unruled half is written down, module by module
71 ///
72 /// One list per module that emits markup, each beside its emitters, and this
73 /// is their union. Keeping the omissions beside the emitters is what stops the
74 /// set drifting from what actually comes out in a document. A name this
75 /// function omits is a name an app reads as dead and deletes live rules for.
76 ///
77 /// [`crate::corpus`] is what keeps the union honest, and it renders rather than
78 /// reading the source: a width class, a drop class and a state appended to an
79 /// open attribute are literals nowhere, which is what a reading of the
80 /// emitters missed for eleven of the fifteen.
81 #[must_use]
82 pub fn names(opts: &Emit) -> BTreeSet<String> {
83 let mut all = vocabulary(opts);
84 all.extend(
85 ROW_PART_CLASSES
86 .iter()
87 .chain(CELL_PART_CLASSES)
88 .chain(CELL_WIDTH_CLASSES)
89 .chain(CELL_DROP_CLASSES)
90 .chain(FLOW_CLASSES)
91 .chain(NESTING_CLASSES)
92 .chain(crate::RUN_CLASSES)
93 .chain(FACET_CLASSES)
94 .chain(FIELD_CLASSES)
95 .chain(FIGURE_CLASSES)
96 .chain(METER_CLASSES)
97 .chain(PLACEHOLDER_CLASSES)
98 .map(|name| crate::class(name, opts)),
99 );
100 all.extend(
101 [Selector::Tabs, Selector::Segmented, Selector::Toggle]
102 .into_iter()
103 .map(|s| crate::class(option_class(s), opts)),
104 );
105 // Unprefixed, deliberately, exactly as the `chosen` and `latched` the
106 // scraped half brings in: a state qualifies a prefixed component rather
107 // than standing on its own.
108 all.extend(FIELD_STATE_CLASSES.iter().map(|name| (*name).to_owned()));
109 all
110 }
111
112 /// Which properties a stylesheet sets on each class it names.
113 ///
114 /// The grain a drift check actually wants. A class name in common is not by
115 /// itself a divergence: goingson's `.badge` sets shape and the generated
116 /// `.badge` sets fill and edge, and the app's own comment says "do not add
117 /// background, border or box-shadow here". That arrangement is settled and
118 /// correct, so a check that flagged the shared name would demand deleting it.
119 /// A shared *property* is the thing that goes wrong, because app CSS is
120 /// unlayered and takes the property from the design system silently.
121 ///
122 /// A property appearing under more than one selector arm collapses into one
123 /// entry. That loses a real distinction -- the sort caret's reserved gap is
124 /// `content` on the unsorted arm and the generated caret is `content` on the
125 /// sorted one, which is a deliberate pairing rather than a clash -- so a
126 /// consumer of this needs a way to say a pair was reviewed. Deciding that here
127 /// would need a selector matcher, and a check that guesses wrong about
128 /// specificity fails correct builds.
129 ///
130 /// A declaration whose value is exactly `revert-layer` is not one of them. It
131 /// takes nothing by construction: it is a later layer handing the property back
132 /// to the one below, which is the opposite of the thing this reader is looking
133 /// for. Counting it made every handoff in a consumer's sheet look like an
134 /// override, and the allowlist entry written to silence one went on permitting
135 /// a real override on the same pair afterwards. [`deferrals_by_class`] is where
136 /// those declarations go instead.
137 #[must_use]
138 pub fn declarations_by_class(css: &str) -> BTreeMap<String, BTreeSet<String>> {
139 by_class(css, |value| !is_handoff(value))
140 }
141
142 /// Which properties a stylesheet hands back to the layer below, per class.
143 ///
144 /// The other half of [`declarations_by_class`]. A `revert-layer` says "whatever
145 /// the design system set here, keep it", so a checker reading a consumer's
146 /// sheet wants it as evidence that a clash was already remedied rather than as
147 /// a clash of its own.
148 #[must_use]
149 pub fn deferrals_by_class(css: &str) -> BTreeMap<String, BTreeSet<String>> {
150 by_class(css, is_handoff)
151 }
152
153 /// [`declarations_by_class`] and [`deferrals_by_class`], which differ only in
154 /// which declarations they keep.
155 fn by_class(css: &str, keep: impl Fn(&str) -> bool) -> BTreeMap<String, BTreeSet<String>> {
156 let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
157 for (selector, body) in rules(css) {
158 let classes = classes_in_selector(&selector);
159 if classes.is_empty() {
160 continue;
161 }
162 let properties = properties_in_body(&body, &keep);
163 if properties.is_empty() {
164 continue;
165 }
166 for class in classes {
167 out.entry(class).or_default().extend(properties.clone());
168 }
169 }
170 out
171 }
172
173 /// Which properties a stylesheet sets on each bare element it names.
174 ///
175 /// The blind spot [`declarations_by_class`] has by construction: it keys rules
176 /// by the classes in their selectors, so a rule carrying no class at all is
177 /// invisible to it. `button { color: var(--content) }` is exactly that, and it
178 /// sets the same property the generated `.button` does on every described act
179 /// in the app -- including the tone of a destructive one, so a delete comes to
180 /// look like an ordinary button with the check reporting nothing.
181 ///
182 /// Only a selector arm that is one bare compound counts: `button`,
183 /// `button:hover`, `input[type="text"]`. A scoped arm (`.page button`) reaches
184 /// the elements inside one region rather than every one of them, so whether it
185 /// lands on a described act depends on where that act is rendered, and a check
186 /// that guessed would fail correct builds. The certain case is the one this
187 /// reads.
188 ///
189 /// Pair the result against [`classes_for_element`] to ask the question a
190 /// checker wants: does this element rule take a property the design system sets
191 /// on a class that element can carry.
192 ///
193 /// The answer carries the strongest arm each property was set on, because the
194 /// app's own remedy has to outrank the rule it remedies. `.field` does not beat
195 /// `input[type="text"]`: both are the app's, both are in the same layer, and
196 /// the attribute makes the element rule the more specific of the two. A check
197 /// reading only "the app mentions this pair somewhere" waves that straight
198 /// through, which is the shape of every handoff that looked written and was
199 /// not.
200 #[must_use]
201 pub fn declarations_by_element(css: &str) -> BTreeMap<String, BTreeMap<String, Specificity>> {
202 let mut out: BTreeMap<String, BTreeMap<String, Specificity>> = BTreeMap::new();
203 for (selector, body) in rules(css) {
204 let properties = properties_in_body(&body, |value| !is_handoff(value));
205 if properties.is_empty() {
206 continue;
207 }
208 for arm in selector.split(',') {
209 let Some(element) = bare_element(arm) else {
210 continue;
211 };
212 let rank = specificity(arm);
213 let entry = out.entry(element).or_default();
214 for property in &properties {
215 let strongest = entry.entry(property.clone()).or_default();
216 *strongest = (*strongest).max(rank);
217 }
218 }
219 }
220 out
221 }
222
223 /// What a stylesheet says about each class, and how strongly.
224 ///
225 /// Every property the sheet names on a class, whether it takes it or hands it
226 /// back, keyed by the strongest arm that names it. The question it answers is
227 /// not "does this collide" -- [`declarations_by_class`] is that -- but "has the
228 /// app spoken for this pair, in a rule that wins where it has to".
229 #[must_use]
230 pub fn mentions_by_class(css: &str) -> BTreeMap<String, BTreeMap<String, Specificity>> {
231 let mut out: BTreeMap<String, BTreeMap<String, Specificity>> = BTreeMap::new();
232 for (selector, body) in rules(css) {
233 let properties = properties_in_body(&body, |_| true);
234 if properties.is_empty() {
235 continue;
236 }
237 for arm in selector.split(',') {
238 let classes = classes_in_selector(arm);
239 if classes.is_empty() {
240 continue;
241 }
242 let rank = specificity(arm);
243 for class in classes {
244 let entry = out.entry(class).or_default();
245 for property in &properties {
246 let strongest = entry.entry(property.clone()).or_default();
247 *strongest = (*strongest).max(rank);
248 }
249 }
250 }
251 }
252 out
253 }
254
255 /// How CSS ranks one selector: ids, then classes, then elements.
256 ///
257 /// Ordered the way the cascade orders it, so the tuple comparison is the
258 /// cascade's comparison. It settles a contest between two rules in the same
259 /// layer, which is the only contest it is used for here: a layer beats
260 /// specificity outright, so nothing in the app's sheet has to be compared
261 /// against the generated one this way.
262 pub type Specificity = (usize, usize, usize);
263
264 /// The specificity of one selector arm.
265 ///
266 /// A functional pseudo-class counts as one class and its argument is not read.
267 /// CSS says `:not(.a.b)` takes the specificity of its strongest argument, so
268 /// this undercounts a compound inside one -- which puts the error on the side
269 /// of reporting a remedy as too weak rather than accepting one that is.
270 #[must_use]
271 pub fn specificity(selector: &str) -> Specificity {
272 let chars: Vec<char> = selector.chars().collect();
273 let (mut ids, mut classes, mut elements) = (0, 0, 0);
274 let mut i = 0;
275 while i < chars.len() {
276 match chars[i] {
277 '#' => {
278 ids += 1;
279 i = skip_name(&chars, i + 1);
280 }
281 '.' => {
282 classes += 1;
283 i = skip_name(&chars, i + 1);
284 }
285 ':' => {
286 // `::before` is an element, `:hover` is a class.
287 if chars.get(i + 1) == Some(&':') {
288 elements += 1;
289 i = skip_name(&chars, i + 2);
290 } else {
291 classes += 1;
292 i = skip_name(&chars, i + 1);
293 }
294 if chars.get(i) == Some(&'(') {
295 i = skip_group(&chars, i);
296 }
297 }
298 '[' => {
299 classes += 1;
300 i = skip_group(&chars, i);
301 }
302 c if c.is_ascii_alphabetic() => {
303 elements += 1;
304 i = skip_name(&chars, i);
305 }
306 // A combinator, whitespace, or the universal selector, none of
307 // which count for anything.
308 _ => i += 1,
309 }
310 }
311 (ids, classes, elements)
312 }
313
314 /// Past the identifier starting at `from`.
315 fn skip_name(chars: &[char], from: usize) -> usize {
316 let mut i = from;
317 while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '-' || chars[i] == '_') {
318 i += 1;
319 }
320 i
321 }
322
323 /// Past the bracketed or parenthesised group opening at `from`, nesting and
324 /// all.
325 fn skip_group(chars: &[char], from: usize) -> usize {
326 let mut depth = 0usize;
327 let mut i = from;
328 while i < chars.len() {
329 match chars[i] {
330 '[' | '(' => depth += 1,
331 ']' | ')' => {
332 depth -= 1;
333 if depth == 0 {
334 return i + 1;
335 }
336 }
337 _ => {}
338 }
339 i += 1;
340 }
341 i
342 }
343
344 /// A value that hands the property back rather than taking it.
345 ///
346 /// Bare only. `revert-layer !important` in a later layer inverts layer order
347 /// and takes the property from every layer below, which is the opposite
348 /// declaration wearing the same word.
349 fn is_handoff(value: &str) -> bool {
350 value.trim() == "revert-layer"
351 }
352
353 /// The property names a declaration block sets, keeping the ones `keep` admits.
354 fn properties_in_body(body: &str, keep: impl Fn(&str) -> bool) -> BTreeSet<String> {
355 body.split(';')
356 .filter_map(|decl| decl.split_once(':'))
357 .filter(|(_, value)| keep(value))
358 .map(|(name, _)| name.trim().to_string())
359 .filter(|name| !name.is_empty() && !name.contains(['{', '}']))
360 .collect()
361 }
362
363 #[must_use]
364 pub fn classes_in_css(css: &str) -> BTreeSet<String> {
365 rules(css)
366 .into_iter()
367 .flat_map(|(selector, _)| classes_in_selector(&selector))
368 .collect()
369 }
370
371 /// `(selector, declaration block)` for every rule in a stylesheet.
372 ///
373 /// One reader for both sides. Comparing what makeover defines against what an
374 /// app defines is only meaningful if the two were read the same way, which is
375 /// why this is the only place either question is answered from.
376 ///
377 /// A comment is skipped whole: the banner at the top of the generated sheet is
378 /// prose about the cascade layer and would otherwise contribute words that look
379 /// like selectors. A string is opaque, because `content: "\25B2"` is the sort
380 /// caret rather than a selector and a brace inside one would desync the stack.
381 /// An at-rule block (`@layer`, `@media`, `@supports`) holds rules rather than
382 /// declarations, so a depth counter alone is not enough and the stack records
383 /// what kind of block each brace opened.
384 fn rules(css: &str) -> Vec<(String, String)> {
385 let mut out = Vec::new();
386 // One entry per open brace: true when that block holds declarations rather
387 // than nested rules.
388 let mut blocks: Vec<bool> = Vec::new();
389 // Text since the last `{`, `}` or `;`. What precedes a `{` is that block's
390 // prelude, and a prelude starting with `@` opens an at-rule.
391 let mut prelude = String::new();
392 // The selector of each open declaration block, and the body so far.
393 let mut open: Vec<(String, String)> = Vec::new();
394
395 let mut chars = css.chars().peekable();
396 while let Some(c) = chars.next() {
397 match c {
398 '/' if chars.peek() == Some(&'*') => {
399 chars.next();
400 let mut star = false;
401 for c in chars.by_ref() {
402 if star && c == '/' {
403 break;
404 }
405 star = c == '*';
406 }
407 prelude.clear();
408 }
409 '"' | '\'' => {
410 let quote = c;
411 let mut escaped = false;
412 // Keep the quotes in the body: a value is not a property name,
413 // and dropping them would join two declarations into one.
414 if blocks.last().copied().unwrap_or(false)
415 && let Some((_, body)) = open.last_mut()
416 {
417 body.push(quote);
418 }
419 for c in chars.by_ref() {
420 if escaped {
421 escaped = false;
422 } else if c == '\\' {
423 escaped = true;
424 } else if c == quote {
425 break;
426 }
427 }
428 // The closing quote only. A value holding `;` or `:` would
429 // otherwise read as two declarations, and `url("a;b:c")` is a
430 // real thing an app writes.
431 if blocks.last().copied().unwrap_or(false)
432 && let Some((_, body)) = open.last_mut()
433 {
434 body.push(quote);
435 }
436 }
437 '{' => {
438 let declarations = !prelude.trim_start().starts_with('@');
439 if declarations {
440 open.push((prelude.clone(), String::new()));
441 }
442 blocks.push(declarations);
443 prelude.clear();
444 }
445 '}' => {
446 if blocks.pop().unwrap_or(false)
447 && let Some(rule) = open.pop()
448 {
449 out.push(rule);
450 }
451 prelude.clear();
452 }
453 _ => {
454 if blocks.last().copied().unwrap_or(false)
455 && let Some((_, body)) = open.last_mut()
456 {
457 body.push(c);
458 } else if c == ';' {
459 prelude.clear();
460 } else {
461 prelude.push(c);
462 }
463 }
464 }
465 }
466 out
467 }
468
469 /// Which generated classes each element can plausibly carry.
470 ///
471 /// The half of the element check that CSS cannot answer. A stylesheet says
472 /// `button { color: ... }` and `.chip { color: ... }` and nothing in either
473 /// text says a chip is rendered as a `<button>`; the renderer knows that, and
474 /// this crate is the renderer. So the pairing is declared here rather than
475 /// inferred, and [`declarations_by_element`] supplies the other half.
476 ///
477 /// Read it as "may carry", not "does carry". A pairing that never occurs in a
478 /// given app costs a check that finds nothing; a pairing left out is a defect
479 /// that ships, which is the trade this list is written on the generous side
480 /// of.
481 ///
482 /// `div` and `span` are deliberately absent. Nearly every container class in
483 /// the vocabulary sits on one of them, so the pairing would be the whole
484 /// vocabulary against one rule and would say nothing about which class was
485 /// meant. An app writing a bare `div { }` rule has a wider problem than this
486 /// check, and the classes it would clobber are containers rather than the
487 /// controls whose tone and bevel carry meaning.
488 pub const ELEMENT_CLASSES: &[(&str, &[&str])] = &[
489 // The controls. `a` and `button` are interchangeable in markup for most of
490 // these -- a link that posts is a button, an act that navigates is an
491 // anchor -- which is why the two lists overlap as much as they do.
492 (
493 "a",
494 &[
495 "link",
496 "button",
497 "tab",
498 "chip",
499 "badge",
500 "card",
501 "row-activate",
502 "figure-act",
503 "chrome-place",
504 ],
505 ),
506 (
507 "button",
508 &[
509 "button",
510 "chip",
511 "segment",
512 "toggle",
513 "tab",
514 "link",
515 "badge",
516 "card",
517 "facet-take",
518 "facet-prune",
519 "chip-remove",
520 "row-activate",
521 ],
522 ),
523 // A disclosure. quasi-webview renders an ask as `<details>` with a
524 // `<summary>` that is styled as an act.
525 ("details", &["ask"]),
526 ("summary", &["button", "ask-open", "ask-body"]),
527 // The form controls. `.field` is the well every one of them sits in.
528 ("input", &["field", "toggle", "row-select"]),
529 ("select", &["field"]),
530 ("textarea", &["field"]),
531 (
532 "label",
533 &[
534 "form-label",
535 "form-checkbox-label",
536 "form-radio-label",
537 "toggle",
538 ],
539 ),
540 ("form", &["form"]),
541 ("progress", &["progress"]),
542 // Text and lists.
543 ("p", &["text", "facet-name", "placeholder-text"]),
544 ("ul", &["list", "facet-values"]),
545 ("ol", &["list"]),
546 ("li", &["facet-value"]),
547 // A table written in HTML rather than described. quasi-webview renders a
548 // described table as divs carrying the same classes, so both spellings of
549 // the same table answer to the same rules and both are worth checking.
550 ("table", &["table"]),
551 ("thead", &["table-head"]),
552 ("tr", &["table-row"]),
553 ("td", &["cell", "cell-value", "cell-content"]),
554 ("th", &["table-heading"]),
555 // A figure, likewise: the described picture is divs, the hand-written one
556 // is the HTML element that means the same thing.
557 ("figure", &["picture", "figure"]),
558 ("img", &["picture-img"]),
559 ("figcaption", &["picture-caption", "figure-caption"]),
560 ("nav", &["chrome-nav"]),
561 ];
562
563 /// The generated classes `element` can carry, prefixed the way `opts` prefixes
564 /// them.
565 ///
566 /// Empty for an element the design system never renders onto, which is the
567 /// answer for most of them: a rule on one of those cannot collide with a
568 /// generated class because no generated class is ever on it.
569 #[must_use]
570 pub fn classes_for_element(element: &str, opts: &Emit) -> BTreeSet<String> {
571 ELEMENT_CLASSES
572 .iter()
573 .find(|(name, _)| *name == element)
574 .map(|(_, classes)| classes.iter().map(|c| crate::class(c, opts)).collect())
575 .unwrap_or_default()
576 }
577
578 /// The element name of one bare compound arm, if that is what it is.
579 fn bare_element(arm: &str) -> Option<String> {
580 // An attribute value or a `:not()` argument can hold anything, including
581 // the spaces and dots this then rejects on. Neither changes which element
582 // the arm styles, so both go before the test rather than into it.
583 let mut flat = String::with_capacity(arm.len());
584 let mut depth = 0usize;
585 for c in arm.chars() {
586 match c {
587 '[' | '(' => depth += 1,
588 ']' | ')' => depth = depth.saturating_sub(1),
589 _ if depth == 0 => flat.push(c),
590 _ => {}
591 }
592 }
593 let flat = flat.trim();
594 // A descendant, a child, a class, an id or a universal: not this.
595 if flat.is_empty() || flat.contains(['.', '#', '>', '+', '~', '*']) {
596 return None;
597 }
598 if flat.chars().any(char::is_whitespace) {
599 return None;
600 }
601 let name: String = flat
602 .chars()
603 .take_while(|c| c.is_alphanumeric() || *c == '-')
604 .collect();
605 // A pseudo-element on nothing (`::selection`) or a pseudo-class on nothing
606 // (`:root`) names no element.
607 if !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
608 return None;
609 }
610 Some(name.to_ascii_lowercase())
611 }
612
613 /// The class names one selector matches on.
614 fn classes_in_selector(selector: &str) -> Vec<String> {
615 let chars: Vec<char> = selector.chars().collect();
616 let mut names = Vec::new();
617 let mut i = 0;
618 while i < chars.len() {
619 // A leading digit is a length (`.5rem`), never a class: CSS forbids an
620 // identifier starting with one.
621 if chars[i] == '.'
622 && chars
623 .get(i + 1)
624 .is_some_and(|c| c.is_alphabetic() || *c == '_')
625 {
626 let start = i + 1;
627 let mut end = start;
628 while end < chars.len()
629 && (chars[end].is_alphanumeric() || chars[end] == '-' || chars[end] == '_')
630 {
631 end += 1;
632 }
633 names.push(chars[start..end].iter().collect());
634 i = end;
635 } else {
636 i += 1;
637 }
638 }
639 names
640 }
641
642 #[cfg(test)]
643 mod tests {
644 use super::*;
645 use crate::list::{cell_part_class, part_class};
646 use makeover_layout::{CellPart, RowPart};
647
648 #[test]
649 fn the_scrape_finds_the_components_the_sheet_is_built_from() {
650 let v = vocabulary(&Emit::default());
651 assert!(
652 v.len() > 20,
653 "scraped {} classes, which reads as a parser failure rather than a small sheet",
654 v.len()
655 );
656 for name in ["card", "tab", "table-heading", "cell-value", "chosen"] {
657 assert!(
658 v.contains(name),
659 "the sheet defines .{name} and the scan missed it"
660 );
661 }
662 }
663
664 #[test]
665 fn every_name_a_caller_can_ask_for_is_one_this_crate_admits_to() {
666 // The two halves of the agreement, checked against each other. A naming
667 // function returning a class outside `names` would put a class in the
668 // markup that nothing downstream can recognise, which is the failure
669 // quasi-webview shipped and phase 1 exists to make impossible.
670 let opts = Emit::default();
671 let all = names(&opts);
672
673 for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
674 let name = option_class(selector);
675 assert!(
676 all.contains(name),
677 "option_class({selector:?}) is .{name}, which nothing admits to"
678 );
679 }
680 for part in [
681 RowPart::Primary,
682 RowPart::Secondary,
683 RowPart::Meta,
684 RowPart::Actions,
685 RowPart::Tokens,
686 RowPart::Proportion,
687 ] {
688 let name = part_class(part);
689 assert!(
690 all.contains(name),
691 "part_class({part:?}) is .{name}, which nothing admits to"
692 );
693 }
694 for part in [
695 CellPart::Value,
696 CellPart::Tokens,
697 CellPart::Actions,
698 CellPart::Link,
699 ] {
700 let name = cell_part_class(part);
701 assert!(
702 all.contains(name),
703 "cell_part_class({part:?}) is .{name}, which nothing admits to"
704 );
705 }
706 }
707
708 #[test]
709 fn the_part_lists_hold_every_arm_of_the_match_beside_them() {
710 // ROW_PART_CLASSES and CELL_PART_CLASSES are written out because a
711 // `#[non_exhaustive]` enum cannot be enumerated. This is the test that
712 // stops them drifting from the matches they sit next to.
713 for part in [
714 RowPart::Primary,
715 RowPart::Secondary,
716 RowPart::Meta,
717 RowPart::Actions,
718 RowPart::Tokens,
719 RowPart::Proportion,
720 ] {
721 assert!(
722 ROW_PART_CLASSES.contains(&part_class(part)),
723 "{part:?} is missing from ROW_PART_CLASSES"
724 );
725 }
726 for part in [
727 CellPart::Value,
728 CellPart::Tokens,
729 CellPart::Actions,
730 CellPart::Link,
731 ] {
732 assert!(
733 CELL_PART_CLASSES.contains(&cell_part_class(part)),
734 "{part:?} is missing from CELL_PART_CLASSES"
735 );
736 }
737 // The fallbacks, which are what an upstream addition lands on.
738 assert!(ROW_PART_CLASSES.contains(&"row-part"));
739 assert!(CELL_PART_CLASSES.contains(&"cell-part"));
740 }
741
742 #[test]
743 fn a_prefix_moves_the_component_classes_and_leaves_the_states_qualifying_them() {
744 let plain = vocabulary(&Emit::default());
745 let prefixed = vocabulary(&Emit {
746 class_prefix: "mo-",
747 ..Emit::default()
748 });
749 assert_eq!(
750 plain.len(),
751 prefixed.len(),
752 "a prefix changed how many classes exist"
753 );
754 // `chosen` and `latched` never stand alone: the sheet writes
755 // `.mo-tab.chosen`, so the state stays bare while the thing moves.
756 // `current` is the third, and it is the same shape: which child of a
757 // region showing one at a time is the one showing.
758 let states = ["chosen", "latched", "current"];
759 for name in &plain {
760 let expected = if states.contains(&name.as_str()) {
761 name.clone()
762 } else {
763 format!("mo-{name}")
764 };
765 assert!(
766 prefixed.contains(&expected),
767 ".{name} did not move to .{expected} under the prefix"
768 );
769 }
770 }
771
772 #[test]
773 fn a_handoff_is_not_an_override() {
774 // The defect this split fixes. `revert-layer` in a later layer gives
775 // the property back to the design system, so counting it as a taking
776 // made every remedy in a consumer's sheet read as the thing it
777 // remedied -- and the allowlist entry written to silence one went on
778 // permitting a real override on the same pair for good.
779 let css = ".button { background: revert-layer; color: red; }";
780 let taken = declarations_by_class(css);
781 let given = deferrals_by_class(css);
782 assert_eq!(
783 taken.get("button"),
784 Some(&["color".to_string()].into_iter().collect())
785 );
786 assert_eq!(
787 given.get("button"),
788 Some(&["background".to_string()].into_iter().collect())
789 );
790 }
791
792 #[test]
793 fn an_important_handoff_is_an_override() {
794 // `revert-layer !important` in a later layer inverts layer order and
795 // takes the property from every layer below it. Same word, opposite
796 // declaration, and the one shape of it this reader must not wave
797 // through.
798 let css = ".button { background: revert-layer !important; }";
799 assert_eq!(
800 declarations_by_class(css).get("button"),
801 Some(&["background".to_string()].into_iter().collect())
802 );
803 assert!(!deferrals_by_class(css).contains_key("button"));
804 }
805
806 #[test]
807 fn a_class_that_only_hands_properties_back_is_not_in_the_taking_set() {
808 // An empty entry would read as "this class collides on nothing", which
809 // is true, and as "this class is in the map", which is what a caller
810 // iterating the map would act on.
811 let by_class = declarations_by_class(".field { background: revert-layer; }");
812 assert!(!by_class.contains_key("field"), "got {by_class:?}");
813 }
814
815 #[test]
816 fn an_element_rule_is_read_where_a_class_reader_sees_nothing() {
817 let css = "button { color: red; background: blue; }";
818 assert!(declarations_by_class(css).is_empty());
819 let by_element = declarations_by_element(css);
820 let button = by_element.get("button").expect("button is named");
821 assert_eq!(
822 button.keys().cloned().collect::<Vec<_>>(),
823 ["background", "color"]
824 );
825 // One element, nothing else: (0, 0, 1).
826 assert_eq!(button["color"], (0, 0, 1));
827 }
828
829 #[test]
830 fn the_strongest_arm_is_the_one_reported() {
831 // A remedy has to outrank the rule it remedies, so a reader that kept
832 // the weakest arm would call a losing handoff sufficient.
833 let css = "input { color: red; }\ninput[type=\"text\"]:focus { color: blue; }\n";
834 assert_eq!(declarations_by_element(css)["input"]["color"], (0, 2, 1));
835 }
836
837 #[test]
838 fn a_selector_is_ranked_the_way_the_cascade_ranks_it() {
839 for (selector, expected) in [
840 ("button", (0, 0, 1)),
841 ("*", (0, 0, 0)),
842 (".field", (0, 1, 0)),
843 ("input.field", (0, 1, 1)),
844 ("input[type=\"text\"]", (0, 1, 1)),
845 ("button:hover", (0, 1, 1)),
846 ("button::before", (0, 0, 2)),
847 ("#main .card > button:focus-visible", (1, 2, 1)),
848 (".chip.latched[aria-pressed=\"true\"]", (0, 3, 0)),
849 ("button:not(.link)", (0, 1, 1)),
850 ] {
851 assert_eq!(specificity(selector), expected, "{selector}");
852 }
853 }
854
855 #[test]
856 fn what_a_class_is_spoken_for_by_counts_a_handoff_as_speech() {
857 // A handoff takes nothing, so `declarations_by_class` is right to drop
858 // it -- and it is still the app saying what happens to that property on
859 // that class, which is what this reader is for.
860 let css = ".field { background: revert-layer; }\ninput.field:focus { color: red; }\n";
861 let mentions = mentions_by_class(css);
862 assert_eq!(mentions["field"]["background"], (0, 1, 0));
863 assert_eq!(mentions["field"]["color"], (0, 2, 1));
864 }
865
866 #[test]
867 fn only_a_bare_compound_counts_as_an_element_rule() {
868 // Each of these styles a `button` and none of them is the certain
869 // case. A scoped arm reaches one region, and an arm carrying a class
870 // is the class reader's business, not this one's.
871 for selector in [
872 ".page button",
873 "button.link",
874 ".card > button",
875 "button + button",
876 "* button",
877 ] {
878 let css = format!("{selector} {{ color: red; }}");
879 assert!(
880 declarations_by_element(&css).is_empty(),
881 "{selector} was read as a bare element rule"
882 );
883 }
884 }
885
886 #[test]
887 fn a_state_or_an_attribute_does_not_stop_an_arm_being_bare() {
888 // All of these reach every button in the document, which is what makes
889 // them certain to reach a described one.
890 for selector in [
891 "button:hover",
892 "button:focus-visible",
893 "button:disabled",
894 "button[aria-disabled=\"true\"]",
895 "button:not(.link)",
896 "button[data-tone=\"danger\"]:hover",
897 ] {
898 let css = format!("{selector} {{ color: red; }}");
899 assert!(
900 declarations_by_element(&css).contains_key("button"),
901 "{selector} was not read as a bare element rule"
902 );
903 }
904 }
905
906 #[test]
907 fn a_pseudo_element_on_nothing_names_no_element() {
908 for selector in [":root", "::selection", "::backdrop", ":root:not(.x)"] {
909 let css = format!("{selector} {{ color: red; }}");
910 assert!(
911 declarations_by_element(&css).is_empty(),
912 "{selector} named an element"
913 );
914 }
915 }
916
917 #[test]
918 fn every_arm_of_a_list_is_read_on_its_own() {
919 let css = "input, select, .field, .page textarea { color: red; }";
920 let by_element = declarations_by_element(css);
921 assert!(by_element.contains_key("input"));
922 assert!(by_element.contains_key("select"));
923 assert!(!by_element.contains_key("textarea"), "that arm is scoped");
924 assert_eq!(by_element.len(), 2);
925 }
926
927 #[test]
928 fn an_element_handing_a_property_back_is_not_taking_it() {
929 let css = "button { background: revert-layer; }";
930 assert!(declarations_by_element(css).is_empty());
931 }
932
933 #[test]
934 fn the_pairing_map_carries_the_elements_this_crate_renders_onto() {
935 // The map is hand-written and the emitters are not, so this is what
936 // stops the two drifting. Every `<tag class="...">` in this crate's own
937 // source, for a tag the map claims to cover, has to be a pairing the
938 // map declares -- or the check reads a smaller world than the renderer
939 // writes and the gap is silent.
940 let mut checked = 0;
941 for (tag, class) in emitted_pairs() {
942 if !ELEMENT_CLASSES.iter().any(|(name, _)| *name == tag) {
943 continue;
944 }
945 checked += 1;
946 assert!(
947 classes_for_element(&tag, &Emit::default()).contains(&class),
948 "this crate emits <{tag} class=\"{class}\"> and ELEMENT_CLASSES \
949 does not pair them"
950 );
951 }
952 assert!(
953 checked > 5,
954 "scraped {checked} pairings off the emitters, which reads as the scan \
955 having stopped matching rather than the renderer having shrunk"
956 );
957 }
958
959 /// `(element, class)` for every literal `<tag class="...">` this crate's
960 /// own source emits.
961 ///
962 /// Source rather than rendered markup, because an emitter no test happens
963 /// to call is exactly the one whose pairing nobody wrote down. A class
964 /// built at runtime (an option class, a row part) is not a literal and is
965 /// not seen here; those are declared in the map by hand.
966 fn emitted_pairs() -> Vec<(String, String)> {
967 const OPEN: &str = "class=\\\"";
968 let mut out = Vec::new();
969 for file in std::fs::read_dir("src").expect("read src") {
970 let path = file.expect("dir entry").path();
971 if path.extension().is_none_or(|e| e != "rs") {
972 continue;
973 }
974 let src = std::fs::read_to_string(&path).expect("read source");
975 for (at, _) in src.match_indices(OPEN) {
976 // The tag is the last `<name` before the attribute.
977 let Some(open) = src[..at].rfind('<') else {
978 continue;
979 };
980 let tag: String = src[open + 1..]
981 .chars()
982 .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
983 .collect();
984 if tag.is_empty() {
985 continue;
986 }
987 // What is pushed next: `push_class(out, "name", opts)`.
988 let tail = &src[at..(at + 300).min(src.len())];
989 let Some(call) = tail.find("push_class(out, \"") else {
990 continue;
991 };
992 let name: String = tail[call + "push_class(out, \"".len()..]
993 .chars()
994 .take_while(|c| *c != '"')
995 .collect();
996 if !name.is_empty() {
997 out.push((tag, name));
998 }
999 }
1000 }
1001 out
1002 }
1003
1004 #[test]
1005 fn the_properties_a_class_carries_are_read_per_class() {
1006 let css = ".badge { padding: 1px; font-weight: 600; }\n .badge[data-color] { border: 1px solid red; }\n @media (min-width: 40rem) { .badge { padding: 2px; } }\n";
1007 let by_class = declarations_by_class(css);
1008 let badge = by_class.get("badge").expect("badge is named");
1009 // Every arm collapses into one entry, including the one inside the
1010 // media block: they are all the same class carrying the same property.
1011 assert!(badge.contains("padding"));
1012 assert!(badge.contains("font-weight"));
1013 assert!(badge.contains("border"));
1014 assert_eq!(badge.len(), 3);
1015 }
1016
1017 #[test]
1018 fn a_value_holding_a_colon_or_a_semicolon_is_not_read_as_a_property() {
1019 let css = ".x { background: url(\"a;b:c\"); color: red; }";
1020 let by_class = declarations_by_class(css);
1021 let x = by_class.get("x").expect("x is named");
1022 assert_eq!(
1023 *x,
1024 ["background".to_string(), "color".to_string()]
1025 .into_iter()
1026 .collect::<BTreeSet<_>>()
1027 );
1028 }
1029
1030 #[test]
1031 fn the_generated_sheet_sets_fill_on_a_badge_and_not_its_shape() {
1032 // The fact goingson's stylesheet states in prose next to its own
1033 // `.badge`: "Fill, edge and text colour come from the generated .badge
1034 // in layout.css... Do not add background, border or box-shadow here."
1035 // A property-grain reader is what turns that comment into a check.
1036 let by_class = declarations_by_class(&crate::stylesheet(&Emit::default()));
1037 let badge = by_class.get("badge").expect("the sheet defines .badge");
1038 // Token::Badge is Depth::Flat, so a badge carries no bevel and no
1039 // fill: what the generated sheet gives it is the text colour, and
1040 // everything about its shape is the app's.
1041 assert!(badge.contains("color"), "got {badge:?}");
1042 assert!(
1043 !badge.contains("padding"),
1044 "shape is the app's, got {badge:?}"
1045 );
1046 }
1047
1048 #[test]
1049 fn a_declaration_value_holding_a_dot_is_not_read_as_a_class() {
1050 let found = classes_in_css(".real { transition: .2s ease; margin: 0.5rem; }");
1051 assert_eq!(found, ["real".to_string()].into_iter().collect());
1052 }
1053
1054 #[test]
1055 fn an_at_rule_does_not_hide_the_selectors_inside_it() {
1056 let found = classes_in_css(
1057 "@layer makeover { @media (min-width: 40rem) { .wide { color: red; } } }",
1058 );
1059 assert_eq!(found, ["wide".to_string()].into_iter().collect());
1060 }
1061
1062 #[test]
1063 fn a_string_is_opaque_and_a_comment_contributes_nothing() {
1064 let found = classes_in_css("/* .notaclass */ .caret::after { content: \"} .alsonot\"; }");
1065 assert_eq!(found, ["caret".to_string()].into_iter().collect());
1066 }
1067
1068 #[test]
1069 fn a_compound_selector_yields_every_class_it_names() {
1070 let found = classes_in_css(
1071 ".tab.chosen[aria-sort=\"ascending\"] > .label:not(.muted) { color: red; }",
1072 );
1073 let expected: BTreeSet<String> = ["tab", "chosen", "label", "muted"]
1074 .into_iter()
1075 .map(String::from)
1076 .collect();
1077 assert_eq!(found, expected);
1078 }
1079 }
1080