rs-rich-interact 0.0.13

Interactive terminal components for rs-rich: event loop, viewport, item model, headless testing
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
//! Date and time pickers (#719): [`DatePicker`], [`TimePicker`] and
//! [`DateTimePicker`].
//!
//! A date is picked on a month grid: ←/→ move a day, ↑/↓ a week,
//! PgUp/PgDn (or `[`/`]`) a month, Shift+PgUp/PgDn (or `{`/`}`) a year,
//! Home/End to the first and last of the month, and `t` to today. A time
//! is picked field by field: ←/→ (or Tab) move between the hour, the
//! minute, the second and AM/PM, ↑/↓ change the field, and digits type it.
//! With both, Tab moves between the grid and the time. Enter picks; Esc
//! cancels. Every key comes from the keymap (context `date`), so it can be
//! rebound. Tab and Shift+Tab are the containers' `focus-next` and
//! `focus-previous`: in a [container](crate::compose), Tab after the last
//! part moves on to the next field, and on its own the picker goes round.
//!
//! A range ([`min`](DatePicker::min), [`max`](DatePicker::max)) limits
//! what can be picked: days outside it are dimmed and the grid does not go
//! to them; a time outside it is refused on Enter, with a message under
//! the picker that says what the limit is, as is an answer a
//! [validator](DatePicker::validate) refuses, and every answer when the
//! earliest is after the latest. The days go from the year 1 to 9999, the
//! years ISO 8601's four digits write. The value so far shows on the
//! question line, and the selected day is in brackets as well as reversed,
//! so both read without colour. Without seconds a picker works to the
//! minute: the value and the answer drop their seconds, and a limit with
//! seconds is the minute that can be picked (the earliest rounds up).
//!
//! Without a terminal each asks for a line and parses it: `2026-10-17`,
//! `14:30` (or `2:30 pm`), or `2026-10-17 14:30`; an empty line answers
//! with the default. A line outside the range or refused by the validator
//! is an error, as is one that does not parse, and so is a default the
//! picker would refuse.

use std::cell::Cell;
use std::sync::Arc;

use rich::{Segment, Style};

use crate::component::{Component, Context, Flow, View};
use crate::components::{Theme, fit, plain, question, text};
use crate::compose::{FOCUS_NEXT, FOCUS_PREVIOUS};
use crate::datetime::{Date, DateTime, Time};
use crate::event::{Button, Event, Key, KeyCode, MouseKind};
use crate::keymap::{Keymap, keys};
use crate::policy::{LineIo, NotInteractive};

/// The keys of the date and time pickers, in context `date`. Tab and
/// Shift+Tab are [`FOCUS_NEXT`] and [`FOCUS_PREVIOUS`], as in a
/// container: past the picker's last part, focus moves on.
pub fn date_keymap() -> Keymap {
    Keymap::new("date")
        .bind("pick", keys("enter"), "pick")
        .bind("cancel", keys("escape"), "cancel")
        .bind("left", keys("left h"), "a day earlier; the field before")
        .bind("right", keys("right l"), "a day later; the next field")
        .bind("up", keys("up k"), "a week earlier; the field up")
        .bind("down", keys("down j"), "a week later; the field down")
        .bind("previous-month", keys("pageup ["), "a month earlier")
        .bind("next-month", keys("pagedown ]"), "a month later")
        .bind("previous-year", keys("shift+pageup {"), "a year earlier")
        .bind("next-year", keys("shift+pagedown }"), "a year later")
        .bind("first-day", keys("home"), "the month's first day")
        .bind("last-day", keys("end"), "the month's last day")
        .bind("today", keys("t"), "today")
        .bind(FOCUS_NEXT, keys("tab"), "the next part")
        .bind(FOCUS_PREVIOUS, keys("shift+tab"), "the part before")
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
    Date,
    Time,
    DateTime,
}

/// What has the focus.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Part {
    Grid,
    Hour,
    Minute,
    Second,
    Half,
}

type Check = Arc<dyn Fn(DateTime) -> Result<(), String> + Send + Sync>;

/// The rows of a month grid: always six weeks, so the picker keeps its
/// height from month to month.
const WEEKS: usize = 6;
/// The grid's width: a space, then a separator and two digits a day, then
/// a last separator.
const GRID_WIDTH: usize = 23;
/// The rows above the grid's weeks: the question, the month, the weekdays.
const GRID_TOP: usize = 3;
/// The first and last days a picker goes to: the years ISO 8601's four
/// digits write, so every answer prints and parses back.
const FIRST_DAY: Date = Date::new(1, 1, 1);
const LAST_DAY: Date = Date::new(9999, 12, 31);

/// The state the three pickers share.
struct Chooser {
    prompt: String,
    mode: Mode,
    value: DateTime,
    /// Whether `value` was given: a default does not move the start then.
    value_given: bool,
    min: Option<DateTime>,
    max: Option<DateTime>,
    seconds: bool,
    twelve_hour: bool,
    today: Date,
    part: Part,
    /// Digits typed into the focused time field so far.
    typed: String,
    /// Why the last Enter was refused, until the next key.
    message: Option<String>,
    check: Option<Check>,
    default: Option<DateTime>,
    theme: Theme,
    mouse: bool,
    keymap: Keymap,
    /// The day the last click selected: a click on it again picks it.
    clicked: Option<Date>,
    answer: Option<Option<String>>,
    /// The width last drawn at, for the mouse.
    width: Cell<usize>,
}

impl Chooser {
    fn new(prompt: String, mode: Mode) -> Chooser {
        let now = DateTime::now_utc();
        let value = match mode {
            Mode::Date => DateTime::new(now.date, Time::MIDNIGHT),
            Mode::Time | Mode::DateTime => {
                DateTime::new(now.date, Time::new(now.time.hour, now.time.minute, 0))
            }
        };
        Chooser {
            prompt,
            mode,
            value,
            value_given: false,
            min: None,
            max: None,
            seconds: false,
            twelve_hour: false,
            today: now.date,
            part: if mode == Mode::Time {
                Part::Hour
            } else {
                Part::Grid
            },
            typed: String::new(),
            message: None,
            check: None,
            default: None,
            theme: Theme::default(),
            mouse: false,
            keymap: date_keymap(),
            clicked: None,
            answer: None,
            width: Cell::new(80),
        }
    }

    fn has_date(&self) -> bool {
        self.mode != Mode::Time
    }

    fn has_time(&self) -> bool {
        self.mode != Mode::Date
    }

    /// The parts Tab goes through, in order.
    fn parts(&self) -> Vec<Part> {
        let mut parts = Vec::new();
        if self.has_date() {
            parts.push(Part::Grid);
        }
        if self.has_time() {
            parts.extend([Part::Hour, Part::Minute]);
            if self.seconds {
                parts.push(Part::Second);
            }
            if self.twelve_hour {
                parts.push(Part::Half);
            }
        }
        parts
    }

    /// Whether the picker works to the minute: it has a time, and no
    /// seconds.
    fn to_the_minute(&self) -> bool {
        self.has_time() && !self.seconds
    }

    /// `at` as the picker shows it, and so answers it: to the minute when
    /// it has no seconds.
    fn shown(&self, at: DateTime) -> DateTime {
        if !self.to_the_minute() {
            return at;
        }
        DateTime::new(
            at.date,
            Time {
                second: 0,
                ..at.time
            },
        )
    }

    /// The earliest moment that can be picked: `min`, rounded up to the
    /// next minute when the picker works to the minute and it has seconds.
    fn earliest(&self) -> Option<DateTime> {
        let min = self.min?;
        if !self.to_the_minute() || min.time.second == 0 {
            return Some(min);
        }
        let minute = i64::from(min.time.seconds() - min.time.second);
        let time = Time::from_seconds(minute + 60);
        let date = if time == Time::MIDNIGHT {
            min.date.add_days(1)
        } else {
            min.date
        };
        Some(DateTime::new(date, time))
    }

    /// The latest moment that can be picked: `max`, to the minute when the
    /// picker works to the minute.
    fn latest(&self) -> Option<DateTime> {
        self.max.map(|max| self.shown(max))
    }

    /// The earliest, as a message says it: the minute that can be picked,
    /// or, when no minute of a time picker's day is that late, `min` to
    /// the second.
    fn earliest_text(&self) -> Option<String> {
        let (min, earliest) = (self.min?, self.earliest()?);
        Some(if self.mode == Mode::Time && earliest.date != min.date {
            min.time.format(true, self.twelve_hour)
        } else {
            self.format(earliest)
        })
    }

    /// Whether `date` has a moment in the range.
    fn day_allowed(&self, date: Date) -> bool {
        (FIRST_DAY..=LAST_DAY).contains(&date)
            && self.earliest().is_none_or(|min| date >= min.date)
            && self.latest().is_none_or(|max| date <= max.date)
    }

    /// `date`, moved into the range (and the years 1 to 9999).
    fn clamp_day(&self, date: Date) -> Date {
        let mut date = date;
        if let Some(min) = self.earliest() {
            date = date.max(min.date);
        }
        if let Some(max) = self.latest() {
            date = date.min(max.date);
        }
        date.clamp(FIRST_DAY, LAST_DAY)
    }

    /// What is compared with the range: a date picker's day, a time
    /// picker's time, or both.
    fn key_of(&self, at: DateTime) -> (Option<Date>, Option<Time>) {
        match self.mode {
            Mode::Date => (Some(at.date), None),
            Mode::Time => (None, Some(at.time)),
            Mode::DateTime => (Some(at.date), Some(at.time)),
        }
    }

    /// How a value is written: as the picker answers it.
    fn format(&self, at: DateTime) -> String {
        match self.mode {
            Mode::Date => at.date.to_string(),
            Mode::Time => at.time.format(self.seconds, self.twelve_hour),
            Mode::DateTime => at.format(self.seconds, self.twelve_hour),
        }
    }

    /// Why `at` cannot be picked, if it cannot. It is compared as shown:
    /// to the minute when the picker works to the minute.
    fn refusal(&self, at: DateTime) -> Option<String> {
        let at = self.shown(at);
        if let (Some(earliest), Some(latest)) = (self.earliest(), self.latest())
            && self.key_of(earliest) > self.key_of(latest)
        {
            return Some(format!(
                "the range is empty: the earliest, {}, is after the latest, {}",
                self.earliest_text().unwrap_or_default(),
                self.format(latest)
            ));
        }
        let at_key = self.key_of(at);
        if let Some(min) = self.min
            && at_key < self.key_of(min)
        {
            let earliest = self.earliest_text().unwrap_or_default();
            return Some(format!("the earliest is {earliest}"));
        }
        if let Some(max) = self.latest()
            && at_key > self.key_of(max)
        {
            return Some(format!("the latest is {}", self.format(max)));
        }
        self.check.as_ref().and_then(|check| check(at).err())
    }

    fn set_day(&mut self, date: Date) {
        self.value.date = self.clamp_day(date);
    }

    /// Change the focused time field by `delta`, wrapping round.
    fn step_field(&mut self, delta: i64) {
        let time = self.value.time;
        let wrap =
            |value: u32, by: i64, modulus: i64| (value as i64 + by).rem_euclid(modulus) as u32;
        self.value.time = match self.part {
            Part::Hour => Time {
                hour: wrap(time.hour, delta, 24),
                ..time
            },
            Part::Minute => Time {
                minute: wrap(time.minute, delta, 60),
                ..time
            },
            Part::Second => Time {
                second: wrap(time.second, delta, 60),
                ..time
            },
            Part::Half => Time {
                hour: (time.hour + 12) % 24,
                ..time
            },
            Part::Grid => time,
        };
    }

    /// A digit typed into the focused time field: two make the field, and
    /// the focus moves on.
    fn type_digit(&mut self, digit: char) {
        self.typed.push(digit);
        let number: u32 = self.typed.parse().unwrap_or(0);
        let time = self.value.time;
        let (most, full) = match self.part {
            Part::Hour if self.twelve_hour => (12, number >= 2 || self.typed.len() == 2),
            Part::Hour => (23, number >= 3 || self.typed.len() == 2),
            _ => (59, number >= 6 || self.typed.len() == 2),
        };
        let number = number.min(most);
        self.value.time = match self.part {
            Part::Hour if self.twelve_hour => {
                let pm = time.hour >= 12;
                let hour = if self.typed.len() == 2 || full {
                    number.max(1) % 12
                } else {
                    number % 12
                };
                Time {
                    hour: hour + if pm { 12 } else { 0 },
                    ..time
                }
            }
            Part::Hour => Time {
                hour: number,
                ..time
            },
            Part::Minute => Time {
                minute: number,
                ..time
            },
            Part::Second => Time {
                second: number,
                ..time
            },
            _ => time,
        };
        if full {
            self.typed.clear();
            self.move_part(1);
        }
    }

    /// Where the focused part is among the parts.
    fn part_index(&self, parts: &[Part]) -> usize {
        parts
            .iter()
            .position(|part| *part == self.part)
            .unwrap_or(0)
    }

    /// Move the focus `by` parts, stopping at the ends (the arrows): the
    /// arrows stay among the time fields.
    fn move_part(&mut self, by: isize) {
        let parts = self.parts();
        let count = parts.len() as isize;
        let first = if self.has_date() { 1 } else { 0 };
        let next = (self.part_index(&parts) as isize + by).clamp(first.min(count - 1), count - 1);
        self.part = parts[next as usize];
        self.typed.clear();
    }

    /// Move the focus to the next part (or the one before), for Tab:
    /// `false` past the last (or before the first), where Tab leaves the
    /// picker for its container's next field.
    fn step_part(&mut self, forward: bool) -> bool {
        let parts = self.parts();
        let at = self.part_index(&parts);
        let next = if forward {
            Some(at + 1)
        } else {
            at.checked_sub(1)
        };
        match next.and_then(|next| parts.get(next)) {
            Some(part) => {
                self.part = *part;
                self.typed.clear();
                true
            }
            None => false,
        }
    }

    /// Take the focus from outside: at the first part going forward, at
    /// the last going back.
    fn enter(&mut self, forward: bool) {
        let parts = self.parts();
        if let Some(part) = if forward { parts.first() } else { parts.last() } {
            self.part = *part;
        }
        self.typed.clear();
    }

    fn pick(&mut self) -> Flow<DateTime> {
        let value = self.shown(self.value);
        if let Some(why) = self.refusal(value) {
            self.message = Some(why);
            return Flow::Continue;
        }
        self.value = value;
        self.answer = Some(Some(self.format(value)));
        Flow::Done(value)
    }

    fn act(&mut self, action: &str) -> Flow<DateTime> {
        let on_grid = self.part == Part::Grid;
        let day = self.value.date;
        match action {
            "pick" => return self.pick(),
            "cancel" => {
                self.answer = Some(None);
                return Flow::Cancel;
            }
            // Past the last part (or before the first) Tab is left to the
            // container: its next field. On its own, the event loop takes
            // the picker round to its other end.
            FOCUS_NEXT | FOCUS_PREVIOUS => {
                if !self.step_part(action == FOCUS_NEXT) {
                    return Flow::Ignored;
                }
            }
            "left" if on_grid => self.set_day(day.add_days(-1)),
            "right" if on_grid => self.set_day(day.add_days(1)),
            "up" if on_grid => self.set_day(day.add_days(-7)),
            "down" if on_grid => self.set_day(day.add_days(7)),
            "left" => self.move_part(-1),
            "right" => self.move_part(1),
            "up" => self.step_field(1),
            "down" => self.step_field(-1),
            "previous-month" if self.has_date() => self.set_day(day.add_months(-1)),
            "next-month" if self.has_date() => self.set_day(day.add_months(1)),
            "previous-year" if self.has_date() => self.set_day(day.add_months(-12)),
            "next-year" if self.has_date() => self.set_day(day.add_months(12)),
            "first-day" if on_grid => self.set_day(day.first_of_month()),
            "last-day" if on_grid => self.set_day(day.last_of_month()),
            "today" if self.has_date() => self.set_day(self.today),
            _ => return Flow::Ignored,
        }
        Flow::Continue
    }

    fn key(&mut self, key: Key) -> Flow<DateTime> {
        let plain_key = !key.modifiers.ctrl && !key.modifiers.alt;
        // Digits and AM/PM in a time field come before the bindings (`h`
        // and `l` move, but not in the middle of `14`).
        if plain_key && self.part != Part::Grid {
            match key.code {
                KeyCode::Char(c @ '0'..='9') if self.part != Part::Half => {
                    self.type_digit(c);
                    return Flow::Continue;
                }
                KeyCode::Char(c @ ('a' | 'A' | 'p' | 'P')) if self.twelve_hour => {
                    let pm = c.eq_ignore_ascii_case(&'p');
                    let hour = self.value.time.hour % 12 + if pm { 12 } else { 0 };
                    self.value.time.hour = hour;
                    return Flow::Continue;
                }
                _ => {}
            }
        }
        let Some(action) = self.keymap.action(key).map(str::to_string) else {
            return Flow::Ignored;
        };
        // A move away from a field ends what was typed into it.
        self.typed.clear();
        self.act(&action)
    }

    /// Where the time row is, under the question (and the grid).
    fn time_row(&self) -> usize {
        if self.has_date() { GRID_TOP + WEEKS } else { 1 }
    }

    /// The day under a click at `column`, `row`, if a day is there.
    fn day_at(&self, column: usize, row: usize) -> Option<Date> {
        if !self.has_date() || !(GRID_TOP..GRID_TOP + WEEKS).contains(&row) || column < 2 {
            return None;
        }
        let cell = (column - 1) / 3;
        if cell >= 7 {
            return None;
        }
        let first = self.value.date.first_of_month();
        let at = (row - GRID_TOP) * 7 + cell;
        let day = (at + 1).checked_sub(first.weekday() as usize)?;
        (1..=Date::days_in_month(first.year, first.month) as usize)
            .contains(&day)
            .then_some(Date {
                day: day as u32,
                ..first
            })
    }

    /// The time field under `column` of the time row.
    fn field_at(&self, column: usize) -> Option<Part> {
        let mut at = self.time_label().len();
        for (part, width) in self.time_fields() {
            if (at..at + width).contains(&column) {
                return Some(part);
            }
            at += width + 1;
        }
        None
    }

    fn mouse_event(&mut self, kind: MouseKind, column: usize, row: usize) -> Flow<DateTime> {
        let over_grid = self.has_date() && row < GRID_TOP + WEEKS;
        match kind {
            MouseKind::Down(Button::Left) => {
                if let Some(day) = self.day_at(column, row) {
                    if !self.day_allowed(day) {
                        return Flow::Continue;
                    }
                    self.part = Part::Grid;
                    if self.clicked == Some(day) && self.value.date == day {
                        return self.pick();
                    }
                    self.value.date = day;
                    self.clicked = Some(day);
                } else if self.has_time()
                    && row == self.time_row()
                    && let Some(part) = self.field_at(column)
                {
                    self.part = part;
                    self.typed.clear();
                }
            }
            MouseKind::ScrollUp | MouseKind::ScrollDown => {
                let by = if kind == MouseKind::ScrollUp { -1 } else { 1 };
                if over_grid {
                    self.set_day(self.value.date.add_months(by));
                } else if self.has_time() && self.part != Part::Grid {
                    // The wheel turns the focused field, as ↑ does.
                    self.step_field(-(by as i64));
                }
            }
            _ => return Flow::Ignored,
        }
        Flow::Continue
    }

    fn event(&mut self, event: &Event) -> Flow<DateTime> {
        if let Some(mouse) = event.mouse() {
            self.message = None;
            return self.mouse_event(mouse.kind, mouse.column as usize, mouse.row as usize);
        }
        match event.key() {
            Some(key) => {
                self.message = None;
                self.key(key)
            }
            None => Flow::Ignored,
        }
    }

    /// The text before the time fields.
    fn time_label(&self) -> &'static str {
        if self.has_date() { "  Time " } else { "  " }
    }

    /// The time's fields and their widths, with brackets round the
    /// focused one.
    fn time_fields(&self) -> Vec<(Part, usize)> {
        let mut fields = vec![(Part::Hour, 2), (Part::Minute, 2)];
        if self.seconds {
            fields.push((Part::Second, 2));
        }
        if self.twelve_hour {
            fields.push((Part::Half, 2));
        }
        fields
            .into_iter()
            .map(|(part, width)| (part, width + if part == self.part { 2 } else { 0 }))
            .collect()
    }

    fn time_line(&self, width: usize) -> Vec<Segment> {
        let theme = &self.theme;
        let time = self.value.time;
        let out = self
            .refusal(self.value)
            .is_some_and(|_| self.min.is_some() || self.max.is_some());
        let reverse = Style::parse("reverse").expect("a built-in style");
        let mut line = vec![plain(self.time_label())];
        let (hour, pm) = time.twelve_hour();
        for (index, (part, _)) in self.time_fields().into_iter().enumerate() {
            if index > 0 {
                line.push(plain(if part == Part::Half { " " } else { ":" }));
            }
            let shown = match part {
                Part::Hour if self.twelve_hour => format!("{hour:02}"),
                Part::Hour => format!("{:02}", time.hour),
                Part::Minute => format!("{:02}", time.minute),
                Part::Second => format!("{:02}", time.second),
                _ => (if pm { "PM" } else { "AM" }).to_string(),
            };
            let shown = if part == self.part && !self.typed.is_empty() {
                format!("{:_<2}", self.typed)
            } else {
                shown
            };
            if part == self.part {
                line.push(text(format!("[{shown}]"), &theme.focused.combine(&reverse)));
            } else if out {
                line.push(text(shown, &theme.error));
            } else {
                line.push(plain(shown));
            }
        }
        fit(line, width)
    }

    fn grid_lines(&self, width: usize) -> Vec<Vec<Segment>> {
        let theme = &self.theme;
        let selected = self.value.date;
        let first = selected.first_of_month();
        let title = format!("{} {}", selected.month_name(), selected.year);
        let pad = GRID_WIDTH.saturating_sub(title.len()) / 2;
        let title_style = Style::parse("bold").expect("a built-in style");
        let mut lines = vec![
            fit(
                vec![plain(" ".repeat(pad)), text(title, &title_style)],
                width,
            ),
            fit(vec![text("  Mo Tu We Th Fr Sa Su", &theme.hint)], width),
        ];
        let reverse = Style::parse("reverse").expect("a built-in style");
        let underline = Style::parse("underline").expect("a built-in style");
        let today_style = Style::parse("bold").expect("a built-in style");
        let chosen = if self.part == Part::Grid {
            theme.focused.combine(&reverse)
        } else {
            underline
        };
        let offset = first.weekday() as usize;
        let days = Date::days_in_month(first.year, first.month) as usize;
        for week in 0..WEEKS {
            let mut line = vec![plain(" ")];
            for cell in 0..7 {
                let at = week * 7 + cell;
                let day = (at + 1)
                    .checked_sub(offset)
                    .filter(|day| (1..=days).contains(day));
                let is = |cell: usize| {
                    (week * 7 + cell + 1)
                        .checked_sub(offset)
                        .is_some_and(|day| day == selected.day as usize)
                };
                // The separator before the day: a bracket opens the
                // selected day and closes the one before.
                line.push(plain(if is(cell) {
                    "["
                } else if cell > 0 && is(cell - 1) {
                    "]"
                } else {
                    " "
                }));
                let Some(day) = day else {
                    line.push(plain("  "));
                    continue;
                };
                let date = Date {
                    day: day as u32,
                    ..first
                };
                let label = format!("{day:>2}");
                line.push(if date == selected {
                    text(label, &chosen)
                } else if !self.day_allowed(date) {
                    text(label, &theme.hint)
                } else if date == self.today {
                    text(label, &today_style)
                } else {
                    plain(label)
                });
            }
            if is_last_selected(week, offset, selected.day) {
                line.push(plain("]"));
            }
            lines.push(fit(line, width));
        }
        lines
    }

    fn hint(&self) -> String {
        let mut hint = String::from("  ");
        hint.push_str(match self.part {
            Part::Grid => "←→↑↓ day · pgup/pgdn month · t today",
            _ => "←→ field · ↑↓ change · type digits",
        });
        if self.parts().len() > 1 {
            hint.push_str(match (self.part, self.mode) {
                (Part::Grid, Mode::DateTime) => " · tab time",
                (_, Mode::DateTime) => " · tab date",
                _ => " · tab next",
            });
        }
        hint.push_str(" · enter pick · esc cancel");
        hint
    }

    /// The range, as the limits that can be picked.
    fn range_line(&self) -> Option<String> {
        let latest = self.latest().map(|at| self.format(at));
        match (self.earliest_text(), latest) {
            (None, None) => None,
            (Some(min), Some(max)) => Some(format!("  from {min} to {max}")),
            (Some(min), None) => Some(format!("  from {min}")),
            (None, Some(max)) => Some(format!("  until {max}")),
        }
    }

    fn render(&self, context: &Context<'_>) -> View {
        let width = context.width;
        self.width.set(width);
        let theme = &self.theme;
        let mut header = question(theme, &self.prompt);
        if let Some(answer) = &self.answer {
            header.push(match answer {
                Some(answer) => text(answer.clone(), &theme.answer),
                None => text("cancelled", &theme.hint),
            });
            return View::new(vec![fit(header, width)]);
        }
        // The value so far, as it would be answered.
        header.push(plain(self.format(self.value)));
        let mut lines = vec![fit(header, width)];
        if self.has_date() {
            lines.extend(self.grid_lines(width));
        }
        if self.has_time() {
            lines.push(self.time_line(width));
        }
        if let Some(range) = self.range_line() {
            lines.push(fit(vec![text(range, &theme.hint)], width));
        }
        lines.push(fit(vec![text(self.hint(), &theme.hint)], width));
        if let Some(message) = &self.message {
            lines.push(fit(
                vec![text(format!("  ✗ {message}"), &theme.error)],
                width,
            ));
        }
        View::new(lines)
    }

    /// What the line-based form expects, for its prompt.
    fn shape(&self) -> &'static str {
        match (self.mode, self.seconds) {
            (Mode::Date, _) => "YYYY-MM-DD",
            (Mode::Time, false) => "HH:MM",
            (Mode::Time, true) => "HH:MM:SS",
            (Mode::DateTime, false) => "YYYY-MM-DD HH:MM",
            (Mode::DateTime, true) => "YYYY-MM-DD HH:MM:SS",
        }
    }

    fn parse(&self, line: &str) -> Result<DateTime, String> {
        match self.mode {
            Mode::Date => line.parse::<Date>().map(DateTime::from),
            Mode::Time => line
                .parse::<Time>()
                .map(|time| DateTime::new(self.value.date, time)),
            Mode::DateTime => line.parse::<DateTime>(),
        }
    }

    fn ask(&mut self, io: &mut dyn LineIo) -> Result<Option<DateTime>, NotInteractive> {
        let mut prompt = format!("{} ({}", self.prompt, self.shape());
        if let Some(range) = self.range_line() {
            prompt.push_str(&format!(", {}", range.trim()));
        }
        prompt.push(')');
        if let Some(default) = self.default {
            prompt.push_str(&format!(" [{}]", self.format(default)));
        }
        io.write(&format!("{prompt}: "));
        let line = match io.read_line() {
            Some(line) if !line.trim().is_empty() => line,
            // Input ended, or an empty line: the default answers, checked
            // as a typed answer is.
            ended => {
                return match self.default {
                    Some(default) => self.checked(default).map(Some),
                    None if ended.is_none() => Err(NotInteractive::Ended),
                    None => Err(NotInteractive::Invalid(format!(
                        "no answer given ({})",
                        self.shape()
                    ))),
                };
            }
        };
        let at = self.parse(&line).map_err(NotInteractive::Invalid)?;
        self.checked(at).map(Some)
    }

    /// `at` as the picker answers it (to the minute without seconds), or
    /// why it is refused, as the line-based form says it.
    fn checked(&self, at: DateTime) -> Result<DateTime, NotInteractive> {
        let at = self.shown(at);
        match self.refusal(at) {
            Some(why) => Err(NotInteractive::Invalid(format!(
                "{}: {why}",
                self.format(at)
            ))),
            None => Ok(at),
        }
    }
}

/// Whether the selected `day` is the last cell of `week` (Sunday), so the
/// row's closing bracket is after it.
fn is_last_selected(week: usize, offset: usize, day: u32) -> bool {
    (week * 7 + 7).checked_sub(offset) == Some(day as usize)
}

/// The builders every picker has.
macro_rules! shared_builders {
    () => {
        pub fn theme(mut self, theme: Theme) -> Self {
            self.0.theme = theme;
            self
        }

        /// Report the mouse (#476): a click selects a day (a second click
        /// on it picks it) or focuses a time field, and the wheel turns the
        /// month or the focused field.
        pub fn with_mouse(mut self, on: bool) -> Self {
            self.0.mouse = on;
            self
        }

        /// Make `keys` do `action` (see [`date_keymap`]) on this picker
        /// only; no keys unbinds it.
        pub fn rebind(mut self, action: &str, keys: impl IntoIterator<Item = Key>) -> Self {
            self.0.keymap.rebind(action, keys);
            self
        }
    };
}

/// The builders of a picker with a time.
macro_rules! time_builders {
    () => {
        /// Pick the seconds too. Without them (the default) the picker
        /// works to the minute, whatever order the builders come in: the
        /// start, the default and a typed answer drop their seconds, the
        /// earliest rounds up to a minute and the latest down.
        pub fn seconds(mut self, on: bool) -> Self {
            self.0.seconds = on;
            self
        }

        /// Show a 12-hour clock with AM and PM (`a` and `p` set them).
        pub fn twelve_hour(mut self, on: bool) -> Self {
            self.0.twelve_hour = on;
            self
        }
    };
}

/// The builders of a picker with a date.
macro_rules! date_builders {
    () => {
        /// The day marked as today and `t` goes to (default: today in
        /// UTC).
        pub fn today(mut self, today: Date) -> Self {
            self.0.today = today;
            self
        }
    };
}

/// Pick a day from a month grid. Returns the [`Date`].
///
/// ```
/// use rich_interact::datetime::Date;
/// use rich_interact::headless::{self, Script};
/// use rich_interact::{DatePicker, Outcome};
///
/// let picker = DatePicker::new("Due").value(Date::new(2026, 10, 17));
/// let script = Script::new().keys("right down enter");
/// let (outcome, record) = headless::run(picker, script, 40, 14);
/// assert_eq!(outcome.unwrap(), Outcome::Done(Date::new(2026, 10, 25)));
/// assert_eq!(record.last_frame(), "? Due › 2026-10-25");
/// ```
#[must_use = "a component does nothing until it is run or mounted"]
pub struct DatePicker(Chooser);

impl DatePicker {
    pub fn new(prompt: impl Into<String>) -> DatePicker {
        DatePicker(Chooser::new(prompt.into(), Mode::Date))
    }

    shared_builders!();
    date_builders!();

    /// Start on this day.
    pub fn value(mut self, date: Date) -> Self {
        self.0.value.date = date;
        self.0.value_given = true;
        self
    }

    /// Answer this day without a terminal and to an empty line, and start
    /// on it unless [`value`](Self::value) says where to start.
    pub fn default(mut self, date: Date) -> Self {
        if !self.0.value_given {
            self.0.value.date = date;
        }
        self.0.default = Some(date.into());
        self
    }

    /// The earliest day that can be picked.
    pub fn min(mut self, date: Date) -> Self {
        self.0.min = Some(date.at(Time::MIDNIGHT));
        self
    }

    /// The latest day that can be picked.
    pub fn max(mut self, date: Date) -> Self {
        self.0.max = Some(date.at(Time::LAST));
        self
    }

    /// Refuse a day `check` returns an error for (a weekend, a holiday):
    /// Enter shows the error and waits.
    pub fn validate(
        mut self,
        check: impl Fn(Date) -> Result<(), String> + Send + Sync + 'static,
    ) -> Self {
        self.0.check = Some(Arc::new(move |at: DateTime| check(at.date)));
        self
    }

    /// The day selected so far.
    pub fn selected(&self) -> Date {
        self.0.value.date
    }
}

/// Pick a time of day, field by field. Returns the [`Time`].
///
/// ```
/// use rich_interact::datetime::Time;
/// use rich_interact::headless::{self, Script};
/// use rich_interact::{Outcome, TimePicker};
///
/// let picker = TimePicker::new("Start").value(Time::new(9, 0, 0));
/// let script = Script::new().text("1415").keys("enter");
/// let (outcome, _) = headless::run(picker, script, 40, 6);
/// assert_eq!(outcome.unwrap(), Outcome::Done(Time::new(14, 15, 0)));
/// ```
#[must_use = "a component does nothing until it is run or mounted"]
pub struct TimePicker(Chooser);

impl TimePicker {
    pub fn new(prompt: impl Into<String>) -> TimePicker {
        TimePicker(Chooser::new(prompt.into(), Mode::Time))
    }

    shared_builders!();
    time_builders!();

    /// Start at this time.
    pub fn value(mut self, time: Time) -> Self {
        self.0.value.time = time;
        self.0.value_given = true;
        self
    }

    /// Answer this time without a terminal and to an empty line, and start
    /// at it unless [`value`](Self::value) says where to start.
    pub fn default(mut self, time: Time) -> Self {
        if !self.0.value_given {
            self.0.value.time = time;
        }
        self.0.default = Some(self.0.value.date.at(time));
        self
    }

    /// The earliest time that can be picked.
    pub fn min(mut self, time: Time) -> Self {
        self.0.min = Some(self.0.value.date.at(time));
        self
    }

    /// The latest time that can be picked.
    pub fn max(mut self, time: Time) -> Self {
        self.0.max = Some(self.0.value.date.at(time));
        self
    }

    /// Refuse a time `check` returns an error for: Enter shows the error
    /// and waits.
    pub fn validate(
        mut self,
        check: impl Fn(Time) -> Result<(), String> + Send + Sync + 'static,
    ) -> Self {
        self.0.check = Some(Arc::new(move |at: DateTime| check(at.time)));
        self
    }

    /// The time selected so far.
    pub fn selected(&self) -> Time {
        self.0.shown(self.0.value).time
    }
}

/// Pick a day and a time: the month grid, then the time under it (Tab
/// moves between them). Returns the [`DateTime`].
///
/// ```
/// use rich_interact::datetime::{Date, DateTime, Time};
/// use rich_interact::headless::{self, Script};
/// use rich_interact::{DateTimePicker, Outcome};
///
/// let start = DateTime::new(Date::new(2026, 10, 17), Time::new(9, 0, 0));
/// let picker = DateTimePicker::new("Meeting").value(start);
/// let script = Script::new().keys("right tab").text("1430").keys("enter");
/// let (outcome, record) = headless::run(picker, script, 40, 16);
/// let expected = DateTime::new(Date::new(2026, 10, 18), Time::new(14, 30, 0));
/// assert_eq!(outcome.unwrap(), Outcome::Done(expected));
/// assert_eq!(record.last_frame(), "? Meeting › 2026-10-18 14:30");
/// ```
#[must_use = "a component does nothing until it is run or mounted"]
pub struct DateTimePicker(Chooser);

impl DateTimePicker {
    pub fn new(prompt: impl Into<String>) -> DateTimePicker {
        DateTimePicker(Chooser::new(prompt.into(), Mode::DateTime))
    }

    shared_builders!();
    date_builders!();
    time_builders!();

    /// Start at this moment.
    pub fn value(mut self, at: DateTime) -> Self {
        self.0.value = at;
        self.0.value_given = true;
        self
    }

    /// Answer this moment without a terminal and to an empty line, and
    /// start at it unless [`value`](Self::value) says where to start.
    pub fn default(mut self, at: DateTime) -> Self {
        if !self.0.value_given {
            self.0.value = at;
        }
        self.0.default = Some(at);
        self
    }

    /// The earliest moment that can be picked: days before its day are
    /// dimmed, and on its day an earlier time is refused.
    pub fn min(mut self, at: DateTime) -> Self {
        self.0.min = Some(at);
        self
    }

    /// The latest moment that can be picked.
    pub fn max(mut self, at: DateTime) -> Self {
        self.0.max = Some(at);
        self
    }

    /// Refuse a moment `check` returns an error for: Enter shows the error
    /// and waits.
    pub fn validate(
        mut self,
        check: impl Fn(DateTime) -> Result<(), String> + Send + Sync + 'static,
    ) -> Self {
        self.0.check = Some(Arc::new(check));
        self
    }

    /// The moment selected so far.
    pub fn selected(&self) -> DateTime {
        self.0.shown(self.0.value)
    }
}

/// The [`Component`] of a picker answering `$output`, made from the
/// shared state by `$from`.
macro_rules! picker_component {
    ($picker:ty, $output:ty, $from:expr) => {
        impl Component for $picker {
            type Output = $output;

            fn start(&mut self, _context: &Context<'_>) -> Flow<$output> {
                // A start outside the range moves into it, and without
                // seconds it is to the minute.
                let mut value = self.0.shown(self.0.value);
                value.date = self.0.clamp_day(value.date);
                self.0.value = value;
                Flow::Continue
            }

            fn handle(&mut self, event: &Event, _context: &Context<'_>) -> Flow<$output> {
                match self.0.event(event) {
                    Flow::Done(at) => Flow::Done($from(at)),
                    Flow::Cancel => Flow::Cancel,
                    Flow::Ignored => Flow::Ignored,
                    _ => Flow::Continue,
                }
            }

            fn render(&self, context: &Context<'_>) -> View {
                self.0.render(context)
            }

            fn mouse(&self) -> bool {
                self.0.mouse
            }

            fn keymap(&self) -> Keymap {
                self.0.keymap.clone()
            }

            /// Tab inside: the next part, if there is one.
            fn focus_step(&mut self, forward: bool) -> bool {
                self.0.step_part(forward)
            }

            /// Tab from outside: the first part, or the last going back.
            fn focus_enter(&mut self, forward: bool) -> bool {
                self.0.enter(forward);
                true
            }

            /// The default, unless the picker would refuse it: outside the
            /// range, or refused by the validator.
            fn default_value(&self) -> Option<$output> {
                self.0
                    .default
                    .and_then(|default| self.0.checked(default).ok())
                    .map($from)
            }

            fn prompt(&mut self, io: &mut dyn LineIo) -> Result<Option<$output>, NotInteractive> {
                Ok(self.0.ask(io)?.map($from))
            }
        }
    };
}

picker_component!(DatePicker, Date, |at: DateTime| at.date);
picker_component!(TimePicker, Time, |at: DateTime| at.time);
picker_component!(DateTimePicker, DateTime, |at: DateTime| at);