makeover-tui 0.36.0

The terminal renderer for makeover-layout, on ratatui. Colour stops being the constraint above 256 entries; geometry never does, because an edge occupies a whole cell on every side.
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
//! The pieces every terminal app draws, drawn once.
//!
//! # Called `widget` until 0.19.0
//!
//! Renamed because `makeover-layout` 0.20.0 took the word for something else,
//! and the two meanings do not sit together. A `Region::Widget` there is
//! host-agnostic: a named assembly of primitives that every renderer draws its
//! own way. What is in this module is the opposite end — renderer-local, the
//! answer to *what a meter looks like in cells*, taking a description plus what
//! only a terminal knows.
//!
//! One word for both would have made the tier unreadable in the crate that
//! implements it. This half moved because the other half is the ecosystem-facing
//! one: a second or third party naming a widget is naming the layout kind, and
//! nothing outside this tree ever needed a word for a drawing routine.
//!
//! `WidgetStyle` went with it and is `PieceStyle`.
//!
//! Arrived in 0.16.0 out of `quasi-tui`, which had written all of them and was
//! the second consumer to do so. A meter, a badge, a control, a figure and a
//! form field are what a screen is made of below the level [`table`](crate::table)
//! works at, and every one of them had been hand-rolled at least twice in this
//! tree before it was lifted.
//!
//! [`activity`] and [`awaiting`] joined them in 0.35.0, out of wiki
//! `loading-and-progress-standard`. They are the one pair here that arrived
//! before their second consumer rather than after it: nothing in the tree drew
//! a wait at all, on any surface, which is why the crate that had the vocabulary
//! for one had never been asked for the drawing.
//!
//! # What these take, and what they leave alone
//!
//! Each takes a `makeover-layout` description, a [`PieceStyle`], and whatever
//! the *host* knows that a description never carries. That last part is the
//! shape worth copying: [`field`] takes what is currently typed in the box as a
//! separate argument, because [`Field`] deliberately does not carry a value and
//! is not going to. `makeover-immediate` reached the same seam from the other
//! side with its `Filling`, and [`Held`] is that seam here.
//!
//! Focus is the other one. Nothing in a description says which control the user
//! is on, so every drawing here takes `focused` as an argument and the caller
//! is what counts. What focus *looks like* is this crate's answer and not the
//! caller's, which is the point of it being here: see
//! [`PieceStyle::focused`].
//!
//! # What they do not do
//!
//! No layout. Each answers rows for a width, or draws into the rect it is
//! given, top-aligned, and never below it. Nothing here measures twice and
//! nothing here places anything relative to anything else, because the moment
//! it did it would be a layout engine with one consumer's flow baked into it.

use makeover_layout::{Act, Awaiting, Field, FieldKind, Figure, Heading, Meter, Token, Tone};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

use crate::text;
use std::time::Duration;

/// The colours and marks the drawings below use.
///
/// [`TableStyle`](crate::table::TableStyle)'s shape, for its reasons: an
/// ungated struct of styles with a [`Default`], plus a
/// [`from_theme`](Self::from_theme) that is what a consumer holding a loaded
/// theme should reach for first. A consumer painting bevels and nothing else
/// should not have to supply text tones it never uses, and gating the whole
/// module on `theme` would make these unreachable to anyone hand-picking
/// colours.
///
/// The default is the one that survives a terminal with no colour at all:
/// modifiers only, no foreground anywhere. That is not a placeholder. A
/// two-colour terminal is the case where a `Style` carrying a foreground is a
/// foreground that will not land, and bold-and-reversed is what is left.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PieceStyle {
    /// Ordinary content, and what [`Tone::Neutral`] reads as.
    pub content: Style,
    /// Content one step back: a field's label, a quoted run.
    pub secondary: Style,
    /// Content two steps back: a caption, a hint, a meter's reading.
    pub muted: Style,
    /// Something worth knowing and nothing to do about it.
    pub info: Style,
    /// Something finished and it worked.
    pub success: Style,
    /// Something the user should look at.
    pub warning: Style,
    /// Something broken, or about to be destroyed.
    pub danger: Style,
    /// A page title.
    pub page: Style,
    /// A section title.
    pub section: Style,
    /// A subsection title.
    pub subsection: Style,
    /// Text that goes somewhere, and a control's label.
    pub action: Style,
    /// A control filled with the action colour, for the one on a screen that is
    /// the thing to press. A form's submit is the case that has it.
    pub filled: Style,
    /// A surface set back from the one it sits on, by colour and nothing else.
    /// What a code run takes, since every cell is monospace and the thing a
    /// webview says with a typeface cannot be said that way here.
    pub sunken: Style,
    /// What "you are on this one" adds to whatever it lands on.
    ///
    /// Reversed video by default, which is the affordance a cell has left once
    /// colour is spent on tone and bold on weight. A webview says it with an
    /// outline; a terminal has no outline that is not four more cells.
    pub focus: Modifier,
    /// How many cells [`meter`] spends on its bar.
    pub meter_cells: u16,
    /// The filled part of a bar.
    pub meter_full: char,
    /// The empty part of a bar.
    pub meter_empty: char,
    /// What marks a compulsory field, appended to its label.
    ///
    /// A knob for `makeover-immediate`'s reason: it is the one piece of *copy*
    /// here, and copy is not a renderer's call.
    pub required_marker: &'static str,
}

impl Default for PieceStyle {
    /// Modifiers only, no foreground: what survives a terminal with two
    /// colours.
    fn default() -> Self {
        Self {
            content: Style::new(),
            secondary: Style::new(),
            muted: Style::new().add_modifier(Modifier::DIM),
            info: Style::new(),
            success: Style::new(),
            warning: Style::new(),
            danger: Style::new().add_modifier(Modifier::BOLD),
            page: Style::new().add_modifier(Modifier::BOLD),
            section: Style::new().add_modifier(Modifier::BOLD),
            subsection: Style::new(),
            action: Style::new().add_modifier(Modifier::UNDERLINED),
            filled: Style::new().add_modifier(Modifier::REVERSED),
            sunken: Style::new().add_modifier(Modifier::DIM),
            focus: Modifier::REVERSED,
            meter_cells: 10,
            meter_full: '#',
            meter_empty: '-',
            required_marker: "*",
        }
    }
}

impl PieceStyle {
    /// The house widgets, from a loaded theme.
    ///
    /// The lift this module exists for. `quasi-tui` carried every line of this
    /// as private methods on its own renderer; a second terminal app wanting a
    /// toned control had no way to reach them and would have picked its own
    /// colours for the same five tones.
    #[cfg(feature = "theme")]
    #[must_use]
    pub fn from_theme(theme: &crate::Theme) -> Self {
        Self {
            content: Style::new().fg(theme.content_primary),
            secondary: Style::new().fg(theme.content_secondary),
            muted: Style::new().fg(theme.content_muted),
            info: Style::new().fg(theme.status_info),
            success: Style::new().fg(theme.status_success),
            warning: Style::new().fg(theme.status_warning),
            danger: Style::new().fg(theme.status_danger),
            // Three depths and two of them are bold, which is the whole of what
            // a terminal has: there is no type scale in a grid of one cell
            // size. A page title takes bold and the accent, a section bold, a
            // subsection the secondary colour. That is the emphasis order a
            // webview's type scale says with size, said with the two axes a
            // cell has.
            page: Style::new()
                .fg(theme.action_primary)
                .add_modifier(Modifier::BOLD),
            section: Style::new()
                .fg(theme.content_primary)
                .add_modifier(Modifier::BOLD),
            subsection: Style::new().fg(theme.content_secondary),
            action: Style::new().fg(theme.action_primary),
            filled: Style::new().fg(theme.selection_on).bg(theme.action_primary),
            sunken: Style::new().bg(theme.surface_sunken),
            focus: Modifier::REVERSED,
            meter_cells: 10,
            meter_full: '#',
            meter_empty: '-',
            required_marker: "*",
        }
    }

    /// The style a tone reads as.
    ///
    /// [`Tone`] is closed and stays closed, so this is total and needs no
    /// fallback arm.
    #[must_use]
    pub const fn tone(&self, tone: Tone) -> Style {
        match tone {
            Tone::Neutral => self.content,
            Tone::Info => self.info,
            Tone::Success => self.success,
            Tone::Warning => self.warning,
            Tone::Danger => self.danger,
        }
    }

    /// The style a heading reads as.
    #[must_use]
    pub const fn heading(&self, level: Heading) -> Style {
        match level {
            Heading::Page => self.page,
            Heading::Section => self.section,
            Heading::Subsection => self.subsection,
        }
    }

    /// `style`, plus the mark that says the user is on this one.
    ///
    /// Takes the flag rather than being called behind an `if`, because every
    /// caller has a bool in hand and the branch is the part that gets forgotten.
    #[must_use]
    pub fn focused(&self, focused: bool, style: Style) -> Style {
        if focused {
            style.add_modifier(self.focus)
        } else {
            style
        }
    }
}

/// What a field currently holds, which a description never carries.
///
/// The terminal counterpart of `makeover_immediate::Filling`, and the same seam:
/// there the widget writes through a `&mut` as the value is edited, and here the
/// caller keeps an edit buffer and lends it out for the draw. Neither is
/// something [`Field`] could carry without becoming a form model.
///
/// An enum rather than a bag of options, for `Filling`'s reason: a checkbox
/// holding a string is unsayable here, where a struct would let it be said and
/// then have to cope.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Held<'a> {
    /// Nothing typed and nothing chosen. The control draws empty.
    #[default]
    Absent,
    /// What is in the box, or the `value` of the chosen [`Choice`].
    ///
    /// [`Choice`]: makeover_layout::Choice
    Text(&'a str),
    /// A checkbox, on or off.
    On(bool),
    /// Both ends of a [`FieldKind::Interval`], lower first.
    ///
    /// Two values rather than one string with a separator, which is
    /// [`makeover_layout::Field::upper_name`]'s reason one level down: an
    /// interval is submitted under two names, so it is held as two values, and
    /// a delimiter this crate owned could appear inside either of them.
    ///
    /// Either end may be empty while the other stands. An open end is an
    /// answer -- "over 120 BPM" -- rather than a half-filled box.
    ///
    /// Added 0.33.0 with makeover-layout 0.34.0.
    Between {
        /// What the lower box holds now.
        lower: &'a str,
        /// What the upper box holds now.
        upper: &'a str,
    },
}

impl<'a> Held<'a> {
    /// What is typed, as a string. A checkbox has no text and answers empty.
    #[must_use]
    pub const fn text(self) -> &'a str {
        match self {
            Self::Text(text) | Self::Between { lower: text, .. } => text,
            Self::Absent | Self::On(_) => "",
        }
    }

    /// The upper end, for the one variant that has one.
    #[must_use]
    pub const fn upper(self) -> &'a str {
        match self {
            Self::Between { upper, .. } => upper,
            Self::Absent | Self::Text(_) | Self::On(_) => "",
        }
    }

    /// Whether a checkbox is ticked.
    #[must_use]
    pub const fn on(self) -> bool {
        matches!(self, Self::On(true))
    }
}

/// What a host can see about a wait that is running.
///
/// Neither half is derivable from a description, which is why both are here and
/// not on [`Awaiting`]. That type says how big the payload is; how much of it
/// has landed is a fact about a transfer in flight, and only whoever is running
/// the transfer knows it.
///
/// The same shape `makeover-immediate` carries, deliberately: a wait is one
/// reading on every surface and the two renderers should not disagree about
/// what a host owes them.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Progress {
    /// How much has arrived, in whatever unit the description counted.
    pub delivered: Option<u64>,
    /// How long the wait has lasted so far.
    ///
    /// The one time value a wait may show. See [`awaiting`] for the three it
    /// may not.
    pub elapsed: Option<Duration>,
}

/// The activity mark: one cell, lit or dark.
///
/// Rule 2 of wiki `loading-and-progress-standard`, and the surface the metaphor
/// came from. A hard-disk light is one cell that blinks, and a terminal draws
/// that with no metaphor in the way — where a webview needs a keyframe and egui
/// needs a repaint schedule, this is a character.
///
/// The two glyphs are [`PieceStyle::meter_full`] and
/// [`PieceStyle::meter_empty`], not a third pair. A bar's filled cell and a lit
/// mark are the same statement in the same alphabet, and a terminal that had to
/// render two vocabularies of "on" would be saying there are two kinds of on.
///
/// **Dark, not absent.** A mark that is drawn half the time is a hole in the
/// line, and the line reflows around it or the reader loses where to look. It
/// occupies its cell either way.
///
/// `lit` is the caller's: this module holds no clock. [`crate::activity_lit`]
/// is the one place the phase is worked out from the cadence, so a caller
/// should reach for that rather than dividing by 500 itself.
#[must_use]
pub fn activity(style: &PieceStyle, lit: bool) -> Span<'static> {
    if lit {
        Span::styled(style.meter_full.to_string(), style.action)
    } else {
        Span::styled(style.meter_empty.to_string(), style.muted)
    }
}

/// A wait as one line, drawn from what is actually known about it.
///
/// [`Awaiting::is_determinate`] is the first branch and there is a second the
/// description cannot answer: whether anything is watching the transfer. A bar
/// wants a total and a numerator both, so a described amount with no
/// [`Progress::delivered`] beside it draws the mark and the size it is waiting
/// on, rather than an empty trough implying somebody is counting.
///
/// So three drawings for three states, which is the point:
///
/// ```text
/// unmeasured                       #            a blinking cell
/// measured, nothing watching       # 41943040   the cell, and how much there is
/// measured and observed            ####------ 17825792/41943040  4s
/// ```
///
/// **What the bar may not do**, from rule 1 of the standard and from
/// [`Awaiting`]'s own docs: what is done over what there is, plus the time it
/// has taken. Never a remaining time, an arrival time, or a rate extrapolated
/// forward. A prediction is wrong the moment the transfer stalls, and being
/// confidently wrong is worse than being honestly indeterminate.
///
/// The numbers are raw. The unit is the app's — bytes for an upload, rows for
/// an import — and a renderer that formatted one as a file size would be
/// dressing up a quantity it was deliberately not told about.
#[must_use]
pub fn awaiting(
    style: &PieceStyle,
    awaiting: Awaiting,
    progress: Progress,
    lit: bool,
) -> Line<'static> {
    let Some(total) = awaiting.amount else {
        return Line::from(vec![activity(style, lit)]);
    };
    let Some(done) = progress.delivered else {
        return Line::from(vec![
            activity(style, lit),
            Span::styled(format!(" {total}"), style.muted),
        ]);
    };
    let cells = u32::from(style.meter_cells);
    // In cells rather than in floating point, the way `meter` does it: a
    // terminal's bar has ten states and rounding through an f64 to reach one of
    // ten is arithmetic nobody needs. Saturating rather than wrapping, because
    // a transfer that over-delivers is a real case and a panicking bar is not
    // the way to report it.
    let filled = u32::try_from(
        done.saturating_mul(u64::from(cells))
            .checked_div(total)
            .unwrap_or(0),
    )
    .unwrap_or(cells)
    .min(cells);
    let bar = format!(
        "{}{}",
        style.meter_full.to_string().repeat(filled as usize),
        style
            .meter_empty
            .to_string()
            .repeat((cells - filled) as usize)
    );
    let reading = match progress.elapsed {
        Some(elapsed) => format!(" {done}/{total}  {}s", elapsed.as_secs()),
        None => format!(" {done}/{total}"),
    };
    Line::from(vec![
        Span::styled(bar, style.action),
        Span::styled(reading, style.muted),
    ])
}

/// A proportion as one line: the bar, then the reading beside it.
///
/// The reading is built here from the two numbers and the noun rather than
/// taken assembled, which is what [`Meter::label`] carrying the noun alone is
/// for: a terminal at one line and a tooltip want different sentence orders.
#[must_use]
pub fn meter(style: &PieceStyle, meter: &Meter<'_>) -> Line<'static> {
    let cells = u32::from(style.meter_cells);
    let filled = meter
        .done
        .checked_mul(cells)
        .and_then(|reached| reached.checked_div(meter.total))
        .unwrap_or(0)
        .min(cells);
    let bar = format!(
        "{}{}",
        style.meter_full.to_string().repeat(filled as usize),
        style
            .meter_empty
            .to_string()
            .repeat((cells - filled) as usize)
    );
    let reading = match meter.label {
        Some(label) => format!(" {}/{} {label}", meter.done, meter.total),
        None => format!(" {}/{}", meter.done, meter.total),
    };
    Line::from(vec![
        Span::styled(bar, style.tone(meter.tone)),
        Span::styled(reading, style.muted),
    ])
}

/// A badge or a chip as one span.
///
/// Round for a badge, square for a chip. A chip answers a press and a badge does
/// not, and the bracket is the only affordance a cell has left once colour is
/// spent on the tone.
///
/// `latched` is a chip that is switched on, and it reads as reversed. So does
/// focus, which is a collision a terminal cannot avoid: latched is "this filter
/// is on" and focused is "you are here", and there is one spare axis for two
/// facts. Said here rather than resolved by inventing a third look nobody would
/// read.
///
/// A chip's removable half is not drawn. The `x` a webview hangs on a chip is a
/// second control inside one span, and a terminal reaches a control by focusing
/// it; two targets in one cell run is a question for whoever owns the
/// interaction, not for a drawing.
#[must_use]
pub fn token(
    style: &PieceStyle,
    label: &str,
    kind: Token,
    tone: Tone,
    latched: bool,
    focused: bool,
) -> Span<'static> {
    let painted = style.tone(tone);
    let painted = if latched {
        painted.add_modifier(style.focus)
    } else {
        style.focused(focused, painted)
    };
    match kind {
        Token::Badge => Span::styled(format!("({label})"), painted),
        Token::Chip { .. } => Span::styled(format!("[{label}]"), painted),
    }
}

/// A control as one line.
///
/// `< Label > (key)`, and the key only where the description named one. That
/// member is the one place `makeover-layout` anticipated a terminal before there
/// was one, and this is the renderer that reads it.
///
/// A disabled control is drawn muted and is not marked focused, whatever the
/// caller passed: it is present, visible and not answering, so a focus mark on
/// it would be an affordance that lies. Whether it is reachable at all is the
/// caller's count to keep — ask [`Act::disabled`].
#[must_use]
pub fn act(style: &PieceStyle, act: &Act<'_>, focused: bool) -> Line<'static> {
    let painted = if act.disabled() {
        style.muted
    } else {
        style.focused(focused, style.tone(act.tone))
    };
    let label = match act.key {
        Some(key) => format!("< {} > ({key})", act.label),
        None => format!("< {} >", act.label),
    };
    Line::from(Span::styled(label, painted))
}

/// A control filled with the action colour, for the one press a screen is about.
///
/// `[ Label ]` rather than `< Label >`, which is the weight difference a webview
/// carries as a primary-versus-secondary button. A form's submit is the case
/// this exists for.
#[must_use]
pub fn filled_act(style: &PieceStyle, label: &str, focused: bool) -> Line<'static> {
    Line::from(Span::styled(
        format!("[ {label} ]"),
        style.focused(focused, style.filled),
    ))
}

/// The rows [`figure`] wants at `width`.
#[must_use]
pub fn figure_height(figure: &Figure<'_>, width: u16) -> u16 {
    text::height(figure.value, width) + text::height(figure.caption, width)
}

/// A figure: the number, then what it counts under it.
///
/// The tone lands on the value and its change rather than on the caption, which
/// is what [`Figure::tone`] means: the figure is an ordinary fact and it is the
/// movement that reads as good or bad.
pub fn figure(style: &PieceStyle, figure: &Figure<'_>, area: Rect, buf: &mut Buffer) -> u16 {
    let value = match figure.change {
        Some(change) => format!("{} {change}", figure.value),
        None => figure.value.to_owned(),
    };
    let used = text::draw(
        &value,
        style.tone(figure.tone).add_modifier(Modifier::BOLD),
        area,
        buf,
    );
    used + text::draw(figure.caption, style.muted, below(area, used), buf)
}

/// The rows [`field`] wants at `width`.
///
/// A label row, the control's rows, and a row for whatever went wrong. A hidden
/// field is nothing at all, which is the one field kind a terminal and a webview
/// agree on completely.
#[must_use]
pub fn field_height(style: &PieceStyle, field: &Field<'_>, width: u16) -> u16 {
    if !field.kind.visible() {
        return 0;
    }
    let label = text::height(&label_of(style, field), width);
    // A range is one row like every other single control: the bar, its two ends
    // and the reading are one line by construction, and a bar that wrapped
    // would stop being a bar.
    let body = match field.kind {
        // Both multi-line kinds get the same three rows, keyed on the
        // description's own `multiline` rather than on the member: a markdown
        // field falling through to the single-row arm is one line for a value
        // whose whole point is that it has several. What a terminal does *with*
        // the markdown is another question and the answer here is nothing --
        // the source is the text, and drawing it as text is honest.
        kind if kind.multiline() => 3,
        kind if kind.offers_options() => u16::try_from(field.options.len()).unwrap_or(u16::MAX),
        _ => 1,
    };
    let note = message_of(style, field).map_or(0, |(text, _)| text::height(text, width));
    label + body + note
}

/// A question: its label, the box, and its standing help or what is wrong now.
///
/// `held` is what the user has done to it since the screen arrived, which is the
/// argument a description cannot supply. See [`Held`].
///
/// `focused` marks the box rather than the label, because the box is where the
/// typing lands.
pub fn field(
    style: &PieceStyle,
    field: &Field<'_>,
    held: Held<'_>,
    focused: bool,
    area: Rect,
    buf: &mut Buffer,
) -> u16 {
    // A hidden field is data travelling with the form. There is nothing to
    // draw, and whoever submits carries it.
    if !field.kind.visible() || area.width == 0 || area.height == 0 {
        return 0;
    }

    let mut used = text::draw(&label_of(style, field), style.secondary, area, buf);

    let well = style.focused(focused, style.content);
    let placeholder = field.placeholder.unwrap_or_default();

    used += match field.kind {
        FieldKind::Checkbox => text::draw(
            if held.on() { "[x]" } else { "[ ]" },
            well,
            below(area, used),
            buf,
        ),
        // A range's two ends are what the question means, so they are drawn
        // rather than left to a hint. A terminal has the bar already: this is
        // `meter`'s cells with the extent read out at either side of them.
        //
        // An unbounded range has no extent to draw and falls through to the
        // text path, which is `makeover-immediate`'s answer as well and for the
        // same reason: bounds this crate invented are bounds the user would
        // then drag against.
        FieldKind::Range if field.bounded() => {
            let line = range_line(style, field, held.text(), well);
            text::draw_line(&line, below(area, used), buf)
        }
        // One question, so one line. The two ends read left to right with the
        // word between them, which is what a terminal has instead of two boxes
        // side by side: a second row would read as a second question, and that
        // is the reading the kind exists to prevent.
        FieldKind::Interval => {
            let line = interval_line(style, field, held, well);
            text::draw_line(&line, below(area, used), buf)
        }
        kind if kind.offers_options() => {
            let mut rows = 0;
            for choice in field.options {
                let chosen = held.text() == choice.value;
                // An option that cannot be picked yet reads as inert, which is
                // the one place muted is the truth rather than the lie below:
                // it will not answer, and the reason it will not is on the row
                // beside it rather than nowhere.
                let (mark, painted, suffix) = match choice.unavailable {
                    Some(reason) => ("( )", style.muted, format!(": {reason}")),
                    None if chosen => ("(*)", well, String::new()),
                    // An option that is not chosen is still an option: pressing
                    // it chooses it. So it takes the secondary content intent
                    // and not the muted one, which is what disabled looks like
                    // (`State::Disabled` resolves to it). Muted here read as a
                    // list of five where four were greyed out.
                    None => ("( )", style.secondary, String::new()),
                };
                rows += text::draw(
                    &format!("{mark} {}{suffix}", choice.label),
                    painted,
                    below(area, used + rows),
                    buf,
                );
            }
            rows
        }
        // A secret's dots come from the caller's buffer and can come from
        // nowhere else: a password that comes back down the wire is a password
        // in a page and in a proxy log, so a description carries nothing to dot
        // out. This is the one control that would be undrawable without `held`.
        FieldKind::Secret if !held.text().is_empty() => {
            let dots = "*".repeat(held.text().chars().count());
            text::draw(&dots, well, below(area, used), buf).max(1)
        }
        // A file field has no way back on a terminal any more than it has on an
        // HTTP host. The name is drawn and picking one belongs to whoever owns
        // the interaction.
        //
        // makeover-layout 0.31.0 gave the description an accept list and a
        // multiplicity, and neither changes anything drawn here. Both are the
        // picker's business, and the picker is the caller's: this crate draws
        // what was picked. A terminal that grows its own picker reads them off
        // `Field::accept` and `Field::multiple` at that point rather than
        // through a second spelling invented here.
        _ if held.text().is_empty() => {
            empty_well(style, placeholder, well, focused, below(area, used), buf)
        }
        _ => text::draw(&measured(field, held.text()), well, below(area, used), buf),
    };

    // Error, then note, then hint -- the order `Field::note` names, and the
    // order a webview draws them in. Once something has gone wrong that is the
    // sentence worth the row; failing that, what the chosen answer costs beats
    // standing help about how the field works.
    match message_of(style, field) {
        Some((text, painted)) => used + text::draw(text, painted, below(area, used), buf),
        None => used,
    }
}

/// A bounded number as one line: the low end, the bar, the high end, then what
/// it currently reads.
///
/// The two ends are drawn because they are the question. A threshold of 0.72
/// says nothing without them, which is the whole argument for
/// [`FieldKind::Range`] being a kind rather than a number with bounds, and a
/// terminal is where it would be easiest to quietly drop them and show a figure.
///
/// The bar is [`meter`]'s cells, so a range and a proportion read as the same
/// object in the same app. What differs is the reading beside it: a meter counts
/// something and a range holds a value.
///
/// A value the host cannot read as a number empties the bar and is still shown
/// as itself. That is [`empty_well`]'s position on an unreadable value: the app
/// put it there, and a terminal that silently rounded it to a bound would be
/// reporting a value nobody set.
fn range_line(style: &PieceStyle, field: &Field<'_>, value: &str, well: Style) -> Line<'static> {
    let cells = usize::from(style.meter_cells);
    let ends = field
        .min
        .zip(field.max)
        .and_then(|(min, max)| Some((min.parse::<f64>().ok()?, max.parse::<f64>().ok()?)));
    let filled = match (ends, value.parse::<f64>()) {
        (Some((min, max)), Ok(number)) if max > min => {
            // Where the value sits is the curve's answer, not a proportion of
            // the extent (makeover-layout 0.32.0). Under `Curve::Linear` the two
            // are the same number, which is why the bar was right before and is
            // unchanged for every range described so far; under a constant ratio
            // they are not, and a bar drawn linearly would put an envelope's
            // whole useful half inside its first cell.
            #[expect(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                reason = "`position_of` returns 0..=1, and the cell count came from a u16"
            )]
            let reached = (field.curve.position_of(number, min, max) * cells as f64) as usize;
            reached.min(cells)
        }
        _ => 0,
    };
    let bar = format!(
        "{}{}",
        style.meter_full.to_string().repeat(filled),
        style.meter_empty.to_string().repeat(cells - filled)
    );
    Line::from(vec![
        Span::styled(format!("{} ", field.min.unwrap_or_default()), style.muted),
        Span::styled(bar, well),
        Span::styled(format!(" {}", field.max.unwrap_or_default()), style.muted),
        Span::styled(format!(" {}", measured(field, value)), well),
    ])
}

/// An interval as one line: the low end, the word, the high end.
///
/// One line because it is one question. Two rows would read as two questions,
/// which is exactly what [`FieldKind::Interval`] exists to stop the description
/// saying, and a terminal has no side-by-side boxes to fall back on.
///
/// # An open end draws the bound it falls back to
///
/// Muted, because it is where the axis ends rather than a value anybody set.
/// With no bound to fall back on there is nothing honest to draw and the end
/// stays blank: a terminal inventing a number here would report a filter the
/// user never applied, which is [`range_line`]'s position on an unreadable
/// value.
///
/// # The word, not a dash
///
/// A dash between two numbers is a minus sign to anyone reading a signed axis,
/// and half the measured axes are signed -- audiofiles filters loudness in
/// dBFS. `to` costs two cells and cannot be misread.
fn interval_line(
    style: &PieceStyle,
    field: &Field<'_>,
    held: Held<'_>,
    well: Style,
) -> Line<'static> {
    let end = |value: &str, fallback: Option<&str>| match (value.is_empty(), fallback) {
        (false, _) => Span::styled(measured(field, value), well),
        (true, Some(bound)) => Span::styled(measured(field, bound), style.muted),
        (true, None) => Span::styled(String::new(), style.muted),
    };
    Line::from(vec![
        end(held.text(), field.min),
        Span::styled(" to ", style.secondary),
        end(held.upper(), field.max),
    ])
}

/// The unit to draw beside this field's value, if there is one to draw.
///
/// Two conditions rather than one: the field has to carry a unit and its kind
/// has to be one that means anything by it. `FieldKind::measurable` is the
/// description answering the second, so this renderer keeps no list of its own
/// of which kinds are quantities.
fn unit_of<'a>(field: &Field<'a>) -> Option<&'a str> {
    field.unit.filter(|_| field.kind.measurable())
}

/// A value with what it is measured in, as one string.
///
/// The unit rides on the value rather than on the label, which is
/// `makeover-layout` 0.33.0's rule and is what a terminal wants anyway: the
/// label is a line above and the number is the line the eye is on.
fn measured(field: &Field<'_>, value: &str) -> String {
    match unit_of(field) {
        Some(unit) => format!("{value} {unit}"),
        None => value.to_owned(),
    }
}

/// The label, marked where the field is compulsory.
fn label_of(style: &PieceStyle, field: &Field<'_>) -> String {
    if field.required {
        format!("{} {}", field.label, style.required_marker)
    } else {
        field.label.to_owned()
    }
}

/// What goes under the box, and how it is painted.
///
/// A terminal field has room for exactly one line, so the three message
/// channels compete for it and the precedence is decided in
/// [`makeover_layout::Field::note`]'s docs rather than three times here:
/// **error, then note, then hint**. What is wrong outranks what the answer
/// costs, which outranks how the field works.
///
/// The tone comes with the note; an error is always danger and a hint is
/// always muted, because neither carries one.
fn message_of<'a>(style: &PieceStyle, field: &Field<'a>) -> Option<(&'a str, Style)> {
    if let Some(error) = field.error {
        return Some((error, style.danger));
    }
    if let Some((tone, note)) = field.note {
        return Some((note, style.tone(tone)));
    }
    field.hint.map(|hint| (hint, style.muted))
}

/// A box with nothing in it: the ghost text, and the caret when it has focus.
///
/// The caret is not decoration. An empty field under a style is an empty field,
/// so a focused one with no placeholder drew literally nothing and there was no
/// way to tell the box was where the typing would go. A browser has a blinking
/// bar for this and gets it without asking; a terminal has one cell of reversed
/// video, put on the first column, which is where the first character lands.
fn empty_well(
    style: &PieceStyle,
    placeholder: &str,
    well: Style,
    focused: bool,
    area: Rect,
    buf: &mut Buffer,
) -> u16 {
    let used = text::draw(placeholder, style.muted, area, buf).max(1);
    if focused
        && area.height > 0
        && area.width > 0
        && let Some(cell) = buf.cell_mut((area.x, area.y))
    {
        cell.set_style(well);
    }
    used
}

/// What is left of `area` after `used` rows from the top.
fn below(area: Rect, used: u16) -> Rect {
    let used = used.min(area.height);
    Rect {
        x: area.x,
        y: area.y + used,
        width: area.width,
        height: area.height - used,
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn one_line_takes_the_error_then_the_note_then_the_hint() {
        // A terminal field has room for exactly one message, so the three
        // channels compete and `Field::note` decides the order.
        let style = PieceStyle::default();
        let mut f = Field::new(FieldKind::Text, "title", "Title");
        f.hint = Some("how it works");
        assert_eq!(message_of(&style, &f).unwrap().0, "how it works");

        f.note = Some((Tone::Warning, "what it costs"));
        assert_eq!(message_of(&style, &f).unwrap().0, "what it costs");
        assert_eq!(message_of(&style, &f).unwrap().1, style.warning);

        f.error = Some("what is wrong");
        assert_eq!(message_of(&style, &f).unwrap().0, "what is wrong");
        assert_eq!(message_of(&style, &f).unwrap().1, style.danger);

        // A note carries its own tone, so a quiet one is not painted as a
        // warning just for being a note.
        f.error = None;
        f.note = Some((Tone::Neutral, "an ordinary fact"));
        assert_eq!(message_of(&style, &f).unwrap().1, style.content);
    }
    use super::*;
    use makeover_layout::{Choice, State};

    /// The style the drawings are read against: one distinguishable modifier
    /// per role, so a test can say which style landed without a colour.
    fn style() -> PieceStyle {
        PieceStyle {
            content: Style::new().add_modifier(Modifier::BOLD),
            secondary: Style::new().add_modifier(Modifier::ITALIC),
            muted: Style::new().add_modifier(Modifier::DIM),
            danger: Style::new().add_modifier(Modifier::CROSSED_OUT),
            ..PieceStyle::default()
        }
    }

    fn buffer(width: u16, height: u16) -> Buffer {
        Buffer::empty(Rect::new(0, 0, width, height))
    }

    /// Everything in the buffer, one string per row.
    fn rows(buf: &Buffer) -> Vec<String> {
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| {
                        buf.cell((x, y))
                            .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '))
                    })
                    .collect::<String>()
                    .trim_end()
                    .to_owned()
            })
            .collect()
    }

    #[test]
    fn a_bar_fills_in_proportion_and_reads_out_the_two_numbers() {
        let style = style();
        let line = meter(&style, &Meter::new(3, 10).label("subtasks"));
        let drawn: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(drawn, "###------- 3/10 subtasks");
        // The noun is optional and the ratio is not, because a bar with no
        // reading is a bar you cannot check.
        let bare = meter(&style, &Meter::new(3, 10));
        let drawn: String = bare.spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(drawn, "###------- 3/10");
    }

    #[test]
    fn an_empty_set_is_an_empty_bar_rather_than_a_divide_by_zero() {
        // `Meter::total` of zero means there is no set, and the checked
        // division is what keeps that from being a panic in a draw.
        let line = meter(&style(), &Meter::new(0, 0));
        let drawn: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(drawn, "---------- 0/0");
    }

    #[test]
    fn an_over_run_fills_the_bar_and_still_reports_the_overflow() {
        // The clamp is for drawing only. The reading is what keeps the fact
        // `Meter::percent` destroys.
        let line = meter(&style(), &Meter::new(14, 10));
        let drawn: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(drawn, "########## 14/10");
    }

    #[test]
    fn a_badge_is_round_and_a_chip_is_square() {
        // The one affordance a cell has left once colour is spent on the tone,
        // and the whole of how a terminal says "this one answers a press".
        let style = style();
        let badge = token(&style, "draft", Token::Badge, Tone::Neutral, false, false);
        assert_eq!(badge.content.as_ref(), "(draft)");
        let chip = token(
            &style,
            "rust",
            Token::Chip { removable: false },
            Tone::Neutral,
            false,
            false,
        );
        assert_eq!(chip.content.as_ref(), "[rust]");
    }

    #[test]
    fn a_latched_chip_reads_the_same_as_a_focused_one() {
        // The collision a terminal cannot avoid, asserted rather than left to
        // be rediscovered: latched is "this filter is on" and focused is "you
        // are here", and there is one spare axis for two facts.
        let style = style();
        let kind = Token::Chip { removable: false };
        let latched = token(&style, "rust", kind, Tone::Neutral, true, false);
        let focused = token(&style, "rust", kind, Tone::Neutral, false, true);
        assert_eq!(latched.style, focused.style);
        assert!(latched.style.add_modifier.contains(Modifier::REVERSED));
    }

    #[test]
    fn a_control_draws_its_key_only_where_one_was_named() {
        let style = style();
        let line = act(&style, &Act::new("Delete"), false);
        assert_eq!(line.spans[0].content.as_ref(), "< Delete >");
        let line = act(&style, &Act::new("Quit").key("q"), false);
        assert_eq!(line.spans[0].content.as_ref(), "< Quit > (q)");
    }

    #[test]
    fn a_disabled_control_is_never_marked_focused() {
        // Present, visible, and not answering. A focus mark on it would be an
        // affordance that lies, so the flag is overridden rather than trusted.
        let style = style();
        let disabled = Act::new("Save").state(State::Disabled);
        let line = act(&style, &disabled, true);
        assert!(
            !line.spans[0]
                .style
                .add_modifier
                .contains(Modifier::REVERSED)
        );
        assert_eq!(line.spans[0].style, style.muted);
        // The same call on a control the description says nothing about: the
        // mark is this renderer's own focus flag and always was, which is why
        // only `Disabled` can override it.
        let unstated = Act::new("Save");
        let line = act(&style, &unstated, true);
        assert!(
            line.spans[0]
                .style
                .add_modifier
                .contains(Modifier::REVERSED)
        );
    }

    #[test]
    fn a_danger_control_keeps_its_tone_under_focus() {
        // Focus adds a modifier rather than repainting, so the fact that this
        // is the button that destroys something survives being landed on.
        let style = style();
        let line = act(&style, &Act::new("Delete").tone(Tone::Danger), true);
        assert_eq!(
            line.spans[0].style.add_modifier,
            style.danger.add_modifier | Modifier::REVERSED
        );
    }

    #[test]
    fn a_figure_puts_the_number_over_what_it_counts() {
        let style = style();
        let figure_ = Figure::new("42", "open tasks");
        let mut buf = buffer(20, 4);
        let used = figure(&style, &figure_, buf.area, &mut buf);
        assert_eq!(used, 2);
        assert_eq!(rows(&buf)[..2], ["42".to_owned(), "open tasks".to_owned()]);
        assert_eq!(figure_height(&figure_, 20), 2);
    }

    #[test]
    fn a_figures_change_rides_on_the_value_row() {
        // The delta is the toned part and the value is an ordinary fact, so the
        // two share a row rather than the caption growing a second sentence.
        let style = style();
        let figure_ = Figure::new("42", "open tasks")
            .change("+3")
            .tone(Tone::Success);
        let mut buf = buffer(20, 4);
        figure(&style, &figure_, buf.area, &mut buf);
        assert_eq!(rows(&buf)[0], "42 +3");
    }

    #[test]
    fn a_compulsory_field_says_so_in_its_label() {
        let style = style();
        let mut field_ = Field::new(FieldKind::Text, "email", "Email");
        field_.required = true;
        let mut buf = buffer(20, 4);
        field(&style, &field_, Held::Absent, false, buf.area, &mut buf);
        assert_eq!(rows(&buf)[0], "Email *");
    }

    #[test]
    fn a_hidden_field_costs_no_rows_at_all() {
        // The one field kind a terminal and a webview agree on completely.
        let style = style();
        let field_ = Field::new(FieldKind::Hidden, "csrf", "Token");
        let mut buf = buffer(20, 4);
        assert_eq!(
            field(
                &style,
                &field_,
                Held::Text("abc"),
                false,
                buf.area,
                &mut buf
            ),
            0
        );
        assert_eq!(field_height(&style, &field_, 20), 0);
        assert_eq!(rows(&buf)[0], "");
    }

    #[test]
    fn a_secret_is_dotted_from_the_callers_buffer_and_never_from_the_description() {
        // The one control that would be undrawable without `held`: a password
        // that came back down the wire is a password in a page and in a log.
        let style = style();
        let field_ = Field::new(FieldKind::Secret, "password", "Password");
        let mut buf = buffer(20, 4);
        field(
            &style,
            &field_,
            Held::Text("hunter2"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1], "*******");
    }

    #[test]
    fn an_error_takes_the_row_the_hint_would_have_had() {
        // Once something has gone wrong that is the sentence worth the row,
        // which is the order a webview uses too.
        let style = style();
        let mut field_ = Field::new(FieldKind::Text, "email", "Email");
        field_.hint = Some("work address");
        field_.error = Some("not an address");
        let mut buf = buffer(20, 5);
        field(
            &style,
            &field_,
            Held::Text("nope"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[2], "not an address");
        assert_eq!(field_height(&style, &field_, 20), 3);
    }

    #[test]
    fn a_focused_empty_box_shows_where_the_typing_will_land() {
        // An empty field under a style is an empty field. Without the caret a
        // focused box with no placeholder drew literally nothing.
        let style = style();
        let field_ = Field::new(FieldKind::Text, "email", "Email");
        let mut buf = buffer(20, 4);
        field(&style, &field_, Held::Absent, true, buf.area, &mut buf);
        let caret = buf.cell((0, 1)).expect("the well's first cell").style();
        assert!(caret.add_modifier.contains(Modifier::REVERSED));
    }

    #[test]
    fn a_choice_field_marks_the_chosen_option_and_costs_a_row_each() {
        let style = style();
        let mut field_ = Field::new(FieldKind::Radio, "size", "Size");
        let options = [Choice::plain("small"), Choice::plain("large")];
        field_.options = &options;
        let mut buf = buffer(20, 5);
        field(
            &style,
            &field_,
            Held::Text("large"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1], "( ) small");
        assert_eq!(rows(&buf)[2], "(*) large");
        assert_eq!(field_height(&style, &field_, 20), 3);
    }

    #[test]
    fn a_range_draws_its_two_ends_and_where_the_value_sits_between_them() {
        let style = style();
        let field_ = Field::range("review", "Review above", "0", "1");
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Text("0.5"),
            false,
            buf.area,
            &mut buf,
        );
        // Ten cells by default, half of them filled, with the extent read out
        // at either side: 0.5 means nothing without the 0 and the 1.
        assert_eq!(rows(&buf)[1].trim_end(), "0 #####----- 1 0.5");
        assert_eq!(field_height(&style, &field_, 40), 2);
    }

    #[test]
    fn a_unit_rides_on_the_value_and_not_on_the_label() {
        // The label is a line above; the number is the line the eye is on.
        let style = style();
        let field_ = Field {
            unit: Some("s"),
            ..Field::range("attack", "Attack", "0", "5")
        };
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Text("2.5"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[0].trim_end(), "Attack");
        assert_eq!(rows(&buf)[1].trim_end(), "0 #####----- 5 2.5 s");
    }

    #[test]
    fn a_typed_number_reads_with_its_unit_too() {
        let style = style();
        let field_ = Field {
            unit: Some("ms"),
            ..Field::new(FieldKind::Number, "fade", "Fade")
        };
        let mut buf = buffer(40, 3);
        field(&style, &field_, Held::Text("50"), false, buf.area, &mut buf);
        assert_eq!(rows(&buf)[1].trim_end(), "50 ms");
    }

    #[test]
    fn a_unit_on_a_kind_that_is_not_a_quantity_is_ignored() {
        // Which kinds are quantities is the description's answer, not a
        // `matches!` kept in this crate.
        let style = style();
        let field_ = Field {
            unit: Some("s"),
            ..Field::new(FieldKind::Text, "name", "Name")
        };
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Text("kick"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1].trim_end(), "kick");
    }

    #[test]
    fn an_interval_is_one_line_with_both_ends_on_it() {
        // One question, one line. Two rows would read as two questions, which
        // is the reading the kind exists to prevent.
        let style = style();
        let field_ = Field {
            min: Some("0"),
            max: Some("300"),
            unit: Some("BPM"),
            ..Field::interval("bpm_min", "bpm_max", "BPM range")
        };
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Between {
                lower: "90",
                upper: "130",
            },
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[0].trim_end(), "BPM range");
        assert_eq!(rows(&buf)[1].trim_end(), "90 BPM to 130 BPM");
        assert_eq!(rows(&buf)[2].trim_end(), "");
    }

    #[test]
    fn an_open_end_falls_back_to_the_bound_it_means() {
        // "Over 120" is an answer rather than a half-filled box, and where the
        // axis ends is what the empty end stands for.
        let style = style();
        let field_ = Field {
            min: Some("0"),
            max: Some("300"),
            ..Field::interval("bpm_min", "bpm_max", "BPM range")
        };
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Between {
                lower: "120",
                upper: "",
            },
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1].trim_end(), "120 to 300");
    }

    #[test]
    fn an_unbounded_open_end_draws_nothing_rather_than_a_number() {
        // A terminal inventing a bound here would report a filter nobody
        // applied, which is `range_line`'s position on an unreadable value.
        // What is left reads as the sentence it is: up to 130.
        let style = style();
        let field_ = Field::interval("bpm_min", "bpm_max", "BPM range");
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Between {
                lower: "",
                upper: "130",
            },
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1].trim_end(), "to 130");
    }

    #[test]
    fn a_range_holding_something_unreadable_still_shows_it() {
        // The app put the value there. A terminal that quietly rounded it to a
        // bound would be reporting a value nobody set, which is `empty_well`'s
        // position on the same problem.
        let style = style();
        let field_ = Field::range("review", "Review above", "0", "1");
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Text("unset"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1].trim_end(), "0 ---------- 1 unset");
    }

    #[test]
    fn an_unbounded_range_is_typed_into_rather_than_dragged() {
        // Bounds this crate invented are bounds the user would then drag
        // against. The text path takes every answer the bar would.
        let style = style();
        let field_ = Field {
            max: Some("1"),
            ..Field::new(FieldKind::Range, "review", "Review above")
        };
        let mut buf = buffer(40, 3);
        field(
            &style,
            &field_,
            Held::Text("0.5"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1].trim_end(), "0.5");
    }

    #[test]
    fn an_unavailable_option_reads_as_inert_and_says_why() {
        // The one place muted is the truth rather than the lie the convention
        // warns about: this option will not answer, and the reason is on the
        // row rather than nowhere.
        let style = style();
        let options = [
            Choice::new("chromatic", "Chromatic"),
            Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
        ];
        let mut field_ = Field::new(FieldKind::Radio, "mode", "Mode");
        field_.options = &options;
        let mut buf = buffer(46, 4);
        field(
            &style,
            &field_,
            Held::Text("chromatic"),
            false,
            buf.area,
            &mut buf,
        );
        assert_eq!(rows(&buf)[1].trim_end(), "(*) Chromatic");
        assert_eq!(
            rows(&buf)[2].trim_end(),
            "( ) Multi-sample: Drop a second sample."
        );
        let muted = buf.cell((0, 2)).expect("the unavailable row").style();
        assert!(muted.add_modifier.contains(Modifier::DIM));
    }

    #[test]
    fn an_unchosen_option_does_not_read_as_disabled() {
        // The three-tone convention: muted is inert, and every option in this
        // list answers a press. Drawn muted, a five-option radio read as one
        // live row and four dead ones.
        let style = style();
        let mut field_ = Field::new(FieldKind::Radio, "size", "Size");
        let options = [Choice::plain("small"), Choice::plain("large")];
        field_.options = &options;
        let mut buf = buffer(20, 5);
        field(
            &style,
            &field_,
            Held::Text("large"),
            false,
            buf.area,
            &mut buf,
        );
        let unchosen = buf.cell((0, 1)).expect("the first option").style();
        assert_eq!(unchosen.add_modifier, style.secondary.add_modifier);
        assert_ne!(unchosen.add_modifier, style.muted.add_modifier);
    }

    #[test]
    fn a_checkbox_reads_a_bool_rather_than_a_submitted_string() {
        // `Held::On` exists so a host's own submission convention -- quasi
        // sends "value" -- stays the host's and never reaches a drawing.
        let style = style();
        let field_ = Field::new(FieldKind::Checkbox, "agree", "Agree");
        let mut buf = buffer(20, 4);
        field(&style, &field_, Held::On(true), false, buf.area, &mut buf);
        assert_eq!(rows(&buf)[1], "[x]");
        let mut buf = buffer(20, 4);
        field(&style, &field_, Held::On(false), false, buf.area, &mut buf);
        assert_eq!(rows(&buf)[1], "[ ]");
    }

    #[test]
    fn a_markdown_field_gets_the_rows_a_textarea_does() {
        // Keyed on `multiline`, so a member added upstream does not silently
        // land on the single-row arm. One row for a value whose whole point is
        // that it has several is the failure this replaced.
        let style = PieceStyle::default();
        let rich = Field::new(FieldKind::Rich, "body", "Body");
        let textarea = Field::new(FieldKind::Textarea, "body", "Body");
        let plain = Field::new(FieldKind::Text, "body", "Body");

        assert_eq!(
            field_height(&style, &rich, 40),
            field_height(&style, &textarea, 40)
        );
        assert!(field_height(&style, &rich, 40) > field_height(&style, &plain, 40));
    }

    #[test]
    fn a_tone_and_a_heading_map_without_a_fallback_arm() {
        // Both source enums are closed, which is what lets these be total. A
        // renderer that had to guess would be picking its own colours again.
        let style = style();
        assert_eq!(style.tone(Tone::Neutral), style.content);
        assert_eq!(style.tone(Tone::Danger), style.danger);
        assert_eq!(style.heading(Heading::Page), style.page);
        assert_eq!(style.heading(Heading::Subsection), style.subsection);
    }

    #[test]
    fn the_default_style_carries_no_colour_at_all() {
        // A two-colour terminal is the case where a foreground will not land,
        // so the default is modifiers only rather than a placeholder palette.
        let style = PieceStyle::default();
        for painted in [style.content, style.danger, style.page, style.action] {
            assert_eq!(painted.fg, None);
            assert_eq!(painted.bg, None);
        }
    }

    #[test]
    fn the_three_states_of_a_wait_are_three_drawings() {
        // The whole done condition of `5db1e0ed`: a measured wait and an
        // unmeasured one stopped being the same line.
        let style = PieceStyle::default();
        let bare = awaiting(&style, Awaiting::unmeasured(), Progress::default(), true);
        let sized = awaiting(&style, Awaiting::of(41_943_040), Progress::default(), true);
        let watched = awaiting(
            &style,
            Awaiting::of(40),
            Progress {
                delivered: Some(20),
                elapsed: Some(Duration::from_secs(4)),
            },
            true,
        );
        let read = |line: &Line<'_>| {
            line.spans
                .iter()
                .map(|s| s.content.to_string())
                .collect::<String>()
        };
        assert_eq!(read(&bare), "#");
        assert_eq!(read(&sized), "# 41943040");
        assert_eq!(read(&watched), "#####----- 20/40  4s");
    }

    #[test]
    fn a_dark_mark_still_occupies_its_cell() {
        // Not absent. A line that reflowed every half second would move the
        // content beside it, and the reader would lose where to look.
        let style = PieceStyle::default();
        assert_eq!(activity(&style, true).content.chars().count(), 1);
        assert_eq!(activity(&style, false).content.chars().count(), 1);
    }

    #[test]
    fn an_over_delivered_wait_clamps_and_does_not_panic() {
        // A transfer can hand over more than the size it announced, and the
        // bar has ten cells whatever happens.
        let style = PieceStyle::default();
        let over = awaiting(
            &style,
            Awaiting::of(4),
            Progress {
                delivered: Some(9),
                elapsed: None,
            },
            true,
        );
        assert!(over.spans[0].content.chars().all(|c| c == '#'));
        assert_eq!(over.spans[0].content.chars().count(), 10);
        // A zero payload is no payload rather than a finished one.
        let empty = awaiting(
            &style,
            Awaiting::of(0),
            Progress {
                delivered: Some(9),
                elapsed: None,
            },
            true,
        );
        assert!(empty.spans[0].content.starts_with('-'));
    }
}