makeover_layout/figure.rs
1use crate::Tone;
2
3// Names this module's prose links to, resolved for rustdoc.
4#[allow(unused_imports)]
5use crate::{Choice, Notice, Readiness};
6
7/// How much of a set is done.
8///
9/// Nine sites across the two webview apps drew a bar and nothing here named
10/// one, so every described screen concatenated the two numbers into its
11/// heading text instead: "Subtasks 3/7", "Time Tracking 45m tracked / 30m est,
12/// over". Every fact survives that and the reading does not, which is the same
13/// loss `RowPart::Tokens` closed when a toned status badge became prose.
14///
15/// # Why a pair and not a percentage
16///
17/// Both numbers, not the percentage the apps compute from them. The percentage
18/// was the obvious shape and it had already been tried: goingson's
19/// `Task::time_progress` divides, rounds, and then clamps to 100, which throws
20/// away the one case the bar exists to show — 45 minutes tracked against a
21/// 30-minute estimate. It carries a separate `is_over_estimate` boolean beside
22/// it to recover the fact the clamp dropped. A pair keeps the over-run without a
23/// companion flag, and [`percent`](Meter::percent) is still one call away for a
24/// renderer that wants it.
25///
26/// The pair is also what the apps already have at every site. All seven
27/// determinate bars write the ratio into the accessible layer and never the
28/// percentage: `title="3/7 subtasks"`, `aria-label="3 of 7 subtasks completed"`,
29/// a milestone's own `3/7` span. Given 43 nothing can recover "3 of 7", so a
30/// percentage member would have made [`label`](Meter::label) mandatory at every
31/// call site, which is the concatenated text this member removes, moved one
32/// layer down.
33///
34/// # What this is not
35///
36/// The progress of an *operation*. Two of the nine sites are that — goingson's
37/// focus timer, Balanced Breakfast's feed fetch — and they get nothing here, on
38/// purpose. Both are imperative controllers over a live handle, driven by a tick
39/// or an event stream, and a description is built once and dropped. Holding one
40/// would mean growing a way to update a description between renders, which is a
41/// different feature. [`Readiness::Pending`] and a [`Notice::Toast`] carry the
42/// honest part.
43///
44/// The two cases are distinguishable in the markup rather than by taste: every
45/// determinate bar in both apps carries a tone, and neither operation bar
46/// carries one. Two codebases drew that line the same way without coordinating.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub struct Meter<'a> {
49 /// How much is done. May exceed [`total`](Self::total), and that is the
50 /// case worth drawing.
51 ///
52 /// `usize` rather than `u32` because a meter has to be able to cross a
53 /// residual: a stand-in number is a six-digit opening and ten digits after
54 /// it, which does not fit in a `u32`. [`Chart::most`](crate::Chart) carries
55 /// its magnitude for the same reason. Apps counting a `Vec` had been
56 /// narrowing with a saturating `try_from` to reach the old type, so this is
57 /// the width they already had.
58 pub done: usize,
59 /// How much there is to do. Zero means there is no set, not that the set is
60 /// complete.
61 pub total: usize,
62 /// What the proportion means right now.
63 ///
64 /// Carried rather than derived, because no renderer can work it out. The
65 /// same 90% is [`Tone::Success`] on a subtask rollup and [`Tone::Danger`] on
66 /// a time estimate, and goingson picks between them from `is_over_estimate`,
67 /// a fact about the data and not about the number.
68 pub tone: Tone,
69 /// What is being counted, if the bar says so: "subtasks", "tasks".
70 ///
71 /// The noun, not the ratio. A renderer builds "3 of 7 subtasks" from this
72 /// and the two numbers; handing it the assembled string would put the
73 /// sentence order in the description, where a terminal at one line and a
74 /// tooltip want different ones.
75 pub label: Option<&'a str>,
76}
77
78impl<'a> Meter<'a> {
79 /// A proportion with no tone and no label.
80 #[must_use]
81 pub const fn new(done: usize, total: usize) -> Self {
82 Self {
83 done,
84 total,
85 tone: Tone::Neutral,
86 label: None,
87 }
88 }
89
90 /// What the proportion means.
91 #[must_use]
92 pub const fn tone(mut self, tone: Tone) -> Self {
93 self.tone = tone;
94 self
95 }
96
97 /// What is being counted.
98 #[must_use]
99 pub const fn label(mut self, label: &'a str) -> Self {
100 self.label = Some(label);
101 self
102 }
103
104 /// How full the bar is, 0 to 100, clamped.
105 ///
106 /// For drawing, which is the only thing a clamped number is good for. Ask
107 /// [`overflowing`](Self::overflowing) before reporting it as a fact, or this
108 /// is `time_progress`'s bug again with the clamp moved.
109 ///
110 /// An empty set reads as 0. Nothing is done, because there is nothing to do
111 /// and no bar to fill; the apps guard on the count before drawing at all.
112 #[must_use]
113 pub const fn percent(&self) -> u8 {
114 if self.total == 0 {
115 return 0;
116 }
117 let scaled = (self.done as u128 * 100) / self.total as u128;
118 if scaled > 100 { 100 } else { scaled as u8 }
119 }
120
121 /// Whether more is done than there was to do.
122 ///
123 /// The fact [`percent`](Self::percent) destroys, kept reachable so a
124 /// renderer can mark the over-run rather than drawing a full bar and
125 /// implying it landed exactly.
126 #[must_use]
127 pub const fn overflowing(&self) -> bool {
128 self.done > self.total
129 }
130
131 /// Whether there is a set at all.
132 ///
133 /// A meter over nothing is sayable on purpose, for the same reason a field
134 /// with no options is: it is what an app with an unloaded count actually
135 /// has, and a renderer that shows an empty bar says so on screen rather than
136 /// dividing by zero.
137 #[must_use]
138 pub const fn is_empty(&self) -> bool {
139 self.total == 0
140 }
141}
142
143/// One figure with a caption: a number and what it counts.
144///
145/// The dashboard shape. A large value over a small caption, several of them in
146/// a strip: a current streak, a completion rate, a total. Four put the value
147/// above the caption and one inverts it, which is drift inside the shape
148/// rather than a second shape.
149///
150/// # Why the value is text
151///
152/// "17", "84%", "12/30", "3d". A figure is whatever the app computed, already
153/// formatted, and the formatting is the app's because only it knows whether the
154/// number is a percentage, a duration or a ratio. This carries none of the
155/// arithmetic [`Meter`] carries, and that is the difference between them: a
156/// meter is a proportion a renderer draws, and a figure is a fact a renderer
157/// sets in type.
158///
159/// # Tone is carried, for [`Meter`]'s reason
160///
161/// Three of the five sites tone the figure by their own means — `red`/`blue` on
162/// the weekly review, a `${type}` class on the monthly one, `sync-stat-warn` on
163/// sync. So tone is carried at every site that needs it and derived at none, and
164/// no renderer can work out that a streak of zero is worth colouring.
165///
166/// # What is not here
167///
168/// Whether the figure answers a click. One of the five is a control — sync's
169/// "Not Applied: 3" opens the list — and an action is not something this crate
170/// can name: nothing here knows what a route is. That belongs beside the figure
171/// in whatever layer holds the actions, the same way a row's activation sits
172/// beside its parts rather than inside them.
173///
174/// The arrangement is not here either. Several figures in a strip is a set, and
175/// a renderer given them one at a time cannot tell it is looking at one; the
176/// layer that holds the tree is where the set gets said.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
178pub struct Figure<'a> {
179 /// The number, formatted the way the app means it to read.
180 pub value: &'a str,
181 /// What it counts. The caption under the value.
182 pub caption: &'a str,
183 /// How the value has moved, if the app is tracking that.
184 ///
185 /// Text, for [`value`](Self::value)'s reason: only the app knows whether a
186 /// move reads as `+12.5%`, `+3` or `2x`, and a renderer handed a number
187 /// would have to guess.
188 ///
189 /// This is what [`tone`](Self::tone) was for and had no consumer of. The MNW
190 /// server has four screens whose stat card is a label, a value and a delta,
191 /// and the delta is the toned part: the figure itself is an ordinary fact
192 /// and it is the movement that reads as good or bad. Without this the delta
193 /// has to be folded into the caption, which loses the tone and reads as a
194 /// longer caption rather than as a second, smaller line.
195 pub change: Option<&'a str>,
196 /// What the figure means right now. [`Tone::Neutral`] is an ordinary fact.
197 ///
198 /// Applies to [`change`](Self::change) where there is one, since that is the
199 /// part that carries the judgement, and to the value where there is not.
200 pub tone: Tone,
201}
202
203impl<'a> Figure<'a> {
204 /// A figure that is an ordinary fact.
205 #[must_use]
206 pub const fn new(value: &'a str, caption: &'a str) -> Self {
207 Self {
208 value,
209 caption,
210 change: None,
211 tone: Tone::Neutral,
212 }
213 }
214
215 /// How the value has moved.
216 #[must_use]
217 pub const fn change(mut self, change: &'a str) -> Self {
218 self.change = Some(change);
219 self
220 }
221
222 /// What the figure means.
223 #[must_use]
224 pub const fn tone(mut self, tone: Tone) -> Self {
225 self.tone = tone;
226 self
227 }
228}
229
230/// Something the user can do, and what it costs to say so.
231///
232/// Beside [`Meter`] and [`Figure`] for the reason those are here: a renderer
233/// that is handed the parts has to decide how to say them, and a renderer that
234/// is handed a finished string has already had the decision made for it.
235///
236/// No address. Where a control goes is the app's business and every host
237/// follows it differently — an `hx-get`, a protocol URL, a function call — so
238/// the description says what the control *is* and the caller keeps what it
239/// does. That is the same split [`Choice`] makes.
240///
241/// No confirmation flag either, and that one is a finding rather than an
242/// omission: a question asked *after* a control is pressed belongs to whatever
243/// is holding the interaction, and a renderer that drew it would be asking
244/// before there was anything to answer.
245/// How a picture sits in the box it is given.
246///
247/// An intent rather than a value, so a renderer picks the expression it has:
248/// `object-fit` in a webview, a texture's UV rect in egui, and in a terminal a
249/// choice about how many cells the blit gets. Named because MNW already makes
250/// the distinction deliberately at 17 sites and makes it three different ways,
251/// which is a policy the app decided rather than one a shared crate would be
252/// picking by accident.
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
254#[non_exhaustive]
255pub enum Fit {
256 /// The picture's own proportions, and the box takes the height they imply.
257 ///
258 /// The default because it is the only one that shows the whole picture at
259 /// its own shape, so a renderer that ignores this enum entirely is still
260 /// right about the common case. A screenshot wants this; the shipped MNW
261 /// carousel sets no `object-fit` at all, which is this.
262 #[default]
263 Natural,
264 /// Fill the box and crop whatever does not fit.
265 ///
266 /// For a picture in a slot whose shape the layout fixed: a thumbnail, an
267 /// avatar, cover art. 15 of MNW's 17 sites.
268 Cover,
269 /// Fit inside the box whole, leaving space on two sides.
270 ///
271 /// The letterbox. For when the whole picture matters more than filling the
272 /// space, and the space is not the picture's shape.
273 Contain,
274}
275
276/// A picture's own pixel dimensions.
277///
278/// Deliberately not [`makeover_geometry`]'s business. Geometry answers *how
279/// much space a thing should get*, which is a scale question with the same
280/// answer on every screen. This is the intrinsic size of one asset, which is a
281/// fact about that asset and varies per picture.
282///
283/// [`makeover_geometry`]: https://docs.rs/makeover-geometry
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
285pub struct Extent {
286 /// Width in the picture's own pixels.
287 pub width: u32,
288 /// Height in the picture's own pixels.
289 pub height: u32,
290}
291
292impl Extent {
293 /// A picture's dimensions.
294 #[must_use]
295 pub const fn new(width: u32, height: u32) -> Self {
296 Self { width, height }
297 }
298
299 /// Width over height, or `None` if either side is zero.
300 ///
301 /// The form a renderer actually reserves space with: a box that knows its
302 /// proportion holds the right height at any width, which is what a
303 /// responsive picture needs and what a fixed pixel height cannot give.
304 #[must_use]
305 pub fn ratio(self) -> Option<f32> {
306 (self.width > 0 && self.height > 0).then(|| self.width as f32 / self.height as f32)
307 }
308}
309
310/// A run of magnitudes read against one axis.
311///
312/// [`Meter`] is one proportion; this is a series of them that share a maximum,
313/// and the shared maximum is the whole difference. A run of meters draws each
314/// bar against its own `total`, so a chart said that way states the axis once
315/// per bar and nothing holds the copies together. Here the axis is stated once
316/// and a bar carries only where it sits on it.
317///
318/// # Why the axis and not a percentage per bar
319///
320/// [`Meter`]'s reason, one layer out. The app that drew MNW's revenue chart
321/// computed `revenue / most * 100.0` and put the percentage in the markup, and
322/// what reached the reader was a width with no numbers behind it: a bar at 100%
323/// because it is the largest and a bar at 100% because the axis is wrong are the
324/// same width and are not the same fact. Carrying both integers keeps the fact,
325/// and [`Bar::fraction`] is one call away for a renderer that wants the ratio.
326///
327/// It is also the only shape that survives a compiled template. A residual holds
328/// numbers the description HANDS a renderer, never ones a renderer works out
329/// from two of them, so a chart drawn from a supplied percentage could be
330/// described and could not be compiled. See `quasi_router::stage::number_at`.
331///
332/// # What is worded here and what is not
333///
334/// [`Bar::at`] is where the bar sits on the axis and [`label`](Self::label) is
335/// what the magnitudes are, which is [`Meter::label`]'s split exactly. What
336/// differs is [`Bar::reading`] and [`Bar::note`]: both arrive already worded,
337/// because a magnitude's own units are the app's ("$42.10", not 4210) and a
338/// count's noun inflects ("1 sale", "3 sales"). A renderer that pluralised
339/// would be growing a lexer for one language.
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
341pub struct Chart<'a> {
342 /// The magnitude the axis runs to. Every bar is read against this.
343 ///
344 /// Zero means there is no axis, not that every bar is full. A renderer draws
345 /// nothing rather than dividing by it; see [`is_empty`](Self::is_empty).
346 ///
347 /// `usize` because that is what a description counts in -- a pager's offset
348 /// and page size are the same -- and because it is the only width
349 /// `quasi_router::stage::number_at` has a stand-in for, which is what lets a
350 /// chart reach a compiled template at all.
351 pub most: usize,
352 /// What the magnitudes are: "revenue", "plays".
353 ///
354 /// The noun, not the unit and not the ratio. The unit is already in each
355 /// [`Bar::reading`], where it belongs, because only the app knows it.
356 pub label: Option<&'a str>,
357 /// What the axis means, where it means anything.
358 pub tone: Tone,
359}
360
361impl<'a> Chart<'a> {
362 /// An axis running to `most`, untoned and unlabelled.
363 #[must_use]
364 pub const fn new(most: usize) -> Self {
365 Self {
366 most,
367 label: None,
368 tone: Tone::Neutral,
369 }
370 }
371
372 /// What the magnitudes are.
373 #[must_use]
374 pub const fn label(mut self, label: &'a str) -> Self {
375 self.label = Some(label);
376 self
377 }
378
379 /// What the axis means.
380 #[must_use]
381 pub const fn tone(mut self, tone: Tone) -> Self {
382 self.tone = tone;
383 self
384 }
385
386 /// Whether there is an axis to read against.
387 ///
388 /// [`Meter::is_empty`]'s case: an axis running to zero is what an app with
389 /// nothing to chart actually has, and saying so beats dividing by it.
390 #[must_use]
391 pub const fn is_empty(&self) -> bool {
392 self.most == 0
393 }
394}
395
396/// One magnitude in a [`Chart`], at its place on the axis.
397///
398/// Carries no axis of its own on purpose: a bar read against a maximum it
399/// states itself is a meter, and a run of those is not a chart.
400#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
401pub struct Bar<'a> {
402 /// Where on the axis this sits: "Mar 3", "Week 12".
403 ///
404 /// The position's own name rather than an index, for the reason a pager's
405 /// jump carries its page number: what a chart shows is a window over a
406 /// series, and an index into that window is not the point it names.
407 pub at: &'a str,
408 /// The magnitude, in the chart's units, read against [`Chart::most`].
409 pub value: usize,
410 /// The magnitude as the app words it: "$42.10".
411 ///
412 /// Worded rather than derived because the units are the app's. A renderer
413 /// handed 4210 cannot know it is money, let alone which money.
414 pub reading: Option<&'a str>,
415 /// A second fact about this bar, already worded: "3 sales".
416 ///
417 /// Worded for the reason [`reading`](Self::reading) is, plus one of its own:
418 /// a count's noun inflects with the count, and that is language rather than
419 /// drawing.
420 pub note: Option<&'a str>,
421}
422
423impl<'a> Bar<'a> {
424 /// A place on the axis, with no magnitude on it yet.
425 ///
426 /// The magnitude arrives through [`of`](Self::of) rather than as a second
427 /// argument, and that is not stylistic: `quasi-declare` stages a
428 /// constructor's plain arguments all one way or all the other, so a
429 /// constructor taking a place AND a magnitude would have the place standing
430 /// in as a number. Split, the place is a value and `of` is a count, which is
431 /// the same split a pager's `of` makes and the reason it is spelled the
432 /// same.
433 #[must_use]
434 pub const fn at(at: &'a str) -> Self {
435 Self {
436 at,
437 value: 0,
438 reading: None,
439 note: None,
440 }
441 }
442
443 /// How far up the axis this bar reaches.
444 #[must_use]
445 pub const fn of(mut self, value: usize) -> Self {
446 self.value = value;
447 self
448 }
449
450 /// How the app words this magnitude.
451 #[must_use]
452 pub const fn reading(mut self, reading: &'a str) -> Self {
453 self.reading = Some(reading);
454 self
455 }
456
457 /// A second fact about the bar, already worded.
458 #[must_use]
459 pub const fn note(mut self, note: &'a str) -> Self {
460 self.note = Some(note);
461 self
462 }
463
464 /// How far up the axis this bar reaches, 0.0 to 1.0, clamped.
465 ///
466 /// For drawing, which is what a clamped number is good for, and for the two
467 /// renderers that draw in cells and pixels rather than in CSS. An empty axis
468 /// reads as 0.0 rather than dividing by zero.
469 ///
470 /// A bar over [`Chart::most`] clamps, and unlike [`Meter`] that is not a
471 /// fact being lost: `most` is the maximum of the bars, so a bar above it is
472 /// an axis the app got wrong rather than an over-run worth drawing.
473 #[must_use]
474 pub fn fraction(&self, chart: &Chart<'_>) -> f32 {
475 if chart.most == 0 {
476 return 0.0;
477 }
478 (self.value as f64 / chart.most as f64).min(1.0) as f32
479 }
480}