makeover-tui 0.48.1

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
//! The pieces every terminal app draws, drawn once.
//!
//! # Not `widget`
//!
//! `makeover-layout` owns that 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.
//! The style type is `PieceStyle`.
//!
//! 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. [`activity`] and
//! [`awaiting`] draw a wait, out of wiki `loading-and-progress-standard`.
//!
//! # 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, Bar, Chart, Field, FieldKind, Figure, Heading, Meter, ThemeVariant, 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;

/// What a badge of one tone is drawn in, when it is drawn filled.
///
/// Two styles and not one, because a filled badge is three spans: an edge, the
/// label, an edge. The label takes [`fill`](Self::fill) whole. An edge takes
/// the fill's background with [`edge`](Self::edge)'s foreground over it, so
/// the half of the cell the glyph leaves empty is the badge's own ground.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct BadgeStyle {
    /// The ground and the ink.
    pub fill: Style,
    /// The edge, as a foreground.
    pub edge: Style,
}

/// 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,
    /// A badge of each tone, in [`Tone`]'s order: neutral, info, success,
    /// warning, danger. Read through [`badge`](Self::badge).
    pub badges: [BadgeStyle; 5],
    /// The glyphs either side of a filled badge, or `None` to draw a badge as
    /// its label in parentheses, in its tone.
    ///
    /// `None` by default, since a fill is a colour and the default has none to
    /// spend.
    pub badge_edges: Option<[&'static str; 2]>,
    /// 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),
            badges: [BadgeStyle::default(); 5],
            badge_edges: None,
            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),
            // The chip of wiki `table-model`: a fill, an edge in the tone, and
            // the label in content. A status fills with makeover's
            // `<tone>-surface` and a neutral badge with the hover's step, which
            // is the weight the tone fills sit at and shows on a striped row
            // as well as a plain one. The raised surface the webview fills a
            // neutral chip with would vanish into the table ground here, where
            // no hairline edge is thin enough to draw around it.
            badges: {
                let badge = |fill, edge| BadgeStyle {
                    fill: Style::new().fg(theme.content_primary).bg(fill),
                    edge: Style::new().fg(edge),
                };
                [
                    badge(theme.row_hover, theme.line_border),
                    badge(theme.status_info_surface, theme.status_info),
                    badge(theme.status_success_surface, theme.status_success),
                    badge(theme.status_warning_surface, theme.status_warning),
                    badge(theme.status_danger_surface, theme.status_danger),
                ]
            },
            // Half blocks, the bevel's glyphs: the outer half of each end cell
            // is the edge and the inner half is fill, so the label sits half a
            // cell in. The same two cells the parentheses took, so a badge
            // gaining its fill moves nothing beside it.
            badge_edges: Some(["\u{258C}", "\u{2590}"]),
            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,
        }
    }

    /// What a badge of this tone is drawn in.
    #[must_use]
    pub const fn badge(&self, tone: Tone) -> BadgeStyle {
        self.badges[match tone {
            Tone::Neutral => 0,
            Tone::Info => 1,
            Tone::Success => 2,
            Tone::Warning => 3,
            Tone::Danger => 4,
        }]
    }

    /// 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.
    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 a line.
///
/// A chip is its label in square brackets, in its tone: it answers a press, and
/// the bracket says so. A badge answers nothing and is drawn filled where the
/// style has [`badge_edges`](PieceStyle::badge_edges), as an edge, the label on
/// its fill, and an edge (wiki `table-model`), and in round brackets in its tone
/// where it has none. Every spelling is the label and two cells, so the width
/// does not depend on which one a terminal gets.
///
/// `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,
) -> Line<'static> {
    let mark = |painted: Style| {
        if latched {
            painted.add_modifier(style.focus)
        } else {
            style.focused(focused, painted)
        }
    };
    match (kind, style.badge_edges) {
        (Token::Badge, Some([open, close])) => {
            let badge = style.badge(tone);
            let edge = mark(badge.fill.patch(badge.edge));
            Line::from(vec![
                Span::styled(open, edge),
                Span::styled(label.to_owned(), mark(badge.fill)),
                Span::styled(close, edge),
            ])
        }
        (Token::Badge, None) => {
            Line::from(Span::styled(format!("({label})"), mark(style.tone(tone))))
        }
        (Token::Chip { .. }, _) => {
            Line::from(Span::styled(format!("[{label}]"), mark(style.tone(tone))))
        }
    }
}

/// 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 control that commits ([`Act::commits`]) is `[ Label ]` filled with the
/// action colour, which is the weight difference a webview carries as its
/// default-button ring. Its tone still says what pressing it means: a
/// committing delete is filled in the danger colour, not the action colour.
///
/// 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`]. A disabled commit keeps its
/// brackets, for the reason a disabled button keeps its bevel.
#[must_use]
pub fn act(style: &PieceStyle, act: &Act<'_>, focused: bool) -> Line<'static> {
    let painted = if act.disabled() {
        style.muted
    } else if act.commits && act.tone == Tone::Neutral {
        style.focused(focused, style.filled)
    } else {
        style.focused(focused, style.tone(act.tone))
    };
    let (open, close) = if act.commits { ("[", "]") } else { ("<", ">") };
    let label = match act.key {
        Some(key) => format!("{open} {} {close} ({key})", act.label),
        None => format!("{open} {} {close}", act.label),
    };
    Line::from(Span::styled(label, painted))
}

/// The muted line a control's [`Act::hint`] draws as, or `None` where it has
/// none.
///
/// A terminal has no pointer, so the hover the other two renderers spend a hint
/// on is not available and is not the thing anyway: what the description says
/// is that the sentence is true, never that it is hidden. A row under the
/// control is this renderer's answer, and it is the same muted row
/// [`field`] gives a field's note, so the two read alike wherever they land.
///
/// Its own function rather than extra lines out of [`act`], because a control
/// is one [`Line`] everywhere it is drawn and a caller laying out a run needs
/// to know it is placing two things.
#[must_use]
pub fn act_note(style: &PieceStyle, act: &Act<'_>) -> Option<Line<'static>> {
    act.hint
        .map(|hint| Line::from(Span::styled(hint.to_owned(), style.muted)))
}

/// 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),
        // A row per theme, a row per group heading, and a row for the follow
        // entry when there is one. The headings are counted by walking the
        // variants rather than by assuming three, because a machine with only
        // dark themes installed draws one heading and reserving three would
        // leave two blank rows under every picker.
        kind if kind.offers_themes() => {
            let mut variants = 0u16;
            let mut open: Option<ThemeVariant> = None;
            for theme in field.themes {
                if open != Some(theme.variant) {
                    variants = variants.saturating_add(1);
                    open = Some(theme.variant);
                }
            }
            let rows = u16::try_from(field.themes.len()).unwrap_or(u16::MAX);
            rows.saturating_add(variants)
                .saturating_add(u16::from(field.follows.is_some()))
        }
        _ => 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.
///
/// [`makeover_layout::Field::as_instant`] is carried and not honoured. It asks
/// for a wall-clock value to be submitted as the moment it names, and this
/// renderer has no submission: it draws the box and the runtime above it
/// gathers what a submit sends, so the conversion belongs where that gathering
/// happens. The value drawn and read here is the local one, in
/// `makeover_layout::DATETIME_FORMAT`.
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)
        }
        // The grouping comes out of the order, not out of a group list:
        // `Field::themes` arrives sorted by variant, so the run of one variant
        // is the group and a heading opens whenever the variant changes. Same
        // walk the other two renderers do, which is what keeps three renderers
        // from disagreeing about where a group starts.
        //
        // Drawn as the radio group above rather than as a closed control,
        // because a terminal has no closed control: the list is already on
        // screen and always was, so the group headings cost a row each and buy
        // the structure the description finally carries.
        kind if kind.offers_themes() => {
            let mut rows = 0;
            if let Some(follow) = field.follows {
                // First, and under no heading. It names no theme and sits in no
                // variant, so a heading over it would be inventing a fourth
                // variant for one row.
                let chosen = held.text() == follow.value;
                let (mark, painted) = if chosen {
                    ("(*)", well)
                } else {
                    ("( )", style.secondary)
                };
                rows += text::draw(
                    &format!("{mark} {}", follow.label),
                    painted,
                    below(area, used + rows),
                    buf,
                );
            }
            let mut open: Option<ThemeVariant> = None;
            for theme in field.themes {
                if open != Some(theme.variant) {
                    // Muted, which is the one place it is the truth rather than
                    // the lie: a heading will not answer, exactly as an
                    // unavailable option will not.
                    rows += text::draw(
                        theme.variant.heading(),
                        style.muted,
                        below(area, used + rows),
                        buf,
                    );
                    open = Some(theme.variant);
                }
                let chosen = held.text() == theme.id;
                let (mark, painted) = if chosen {
                    ("(*)", well)
                } else {
                    ("( )", style.secondary)
                };
                rows += text::draw(
                    &format!("{mark} {} [{}]", theme.name, theme.contrast.badge()),
                    painted,
                    below(area, used + rows),
                    buf,
                );
            }
            rows
        }
        kind if kind.offers_options() => {
            // A checklist's answer is a set, so its options mark themselves
            // with `Choice::chosen` and no one held value names any of them. A
            // single answer is marked either way, which is `chosen`'s rule for
            // every renderer. The box says which of the two the question is.
            let several = kind.takes_several();
            let (open, ticked) = if several {
                ("[ ]", "[x]")
            } else {
                ("( )", "(*)")
            };
            let mut rows = 0;
            for choice in field.options {
                let chosen = choice.chosen || (!several && 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) => (open, style.muted, format!(": {reason}")),
                    None if chosen => (ticked, 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 => (open, style.secondary, String::new()),
                };
                rows += text::draw(
                    &format!("{mark} {}{suffix}", choice.label),
                    painted,
                    below(area, used + rows),
                    buf,
                );
                // What picking it means, on a row of its own under the option.
                // makeover-layout 0.39.0, and this is the host with the most
                // room of the three: a browser's `<select>` has to run the line
                // into the option's text and a terminal does not, so it does
                // not.
                //
                // Indented past the mark, so the line reads as belonging to the
                // option above it rather than as another option. Muted, which
                // is the truth here rather than the lie the arms above are
                // careful about: the row is not a thing to press.
                if let Some(detail) = choice.detail {
                    rows += text::draw(detail, style.muted, indented(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 what a
/// terminal wants: 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.
/// The rows under what has been drawn, inset by the width of an option's mark.
///
/// An option's second line has to read as belonging to the option above it rather than as another option, and the only thing that
/// says so on a terminal is where it starts. The inset is `text::draw`'s to
/// honour as an area rather than as spaces in the string: the drawing wraps on
/// words, so leading spaces would survive the first line and vanish from every
/// one after it.
///
/// Four columns, which is `"( ) "`. Named against the mark rather than picked,
/// so a mark that changes width takes this with it.
fn indented(area: Rect, used: u16) -> Rect {
    const MARK: u16 = 4;
    let area = below(area, used);
    Rect {
        x: area.x + MARK.min(area.width),
        width: area.width.saturating_sub(MARK),
        ..area
    }
}

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;

/// A chart, one line per bar.
///
/// # Why the bars lie down here
///
/// A webview draws a chart as columns standing on an axis, and a terminal has
/// one glyph per cell and a handful of rows. Standing the bars up would mean
/// drawing each one as a stack of partial blocks and giving up the labels,
/// which are the half a reader actually reads. Laid down, every bar keeps its
/// place on the axis, its magnitude and its reading, and the drawing is
/// [`meter`]'s repeated -- which is the honest answer for the same reason
/// `quasi-tui`'s timeline draws no gridlines: a terminal draws what a terminal
/// draws rather than an impression of the other renderer.
///
/// The axis is not drawn as a rule or a scale, for that same reason. It is
/// stated instead: every bar is `meter_cells` wide and full means
/// [`Chart::most`], so the widths are comparable across the run, which is the
/// one thing a chart has to get right.
///
/// # What is left out
///
/// [`Chart::label`] is not drawn. It names what the magnitudes are and every
/// bar's own [`Bar::reading`] already carries the units, so drawing it would be
/// a heading this function does not own the room for. A caller that wants it
/// says it as a heading, which is what a description does anyway.
///
/// Labels are padded to the widest, so the bars line up. That is measured in
/// characters rather than in display cells, which is wrong for a label holding
/// a wide glyph and is what [`crate::text`] would cost to bring in for a case
/// that has not turned up.
#[must_use]
pub fn chart(style: &PieceStyle, chart: &Chart<'_>, bars: &[Bar<'_>]) -> Vec<Line<'static>> {
    let widest = bars
        .iter()
        .map(|bar| bar.at.chars().count())
        .max()
        .unwrap_or(0);
    bars.iter()
        .map(|bar| chart_line(style, chart, bar, widest))
        .collect()
}

/// One bar's line: where it sits, how far it reaches, and what it says.
fn chart_line(
    style: &PieceStyle,
    chart: &Chart<'_>,
    bar: &Bar<'_>,
    widest: usize,
) -> Line<'static> {
    let cells = usize::from(style.meter_cells);
    // Rounded rather than truncated, so a bar that is nearly full does not read
    // as one cell short of every other. The multiplication is done before the
    // division for the reason it is in `meter`: in integers, the other order is
    // zero.
    let filled = if chart.most == 0 {
        0
    } else {
        let scaled = (bar.value as u128 * cells as u128).div_ceil(chart.most as u128);
        (scaled as usize).min(cells)
    };

    let mut spans = vec![Span::styled(
        format!("{:width$} ", bar.at, width = widest),
        style.secondary,
    )];
    spans.push(Span::styled(
        format!(
            "{}{}",
            style.meter_full.to_string().repeat(filled),
            style.meter_empty.to_string().repeat(cells - filled)
        ),
        style.tone(chart.tone),
    ));
    if let Some(reading) = chart_reading(bar) {
        spans.push(Span::styled(reading, style.muted));
    }
    Line::from(spans)
}

/// What a bar says beside its own drawing, or nothing.
///
/// The webview's `bar_text` in this renderer's spelling. Both facts joined the
/// same way, and both left out when the description carried neither.
fn chart_reading(bar: &Bar<'_>) -> Option<String> {
    match (bar.reading, bar.note) {
        (Some(reading), Some(note)) => Some(format!(" {reading} / {note}")),
        (Some(only), None) | (None, Some(only)) => Some(format!(" {only}")),
        (None, None) => None,
    }
}