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 or the sequence is empty, the two inputs with
520    /// no answer rather than a clamped one. A renderer reads an empty set as no
521    /// page, not as "page 1 of 0".
522    ///
523    /// A window that does not start on a multiple of `count` has a short
524    /// window before it, and that one counts: rows 5 to 14 of 20 in tens is the
525    /// second of three, not the first of two, which is what agrees with
526    /// [`has_before`](Self::has_before). An aligned window reads as it always
527    /// did.
528    #[must_use]
529    pub const fn index(self) -> Option<usize> {
530        if self.count == 0 || matches!(self.of, Some(0)) {
531            return None;
532        }
533        Some(self.from.div_ceil(self.count))
534    }
535
536    /// How many windows the sequence holds.
537    ///
538    /// `None` unless both the length and a non-zero `count` are known. A
539    /// partial answer here would be a renderer drawing "of 0".
540    #[must_use]
541    pub const fn windows(self) -> Option<usize> {
542        match self.of {
543            Some(of) if self.count > 0 => Some(
544                self.from.div_ceil(self.count) + of.saturating_sub(self.from).div_ceil(self.count),
545            ),
546            _ => None,
547        }
548    }
549
550    /// Whether anything sits before this window.
551    #[must_use]
552    pub const fn has_before(self) -> bool {
553        self.from > 0
554    }
555
556    /// How many sit after this window, when the length is known.
557    ///
558    /// Here rather than in each renderer for [`Showing::selective`]'s reason:
559    /// three of them writing the same subtraction is how they come to disagree,
560    /// and this one has an underflow in it for whoever writes it fourth.
561    #[must_use]
562    pub const fn after(self) -> Option<usize> {
563        match self.of {
564            Some(of) => Some(of.saturating_sub(self.from.saturating_add(self.count))),
565            None => None,
566        }
567    }
568
569    /// Whether anything sits after it.
570    ///
571    /// `true` when the length is unknown: a host that cannot count cannot rule
572    /// out more, and offering a way forward that turns out to be empty is the
573    /// cheaper of the two mistakes.
574    #[must_use]
575    pub const fn has_after(self) -> bool {
576        match self.of {
577            Some(of) => self.from.saturating_add(self.count) < of,
578            None => true,
579        }
580    }
581
582    /// The window with `from` brought inside the sequence.
583    ///
584    /// A no-op when the length is unknown, since there is nothing to clamp
585    /// against.
586    #[must_use]
587    pub const fn clamped(mut self) -> Self {
588        if let Some(of) = self.of
589            && self.from >= of
590        {
591            // `max(1)` by hand: `Ord::max` is not const yet, and a zero-count
592            // window would otherwise clamp onto the end rather than inside it.
593            let step = if self.count == 0 { 1 } else { self.count };
594            self.from = of.saturating_sub(step);
595        }
596        self
597    }
598}
599
600/// Where a reader is in a set that arrived in parts.
601///
602/// A [`Window`] wearing the paged reading of itself. Distinct from a carousel's
603/// window at the top level on purpose, because the intent differs and a call
604/// site should say which one it means, while the arithmetic below is shared so
605/// the two cannot drift apart.
606///
607/// # The two idioms, and which one a renderer may draw
608///
609/// Load-more and numbered pages are both this type. Which is honest is
610/// [`kind`](Self::kind): a set whose page size is known can be drawn as
611/// "Page 3 of 8", and one without can only be drawn as "150 of 400" and a way
612/// forward. Saying it here rather than letting each renderer guess is the point
613///, three renderers inferring it from the numbers is how they come to disagree.
614///
615/// # What it does not carry
616///
617/// No addresses. `makeover-layout` cannot name an action, and the way to ask for
618/// the next part is the host's: `quasi_router` pairs this with the addresses the
619/// same way `Row` pairs its parts with `Row::activate`. That split is the reason
620/// this type is reusable by a carousel, which has nothing to ask.
621#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
622#[non_exhaustive]
623pub struct Paging {
624    /// The window onto the set.
625    pub window: Window,
626    /// Whether the parts are a fixed size, and so whether pages are countable.
627    pub kind: PageKind,
628}
629
630/// Whether a paged set arrives in pages of a fixed size or as one window that
631/// grows.
632///
633/// The fact [`Paging`] carries so no renderer infers it from the numbers.
634#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
635#[non_exhaustive]
636pub enum PageKind {
637    /// Parts of a fixed size, so "Page 3 of 8" names something.
638    #[default]
639    Numbered,
640    /// Load-more: the window starts at the beginning and grows, and "page 2"
641    /// would name nothing.
642    Growing,
643}
644
645impl Paging {
646    /// A page of `per`, starting at `from`.
647    #[must_use]
648    pub const fn pages(from: usize, per: usize) -> Self {
649        Self {
650            window: Window::new(from, per),
651            kind: PageKind::Numbered,
652        }
653    }
654
655    /// The first `shown`, with more behind them.
656    ///
657    /// The load-more shape: the window starts at the beginning and grows, so
658    /// there is no page to number.
659    #[must_use]
660    pub const fn more(shown: usize) -> Self {
661        Self {
662            window: Window::new(0, shown),
663            kind: PageKind::Growing,
664        }
665    }
666
667    /// How many there are altogether.
668    ///
669    /// Left unsaid by a host that cannot count, and left unsaid **for good**:
670    /// a total arriving later widens whatever prints it. See "First paint is
671    /// final paint" in the crate header.
672    #[must_use]
673    pub const fn of(mut self, of: usize) -> Self {
674        self.window = self.window.of(of);
675        self
676    }
677
678    /// Which page this is, counting from one, when pages are countable.
679    ///
680    /// One-based because it is read aloud. [`Window::index`] is the zero-based
681    /// form for anyone indexing with it.
682    #[must_use]
683    pub const fn page(self) -> Option<usize> {
684        if matches!(self.kind, PageKind::Growing) {
685            return None;
686        }
687        match self.window.index() {
688            Some(index) => Some(index + 1),
689            None => None,
690        }
691    }
692
693    /// How many pages there are, when that is countable.
694    #[must_use]
695    pub const fn pages_total(self) -> Option<usize> {
696        if matches!(self.kind, PageKind::Growing) {
697            return None;
698        }
699        self.window.windows()
700    }
701
702    /// How many are on screen.
703    #[must_use]
704    pub const fn shown(self) -> usize {
705        self.window.count
706    }
707
708    /// How many there are, when the host counted.
709    #[must_use]
710    pub const fn total(self) -> Option<usize> {
711        self.window.of
712    }
713
714    /// How many are not shown yet, when the host counted.
715    ///
716    /// The figure a load-more control puts in its label. `None` is the honest
717    /// and common case: a set that cannot say how many more there are still has
718    /// a way to ask for them.
719    #[must_use]
720    pub const fn remaining(self) -> Option<usize> {
721        self.window.after()
722    }
723
724    /// Whether there is anything further on.
725    #[must_use]
726    pub const fn has_more(self) -> bool {
727        self.window.has_after()
728    }
729
730    /// Whether there is anything back the other way.
731    #[must_use]
732    pub const fn has_previous(self) -> bool {
733        self.window.has_before()
734    }
735}
736
737/// How much of the width an arrangement's first region takes.
738///
739/// Nothing said how much room a region got, so every renderer invented its own
740/// number and two hosts showing one screen disagreed about its proportions. A
741/// webview never noticed, because the stylesheet answered once for every
742/// consumer; a terminal has no stylesheet to inherit from, so `quasi-tui`
743/// picked 24 columns for a sidebar and 40% for a list pane and neither had
744/// anything behind it.
745///
746/// # A proportion, never a unit
747///
748/// Held as a percentage, and that is the only form it comes in. A description
749/// carrying columns would be describing a terminal and one carrying pixels a
750/// webview, and the whole point is that both honour the same fact: a terminal
751/// resolves it against a column count, a webview writes it into a grid, and
752/// neither has to know what the other did.
753///
754/// It is not [`makeover_geometry::Ratio`]'s job either, which was the first
755/// guess. Geometry is scales that answer the same for every screen and takes
756/// no input that would let a sidebar screen differ from a list-detail one.
757///
758/// [`makeover_geometry::Ratio`]: https://docs.rs/makeover-geometry
759#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
760#[non_exhaustive]
761pub struct Share(u8);
762
763impl Share {
764    /// What a sidebar takes, when nobody says otherwise.
765    ///
766    /// A quarter. `quasi-tui` drew 24 columns, which is a quarter of a
767    /// 96-column terminal and about a fifth of a wide one; a quarter is that
768    /// number said in the form a webview can honour too.
769    pub const SIDEBAR: Self = Self(25);
770
771    /// What the list side of a list-detail takes, when nobody says otherwise.
772    ///
773    /// Sixty percent. A webview's list side is usually a table of four or five
774    /// columns, and less than this is not enough room for one; a terminal's
775    /// list of titles loses nothing it needs at this share. A screen that wants
776    /// something else says so with the `share` word in `quasi-declare`'s
777    /// screen block.
778    pub const LIST: Self = Self(60);
779
780    /// A share of the width, as a percentage.
781    ///
782    /// Clamped to 5..=95 rather than refused. A description that asked for a
783    /// region of nothing is a bug in the app, and a renderer drawing a region
784    /// zero cells wide reports it as a region that vanished, which is the
785    /// hardest kind of bug to find from what is on the screen.
786    #[must_use]
787    pub const fn percent(percent: u8) -> Self {
788        Self(if percent < 5 {
789            5
790        } else if percent > 95 {
791            95
792        } else {
793            percent
794        })
795    }
796
797    /// The share as a percentage.
798    #[must_use]
799    pub const fn as_percent(self) -> u8 {
800        self.0
801    }
802
803    /// This share of a width, rounded to the nearest whole unit.
804    ///
805    /// What a terminal calls to turn the proportion into columns. At least one
806    /// when there is any width at all, because a region the description named
807    /// should be visible: a screen 3 columns wide is unusable either way, and a
808    /// sidebar that is there is a truer picture of the description than a
809    /// sidebar that is not. Nothing of nothing is nothing.
810    #[must_use]
811    pub const fn of(self, whole: u16) -> u16 {
812        if whole == 0 {
813            return 0;
814        }
815        // Half up: 50 hundredths is the half.
816        let taken = (whole as u32 * self.0 as u32 + 50) / 100;
817        if taken == 0 { 1 } else { taken as u16 }
818    }
819}
820
821/// How a screen is laid out.
822///
823/// Three, and no one of them is a variant of another. goingson is list-detail,
824/// Balanced Breakfast is sidebar plus content, and MNW's embeds are one region
825/// filling the document. The tab group is a modifier rather than a member,
826/// because goingson uses it *inside* the same content region rather than
827/// instead of one.
828///
829/// This exists at all because the router has to be able to express a screen
830/// rather than only a control. Discovering the arrangement layer missing after
831/// the renderers exist is a redesign; naming two now is a morning.
832///
833/// # Why the share rides here
834///
835/// A share is per-arrangement: how much a sidebar takes and how much a list
836/// side takes are different questions, and this enum is the only thing that
837/// knows which one is being asked. Geometry would have had to invent a channel
838/// to be told.
839///
840/// [`list_detail`](Self::list_detail) and
841/// [`sidebar_content`](Self::sidebar_content) build these with the default
842/// shares, so a screen that has no opinion does not have to have one.
843#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
844#[non_exhaustive]
845pub enum Arrangement {
846    /// A list that chooses what the detail beside it shows.
847    ListDetail {
848        /// Whether the detail side is a [`Region::TabGroup`].
849        tabbed: bool,
850        /// How much of the width the list side takes.
851        share: Share,
852    },
853    /// Navigation down the side, content filling the rest.
854    SidebarContent {
855        /// How much of the width the sidebar takes.
856        share: Share,
857    },
858    /// One region, filling the document.
859    ///
860    /// The other two are both about dividing a width between two regions, so a
861    /// screen that is one region had to borrow one of them and then undo it:
862    /// MNW's five embeds said `list_detail(title, false)` and the host spent a
863    /// `display: block` cancelling the grid that produced. A host writing CSS
864    /// to contradict the description rather than to add to it is the thing
865    /// this member ends.
866    ///
867    /// Carries no [`Share`], because there is no division to describe. That is
868    /// why [`share`](Self::share) answers `None` here.
869    Single,
870}
871
872impl Arrangement {
873    /// A list and a detail beside it, at the default share.
874    #[must_use]
875    pub const fn list_detail(tabbed: bool) -> Self {
876        Self::ListDetail {
877            tabbed,
878            share: Share::LIST,
879        }
880    }
881
882    /// A sidebar and content beside it, at the default share.
883    #[must_use]
884    pub const fn sidebar_content() -> Self {
885        Self::SidebarContent {
886            share: Share::SIDEBAR,
887        }
888    }
889
890    /// How much of the width the first region takes, when two regions divide it.
891    ///
892    /// `None` for [`Single`](Self::Single): one region takes the width, and a
893    /// renderer that asked how to divide it was asking the wrong question. It
894    /// answers `Option` rather than a full-width `Share` so that a host cannot
895    /// quietly draw a one-region screen as a grid with an empty second column.
896    #[must_use]
897    pub const fn share(self) -> Option<Share> {
898        match self {
899            Self::ListDetail { share, .. } | Self::SidebarContent { share } => Some(share),
900            Self::Single => None,
901        }
902    }
903
904    /// The same arrangement, at this share.
905    ///
906    /// [`Single`](Self::Single) is returned unchanged: it has no division to
907    /// set, so a share named for it is a statement about nothing rather than an
908    /// error worth refusing a screen over.
909    #[must_use]
910    pub const fn with_share(self, share: Share) -> Self {
911        match self {
912            Self::ListDetail { tabbed, .. } => Self::ListDetail { tabbed, share },
913            Self::SidebarContent { .. } => Self::SidebarContent { share },
914            Self::Single => Self::Single,
915        }
916    }
917}
918
919/// How wide the content of a whole screen runs.
920///
921/// Both are the description's, which is what answering the two together
922/// settled.
923///
924/// Measured in the MNW server, where 69 of 72 templates carry exactly one of
925/// three mutually exclusive classes and the choice is per screen. GoingsOn
926/// reaches for `max-width` 56 times and Balanced Breakfast 12, neither with a
927/// token for it, so three apps were solving one thing by hand.
928///
929/// # Named for the measure, not for MNW's classes
930///
931/// A renderer that is not a browser has to answer this too, and `padded-page`
932/// tells a terminal nothing. The three say how wide the text runs, which is a
933/// question every renderer can answer: a webview with a `max-width`, a terminal
934/// with gutters, an immediate-mode frame with its own width.
935///
936/// `#[non_exhaustive]` for [`Fill`]'s reason. The set is closed today because
937/// the measurement found three, and a fourth arriving should not be a lockstep
938/// release across nine repos.
939#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
940#[non_exhaustive]
941pub enum Measure {
942    /// The whole width, with gutters. The default.
943    ///
944    /// What a dashboard, a table and a settings screen want: the content is
945    /// wide because the content *is* wide, and constraining it would waste the
946    /// window.
947    #[default]
948    Wide,
949    /// Capped at a comfortable page width, centred.
950    ///
951    /// A form, a sign-in, a purchase. Content that does not get better by
952    /// getting wider, but is not prose either.
953    ///
954    /// **How wide is the consumer's answer, not this enum's**, and a consumer
955    /// that gives no answer gets a cap too wide to do much. quasi-webview reads
956    /// `--measure-contained` and falls back to 87.5rem, which is 1400px: at any
957    /// ordinary window that is indistinguishable from [`Wide`]. MNW sets 56rem
958    /// and gets the shape this variant describes. So declaring `Contained` and
959    /// setting no token is a screen that asked to be narrowed and was not,
960    /// which is worth knowing before reading a wide-looking form as a renderer
961    /// bug.
962    Contained,
963    /// Capped at a line length that reads well.
964    ///
965    /// Prose. The narrowest of the three, and the one with a reason outside
966    /// taste: a line of text past roughly 75 characters costs the reader the
967    /// return sweep.
968    Reading,
969}
970
971impl Measure {
972    /// A stable name, for a renderer that needs to spell it.
973    ///
974    /// Here rather than in each renderer for [`Sort::as_str`]'s reason: three
975    /// renderers spelling one enum is three chances to spell it differently.
976    #[must_use]
977    pub const fn as_str(self) -> &'static str {
978        match self {
979            Self::Wide => "wide",
980            Self::Contained => "contained",
981            Self::Reading => "reading",
982        }
983    }
984}