Skip to main content

makeover_layout/
region.rs

1use crate::Depth;
2
3// Names this module's prose links to, resolved for rustdoc.
4#[allow(unused_imports)]
5use crate::{Fill, Heading, Readiness, RowPart, Selector, Sort, Track};
6
7/// A named part of a screen.
8///
9/// The thing `makeover-geometry` deliberately does not name: it names the space
10/// *between* things by relationship, and nothing named the things. Six named
11/// members, taken from what the two webview apps actually use, plus
12/// [`Region::Handover`] and [`Region::Ceded`] for the parts no description
13/// should reach. Both apps'
14/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
15/// this layer is absent rather than divergent, which makes it the cheapest of
16/// the schemas to add and the easiest to over-build.
17///
18/// `#[non_exhaustive]`, for [`RowPart`]'s and [`Readiness`]' reason: the member
19/// after this one should not be a lockstep event across three renderers.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21#[non_exhaustive]
22pub enum Region<'a> {
23    /// A full-width strip with a title slot and an actions cluster, either of
24    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
25    /// `.header` and `.detail-header` are all this, differing only in which
26    /// slots they fill.
27    Band,
28    /// A persistent column beside the content, holding navigation.
29    Sidebar,
30    /// A region of content with its own scroll.
31    Pane,
32    /// Things that belong together, and nothing else.
33    ///
34    /// The block [`Heading::Section`] names, which the vocabulary otherwise
35    /// cannot contain. A section heading is a leaf sitting
36    /// *beside* the things it names, so nothing said where a section started or
37    /// ended and a renderer learned one had ended only because the next heading
38    /// arrived.
39    ///
40    /// # The measurement
41    ///
42    /// 41 [`Heading::Section`] sites across the ten screens described through
43    /// the router, not one of them contained. audiofiles' settings screen is the
44    /// clearest: one pane holding a heading, a field, a heading, two toggles, a
45    /// heading, a toggle and a heading, which is four sections and no
46    /// containers. Under the hand-written CSS the ports are replacing the same
47    /// block is spelled `.settings-section` in goingson, `.form-section` and
48    /// `.content-section` in the MNW server, `.help-section` in Balanced
49    /// Breakfast: three apps, four names, one shape.
50    ///
51    /// # Why the existing members were the wrong answer
52    ///
53    /// [`Pane`](Self::Pane) is what apps reach for, and it claims a scroll of its own and
54    /// [`Depth::Well`], so four settings groups inside a pane are four wells
55    /// inside a well and four scroll contexts. Neither claim is true of a group.
56    ///
57    /// [`Widget`](Self::Widget) is wrong from the other side. Its own docs say a
58    /// widget is never how a primitive gets added by the back door, and a run of
59    /// related controls under a heading is furniture any app would have, which
60    /// is the generic-against-bespoke bar a primitive has to clear.
61    ///
62    /// # What it does not carry
63    ///
64    /// **A heading.** A group usually has one and it is an ordinary node in the
65    /// body, the way it already was. A group of related toggles with no heading
66    /// is a real thing and a mandatory slot would forbid it.
67    ///
68    /// **A depth.** [`Depth::Flat`], on [`Handover`](Self::Handover)'s reasoning:
69    /// it inherits, and an app that wants its group in a well puts it in a
70    /// [`Pane`](Self::Pane), which composes rather than adding a knob here.
71    ///
72    /// **A colour.** Distinguishing sibling groups by colour is the thing this
73    /// member was asked for and it is deliberately not stated here. The
74    /// description says these things belong together; which of the theme's
75    /// categorical colours a renderer reaches for, and whether it reaches for
76    /// one at all, is derived from sibling order at the renderer. A terminal
77    /// that tints nothing and separates with a rule is honouring this.
78    Group,
79    /// Two panes side by side, where the left chooses what the right shows.
80    Split,
81    /// Peer regions across, all of them equals.
82    ///
83    /// A kanban board's columns, and the shape [`Split`](Self::Split) is not:
84    /// a split's two panes stand in a master-detail relationship, where the
85    /// left chooses what the right shows. These choose nothing about each
86    /// other. Each is a whole region and the set is the arrangement.
87    ///
88    /// # What it does not carry
89    ///
90    /// **How many.** The children say, and a count here would be a second
91    /// source for something the description already states by containing them.
92    ///
93    /// **How wide.** Peers are equal by definition, so there is no [`Share`] to
94    /// state. A board whose columns wanted different widths would be a
95    /// different member, and no app has one.
96    ///
97    /// **What happens when there is no room.** Scroll across, wrap, or collapse
98    /// to one column at a time: all three are right on some host, none is
99    /// derivable from the description, and every one of them is presentation.
100    /// A terminal that stacks them vertically is honouring this, not degrading
101    /// it.
102    ///
103    /// # Why it is not an `Arrangement`
104    ///
105    /// [`Arrangement`] is the page's shape, and a board is usually a region
106    /// *inside* a page that also has a band over it. Naming it here composes;
107    /// naming it there would make a screen either a board or a list-detail and
108    /// never a band above a board. It also keeps [`Arrangement::share`]
109    /// meaningful, which a peer arrangement has no answer for.
110    Columns,
111    /// A set of panes, one visible at a time, and a [`Selector::Tabs`] that
112    /// chooses between them.
113    ///
114    /// Which way the strip runs is a [`Strip`], stated by whoever holds the
115    /// region and carried beside it, the way [`Showing`] carries the index.
116    /// Where the strip goes when there is no room is still the renderer's to
117    /// measure, the same as its overflow.
118    TabGroup,
119    /// Content over a scrim, taking input until dismissed.
120    Modal,
121    /// A region this crate names the *place* of, whose contents the app still
122    /// owes every host.
123    ///
124    /// The escape hatch, and the thing that keeps the description honest about
125    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
126    /// paint interaction over the timeline are not describable here and are not
127    /// going to become describable: a description expressive enough to produce
128    /// a timeline is a widget library wearing a description's name.
129    ///
130    /// But a screen containing one still has to be a screen. Without this
131    /// member the description covers only the boring screens, and the four that
132    /// make goingson worth using would need a second, undescribed path beside
133    /// the router. Two paths is how the vocabulary starts drifting from the app
134    /// again, which is the exact failure this crate exists to end.
135    ///
136    /// So the description says "a thing called `day-plan` goes here" and stops.
137    /// The name is opaque: this crate never interprets it, and no renderer is
138    /// expected to know what it means beyond handing the space over.
139    ///
140    /// # What separates it from [`Ceded`](Self::Ceded)
141    ///
142    /// **A fill is owed here in every host's currency.** A renderer handed one
143    /// of these and given nothing to put in it is looking at a hole the app
144    /// meant to fill, and saying so is the honest drawing. [`owed`](Self::owed)
145    /// is how it asks.
146    ///
147    /// That is the whole of the split. Before it there was one opaque member,
148    /// so a region the description had given up on and a region nobody had
149    /// converted yet were the same value, and both drew as a silently empty
150    /// box on the two renderers that answer no fill.
151    Handover {
152        /// What the app calls it. Never interpreted here.
153        name: &'a str,
154    },
155    /// A region this crate names the place of, whose contents no host is owed.
156    ///
157    /// The other half of the old single opaque member. The app has decided this
158    /// space is not the description's to fill and is not going to become so:
159    /// a chart, a waveform, a rendered picture of domain data with marks
160    /// painted over it at positions no description knows.
161    ///
162    /// **Silence is the correct drawing.** A renderer with no fill for this
163    /// draws nothing and is right to; unlike [`Handover`](Self::Handover) there
164    /// is nothing missing. That is what makes the pair worth two members rather
165    /// than a flag: the two want opposite behaviour from a renderer that cannot
166    /// fill them, and one name cannot carry both.
167    ///
168    /// The measured sites are MNW's analytics charts, which already carry the
169    /// ruling that a bar chart is not describable and should not be, and
170    /// audiofiles' waveform, whose exclusion had no vocabulary to live in and
171    /// was recorded in a doc comment instead.
172    Ceded {
173        /// What the app calls it. Never interpreted here.
174        name: &'a str,
175    },
176    /// A named assembly of things the vocabulary already says.
177    ///
178    /// The third tier, between a primitive and the two opaque members.
179    ///
180    /// # What separates it from the two members either side
181    ///
182    /// A primitive is a thing every renderer draws from scratch, and the test
183    /// it has to pass is that every host has an honest answer. A carousel fails
184    /// that test (a terminal has no carousel) which is the same refusal
185    /// `Node::Html` got and is why the carousel sat unsayable for months.
186    ///
187    /// [`Handover`](Self::Handover) fails it from the other side. It is for
188    /// what one app owns and nobody will build twice, and it carries *no*
189    /// contents: the description names the place and stops. A carousel is
190    /// furniture any app would have, and every part of it (an ordered set of
191    /// frames, a position, prev and next, a strip of position indicators) is
192    /// already sayable. Only the assembly had no name.
193    ///
194    /// So this member is the pair the other two are not: a name **and**
195    /// contents. The contents are the assembly, in the region's own body, said
196    /// in members that already exist.
197    ///
198    /// # Why the name does not have to be understood
199    ///
200    /// A renderer that recognises the name draws it the way its host does it: a
201    /// carousel in a webview, a pager with a count in a terminal, a selector in
202    /// egui. A renderer that does not recognise it walks the body, which is
203    /// primitives all the way down and which it can already draw.
204    ///
205    /// That is what lets the widget set be **open** without every renderer
206    /// knowing every widget. An unrecognised widget degrades to its assembly
207    /// instead of failing, so a second or third party can name one without
208    /// three renderers releasing in lockstep to accept it. Contrast
209    /// [`Handover`](Self::Handover), which no renderer can degrade: there is
210    /// nothing under it to fall back to.
211    ///
212    /// # What it does not do
213    ///
214    /// A widget is an assembly of things the vocabulary *already* says, so it
215    /// buys no expressive power. Anything needing a member the vocabulary does
216    /// not have is a finding about the vocabulary, and the answer to a finding
217    /// is to add the member. A widget is never the way a primitive gets added
218    /// by the back door. A timeline is describable because [`Track`] was added
219    /// to say it, not because a screen was dressed up as an assembly.
220    Widget {
221        /// What the assembly is called. This crate never interprets it, and a
222        /// renderer is free not to know it.
223        name: &'a str,
224    },
225}
226
227impl<'a> Region<'a> {
228    /// How the region sits on what is behind it.
229    #[must_use]
230    pub const fn depth(self) -> Depth {
231        match self {
232            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
233            // Flat, and it inherits. A group says its contents belong together
234            // and says nothing about the surface they sit on, so a group in a
235            // pane is in a well and a group on the page is on the page. An app
236            // wanting one lifted puts it in a `Pane`.
237            Self::Group => Depth::Flat,
238            // Flat, and it is the container rather than the columns. Each
239            // column is its own region and brings its own depth; a well here
240            // would put a second edge around a row of wells.
241            Self::Columns => Depth::Flat,
242            // A pane is looked into, the same as a table body or a tag tree.
243            Self::Pane => Depth::Well,
244            Self::Modal => Depth::Raised,
245            // Flat because it inherits: a bespoke region takes the depth of
246            // whatever frames it. An app that wants its timeline in a well puts
247            // it in a `Pane`, which composes rather than adding a knob here.
248            //
249            // A widget inherits for the same reason and it matters more here,
250            // because a widget is drawn by whichever renderer recognises it. A
251            // depth set here would be this crate deciding that a carousel is
252            // raised on every host, which is the kind of value the deferral
253            // rule exists to refuse.
254            Self::Handover { .. } | Self::Ceded { .. } | Self::Widget { .. } => Depth::Flat,
255        }
256    }
257
258    /// Whether this crate can say anything about the region's contents.
259    ///
260    /// A renderer walks the description and hands every region it understands
261    /// to the right drawing code. This is how it tells the two apart, and the
262    /// reason it is a method rather than a `matches!` at each renderer: there
263    /// is exactly one opaque member and there should stay exactly one.
264    ///
265    /// [`Widget`](Self::Widget) is described, and that is the whole of what
266    /// separates it from the two opaque members here. All three carry a name
267    /// this crate never interprets; only the widget carries contents under it.
268    /// A renderer that does not recognise a widget's name still walks its body,
269    /// so there is nothing for it to hand over and nothing it cannot draw.
270    #[must_use]
271    pub const fn described(self) -> bool {
272        !matches!(self, Self::Handover { .. } | Self::Ceded { .. })
273    }
274
275    /// Whether a fill is owed here, for a renderer that has none.
276    ///
277    /// The question the single opaque member could not answer. True for
278    /// [`Handover`](Self::Handover): the app meant to fill this and a renderer
279    /// with nothing to put in it should say so. False for everything else,
280    /// [`Ceded`](Self::Ceded) included, where silence is the correct drawing
281    /// because nothing is missing.
282    ///
283    /// A method rather than a `matches!` at each renderer, for
284    /// [`described`](Self::described)'s reason: three renderers writing the
285    /// same match is three chances to disagree about what an empty region
286    /// means.
287    #[must_use]
288    pub const fn owed(self) -> bool {
289        matches!(self, Self::Handover { .. })
290    }
291
292    /// The name an app gave this region, if it gave one.
293    ///
294    /// [`Handover`](Self::Handover), [`Ceded`](Self::Ceded) and
295    /// [`Widget`](Self::Widget) are the members that carry a name, for two
296    /// different purposes: the first two say what the app puts in the space,
297    /// the third says what the assembly under it is called. A renderer dispatching on either wants the string without
298    /// caring which member it came from, and writing that `matches!` at each
299    /// renderer is how the two drift apart.
300    #[must_use]
301    pub const fn name(self) -> Option<&'a str> {
302        match self {
303            Self::Handover { name } | Self::Ceded { name } | Self::Widget { name } => Some(name),
304            // Spelled out rather than a wildcard, so a member added later has
305            // to answer whether it carries a name instead of inheriting `None`
306            // by sitting under a `_`.
307            Self::Band
308            | Self::Sidebar
309            | Self::Pane
310            | Self::Group
311            | Self::Split
312            | Self::Columns
313            | Self::TabGroup
314            | Self::Modal => None,
315        }
316    }
317}
318
319/// How many of a region's children are visible at once.
320///
321/// One sentence covering three shapes: *this region holds several children and
322/// shows some of them, and the reader can change which.* A tab group, a
323/// carousel and a disclosure all need it, and without it a renderer has two
324/// moves: hardcode a widget name, or draw every child. That is what puts
325/// per-widget code in renderers.
326///
327/// # What is here and what is not
328///
329/// The *kind*, and only the kind. Which child is currently up is the current
330/// answer, and a layer that defers every address does not hold the current
331/// answer either, the split [`Selector`] already makes, where this crate says
332/// what kind of chooser a thing is and the router says which option is picked.
333/// So a holder of regions carries the index and the per-child label beside this.
334///
335/// # What a renderer does with it
336///
337/// Derives its chrome, once, for every widget rather than per name:
338///
339/// - Children carrying labels get a strip of the labels, the current one marked.
340/// - Children carrying none get previous, position, next.
341/// - [`AtMostOne`](Self::AtMostOne) over one child gets a summary line that
342///   opens.
343///
344/// The name on [`Region::Widget`] survives as app vocabulary, for a renderer
345/// that wants to do something *special* with one, which is what it should have
346/// been from the start.
347///
348/// Degradation runs the way it already did: a renderer ignoring this draws every
349/// child, which is more content rather than less.
350#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
351#[non_exhaustive]
352pub enum Showing {
353    /// Every child, in order. What every region did before this existed.
354    #[default]
355    All,
356    /// Exactly one. A carousel, a tab group.
357    One,
358    /// One, or none. A disclosure, which is closed until it is opened.
359    AtMostOne,
360}
361
362impl Showing {
363    /// Whether the reader can change which child is up.
364    ///
365    /// The question every renderer's region arm asks before deriving any
366    /// chrome, and a method rather than a `matches!` at each renderer for
367    /// [`Region::name`]'s reason: three renderers writing the same comparison is
368    /// how they come to disagree about a member added later.
369    #[must_use]
370    pub const fn selective(self) -> bool {
371        !matches!(self, Self::All)
372    }
373
374    /// Whether showing nothing is a legal state.
375    ///
376    /// True only for [`AtMostOne`](Self::AtMostOne). A renderer needs this to
377    /// know whether its control closes as well as moves: a carousel's row moves
378    /// between frames and never reaches empty, and a disclosure's summary line
379    /// is the same control wearing its closed state.
380    #[must_use]
381    pub const fn dismissible(self) -> bool {
382        matches!(self, Self::AtMostOne)
383    }
384}
385
386/// Which way a [`Region::TabGroup`]'s strip runs.
387///
388/// Across is a row of tabs over the panes it opens; down is a column of them
389/// beside the panes. Both are the folder semantic, one pane showing at a time,
390/// and both put the strip first, so a tab is always read before the pane it
391/// opens.
392///
393/// # Why the description says it
394///
395/// A renderer left to choose picks across every time, so a tab group that
396/// wants a column has no way to get one. Both shapes are in use: strips across
397/// a screen, and long settings panels with their sections listed down beside
398/// them. The language says both.
399///
400/// # What is here and what is not
401///
402/// The direction, carried beside the region the way [`Showing`] is: this crate
403/// names the fact and the holder of the region states it, because the region
404/// member is a place and not a record of how it is dressed.
405///
406/// **No default.** A tab group that says nothing about its strip is the silence
407/// this type exists to end, so a holder has to pick one.
408///
409/// **No breakpoint.** Room is still the renderer's to measure. A strip that
410/// runs down may fold over its panes when there is no room beside them, the
411/// way a row folds into a menu; what it may not do is run across when there
412/// is room, because then the description stopped being what was drawn.
413#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
414#[non_exhaustive]
415pub enum Strip {
416    /// A row over the panes.
417    Across,
418    /// A column beside the panes.
419    Down,
420}
421
422impl Strip {
423    /// Whether the tabs stack vertically.
424    ///
425    /// What a renderer asks for the two things that turn on direction rather
426    /// than on placement: the accessibility orientation a strip announces, and
427    /// which pair of arrow keys moves between its tabs. A method for
428    /// [`Region::name`]'s reason, so three renderers do not each write the
429    /// comparison.
430    #[must_use]
431    pub const fn runs_down(self) -> bool {
432        matches!(self, Self::Down)
433    }
434}
435
436/// A window onto a sequence: where it starts, how much it covers, and how long
437/// the sequence is when that is known.
438///
439/// The mechanism under two things the vocabulary deliberately keeps apart. A
440/// carousel is a window of one frame over children that are all present; a
441/// paged list is a window of a page over rows most of which were never fetched.
442/// Those are different facts and they stay different types ([`Showing`] says
443/// which child is up, [`Paging`] says where a reader is in a query) but the
444/// arithmetic underneath is one piece of code, so a terminal and a browser
445/// cannot come to disagree about which frame is last.
446///
447/// # Why `of` is optional and `count` is not
448///
449/// `count` is what is on screen and is therefore always known. `of` is the
450/// length of the thing being windowed, and a host that cannot count says so by
451/// leaving it empty **for the life of the screen**. It is never "not counted
452/// yet": see "First paint is final paint" in the crate header. A total that
453/// turns up on a later pass widens the text that prints it.
454///
455/// # Clamping
456///
457/// Every derivation clamps rather than refusing, and a zero `count` answers
458/// `None` rather than dividing. A window past the end is a bug in the host, and
459/// a renderer that answered it by drawing nothing would report a region that
460/// vanished, which is the hardest kind of bug to find from what is on screen.
461/// [`Share::percent`] clamps for the same reason.
462#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
463#[non_exhaustive]
464pub struct Window {
465    from: usize,
466    count: usize,
467    of: Option<usize>,
468}
469
470impl Window {
471    /// A window of `count`, starting at `from`, over a sequence of unknown
472    /// length.
473    #[must_use]
474    pub const fn new(from: usize, count: usize) -> Self {
475        Self {
476            from,
477            count,
478            of: None,
479        }
480    }
481
482    /// How long the sequence is.
483    #[must_use]
484    pub const fn of(mut self, of: usize) -> Self {
485        self.of = Some(of);
486        self
487    }
488
489    /// The index into the sequence where the window starts.
490    #[must_use]
491    pub const fn from(self) -> usize {
492        self.from
493    }
494
495    /// How many the window covers. One, for a carousel.
496    #[must_use]
497    pub const fn count(self) -> usize {
498        self.count
499    }
500
501    /// How long the sequence is, when the host can say.
502    #[must_use]
503    pub const fn length(self) -> Option<usize> {
504        self.of
505    }
506
507    /// One item of a sequence whose length is known. A carousel frame.
508    #[must_use]
509    pub const fn frame(at: usize, of: usize) -> Self {
510        Self {
511            from: at,
512            count: 1,
513            of: Some(of),
514        }
515    }
516
517    /// Which window this is, counting from zero.
518    ///
519    /// `None` when `count` is zero, which is the only input with no answer
520    /// rather than a clamped one.
521    ///
522    /// A window that does not start on a multiple of `count` has a short
523    /// window before it, and that one counts: rows 5 to 14 of 20 in tens is the
524    /// second of three, not the first of two, which is what agrees with
525    /// [`has_before`](Self::has_before). An aligned window reads as it always
526    /// did.
527    #[must_use]
528    pub const fn index(self) -> Option<usize> {
529        if self.count == 0 {
530            return None;
531        }
532        Some(self.from.div_ceil(self.count))
533    }
534
535    /// How many windows the sequence holds.
536    ///
537    /// `None` unless both the length and a non-zero `count` are known. A
538    /// partial answer here would be a renderer drawing "of 0".
539    #[must_use]
540    pub const fn windows(self) -> Option<usize> {
541        match self.of {
542            Some(of) if self.count > 0 => Some(
543                self.from.div_ceil(self.count) + of.saturating_sub(self.from).div_ceil(self.count),
544            ),
545            _ => None,
546        }
547    }
548
549    /// Whether anything sits before this window.
550    #[must_use]
551    pub const fn has_before(self) -> bool {
552        self.from > 0
553    }
554
555    /// How many sit after this window, when the length is known.
556    ///
557    /// Here rather than in each renderer for [`Showing::selective`]'s reason:
558    /// three of them writing the same subtraction is how they come to disagree,
559    /// and this one has an underflow in it for whoever writes it fourth.
560    #[must_use]
561    pub const fn after(self) -> Option<usize> {
562        match self.of {
563            Some(of) => Some(of.saturating_sub(self.from.saturating_add(self.count))),
564            None => None,
565        }
566    }
567
568    /// Whether anything sits after it.
569    ///
570    /// `true` when the length is unknown: a host that cannot count cannot rule
571    /// out more, and offering a way forward that turns out to be empty is the
572    /// cheaper of the two mistakes.
573    #[must_use]
574    pub const fn has_after(self) -> bool {
575        match self.of {
576            Some(of) => self.from.saturating_add(self.count) < of,
577            None => true,
578        }
579    }
580
581    /// The window with `from` brought inside the sequence.
582    ///
583    /// A no-op when the length is unknown, since there is nothing to clamp
584    /// against.
585    #[must_use]
586    pub const fn clamped(mut self) -> Self {
587        if let Some(of) = self.of
588            && self.from >= of
589        {
590            // `max(1)` by hand: `Ord::max` is not const yet, and a zero-count
591            // window would otherwise clamp onto the end rather than inside it.
592            let step = if self.count == 0 { 1 } else { self.count };
593            self.from = of.saturating_sub(step);
594        }
595        self
596    }
597}
598
599/// Where a reader is in a set that arrived in parts.
600///
601/// A [`Window`] wearing the paged reading of itself. Distinct from a carousel's
602/// window at the top level on purpose, because the intent differs and a call
603/// site should say which one it means, while the arithmetic below is shared so
604/// the two cannot drift apart.
605///
606/// # The two idioms, and which one a renderer may draw
607///
608/// Load-more and numbered pages are both this type. Which is honest is
609/// [`kind`](Self::kind): a set whose page size is known can be drawn as
610/// "Page 3 of 8", and one without can only be drawn as "150 of 400" and a way
611/// forward. Saying it here rather than letting each renderer guess is the point
612///, three renderers inferring it from the numbers is how they come to disagree.
613///
614/// # What it does not carry
615///
616/// No addresses. `makeover-layout` cannot name an action, and the way to ask for
617/// the next part is the host's: `quasi_router` pairs this with the addresses the
618/// same way `Row` pairs its parts with `Row::activate`. That split is the reason
619/// this type is reusable by a carousel, which has nothing to ask.
620#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
621#[non_exhaustive]
622pub struct Paging {
623    /// The window onto the set.
624    pub window: Window,
625    /// Whether the parts are a fixed size, and so whether pages are countable.
626    pub kind: PageKind,
627}
628
629/// Whether a paged set arrives in pages of a fixed size or as one window that
630/// grows.
631///
632/// The fact [`Paging`] carries so no renderer infers it from the numbers.
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
634#[non_exhaustive]
635pub enum PageKind {
636    /// Parts of a fixed size, so "Page 3 of 8" names something.
637    #[default]
638    Numbered,
639    /// Load-more: the window starts at the beginning and grows, and "page 2"
640    /// would name nothing.
641    Growing,
642}
643
644impl Paging {
645    /// A page of `per`, starting at `from`.
646    #[must_use]
647    pub const fn pages(from: usize, per: usize) -> Self {
648        Self {
649            window: Window::new(from, per),
650            kind: PageKind::Numbered,
651        }
652    }
653
654    /// The first `shown`, with more behind them.
655    ///
656    /// The load-more shape: the window starts at the beginning and grows, so
657    /// there is no page to number.
658    #[must_use]
659    pub const fn more(shown: usize) -> Self {
660        Self {
661            window: Window::new(0, shown),
662            kind: PageKind::Growing,
663        }
664    }
665
666    /// How many there are altogether.
667    ///
668    /// Left unsaid by a host that cannot count, and left unsaid **for good**:
669    /// a total arriving later widens whatever prints it. See "First paint is
670    /// final paint" in the crate header.
671    #[must_use]
672    pub const fn of(mut self, of: usize) -> Self {
673        self.window = self.window.of(of);
674        self
675    }
676
677    /// Which page this is, counting from one, when pages are countable.
678    ///
679    /// One-based because it is read aloud. [`Window::index`] is the zero-based
680    /// form for anyone indexing with it.
681    #[must_use]
682    pub const fn page(self) -> Option<usize> {
683        if matches!(self.kind, PageKind::Growing) {
684            return None;
685        }
686        match self.window.index() {
687            Some(index) => Some(index + 1),
688            None => None,
689        }
690    }
691
692    /// How many pages there are, when that is countable.
693    #[must_use]
694    pub const fn pages_total(self) -> Option<usize> {
695        if matches!(self.kind, PageKind::Growing) {
696            return None;
697        }
698        self.window.windows()
699    }
700
701    /// How many are on screen.
702    #[must_use]
703    pub const fn shown(self) -> usize {
704        self.window.count
705    }
706
707    /// How many there are, when the host counted.
708    #[must_use]
709    pub const fn total(self) -> Option<usize> {
710        self.window.of
711    }
712
713    /// How many are not shown yet, when the host counted.
714    ///
715    /// The figure a load-more control puts in its label. `None` is the honest
716    /// and common case: a set that cannot say how many more there are still has
717    /// a way to ask for them.
718    #[must_use]
719    pub const fn remaining(self) -> Option<usize> {
720        self.window.after()
721    }
722
723    /// Whether there is anything further on.
724    #[must_use]
725    pub const fn has_more(self) -> bool {
726        self.window.has_after()
727    }
728
729    /// Whether there is anything back the other way.
730    #[must_use]
731    pub const fn has_previous(self) -> bool {
732        self.window.has_before()
733    }
734}
735
736/// How much of the width an arrangement's first region takes.
737///
738/// Nothing said how much room a region got, so every renderer invented its own
739/// number and two hosts showing one screen disagreed about its proportions. A
740/// webview never noticed, because the stylesheet answered once for every
741/// consumer; a terminal has no stylesheet to inherit from, so `quasi-tui`
742/// picked 24 columns for a sidebar and 40% for a list pane and neither had
743/// anything behind it.
744///
745/// # A proportion, never a unit
746///
747/// Held as a percentage, and that is the only form it comes in. A description
748/// carrying columns would be describing a terminal and one carrying pixels a
749/// webview, and the whole point is that both honour the same fact: a terminal
750/// resolves it against a column count, a webview writes it into a grid, and
751/// neither has to know what the other did.
752///
753/// It is not [`makeover_geometry::Ratio`]'s job either, which was the first
754/// guess. Geometry is scales that answer the same for every screen and takes
755/// no input that would let a sidebar screen differ from a list-detail one.
756///
757/// [`makeover_geometry::Ratio`]: https://docs.rs/makeover-geometry
758#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
759#[non_exhaustive]
760pub struct Share(u8);
761
762impl Share {
763    /// What a sidebar takes, when nobody says otherwise.
764    ///
765    /// A quarter. `quasi-tui` drew 24 columns, which is a quarter of a
766    /// 96-column terminal and about a fifth of a wide one; a quarter is that
767    /// number said in the form a webview can honour too.
768    pub const SIDEBAR: Self = Self(25);
769
770    /// What the list side of a list-detail takes, when nobody says otherwise.
771    ///
772    /// Sixty percent. A webview's list side is usually a table of four or five
773    /// columns, and less than this is not enough room for one; a terminal's
774    /// list of titles loses nothing it needs at this share. A screen that wants
775    /// something else says so with the `share` word in `quasi-declare`'s
776    /// screen block.
777    pub const LIST: Self = Self(60);
778
779    /// A share of the width, as a percentage.
780    ///
781    /// Clamped to 5..=95 rather than refused. A description that asked for a
782    /// region of nothing is a bug in the app, and a renderer drawing a region
783    /// zero cells wide reports it as a region that vanished, which is the
784    /// hardest kind of bug to find from what is on the screen.
785    #[must_use]
786    pub const fn percent(percent: u8) -> Self {
787        Self(if percent < 5 {
788            5
789        } else if percent > 95 {
790            95
791        } else {
792            percent
793        })
794    }
795
796    /// The share as a percentage.
797    #[must_use]
798    pub const fn as_percent(self) -> u8 {
799        self.0
800    }
801
802    /// This share of a width, rounded to the nearest whole unit.
803    ///
804    /// What a terminal calls to turn the proportion into columns. At least one
805    /// when there is any width at all, because a region the description named
806    /// should be visible: a screen 3 columns wide is unusable either way, and a
807    /// sidebar that is there is a truer picture of the description than a
808    /// sidebar that is not. Nothing of nothing is nothing.
809    #[must_use]
810    pub const fn of(self, whole: u16) -> u16 {
811        if whole == 0 {
812            return 0;
813        }
814        // Half up: 50 hundredths is the half.
815        let taken = (whole as u32 * self.0 as u32 + 50) / 100;
816        if taken == 0 { 1 } else { taken as u16 }
817    }
818}
819
820/// How a screen is laid out.
821///
822/// Three, and no one of them is a variant of another. goingson is list-detail,
823/// Balanced Breakfast is sidebar plus content, and MNW's embeds are one region
824/// filling the document. The tab group is a modifier rather than a member,
825/// because goingson uses it *inside* the same content region rather than
826/// instead of one.
827///
828/// This exists at all because the router has to be able to express a screen
829/// rather than only a control. Discovering the arrangement layer missing after
830/// the renderers exist is a redesign; naming two now is a morning.
831///
832/// # Why the share rides here
833///
834/// A share is per-arrangement: how much a sidebar takes and how much a list
835/// side takes are different questions, and this enum is the only thing that
836/// knows which one is being asked. Geometry would have had to invent a channel
837/// to be told.
838///
839/// [`list_detail`](Self::list_detail) and
840/// [`sidebar_content`](Self::sidebar_content) build these with the default
841/// shares, so a screen that has no opinion does not have to have one.
842#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
843#[non_exhaustive]
844pub enum Arrangement {
845    /// A list that chooses what the detail beside it shows.
846    ListDetail {
847        /// Whether the detail side is a [`Region::TabGroup`].
848        tabbed: bool,
849        /// How much of the width the list side takes.
850        share: Share,
851    },
852    /// Navigation down the side, content filling the rest.
853    SidebarContent {
854        /// How much of the width the sidebar takes.
855        share: Share,
856    },
857    /// One region, filling the document.
858    ///
859    /// The other two are both about dividing a width between two regions, so a
860    /// screen that is one region had to borrow one of them and then undo it:
861    /// MNW's five embeds said `list_detail(title, false)` and the host spent a
862    /// `display: block` cancelling the grid that produced. A host writing CSS
863    /// to contradict the description rather than to add to it is the thing
864    /// this member ends.
865    ///
866    /// Carries no [`Share`], because there is no division to describe. That is
867    /// why [`share`](Self::share) answers `None` here.
868    Single,
869}
870
871impl Arrangement {
872    /// A list and a detail beside it, at the default share.
873    #[must_use]
874    pub const fn list_detail(tabbed: bool) -> Self {
875        Self::ListDetail {
876            tabbed,
877            share: Share::LIST,
878        }
879    }
880
881    /// A sidebar and content beside it, at the default share.
882    #[must_use]
883    pub const fn sidebar_content() -> Self {
884        Self::SidebarContent {
885            share: Share::SIDEBAR,
886        }
887    }
888
889    /// How much of the width the first region takes, when two regions divide it.
890    ///
891    /// `None` for [`Single`](Self::Single): one region takes the width, and a
892    /// renderer that asked how to divide it was asking the wrong question. It
893    /// answers `Option` rather than a full-width `Share` so that a host cannot
894    /// quietly draw a one-region screen as a grid with an empty second column.
895    #[must_use]
896    pub const fn share(self) -> Option<Share> {
897        match self {
898            Self::ListDetail { share, .. } | Self::SidebarContent { share } => Some(share),
899            Self::Single => None,
900        }
901    }
902
903    /// The same arrangement, at this share.
904    ///
905    /// [`Single`](Self::Single) is returned unchanged: it has no division to
906    /// set, so a share named for it is a statement about nothing rather than an
907    /// error worth refusing a screen over.
908    #[must_use]
909    pub const fn with_share(self, share: Share) -> Self {
910        match self {
911            Self::ListDetail { tabbed, .. } => Self::ListDetail { tabbed, share },
912            Self::SidebarContent { .. } => Self::SidebarContent { share },
913            Self::Single => Self::Single,
914        }
915    }
916}
917
918/// How wide the content of a whole screen runs.
919///
920/// Both are the description's, which is what answering the two together
921/// settled.
922///
923/// Measured in the MNW server, where 69 of 72 templates carry exactly one of
924/// three mutually exclusive classes and the choice is per screen. GoingsOn
925/// reaches for `max-width` 56 times and Balanced Breakfast 12, neither with a
926/// token for it, so three apps were solving one thing by hand.
927///
928/// # Named for the measure, not for MNW's classes
929///
930/// A renderer that is not a browser has to answer this too, and `padded-page`
931/// tells a terminal nothing. The three say how wide the text runs, which is a
932/// question every renderer can answer: a webview with a `max-width`, a terminal
933/// with gutters, an immediate-mode frame with its own width.
934///
935/// `#[non_exhaustive]` for [`Fill`]'s reason. The set is closed today because
936/// the measurement found three, and a fourth arriving should not be a lockstep
937/// release across nine repos.
938#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
939#[non_exhaustive]
940pub enum Measure {
941    /// The whole width, with gutters. The default, and 53 of the 69.
942    ///
943    /// What a dashboard, a table and a settings screen want: the content is
944    /// wide because the content *is* wide, and constraining it would waste the
945    /// window.
946    #[default]
947    Wide,
948    /// Capped at a comfortable page width, centred. 13 of the 69.
949    ///
950    /// A form, a sign-in, a purchase. Content that does not get better by
951    /// getting wider, but is not prose either.
952    Contained,
953    /// Capped at a line length that reads well. 3 of the 69.
954    ///
955    /// Prose. The narrowest of the three, and the one with a reason outside
956    /// taste: a line of text past roughly 75 characters costs the reader the
957    /// return sweep.
958    Reading,
959}
960
961impl Measure {
962    /// A stable name, for a renderer that needs to spell it.
963    ///
964    /// Here rather than in each renderer for [`Sort::as_str`]'s reason: three
965    /// renderers spelling one enum is three chances to spell it differently.
966    #[must_use]
967    pub const fn as_str(self) -> &'static str {
968        match self {
969            Self::Wide => "wide",
970            Self::Contained => "contained",
971            Self::Reading => "reading",
972        }
973    }
974}