Skip to main content

max / makeover-webview

11.7 KB · 330 lines History Blame Raw
1 //! A render of everything this crate can emit, scraped for class names.
2 //!
3 //! [`vocabulary::names`](crate::vocabulary::names) claims to hold every class
4 //! this crate can put in markup, and this is what checks the claim. A name
5 //! missing from that set is worse than a name missing from the stylesheet: an
6 //! app checking its own stylesheet against the set concludes that its rules for
7 //! the name are dead and deletes live styling.
8 //!
9 //! This is a render and not a scan of the emitters: a careful read of `quasi-webview`'s emitters produced 35 names and
10 //! its corpus found 14 more. A class assembled at runtime -- a width class, a
11 //! drop class, a state appended to an attribute already open -- is a literal
12 //! nowhere in this source, and that is the shape of every name that was
13 //! missing here.
14 //!
15 //! # What it is not
16 //!
17 //! Not a rendering test. Nothing here asserts what an emitter produced, only
18 //! which classes came out, so it stays quiet when markup changes and speaks
19 //! when the vocabulary does.
20
21 use crate::form::{Filling, Markup, Value, field_html};
22 use crate::list::{Cell, cells_html};
23 use crate::{Emit, facet::facet_html, figure::figures_html};
24 use crate::{meter::meter_html, placeholder::placeholder_html};
25 use makeover_layout::{
26 Accepted, CellPart, Choice, Column, Contrast, Facet, FacetValue, Field, FieldKind, Figure,
27 Meter, Priority, Readiness, Selecting, Sort, Standing, ThemeChoice, ThemeVariant, Tone, Width,
28 };
29 use std::collections::BTreeSet;
30
31 /// Every class the corpus puts in a document, unprefixed.
32 ///
33 /// Scraped from `class="..."` rather than predicted, which is the point.
34 pub(crate) fn emitted() -> BTreeSet<String> {
35 emitted_with(&Emit::default())
36 }
37
38 /// [`emitted`], with the emit options a host would set.
39 fn emitted_with(opts: &Emit) -> BTreeSet<String> {
40 let mut found = BTreeSet::new();
41 for html in documents(opts) {
42 let mut rest = html.as_str();
43 while let Some(at) = rest.find("class=\"") {
44 rest = &rest[at + "class=\"".len()..];
45 let end = rest.find('"').expect("an attribute closes");
46 for name in rest[..end].split_whitespace() {
47 found.insert(name.to_owned());
48 }
49 rest = &rest[end..];
50 }
51 }
52 found
53 }
54
55 /// One document per emitter, over every input that changes what it writes.
56 ///
57 /// Every markup emitter this crate has is called here. A new one that is not
58 /// added is the one hole this guard has, which is why the list is short enough
59 /// to read: `placeholder`, `form`, `figure`, `facet`, `meter` and `list` are
60 /// the whole of what emits markup, and `lib.rs` writes rules rather than
61 /// documents.
62 fn documents(opts: &Emit) -> Vec<String> {
63 let mut out = vec![placeholders(opts), fields(opts), rows(opts)];
64 out.push(figures_html(
65 &[
66 Figure::new("42", "Tasks"),
67 Figure::new("12.5%", "Growth")
68 .change("+3")
69 .tone(Tone::Success),
70 ],
71 opts,
72 ));
73 for mode in [
74 Selecting::OneOf,
75 Selecting::AnyOf,
76 Selecting::Range,
77 Selecting::Text,
78 Selecting::Subtree,
79 ] {
80 let values = [
81 FacetValue::new("music", "Music")
82 .standing(Standing::Taken)
83 .counted(128)
84 .at(0, true),
85 FacetValue::new("music/synths", "Synths")
86 .standing(Standing::Inherited)
87 .at(1, false),
88 FacetValue::new("music/drums", "Drums")
89 .standing(Standing::Pruned)
90 .at(1, false),
91 FacetValue::new("talk", "Talk").at(0, false),
92 ];
93 out.push(facet_html(&Facet::new("Tag", mode, &values), opts));
94 }
95 // Toned, untoned, and over its total, which is the one state that adds an
96 // attribute of its own.
97 for meter in [
98 Meter::new(3, 7),
99 Meter::new(3, 7).tone(Tone::Success).label("subtasks"),
100 Meter::new(9, 7).tone(Tone::Danger),
101 ] {
102 out.push(meter_html(&meter, opts));
103 }
104 out
105 }
106
107 /// Every readiness, with and without the action a stand-in can carry.
108 fn placeholders(opts: &Emit) -> String {
109 let mut html = String::new();
110 for state in [
111 Readiness::Ready,
112 Readiness::Pending,
113 Readiness::Empty,
114 Readiness::Failed,
115 ] {
116 html.push_str(&placeholder_html(state, "Nothing here", None, opts));
117 html.push_str(&placeholder_html(
118 state,
119 "Nothing here",
120 Some(Markup("<button>Add one</button>")),
121 opts,
122 ));
123 }
124 html
125 }
126
127 /// Every field kind, twice: plain, and carrying everything a group can hold.
128 ///
129 /// The second pass is where the vocabulary lives. A hint, a unit and an error
130 /// each add a class, and an error adds two -- one on the message and one on the
131 /// group, which is `Field::invalid`'s own reasoning about a renderer that
132 /// cannot find the group from the message.
133 fn fields(opts: &Emit) -> String {
134 const OPTIONS: &[Choice<'_>] = &[
135 Choice::new("a", "The first"),
136 Choice::new("b", "The second").unless("Not while the first is running"),
137 ];
138 const ACCEPT: &[Accepted<'_>] = &[Accepted::Type("image/png"), Accepted::Suffix(".zip")];
139 // Two variants and two tiers, so the corpus carries a group boundary and a
140 // badge that is not the same badge twice. One theme per variant would emit
141 // one `<optgroup>` and prove nothing about where the next one opens.
142 const THEMES: &[ThemeChoice<'_>] = &[
143 ThemeChoice::new("goingson", "GoingsOn", ThemeVariant::Light, Contrast::High),
144 ThemeChoice::new("ayu-light", "Ayu Light", ThemeVariant::Light, Contrast::Low),
145 ThemeChoice::new("carbonfox", "Carbonfox", ThemeVariant::Dark, Contrast::High),
146 ThemeChoice::new("nord", "Nord", ThemeVariant::Dark, Contrast::Standard),
147 ];
148
149 let mut html = String::new();
150 for kind in [
151 FieldKind::Text,
152 FieldKind::Secret,
153 FieldKind::Number,
154 FieldKind::Range,
155 FieldKind::Interval,
156 FieldKind::Email,
157 FieldKind::Url,
158 FieldKind::Tel,
159 FieldKind::Date,
160 FieldKind::DateTime,
161 FieldKind::Textarea,
162 FieldKind::Rich,
163 FieldKind::Select,
164 FieldKind::Radio,
165 FieldKind::Checkbox,
166 FieldKind::File,
167 FieldKind::Theme,
168 FieldKind::Hidden,
169 ] {
170 let plain = Field {
171 options: OPTIONS,
172 themes: THEMES,
173 follows: Some(Choice::new("system", "Follow System")),
174 accept: ACCEPT,
175 upper_name: Some("upper"),
176 min: Some("0"),
177 max: Some("10"),
178 ..Field::new(kind, "name", "Label")
179 };
180 let dressed = Field {
181 hint: Some("What it is for"),
182 error: Some("That will not do"),
183 unit: Some("minutes"),
184 required: true,
185 ..plain
186 };
187 for field in [plain, dressed] {
188 for value in [
189 Value::Absent,
190 Value::Text("a"),
191 Value::On(true),
192 Value::Between {
193 lower: "1",
194 upper: "9",
195 },
196 ] {
197 html.push_str(&field_html(&field, &Filling::of(value), opts));
198 }
199 }
200 }
201 html
202 }
203
204 /// A cell of every width and every priority, and every part a cell can be.
205 ///
206 /// The width and the drop are the classes no source literal carries: they are
207 /// chosen from the column and pushed, which is how `cell-fill` came to be
208 /// emitted by every table in the tree and named by nothing.
209 fn rows(opts: &Emit) -> String {
210 let mut columns = Vec::new();
211 for (index, width) in [Width::Content, Width::Fixed, Width::Fill]
212 .into_iter()
213 .enumerate()
214 {
215 for (rank, priority) in [Priority::Optional, Priority::Secondary, Priority::Essential]
216 .into_iter()
217 .enumerate()
218 {
219 columns.push(Column {
220 width,
221 priority,
222 sortable: true,
223 sorted: Some(if rank % 2 == 0 {
224 Sort::Ascending
225 } else {
226 Sort::Descending
227 }),
228 ..Column::new(NAMES[index * 3 + rank])
229 });
230 }
231 }
232
233 let parts = [
234 None,
235 Some(CellPart::Value),
236 Some(CellPart::Tokens),
237 Some(CellPart::Actions),
238 Some(CellPart::Link),
239 ];
240 let mut html = String::new();
241 for part in parts {
242 let cells: Vec<Cell<'_>> = columns
243 .iter()
244 .map(|column| Cell {
245 column: column.name,
246 part,
247 content: Markup("<span>x</span>"),
248 })
249 .collect();
250 html.push_str(&cells_html(&columns, &cells, opts));
251 }
252 html
253 }
254
255 /// A name per column, so the nine are nine columns rather than one repeated.
256 const NAMES: [&str; 9] = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
257
258 #[cfg(test)]
259 mod tests {
260 use super::*;
261
262 #[test]
263 fn every_class_this_crate_emits_is_one_its_vocabulary_names() {
264 // The guard `MAKEOVER_UNLISTED` in quasi-webview was standing in for.
265 // A name emitted and not written down shrinks the set an app checks
266 // against, so the app concludes its live rules are dead -- silently,
267 // and in the direction that deletes styling rather than keeping too
268 // much of it.
269 let opts = Emit::default();
270 let names = crate::vocabulary::names(&opts);
271 let emitted = emitted();
272 assert!(
273 emitted.len() > 30,
274 "the corpus rendered {} classes, which reads as the corpus having \
275 stopped calling the emitters rather than the crate having shrunk",
276 emitted.len()
277 );
278
279 let stranger: Vec<&String> = emitted
280 .iter()
281 // The one open family, and it is this crate's: a cell carries a
282 // class built from its column's name, which is app data and which
283 // no set can hold. See `list::push_column_class`.
284 .filter(|class| !class.starts_with("col-"))
285 .filter(|class| !names.contains(*class))
286 .collect();
287 assert!(
288 stranger.is_empty(),
289 "{} class(es) emitted that `vocabulary::names` does not hold. Give \
290 them a rule, or add them to the unruled list `names` reads:\n{}",
291 stranger.len(),
292 stranger
293 .iter()
294 .map(|c| format!(" .{c}"))
295 .collect::<Vec<_>>()
296 .join("\n")
297 );
298 }
299
300 #[test]
301 fn a_class_prefix_reaches_every_class_but_the_states() {
302 // The same guard with a prefix set, which is a different question: a
303 // name that reached markup without going through `class` is prefixed
304 // nowhere and would pass the check above, then fail in the one app that
305 // sets a prefix. `names` answers for both, because it prefixes the
306 // written-down half and leaves the states alone.
307 let opts = Emit {
308 class_prefix: "mk-",
309 ..Emit::default()
310 };
311 let names = crate::vocabulary::names(&opts);
312 let stranger: Vec<String> = emitted_with(&opts)
313 .into_iter()
314 .filter(|class| !class.starts_with("mk-col-"))
315 .filter(|class| !names.contains(class))
316 .collect();
317 assert!(
318 stranger.is_empty(),
319 "{} class(es) a prefixed render emits that `vocabulary::names` does \
320 not hold:\n{}",
321 stranger.len(),
322 stranger
323 .iter()
324 .map(|c| format!(" .{c}"))
325 .collect::<Vec<_>>()
326 .join("\n")
327 );
328 }
329 }
330