mach-tui 0.8.0

A terminal-first task manager for people who live in the shell and work with agents
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
//! Every screen is drawn once against an in-memory terminal.
//!
//! The drawing code does its own arithmetic on rects, widths and scroll
//! offsets, so a bad subtraction panics rather than misdraws. These
//! render each mode at a few sizes — including ones barely big enough —
//! and assert the frame comes out with something recognisable on it.

use chrono::{Datelike, Duration};
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{Event, KeyModifiers, MouseEvent, MouseEventKind};
use ratatui::style::Modifier;

use mach::app::{App, Focus, Mode};
use mach::form::CategoryForm;
use mach::input::handle_event;
use mach::model::{Block, Category, Label, LabelColor, Task};
use mach::store::Store;
use mach::ui;

#[path = "common/render.rs"]
mod render_common;
use render_common::{buffer_text, draw, find_cells, move_mouse};

/// The screen as text, one line per row.
fn render(app: &mut App, width: u16, height: u16) -> String {
    buffer_text(&draw(app, width, height))
}

/// Whether the cells spelling out `needle` are all bold — how the help
/// page marks a section heading. Panics if the text is not on screen.
fn is_bold(buffer: &Buffer, needle: &str) -> bool {
    let (x0, y) = find_cells(buffer, needle);
    (x0..x0 + needle.chars().count() as u16)
        .map(|x| &buffer[(x, y)])
        .filter(|cell| !cell.symbol().trim().is_empty())
        .all(|cell| cell.modifier.contains(Modifier::BOLD))
}

/// An app with two categories and a few tasks, backed by an independent
/// in-memory store for each test.
fn sample_app() -> App {
    let mut store = Store::open_in_memory_with_paths(
        std::env::temp_dir().join(format!("mach-render-test-{}", uuid::Uuid::new_v4())),
    )
    .unwrap();
    let categories = vec![
        Category {
            id: "c-work".into(),
            name: "Work".into(),
            description: "what pays".into(),
        },
        Category {
            id: "c-home".into(),
            name: "Home".into(),
            description: String::new(),
        },
    ];
    let mut flagged = Task::new(
        "ship the release",
        3,
        Some("c-work".into()),
        "2030-01-02 09:00",
    );
    flagged.description = vec![
        Block::text("with a note"),
        Block::todo("step one", true),
        Block::todo("step two", false),
        Block::link("https://example.com"),
        Block::bullet("a point"),
        Block::number("first"),
    ];
    let mut done = Task::new("已完成的任务", 0, Some("c-home".into()), "");
    done.done = true;
    let tasks = vec![flagged, done, Task::new("no category", 1, None, "09:00")];
    store
        .update(|data| {
            data.categories = categories;
            data.tasks = tasks;
            Ok(())
        })
        .unwrap();
    let mut app = App::with_store("test", store).unwrap();
    // A fresh store has no recorded version, so the welcome splash is up;
    // tests that want it set the mode themselves.
    app.mode = Mode::Normal;
    app
}

#[test]
fn draws_the_main_screen() {
    let mut app = sample_app();
    let screen = render(&mut app, 100, 30);
    assert!(screen.contains("Categories"), "{screen}");
    assert!(screen.contains("Tasks"), "{screen}");
    assert!(screen.contains("ship the release"), "{screen}");
    assert!(screen.contains("Work"), "{screen}");
    // Flags, tick marks and the due date all share the row.
    assert!(screen.contains("[✓]") && screen.contains("[ ]"), "{screen}");
    assert!(screen.contains(""), "{screen}");
}

#[test]
fn hover_adds_background_only_to_an_unselected_task_row() {
    let mut app = sample_app();
    let label = Label::new("tag", LabelColor::Orange);
    let label_id = label.id.clone();
    app.labels.push(label);
    app.tasks
        .iter_mut()
        .find(|task| task.title == "no category")
        .unwrap()
        .label_ids
        .push(label_id);
    let initial = draw(&mut app, 100, 30);
    let (selected_x, selected_y) = find_cells(&initial, "ship the release");
    let selected_style = initial[(selected_x, selected_y)].style();
    let (other_x, other_y) = find_cells(&initial, "no category");
    let other_style = initial[(other_x, other_y)].style();
    let (label_x, label_y) = find_cells(&initial, "tag");
    let label_style = initial[(label_x, label_y)].style();
    let selected = app.task_index;

    assert!(move_mouse(&mut app, selected_x, selected_y));
    let selected_hover = draw(&mut app, 100, 30);
    let hovered_style = selected_hover[(selected_x, selected_y)].style();
    assert_eq!(
        hovered_style, selected_style,
        "the selected row must keep its stronger active style"
    );

    assert!(move_mouse(&mut app, other_x, other_y));
    let other_hover = draw(&mut app, 100, 30);
    let hovered_style = other_hover[(other_x, other_y)].style();
    assert!(
        hovered_style.bg != other_style.bg
            || (hovered_style
                .add_modifier
                .contains(Modifier::DIM | Modifier::REVERSED)
                && !other_style
                    .add_modifier
                    .contains(Modifier::DIM | Modifier::REVERSED)),
        "an unselected task row should gain a background-style hover state"
    );
    assert!(
        !hovered_style.add_modifier.contains(Modifier::UNDERLINED),
        "hover is a background, not an underline"
    );
    assert_eq!(
        other_hover[(label_x, label_y)].style(),
        label_style,
        "task-row hover must preserve a label badge's identity color"
    );
    assert_eq!(
        other_hover[(selected_x, selected_y)].style(),
        selected_style,
        "the previous selected row must retain only its active style"
    );
    assert_eq!(
        app.task_index, selected,
        "drawing hover cannot select a task"
    );
}

#[test]
fn category_command_and_label_items_receive_background_hover() {
    let assert_hover_changed = |before: &Buffer, after: &Buffer, x, y, kind: &str| {
        let before = before[(x, y)].style();
        let after = after[(x, y)].style();
        assert_ne!(after, before, "{kind} should receive hover styling");
        assert!(
            !after.add_modifier.contains(Modifier::UNDERLINED),
            "{kind} hover must not add an underline"
        );
    };

    let mut categories = sample_app();
    let initial = draw(&mut categories, 100, 30);
    let (x, y) = find_cells(&initial, "Home");
    assert!(move_mouse(&mut categories, x, y));
    let hovered = draw(&mut categories, 100, 30);
    assert_hover_changed(&initial, &hovered, x, y, "category row");

    let mut commands = sample_app();
    commands.mode = Mode::Slash;
    let initial = draw(&mut commands, 100, 30);
    let (x, y) = find_cells(&initial, "/settings");
    assert!(move_mouse(&mut commands, x, y));
    let hovered = draw(&mut commands, 100, 30);
    assert_hover_changed(&initial, &hovered, x, y, "command row");

    let mut labels = sample_app();
    labels.create_label("bug").unwrap();
    labels.create_label("feat").unwrap();
    labels.open_labels();
    let initial = draw(&mut labels, 100, 30);
    let (selected_x, selected_y) = find_cells(&initial, "bug");
    let selected_style = initial[(selected_x, selected_y)].style();
    let (x, y) = find_cells(&initial, "feat");
    assert!(move_mouse(&mut labels, x, y));
    let hovered = draw(&mut labels, 100, 30);
    assert_hover_changed(&initial, &hovered, x, y, "label item");

    assert!(move_mouse(&mut labels, selected_x, selected_y));
    let selected_hover = draw(&mut labels, 100, 30);
    assert_eq!(
        selected_hover[(selected_x, selected_y)].style(),
        selected_style,
        "the selected label must keep its active style"
    );
}

#[test]
fn form_fields_do_not_receive_hover_styling() {
    let mut app = sample_app();
    app.open_edit_task();
    let initial = draw(&mut app, 100, 30);
    let title = app.form.as_ref().unwrap().areas.title;
    let category = app.form.as_ref().unwrap().areas.category;
    let (title_x, title_y) = find_cells(&initial, " Title ");
    let (category_x, category_y) = find_cells(&initial, " Category ");
    let title_style = initial[(title_x, title_y)].style();
    let category_style = initial[(category_x, category_y)].style();
    let field = app.form.as_ref().unwrap().field;

    assert!(handle_event(
        &mut app,
        Event::Mouse(MouseEvent {
            kind: MouseEventKind::Moved,
            column: title.x,
            row: title.y,
            modifiers: KeyModifiers::NONE,
        }),
    ));
    let title_hover = draw(&mut app, 100, 30);
    assert_eq!(
        title_hover[(title_x, title_y)].style(),
        title_style,
        "field chrome must not receive hover styling"
    );

    assert!(!handle_event(
        &mut app,
        Event::Mouse(MouseEvent {
            kind: MouseEventKind::Moved,
            column: category.x,
            row: category.y,
            modifiers: KeyModifiers::NONE,
        }),
    ));
    let category_hover = draw(&mut app, 100, 30);
    assert_eq!(
        category_hover[(category_x, category_y)].style(),
        category_style,
        "moving between form fields must not introduce hover styling"
    );
    assert_eq!(app.form.as_ref().unwrap().field, field);
}

#[test]
fn due_calendar_hover_marks_one_date_without_overriding_the_active_date() {
    let mut app = sample_app();
    app.open_edit_task();
    app.form.as_mut().unwrap().open_due_picker();
    let initial = draw(&mut app, 100, 40);
    let picker = app.form.as_ref().unwrap().picker.as_ref().unwrap();
    let days = picker.layout.days;
    let selected = picker.day;
    let first = selected.with_day(1).unwrap();
    let start = first
        .checked_sub_signed(Duration::days(
            first.weekday().num_days_from_sunday().into(),
        ))
        .unwrap();
    let cell_for = |date: chrono::NaiveDate| {
        let offset = date.signed_duration_since(start).num_days() as u16;
        (
            days.x.saturating_add((offset % 7).saturating_mul(3)),
            days.y.saturating_add(offset / 7),
        )
    };

    let (selected_x, selected_y) = cell_for(selected);
    let selected_text_x = selected_x.saturating_add(2);
    let selected_style = initial[(selected_text_x, selected_y)].style();
    assert!(move_mouse(&mut app, selected_x, selected_y));
    let active_hover = draw(&mut app, 100, 40);
    assert_eq!(
        active_hover[(selected_text_x, selected_y)].style(),
        selected_style,
        "the active date must keep its stronger selection style"
    );

    let next = selected.succ_opt().unwrap();
    let (next_x, next_y) = cell_for(next);
    let next_first_digit_x = next_x.saturating_add(1);
    let next_text_x = next_x.saturating_add(2);
    let gutter_style = initial[(next_x, next_y)].style();
    let first_digit_style = initial[(next_first_digit_x, next_y)].style();
    let before = initial[(next_text_x, next_y)].style();
    assert!(move_mouse(&mut app, next_x, next_y));
    let hovered = draw(&mut app, 100, 40);
    assert_eq!(
        hovered[(next_x, next_y)].style(),
        gutter_style,
        "the one-cell date gutter must remain unpainted"
    );
    assert_ne!(
        hovered[(next_first_digit_x, next_y)].style(),
        first_digit_style,
        "the two-character day field should include its leading digit cell"
    );
    let after = hovered[(next_text_x, next_y)].style();
    assert!(
        after.bg != before.bg
            || (after
                .add_modifier
                .contains(Modifier::DIM | Modifier::REVERSED)
                && !before
                    .add_modifier
                    .contains(Modifier::DIM | Modifier::REVERSED)),
        "an unselected calendar date should gain a background hover"
    );
    assert!(
        !after.add_modifier.contains(Modifier::UNDERLINED),
        "date hover is a background, not an underline"
    );
}

#[test]
fn draws_every_overlay() {
    for (mode, expect) in [
        (Mode::Help, "MOVING AROUND"),
        (Mode::Settings, "Sort"),
        (Mode::Welcome, "Welcome to mach"),
        (Mode::WhatsNew, "What's new in mach"),
        (Mode::Slash, "search tasks by text or label"),
    ] {
        let mut app = sample_app();
        app.mode = mode;
        let screen = render(&mut app, 100, 30);
        assert!(
            screen.contains(expect),
            "{mode:?} missing {expect:?}:\n{screen}"
        );
    }
}

#[test]
fn whats_new_shows_complete_highlight_descriptions() {
    for (width, height) in [(60, 16), (100, 30)] {
        let mut app = sample_app();
        app.mode = Mode::WhatsNew;
        let screen = render(&mut app, width, height);

        for ending in ["assignments.", "editors.", "pickers."] {
            assert!(
                screen.contains(ending),
                "{ending:?} was clipped at {width}x{height}:\n{screen}"
            );
        }
    }
}

#[test]
fn help_marks_both_section_headings() {
    let mut app = sample_app();
    app.mode = Mode::Help;
    let buffer = draw(&mut app, 110, 40);
    // "COMMANDS  (press /)" has lowercase inside it, so a heading cannot
    // be recognised by its casing — it has to be marked as one.
    assert!(is_bold(&buffer, "MOVING AROUND"), "first heading not bold");
    assert!(
        is_bold(&buffer, "TASKS, CATEGORIES & LABELS"),
        "first heading not bold"
    );
    assert!(
        is_bold(&buffer, "COMMANDS  (press /)"),
        "second heading not bold"
    );
    assert!(is_bold(&buffer, "TASK PREVIEW"), "second heading not bold");
    // An ordinary row is plain, so the checks above mean something.
    assert!(
        !is_bold(&buffer, "/quit"),
        "description row should not be bold"
    );
}

#[test]
fn draws_the_task_dialog_with_a_description() {
    let mut app = sample_app();
    app.open_edit_task();
    // Tall enough that the docked preview shows the full description stack.
    let screen = render(&mut app, 100, 48);
    assert!(screen.contains("Edit task"), "{screen}");
    assert!(
        screen.contains("Title") && screen.contains("Due"),
        "{screen}"
    );
    assert!(screen.contains("ship the release"), "{screen}");
    // Description blocks keep their markers (docked under the task list).
    assert!(screen.contains("[✓] step one"), "{screen}");
    assert!(screen.contains("• a point"), "{screen}");
    assert!(screen.contains("1. first"), "{screen}");
    assert!(screen.contains("↗ https://example.com"), "{screen}");
    assert!(
        screen.contains("Task preview") || screen.contains("Esc list"),
        "{screen}"
    );
}

#[test]
fn preview_wraps_every_label_and_rows_compact_only_whole_label_tokens() {
    let mut app = sample_app();
    let labels = ["bug", "backend", "release", "customer-visible"]
        .into_iter()
        .map(|name| app.create_label(name).unwrap())
        .collect::<Vec<_>>();
    let task = app.selected_task().unwrap().id.clone();
    app.set_task_labels(&task, labels).unwrap();
    let labelled = app.tasks.iter_mut().find(|item| item.id == task).unwrap();
    labelled.due.clear();
    labelled.description.clear();
    app.invalidate_preview();
    app.rebuild_view();

    let wide_buffer = draw(&mut app, 100, 30);
    let wide = buffer_text(&wide_buffer);
    for label in ["bug", "backend", "release", "customer-visible"] {
        assert!(
            wide.contains(label),
            "missing {label:?} in preview:\n{wide}"
        );
    }
    assert!(!wide.contains("#bug"), "TUI labels no longer use #: {wide}");
    let (bug_x, bug_y) = find_cells(&wide_buffer, "bug");
    let (title_x, title_y) = find_cells(&wide_buffer, "ship the release");
    assert_eq!(
        bug_y, title_y,
        "first label match should be on the task row"
    );
    let expected_badge = app.theme().label_badge(app.labels[0].color, false);
    assert_eq!(
        wide_buffer[(bug_x, bug_y)].bg,
        expected_badge.bg.unwrap_or(ratatui::style::Color::Reset),
        "the focused task row must preserve the label badge background"
    );
    if expected_badge.bg.is_some() {
        assert_ne!(
            wide_buffer[(bug_x, bug_y)].bg,
            wide_buffer[(title_x, title_y)].bg,
            "the label color belongs to its badge, not its text"
        );
    }

    app.settings.preview_position = "right".into();
    let narrow = render(&mut app, 90, 30);
    let task_row = narrow
        .lines()
        .find(|line| line.contains("[ ]") && line.contains("ship the"))
        .expect("task row");
    assert!(task_row.contains("bug"), "{task_row}");
    assert!(
        task_row.contains("+"),
        "hidden labels need a count: {task_row}"
    );
    assert!(
        !task_row.contains("back…"),
        "label tokens must not truncate: {task_row}"
    );
}

#[test]
fn draws_labels_manager_and_task_label_picker_at_supported_sizes() {
    for (width, height) in [(60, 16), (100, 30)] {
        let mut app = sample_app();
        app.create_label("bug").unwrap();
        app.create_label("backend").unwrap();
        if height == 16 {
            for name in ["frontend", "design", "docs", "release", "blocked", "later"] {
                app.create_label(name).unwrap();
            }
        }
        app.mode = Mode::Labels;
        let manager_buffer = draw(&mut app, width, height);
        let manager = buffer_text(&manager_buffer);
        assert!(manager.contains("Labels"), "{manager}");
        assert!(manager.contains("bug"), "{manager}");
        let (_, bug_y) = find_cells(&manager_buffer, "bug");
        let (_, backend_y) = find_cells(&manager_buffer, "backend");
        assert_eq!(bug_y, backend_y, "labels should flow across the row");

        app.begin_rename_label();
        let editor = render(&mut app, width, height);
        for field in ["Edit label", "Name", "Color"] {
            assert!(editor.contains(field), "missing {field:?}:\n{editor}");
        }

        app.close_labels();
        app.open_edit_task();
        app.form
            .as_mut()
            .unwrap()
            .set_field(mach::form::Field::Labels);
        app.form.as_mut().unwrap().open_label_picker();
        let picker_buffer = draw(&mut app, width, height);
        let picker = buffer_text(&picker_buffer);
        let form = app.form.as_ref().unwrap();
        let picker_area = form.label_picker_area().unwrap();
        if height == 16 {
            assert!(
                picker_area.y >= form.areas.labels.bottom(),
                "short label picker must shrink below its field:\n{picker}"
            );
        }
        let title_area = form.areas.title;
        let overlaps_title = picker_area.x < title_area.right()
            && picker_area.right() > title_area.x
            && picker_area.y < title_area.bottom()
            && picker_area.bottom() > title_area.y;
        assert!(
            !overlaps_title,
            "label picker must shrink instead of covering Title:\n{picker}"
        );
        if width >= 100 {
            assert!(picker.contains("bug"), "{picker}");
        }
    }
}

#[test]
fn task_label_picker_shows_manage_when_choices_fit_the_color_palette() {
    let mut app = sample_app();
    let choice_count = LabelColor::ALL.len().saturating_sub(2);
    for index in 0..choice_count {
        app.create_label(&format!("label-{index:02}")).unwrap();
    }
    app.open_edit_task();
    app.form
        .as_mut()
        .unwrap()
        .set_field(mach::form::Field::Labels);
    app.form.as_mut().unwrap().open_label_picker();

    let picker = render(&mut app, 100, 44);

    assert!(picker.contains("label-09"), "{picker}");
    assert!(picker.contains("Manage"), "{picker}");
}

#[test]
fn task_form_overlays_replace_overlapped_description_images_with_a_marker() {
    for field in [mach::form::Field::Labels, mach::form::Field::Due] {
        let mut app = sample_app();
        app.create_label("bug").unwrap();
        app.tasks[0].description = vec![
            Block::text("one"),
            Block::text("two"),
            Block::image("missing.png"),
        ];
        app.rebuild_view();
        app.open_edit_task();

        let form = app.form.as_mut().unwrap();
        match field {
            mach::form::Field::Labels => form.open_label_picker(),
            mach::form::Field::Due => form.open_due_picker(),
            _ => unreachable!(),
        }

        let screen = render(&mut app, 140, 50);
        assert!(
            screen.contains("[image]"),
            "{field:?} overlay must hide the image protocol it covers:\n{screen}"
        );
    }
}

#[test]
fn labels_manager_occludes_underlying_task_preview_images() {
    let mut app = sample_app();
    app.settings.preview_position = "right".into();
    app.tasks[0].description = (0..14)
        .map(|_| Block::text("line"))
        .chain(std::iter::once(Block::image("missing.png")))
        .collect();
    app.rebuild_view();
    app.open_labels();
    app.begin_new_label();

    let screen = render(&mut app, 140, 50);
    assert!(
        screen.contains("[image]"),
        "the labels manager must hide the preview image protocol it covers:\n{screen}"
    );
}

#[test]
fn narrow_side_preview_uses_a_stacked_in_place_editor() {
    let mut app = sample_app();
    app.settings.preview_position = "right".into();
    app.open_edit_task();

    let buffer = draw(&mut app, 90, 30);
    let preview = app.areas.preview;
    let (edit_x, _) = find_cells(&buffer, " Edit task ");
    assert!(
        edit_x >= preview.x && edit_x < preview.right(),
        "editor should stay inside the task preview: preview={preview:?}\n{}",
        buffer_text(&buffer)
    );

    let (_, title_y) = find_cells(&buffer, " Title ");
    let (_, category_y) = find_cells(&buffer, " Category ");
    let (_, labels_y) = find_cells(&buffer, " Labels ");
    let (_, due_y) = find_cells(&buffer, " Due ");
    let (_, flags_y) = find_cells(&buffer, " Flags ");
    assert!(
        title_y < category_y && category_y < labels_y && labels_y < due_y && due_y < flags_y,
        "compact metadata fields should stack vertically\n{}",
        buffer_text(&buffer)
    );
}

#[test]
fn modal_task_editor_keeps_the_task_preview_visible_behind_it() {
    let mut app = sample_app();
    app.settings.preview_position = "right".into();
    app.tasks[0].title = format!("{}UNDERLAY", " ".repeat(32));
    app.invalidate_preview();
    app.rebuild_view();
    app.open_edit_task();

    let buffer = draw(&mut app, 120, 16);
    let preview = app.areas.preview;
    let (edit_x, _) = find_cells(&buffer, " Edit task ");
    assert!(edit_x < preview.x, "fixture should use the modal fallback");

    // The modal ends before the right edge. A marker placed at the far end
    // of the underlying preview title must remain visible beside it.
    let edge_start = buffer.area.width.saturating_sub(14);
    let mut right_edge = String::new();
    for y in 0..buffer.area.height {
        for x in edge_start..buffer.area.width {
            right_edge.push_str(buffer[(x, y)].symbol());
        }
        right_edge.push('\n');
    }
    assert!(
        right_edge.contains("UNDERLAY"),
        "modal fallback should preserve the task preview\n{}",
        buffer_text(&buffer)
    );
}

#[test]
fn draws_the_new_task_dialog_and_its_calendar() {
    let mut app = sample_app();
    app.select_category(1);
    app.open_new_task();
    let screen = render(&mut app, 100, 30);
    assert!(screen.contains("New task"), "{screen}");
    assert!(
        screen.contains("Category") && screen.contains("Work"),
        "{screen}"
    );

    app.form.as_mut().unwrap().open_due_picker();
    let screen = render(&mut app, 100, 30);
    assert!(
        screen.contains("Su") && screen.contains("Sa"),
        "weekday header:\n{screen}"
    );
    assert!(screen.contains("clear(x)"), "{screen}");
}

#[test]
fn draws_the_category_dialog() {
    let mut app = sample_app();
    app.focus = Focus::Sidebar;
    app.select_category(1);
    app.open_edit_category();
    let screen = render(&mut app, 100, 30);
    assert!(screen.contains("Edit category"), "{screen}");
    assert!(
        screen.contains("Work") && screen.contains("what pays"),
        "{screen}"
    );

    app.category_form = Some(CategoryForm::new());
    assert!(render(&mut app, 100, 30).contains("New category"));
}

#[test]
fn draws_search_and_its_empty_result() {
    let mut app = sample_app();
    app.start_search("ship");
    let screen = render(&mut app, 100, 30);
    assert!(screen.contains("ship the release"), "{screen}");
    assert!(
        !screen.contains("no category"),
        "other tasks filtered out:\n{screen}"
    );

    app.start_search("nothing matches this");
    let screen = render(&mut app, 100, 30);
    assert!(screen.contains("No tasks found"), "{screen}");
}

#[test]
fn draws_an_empty_store() {
    let mut app = sample_app();
    app.tasks.clear();
    app.rebuild_view();
    assert!(render(&mut app, 100, 30).contains("No active tasks"));
}

#[test]
fn survives_sizes_from_tiny_to_wide() {
    // Below the floor the UI says so instead of laying anything out.
    let mut app = sample_app();
    assert!(render(&mut app, 20, 5).contains("too small"));
    assert!(render(&mut app, 30, 8).contains("60×16"));

    // At and above the honest floor every mode remains operable.
    for (width, height) in [(60, 16), (80, 24), (200, 60)] {
        for mode in [
            Mode::Normal,
            Mode::Help,
            Mode::Settings,
            Mode::Labels,
            Mode::Welcome,
            Mode::WhatsNew,
            Mode::Slash,
            Mode::TaskForm,
            Mode::CategoryForm,
        ] {
            let mut app = sample_app();
            match mode {
                Mode::TaskForm => app.open_edit_task(),
                Mode::CategoryForm => {
                    app.select_category(1);
                    app.open_edit_category();
                }
                _ => app.mode = mode,
            }
            render(&mut app, width, height);
        }
    }
}

#[test]
fn minimum_size_keeps_both_primary_panels_visible() {
    let mut app = sample_app();
    let screen = render(&mut app, 60, 16);
    assert!(screen.contains("Categories"), "{screen}");
    assert!(screen.contains("Tasks"), "{screen}");
    assert!(screen.contains("ship the re"), "{screen}");
}

#[test]
fn wide_help_uses_paired_columns_and_content_height() {
    let mut app = sample_app();
    app.mode = Mode::Help;
    let buffer = draw(&mut app, 120, 40);

    let (_, title_y) = find_cells(&buffer, " mach ");
    let (_, moving_y) = find_cells(&buffer, "MOVING AROUND");
    let (_, tasks_y) = find_cells(&buffer, "TASKS, CATEGORIES & LABELS");

    assert_eq!(moving_y, tasks_y, "wide help sections must share a row");
    assert!(title_y > 0, "wide help must not fill the terminal height");
}

#[test]
fn narrow_help_scrolls_to_every_section() {
    let mut app = sample_app();
    app.mode = Mode::Help;
    let top = render(&mut app, 80, 24);
    assert!(top.contains("MOVING AROUND"), "{top}");

    app.help_scroll = usize::MAX;
    let bottom = render(&mut app, 80, 24);
    assert!(bottom.contains("PREVIEW"), "{bottom}");
    assert!(bottom.contains("github.com/Q1CHENL/mach"), "{bottom}");
}

#[test]
fn hidden_geometry_is_cleared_on_an_undersized_frame() {
    let mut app = sample_app();
    let _ = render(&mut app, 100, 30);
    assert!(!app.areas.tasks.is_empty());
    assert!(!app.areas.command_bar.is_empty());

    let _ = render(&mut app, 20, 5);
    assert!(app.areas.tasks.is_empty());
    assert!(app.areas.sidebar.is_empty());
    assert!(app.areas.command_bar.is_empty());
    assert!(app.areas.slash_menu.is_empty());
}

#[test]
fn a_clipped_read_only_preview_says_that_more_content_exists() {
    let mut app = sample_app();
    app.tasks[0].description = (0..40)
        .map(|index| Block::text(&format!("preview line {index}")))
        .collect();
    app.invalidate_preview();
    app.rebuild_view();

    let screen = render(&mut app, 80, 24);
    assert!(screen.contains("↓ more · Enter to edit"), "{screen}");
}

#[test]
fn survives_every_sort_order() {
    for sort in mach::settings::SORTS {
        let mut app = sample_app();
        app.settings.sort = sort.to_string();
        app.rebuild_view();
        assert!(
            render(&mut app, 100, 30).contains("ship the release"),
            "sort {sort}"
        );
    }
}

// ------------------------------------------------------- picture geometry

/// A picture is letterboxed into its box, never cropped.
///
/// The size is worked out in cells and the terminal is then told to draw
/// `cells × cell_size` pixels there, so this has to come out to a rect that
/// fits — anything larger is clipped by the terminal, which reads as the
/// right and bottom of the picture being cut off.
#[test]
fn a_picture_is_letterboxed_into_its_box_never_cropped() {
    use image::DynamicImage;
    use ratatui::layout::{Rect, Size};
    use ratatui_image::picker::Picker;
    use ratatui_image::{FontSize, Resize};

    let cell = FontSize::new(8, 16);
    // Wider than any box below, so a crop would be obvious.
    let (iw, ih) = (1873u32, 1050u32);
    #[allow(deprecated, reason = "the only way to pin a cell size for a test")]
    let picker = Picker::from_fontsize(cell);
    let protocol = picker.new_resize_protocol(DynamicImage::new_rgba8(iw, ih));

    for box_size in [
        Size::new(128, 55),
        Size::new(120, 50),
        Size::new(200, 60),
        Size::new(60, 40),
        Size::new(10, 4),
    ] {
        let fitted = protocol.size_for(Resize::Scale(None), box_size);
        let area = Rect {
            x: 0,
            y: 0,
            width: box_size.width,
            height: box_size.height,
        };
        let picture = ui::centered(
            area,
            fitted.width.min(area.width),
            fitted.height.min(area.height),
        );

        assert!(
            picture.width <= area.width && picture.height <= area.height,
            "{box_size:?}: picture {picture:?} spills out of its box"
        );
        assert!(
            picture.right() <= area.right() && picture.bottom() <= area.bottom(),
            "{box_size:?}: picture {picture:?} would be clipped"
        );

        // Aspect ratio survives, to within the cell the size is rounded up to.
        let want_h = (box_size.width as f32 * cell.width as f32 * ih as f32)
            / (iw as f32 * cell.height as f32);
        let capped = want_h.min(box_size.height as f32);
        assert!(
            (picture.height as f32 - capped).abs() <= 1.5,
            "{box_size:?}: {} rows, expected about {capped:.1}",
            picture.height
        );
    }
}

#[test]
fn categories_scrollbar_track_uses_accent_when_focused() {
    let mut app = sample_app();
    app.focus = Focus::Sidebar;
    for i in 0..40 {
        app.categories.push(Category {
            id: format!("c-{i}"),
            name: format!("Cat{i}"),
            description: String::new(),
        });
    }
    app.rebuild_view();
    let buffer = draw(&mut app, 100, 20);
    let accent = app.theme().accent;
    // Right border column of the Categories panel (SIDEBAR_WIDTH = 26).
    let x = mach::ui::SIDEBAR_WIDTH - 1;
    let mut found_track = false;
    for y in 2..18 {
        let cell = &buffer[(x, y)];
        let sym = cell.symbol();
        if matches!(sym, "" | "" | "") {
            found_track = true;
            assert_eq!(
                cell.style().fg,
                Some(accent),
                "track at ({x},{y}) should be accent, got {:?} sym={sym:?}",
                cell.style().fg
            );
        }
        if sym == "" || sym == "" {
            assert_eq!(cell.style().fg, Some(accent), "thumb should be accent");
        }
    }
    assert!(
        found_track,
        "expected a scrollbar track on the categories border"
    );
}

#[test]
fn preview_can_sit_on_the_right() {
    let mut app = sample_app();
    app.settings.preview_position = "right".into();
    // Wide + tall enough for a side preview.
    let screen = render(&mut app, 120, 30);
    assert!(screen.contains("Task preview"), "{screen}");
    assert!(screen.contains("ship the release"), "{screen}");
    // Tasks and Task preview titles should appear on the same band (top),
    // not only with Task preview under a short task list.
    let lines: Vec<&str> = screen.lines().collect();
    let tasks_y = lines
        .iter()
        .position(|l| l.contains("Tasks"))
        .expect("Tasks");
    let preview_y = lines
        .iter()
        .position(|l| l.contains("Task preview"))
        .expect("Task preview");
    assert!(
        preview_y.abs_diff(tasks_y) <= 2,
        "preview should be beside tasks, not far below: tasks={tasks_y} preview={preview_y}\n{screen}"
    );
}