makeover_webview/meter.rs
1//! A proportion, rendered as a bar.
2//!
3//! The third phase-B emitter, beside [`form`](crate::form) and
4//! [`list`](crate::list). It is much the smallest, and it is here rather than in
5//! the app because the trough it fills has been in phase A since before anything
6//! could describe one: `progress_rules` emitted `.progress` and
7//! `.progress-fill[data-tone]` for every tone while the only way to say "3 of 7"
8//! was to concatenate it into a heading.
9//!
10//! # What the pair buys, at the last layer
11//!
12//! `makeover_layout::Meter` carries `done` and `total` rather than a percentage,
13//! and the reason shows up here. A bar that is full because it landed exactly
14//! and a bar that is full because it ran over are the same width and are not the
15//! same fact, so the width is not allowed to be the only thing emitted. The
16//! over-run leaves as `data-over="true"`, and the accessible name keeps both
17//! true numbers.
18//!
19//! No CSS rule is emitted for `data-over`. What an over-run should look like is
20//! app taste — goingson already says it with `Tone::Danger` — and a renderer
21//! that picked a stripe for everyone would be decorating rather than describing.
22
23use crate::form::escape_into;
24use crate::{Emit, push_class};
25use makeover_layout::{Intent, Meter, Tone};
26use std::fmt::Write as _;
27
28/// The accessible name for a meter: the two numbers, and the noun if it has one.
29///
30/// The description carries the noun alone, so the sentence is built here. That
31/// is the whole reason `Meter::label` is not the assembled string: a tooltip
32/// wants "3 of 7 subtasks" and a terminal at one line wants "3/7", and a
33/// description that shipped either one would have chosen for both.
34///
35/// The true `done` is used, not the clamped one. This is the text that says an
36/// over-run happened.
37#[must_use]
38pub fn meter_text(meter: &Meter<'_>) -> String {
39 match meter.label {
40 Some(label) => format!("{} of {} {label}", meter.done, meter.total),
41 None => format!("{} of {}", meter.done, meter.total),
42 }
43}
44
45/// A meter as a filled trough.
46///
47/// ```
48/// use makeover_layout::{Meter, Tone};
49/// use makeover_webview::{Emit, meter::meter_html};
50///
51/// let meter = Meter::new(3, 7).tone(Tone::Success).label("subtasks");
52/// let html = meter_html(&meter, &Emit::default());
53///
54/// assert!(html.contains(r#"aria-label="3 of 7 subtasks""#));
55/// assert!(html.contains(r#"data-tone="success""#));
56/// assert!(html.contains("width: 42%"));
57/// ```
58///
59/// `aria-valuenow` is clamped to `aria-valuemax`, because a value outside the
60/// range is invalid ARIA and a screen reader is entitled to ignore the whole
61/// element. The unclamped truth is in the accessible name, which is read either
62/// way.
63#[must_use]
64pub fn meter_html(meter: &Meter<'_>, opts: &Emit) -> String {
65 let mut html = String::new();
66 meter_html_into(meter, opts, &mut html);
67 html
68}
69
70/// A meter, written into a buffer the caller already has.
71///
72/// [`meter_html`]'s streaming form, byte-identical to it. The accessible name is
73/// written a piece at a time rather than built and then escaped: the numbers
74/// carry nothing an escaper would encode, so only the noun goes through one.
75pub fn meter_html_into(meter: &Meter<'_>, opts: &Emit, out: &mut String) {
76 let reported = meter.done.min(meter.total);
77
78 out.push_str("<div class=\"");
79 push_class(out, "progress", opts);
80 let _ = write!(
81 out,
82 "\" role=\"progressbar\" aria-valuenow=\"{reported}\" \
83 aria-valuemin=\"0\" aria-valuemax=\"{}\" aria-label=\"{} of {}",
84 meter.total, meter.done, meter.total
85 );
86 if let Some(label) = meter.label {
87 out.push(' ');
88 escape_into(label, out);
89 }
90 out.push_str("\">");
91
92 out.push_str("<div class=\"");
93 push_class(out, "progress-fill", opts);
94 out.push('"');
95 // Neutral is the untoned bar, and `progress_rules` gives it `--action`
96 // rather than a tone attribute. Emitting `data-tone="content-muted"` would
97 // match a rule that does not exist and read as disabled if it did.
98 if meter.tone != Tone::Neutral {
99 let _ = write!(out, " data-tone=\"{}\"", meter.tone.token());
100 }
101 if meter.overflowing() {
102 out.push_str(" data-over=\"true\"");
103 }
104 let _ = write!(out, " style=\"width: {}%\"></div></div>", meter.percent());
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110 use crate::form::escape;
111
112 /// The accessible name is built by [`meter_text`] in one form and written a
113 /// piece at a time in the other, and the over-run case is the one where the
114 /// numbers differ from what the bar draws.
115 #[test]
116 fn a_streamed_meter_is_the_meter_the_other_form_returns() {
117 let opts = Emit {
118 class_prefix: "mk-",
119 ..Emit::default()
120 };
121 for meter in [
122 Meter::new(0, 0),
123 Meter::new(3, 7).label("sub & tasks"),
124 Meter::new(9, 7).tone(Tone::Danger).label("<tasks>"),
125 ] {
126 let mut streamed = String::new();
127 meter_html_into(&meter, &opts, &mut streamed);
128 assert_eq!(streamed, meter_html(&meter, &opts));
129 assert!(
130 streamed.contains(&format!("aria-label=\"{}\"", escape(&meter_text(&meter)))),
131 "{streamed}"
132 );
133 }
134 }
135
136 #[test]
137 fn a_full_bar_says_whether_it_ran_over() {
138 // The two facts a percentage could not tell apart, and the reason the
139 // description carries a pair. Both are 100% wide.
140 let exact = meter_html(&Meter::new(30, 30), &Emit::default());
141 let over = meter_html(&Meter::new(45, 30), &Emit::default());
142
143 assert!(exact.contains("width: 100%"));
144 assert!(over.contains("width: 100%"));
145 assert!(!exact.contains("data-over"));
146 assert!(over.contains(r#"data-over="true""#));
147 }
148
149 #[test]
150 fn the_accessible_name_keeps_the_number_the_bar_cannot_show() {
151 // The bar is clamped and the name is not. Losing this is how an
152 // over-run becomes invisible to anyone not looking at the colour.
153 let over = Meter::new(45, 30).label("minutes");
154 assert_eq!(meter_text(&over), "45 of 30 minutes");
155 assert!(meter_html(&over, &Emit::default()).contains(r#"aria-label="45 of 30 minutes""#));
156 }
157
158 #[test]
159 fn aria_valuenow_stays_inside_its_range() {
160 // Outside it, the element is invalid and a reader may drop it whole,
161 // which would lose the label above along with it.
162 let html = meter_html(&Meter::new(45, 30), &Emit::default());
163 assert!(html.contains(r#"aria-valuenow="30""#));
164 assert!(html.contains(r#"aria-valuemax="30""#));
165 }
166
167 #[test]
168 fn an_untoned_bar_emits_no_tone_attribute() {
169 // `progress_rules` styles the untoned bar with `--action` on the bare
170 // class. A `data-tone="content-muted"` here would match no rule.
171 let plain = meter_html(&Meter::new(1, 2), &Emit::default());
172 assert!(!plain.contains("data-tone"));
173
174 let toned = meter_html(&Meter::new(1, 2).tone(Tone::Danger), &Emit::default());
175 assert!(toned.contains(r#"data-tone="danger""#));
176 }
177
178 #[test]
179 fn an_empty_set_renders_an_empty_trough() {
180 // Sayable, so it has to be emittable. Nothing here divides by zero.
181 let html = meter_html(&Meter::new(0, 0), &Emit::default());
182 assert!(html.contains("width: 0%"));
183 assert!(html.contains(r#"aria-valuemax="0""#));
184 }
185
186 #[test]
187 fn the_label_is_escaped_like_every_other_string() {
188 // It arrives from the app the same as a field label does.
189 let html = meter_html(&Meter::new(1, 2).label("a & b"), &Emit::default());
190 assert!(html.contains("a & b"));
191 assert!(!html.contains("a & b"));
192 }
193
194 #[test]
195 fn the_prefix_reaches_both_classes() {
196 // A prefixed build claims its own names, and the fill is a descendant
197 // selector in the emitted CSS: miss one and the rule stops matching.
198 let opts = Emit {
199 class_prefix: "mo-",
200 ..Emit::default()
201 };
202 let html = meter_html(&Meter::new(1, 2), &opts);
203 assert!(html.contains(r#"class="mo-progress""#));
204 assert!(html.contains(r#"class="mo-progress-fill""#));
205 }
206}