makeover-layout 0.46.0

The renderer-agnostic half of the make-family design system: what a thing IS, named as intents and relationships and never as values. Colour defers to makeover, spacing to makeover-geometry; what is left is composition.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
use crate::Depth;

// Names this module's prose links to, resolved for rustdoc.
#[allow(unused_imports)]
use crate::{Fill, Heading, Readiness, RowPart, Selector, Sort, Track};

/// A named part of a screen.
///
/// The thing `makeover-geometry` deliberately does not name: it names the space
/// *between* things by relationship, and nothing named the things. Six named
/// members, taken from what the two webview apps actually use, plus
/// [`Region::Handover`] and [`Region::Ceded`] for the parts no description
/// should reach. Both apps'
/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
/// this layer is absent rather than divergent, which makes it the cheapest of
/// the schemas to add and the easiest to over-build.
///
/// `#[non_exhaustive]`, for [`RowPart`]'s and [`Readiness`]' reason: the member
/// after this one should not be a lockstep event across three renderers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Region<'a> {
    /// A full-width strip with a title slot and an actions cluster, either of
    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
    /// `.header` and `.detail-header` are all this, differing only in which
    /// slots they fill.
    Band,
    /// A persistent column beside the content, holding navigation.
    Sidebar,
    /// A region of content with its own scroll.
    Pane,
    /// Things that belong together, and nothing else.
    ///
    /// The block [`Heading::Section`] names, which the vocabulary otherwise
    /// cannot contain. A section heading is a leaf sitting
    /// *beside* the things it names, so nothing said where a section started or
    /// ended and a renderer learned one had ended only because the next heading
    /// arrived.
    ///
    /// # The measurement
    ///
    /// 41 [`Heading::Section`] sites across the ten screens described through
    /// the router, not one of them contained. audiofiles' settings screen is the
    /// clearest: one pane holding a heading, a field, a heading, two toggles, a
    /// heading, a toggle and a heading, which is four sections and no
    /// containers. Under the hand-written CSS the ports are replacing the same
    /// block is spelled `.settings-section` in goingson, `.form-section` and
    /// `.content-section` in the MNW server, `.help-section` in Balanced
    /// Breakfast: three apps, four names, one shape.
    ///
    /// # Why the existing members were the wrong answer
    ///
    /// [`Pane`](Self::Pane) is what apps reached for, and it is 28 of the 45
    /// regions in the described screens. It claims a scroll of its own and
    /// [`Depth::Well`], so four settings groups inside a pane are four wells
    /// inside a well and four scroll contexts. Neither claim is true of a group.
    ///
    /// [`Widget`](Self::Widget) is wrong from the other side. Its own docs say a
    /// widget is never how a primitive gets added by the back door, and a run of
    /// related controls under a heading is furniture any app would have, which
    /// is the generic-against-bespoke bar a primitive has to clear.
    ///
    /// # What it does not carry
    ///
    /// **A heading.** A group usually has one and it is an ordinary node in the
    /// body, the way it already was. A group of related toggles with no heading
    /// is a real thing and a mandatory slot would forbid it.
    ///
    /// **A depth.** [`Depth::Flat`], on [`Handover`](Self::Handover)'s reasoning:
    /// it inherits, and an app that wants its group in a well puts it in a
    /// [`Pane`](Self::Pane), which composes rather than adding a knob here.
    ///
    /// **A colour.** Distinguishing sibling groups by colour is the thing this
    /// member was asked for and it is deliberately not stated here. The
    /// description says these things belong together; which of the theme's
    /// categorical colours a renderer reaches for, and whether it reaches for
    /// one at all, is derived from sibling order at the renderer. A terminal
    /// that tints nothing and separates with a rule is honouring this.
    Group,
    /// Two panes side by side, where the left chooses what the right shows.
    Split,
    /// Peer regions across, all of them equals.
    ///
    /// A kanban board's columns, and the shape [`Split`](Self::Split) is not:
    /// a split's two panes stand in a master-detail relationship, where the
    /// left chooses what the right shows. These choose nothing about each
    /// other. Each is a whole region and the set is the arrangement.
    ///
    /// # What it does not carry
    ///
    /// **How many.** The children say, and a count here would be a second
    /// source for something the description already states by containing them.
    ///
    /// **How wide.** Peers are equal by definition, so there is no [`Share`] to
    /// state. A board whose columns wanted different widths would be a
    /// different member, and no app has one.
    ///
    /// **What happens when there is no room.** Scroll across, wrap, or collapse
    /// to one column at a time: all three are right on some host, none is
    /// derivable from the description, and every one of them is presentation.
    /// A terminal that stacks them vertically is honouring this, not degrading
    /// it.
    ///
    /// # Why it is not an `Arrangement`
    ///
    /// [`Arrangement`] is the page's shape, and a board is usually a region
    /// *inside* a page that also has a band over it. Naming it here composes;
    /// naming it there would make a screen either a board or a list-detail and
    /// never a band above a board. It also keeps [`Arrangement::share`]
    /// meaningful, which a peer arrangement has no answer for.
    Columns,
    /// A set of panes, one visible at a time, and a [`Selector::Tabs`] that
    /// chooses between them.
    ///
    /// Says nothing about where the strip sits. A row over the panes, a column
    /// beside them, a wrapped run of links under them: all three are the same
    /// member drawn by a renderer that knows its host, the way the strip's
    /// overflow is.
    TabGroup,
    /// Content over a scrim, taking input until dismissed.
    Modal,
    /// A region this crate names the *place* of, whose contents the app still
    /// owes every host.
    ///
    /// The escape hatch, and the thing that keeps the description honest about
    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
    /// paint interaction over the timeline are not describable here and are not
    /// going to become describable: a description expressive enough to produce
    /// a timeline is a widget library wearing a description's name.
    ///
    /// But a screen containing one still has to be a screen. Without this
    /// member the description covers only the boring screens, and the four that
    /// make goingson worth using would need a second, undescribed path beside
    /// the router. Two paths is how the vocabulary starts drifting from the app
    /// again, which is the exact failure this crate exists to end.
    ///
    /// So the description says "a thing called `day-plan` goes here" and stops.
    /// The name is opaque: this crate never interprets it, and no renderer is
    /// expected to know what it means beyond handing the space over.
    ///
    /// # What separates it from [`Ceded`](Self::Ceded)
    ///
    /// **A fill is owed here in every host's currency.** A renderer handed one
    /// of these and given nothing to put in it is looking at a hole the app
    /// meant to fill, and saying so is the honest drawing. [`owed`](Self::owed)
    /// is how it asks.
    ///
    /// That is the whole of the split. Before it there was one opaque member,
    /// so a region the description had given up on and a region nobody had
    /// converted yet were the same value, and both drew as a silently empty
    /// box on the two renderers that answer no fill.
    Handover {
        /// What the app calls it. Never interpreted here.
        name: &'a str,
    },
    /// A region this crate names the place of, whose contents no host is owed.
    ///
    /// The other half of the old single opaque member. The app has decided this
    /// space is not the description's to fill and is not going to become so:
    /// a chart, a waveform, a rendered picture of domain data with marks
    /// painted over it at positions no description knows.
    ///
    /// **Silence is the correct drawing.** A renderer with no fill for this
    /// draws nothing and is right to; unlike [`Handover`](Self::Handover) there
    /// is nothing missing. That is what makes the pair worth two members rather
    /// than a flag: the two want opposite behaviour from a renderer that cannot
    /// fill them, and one name cannot carry both.
    ///
    /// The measured sites are MNW's analytics charts, which already carry the
    /// ruling that a bar chart is not describable and should not be, and
    /// audiofiles' waveform, whose exclusion had no vocabulary to live in and
    /// was recorded in a doc comment instead.
    Ceded {
        /// What the app calls it. Never interpreted here.
        name: &'a str,
    },
    /// A named assembly of things the vocabulary already says.
    ///
    /// The third tier, between a primitive and the two opaque members.
    ///
    /// # What separates it from the two members either side
    ///
    /// A primitive is a thing every renderer draws from scratch, and the test
    /// it has to pass is that every host has an honest answer. A carousel fails
    /// that test — a terminal has no carousel — which is the same refusal
    /// `Node::Html` got and is why the carousel sat unsayable for months.
    ///
    /// [`Handover`](Self::Handover) fails it from the other side. It is for
    /// what one app owns and nobody will build twice, and it carries *no*
    /// contents: the description names the place and stops. A carousel is
    /// furniture any app would have, and every part of it — an ordered set of
    /// frames, a position, prev and next, a strip of position indicators — is
    /// already sayable. Only the assembly had no name.
    ///
    /// So this member is the pair the other two are not: a name **and**
    /// contents. The contents are the assembly, in the region's own body, said
    /// in members that already exist.
    ///
    /// # Why the name does not have to be understood
    ///
    /// A renderer that recognises the name draws it the way its host does it: a
    /// carousel in a webview, a pager with a count in a terminal, a selector in
    /// egui. A renderer that does not recognise it walks the body, which is
    /// primitives all the way down and which it can already draw.
    ///
    /// That is what lets the widget set be **open** without every renderer
    /// knowing every widget. An unrecognised widget degrades to its assembly
    /// instead of failing, so a second or third party can name one without
    /// three renderers releasing in lockstep to accept it. Contrast
    /// [`Handover`](Self::Handover), which no renderer can degrade: there is
    /// nothing under it to fall back to.
    ///
    /// # What it does not do
    ///
    /// A widget is an assembly of things the vocabulary *already* says, so it
    /// buys no expressive power. Anything needing a member the vocabulary does
    /// not have is a finding about the vocabulary, and the answer to a finding
    /// is to add the member. A widget is never the way a primitive gets added
    /// by the back door. A timeline is describable because [`Track`] was added
    /// to say it, not because a screen was dressed up as an assembly.
    Widget {
        /// What the assembly is called. This crate never interprets it, and a
        /// renderer is free not to know it.
        name: &'a str,
    },
}

impl<'a> Region<'a> {
    /// How the region sits on what is behind it.
    #[must_use]
    pub const fn depth(self) -> Depth {
        match self {
            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
            // Flat, and it inherits. A group says its contents belong together
            // and says nothing about the surface they sit on, so a group in a
            // pane is in a well and a group on the page is on the page. An app
            // wanting one lifted puts it in a `Pane`.
            Self::Group => Depth::Flat,
            // Flat, and it is the container rather than the columns. Each
            // column is its own region and brings its own depth; a well here
            // would put a second edge around a row of wells.
            Self::Columns => Depth::Flat,
            // A pane is looked into, the same as a table body or a tag tree.
            Self::Pane => Depth::Well,
            Self::Modal => Depth::Raised,
            // Flat because it inherits: a bespoke region takes the depth of
            // whatever frames it. An app that wants its timeline in a well puts
            // it in a `Pane`, which composes rather than adding a knob here.
            //
            // A widget inherits for the same reason and it matters more here,
            // because a widget is drawn by whichever renderer recognises it. A
            // depth set here would be this crate deciding that a carousel is
            // raised on every host, which is the kind of value the deferral
            // rule exists to refuse.
            Self::Handover { .. } | Self::Ceded { .. } | Self::Widget { .. } => Depth::Flat,
        }
    }

    /// Whether this crate can say anything about the region's contents.
    ///
    /// A renderer walks the description and hands every region it understands
    /// to the right drawing code. This is how it tells the two apart, and the
    /// reason it is a method rather than a `matches!` at each renderer: there
    /// is exactly one opaque member and there should stay exactly one.
    ///
    /// [`Widget`](Self::Widget) is described, and that is the whole of what
    /// separates it from the two opaque members here. All three carry a name
    /// this crate never interprets; only the widget carries contents under it.
    /// A renderer that does not recognise a widget's name still walks its body,
    /// so there is nothing for it to hand over and nothing it cannot draw.
    #[must_use]
    pub const fn described(self) -> bool {
        !matches!(self, Self::Handover { .. } | Self::Ceded { .. })
    }

    /// Whether a fill is owed here, for a renderer that has none.
    ///
    /// The question the single opaque member could not answer. True for
    /// [`Handover`](Self::Handover): the app meant to fill this and a renderer
    /// with nothing to put in it should say so. False for everything else,
    /// [`Ceded`](Self::Ceded) included, where silence is the correct drawing
    /// because nothing is missing.
    ///
    /// A method rather than a `matches!` at each renderer, for
    /// [`described`](Self::described)'s reason: three renderers writing the
    /// same match is three chances to disagree about what an empty region
    /// means.
    #[must_use]
    pub const fn owed(self) -> bool {
        matches!(self, Self::Handover { .. })
    }

    /// The name an app gave this region, if it gave one.
    ///
    /// [`Handover`](Self::Handover), [`Ceded`](Self::Ceded) and
    /// [`Widget`](Self::Widget) are the members that carry a name, for two
    /// different purposes: the first two say what the app puts in the space,
    /// the third says what the assembly under it is called. A renderer dispatching on either wants the string without
    /// caring which member it came from, and writing that `matches!` at each
    /// renderer is how the two drift apart.
    #[must_use]
    pub const fn name(self) -> Option<&'a str> {
        match self {
            Self::Handover { name } | Self::Ceded { name } | Self::Widget { name } => Some(name),
            // Spelled out rather than a wildcard, so a member added later has
            // to answer whether it carries a name instead of inheriting `None`
            // by sitting under a `_`.
            Self::Band
            | Self::Sidebar
            | Self::Pane
            | Self::Group
            | Self::Split
            | Self::Columns
            | Self::TabGroup
            | Self::Modal => None,
        }
    }
}

/// How many of a region's children are visible at once.
///
/// One sentence covering three shapes: *this region holds several children and
/// shows some of them, and the reader can change which.* A tab group, a
/// carousel and a disclosure all need it, and without it a renderer has two
/// moves: hardcode a widget name, or draw every child. That is what puts
/// per-widget code in renderers.
///
/// # What is here and what is not
///
/// The *kind*, and only the kind. Which child is currently up is the current
/// answer, and a layer that defers every address does not hold the current
/// answer either — the split [`Selector`] already makes, where this crate says
/// what kind of chooser a thing is and the router says which option is picked.
/// So a holder of regions carries the index and the per-child label beside this.
///
/// # What a renderer does with it
///
/// Derives its chrome, once, for every widget rather than per name:
///
/// - Children carrying labels get a strip of the labels, the current one marked.
/// - Children carrying none get previous, position, next.
/// - [`AtMostOne`](Self::AtMostOne) over one child gets a summary line that
///   opens.
///
/// The name on [`Region::Widget`] survives as app vocabulary, for a renderer
/// that wants to do something *special* with one, which is what it should have
/// been from the start.
///
/// Degradation runs the way it already did: a renderer ignoring this draws every
/// child, which is more content rather than less.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Showing {
    /// Every child, in order. What every region did before this existed.
    #[default]
    All,
    /// Exactly one. A carousel, a tab group.
    One,
    /// One, or none. A disclosure, which is closed until it is opened.
    AtMostOne,
}

impl Showing {
    /// Whether the reader can change which child is up.
    ///
    /// The question every renderer's region arm asks before deriving any
    /// chrome, and a method rather than a `matches!` at each renderer for
    /// [`Region::name`]'s reason: three renderers writing the same comparison is
    /// how they come to disagree about a member added later.
    #[must_use]
    pub const fn selective(self) -> bool {
        !matches!(self, Self::All)
    }

    /// Whether showing nothing is a legal state.
    ///
    /// True only for [`AtMostOne`](Self::AtMostOne). A renderer needs this to
    /// know whether its control closes as well as moves: a carousel's row moves
    /// between frames and never reaches empty, and a disclosure's summary line
    /// is the same control wearing its closed state.
    #[must_use]
    pub const fn dismissible(self) -> bool {
        matches!(self, Self::AtMostOne)
    }
}

/// A window onto a sequence: where it starts, how much it covers, and how long
/// the sequence is when that is known.
///
/// The mechanism under two things the vocabulary deliberately keeps apart. A
/// carousel is a window of one frame over children that are all present; a
/// paged list is a window of a page over rows most of which were never fetched.
/// Those are different facts and they stay different types — [`Showing`] says
/// which child is up, [`Paging`] says where a reader is in a query — but the
/// arithmetic underneath is one piece of code, so a terminal and a browser
/// cannot come to disagree about which frame is last.
///
/// # Why `of` is optional and `count` is not
///
/// `count` is what is on screen and is therefore always known. `of` is the
/// length of the thing being windowed, and a host that cannot count says so by
/// leaving it empty **for the life of the screen**. It is never "not counted
/// yet": see "First paint is final paint" in the crate header. A total that
/// turns up on a later pass widens the text that prints it.
///
/// # Clamping
///
/// Every derivation clamps rather than refusing, and a zero `count` answers
/// `None` rather than dividing. A window past the end is a bug in the host, and
/// a renderer that answered it by drawing nothing would report a region that
/// vanished, which is the hardest kind of bug to find from what is on screen.
/// [`Share::percent`] clamps for the same reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Window {
    /// The index into the sequence where the window starts.
    pub from: usize,
    /// How many the window covers. One, for a carousel.
    pub count: usize,
    /// How long the sequence is, when the host can say.
    pub of: Option<usize>,
}

impl Window {
    /// A window of `count`, starting at `from`, over a sequence of unknown
    /// length.
    #[must_use]
    pub const fn new(from: usize, count: usize) -> Self {
        Self {
            from,
            count,
            of: None,
        }
    }

    /// How long the sequence is.
    #[must_use]
    pub const fn of(mut self, of: usize) -> Self {
        self.of = Some(of);
        self
    }

    /// One item of a sequence whose length is known. A carousel frame.
    #[must_use]
    pub const fn frame(at: usize, of: usize) -> Self {
        Self {
            from: at,
            count: 1,
            of: Some(of),
        }
    }

    /// Which window this is, counting from zero.
    ///
    /// `None` when `count` is zero, which is the only input with no answer
    /// rather than a clamped one.
    #[must_use]
    pub const fn index(self) -> Option<usize> {
        if self.count == 0 {
            return None;
        }
        Some(self.from / self.count)
    }

    /// How many windows the sequence holds.
    ///
    /// `None` unless both the length and a non-zero `count` are known. A
    /// partial answer here would be a renderer drawing "of 0".
    #[must_use]
    pub const fn windows(self) -> Option<usize> {
        match self.of {
            Some(of) if self.count > 0 => Some(of.div_ceil(self.count)),
            _ => None,
        }
    }

    /// Whether anything sits before this window.
    #[must_use]
    pub const fn has_before(self) -> bool {
        self.from > 0
    }

    /// How many sit after this window, when the length is known.
    ///
    /// Here rather than in each renderer for [`Showing::selective`]'s reason:
    /// three of them writing the same subtraction is how they come to disagree,
    /// and this one has an underflow in it for whoever writes it fourth.
    #[must_use]
    pub const fn after(self) -> Option<usize> {
        match self.of {
            Some(of) => Some(of.saturating_sub(self.from.saturating_add(self.count))),
            None => None,
        }
    }

    /// Whether anything sits after it.
    ///
    /// `true` when the length is unknown: a host that cannot count cannot rule
    /// out more, and offering a way forward that turns out to be empty is the
    /// cheaper of the two mistakes.
    #[must_use]
    pub const fn has_after(self) -> bool {
        match self.of {
            Some(of) => self.from.saturating_add(self.count) < of,
            None => true,
        }
    }

    /// The window with `from` brought inside the sequence.
    ///
    /// A no-op when the length is unknown, since there is nothing to clamp
    /// against.
    #[must_use]
    pub const fn clamped(mut self) -> Self {
        if let Some(of) = self.of
            && self.from >= of
        {
            // `max(1)` by hand: `Ord::max` is not const yet, and a zero-count
            // window would otherwise clamp onto the end rather than inside it.
            let step = if self.count == 0 { 1 } else { self.count };
            self.from = of.saturating_sub(step);
        }
        self
    }
}

/// Where a reader is in a set that arrived in parts.
///
/// A [`Window`] wearing the paged reading of itself. Distinct from a carousel's
/// window at the top level on purpose, because the intent differs and a call
/// site should say which one it means, while the arithmetic below is shared so
/// the two cannot drift apart.
///
/// # The two idioms, and which one a renderer may draw
///
/// Load-more and numbered pages are both this type. Which is honest is
/// [`paged`](Self::paged): a set whose page size is known can be drawn as
/// "Page 3 of 8", and one without can only be drawn as "150 of 400" and a way
/// forward. Saying it here rather than letting each renderer guess is the point
/// — three renderers inferring it from the numbers is how they come to disagree.
///
/// # What it does not carry
///
/// No addresses. `makeover-layout` cannot name an action, and the way to ask for
/// the next part is the host's: `quasi_router` pairs this with the addresses the
/// same way `Row` pairs its parts with `Row::activate`. That split is the reason
/// this type is reusable by a carousel, which has nothing to ask.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Paging {
    /// The window onto the set.
    pub window: Window,
    /// Whether the parts are a fixed size, and so whether pages are countable.
    ///
    /// `false` for load-more, where the window simply grew and "page 2" would
    /// name nothing.
    pub paged: bool,
}

impl Paging {
    /// A page of `per`, starting at `from`.
    #[must_use]
    pub const fn pages(from: usize, per: usize) -> Self {
        Self {
            window: Window::new(from, per),
            paged: true,
        }
    }

    /// The first `shown`, with more behind them.
    ///
    /// The load-more shape: the window starts at the beginning and grows, so
    /// there is no page to number.
    #[must_use]
    pub const fn more(shown: usize) -> Self {
        Self {
            window: Window::new(0, shown),
            paged: false,
        }
    }

    /// How many there are altogether.
    ///
    /// Left unsaid by a host that cannot count, and left unsaid **for good**:
    /// a total arriving later widens whatever prints it. See "First paint is
    /// final paint" in the crate header.
    #[must_use]
    pub const fn of(mut self, of: usize) -> Self {
        self.window = self.window.of(of);
        self
    }

    /// Which page this is, counting from one, when pages are countable.
    ///
    /// One-based because it is read aloud. [`Window::index`] is the zero-based
    /// form for anyone indexing with it.
    #[must_use]
    pub const fn page(self) -> Option<usize> {
        if !self.paged {
            return None;
        }
        match self.window.index() {
            Some(index) => Some(index + 1),
            None => None,
        }
    }

    /// How many pages there are, when that is countable.
    #[must_use]
    pub const fn pages_total(self) -> Option<usize> {
        if !self.paged {
            return None;
        }
        self.window.windows()
    }

    /// How many are on screen.
    #[must_use]
    pub const fn shown(self) -> usize {
        self.window.count
    }

    /// How many there are, when the host counted.
    #[must_use]
    pub const fn total(self) -> Option<usize> {
        self.window.of
    }

    /// How many are not shown yet, when the host counted.
    ///
    /// The figure a load-more control puts in its label. `None` is the honest
    /// and common case: a set that cannot say how many more there are still has
    /// a way to ask for them.
    #[must_use]
    pub const fn remaining(self) -> Option<usize> {
        self.window.after()
    }

    /// Whether there is anything further on.
    #[must_use]
    pub const fn has_more(self) -> bool {
        self.window.has_after()
    }

    /// Whether there is anything back the other way.
    #[must_use]
    pub const fn has_previous(self) -> bool {
        self.window.has_before()
    }
}

/// How much of the width an arrangement's first region takes.
///
/// Nothing said how much room a region got, so every renderer invented its own
/// number and two hosts showing one screen disagreed about its proportions. A
/// webview never noticed, because the stylesheet answered once for every
/// consumer; a terminal has no stylesheet to inherit from, so `quasi-tui`
/// picked 24 columns for a sidebar and 40% for a list pane and neither had
/// anything behind it.
///
/// # A proportion, never a unit
///
/// Held as a percentage, and that is the only form it comes in. A description
/// carrying columns would be describing a terminal and one carrying pixels a
/// webview, and the whole point is that both honour the same fact: a terminal
/// resolves it against a column count, a webview writes it into a grid, and
/// neither has to know what the other did.
///
/// It is not [`makeover_geometry::Ratio`]'s job either, which was the first
/// guess. Geometry is scales that answer the same for every screen and takes
/// no input that would let a sidebar screen differ from a list-detail one.
///
/// [`makeover_geometry::Ratio`]: https://docs.rs/makeover-geometry
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Share(u8);

impl Share {
    /// What a sidebar takes, when nobody says otherwise.
    ///
    /// A quarter. `quasi-tui` drew 24 columns, which is a quarter of a
    /// 96-column terminal and about a fifth of a wide one; a quarter is that
    /// number said in the form a webview can honour too.
    pub const SIDEBAR: Self = Self(25);

    /// What the list side of a list-detail takes, when nobody says otherwise.
    ///
    /// `quasi-tui`'s 40%, which was already a proportion and is the one number
    /// this member did not have to invent.
    pub const LIST: Self = Self(40);

    /// A share of the width, as a percentage.
    ///
    /// Clamped to 5..=95 rather than refused. A description that asked for a
    /// region of nothing is a bug in the app, and a renderer drawing a region
    /// zero cells wide reports it as a region that vanished, which is the
    /// hardest kind of bug to find from what is on the screen.
    #[must_use]
    pub const fn percent(percent: u8) -> Self {
        Self(if percent < 5 {
            5
        } else if percent > 95 {
            95
        } else {
            percent
        })
    }

    /// The share as a percentage.
    #[must_use]
    pub const fn as_percent(self) -> u8 {
        self.0
    }

    /// This share of a width, rounded to the nearest whole unit.
    ///
    /// What a terminal calls to turn the proportion into columns. At least one,
    /// because a region the description named should be visible: a screen
    /// 3 columns wide is unusable either way, and a sidebar that is there is a
    /// truer picture of the description than a sidebar that is not.
    #[must_use]
    pub const fn of(self, whole: u16) -> u16 {
        let taken = (whole as u32 * self.0 as u32).div_ceil(100);
        if taken == 0 { 1 } else { taken as u16 }
    }
}

/// How a screen is laid out.
///
/// Three, and no one of them is a variant of another. goingson is list-detail,
/// Balanced Breakfast is sidebar plus content, and MNW's embeds are one region
/// filling the document. The tab group is a modifier rather than a member,
/// because goingson uses it *inside* the same content region rather than
/// instead of one.
///
/// This exists at all because the router has to be able to express a screen
/// rather than only a control. Discovering the arrangement layer missing after
/// the renderers exist is a redesign; naming two now is a morning.
///
/// # Why the share rides here
///
/// A share is per-arrangement: how much a sidebar takes and how much a list
/// side takes are different questions, and this enum is the only thing that
/// knows which one is being asked. Geometry would have had to invent a channel
/// to be told.
///
/// [`list_detail`](Self::list_detail) and
/// [`sidebar_content`](Self::sidebar_content) build these with the default
/// shares, so a screen that has no opinion does not have to have one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Arrangement {
    /// A list that chooses what the detail beside it shows.
    ListDetail {
        /// Whether the detail side is a [`Region::TabGroup`].
        tabbed: bool,
        /// How much of the width the list side takes.
        share: Share,
    },
    /// Navigation down the side, content filling the rest.
    SidebarContent {
        /// How much of the width the sidebar takes.
        share: Share,
    },
    /// One region, filling the document.
    ///
    /// The other two are both about dividing a width between two regions, so a
    /// screen that is one region had to borrow one of them and then undo it:
    /// MNW's five embeds said `list_detail(title, false)` and the host spent a
    /// `display: block` cancelling the grid that produced. A host writing CSS
    /// to contradict the description rather than to add to it is the thing
    /// this member ends.
    ///
    /// Carries no [`Share`], because there is no division to describe. That is
    /// why [`share`](Self::share) answers `None` here.
    Single,
}

impl Arrangement {
    /// A list and a detail beside it, at the default share.
    #[must_use]
    pub const fn list_detail(tabbed: bool) -> Self {
        Self::ListDetail {
            tabbed,
            share: Share::LIST,
        }
    }

    /// A sidebar and content beside it, at the default share.
    #[must_use]
    pub const fn sidebar_content() -> Self {
        Self::SidebarContent {
            share: Share::SIDEBAR,
        }
    }

    /// How much of the width the first region takes, when two regions divide it.
    ///
    /// `None` for [`Single`](Self::Single): one region takes the width, and a
    /// renderer that asked how to divide it was asking the wrong question. It
    /// answers `Option` rather than a full-width `Share` so that a host cannot
    /// quietly draw a one-region screen as a grid with an empty second column.
    #[must_use]
    pub const fn share(self) -> Option<Share> {
        match self {
            Self::ListDetail { share, .. } | Self::SidebarContent { share } => Some(share),
            Self::Single => None,
        }
    }

    /// The same arrangement, at this share.
    ///
    /// [`Single`](Self::Single) is returned unchanged: it has no division to
    /// set, so a share named for it is a statement about nothing rather than an
    /// error worth refusing a screen over.
    #[must_use]
    pub const fn with_share(self, share: Share) -> Self {
        match self {
            Self::ListDetail { tabbed, .. } => Self::ListDetail { tabbed, share },
            Self::SidebarContent { .. } => Self::SidebarContent { share },
            Self::Single => Self::Single,
        }
    }
}

/// How wide the content of a whole screen runs.
///
/// Both are the description's, which is what answering the two together
/// settled.
///
/// Measured in the MNW server, where 69 of 72 templates carry exactly one of
/// three mutually exclusive classes and the choice is per screen. GoingsOn
/// reaches for `max-width` 56 times and Balanced Breakfast 12, neither with a
/// token for it, so three apps were solving one thing by hand.
///
/// # Named for the measure, not for MNW's classes
///
/// A renderer that is not a browser has to answer this too, and `padded-page`
/// tells a terminal nothing. The three say how wide the text runs, which is a
/// question every renderer can answer: a webview with a `max-width`, a terminal
/// with gutters, an immediate-mode frame with its own width.
///
/// `#[non_exhaustive]` for [`Fill`]'s reason. The set is closed today because
/// the measurement found three, and a fourth arriving should not be a lockstep
/// release across nine repos.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Measure {
    /// The whole width, with gutters. The default, and 53 of the 69.
    ///
    /// What a dashboard, a table and a settings screen want: the content is
    /// wide because the content *is* wide, and constraining it would waste the
    /// window.
    #[default]
    Wide,
    /// Capped at a comfortable page width, centred. 13 of the 69.
    ///
    /// A form, a sign-in, a purchase. Content that does not get better by
    /// getting wider, but is not prose either.
    Contained,
    /// Capped at a line length that reads well. 3 of the 69.
    ///
    /// Prose. The narrowest of the three, and the one with a reason outside
    /// taste: a line of text past roughly 75 characters costs the reader the
    /// return sweep.
    Reading,
}

impl Measure {
    /// A stable name, for a renderer that needs to spell it.
    ///
    /// Here rather than in each renderer for [`Sort::as_str`]'s reason: three
    /// renderers spelling one enum is three chances to spell it differently.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Wide => "wide",
            Self::Contained => "contained",
            Self::Reading => "reading",
        }
    }
}