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
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
use ferritin_common::DocRef;
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use rustdoc_types::Item;
use std::borrow::Cow;

/// Interactive action that can be attached to a span
#[derive(Debug, Clone)]
pub enum TuiAction<'a> {
    /// Navigate to an already-loaded item (zero-cost since DocRef is Copy)
    Navigate {
        doc_ref: DocRef<'a, Item>,
        /// Optional docs.rs URL for renderers that need it (e.g., TTY mode OSC8 links)
        url: Option<Cow<'a, str>>,
    },
    /// Navigate to an item by path (resolves lazily)
    /// Uses Cow to borrow from JSON when possible, avoiding allocation
    NavigateToPath {
        path: Cow<'a, str>,
        /// Optional docs.rs URL for renderers that need it (e.g., TTY mode OSC8 links)
        url: Option<Cow<'a, str>>,
    },
    /// Expand a truncated block (identified by index path into document tree)
    ExpandBlock(NodePath),
    /// Open an external URL in browser
    OpenUrl(Cow<'a, str>),
    /// Select a theme (interactive mode only)
    SelectTheme(Cow<'a, str>),
}

impl<'a> TuiAction<'a> {
    /// Get or generate the URL for this action.
    /// URLs are generated lazily for Navigate/NavigateToPath actions.
    /// Returns Cow to avoid allocations when URL is already borrowed.
    pub fn url(&self) -> Option<Cow<'a, str>> {
        match self {
            TuiAction::Navigate { doc_ref, url } => {
                url.clone().or_else(|| {
                    // Generate URL from DocRef
                    Some(Cow::Owned(crate::generate_docsrs_url::generate_docsrs_url(
                        *doc_ref,
                    )))
                })
            }
            TuiAction::NavigateToPath { path, url } => {
                url.clone().or_else(|| {
                    // Generate a heuristic URL from the path
                    Some(Cow::Owned(generate_url_from_path(path)))
                })
            }
            TuiAction::ExpandBlock(_) => None,
            TuiAction::OpenUrl(cow) => Some(cow.clone()),
            TuiAction::SelectTheme(_) => None,
        }
    }
}

/// Generate a heuristic docs.rs URL from a path string
/// Since we don't know the item kind, we generate a search URL
fn generate_url_from_path(path: &str) -> String {
    let parts: Vec<&str> = path.split("::").collect();
    if parts.is_empty() {
        return String::new();
    }

    let crate_name = parts[0];
    let is_std = matches!(crate_name, "std" | "core" | "alloc" | "proc_macro");

    let base = if is_std {
        "https://doc.rust-lang.org/nightly".to_string()
    } else {
        format!("https://docs.rs/{}/latest", crate_name)
    };

    if parts.len() == 1 {
        // Just the crate name
        return format!("{}/{}/index.html", base, crate_name);
    }

    // Generate search URL for the full path
    let module_path = if parts.len() > 2 {
        parts[1..parts.len() - 1].join("/")
    } else {
        String::new()
    };

    let index_path = if module_path.is_empty() {
        format!("{}/{}/index.html", base, crate_name)
    } else {
        format!("{}/{}/{}/index.html", base, crate_name, module_path)
    };

    // Add search query for the full path
    format!(
        "{}?search={}",
        index_path,
        utf8_percent_encode(path, NON_ALPHANUMERIC)
    )
}

/// Path to a node in the document tree using indices
/// Example: [2, 3, 1] means nodes[2].children[3].children[1]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodePath {
    indices: [u16; 8], // 8 levels deep should be enough
    len: u8,
}

impl NodePath {
    pub fn new() -> Self {
        Self {
            indices: [0; 8],
            len: 0,
        }
    }

    pub fn push(&mut self, index: usize) {
        if (self.len as usize) < self.indices.len() {
            self.indices[self.len as usize] = index as u16;
            self.len += 1;
        }
    }

    pub fn indices(&self) -> &[u16] {
        &self.indices[..self.len as usize]
    }
}

/// Target for an intra-doc link
#[derive(Debug, Clone)]
pub enum LinkTarget<'a> {
    /// A resolved item reference (for same-crate items we already loaded)
    Resolved(DocRef<'a, Item>),
    /// An unresolved path string (for external items or fallback)
    Path(Cow<'a, str>),
}

/// A semantic content tree for Rust documentation
#[derive(Debug, Clone)]
pub struct Document<'a> {
    pub nodes: Vec<DocumentNode<'a>>,
}

/// Condition for when to show content (used by Conditional node)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShowWhen {
    /// Always show (default)
    Always,
    /// Only in interactive mode
    Interactive,
    /// Only in non-interactive mode
    NonInteractive,
}

/// A node in the documentation tree
#[derive(Debug, Clone)]
pub enum DocumentNode<'a> {
    /// Block-level paragraph
    Paragraph { spans: Vec<Span<'a>> },

    /// Block-level heading
    Heading {
        level: HeadingLevel,
        spans: Vec<Span<'a>>,
    },

    /// Structural section with optional title
    Section {
        title: Option<Vec<Span<'a>>>,
        nodes: Vec<DocumentNode<'a>>,
    },

    /// List of items
    List { items: Vec<ListItem<'a>> },

    /// Code block with syntax highlighting (from markdown fenced blocks)
    CodeBlock {
        lang: Option<Cow<'a, str>>,
        code: Cow<'a, str>,
    },

    /// Generated code with pre-styled spans (for signatures, etc.)
    GeneratedCode { spans: Vec<Span<'a>> },

    /// Horizontal rule/divider
    HorizontalRule,

    /// Block quote
    BlockQuote { nodes: Vec<DocumentNode<'a>> },

    /// Table
    Table {
        header: Option<Vec<TableCell<'a>>>,
        rows: Vec<Vec<TableCell<'a>>>,
    },

    /// Truncated documentation block
    /// Renderers decide how to truncate based on the level hint
    TruncatedBlock {
        nodes: Vec<DocumentNode<'a>>,
        level: TruncationLevel,
    },

    /// Conditionally shown content based on render context
    /// Formatters can use this to include content that only appears in certain modes
    Conditional {
        show_when: ShowWhen,
        nodes: Vec<DocumentNode<'a>>,
    },
}

/// A single cell in a table
#[derive(Debug, Clone)]
pub struct TableCell<'a> {
    pub spans: Vec<Span<'a>>,
}

/// A single item in a list
#[derive(Debug, Clone)]
pub struct ListItem<'a> {
    pub content: Vec<DocumentNode<'a>>,
}

/// Heading level for semantic structure
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeadingLevel {
    Title,   // Top-level item name: "Item: Vec"
    Section, // Section header: "Fields:", "Methods:"
}

/// Truncation level hint for renderers
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TruncationLevel {
    /// Single-line summary (for listings)
    SingleLine,
    /// Brief paragraph (for secondary items like methods/fields)
    Brief,
    /// Full documentation (for main requested item)
    Full,
}

/// A styled text span with semantic meaning
#[derive(Debug, Clone)]
pub struct Span<'a> {
    pub text: Cow<'a, str>,
    pub style: SpanStyle,
    pub action: Option<TuiAction<'a>>,
}

impl<'a> Span<'a> {
    pub fn url(&self) -> Option<Cow<'a, str>> {
        self.action.as_ref()?.url()
    }
}

/// Semantic styling categories for Rust code elements
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SpanStyle {
    // Rust code semantic elements
    Keyword,      // struct, enum, pub, fn, const, etc.
    TypeName,     // MyStruct, Vec, String, etc.
    FunctionName, // my_function, new, etc.
    FieldName,    // field names in structs
    Lifetime,     // 'a, 'static, etc.
    Generic,      // T, U, generic parameters

    // Structural elements
    Plain,       // unstyled text, whitespace
    Punctuation, // :, {, }, (, ), etc.
    Operator,    // &, *, ->, etc.
    Comment,     // // comments in code output

    // Code content
    InlineRustCode, // Inline code expressions (const values, etc.) - unparsed Rust code
    InlineCode,     // Generic inline code from markdown backticks

    // Markdown semantic styles
    Strong,        // **bold** - semantic emphasis
    Emphasis,      // *italic* - semantic emphasis
    Strikethrough, // ~~strikethrough~~ - from GFM
}

impl<'a> Span<'a> {
    // Rust code element constructors
    pub fn keyword(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Keyword,
            action: None,
        }
    }

    pub fn type_name(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::TypeName,
            action: None,
        }
    }

    pub fn function_name(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::FunctionName,
            action: None,
        }
    }

    pub fn field_name(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::FieldName,
            action: None,
        }
    }

    pub fn lifetime(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Lifetime,
            action: None,
        }
    }

    pub fn generic(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Generic,
            action: None,
        }
    }

    // Structural element constructors
    pub fn plain(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Plain,
            action: None,
        }
    }

    pub fn punctuation(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Punctuation,
            action: None,
        }
    }

    pub fn operator(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Operator,
            action: None,
        }
    }

    pub fn comment(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Comment,
            action: None,
        }
    }

    pub fn inline_rust_code(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::InlineRustCode,
            action: None,
        }
    }

    pub fn inline_code(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::InlineCode,
            action: None,
        }
    }

    pub fn strong(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Strong,
            action: None,
        }
    }

    pub fn emphasis(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Emphasis,
            action: None,
        }
    }

    pub fn strikethrough(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            style: SpanStyle::Strikethrough,
            action: None,
        }
    }

    /// Chainable method to attach an action to this span
    pub fn with_action(mut self, action: TuiAction<'a>) -> Self {
        self.action = Some(action);
        self
    }

    /// Attach a navigation action for an already-loaded item
    pub fn with_target(mut self, target: Option<DocRef<'a, Item>>) -> Self {
        if let Some(target) = target {
            self.action = Some(TuiAction::Navigate {
                doc_ref: target,
                url: None,
            });
        }
        self
    }

    /// Attach a navigation action for an item path (resolved lazily)
    pub fn with_path(mut self, path: impl Into<Cow<'a, str>>) -> Self {
        self.action = Some(TuiAction::NavigateToPath {
            path: path.into(),
            url: None,
        });
        self
    }
}

impl<'a> Document<'a> {
    pub fn new() -> Self {
        Self { nodes: Vec::new() }
    }

    pub fn with_nodes(nodes: Vec<DocumentNode<'a>>) -> Self {
        Self { nodes }
    }
}

impl<'a> Default for Document<'a> {
    fn default() -> Self {
        Self::new()
    }
}

// Into<Document> conversions for ergonomic render() calls
impl<'a> From<Vec<DocumentNode<'a>>> for Document<'a> {
    fn from(nodes: Vec<DocumentNode<'a>>) -> Self {
        Self { nodes }
    }
}

impl<'a, 'b> From<&'b Document<'a>> for Document<'a> {
    fn from(doc: &'b Document<'a>) -> Self {
        doc.clone()
    }
}

impl<'a> ListItem<'a> {
    pub fn new(content: Vec<DocumentNode<'a>>) -> Self {
        Self { content }
    }
}

impl<'a> DocumentNode<'a> {
    /// Convenience constructor for a paragraph
    pub fn paragraph(spans: Vec<Span<'a>>) -> Self {
        DocumentNode::Paragraph { spans }
    }

    /// Convenience constructor for a heading
    pub fn heading(level: HeadingLevel, spans: Vec<Span<'a>>) -> Self {
        DocumentNode::Heading { level, spans }
    }

    /// Convenience constructor for a section with title
    pub fn section(title: Vec<Span<'a>>, nodes: Vec<DocumentNode<'a>>) -> Self {
        DocumentNode::Section {
            title: Some(title),
            nodes,
        }
    }

    /// Convenience constructor for a section without title
    pub fn section_untitled(nodes: Vec<DocumentNode<'a>>) -> Self {
        DocumentNode::Section { title: None, nodes }
    }

    /// Convenience constructor for a list
    pub fn list(items: Vec<ListItem<'a>>) -> Self {
        DocumentNode::List { items }
    }

    /// Convenience constructor for a code block
    pub fn code_block(
        lang: Option<impl Into<Cow<'a, str>>>,
        code: impl Into<Cow<'a, str>>,
    ) -> Self {
        DocumentNode::CodeBlock {
            lang: lang.map(Into::into),
            code: code.into(),
        }
    }

    /// Convenience constructor for generated code
    pub fn generated_code(spans: Vec<Span<'a>>) -> Self {
        DocumentNode::GeneratedCode { spans }
    }

    /// Convenience constructor for a horizontal rule
    pub fn horizontal_rule() -> Self {
        DocumentNode::HorizontalRule
    }

    /// Convenience constructor for a block quote
    pub fn block_quote(nodes: Vec<DocumentNode<'a>>) -> Self {
        DocumentNode::BlockQuote { nodes }
    }

    /// Convenience constructor for a table
    pub fn table(header: Option<Vec<TableCell<'a>>>, rows: Vec<Vec<TableCell<'a>>>) -> Self {
        DocumentNode::Table { header, rows }
    }

    /// Convenience constructor for a truncated block
    pub fn truncated_block(nodes: Vec<DocumentNode<'a>>, level: TruncationLevel) -> Self {
        DocumentNode::TruncatedBlock { nodes, level }
    }
}

impl<'a> TableCell<'a> {
    /// Create a new table cell from spans
    pub fn new(spans: Vec<Span<'a>>) -> Self {
        Self { spans }
    }

    /// Create a table cell from a single span
    pub fn from_span(span: Span<'a>) -> Self {
        Self { spans: vec![span] }
    }
}

// Compile-time thread-safety assertions for Document
//
// Document<'a> contains DocumentNode<'a> which may hold DocRef<'a> references.
// For the threading model to work, Document must be Send so it can be passed
// between threads in scoped thread scenarios (formatting thread → UI thread).
#[allow(dead_code)]
const _: () = {
    const fn assert_send<T: Send>() {}
    const fn assert_sync<T: Sync>() {}

    // Document<'a> must be Send (can cross thread boundaries in scoped threads)
    const fn check_document_send() {
        assert_send::<Document<'_>>();
    }

    // Document<'a> should also be Sync (multiple threads can hold &Document safely)
    const fn check_document_sync() {
        assert_sync::<Document<'_>>();
    }
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_span_creation() {
        let span = Span::keyword("struct");
        assert_eq!(span.text, "struct");
        assert!(matches!(span.style, SpanStyle::Keyword));
    }

    #[test]
    fn test_section() {
        let section = DocumentNode::section(
            vec![Span::plain("Fields:")],
            vec![DocumentNode::list(vec![
                ListItem::new(vec![DocumentNode::paragraph(vec![Span::field_name("x")])]),
                ListItem::new(vec![DocumentNode::paragraph(vec![Span::field_name("y")])]),
            ])],
        );

        if let DocumentNode::Section { title, nodes } = section {
            assert!(title.is_some());
            assert_eq!(nodes.len(), 1);
        } else {
            panic!("Expected section node");
        }
    }

    #[test]
    fn test_list_items() {
        let list = DocumentNode::list(vec![
            ListItem::new(vec![DocumentNode::paragraph(vec![
                Span::field_name("foo"),
                Span::punctuation(":"),
                Span::type_name("u32"),
            ])]),
            ListItem::new(vec![DocumentNode::paragraph(vec![Span::field_name("bar")])]),
        ]);

        if let DocumentNode::List { items } = list {
            assert_eq!(items.len(), 2);
            assert_eq!(items[0].content.len(), 1);
            assert_eq!(items[1].content.len(), 1);
        } else {
            panic!("Expected list node");
        }
    }

    #[test]
    fn test_heading_levels() {
        let title = DocumentNode::heading(HeadingLevel::Title, vec![Span::plain("Item: Vec")]);
        let section = DocumentNode::heading(HeadingLevel::Section, vec![Span::plain("Methods:")]);

        assert!(matches!(title, DocumentNode::Heading { .. }));
        assert!(matches!(section, DocumentNode::Heading { .. }));
    }

    #[test]
    fn test_code_block() {
        let code = DocumentNode::code_block(Some("rust".to_string()), "fn main() {}".to_string());

        if let DocumentNode::CodeBlock { lang, code } = code {
            assert_eq!(lang, Some("rust".into()));
            assert_eq!(code, "fn main() {}");
        } else {
            panic!("Expected code block");
        }
    }
}