makeover_webview/vocabulary.rs
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, and 0.27.0 shipped
7//! it. The other half is 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
37use crate::list::{CELL_PART_CLASSES, ROW_PART_CLASSES};
38use crate::{Emit, option_class};
39use makeover_layout::Selector;
40use std::collections::{BTreeMap, BTreeSet};
41
42/// Every class name the generated stylesheet defines a rule for, prefixed the
43/// way `opts` prefixes them.
44///
45/// Includes the state classes a caller never spells alone (`chosen`,
46/// `latched`). Those are deliberately unprefixed: they qualify a prefixed
47/// component (`.mo-tab.chosen`) rather than standing on their own, so a prefix
48/// moves the thing and not its state.
49#[must_use]
50pub fn vocabulary(opts: &Emit) -> BTreeSet<String> {
51 classes_in_css(&crate::stylesheet(opts))
52}
53
54/// Every class this crate can put in markup or in a rule.
55///
56/// [`vocabulary`] plus the part classes it deliberately leaves unruled. This is
57/// the set to check a renderer's emitted markup against: a class outside it is
58/// a name that renderer invented, which is how quasi-webview came to spell
59/// `tabs`, `segmented` and `option` and render every described selector flat.
60#[must_use]
61pub fn names(opts: &Emit) -> BTreeSet<String> {
62 let mut all = vocabulary(opts);
63 all.extend(
64 ROW_PART_CLASSES
65 .iter()
66 .chain(CELL_PART_CLASSES)
67 .map(|name| crate::class(name, opts)),
68 );
69 all.extend(
70 [Selector::Tabs, Selector::Segmented, Selector::Toggle]
71 .into_iter()
72 .map(|s| crate::class(option_class(s), opts)),
73 );
74 all
75}
76
77/// The class names a stylesheet's selectors match.
78///
79/// Public because the check this exists for reads an app's stylesheet too, and
80/// comparing what makeover defines against what the app defines is only
81/// meaningful if both sides were read the same way.
82///
83/// Selector text only. A declaration value can hold a dot (`0.5rem`,
84/// `transition: .2s`) and none of those are classes, so the scan tracks whether
85/// it is inside a declaration block and ignores what it finds there. An at-rule
86/// block (`@layer`, `@media`, `@supports`) contains rules rather than
87/// declarations, which is why a depth counter alone is not enough: the stack
88/// records what kind of block each brace opened.
89/// Which properties a stylesheet sets on each class it names.
90///
91/// The grain a drift check actually wants. A class name in common is not by
92/// itself a divergence: goingson's `.badge` sets shape and the generated
93/// `.badge` sets fill and edge, and the app's own comment says "do not add
94/// background, border or box-shadow here". That arrangement is settled and
95/// correct, so a check that flagged the shared name would demand deleting it.
96/// A shared *property* is the thing that goes wrong, because app CSS is
97/// unlayered and takes the property from the design system silently.
98///
99/// A property appearing under more than one selector arm collapses into one
100/// entry. That loses a real distinction -- the sort caret's reserved gap is
101/// `content` on the unsorted arm and the generated caret is `content` on the
102/// sorted one, which is a deliberate pairing rather than a clash -- so a
103/// consumer of this needs a way to say a pair was reviewed. Deciding that here
104/// would need a selector matcher, and a check that guesses wrong about
105/// specificity fails correct builds.
106#[must_use]
107pub fn declarations_by_class(css: &str) -> BTreeMap<String, BTreeSet<String>> {
108 let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
109 for (selector, body) in rules(css) {
110 let classes = classes_in_selector(&selector);
111 if classes.is_empty() {
112 continue;
113 }
114 let properties = properties_in_body(&body);
115 for class in classes {
116 out.entry(class).or_default().extend(properties.clone());
117 }
118 }
119 out
120}
121
122/// The property names a declaration block sets.
123fn properties_in_body(body: &str) -> BTreeSet<String> {
124 body.split(';')
125 .filter_map(|decl| decl.split_once(':'))
126 .map(|(name, _)| name.trim().to_string())
127 .filter(|name| !name.is_empty() && !name.contains(['{', '}']))
128 .collect()
129}
130
131#[must_use]
132pub fn classes_in_css(css: &str) -> BTreeSet<String> {
133 rules(css)
134 .into_iter()
135 .flat_map(|(selector, _)| classes_in_selector(&selector))
136 .collect()
137}
138
139/// `(selector, declaration block)` for every rule in a stylesheet.
140///
141/// One reader for both sides. Comparing what makeover defines against what an
142/// app defines is only meaningful if the two were read the same way, which is
143/// why this is the only place either question is answered from.
144///
145/// A comment is skipped whole: the banner at the top of the generated sheet is
146/// prose about the cascade layer and would otherwise contribute words that look
147/// like selectors. A string is opaque, because `content: "\2191"` is the sort
148/// caret rather than a selector and a brace inside one would desync the stack.
149/// An at-rule block (`@layer`, `@media`, `@supports`) holds rules rather than
150/// declarations, so a depth counter alone is not enough and the stack records
151/// what kind of block each brace opened.
152fn rules(css: &str) -> Vec<(String, String)> {
153 let mut out = Vec::new();
154 // One entry per open brace: true when that block holds declarations rather
155 // than nested rules.
156 let mut blocks: Vec<bool> = Vec::new();
157 // Text since the last `{`, `}` or `;`. What precedes a `{` is that block's
158 // prelude, and a prelude starting with `@` opens an at-rule.
159 let mut prelude = String::new();
160 // The selector of each open declaration block, and the body so far.
161 let mut open: Vec<(String, String)> = Vec::new();
162
163 let mut chars = css.chars().peekable();
164 while let Some(c) = chars.next() {
165 match c {
166 '/' if chars.peek() == Some(&'*') => {
167 chars.next();
168 let mut star = false;
169 for c in chars.by_ref() {
170 if star && c == '/' {
171 break;
172 }
173 star = c == '*';
174 }
175 prelude.clear();
176 }
177 '"' | '\'' => {
178 let quote = c;
179 let mut escaped = false;
180 // Keep the quotes in the body: a value is not a property name,
181 // and dropping them would join two declarations into one.
182 if blocks.last().copied().unwrap_or(false)
183 && let Some((_, body)) = open.last_mut()
184 {
185 body.push(quote);
186 }
187 for c in chars.by_ref() {
188 if escaped {
189 escaped = false;
190 } else if c == '\\' {
191 escaped = true;
192 } else if c == quote {
193 break;
194 }
195 }
196 // The closing quote only. A value holding `;` or `:` would
197 // otherwise read as two declarations, and `url("a;b:c")` is a
198 // real thing an app writes.
199 if blocks.last().copied().unwrap_or(false)
200 && let Some((_, body)) = open.last_mut()
201 {
202 body.push(quote);
203 }
204 }
205 '{' => {
206 let declarations = !prelude.trim_start().starts_with('@');
207 if declarations {
208 open.push((prelude.clone(), String::new()));
209 }
210 blocks.push(declarations);
211 prelude.clear();
212 }
213 '}' => {
214 if blocks.pop().unwrap_or(false)
215 && let Some(rule) = open.pop()
216 {
217 out.push(rule);
218 }
219 prelude.clear();
220 }
221 _ => {
222 if blocks.last().copied().unwrap_or(false)
223 && let Some((_, body)) = open.last_mut()
224 {
225 body.push(c);
226 } else if c == ';' {
227 prelude.clear();
228 } else {
229 prelude.push(c);
230 }
231 }
232 }
233 }
234 out
235}
236
237/// The class names one selector matches on.
238fn classes_in_selector(selector: &str) -> Vec<String> {
239 let chars: Vec<char> = selector.chars().collect();
240 let mut names = Vec::new();
241 let mut i = 0;
242 while i < chars.len() {
243 // A leading digit is a length (`.5rem`), never a class: CSS forbids an
244 // identifier starting with one.
245 if chars[i] == '.'
246 && chars
247 .get(i + 1)
248 .is_some_and(|c| c.is_alphabetic() || *c == '_')
249 {
250 let start = i + 1;
251 let mut end = start;
252 while end < chars.len()
253 && (chars[end].is_alphanumeric() || chars[end] == '-' || chars[end] == '_')
254 {
255 end += 1;
256 }
257 names.push(chars[start..end].iter().collect());
258 i = end;
259 } else {
260 i += 1;
261 }
262 }
263 names
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269 use crate::list::{cell_part_class, part_class};
270 use makeover_layout::{CellPart, RowPart};
271
272 #[test]
273 fn the_scrape_finds_the_components_the_sheet_is_built_from() {
274 let v = vocabulary(&Emit::default());
275 assert!(
276 v.len() > 20,
277 "scraped {} classes, which reads as a parser failure rather than a small sheet",
278 v.len()
279 );
280 for name in ["card", "tab", "table-heading", "cell-value", "chosen"] {
281 assert!(
282 v.contains(name),
283 "the sheet defines .{name} and the scan missed it"
284 );
285 }
286 }
287
288 #[test]
289 fn every_name_a_caller_can_ask_for_is_one_this_crate_admits_to() {
290 // The two halves of the agreement, checked against each other. A naming
291 // function returning a class outside `names` would put a class in the
292 // markup that nothing downstream can recognise, which is the failure
293 // quasi-webview shipped and phase 1 exists to make impossible.
294 let opts = Emit::default();
295 let all = names(&opts);
296
297 for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
298 let name = option_class(selector);
299 assert!(
300 all.contains(name),
301 "option_class({selector:?}) is .{name}, which nothing admits to"
302 );
303 }
304 for part in [
305 RowPart::Primary,
306 RowPart::Secondary,
307 RowPart::Meta,
308 RowPart::Actions,
309 RowPart::Tokens,
310 RowPart::Proportion,
311 ] {
312 let name = part_class(part);
313 assert!(
314 all.contains(name),
315 "part_class({part:?}) is .{name}, which nothing admits to"
316 );
317 }
318 for part in [
319 CellPart::Value,
320 CellPart::Tokens,
321 CellPart::Actions,
322 CellPart::Link,
323 ] {
324 let name = cell_part_class(part);
325 assert!(
326 all.contains(name),
327 "cell_part_class({part:?}) is .{name}, which nothing admits to"
328 );
329 }
330 }
331
332 #[test]
333 fn the_part_lists_hold_every_arm_of_the_match_beside_them() {
334 // ROW_PART_CLASSES and CELL_PART_CLASSES are written out because a
335 // `#[non_exhaustive]` enum cannot be enumerated. This is the test that
336 // stops them drifting from the matches they sit next to.
337 for part in [
338 RowPart::Primary,
339 RowPart::Secondary,
340 RowPart::Meta,
341 RowPart::Actions,
342 RowPart::Tokens,
343 RowPart::Proportion,
344 ] {
345 assert!(
346 ROW_PART_CLASSES.contains(&part_class(part)),
347 "{part:?} is missing from ROW_PART_CLASSES"
348 );
349 }
350 for part in [
351 CellPart::Value,
352 CellPart::Tokens,
353 CellPart::Actions,
354 CellPart::Link,
355 ] {
356 assert!(
357 CELL_PART_CLASSES.contains(&cell_part_class(part)),
358 "{part:?} is missing from CELL_PART_CLASSES"
359 );
360 }
361 // The fallbacks, which are what an upstream addition lands on.
362 assert!(ROW_PART_CLASSES.contains(&"row-part"));
363 assert!(CELL_PART_CLASSES.contains(&"cell-part"));
364 }
365
366 #[test]
367 fn a_prefix_moves_the_component_classes_and_leaves_the_states_qualifying_them() {
368 let plain = vocabulary(&Emit::default());
369 let prefixed = vocabulary(&Emit {
370 class_prefix: "mo-",
371 ..Emit::default()
372 });
373 assert_eq!(
374 plain.len(),
375 prefixed.len(),
376 "a prefix changed how many classes exist"
377 );
378 // `chosen` and `latched` never stand alone: the sheet writes
379 // `.mo-tab.chosen`, so the state stays bare while the thing moves.
380 let states = ["chosen", "latched"];
381 for name in &plain {
382 let expected = if states.contains(&name.as_str()) {
383 name.clone()
384 } else {
385 format!("mo-{name}")
386 };
387 assert!(
388 prefixed.contains(&expected),
389 ".{name} did not move to .{expected} under the prefix"
390 );
391 }
392 }
393
394 #[test]
395 fn the_properties_a_class_carries_are_read_per_class() {
396 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";
397 let by_class = declarations_by_class(css);
398 let badge = by_class.get("badge").expect("badge is named");
399 // Every arm collapses into one entry, including the one inside the
400 // media block: they are all the same class carrying the same property.
401 assert!(badge.contains("padding"));
402 assert!(badge.contains("font-weight"));
403 assert!(badge.contains("border"));
404 assert_eq!(badge.len(), 3);
405 }
406
407 #[test]
408 fn a_value_holding_a_colon_or_a_semicolon_is_not_read_as_a_property() {
409 let css = ".x { background: url(\"a;b:c\"); color: red; }";
410 let by_class = declarations_by_class(css);
411 let x = by_class.get("x").expect("x is named");
412 assert_eq!(
413 *x,
414 ["background".to_string(), "color".to_string()]
415 .into_iter()
416 .collect::<BTreeSet<_>>()
417 );
418 }
419
420 #[test]
421 fn the_generated_sheet_sets_fill_on_a_badge_and_not_its_shape() {
422 // The fact goingson's stylesheet states in prose next to its own
423 // `.badge`: "Fill, edge and text colour come from the generated .badge
424 // in layout.css... Do not add background, border or box-shadow here."
425 // A property-grain reader is what turns that comment into a check.
426 let by_class = declarations_by_class(&crate::stylesheet(&Emit::default()));
427 let badge = by_class.get("badge").expect("the sheet defines .badge");
428 // Token::Badge is Depth::Flat, so a badge carries no bevel and no
429 // fill: what the generated sheet gives it is the text colour, and
430 // everything about its shape is the app's.
431 assert!(badge.contains("color"), "got {badge:?}");
432 assert!(
433 !badge.contains("padding"),
434 "shape is the app's, got {badge:?}"
435 );
436 }
437
438 #[test]
439 fn a_declaration_value_holding_a_dot_is_not_read_as_a_class() {
440 let found = classes_in_css(".real { transition: .2s ease; margin: 0.5rem; }");
441 assert_eq!(found, ["real".to_string()].into_iter().collect());
442 }
443
444 #[test]
445 fn an_at_rule_does_not_hide_the_selectors_inside_it() {
446 let found = classes_in_css(
447 "@layer makeover { @media (min-width: 40rem) { .wide { color: red; } } }",
448 );
449 assert_eq!(found, ["wide".to_string()].into_iter().collect());
450 }
451
452 #[test]
453 fn a_string_is_opaque_and_a_comment_contributes_nothing() {
454 let found = classes_in_css("/* .notaclass */ .caret::after { content: \"} .alsonot\"; }");
455 assert_eq!(found, ["caret".to_string()].into_iter().collect());
456 }
457
458 #[test]
459 fn a_compound_selector_yields_every_class_it_names() {
460 let found = classes_in_css(
461 ".tab.chosen[aria-sort=\"ascending\"] > .label:not(.muted) { color: red; }",
462 );
463 let expected: BTreeSet<String> = ["tab", "chosen", "label", "muted"]
464 .into_iter()
465 .map(String::from)
466 .collect();
467 assert_eq!(found, expected);
468 }
469}