Skip to main content

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.
16//!
17//! # Neither number is divided here
18//!
19//! `--meter-done` and `--meter-total` go out as themselves and `progress_rules`
20//! does the arithmetic. That is the property the residual seam needs, and
21//! [`chart`](crate::chart) states the reasoning in full: a residual is derived
22//! once from stand-in values, so a number this crate WORKS OUT from two of them
23//! is not a stand-in any filler can find, and one request's percentage bakes
24//! into the template. A number handed over whole stays a hole.
25//!
26//! It also retires `data-over`. That flag existed because a percentage was the
27//! only thing emitted, so the over-run had nowhere else to live; with both
28//! integers in the markup the comparison is there to be read, and a stylesheet
29//! that wants to react can make it where it uses it. Dropping it also clears a
30//! collision: quasi-webview writes `data-over="<selection>"` on a control, and
31//! goingson's `quasi-selection.js` selects `[data-over]` blind.
32//!
33//! What an over-run should look like stays app taste -- goingson says it with
34//! `Tone::Danger` -- and a renderer that picked a stripe for everyone would be
35//! decorating rather than describing.
36
37use crate::form::escape_into;
38use crate::{Emit, push_class};
39use makeover_layout::{Intent, Meter, Tone};
40use std::fmt::Write as _;
41
42/// Every class this module can put in markup.
43///
44/// [`crate::facet::FACET_CLASSES`]' obligation. Both carry rules, so the
45/// scraped vocabulary already holds them; the list is what keeps that true if
46/// a rule goes away.
47pub const METER_CLASSES: &[&str] = &["progress", "progress-fill"];
48
49/// The accessible name for a meter: the two numbers, and the noun if it has one.
50///
51/// The description carries the noun alone, so the sentence is built here. That
52/// is the whole reason `Meter::label` is not the assembled string: a tooltip
53/// wants "3 of 7 subtasks" and a terminal at one line wants "3/7", and a
54/// description that shipped either one would have chosen for both.
55///
56/// The true `done` is used, not the clamped one. This is the text that says an
57/// over-run happened.
58#[must_use]
59pub fn meter_text(meter: &Meter<'_>) -> String {
60    match meter.label {
61        Some(label) => format!("{} of {} {label}", meter.done, meter.total),
62        None => format!("{} of {}", meter.done, meter.total),
63    }
64}
65
66/// A meter as a filled trough.
67///
68/// ```
69/// use makeover_layout::{Meter, Tone};
70/// use makeover_webview::{Emit, meter::meter_html};
71///
72/// let meter = Meter::new(3, 7).tone(Tone::Success).label("subtasks");
73/// let html = meter_html(&meter, &Emit::default());
74///
75/// assert!(html.contains(r#"aria-label="3 of 7 subtasks""#));
76/// assert!(html.contains(r#"data-tone="success""#));
77/// // The two counts, not the 42% they come to: `progress_rules` divides.
78/// assert!(html.contains("--meter-done: 3; --meter-total: 7"));
79/// assert!(!html.contains("--meter-fill"));
80/// ```
81///
82/// `aria-valuenow` is `done` as it stands, so an over-run reports above
83/// `aria-valuemax`. The clamp that used to sit here was a derivation and could
84/// not survive a residual; see [`meter_html_into`] for the whole argument.
85#[must_use]
86pub fn meter_html(meter: &Meter<'_>, opts: &Emit) -> String {
87    let mut html = String::new();
88    meter_html_into(meter, opts, &mut html);
89    html
90}
91
92/// A meter, written into a buffer the caller already has.
93///
94/// [`meter_html`]'s streaming form, byte-identical to it. The accessible name is
95/// written a piece at a time rather than built and then escaped: the numbers
96/// carry nothing an escaper would encode, so only the noun goes through one.
97pub fn meter_html_into(meter: &Meter<'_>, opts: &Emit, out: &mut String) {
98    out.push_str("<div class=\"");
99    push_class(out, "progress", opts);
100    // `aria-valuenow` is `done` as it stands, not `done.min(total)`. The clamp
101    // was a derivation, so it baked one request's value into a residual where
102    // the raw number is a hole -- and a stylesheet cannot write an attribute,
103    // so moving the width into CSS would not have reached it.
104    //
105    // An over-run therefore reports a value above `aria-valuemax`, which ARIA
106    // calls out of range. That is the honest reading: a progressbar whose value
107    // exceeds its maximum is what an over-run IS, and clamping is the renderer
108    // deciding a screen-reader user should not be told what the sighted reader
109    // can see. The accessible name below carries both true numbers either way.
110    let _ = write!(
111        out,
112        "\" role=\"progressbar\" aria-valuenow=\"{}\" \
113         aria-valuemin=\"0\" aria-valuemax=\"{}\" aria-label=\"{} of {}",
114        meter.done, meter.total, meter.done, meter.total
115    );
116    if let Some(label) = meter.label {
117        out.push(' ');
118        escape_into(label, out);
119    }
120    out.push_str("\">");
121
122    out.push_str("<div class=\"");
123    push_class(out, "progress-fill", opts);
124    out.push('"');
125    // Neutral is the untoned bar, and `progress_rules` gives it `--action`
126    // rather than a tone attribute. Emitting `data-tone="content-muted"` would
127    // match a rule that does not exist and read as disabled if it did.
128    if meter.tone != Tone::Neutral {
129        let _ = write!(out, " data-tone=\"{}\"", meter.tone.token());
130    }
131    // The two counts as custom properties the trough's rule divides, in
132    // `data-vars` rather than `style`: see [`crate::VARS_ATTR`]. Not the fill:
133    // see the module header for why nothing is divided here.
134    let _ = write!(
135        out,
136        " {}=\"--meter-done: {}; --meter-total: {}\"></div></div>",
137        crate::VARS_ATTR,
138        meter.done,
139        meter.total
140    );
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::form::escape;
147
148    /// The accessible name is built by [`meter_text`] in one form and written a
149    /// piece at a time in the other, and the over-run case is the one where the
150    /// numbers differ from what the bar draws.
151    #[test]
152    fn a_streamed_meter_is_the_meter_the_other_form_returns() {
153        let opts = Emit {
154            class_prefix: "mk-",
155            ..Emit::default()
156        };
157        for meter in [
158            Meter::new(0, 0),
159            Meter::new(3, 7).label("sub & tasks"),
160            Meter::new(9, 7).tone(Tone::Danger).label("<tasks>"),
161        ] {
162            let mut streamed = String::new();
163            meter_html_into(&meter, &opts, &mut streamed);
164            assert_eq!(streamed, meter_html(&meter, &opts));
165            assert!(
166                streamed.contains(&format!("aria-label=\"{}\"", escape(&meter_text(&meter)))),
167                "{streamed}"
168            );
169        }
170    }
171
172    #[test]
173    fn a_full_bar_says_whether_it_ran_over() {
174        // The two facts a percentage could not tell apart, and the reason the
175        // description carries a pair. Both draw a full bar -- the rule clamps
176        // with `min` -- and the markup still tells them apart, now because both
177        // counts are in it rather than because a flag was bolted on.
178        let exact = meter_html(&Meter::new(30, 30), &Emit::default());
179        let over = meter_html(&Meter::new(45, 30), &Emit::default());
180
181        assert!(
182            exact.contains("--meter-done: 30; --meter-total: 30"),
183            "{exact}"
184        );
185        assert!(
186            over.contains("--meter-done: 45; --meter-total: 30"),
187            "{over}"
188        );
189        assert!(!exact.contains("style="));
190
191        // No percentage is emitted at all: that is what lets a meter cross a
192        // residual. If this ever comes back, the seam quietly closes again.
193        assert!(!exact.contains("--meter-fill"), "{exact}");
194        assert!(!over.contains("--meter-fill"), "{over}");
195
196        // `data-over` is retired, on both the exact and the over-run bar. The
197        // spelling belongs to quasi-webview's `Act::over` now, and goingson's
198        // selection script selects it blind.
199        assert!(!exact.contains("data-over"), "{exact}");
200        assert!(!over.contains("data-over"), "{over}");
201    }
202
203    #[test]
204    fn the_accessible_name_keeps_the_number_the_bar_cannot_show() {
205        // The bar is clamped and the name is not. Losing this is how an
206        // over-run becomes invisible to anyone not looking at the colour.
207        let over = Meter::new(45, 30).label("minutes");
208        assert_eq!(meter_text(&over), "45 of 30 minutes");
209        assert!(meter_html(&over, &Emit::default()).contains(r#"aria-label="45 of 30 minutes""#));
210    }
211
212    #[test]
213    fn aria_valuenow_reports_the_over_run_rather_than_clamping_it() {
214        // This test used to assert the opposite, and the reversal is deliberate
215        // rather than a relaxation, so the reason is written down here.
216        //
217        // `aria-valuenow` was `done.min(total)`. That is a number worked out
218        // from two others, so it could not be a residual stand-in: one
219        // request's clamped value baked into the template. Moving the width
220        // into the stylesheet does not reach it, because a stylesheet cannot
221        // write an attribute -- this was the last derivation in the emitter.
222        //
223        // The cost is real and accepted: on an over-run the value sits above
224        // the maximum, which ARIA calls out of range. The alternative is the
225        // renderer deciding a screen-reader user should not be told what the
226        // sighted reader can see, and `aria-label` carries both true numbers
227        // either way (pinned by the test above).
228        let html = meter_html(&Meter::new(45, 30), &Emit::default());
229        assert!(html.contains(r#"aria-valuenow="45""#), "{html}");
230        assert!(html.contains(r#"aria-valuemax="30""#), "{html}");
231
232        // A bar that did not run over reports exactly what it always did, so
233        // the change is confined to the case that was being misreported.
234        let under = meter_html(&Meter::new(3, 7), &Emit::default());
235        assert!(under.contains(r#"aria-valuenow="3""#), "{under}");
236        assert!(under.contains(r#"aria-valuemax="7""#), "{under}");
237    }
238
239    #[test]
240    fn an_untoned_bar_emits_no_tone_attribute() {
241        // `progress_rules` styles the untoned bar with `--action` on the bare
242        // class. A `data-tone="content-muted"` here would match no rule.
243        let plain = meter_html(&Meter::new(1, 2), &Emit::default());
244        assert!(!plain.contains("data-tone"));
245
246        let toned = meter_html(&Meter::new(1, 2).tone(Tone::Danger), &Emit::default());
247        assert!(toned.contains(r#"data-tone="danger""#));
248    }
249
250    #[test]
251    fn an_empty_set_renders_an_empty_trough() {
252        // Sayable, so it has to be emittable. The emitter no longer divides at
253        // all, so the zero case cannot fault here; what it has to get right is
254        // that the RULE survives it, which `the_progress_trough_has_a_height_
255        // the_fill_fills` pins by reading the emitted `max(..., 1)` divisor.
256        let html = meter_html(&Meter::new(0, 0), &Emit::default());
257        assert!(html.contains("--meter-done: 0; --meter-total: 0"), "{html}");
258        assert!(html.contains(r#"aria-valuemax="0""#));
259    }
260
261    #[test]
262    fn the_label_is_escaped_like_every_other_string() {
263        // It arrives from the app the same as a field label does.
264        let html = meter_html(&Meter::new(1, 2).label("a & b"), &Emit::default());
265        assert!(html.contains("a &amp; b"));
266        assert!(!html.contains("a & b"));
267    }
268
269    #[test]
270    fn the_prefix_reaches_both_classes() {
271        // A prefixed build claims its own names, and the fill is a descendant
272        // selector in the emitted CSS: miss one and the rule stops matching.
273        let opts = Emit {
274            class_prefix: "mo-",
275            ..Emit::default()
276        };
277        let html = meter_html(&Meter::new(1, 2), &opts);
278        assert!(html.contains(r#"class="mo-progress""#));
279        assert!(html.contains(r#"class="mo-progress-fill""#));
280    }
281}