makeover-layout 0.2.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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! The renderer-agnostic half of the make-family design system.
//!
//! <!-- wiki: makeover-layout -->
//!
//! `makeover` answers *what colour*, and varies by theme. `makeover-geometry`
//! answers *how much space*, and varies by density and surface. This crate
//! answers *what the thing is*, and varies by nothing.
//!
//! # The deferral rule
//!
//! A description names intents and relationships, never values. Say
//! [`Fill::Raised`], never `#D9DDF4`. Say `Gap::Peer`, never `6px`. What is
//! left once colour and spacing are deferred is **composition**: which edges
//! are lit, what inverts on press, what nests in what.
//!
//! The constraint that shapes all of it: a renderer that can only paint
//! rectangles has to be able to express the result. egui has no
//! `box-shadow: inset` and one stroke per widget with no per-side control; a
//! terminal has box-drawing characters and one cell of resolution, and cannot
//! draw a two-tone lit edge at all. A description that assumes per-side edges
//! is a CSS description wearing a neutral name. So this crate names the
//! *intent* — this region is a well — and each renderer chooses an expression
//! it can actually produce, including dropping half of one.
//!
//! # Scope
//!
//! Depth came first: the bevel and the surfaces it shapes. That much was
//! settled the hard way — the vocabulary here was read off audiofiles'
//! `ui::theme` and `ui::widgets`, which are the only implementation written
//! by a consumer with no CSS, then checked against both webview apps. All
//! three agreed once Balanced Breakfast's fills were corrected.
//!
//! 0.2.0 adds the rest of the description, each member drawn the same way,
//! from what the three apps already hand-write rather than from a taxonomy:
//!
//! - Components. [`Token`] (badge against chip), [`Notice`] (toast against
//!   banner), [`RowPart`], [`Heading`], [`Selector`], [`Readiness`], and
//!   [`Tone`], which is the one intent family they share.
//! - Schemas. [`Field`] for forms and [`Column`] for lists and tables.
//! - Structure. [`Region`] for the parts of a screen, [`Arrangement`] for how
//!   a screen is put together.
//!
//! **Validation** is absent on purpose rather than pending: neither app has a
//! shared story, and a schema describing fields but not constraints acquires a
//! constraint layer per app, which is how the divergence this crate exists to
//! end got started.
//!
//! # Where the description stops
//!
//! The bespoke widgets, a day-plan timeline and a kanban board and a calendar,
//! are not describable here and will not become describable. A description
//! expressive enough to produce a timeline is a widget library wearing a
//! description's name. Generate the boring 80% so the bespoke 20% gets the
//! attention.
//!
//! [`Region::Bespoke`] is how that limit is stated rather than hidden. The
//! description names the *place* and the app owns the contents, so a screen
//! containing a timeline is still a whole screen and still routable. Without
//! it, the four goingson screens that make the app worth using would need a
//! second, undescribed path beside the router, and two paths is how a
//! vocabulary starts drifting from its app again.

#![forbid(unsafe_code)]

/// A colour intent this crate refers to but never resolves.
///
/// The string is the token name `makeover` publishes, so a renderer can look
/// it up without this crate knowing what colour came back.
pub trait Intent {
    /// The `makeover` intent token this resolves against.
    fn token(self) -> &'static str;
}

/// Which way the light falls across a two-tone edge.
///
/// The whole content of a bevel, once colour and thickness are deferred. The
/// light is always assumed to come from the top left: every consumer measured
/// agreed on that and none of them ever varied it, so it is an invariant here
/// rather than a parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Bevel {
    /// Lit from the top left: light on top and left, dark on bottom and right.
    Raised,
    /// The same edge inverted, which is also the pressed state of anything
    /// that draws itself [`Bevel::Raised`].
    Inset,
}

impl Bevel {
    /// The edge intents, as `(top_left, bottom_right)`.
    ///
    /// Split out from any painting because the inversion *is* the idea, and
    /// it is the one part every renderer implements identically.
    #[must_use]
    pub const fn edges(self) -> (Edge, Edge) {
        match self {
            Self::Raised => (Edge::Light, Edge::Dark),
            Self::Inset => (Edge::Dark, Edge::Light),
        }
    }

    /// Pressing inverts. A raised control reads as inset while held.
    ///
    /// Stated here rather than left to each consumer because a cascade can
    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
    /// resolves this per call site, eighteen times.
    #[must_use]
    pub const fn pressed(self) -> Self {
        match self {
            Self::Raised => Self::Inset,
            Self::Inset => Self::Raised,
        }
    }
}

/// One side of a bevel, named by the intent it takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Edge {
    /// The lit side.
    Light,
    /// The shadowed side.
    Dark,
}

impl Intent for Edge {
    fn token(self) -> &'static str {
        match self {
            Self::Light => "bevel-light",
            Self::Dark => "bevel-dark",
        }
    }
}

/// A surface intent a region is filled with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Fill {
    /// The page behind everything.
    Page,
    /// A surface lifted off the page: cards, controls, menus, toasts.
    Raised,
    /// A surface floating above the page rather than resting on it.
    Overlay,
    /// The inside of a well.
    Well,
}

// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
// had something to paint. makeover-tui found that wrong within a day: page is
// the surface a well is usually cut into, so on a terminal that substitution
// produces exactly the invisibility it was meant to prevent, and the right
// answer there is a drawn edge rather than a different colour.
//
// Substituting one intent for another is renderer policy. The description says
// what the region is and stops.

impl Intent for Fill {
    fn token(self) -> &'static str {
        match self {
            Self::Page => "surface-page",
            Self::Raised => "surface-raised",
            Self::Overlay => "surface-overlay",
            Self::Well => "surface-well",
        }
    }
}

/// How a region sits relative to the surface behind it.
///
/// Fill and bevel are named together because naming them apart is what let
/// them disagree. Every consumer measured had at least one region carrying a
/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
/// and recorded the bug in its doc comment, and Balanced Breakfast still had
/// twelve of them a year later. A single name for the pair makes that
/// unrepresentable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Depth {
    /// Level with its surroundings. No edge.
    Flat,
    /// A card laid on the panel it sits in.
    Raised,
    /// A hole in the panel, with content down inside it. For anything the
    /// user looks *into*: a table body, a tag tree, a text field.
    Well,
}

impl Depth {
    /// The edge this depth is drawn with, if it has one.
    #[must_use]
    pub const fn bevel(self) -> Option<Bevel> {
        match self {
            Self::Flat => None,
            Self::Raised => Some(Bevel::Raised),
            Self::Well => Some(Bevel::Inset),
        }
    }

    /// The surface this depth is filled with.
    ///
    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
    /// which is the difference between level-with and painted-the-same-colour.
    #[must_use]
    pub const fn fill(self) -> Option<Fill> {
        match self {
            Self::Flat => None,
            Self::Raised => Some(Fill::Raised),
            Self::Well => Some(Fill::Well),
        }
    }

    /// Pressing a raised region reads as a well, and nothing else moves.
    #[must_use]
    pub const fn pressed(self) -> Self {
        match self {
            Self::Raised => Self::Well,
            other => other,
        }
    }
}

/// What a region is saying, when it is saying something.
///
/// The one intent family shared by badges, notices and nothing else. Kept
/// separate from [`Fill`] because a surface is where a thing sits and a tone is
/// what it means, and the three apps agree on the four statuses:
/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
/// `.toast.error` in Balanced Breakfast.
///
/// The per-tag palette (`category-one` through `category-six`) is deliberately
/// not here. Which colour a *particular* tag takes is app domain, and both
/// webview apps already carry it as a `data-color` attribute.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Tone {
    /// No status. Reads as ordinary de-emphasised content.
    Neutral,
    /// Something worth knowing and nothing to do about it.
    Info,
    /// Something finished and it worked.
    Success,
    /// Something the user should look at before continuing.
    Warning,
    /// Something broken, or something about to be destroyed.
    Danger,
}

impl Intent for Tone {
    fn token(self) -> &'static str {
        match self {
            // Neutral has no status token of its own. It takes the muted
            // content intent, which is what both webview apps already spell as
            // `data-color="muted"`.
            Self::Neutral => "content-muted",
            Self::Info => "info",
            Self::Success => "success",
            Self::Warning => "warning",
            Self::Danger => "danger",
        }
    }
}

/// A small labelled thing that sits inside something else.
///
/// Two members, because the three apps drew three taxonomies and only one line
/// runs through all of them: does it answer a click. audiofiles has
/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
/// to decide which of the two it always was.
///
/// The evidence that a chip is a real concept rather than a badge with a
/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
/// holds itself down", which is exactly what [`Depth::pressed`] already says.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Token {
    /// Non-interactive status or count. Answers no click.
    Badge,
    /// An interactive or removable token. Answers a click, and latches if it
    /// stands for a filter that is either on or off.
    Chip {
        /// Whether it carries its own remove affordance.
        removable: bool,
    },
}

impl Token {
    /// Whether this answers a click.
    ///
    /// The whole difference between the two members, and the reason a renderer
    /// with no hover (a touch surface, a terminal) can still tell them apart.
    #[must_use]
    pub const fn interactive(self) -> bool {
        matches!(self, Self::Chip { .. })
    }

    /// How it sits, given whether it is currently latched down.
    ///
    /// A badge is flat: it is a label, and giving it an edge would say it can
    /// be pressed. A chip is raised, and inset while latched.
    #[must_use]
    pub const fn depth(self, latched: bool) -> Depth {
        match self {
            Self::Badge => Depth::Flat,
            Self::Chip { .. } if latched => Depth::Well,
            Self::Chip { .. } => Depth::Raised,
        }
    }
}

/// Something the app is telling the user, unprompted.
///
/// Two concepts, not one with a placement. They differ in more than where they
/// sit: a toast is transient, stacked and self-dismissing, and a banner is
/// persistent, in flow, one per region, and dismissed by fixing the condition
/// it reports. Folding them into one member with a placement parameter would
/// make lifetime, stacking and dismissal all placement-dependent, which is the
/// description leaking renderer policy.
///
/// All three apps have banners: `info_banner` and `warning_banner` in
/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
/// webview apps also have toasts. So neither member is speculative, and no app
/// gains a concept it lacks except audiofiles, whose renderer may legitimately
/// decline to draw a toast at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Notice {
    /// Transient, stacked, dismisses itself.
    Toast,
    /// Persistent, in flow, one per region, dismissed by fixing the cause.
    Banner,
}

impl Notice {
    /// Whether it goes away on its own.
    #[must_use]
    pub const fn transient(self) -> bool {
        matches!(self, Self::Toast)
    }

    /// How it sits.
    ///
    /// A toast floats above the page rather than resting on it, which is
    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
    /// flow. Both are raised, and they are raised off different things.
    #[must_use]
    pub const fn fill(self) -> Fill {
        match self {
            Self::Toast => Fill::Overlay,
            Self::Banner => Fill::Raised,
        }
    }
}

/// The parts of a list row.
///
/// Four, taken from Balanced Breakfast, which is the only consumer that had all
/// of them (`row-primary`, `row-secondary`, `row-meta`, `row-actions`).
/// audiofiles has two and no slot structure at all, so it gains meta and
/// actions as real work rather than a rename; goingson moves off
/// `task-row` / `task-cell`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RowPart {
    /// The thing itself. What the row is called.
    Primary,
    /// Supporting text under the primary.
    Secondary,
    /// A short trailing fact: a count, a size, a date.
    Meta,
    /// Controls that act on this row.
    Actions,
}

impl RowPart {
    /// Whether the part stays hidden until the row is hovered or focused.
    ///
    /// Behaviour of the part, not app policy: Balanced Breakfast and goingson
    /// grew the same hover-reveal on their actions independently and neither
    /// applies it to anything else.
    ///
    /// A renderer with no hover shows it always. That is a renderer decision
    /// and this returning `true` does not forbid it.
    #[must_use]
    pub const fn revealed_on_hover(self) -> bool {
        matches!(self, Self::Actions)
    }

    /// The content intent the part takes.
    #[must_use]
    pub const fn intent(self) -> &'static str {
        match self {
            Self::Primary => "content",
            Self::Secondary => "content-secondary",
            Self::Meta => "content-muted",
            // Actions carry controls rather than text, so they inherit.
            Self::Actions => "content",
        }
    }
}

/// How far down the heading tree a title sits.
///
/// Three, and only the three that are actually headings. The bands those used
/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
/// and `.detail-header`) are arrangement, not type, and live at
/// [`Region::Band`]. One of them contains no text at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Heading {
    /// Names the whole screen. One per screen.
    Page,
    /// Names a block within the screen.
    Section,
    /// Names a sub-block inside an already-named section.
    Subsection,
}

impl Heading {
    /// Whether a rule follows the heading.
    ///
    /// audiofiles' `section_header` draws a separator and its
    /// `subsection_label` deliberately does not, which is the only thing
    /// distinguishing the two once weight and colour are deferred.
    #[must_use]
    pub const fn separated(self) -> bool {
        matches!(self, Self::Section)
    }
}

/// A control that picks between things.
///
/// Three, because three distinct behaviours are in play and collapsing any two
/// loses something. A segmented control picks a value; a tab picks a pane; a
/// toggle picks nothing and simply holds itself on or off.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Selector {
    /// Exactly one of N, and the options abut.
    Segmented,
    /// Independent on or off, on its own.
    Toggle,
    /// Navigation between panes. The folder semantic.
    Tabs,
}

impl Selector {
    /// How the chosen option sits.
    ///
    /// Held in for a segmented control and a toggle, which is the same shape
    /// pressing produces and the whole economy of the idiom: one appearance,
    /// two reasons to wear it. A tab is the exception, because the selected
    /// folder tab comes *forward* to join the pane it opens.
    #[must_use]
    pub const fn chosen(self) -> Depth {
        match self {
            Self::Segmented | Self::Toggle => Depth::Well,
            Self::Tabs => Depth::Raised,
        }
    }

    /// Whether the options touch.
    ///
    /// The gap is the entire difference between a segmented control and a row
    /// of buttons that happen to sit near each other, which is what audiofiles'
    /// `segmented_control` says in its own comment and why it zeroes the
    /// spacing by hand.
    #[must_use]
    pub const fn abutting(self) -> bool {
        matches!(self, Self::Segmented | Self::Tabs)
    }
}

/// Whether the content of a region has arrived.
///
/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
/// nothing at all is renderer policy, the same class of decision that got
/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
/// each grew a skeleton with differently-named parts; both keep them, as the
/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
/// and needs none, because an immediate-mode renderer simply repaints.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Readiness {
    /// The content is here.
    Ready,
    /// The content is on its way.
    Pending,
}

/// 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::Bespoke`] 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.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
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,
    /// Two panes side by side, where the left chooses what the right shows.
    Split,
    /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
    TabGroup,
    /// Content over a scrim, taking input until dismissed.
    Modal,
    /// A region this crate names the *place* of and nothing else. The app owns
    /// what goes in it.
    ///
    /// 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.
    Bespoke {
        /// What the app calls it. Never interpreted here.
        name: &'a str,
    },
}

impl Region<'_> {
    /// 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,
            // 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.
            Self::Bespoke { .. } => 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.
    #[must_use]
    pub const fn described(self) -> bool {
        !matches!(self, Self::Bespoke { .. })
    }
}

/// How a screen is laid out.
///
/// Two, and the second is not a variant of the first. goingson is list-detail,
/// Balanced Breakfast is sidebar plus content, and neither app has a third.
/// 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.
#[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,
    },
    /// Navigation down the side, content filling the rest.
    SidebarContent,
}

/// What kind of value a form field takes.
///
/// The union of the two vocabularies that diverged, which is what triggered
/// this crate. They have since converged on their own: both apps now have a
/// `renderFormField` emitting the same anatomy, and what is left differing is
/// the kind set, the error shape, and whether the return is a string or a node.
///
/// Validation is deliberately absent. Neither app has a shared story (goingson
/// validates after collecting the form data, with per-field transform hooks;
/// Balanced Breakfast has `required` and nothing else), and a schema that
/// describes fields but not constraints acquires a constraint layer per app,
/// which is exactly how the current divergence started. Naming it absent is a
/// decision; leaving it unmentioned would not be.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FieldKind {
    /// A single line of text.
    Text,
    /// A single line of text that must never be echoed, logged or round-tripped
    /// through anything that might persist it.
    Secret,
    /// A number.
    Number,
    /// Several lines of text.
    Textarea,
    /// One of a fixed set.
    Select,
    /// On or off.
    Checkbox,
    /// Carried through the form and never shown.
    Hidden,
}

impl FieldKind {
    /// Whether the field is drawn at all.
    #[must_use]
    pub const fn visible(self) -> bool {
        !matches!(self, Self::Hidden)
    }

    /// Whether the value must be kept out of logs and diagnostics.
    #[must_use]
    pub const fn confidential(self) -> bool {
        matches!(self, Self::Secret)
    }

    /// Where the field's own label sits.
    ///
    /// A checkbox labels itself on the right of the box; everything else takes
    /// a label above. Both webview apps already do this and both special-case
    /// it inline, which is the tell that it belongs in the description.
    #[must_use]
    pub const fn labels_itself(self) -> bool {
        matches!(self, Self::Checkbox)
    }
}

/// One field of a form.
///
/// Borrowed rather than owned: a description is built, read once by a renderer,
/// and dropped. Nothing here outlives the screen it describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Field<'a> {
    /// What kind of value it takes.
    pub kind: FieldKind,
    /// The name the value is submitted under.
    pub name: &'a str,
    /// What the user is asked for.
    pub label: &'a str,
    /// Standing help, shown whether or not anything is wrong.
    pub hint: Option<&'a str>,
    /// What is currently wrong with the value.
    pub error: Option<&'a str>,
    /// Whether the form refuses to submit without it.
    pub required: bool,
    /// Whether the field lives behind a "more options" disclosure.
    pub extended: bool,
}

impl<'a> Field<'a> {
    /// A plain required-nothing field of the given kind.
    #[must_use]
    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
        Self {
            kind,
            name,
            label,
            hint: None,
            error: None,
            required: false,
            extended: false,
        }
    }

    /// Whether the field is currently reporting a problem.
    ///
    /// Read this rather than testing `error.is_some()` at each renderer: the
    /// error state has to mark the field's whole group and not only the
    /// message, because a renderer with no descendant selectors (egui, a
    /// terminal) cannot find the group from the message. goingson already marks
    /// the group and Balanced Breakfast does not, so goingson's shape is the
    /// one taken here.
    #[must_use]
    pub const fn invalid(&self) -> bool {
        self.error.is_some()
    }
}

/// How much room a column asks for.
///
/// An intent, so the actual floor stays with `makeover-geometry`. goingson's
/// task table spells these as `minmax(200px, 1fr)`, `140px` and content-sized;
/// only the first three words of that survive deferral.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Width {
    /// Takes what it needs and no more.
    Content,
    /// A fixed share, the same at every width.
    Fixed,
    /// Absorbs whatever is left over.
    Fill,
}

/// What a column is worth when there is not room for all of them.
///
/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
/// drops. This replaces addressing columns by position, which is what both
/// webview apps do today and is a live bug rather than only verbosity. goingson
/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
/// inserting a column silently hides the wrong one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Priority {
    /// Dropped first.
    Optional,
    /// Dropped once the optional columns are gone.
    Secondary,
    /// Never dropped. Without it the row does not identify itself.
    Essential,
}

/// One column of a table.
///
/// Described once. The grid track, the cell order and the drop behaviour are
/// all derived from this, rather than being three hand-written encodings that
/// must agree and are never checked against each other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Column<'a> {
    /// The heading, and the name the cell is addressed by.
    pub name: &'a str,
    /// How much room it asks for.
    pub width: Width,
    /// What it is worth when room runs out.
    pub priority: Priority,
}

impl<'a> Column<'a> {
    /// A column that absorbs slack and drops after the optional ones.
    #[must_use]
    pub const fn new(name: &'a str) -> Self {
        Self {
            name,
            width: Width::Fill,
            priority: Priority::Secondary,
        }
    }

    /// Whether this column survives at the given cutoff.
    ///
    /// A renderer narrows by raising the cutoff, and never by counting
    /// positions.
    #[must_use]
    pub const fn kept_at(&self, cutoff: Priority) -> bool {
        (self.priority as u8) >= (cutoff as u8)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn inset_is_raised_with_the_light_moved() {
        let (rl, rd) = Bevel::Raised.edges();
        let (il, id) = Bevel::Inset.edges();
        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
        assert_eq!((il, id), (rd, rl));
    }

    #[test]
    fn pressing_twice_is_a_no_op() {
        for b in [Bevel::Raised, Bevel::Inset] {
            assert_eq!(b.pressed().pressed(), b);
        }
    }

    #[test]
    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
        // The bug this vocabulary exists to make unrepresentable.
        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
    }

    #[test]
    fn flat_has_neither_edge_nor_fill() {
        assert_eq!(Depth::Flat.bevel(), None);
        assert_eq!(Depth::Flat.fill(), None);
    }

    #[test]
    fn pressing_a_card_makes_a_well() {
        assert_eq!(Depth::Raised.pressed(), Depth::Well);
        assert_eq!(
            Depth::Raised.pressed().bevel(),
            Depth::Raised.bevel().map(Bevel::pressed)
        );
        // Only raised regions respond to being pressed.
        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
        assert_eq!(Depth::Well.pressed(), Depth::Well);
    }

    #[test]
    fn intents_name_makeover_tokens_and_nothing_else() {
        assert_eq!(Edge::Light.token(), "bevel-light");
        assert_eq!(Edge::Dark.token(), "bevel-dark");
        assert_eq!(Fill::Raised.token(), "surface-raised");
        assert_eq!(Fill::Well.token(), "surface-well");
        // No value ever leaves this crate.
        for t in [
            Edge::Light.token(),
            Edge::Dark.token(),
            Tone::Danger.token(),
            Tone::Neutral.token(),
        ] {
            assert!(!t.starts_with('#'), "{t} looks like a value");
            assert!(
                !t.chars().next().unwrap().is_ascii_digit(),
                "{t} is a value"
            );
        }
    }

    #[test]
    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
        // The one line that runs through all three apps' taxonomies.
        assert!(!Token::Badge.interactive());
        assert!(Token::Chip { removable: false }.interactive());
        assert!(Token::Chip { removable: true }.interactive());

        // A badge is a label, so giving it an edge would lie about it.
        assert_eq!(Token::Badge.depth(false), Depth::Flat);
        assert_eq!(Token::Badge.depth(true), Depth::Flat);

        // A latched chip wears the same shape a pressed one does.
        let chip = Token::Chip { removable: false };
        assert_eq!(chip.depth(false), Depth::Raised);
        assert_eq!(chip.depth(true), Depth::Raised.pressed());
    }

    #[test]
    fn a_toast_and_a_banner_differ_in_more_than_placement() {
        assert!(Notice::Toast.transient());
        assert!(!Notice::Banner.transient());
        // A toast floats above the page; a banner rests in the flow.
        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
        assert_eq!(Notice::Banner.fill(), Fill::Raised);
    }

    #[test]
    fn only_the_actions_part_hides_until_hovered() {
        for p in [RowPart::Primary, RowPart::Secondary, RowPart::Meta] {
            assert!(!p.revealed_on_hover(), "{p:?} should always be visible");
        }
        assert!(RowPart::Actions.revealed_on_hover());
        // Emphasis falls off down the row, and never rises again.
        assert_eq!(RowPart::Primary.intent(), "content");
        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
        assert_eq!(RowPart::Meta.intent(), "content-muted");
    }

    #[test]
    fn a_separator_is_what_tells_a_section_from_a_subsection() {
        assert!(Heading::Section.separated());
        assert!(!Heading::Subsection.separated());
        assert!(!Heading::Page.separated());
    }

    #[test]
    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
        // The exception, and the whole folder semantic: the open tab joins its
        // pane rather than sinking away from it.
        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);

        // A held-in segment is indistinguishable from a pressed raised one,
        // which is the economy the light model buys over a colour swap.
        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());

        // A toggle stands alone; the other two are built out of parts that
        // touch.
        assert!(Selector::Segmented.abutting());
        assert!(Selector::Tabs.abutting());
        assert!(!Selector::Toggle.abutting());
    }

    #[test]
    fn a_pane_is_looked_into_and_a_band_is_not() {
        assert_eq!(Region::Pane.depth(), Depth::Well);
        assert_eq!(Region::Modal.depth(), Depth::Raised);
        for r in [
            Region::Band,
            Region::Sidebar,
            Region::Split,
            Region::TabGroup,
        ] {
            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
        }
    }

    #[test]
    fn exactly_one_region_is_opaque() {
        // The escape hatch is one member and stays one member. If a second
        // undescribed region ever appears, the description has started
        // conceding rather than deferring.
        for r in [
            Region::Band,
            Region::Sidebar,
            Region::Pane,
            Region::Split,
            Region::TabGroup,
            Region::Modal,
        ] {
            assert!(r.described(), "{r:?} should be describable");
        }
        assert!(!Region::Bespoke { name: "day-plan" }.described());
    }

    #[test]
    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
        // The app owns the contents, not the placement. An app that wants its
        // timeline in a well frames it in a Pane.
        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
    }

    #[test]
    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
        // The argument the member exists for: goingson's day-plan has to be
        // routable, or the description covers only the boring screens and the
        // interesting four need a second path beside the router.
        let day_plan = [
            Region::Band,
            Region::Bespoke { name: "day-plan" },
            Region::Sidebar,
        ];
        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
    }

    #[test]
    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
        let secret = Field::new(FieldKind::Secret, "password", "Password");
        assert!(secret.kind.confidential());
        assert!(secret.kind.visible());

        assert!(!FieldKind::Hidden.visible());
        // Nothing else is confidential, or the marker means nothing.
        for k in [
            FieldKind::Text,
            FieldKind::Number,
            FieldKind::Textarea,
            FieldKind::Select,
            FieldKind::Checkbox,
            FieldKind::Hidden,
        ] {
            assert!(!k.confidential(), "{k:?} should not be confidential");
        }

        // Only a checkbox carries its own label.
        assert!(FieldKind::Checkbox.labels_itself());
        assert!(!FieldKind::Text.labels_itself());
    }

    #[test]
    fn a_field_reports_its_own_error_state() {
        let mut f = Field::new(FieldKind::Text, "title", "Title");
        assert!(!f.invalid());
        f.error = Some("Required");
        assert!(f.invalid());
    }

    #[test]
    fn columns_drop_by_priority_and_never_by_position() {
        let cols = [
            Column {
                name: "Title",
                width: Width::Fill,
                priority: Priority::Essential,
            },
            Column {
                name: "Due",
                width: Width::Fixed,
                priority: Priority::Secondary,
            },
            Column {
                name: "Estimate",
                width: Width::Fixed,
                priority: Priority::Optional,
            },
        ];

        // Widest: everything survives.
        assert_eq!(
            cols.iter()
                .filter(|c| c.kept_at(Priority::Optional))
                .count(),
            3
        );
        // Narrower: the optional column goes first.
        let kept: Vec<_> = cols
            .iter()
            .filter(|c| c.kept_at(Priority::Secondary))
            .map(|c| c.name)
            .collect();
        assert_eq!(kept, ["Title", "Due"]);
        // Narrowest: only what identifies the row.
        let kept: Vec<_> = cols
            .iter()
            .filter(|c| c.kept_at(Priority::Essential))
            .map(|c| c.name)
            .collect();
        assert_eq!(kept, ["Title"]);
    }

    #[test]
    fn inserting_a_column_does_not_move_what_gets_dropped() {
        // The bug the ordinal form has and this form cannot: goingson hides
        // `nth-child(n+5)` against a seven-column table, so a column inserted
        // anywhere to the left silently hides a different one.
        let before = [
            Column::new("Title"),
            Column {
                name: "Estimate",
                width: Width::Fixed,
                priority: Priority::Optional,
            },
        ];
        let after = [
            Column::new("Title"),
            Column::new("Project"), // inserted
            Column {
                name: "Estimate",
                width: Width::Fixed,
                priority: Priority::Optional,
            },
        ];

        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
            cols.iter()
                .filter(|c| !c.kept_at(Priority::Secondary))
                .map(|c| c.name)
                .collect()
        }
        assert_eq!(dropped(&before), ["Estimate"]);
        assert_eq!(dropped(&after), ["Estimate"]);
    }

    #[test]
    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
        // goingson uses the tab group inside the content region rather than
        // instead of one, so it is not a third arrangement.
        let go = Arrangement::ListDetail { tabbed: true };
        let plain = Arrangement::ListDetail { tabbed: false };
        assert_ne!(go, plain);
        assert_ne!(go, Arrangement::SidebarContent);
    }

    #[test]
    fn readiness_names_the_state_and_not_the_shimmer() {
        // Two members and no third. If a skeleton ever appears in this enum,
        // the deferral rule has been broken.
        assert_ne!(Readiness::Ready, Readiness::Pending);
    }
}