very-normal 0.2.1

A terminal typing tutor that makes a keyboard layout from your own typing and moves you to it from QWERTY a few keys at a time
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
//! The TUI: stage, keyboard map, next Oryx edits, gate, and the trainer.

use std::path::PathBuf;
use std::time::Instant;

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Paragraph, Wrap};

use crate::drill::{Drill, Mode, Rng, build};
use crate::gate;
use crate::layout;
use crate::store::{Progress, Run};
use crate::warmup::{self, Warmup};
use crate::{coach, oryx, report};

const PINK: Color = Color::Magenta;
const TEAL: Color = Color::Cyan;
/// Restarts this close together suggest frustration.
const ABANDON_WINDOW: std::time::Duration = std::time::Duration::from_secs(10 * 60);

pub struct App {
    pub progress: Progress,
    path: PathBuf,
    /// The troublesome keys this drill's words lean on.
    leaning: Vec<char>,
    mode: Mode,
    drill: Drill,
    typing: bool,
    rng: Rng,
    /// The result of the last drill, or of the last thing you did.
    message: Option<(String, bool)>,
    /// The last `c` check against Oryx.
    check: Vec<String>,
    layout_id: String,
    /// Set when the coach said stop and you pressed enter anyway once.
    override_armed: bool,
    /// The warm-up, while it runs.
    warmup: Option<Warmup>,
    /// When you recently gave up on a drill with esc; several close together
    /// usually means frustration.
    abandons: Vec<Instant>,
    pub should_quit: bool,
}

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

impl App {
    pub fn new(progress: Progress, path: PathBuf, now: Instant) -> App {
        let mut rng = Rng::new();
        let stage = progress.stage.min(layout::last());
        let leaning = crate::drill::leaning(Mode::Words, stage, &progress);
        let drill = Drill::new(
            Mode::Words,
            stage,
            build(Mode::Words, stage, &progress, &mut rng),
            now,
        );
        App {
            progress,
            path,
            leaning,
            mode: Mode::Words,
            drill,
            typing: false,
            rng,
            message: None,
            check: Vec::new(),
            layout_id: oryx::layout_id(),
            override_armed: false,
            warmup: None,
            abandons: Vec::new(),
            should_quit: false,
        }
    }

    fn stage(&self) -> usize {
        self.progress.stage.min(layout::last())
    }

    fn save(&mut self) {
        if let Err(e) = self.progress.save(&self.path) {
            self.message = Some((format!("Couldn't save progress: {e}"), false));
        }
    }

    fn new_drill(&mut self, now: Instant) {
        let text = build(self.mode, self.stage(), &self.progress, &mut self.rng);
        self.leaning = crate::drill::leaning(self.mode, self.stage(), &self.progress);
        self.drill = Drill::new(self.mode, self.stage(), text, now);
    }

    fn set_stage(&mut self, stage: usize, now: Instant) {
        self.progress.stage = stage.min(layout::last());
        self.check.clear();
        self.message = None;
        self.save();
        self.new_drill(now);
    }

    /// Ends a timed drill once its minute is up.
    pub fn tick(&mut self, now: Instant) {
        if self.warmup.as_ref().is_some_and(|w| w.done(now)) {
            self.end_warmup(true);
        }
        if self.typing {
            self.drill.tick(now);
            if self.drill.done {
                self.finish(now);
            }
        }
    }

    fn needs_warmup(&self) -> bool {
        self.progress.warmed_up.as_deref() != Some(coach::today(now_ms()).as_str())
    }

    fn end_warmup(&mut self, completed: bool) {
        self.warmup = None;
        self.progress.warmed_up = Some(coach::today(now_ms()));
        self.save();
        self.message = Some(if completed {
            (
                "Warmed up. Fingers loose, shoulders down. Press enter to start.".into(),
                true,
            )
        } else {
            (
                "Skipping the warm-up? Bold. Your wrists will remember this.".into(),
                false,
            )
        });
    }

    fn finish(&mut self, now: Instant) {
        self.typing = false;
        let (stage, mode) = (self.drill.stage, self.drill.mode);
        // round once, so the number shown, the number saved and the number judged agree
        let wpm = (self.drill.wpm(now) * 10.0).round() / 10.0;
        let acc = (self.drill.accuracy() * 10.0).round() / 10.0;
        let previous_best = self
            .progress
            .runs_for(stage, mode.id())
            .iter()
            .map(|r| r.wpm)
            .fold(None, |best: Option<f64>, w| {
                Some(best.map_or(w, |b| b.max(w)))
            });
        let t = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        let run = Run {
            t,
            stage,
            mode: mode.id().into(),
            wpm,
            acc,
            secs: (self.drill.elapsed(now).as_secs_f64() * 10.0).round() / 10.0,
            letters: self.drill.letters().clone(),
            typos: self.drill.typos().clone(),
        };
        self.progress.record(run, self.drill.pairs());
        self.save();

        let mut good = true;
        let verdict = match mode {
            Mode::Words if stage > 0 => {
                good = acc >= gate::WORDS_ACCURACY;
                let hits = gate::words_hits(&self.progress, stage).min(gate::WORDS_NEEDED);
                if good && hits >= gate::WORDS_NEEDED {
                    "That one counts, and that's the accuracy part of the gate done!".to_string()
                } else if good {
                    format!("That one counts: {hits} of {}.", gate::WORDS_NEEDED)
                } else {
                    "Not one for the gate this time. Every rep still teaches your fingers; slow and smooth wins.".to_string()
                }
            }
            Mode::Real if stage == 0 => "Saved toward your baseline.".to_string(),
            Mode::Real => match self.progress.baseline() {
                Some(b) => {
                    let target = b * gate::SPEED_SHARE;
                    good = wpm >= target && acc >= gate::REAL_ACCURACY;
                    format!("Target is {target:.0} WPM at 95%+.")
                }
                None => "Record a baseline in stage 0 to get a target.".to_string(),
            },
            Mode::Recall => {
                let slow: Vec<String> = self
                    .drill
                    .slowest(3)
                    .iter()
                    .map(|(c, ms, miss)| {
                        if *miss > 0 {
                            format!("{c} {ms:.0}ms, {miss} missed")
                        } else {
                            format!("{c} {ms:.0}ms")
                        }
                    })
                    .collect();
                format!("Slowest: {}", slow.join(" · "))
            }
            _ => String::new(),
        };
        let record = match previous_best {
            Some(best) if wpm > best && acc >= 90.0 => " New speed record for this stage!",
            _ => "",
        };
        self.message = Some((
            format!("{wpm:.0} WPM · {acc:.1}% accuracy. {verdict}{record}"),
            good,
        ));
    }

    pub fn handle_key(&mut self, key: KeyEvent, now: Instant) {
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.should_quit = true;
            return;
        }
        if let Some(w) = &mut self.warmup {
            match key.code {
                KeyCode::Enter | KeyCode::Tab | KeyCode::Char(' ') => {
                    w.skip_step(now);
                    if w.done(now) {
                        self.end_warmup(true);
                    }
                }
                KeyCode::Char('s') => self.end_warmup(false),
                KeyCode::Esc => {
                    self.warmup = None;
                    self.message = Some((
                        "Warm-up paused. Press enter when you're ready.".into(),
                        true,
                    ));
                }
                _ => {}
            }
            return;
        }
        if self.typing {
            match key.code {
                KeyCode::Esc => {
                    self.typing = false;
                    self.abandons
                        .retain(|t| now.duration_since(*t) < ABANDON_WINDOW);
                    self.abandons.push(now);
                    self.message = Some(if self.abandons.len() >= 3 {
                        (
                            "That's a few restarts in a row. Frustration makes fingers tense, and tense fingers miss. Take five and come back loose.".into(),
                            false,
                        )
                    } else {
                        ("Stopped. Nothing was saved.".into(), true)
                    });
                    self.new_drill(now);
                }
                KeyCode::Char(c)
                    if !key
                        .modifiers
                        .intersects(KeyModifiers::ALT | KeyModifiers::SUPER) =>
                {
                    self.drill.press(c, now);
                    if self.drill.done {
                        self.finish(now);
                    }
                }
                _ => {}
            }
            return;
        }
        let stage = self.stage();
        match key.code {
            KeyCode::Char('q') => self.should_quit = true,
            KeyCode::Left | KeyCode::Char('[') if stage > 0 => self.set_stage(stage - 1, now),
            KeyCode::Right | KeyCode::Char(']') if stage < layout::last() => {
                self.set_stage(stage + 1, now)
            }
            KeyCode::Char(d @ '1'..='6') => {
                self.mode = Mode::ALL[d as usize - '1' as usize];
                self.message = None;
                self.new_drill(now);
            }
            KeyCode::Enter | KeyCode::Tab | KeyCode::Char(' ') => {
                let advice = self.advice();
                if advice.blocks() && !self.override_armed {
                    self.override_armed = true;
                    self.message = Some((
                        format!(
                            "{} Press enter again to practise anyway, rebel.",
                            advice.message
                        ),
                        false,
                    ));
                    return;
                }
                self.override_armed = false;
                if self.needs_warmup() {
                    self.warmup = Some(Warmup::new(now));
                    self.message = None;
                    return;
                }
                if self.drill.done || self.drill.started() {
                    self.new_drill(now);
                }
                self.message = None;
                self.drill.touch(now);
                self.typing = true;
            }
            KeyCode::Char('u') => {
                self.warmup = Some(Warmup::new(now));
                self.message = None;
            }
            KeyCode::Char('n') => {
                self.message = None;
                self.new_drill(now);
            }
            KeyCode::Char('c') => {
                self.check = match oryx::fetch(&self.layout_id) {
                    Ok(snap) => report::check(&snap, stage),
                    Err(e) => vec![format!("Couldn't read Oryx: {e}")],
                };
            }
            KeyCode::Char('g') => {
                let out = crate::charts::default_path(&self.path);
                let now_ms = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_millis() as u64)
                    .unwrap_or(0);
                self.message = Some(
                    match crate::charts::write(&self.progress, &out, now_ms)
                        .and_then(|()| crate::open_url(&out.display().to_string()))
                    {
                        Ok(()) => (format!("Charts opened from {}", out.display()), true),
                        Err(e) => (format!("Couldn't make the charts: {e}"), false),
                    },
                );
            }
            KeyCode::Char('o') => {
                let url = oryx::edit_url(&self.layout_id);
                self.message = Some(match crate::open_url(&url) {
                    Ok(()) => (format!("Opened {url}"), true),
                    Err(e) => (format!("Couldn't open {url}: {e}"), false),
                });
            }
            KeyCode::Char(c) => {
                if let Some(tick) = gate::items(&self.progress, stage)
                    .iter()
                    .filter_map(|i| i.tick)
                    .find(|t| t.key() == c)
                {
                    tick.toggle(&mut self.progress, stage);
                    self.save();
                }
            }
            _ => {}
        }
    }

    pub fn render(&self, frame: &mut Frame, now: Instant) {
        // tall enough for the next stage's edits (plus any check) and the gate
        let next_lines = report::next_stage_compact(self.stage(), "").len()
            + if self.check.is_empty() {
                0
            } else {
                self.check.len() + 1
            };
        let gate_lines = gate::items(&self.progress, self.stage())
            .iter()
            .map(|i| 1 + usize::from(!i.detail.is_empty()))
            .sum::<usize>()
            + 1;
        // the trainer keeps at least 8 rows; the middle panels take what is left
        let spare = frame.area().height.saturating_sub(3 + 1 + 5 + 1 + 8);
        let middle_height = ((next_lines.max(gate_lines) + 2).min(18) as u16).min(spare);
        let [header, blurb, keyboard, middle, trainer, footer] = Layout::vertical([
            Constraint::Length(3),
            Constraint::Length(1),
            Constraint::Length(5),
            Constraint::Length(middle_height),
            Constraint::Fill(1),
            Constraint::Length(1),
        ])
        .areas(frame.area());
        self.render_header(frame, header);
        frame.render_widget(
            Paragraph::new(layout::blurb(self.stage()))
                .style(dim())
                .wrap(Wrap { trim: true }),
            blurb,
        );
        self.render_keyboard(frame, keyboard, now);
        let [next, gate] =
            Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)])
                .areas(middle);
        self.render_next(frame, next);
        self.render_gate(frame, gate);
        self.render_trainer(frame, trainer, now);
        let help = if self.warmup.is_some() {
            "enter next step · s skip the warm-up · esc pause"
        } else if self.typing {
            "type the text · esc stops without saving"
        } else {
            "←/→ stage · 1-6 drill · enter start · u warm-up · n new text · g charts · c check oryx · o open oryx · k/v/w tick · q quit"
        };
        frame.render_widget(Paragraph::new(help).style(dim()), footer);
    }

    fn render_header(&self, frame: &mut Frame, area: Rect) {
        let s = self.stage();
        let (home, sfb) = layout::stats(s);
        let title = Line::from(vec![
            Span::styled(
                format!("{}  ", layout::plan().name.to_lowercase()),
                Style::new().fg(PINK).add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("stage {s} of {} · {}", layout::last(), layout::name(s)),
                Style::new().add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("   {home}% home row · {sfb}% same-finger pairs"),
                dim(),
            ),
        ]);
        let mut steps = Vec::new();
        for i in 0..=layout::last() {
            let passed = gate::passed(&self.progress, i);
            let style = if i == s {
                Style::new()
                    .fg(Color::Black)
                    .bg(PINK)
                    .add_modifier(Modifier::BOLD)
            } else if passed {
                Style::new().fg(Color::Green)
            } else {
                dim()
            };
            steps.push(Span::styled(
                format!(" {i}{} ", if passed { "✓" } else { "" }),
                style,
            ));
            steps.push(Span::raw(" "));
        }
        let advice = self.advice();
        let (icon, color) = match advice.level {
            coach::Level::Good => ("✓", Color::Green),
            coach::Level::Nudge => ("»", Color::Yellow),
            coach::Level::Stop => ("✋", Color::LightRed),
        };
        let coach_line = Line::from(vec![
            Span::styled(
                format!("{icon} {}", advice.message),
                Style::new().fg(color).add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!(
                    "   today {:.0}/{:.0} min · session {:.0} min",
                    advice.today_minutes,
                    coach::DAILY_GOAL,
                    advice.session_minutes
                ),
                dim(),
            ),
        ]);
        frame.render_widget(
            Paragraph::new(vec![title, Line::from(steps), coach_line]),
            area,
        );
    }

    pub fn advice(&self) -> coach::Advice {
        coach::assess(&self.progress.runs, now_ms())
    }

    fn render_keyboard(&self, frame: &mut Frame, area: Rect, now: Instant) {
        let s = self.stage();
        let keys = layout::keys(s);
        let mirror_mode = self.mode == Mode::Mirror;
        let hint = if self.typing && self.drill.hesitating(now) {
            self.drill.expected()
        } else {
            None
        };
        let hinted = |index: usize| -> bool {
            let Some(h) = hint else { return false };
            if mirror_mode {
                index % 10 < 5 && (keys[index] == h || keys[layout::mirror(index)] == h)
            } else {
                keys[index] == h
            }
        };
        let mut lines = Vec::new();
        for row in 0..3 {
            let mut spans = vec![Span::styled(
                format!("{:>4} ", layout::OUTER_LEFT[row]),
                dim(),
            )];
            for col in 0..10 {
                let i = row * 10 + col;
                if col == 5 {
                    spans.push(Span::raw("     "));
                }
                let mut style = if layout::changed_now(s, i) {
                    Style::new().fg(PINK).add_modifier(Modifier::BOLD)
                } else if layout::moved(s, i) {
                    Style::new().fg(TEAL)
                } else {
                    Style::new()
                };
                if hinted(i) {
                    style = Style::new()
                        .fg(Color::Black)
                        .bg(Color::Yellow)
                        .add_modifier(Modifier::BOLD);
                }
                if mirror_mode && col < 5 {
                    spans.push(Span::styled(format!(" {}", keys[i]), style));
                    spans.push(Span::styled(
                        format!("{} ", keys[layout::mirror(i)]),
                        Style::new().fg(PINK),
                    ));
                } else {
                    spans.push(Span::styled(format!(" {} ", keys[i]), style));
                }
            }
            spans.push(Span::styled(
                format!(" {}", layout::OUTER_RIGHT[row]),
                dim(),
            ));
            lines.push(Line::from(spans));
        }
        let legend = Line::from(vec![
            Span::styled("pink", Style::new().fg(PINK)),
            Span::styled(" moves this stage · ", dim()),
            Span::styled("teal", Style::new().fg(TEAL)),
            Span::styled(" moved earlier · yellow: the key you're looking for", dim()),
        ]);
        let block = Block::bordered().title(" voyager ").title_bottom(legend);
        frame.render_widget(Paragraph::new(lines).block(block), area);
    }

    fn render_next(&self, frame: &mut Frame, area: Rect) {
        let s = self.stage();
        let url = oryx::edit_url(&self.layout_id);
        let mut lines: Vec<Line> = report::next_stage_compact(s, &url)
            .into_iter()
            .map(Line::from)
            .collect();
        if !self.check.is_empty() {
            lines.push(Line::raw(""));
            lines.extend(
                self.check
                    .iter()
                    .map(|l| Line::styled(l.clone(), Style::new().fg(TEAL))),
            );
        }
        let block = Block::bordered().title(" next oryx edits (o open · c check) ");
        frame.render_widget(
            Paragraph::new(lines)
                .block(block)
                .wrap(Wrap { trim: false }),
            area,
        );
    }

    fn render_gate(&self, frame: &mut Frame, area: Rect) {
        let s = self.stage();
        let mut lines = Vec::new();
        for item in gate::items(&self.progress, s) {
            let mark = if item.ok {
                Span::styled("[✓] ", Style::new().fg(Color::Green))
            } else {
                Span::styled("[ ] ", dim())
            };
            let key = item
                .tick
                .map_or(String::new(), |t| format!(" ({})", t.key()));
            lines.push(Line::from(vec![
                mark,
                Span::raw(item.label),
                Span::styled(key, Style::new().fg(PINK)),
            ]));
            if !item.detail.is_empty() {
                lines.push(Line::styled(format!("    {}", item.detail), dim()));
            }
        }
        if gate::passed(&self.progress, s) {
            let msg = if s < layout::last() {
                format!(
                    "Gate passed. Make the stage {} edits, flash, then →.",
                    s + 1
                )
            } else {
                format!("Every gate passed. You type {}.", layout::plan().name)
            };
            lines.push(Line::styled(msg, Style::new().fg(Color::Green)));
        }
        let block = Block::bordered().title(format!(
            " gate before stage {} ",
            (s + 1).min(layout::last())
        ));
        frame.render_widget(
            Paragraph::new(lines)
                .block(block)
                .wrap(Wrap { trim: false }),
            area,
        );
    }

    fn render_warmup(&self, frame: &mut Frame, area: Rect, w: &Warmup, now: Instant) {
        let current = w.current(now);
        let mut lines = vec![
            Line::styled(
                format!(
                    "About {} seconds. Gentle: nothing should hurt.",
                    Warmup::total()
                ),
                dim(),
            ),
            Line::raw(""),
        ];
        for (i, step) in warmup::STEPS.iter().enumerate() {
            let line = match current {
                Some((c, left)) if c == i => Line::from(vec![
                    Span::styled(
                        format!(" ▶ {} ", step.title),
                        Style::new()
                            .fg(Color::Black)
                            .bg(PINK)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(format!("  {left}s  "), Style::new().fg(PINK)),
                    Span::raw(step.how),
                ]),
                Some((c, _)) if c > i => {
                    Line::styled(format!(" ✓ {}", step.title), Style::new().fg(Color::Green))
                }
                _ => Line::styled(format!("   {} ({}s)", step.title, step.secs), dim()),
            };
            lines.push(line);
        }
        if let Some(b) = w.breath(now) {
            lines.push(Line::raw(""));
            lines.push(Line::styled(
                format!("        {b}"),
                Style::new().fg(TEAL).add_modifier(Modifier::BOLD),
            ));
        }
        let block = Block::bordered()
            .border_style(Style::new().fg(TEAL))
            .title(" warm-up ");
        frame.render_widget(
            Paragraph::new(lines)
                .block(block)
                .wrap(Wrap { trim: false }),
            area,
        );
    }

    fn render_trainer(&self, frame: &mut Frame, area: Rect, now: Instant) {
        if let Some(w) = &self.warmup {
            self.render_warmup(frame, area, w, now);
            return;
        }
        let s = self.stage();
        let mut tabs = Vec::new();
        for (n, m) in Mode::ALL.iter().enumerate() {
            let style = if *m == self.mode {
                Style::new()
                    .fg(Color::Black)
                    .bg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else {
                dim()
            };
            tabs.push(Span::styled(format!(" {} {} ", n + 1, m.label()), style));
            tabs.push(Span::raw(" "));
        }
        let mut lines = vec![Line::from(tabs), Line::styled(self.mode.describe(s), dim())];
        if let Some(line) = self.leaning_line() {
            lines.push(line);
        }
        lines.push(Line::raw(""));
        lines.extend(self.text_lines());
        lines.push(Line::raw(""));
        lines.push(self.status_line(now));
        if let Some((msg, good)) = &self.message {
            // misses are yellow, not red: they're information, not a telling-off
            let color = if *good { Color::Green } else { Color::Yellow };
            lines.push(Line::styled(msg.clone(), Style::new().fg(color)));
        }
        let recent: Vec<_> = self.progress.runs.iter().rev().take(3).collect();
        if !recent.is_empty() {
            lines.push(Line::raw(""));
            for r in recent {
                lines.push(Line::styled(
                    format!(
                        "  stage {} · {:<14} {:>3.0} wpm  {:>5.1}%",
                        r.stage,
                        Mode::label_for(&r.mode),
                        r.wpm,
                        r.acc
                    ),
                    dim(),
                ));
            }
        }
        let border = if self.typing {
            Style::new().fg(PINK)
        } else {
            Style::new()
        };
        let block = Block::bordered().border_style(border).title(" trainer ");
        frame.render_widget(
            Paragraph::new(lines)
                .block(block)
                .wrap(Wrap { trim: false }),
            area,
        );
    }

    fn text_lines(&self) -> Vec<Line<'static>> {
        let d = &self.drill;
        if d.done {
            return vec![Line::styled("Done. Press enter for another round.", dim())];
        }
        if d.mode == Mode::Recall {
            let cur = d.expected().unwrap_or(' ');
            let next: String = d
                .text
                .iter()
                .skip(d.pos + 1)
                .take(3)
                .flat_map(|c| [*c, ' '])
                .collect();
            let style = if d.error {
                Style::new()
                    .fg(Color::Black)
                    .bg(Color::LightRed)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::new()
                    .fg(Color::Black)
                    .bg(PINK)
                    .add_modifier(Modifier::BOLD)
            };
            return vec![Line::from(vec![
                Span::raw("      "),
                Span::styled(format!("   {cur}   "), style),
                Span::styled(format!("    next: {next}"), dim()),
            ])];
        }
        let mut start = d.pos.saturating_sub(40);
        while start > 0 && d.text[start - 1] != ' ' {
            start -= 1;
        }
        let end = (start + 240).min(d.text.len());
        let mut spans = Vec::new();
        for i in start..end {
            let c = d.text[i];
            let style = if i < d.pos {
                Style::new()
            } else if i == d.pos {
                let base = Style::new().add_modifier(Modifier::UNDERLINED | Modifier::BOLD);
                if d.error {
                    base.bg(Color::LightRed).fg(Color::Black)
                } else {
                    base.fg(PINK)
                }
            } else {
                dim()
            };
            let shown = if c == ' ' && i == d.pos { '·' } else { c };
            spans.push(Span::styled(shown.to_string(), style));
        }
        vec![Line::from(spans)]
    }

    /// Names the keys the words lean on: extra reps, said kindly.
    fn leaning_line(&self) -> Option<Line<'static>> {
        let keys: Vec<String> = self.leaning.iter().map(char::to_string).collect();
        let named = match keys.as_slice() {
            [] => return None,
            [one] => one.clone(),
            [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
        };
        Some(Line::styled(
            format!("A few extra words with {named} in them, your trickiest keys right now."),
            dim(),
        ))
    }

    fn status_line(&self, now: Instant) -> Line<'static> {
        let d = &self.drill;
        if !self.typing && self.needs_warmup() {
            return Line::styled(
                "Press enter to start. First session today, so a one-minute warm-up comes first.",
                dim(),
            );
        }
        if !self.typing {
            return Line::styled(
                "Press enter to start. If you hesitate, the key lights up on the map.",
                dim(),
            );
        }
        if !d.started() {
            return Line::styled(
                "Go! The timer starts on your first key.",
                Style::new().fg(PINK),
            );
        }
        let progress = match d.remaining(now) {
            Some(r) => format!("{}s left", r.as_secs() + u64::from(r.subsec_millis() > 0)),
            None => format!("{}/{}", d.pos, d.text.len()),
        };
        Line::styled(
            format!(
                "{progress} · {:.0} wpm · {:.1}% accuracy",
                d.wpm(now),
                d.accuracy()
            ),
            Style::new().fg(TEAL),
        )
    }
}

fn dim() -> Style {
    Style::new().fg(Color::DarkGray)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use ratatui::crossterm::event::KeyEventKind;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new_with_kind(code, KeyModifiers::NONE, KeyEventKind::Press)
    }

    fn app() -> (App, PathBuf) {
        let path = std::env::temp_dir().join(format!(
            "very-normal-app-{}-{:?}.json",
            std::process::id(),
            std::thread::current().id()
        ));
        let p = Progress {
            stage: 1,
            warmed_up: Some(coach::today(now_ms())),
            ..Default::default()
        };
        (App::new(p, path.clone(), Instant::now()), path)
    }

    fn screen(app: &App) -> String {
        let mut t = Terminal::new(TestBackend::new(200, 40)).unwrap();
        t.draw(|f| app.render(f, Instant::now())).unwrap();
        t.backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect::<String>()
    }

    #[test]
    fn shows_the_stage_and_the_next_edits() {
        let (app, _) = app();
        let s = screen(&app);
        assert!(s.contains("stage 1 of 9"));
        assert!(s.contains("Stage 2: I and O come home"));
        assert!(s.contains("configure.zsa.io/voyager/layouts/"));
        assert!(s.contains("keys: i→a  o→k  a→i  k→o (keep alt)"));
    }

    #[test]
    fn typing_a_whole_drill_records_a_run() {
        let (mut app, path) = app();
        let now = Instant::now();
        app.handle_key(key(KeyCode::Enter), now);
        let text: Vec<char> = app.drill.text.clone();
        for c in text {
            app.handle_key(key(KeyCode::Char(c)), now);
        }
        assert!(!app.typing);
        assert_eq!(app.progress.runs.len(), 1);
        assert_eq!(app.progress.runs[0].mode, "words");
        assert_eq!(app.progress.runs[0].acc, 100.0);
        assert!(Progress::load(&path).unwrap().runs.len() == 1);
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn letters_typed_outside_a_drill_tick_boxes_instead() {
        let (mut app, path) = app();
        app.handle_key(key(KeyCode::Char('v')), Instant::now());
        assert!(app.progress.manual(1).vim);
        app.handle_key(key(KeyCode::Right), Instant::now());
        assert_eq!(app.progress.stage, 2);
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn escape_abandons_a_drill_without_saving() {
        let (mut app, path) = app();
        let now = Instant::now();
        app.handle_key(key(KeyCode::Enter), now);
        app.handle_key(key(KeyCode::Char('x')), now);
        app.handle_key(key(KeyCode::Esc), now);
        assert!(!app.typing);
        assert!(app.progress.runs.is_empty());
        std::fs::remove_file(path).ok();
    }
}

#[cfg(test)]
mod coach_tests {
    use super::*;
    use ratatui::crossterm::event::KeyEventKind;

    #[test]
    fn the_coach_makes_you_ask_twice_after_a_long_session() {
        let path =
            std::env::temp_dir().join(format!("very-normal-coach-{}.json", std::process::id()));
        let end = now_ms();
        let runs = (0..13u64)
            .map(|i| Run {
                t: end - (12 - i) * 120_000,
                stage: 1,
                mode: "words".into(),
                wpm: 15.0,
                acc: 98.0,
                secs: 120.0,
                ..Run::default()
            })
            .collect();
        let p = Progress {
            stage: 1,
            runs,
            warmed_up: Some(coach::today(now_ms())),
            ..Default::default()
        };
        let mut app = App::new(p, path.clone(), Instant::now());
        let enter =
            KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Press);
        app.handle_key(enter, Instant::now());
        assert!(!app.typing);
        assert!(app.message.as_ref().unwrap().0.contains("rebel"));
        app.handle_key(enter, Instant::now());
        assert!(app.typing);
        std::fs::remove_file(path).ok();
    }
}

#[cfg(test)]
mod warmup_tests {
    use super::*;
    use ratatui::crossterm::event::KeyEventKind;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new_with_kind(code, KeyModifiers::NONE, KeyEventKind::Press)
    }

    #[test]
    fn the_first_drill_of_the_day_starts_with_a_warm_up() {
        let path =
            std::env::temp_dir().join(format!("very-normal-warmup-{}.json", std::process::id()));
        let mut app = App::new(
            Progress {
                stage: 1,
                ..Default::default()
            },
            path.clone(),
            Instant::now(),
        );
        let now = Instant::now();
        app.handle_key(key(KeyCode::Enter), now);
        assert!(app.warmup.is_some() && !app.typing);

        app.handle_key(key(KeyCode::Char('s')), now);
        assert!(app.warmup.is_none());
        assert!(app.message.as_ref().unwrap().0.contains("Bold"));
        assert_eq!(app.progress.warmed_up, Some(coach::today(now_ms())));

        app.handle_key(key(KeyCode::Enter), now);
        assert!(app.typing, "no second warm-up the same day");
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn enter_steps_through_the_warm_up_to_the_end() {
        let path =
            std::env::temp_dir().join(format!("very-normal-warmup2-{}.json", std::process::id()));
        let mut app = App::new(Progress::default(), path.clone(), Instant::now());
        let now = Instant::now();
        app.handle_key(key(KeyCode::Char('u')), now);
        for _ in 0..warmup::STEPS.len() {
            app.handle_key(key(KeyCode::Enter), now);
        }
        assert!(app.warmup.is_none());
        assert!(app.message.as_ref().unwrap().0.contains("Warmed up"));
        std::fs::remove_file(path).ok();
    }
}

#[cfg(test)]
mod verdict_tests {
    use super::*;
    use crate::store::Run;

    fn words_run(acc: f64) -> Run {
        Run {
            t: 1,
            stage: 1,
            mode: "words".into(),
            wpm: 15.0,
            acc,
            secs: 60.0,
            ..Run::default()
        }
    }

    #[test]
    fn the_number_shown_is_the_number_judged() {
        // 96.96% shows as 97.0%, so it has to count as 97%
        let p = Progress {
            runs: vec![words_run((96.96f64 * 10.0).round() / 10.0)],
            ..Default::default()
        };
        assert_eq!(gate::words_hits(&p, 1), 1);
    }
}

#[cfg(test)]
mod frustration_tests {
    use super::*;
    use ratatui::crossterm::event::KeyEventKind;

    #[test]
    fn several_restarts_suggest_a_break() {
        let path = std::env::temp_dir().join(format!(
            "very-normal-frustration-{}.json",
            std::process::id()
        ));
        let p = Progress {
            stage: 1,
            warmed_up: Some(coach::today(now_ms())),
            ..Default::default()
        };
        let mut app = App::new(p, path.clone(), Instant::now());
        let key = |c| KeyEvent::new_with_kind(c, KeyModifiers::NONE, KeyEventKind::Press);
        for _ in 0..3 {
            app.handle_key(key(KeyCode::Enter), Instant::now());
            app.handle_key(key(KeyCode::Esc), Instant::now());
        }
        assert!(app.message.as_ref().unwrap().0.contains("Frustration"));
        std::fs::remove_file(path).ok();
    }
}