perga 0.1.5

A terminal Markdown browser with a persistent file tree, tabs, wiki-links and backlinks
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
//! Snapshot tests of rendered frames.
//!
//! Rendering is a pure function of state, so every one of these drives the app
//! through `Action`s and then renders to `TestBackend`. No terminal is
//! involved.

mod common;

use common::{app, app_with, frame, SIZES};
use perga::action::Action;
use perga::ui::sidebar::SidebarMode;
use perga::ui::welcome::{LogoTier, MEDIUM_MIN_WIDTH, MIN_LOGO_HEIGHT};

#[test]
fn welcome_screen_at_every_size() {
    for (width, height) in SIZES {
        let mut app = app(width, height);
        insta::assert_snapshot!(
            format!("welcome_{width}x{height}"),
            frame(&mut app, width, height)
        );
    }
}

#[test]
fn sidebar_hidden() {
    let mut app = app(120, 40);
    app.update(Action::ToggleSidebar);
    insta::assert_snapshot!(frame(&mut app, 120, 40));
}

#[test]
fn sidebar_focused() {
    let mut app = common::vault_app(120, 40);
    app.update(Action::FocusNext);
    insta::assert_snapshot!(frame(&mut app, 120, 40));
}

#[test]
fn each_sidebar_mode() {
    for mode in SidebarMode::ALL {
        let mut app = common::vault_app(120, 40);
        app.update(Action::SetSidebarMode(mode));
        insta::assert_snapshot!(format!("sidebar_mode_{mode}"), frame(&mut app, 120, 40));
    }
}

/// The tree with the filter line open, and with non-Markdown files shown.
#[test]
fn files_sidebar_states() {
    let mut app = common::vault_app(120, 40);
    app.update(Action::TreeFilter);
    for c in "auth".chars() {
        app.update(Action::TreeFilterEdit(
            perga::ui::overlay::prompt::TextEdit::Insert(c),
        ));
    }
    insta::assert_snapshot!("files_filtered", frame(&mut app, 120, 40));

    let mut app = common::vault_app(120, 40);
    app.update(Action::TreeToggleAllFiles);
    insta::assert_snapshot!("files_all_files", frame(&mut app, 120, 40));
}

/// Hint mode, with a label over every link in view.
#[test]
fn link_hint_mode() {
    let mut app = common::app_with("README.md", 120, 40);
    frame(&mut app, 120, 40);
    app.update(Action::HintMode);
    insta::assert_snapshot!(frame(&mut app, 120, 40));
}

/// The outline mode, and the find bar with matches highlighted behind it.
#[test]
fn outline_and_find() {
    let mut app = common::app_with("anchors.md", 120, 40);
    frame(&mut app, 120, 40);
    app.update(Action::SetSidebarMode(
        perga::ui::sidebar::SidebarMode::Outline,
    ));
    insta::assert_snapshot!("sidebar_outline_populated", frame(&mut app, 120, 40));

    app.update(Action::OpenFindInDocument);
    for c in "section".chars() {
        app.update(Action::FindEdit(
            perga::ui::overlay::prompt::TextEdit::Insert(c),
        ));
    }
    insta::assert_snapshot!("find_bar", frame(&mut app, 120, 40));
}

/// The links mode, with outgoing links and backlinks.
#[test]
fn sidebar_links_populated() {
    let mut app = common::app_with("docs/guides/Token Rotation.md", 120, 40);
    app.index_now();
    frame(&mut app, 120, 40);
    app.update(Action::SetSidebarMode(
        perga::ui::sidebar::SidebarMode::Links,
    ));
    insta::assert_snapshot!(frame(&mut app, 120, 40));
}

/// The disambiguation overlay a wiki-link with two candidates produces.
#[test]
fn disambiguation_overlay() {
    let mut app = common::app_with("wiki.md", 120, 40);
    app.index_now();
    frame(&mut app, 120, 40);

    let index = app
        .tab()
        .doc
        .as_ref()
        .unwrap()
        .links
        .iter()
        .position(|link| link.target == "Ambiguous")
        .expect("the fixture has an ambiguous wiki-link");
    app.update(Action::FollowHintedLink(index));

    insta::assert_snapshot!(frame(&mut app, 120, 40));
}

/// The search mode with results, the search prompt, and the quick switcher.
#[test]
fn search_and_switcher() {
    let mut app = common::vault_app(120, 40);
    app.search_now("token");
    // Pinned, so the snapshot does not change with the machine it ran on.
    app.search.elapsed = Some(std::time::Duration::from_millis(7));
    frame(&mut app, 120, 40);
    insta::assert_snapshot!("sidebar_search_populated", frame(&mut app, 120, 40));

    app.update(Action::OpenProjectSearch);
    insta::assert_snapshot!("search_prompt", frame(&mut app, 120, 40));

    app.update(Action::Escape);
    app.update(Action::OpenQuickSwitcher);
    for c in "auth".chars() {
        app.update(Action::SwitcherEdit(
            perga::ui::overlay::prompt::TextEdit::Insert(c),
        ));
    }
    insta::assert_snapshot!("quick_switcher", frame(&mut app, 120, 40));
}

/// Edit mode, and the confirmation that guards leaving it dirty.
#[test]
fn edit_mode_and_confirm() {
    let mut app = common::app_with("gfm.md", 120, 40);
    frame(&mut app, 120, 40);
    app.update(Action::EnterEditMode);
    insta::assert_snapshot!("edit_mode", frame(&mut app, 120, 40));

    app.update(Action::EditInput(crossterm::event::KeyEvent::new(
        crossterm::event::KeyCode::Char('x'),
        crossterm::event::KeyModifiers::NONE,
    )));
    app.update(Action::Escape);
    insta::assert_snapshot!("confirm_overlay", frame(&mut app, 120, 40));
}

/// The same frame under each of the three built-in themes.
///
/// Text rather than style, like every other snapshot here, so the diff is
/// readable; the styles themselves are asserted in `src/theme`. What this
/// catches is a theme that changes the *layout* — a wider marker, a longer
/// label — rather than only the colours.
#[test]
fn every_builtin_theme_renders() {
    for name in ["dark", "light", "high-contrast"] {
        let mut app = common::app_with("gfm.md", 120, 40);
        app.theme = perga::theme::Theme::builtin(name).expect("a built-in theme");
        insta::assert_snapshot!(format!("theme_{name}"), frame(&mut app, 120, 40));
    }
}

/// Section 19: every logo tier at its boundary width, under the theme with the
/// fewest colours to hide behind.
#[test]
fn the_logo_tiers_survive_the_high_contrast_theme() {
    for (label, width, height) in [
        ("large", 100u16, 40u16),
        ("medium", 48, 40),
        ("minimal", 30, 40),
        ("short", 100, 10),
    ] {
        let mut app = app(width, height);
        app.theme = perga::theme::Theme::builtin("high-contrast").expect("a built-in theme");
        app.update(Action::ToggleSidebar);

        let painted = frame(&mut app, width, height);
        for line in painted.lines() {
            assert!(
                line.chars().count() <= usize::from(width),
                "the {label} tier overflowed {width} columns: {line:?}"
            );
        }
    }
}

#[test]
fn help_overlay() {
    let mut app = app(120, 40);
    app.update(Action::ToggleHelp);
    insta::assert_snapshot!(frame(&mut app, 120, 40));
}

#[test]
fn terminal_too_small() {
    let mut app = app(30, 8);
    insta::assert_snapshot!(frame(&mut app, 30, 8));
}

/// Each logo tier and the short-viewport fallback, at their boundary widths.
///
/// The tiers exist because a banner wider than the viewport corrupts the frame,
/// so these are the snapshots that would catch it.
#[test]
fn welcome_logo_tiers() {
    for (label, width, height) in [
        ("large", 100u16, 40u16),
        ("medium", 48, 40),
        ("minimal", 30, 40),
        ("short", 100, 10),
    ] {
        let mut app = app(width, height);
        // Hide the sidebar so the viewport, not the split, sets the tier.
        app.update(Action::ToggleSidebar);
        insta::assert_snapshot!(
            format!("welcome_tier_{label}"),
            frame(&mut app, width, height)
        );
    }
}

#[test]
fn no_frame_overflows_its_terminal() {
    // Section 8.1: never panic on tiny terminals, and never draw outside them.
    for width in [30u16, 40, 41, 55, 56, 79, 80, 120, 200] {
        for height in [8u16, 10, 12, 19, 20, 24, 60] {
            let mut app = app(width, height);
            app.update(Action::ToggleHelp);

            for line in frame(&mut app, width, height).lines() {
                assert!(
                    line.chars().count() <= width as usize,
                    "{width}x{height}: a line is {} columns wide",
                    line.chars().count()
                );
            }
        }
    }
}

#[test]
fn resizing_from_large_to_tiny_and_back_is_clean() {
    // The M1 definition of done: resize from 200x60 down to 30x8 without a
    // panic and without a corrupt frame.
    let mut app = app(200, 60);
    let before = frame(&mut app, 200, 60);

    for (width, height) in [(200u16, 60u16), (120, 40), (80, 24), (40, 10), (30, 8)] {
        app.update(Action::Resize(width, height));
        let rendered = frame(&mut app, width, height);
        assert!(!rendered.is_empty());
    }

    app.update(Action::Resize(200, 60));
    assert_eq!(
        frame(&mut app, 200, 60),
        before,
        "the frame did not come back"
    );
}

#[test]
fn logo_tier_boundaries_match_the_rendered_frame() {
    assert_eq!(LogoTier::for_size(MEDIUM_MIN_WIDTH, 40), LogoTier::Medium);
    assert_eq!(
        LogoTier::for_size(MEDIUM_MIN_WIDTH - 1, 40),
        LogoTier::Minimal
    );
    assert_eq!(LogoTier::for_size(100, MIN_LOGO_HEIGHT - 1), LogoTier::None);
}

// -- The fixture corpus ---------------------------------------------------

/// Every document in the corpus, at every snapshot size.
///
/// This is the test that catches a rendering regression anywhere in the
/// pipeline: a wrapping change, a style change, a block that stops rendering.
#[test]
fn fixture_corpus_at_every_size() {
    for name in [
        "README.md",
        "gfm.md",
        "wide.md",
        "unicode.md",
        "broken-links.md",
        "docs/api/auth.md",
    ] {
        for (width, height) in SIZES {
            let mut app = app_with(name, width, height);
            let label = name.replace(['/', '.'], "_");
            insta::assert_snapshot!(
                format!("corpus_{label}_{width}x{height}"),
                frame(&mut app, width, height)
            );
        }
    }
}

#[test]
fn degenerate_documents_render_without_panicking() {
    for name in [
        "empty.md",
        "frontmatter-only.md",
        "no-trailing-newline.md",
        "crlf.md",
        "invalid-utf8.md",
        "spaces and #hash/awkward ışık #1.md",
    ] {
        for (width, height) in SIZES {
            let mut app = app_with(name, width, height);
            let rendered = frame(&mut app, width, height);
            assert!(!rendered.is_empty(), "{name} at {width}x{height}");
        }
    }
}

#[test]
fn a_non_utf8_document_says_so_and_refuses_editing() {
    let app = app_with("invalid-utf8.md", 120, 40);
    let doc = app.tab().doc.as_ref().expect("a document is open");

    assert!(!doc.is_editable());
    assert_eq!(
        app.status.message.as_ref().map(|(t, _)| t.as_str()),
        Some("Read-only: file is not valid UTF-8")
    );
}

#[test]
fn the_frontmatter_title_becomes_the_tab_label() {
    let app = app_with("README.md", 120, 40);
    assert_eq!(app.tab().label(), "Fixture Vault");
}

// -- Scrolling ------------------------------------------------------------

#[test]
fn scrolling_moves_the_window_and_stops_at_the_ends() {
    let mut app = app_with("gfm.md", 100, 30);
    frame(&mut app, 100, 30);
    assert_eq!(app.tab().scroll, 0);

    // Scrolling up at the top is a no-op rather than an error.
    app.update(Action::ScrollLineUp);
    assert_eq!(app.tab().scroll, 0);

    for _ in 0..5 {
        app.update(Action::ScrollLineDown);
    }
    assert_eq!(app.tab().scroll, 5);

    app.update(Action::ScrollTop);
    assert_eq!(app.tab().scroll, 0);

    app.update(Action::ScrollBottom);
    let bottom = app.tab().scroll;
    assert!(bottom > 0, "the document is taller than the viewport");

    // ...and scrolling down at the bottom stays there.
    app.update(Action::ScrollLineDown);
    assert_eq!(app.tab().scroll, bottom);
}

#[test]
fn a_page_scroll_moves_by_the_viewport_height() {
    // A document taller than several pages, so the move is not cut short by
    // the clamp that keeps a screenful in view at the bottom.
    let path = common::large_document(50_000);
    let mut app = app(100, 30);
    app.open(perga::doc::document::Document::load(&path).unwrap());
    frame(&mut app, 100, 30);

    let page = usize::from(app.viewport_inner().height);
    app.update(Action::ScrollPageDown);
    assert_eq!(app.tab().scroll, page);

    app.update(Action::ScrollHalfPageUp);
    assert_eq!(app.tab().scroll, page - page / 2);
}

#[test]
fn heading_motions_land_on_headings() {
    let mut app = app_with("gfm.md", 100, 30);
    frame(&mut app, 100, 30);

    app.update(Action::NextHeading);
    let first = app.tab().scroll;
    assert!(first > 0);

    app.update(Action::NextHeading);
    assert!(app.tab().scroll > first);

    app.update(Action::PrevHeading);
    assert_eq!(app.tab().scroll, first);
}

#[test]
fn a_wide_code_line_is_clipped_and_reachable_by_scrolling_right() {
    let mut app = app_with("wide.md", 80, 30);
    let before = frame(&mut app, 80, 30);
    assert!(before.contains('…'), "the wide line should be clipped");

    for _ in 0..20 {
        app.update(Action::ScrollRight);
    }
    assert_eq!(app.tab().hscroll, 20);

    let after = frame(&mut app, 80, 30);
    assert_ne!(before, after, "scrolling right changed nothing");

    // ...and it does not scroll past the left edge.
    for _ in 0..50 {
        app.update(Action::ScrollLeft);
    }
    assert_eq!(app.tab().hscroll, 0);
}

#[test]
fn scrolling_never_draws_outside_the_viewport() {
    let mut app = app_with("wide.md", 80, 24);

    for _ in 0..30 {
        for line in frame(&mut app, 80, 24).lines() {
            assert!(line.chars().count() <= 80, "{line:?}");
        }
        app.update(Action::ScrollLineDown);
        app.update(Action::ScrollRight);
    }
}

// -- Large documents ------------------------------------------------------

#[test]
fn a_large_document_paints_before_it_is_fully_measured() {
    // Section 9.2: only visible blocks render. The assertion is on ordering,
    // not on wall-clock time, which is unreliable on a shared runner.
    let path = common::large_document(50_000);
    let mut app = app(120, 40);
    app.set_vault_root(common::vault());
    app.open(perga::doc::document::Document::load(&path).unwrap());

    let rendered = frame(&mut app, 120, 40);
    assert!(rendered.contains("A large document"));

    // The total is still unknown, so the title bar shows no position yet.
    assert_eq!(app.scroll_position(), None);
}

#[test]
fn a_large_document_can_be_measured_to_the_end() {
    let path = common::large_document(50_000);
    let mut app = app(120, 40);
    app.open(perga::doc::document::Document::load(&path).unwrap());

    frame(&mut app, 120, 40);
    // Measurement is chunked, so reaching the end takes several passes.
    for _ in 0..500 {
        app.update(Action::ScrollBottom);
        if app.scroll_position().is_some() {
            break;
        }
    }

    let (current, total) = app.scroll_position().expect("the document is measured");
    assert!(total > 50_000, "{total}");
    assert!(current <= total);
}

/// Section 19: `perga FILE | cat` produces clean ANSI with no TUI control
/// sequences.
///
/// Run against the built binary rather than the library: what matters is that
/// the *process* does not touch the alternate screen when stdout is a pipe.
#[test]
fn piped_output_carries_no_tui_control_sequences() {
    let exe = env!("CARGO_BIN_EXE_perga");
    let path = common::vault().join("gfm.md");

    let out = std::process::Command::new(exe)
        .arg(&path)
        .output()
        .expect("the binary runs");

    assert!(out.status.success(), "{:?}", out.status);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(!text.is_empty());

    for (sequence, what) in [
        ("\x1b[?1049h", "enter the alternate screen"),
        ("\x1b[?1049l", "leave the alternate screen"),
        ("\x1b[?1000", "mouse tracking"),
        ("\x1b[?2004", "bracketed paste"),
        ("\x1b[?25l", "hide the cursor"),
        ("\x1b[2J", "clear the screen"),
    ] {
        assert!(!text.contains(sequence), "piped output tried to {what}");
    }

    // Styling is expected and wanted; it is the control sequences that are not.
    assert!(text.contains('\x1b'), "piped output should still be styled");
}

/// ...and `NO_COLOR` takes even that away.
#[test]
fn no_color_strips_the_styling_from_piped_output() {
    let exe = env!("CARGO_BIN_EXE_perga");
    let path = common::vault().join("gfm.md");

    let out = std::process::Command::new(exe)
        .arg(&path)
        .env("NO_COLOR", "1")
        .output()
        .expect("the binary runs");

    let text = String::from_utf8_lossy(&out.stdout);
    assert!(!text.is_empty());
    assert!(!text.contains('\x1b'), "NO_COLOR left an escape behind");
}

/// Section 9.12: the theme applies in print mode. It did not — print mode
/// built its own `dark` and never read the configuration at all, so
/// `--theme`, `theme.name`, `general.wrap` and every `[ui]` key were ignored
/// by `--print`.
#[test]
fn print_mode_honours_the_theme_and_the_configuration() {
    let exe = env!("CARGO_BIN_EXE_perga");
    let path = common::vault().join("gfm.md");

    let colours = |args: &[&str]| -> String {
        let out = std::process::Command::new(exe)
            .args(args)
            .arg(&path)
            .output()
            .expect("the binary runs");
        String::from_utf8_lossy(&out.stdout).into_owned()
    };

    let dark = colours(&["--print", "--theme", "dark"]);
    let light = colours(&["--print", "--theme", "light"]);

    assert!(!dark.is_empty() && !light.is_empty());
    assert_ne!(dark, light, "`--theme` did not reach print mode");
}

#[test]
fn print_mode_honours_show_heading_markers() {
    let exe = env!("CARGO_BIN_EXE_perga");
    let dir = std::env::temp_dir().join(format!("perga-print-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();

    let config = dir.join("config.toml");
    std::fs::write(&config, "[ui]\nshow_heading_markers = false\n").unwrap();

    let doc = dir.join("h.md");
    std::fs::write(&doc, "# Heading\n\nbody\n").unwrap();

    let run = |args: &[&str]| -> String {
        let out = std::process::Command::new(exe)
            .args(args)
            .arg(&doc)
            .env("NO_COLOR", "1")
            .output()
            .expect("the binary runs");
        String::from_utf8_lossy(&out.stdout).into_owned()
    };

    assert!(run(&["--print"]).contains("# Heading"));
    assert!(!run(&["--print", "--config", config.to_str().unwrap()]).contains('#'));
}

/// A directory in print mode is a usage error, not a guess at a file.
#[test]
fn a_directory_piped_is_a_usage_error() {
    let exe = env!("CARGO_BIN_EXE_perga");

    let out = std::process::Command::new(exe)
        .arg(common::vault())
        .output()
        .expect("the binary runs");

    assert_eq!(out.status.code(), Some(2));
    assert!(String::from_utf8_lossy(&out.stderr).contains("directory"));
}

/// A reader quitting `less` early, or `| head`, closes the pipe mid-write.
///
/// Every well-behaved Unix tool treats that as the end of the job. perga used
/// to print `writing to stdout: Broken pipe` and exit 1, which is exactly what
/// `perga README.md | less -R` produces the moment the reader presses `q`.
#[test]
fn a_closed_pipe_is_not_an_error() {
    use std::io::Read as _;
    use std::process::{Command, Stdio};

    let exe = env!("CARGO_BIN_EXE_perga");
    let path = common::vault().join("gfm.md");

    let mut child = Command::new(exe)
        .arg(&path)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("the binary runs");

    // Read a little and drop the pipe, the way `head` does.
    let mut stdout = child.stdout.take().expect("a pipe");
    let mut sip = [0u8; 64];
    let _ = stdout.read(&mut sip);
    drop(stdout);

    let out = child.wait_with_output().expect("the child exits");
    let stderr = String::from_utf8_lossy(&out.stderr);

    assert!(
        stderr.is_empty(),
        "a closed pipe should be silent, got: {stderr}"
    );
    assert_eq!(out.status.code(), Some(0), "and should exit cleanly");
}