ferritin 0.8.0

Human-friendly CLI for browsing Rust 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
use super::*;
use crate::{
    logging::StatusLogBackend,
    styled_string::{Document, DocumentNode, Span, SpanStyle},
};
use crossbeam_channel::unbounded as channel;
use ratatui::{Terminal, backend::TestBackend};

/// Helper to create a minimal test state
fn create_test_state<'a>() -> InteractiveState<'a> {
    let (cmd_tx, _cmd_rx) = channel();
    let (_resp_tx, resp_rx) = channel();

    let document = Document {
        nodes: vec![DocumentNode::paragraph(vec![Span {
            text: "Test document".into(),
            style: SpanStyle::Plain,
            action: None,
        }])],
    };
    let render_context = RenderContext::new();
    let theme = InteractiveTheme::from_render_context(&render_context);
    let (_, log_reader) = StatusLogBackend::new(100);

    InteractiveState::new(
        document,
        None,
        cmd_tx,
        resp_rx,
        render_context,
        theme,
        log_reader,
    )
}

#[test]
fn test_initial_state_is_normal_mode() {
    let state = create_test_state();
    assert!(matches!(state.ui_mode, UiMode::Normal));
}

#[test]
fn test_mode_transitions_via_state() {
    let mut state = create_test_state();

    // Start in Normal mode
    assert!(matches!(state.ui_mode, UiMode::Normal));

    // Transition to Help
    state.ui_mode = UiMode::Help;
    assert!(matches!(state.ui_mode, UiMode::Help));

    // Back to Normal
    state.ui_mode = UiMode::Normal;
    assert!(matches!(state.ui_mode, UiMode::Normal));

    // Transition to GoTo
    state.ui_mode = UiMode::Input(InputMode::GoTo {
        buffer: String::new(),
    });
    assert!(matches!(
        state.ui_mode,
        UiMode::Input(InputMode::GoTo { .. })
    ));

    // Transition to Search
    state.ui_mode = UiMode::Input(InputMode::Search {
        buffer: String::new(),
        all_crates: false,
    });
    assert!(matches!(
        state.ui_mode,
        UiMode::Input(InputMode::Search {
            all_crates: false,
            ..
        })
    ));
}

#[test]
fn test_input_mode_buffer_manipulation() {
    let mut state = create_test_state();

    // Enter GoTo mode
    state.ui_mode = UiMode::Input(InputMode::GoTo {
        buffer: String::from("test"),
    });

    // Modify buffer
    if let UiMode::Input(InputMode::GoTo { buffer }) = &mut state.ui_mode {
        buffer.push_str("_path");
        assert_eq!(buffer, "test_path");
    }

    // Enter Search mode
    state.ui_mode = UiMode::Input(InputMode::Search {
        buffer: String::from("query"),
        all_crates: false,
    });

    // Toggle all_crates
    if let UiMode::Input(InputMode::Search { buffer, all_crates }) = &mut state.ui_mode {
        assert_eq!(buffer, "query");
        assert!(!*all_crates);
        *all_crates = true;
        assert!(*all_crates);
    }
}

#[test]
fn test_history_navigation() {
    let mut state = create_test_state();

    // Initially no history, can't go back or forward
    assert!(!state.document.history.can_go_back());
    assert!(!state.document.history.can_go_forward());

    // Add first entry
    state.document.history.push(HistoryEntry::List {
        default_crate: None,
    });
    // Still can't go back (only one entry, at index 0)
    assert!(!state.document.history.can_go_back());
    assert!(!state.document.history.can_go_forward());

    // Add second entry
    state.document.history.push(HistoryEntry::Search {
        query: "test".to_string(),
        crate_name: None,
    });
    // Now we can go back (two entries, at index 1)
    assert!(state.document.history.can_go_back());
    assert!(!state.document.history.can_go_forward());

    // Go back
    state.document.history.go_back();
    // Now we can go forward but not back (at index 0)
    assert!(!state.document.history.can_go_back());
    assert!(state.document.history.can_go_forward());

    // Go forward
    state.document.history.go_forward();
    // Back at the end (index 1)
    assert!(state.document.history.can_go_back());
    assert!(!state.document.history.can_go_forward());
}

#[test]
fn test_rendering_to_test_backend() {
    let mut state = create_test_state();
    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();

    // Render the state
    terminal.draw(|frame| state.render_frame(frame)).unwrap();

    // Get the buffer and verify some content
    let buffer = terminal.backend().buffer();

    // The test document has "Test document" text, should appear in the buffer
    let buffer_str = buffer
        .content()
        .iter()
        .map(|cell| cell.symbol())
        .collect::<String>();
    assert!(
        buffer_str.contains("Test document"),
        "Rendered buffer should contain document text"
    );
}

#[test]
fn test_brief_truncation_with_code_block() {
    use crate::styled_string::TruncationLevel;

    let (cmd_tx, _cmd_rx) = channel();
    let (_resp_tx, resp_rx) = channel();

    // Create a document with a Brief truncated block containing text and a code block
    let document = Document {
        nodes: vec![DocumentNode::TruncatedBlock {
            level: TruncationLevel::Brief,
            nodes: vec![
                DocumentNode::paragraph(vec![Span::plain("First paragraph with some text.")]),
                DocumentNode::paragraph(vec![Span::plain("Second paragraph with more text.")]),
                DocumentNode::CodeBlock {
                    lang: Some("rust".into()),
                    code: "fn example() {\n    println!(\"Hello\");\n    let x = 42;\n    let y = 100;\n    let z = x + y;\n}\n".into(),
                },
                DocumentNode::paragraph(vec![Span::plain("Third paragraph after code.")]),
            ],
        }],
    };

    let render_context = RenderContext::new();
    let theme = InteractiveTheme::from_render_context(&render_context);
    let (_, log_reader) = StatusLogBackend::new(100);

    let mut state = InteractiveState::new(
        document,
        None,
        cmd_tx,
        resp_rx,
        render_context,
        theme,
        log_reader,
    );
    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();

    // Render the state
    terminal.draw(|frame| state.render_frame(frame)).unwrap();

    // Get the buffer and inspect what was rendered
    let buffer = terminal.backend().buffer();

    // Convert buffer to line-by-line representation for easier debugging
    let mut lines = Vec::new();
    for y in 0..24 {
        let line: String = (0..80)
            .map(|x| buffer.cell((x, y)).unwrap().symbol())
            .collect();
        lines.push(line);
    }

    // Print the rendered output for debugging
    println!("\n=== Rendered output ===");
    for (i, line) in lines.iter().enumerate() {
        println!("{:2}: |{}|", i, line.trim_end());
    }
    println!("=== End output ===\n");

    // Check for issues:
    // 1. Count code block borders
    let top_borders = lines.iter().filter(|l| l.contains("â•­")).count();
    let bottom_borders = lines.iter().filter(|l| l.contains("╯")).count();

    println!("Top borders (â•­): {}", top_borders);
    println!("Bottom borders (╯): {}", bottom_borders);

    // Look for the truncated block's closing border
    let truncation_indicators = lines.iter().filter(|l| l.contains("╰─[...]")).count();
    println!("Truncation indicators (╰─[...]): {}", truncation_indicators);

    // If a code block is started but not finished, we'd see an imbalance
    // This test documents the current behavior - it may show the bug
}

#[test]
fn test_brief_with_short_code_block() {
    use crate::styled_string::TruncationLevel;

    let (cmd_tx, _cmd_rx) = channel();
    let (_resp_tx, resp_rx) = channel();

    // Create a simpler case: just one line of text and a small code block
    let document = Document {
        nodes: vec![DocumentNode::TruncatedBlock {
            level: TruncationLevel::Brief,
            nodes: vec![
                DocumentNode::paragraph(vec![Span::plain("Some text before code.")]),
                DocumentNode::CodeBlock {
                    lang: Some("rust".into()),
                    code: "let x = 42;".into(),
                },
            ],
        }],
    };

    let render_context = RenderContext::new();
    let theme = InteractiveTheme::from_render_context(&render_context);
    let (_, log_reader) = StatusLogBackend::new(100);

    let mut state = InteractiveState::new(
        document,
        None,
        cmd_tx,
        resp_rx,
        render_context,
        theme,
        log_reader,
    );
    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|frame| state.render_frame(frame)).unwrap();

    let buffer = terminal.backend().buffer();
    let mut lines = Vec::new();
    for y in 0..10 {
        let line: String = (0..80)
            .map(|x| buffer.cell((x, y)).unwrap().symbol())
            .collect();
        lines.push(line);
    }

    println!("\n=== Short code block test ===");
    for (i, line) in lines.iter().enumerate() {
        println!("{:2}: |{}|", i, line.trim_end());
    }

    let top_borders = lines.iter().filter(|l| l.contains("â•­")).count();
    let bottom_borders = lines.iter().filter(|l| l.contains("╯")).count();

    println!("Top code block borders: {}", top_borders);
    println!("Bottom code block borders: {}", bottom_borders);

    // If code block renders, borders should match
    if top_borders > 0 || bottom_borders > 0 {
        assert_eq!(
            top_borders, bottom_borders,
            "Code block should have matching top and bottom borders, or not render at all"
        );
    }
}

#[test]
fn test_truncated_block_border_on_wrapped_lines() {
    use crate::styled_string::TruncationLevel;

    let (cmd_tx, _cmd_rx) = channel();
    let (_resp_tx, resp_rx) = channel();

    // Create a document with a Brief truncated block containing a very long line that will wrap
    // Brief mode has an 8-line limit, so we need enough content to exceed that and trigger truncation
    let long_text = "This is a very long line of text that should wrap across multiple lines when rendered in a narrow terminal window and we want to make sure the border appears on all wrapped lines not just the last one.";

    let document = Document {
        nodes: vec![DocumentNode::TruncatedBlock {
            level: TruncationLevel::Brief,
            nodes: vec![
                DocumentNode::paragraph(vec![Span::plain(long_text)]),
                DocumentNode::paragraph(vec![Span::plain(
                    "Second paragraph with additional content.",
                )]),
                DocumentNode::paragraph(vec![Span::plain(
                    "Third paragraph to ensure we exceed the 8-line Brief limit.",
                )]),
                DocumentNode::paragraph(vec![Span::plain(
                    "Fourth paragraph - this should be truncated.",
                )]),
                DocumentNode::paragraph(vec![Span::plain("Fifth paragraph - also truncated.")]),
            ],
        }],
    };

    let render_context = RenderContext::new();
    let theme = InteractiveTheme::from_render_context(&render_context);
    let (_, log_reader) = StatusLogBackend::new(100);

    let mut state = InteractiveState::new(
        document,
        None,
        cmd_tx,
        resp_rx,
        render_context,
        theme,
        log_reader,
    );
    let backend = TestBackend::new(60, 24); // Narrow width to force wrapping
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|frame| state.render_frame(frame)).unwrap();

    let buffer = terminal.backend().buffer();
    let mut lines = Vec::new();
    for y in 0..10 {
        let line: String = (0..60)
            .map(|x| buffer.cell((x, y)).unwrap().symbol())
            .collect();
        lines.push(line);
    }

    println!("\n=== Wrapped line border test ===");
    for (i, line) in lines.iter().enumerate() {
        println!("{:2}: |{}|", i, line.trim_end());
    }

    // Count how many lines have the border character │
    let border_lines: Vec<usize> = lines
        .iter()
        .enumerate()
        .filter(|(_, line)| line.contains('│'))
        .map(|(i, _)| i)
        .collect();

    println!("Lines with borders: {:?}", border_lines);

    // The border should appear on all lines with content, including wrapped lines
    // With a 60-char width, the long text should wrap to at least 3 lines
    assert!(
        border_lines.len() >= 3,
        "Expected borders on at least 3 wrapped lines, found on {} lines",
        border_lines.len()
    );
}

#[test]
#[ignore] // Run with --ignored to update snapshot
fn test_std_module_spacing() {
    use crate::styled_string::{DocumentNode, ListItem, Span};

    let (cmd_tx, _cmd_rx) = channel();
    let (_resp_tx, resp_rx) = channel();

    // Simulate the structure from std's markdown: paragraph, list, paragraph, list
    let document = Document {
        nodes: vec![
            // First paragraph
            DocumentNode::paragraph(vec![Span::plain(
                "The standard library exposes three common ways:",
            )]),
            // First list
            DocumentNode::List {
                items: vec![
                    ListItem::new(vec![DocumentNode::paragraph(vec![Span::plain(
                        "Vec<T> - A heap-allocated vector",
                    )])]),
                    ListItem::new(vec![DocumentNode::paragraph(vec![Span::plain(
                        "[T; N] - An inline array",
                    )])]),
                    ListItem::new(vec![DocumentNode::paragraph(vec![Span::plain(
                        "[T] - A dynamically sized slice",
                    )])]),
                ],
            },
            // Second paragraph
            DocumentNode::paragraph(vec![Span::plain(
                "Slices can only be handled through pointers:",
            )]),
            // Second list
            DocumentNode::List {
                items: vec![
                    ListItem::new(vec![DocumentNode::paragraph(vec![Span::plain(
                        "&[T] - shared slice",
                    )])]),
                    ListItem::new(vec![DocumentNode::paragraph(vec![Span::plain(
                        "&mut [T] - mutable slice",
                    )])]),
                    ListItem::new(vec![DocumentNode::paragraph(vec![Span::plain(
                        "Box<[T]> - owned slice",
                    )])]),
                ],
            },
            // Final paragraph
            DocumentNode::paragraph(vec![Span::plain(
                "str, a UTF-8 string slice, is a primitive type.",
            )]),
        ],
    };

    let render_context = RenderContext::new();
    let theme = InteractiveTheme::from_render_context(&render_context);
    let (_, log_reader) = StatusLogBackend::new(100);

    let mut state = InteractiveState::new(
        document,
        None,
        cmd_tx,
        resp_rx,
        render_context,
        theme,
        log_reader,
    );
    let backend = TestBackend::new(80, 30);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|frame| state.render_frame(frame)).unwrap();

    let buffer = terminal.backend().buffer();
    let mut output = String::new();
    for y in 0..25 {
        let line: String = (0..80)
            .map(|x| buffer.cell((x, y)).unwrap().symbol())
            .collect();
        output.push_str(&format!("{}\n", line.trim_end()));
    }

    println!("\n=== Current std-like spacing ===");
    println!("{}", output);
    println!("=== End ===\n");

    // TODO: Once we fix spacing, add assertions about blank line counts
}

#[test]
#[ignore] // Run with --ignored to update snapshot
fn test_code_block_spacing() {
    let (cmd_tx, _cmd_rx) = channel();
    let (_resp_tx, resp_rx) = channel();

    // Simulate paragraph followed by code block (like alloc module docs)
    let document = Document {
        nodes: vec![
            DocumentNode::paragraph(vec![Span::plain("Here's an example:")]),
            DocumentNode::CodeBlock {
                lang: Some("rust".into()),
                code: "let x = vec![1, 2, 3];".into(),
            },
            DocumentNode::paragraph(vec![Span::plain("More content after the code block.")]),
        ],
    };

    let render_context = RenderContext::new();
    let theme = InteractiveTheme::from_render_context(&render_context);
    let (_, log_reader) = StatusLogBackend::new(100);

    let mut state = InteractiveState::new(
        document,
        None,
        cmd_tx,
        resp_rx,
        render_context,
        theme,
        log_reader,
    );
    let backend = TestBackend::new(60, 20);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|frame| state.render_frame(frame)).unwrap();

    let buffer = terminal.backend().buffer();
    let mut output = String::new();
    for y in 0..15 {
        let line: String = (0..60)
            .map(|x| buffer.cell((x, y)).unwrap().symbol())
            .collect();
        output.push_str(&format!("{}\n", line.trim_end()));
    }

    println!("\n=== Current code block spacing ===");
    println!("{}", output);
    println!("=== End ===\n");

    // Count blank lines
    let blank_lines_before_code = output
        .lines()
        .skip(1) // Skip "Here's an example:"
        .take_while(|l| l.trim().is_empty())
        .count();

    println!("Blank lines before code block: {}", blank_lines_before_code);
    println!("Expected: 1 blank line between paragraph and code block");

    // TODO: Once we fix spacing, assert blank_lines_before_code == 1
}