logana 0.5.1

Turn any log source — files, compressed archives, Docker, or OTel streams — into structured data. Filter by pattern, field, or date range; annotate lines; bookmark findings; and export to Markdown, Jira, or AI assistants via the built-in MCP server.
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
use std::collections::HashSet;

use unicode_width::UnicodeWidthChar;

use crate::parser::{DisplayParts, LogFormatParser, SpanInfo, format_span_col};

#[derive(Debug, Clone, Default)]
pub struct FieldLayout {
    pub columns: Option<Vec<String>>,
}

/// Number of terminal rows a line occupies when word-wrapped to `inner_width` columns.
///
/// Simulates ratatui `Wrap { trim: false }` behavior:
/// - Words that fit on the current row are placed there.
/// - Words that don't fit are moved to the next row.
/// - Words wider than `inner_width` are split at character boundaries across rows.
///
/// Returns 1 when `inner_width` is 0 or the line is empty.
pub fn line_row_count(bytes: &[u8], inner_width: usize) -> usize {
    if inner_width == 0 {
        return 1;
    }
    let text = std::str::from_utf8(bytes).unwrap_or("");
    if text.is_empty() {
        return 1;
    }

    let mut rows = 1usize;
    let mut col = 0usize; // current column (unicode width)
    let mut word_w = 0usize; // accumulated width of the current non-whitespace word

    for ch in text.chars() {
        if ch.is_ascii_whitespace() {
            // Commit the pending word before placing the whitespace character.
            if word_w > 0 {
                if col > 0 && col + word_w > inner_width {
                    // Word doesn't fit on current row: move to next.
                    rows += 1;
                    col = 0;
                }
                if col == 0 && word_w > inner_width {
                    // Word is wider than a full row: split at character boundaries.
                    rows += word_w.div_ceil(inner_width) - 1;
                    col = word_w % inner_width;
                } else {
                    col += word_w;
                }
                word_w = 0;
            }
            let cw = UnicodeWidthChar::width(ch).unwrap_or(0);
            if col + cw > inner_width {
                rows += 1;
                col = cw; // trim: false — keep the space on the new row
            } else {
                col += cw;
            }
        } else {
            word_w += UnicodeWidthChar::width(ch).unwrap_or(0);
        }
    }

    // Commit any remaining word.
    if word_w > 0 {
        if col > 0 && col + word_w > inner_width {
            rows += 1;
            col = 0;
        }
        if col == 0 && word_w > inner_width {
            rows += word_w.div_ceil(inner_width) - 1;
        }
    }

    rows
}

/// Simulate word-wrap of `text` into a box of `width` columns and return the
/// number of lines that result. Used to size the status bar dynamically.
pub fn count_wrapped_lines(text: &str, width: usize) -> usize {
    if width == 0 {
        return 1;
    }
    let mut lines = 1usize;
    let mut col = 0usize;
    for word in text.split_whitespace() {
        let wl = word.len();
        if col == 0 {
            col = wl;
        } else if col + 1 + wl > width {
            lines += 1;
            col = wl;
        } else {
            col += 1 + wl;
        }
    }
    lines
}

/// Row count for a line, using the structured rendering width when a parser is
/// available. In wrap mode with structured log formats (e.g. JSON tracing logs),
/// raw bytes can be much longer than the rendered output, causing `line_row_count`
/// on raw bytes to underestimate how many lines fit in the viewport. This function
/// uses the actual rendered-column text width instead.
pub fn effective_row_count(
    line_bytes: &[u8],
    inner_width: usize,
    parser: Option<&dyn LogFormatParser>,
    layout: &FieldLayout,
    hidden_fields: &HashSet<String>,
    show_keys: bool,
) -> usize {
    if let Some(p) = parser
        && let Some(parts) = p.parse_line(line_bytes)
    {
        let cols = apply_field_layout(&parts, layout, hidden_fields, show_keys, None);
        if !cols.is_empty() {
            let rendered = cols.join(" ");
            return line_row_count(rendered.as_bytes(), inner_width);
        }
    }
    line_row_count(line_bytes, inner_width)
}

// ---------------------------------------------------------------------------
// Structured field layout helpers
// ---------------------------------------------------------------------------

pub fn get_col(
    p: &DisplayParts<'_>,
    name: &str,
    show_keys: bool,
    year_override: Option<i32>,
) -> Option<String> {
    match name {
        "span" => p.span.as_ref().map(|s| format_span_col(s, show_keys)),
        n => {
            // Resolve dotted span sub-field names (e.g. "span.name", "span.method").
            if let Some(suffix) = n.strip_prefix("span.") {
                return p.span.as_ref().and_then(|s| {
                    if suffix == "name" {
                        Some(s.name.to_string())
                    } else {
                        s.fields
                            .iter()
                            .find(|(k, _)| *k == suffix)
                            .map(|(_, v)| v.to_string())
                    }
                });
            }
            // Resolve dotted fields sub-field names (e.g. "fields.message", "fields.count").
            if let Some(suffix) = n.strip_prefix("fields.") {
                return if suffix == "message" {
                    p.message.map(|s| s.to_string())
                } else {
                    p.extra_fields
                        .iter()
                        .find(|(_, k, _)| *k == suffix)
                        .map(|(_, _, v)| v.to_string())
                };
            }
            // Map canonical slot names to DisplayParts slots.
            match n {
                "timestamp" => {
                    return p.timestamp.map(|s| {
                        crate::filters::canonical_timestamp(s, year_override)
                            .unwrap_or_else(|| s.to_string())
                    });
                }
                "level" => {
                    return p.level.map(|l| format!("{:<5}", l));
                }
                "target" => {
                    return p.target.map(|s| s.to_string());
                }
                "message" => {
                    return p.message.map(|s| s.to_string());
                }
                _ => {}
            }
            p.extra_fields
                .iter()
                .find(|(_, k, _)| *k == n)
                .map(|(_, _, v)| v.to_string())
        }
    }
}

#[cfg(test)]
fn default_cols(p: &DisplayParts<'_>, show_keys: bool) -> Vec<String> {
    let mut cols = Vec::new();
    if let Some(ts) = p.timestamp {
        cols.push(ts.to_string());
    }
    if let Some(lvl) = p.level {
        cols.push(format!("{:<5}", lvl));
    }
    if let Some(tgt) = p.target {
        cols.push(tgt.to_string());
    }
    if let Some(span) = &p.span {
        cols.push(format_span_col(span, show_keys));
    }
    for (_, key, value) in &p.extra_fields {
        if show_keys {
            cols.push(format!("{key}={value}"));
        } else {
            cols.push(value.to_string());
        }
    }
    if let Some(msg) = p.message {
        cols.push(msg.to_string());
    }
    cols
}

/// Render a span, filtering out sub-fields whose keys are in `excluded_keys`.
fn render_span(s: &SpanInfo<'_>, excluded_keys: &HashSet<&str>, show_keys: bool) -> String {
    if excluded_keys.is_empty() {
        return format_span_col(s, show_keys);
    }
    let visible_fields: Vec<(&str, &str)> = s
        .fields
        .iter()
        .filter(|(k, _)| !excluded_keys.contains(k))
        .copied()
        .collect();
    let filtered = SpanInfo {
        name: s.name,
        fields: visible_fields,
    };
    format_span_col(&filtered, show_keys)
}

pub fn apply_field_layout(
    p: &DisplayParts<'_>,
    layout: &FieldLayout,
    hidden_fields: &HashSet<String>,
    show_keys: bool,
    year_override: Option<i32>,
) -> Vec<String> {
    let excluded_keys: HashSet<&str> = hidden_fields
        .iter()
        .filter_map(|h| h.strip_prefix("span."))
        .collect();

    if let Some(names) = &layout.columns {
        // Explicit layout — filter hidden column names and span sub-fields.
        names
            .iter()
            .filter(|name| !hidden_fields.contains(name.as_str()))
            .filter_map(|name| {
                if name == "span" {
                    p.span
                        .as_ref()
                        .map(|s| render_span(s, &excluded_keys, show_keys))
                } else {
                    get_col(p, name, show_keys, year_override)
                }
            })
            .collect()
    } else {
        // Default layout — rebuild without hidden fields.
        // Check all aliases for each canonical slot so that hiding by raw key
        // (e.g. "lvl") works in the default (no explicit layout) path too.
        let ts_hidden = hidden_fields.contains("timestamp");
        let lvl_hidden = hidden_fields.contains("level");
        let tgt_hidden = hidden_fields.contains("target");
        let msg_hidden = hidden_fields.contains("message");
        let mut cols = Vec::new();
        if !ts_hidden && let Some(ts) = p.timestamp {
            cols.push(
                crate::filters::canonical_timestamp(ts, year_override)
                    .unwrap_or_else(|| ts.to_string()),
            );
        }
        if !lvl_hidden && let Some(lvl) = p.level {
            cols.push(format!("{:<5}", lvl));
        }
        if !tgt_hidden && let Some(tgt) = p.target {
            cols.push(tgt.to_string());
        }
        if !hidden_fields.contains("span")
            && let Some(span) = &p.span
        {
            cols.push(render_span(span, &excluded_keys, show_keys));
        }
        let mut sorted_extras: Vec<_> = p.extra_fields.iter().collect();
        sorted_extras.sort_by_key(|(_, k, _)| *k);
        for (_, key, value) in sorted_extras {
            if !hidden_fields.contains(*key) {
                if show_keys {
                    cols.push(format!("{key}={value}"));
                } else {
                    cols.push(value.to_string());
                }
            }
        }
        if !msg_hidden && let Some(msg) = p.message {
            cols.push(msg.to_string());
        }
        cols
    }
}

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

    // -----------------------------------------------------------------------
    // line_row_count
    // -----------------------------------------------------------------------

    #[test]
    fn test_line_row_count_zero_width() {
        assert_eq!(line_row_count(b"hello", 0), 1);
    }

    #[test]
    fn test_line_row_count_empty_line() {
        assert_eq!(line_row_count(b"", 80), 1);
    }

    #[test]
    fn test_line_row_count_fits_in_one_row() {
        assert_eq!(line_row_count(b"hello", 80), 1);
    }

    #[test]
    fn test_line_row_count_wraps_to_two_rows() {
        // Single word, 10 chars in width 6 → ceil(10/6) = 2 (same as char-wrap for single words)
        assert_eq!(line_row_count(b"0123456789", 6), 2);
    }

    #[test]
    fn test_line_row_count_word_wrap_exceeds_char_wrap() {
        // "hello world test abc" (20 chars) in width 7:
        //   char-wrap: ceil(20/7) = 3 rows
        //   word-wrap: "hello"(5) → col 5; space → col 6;
        //              "world"(5) doesn't fit → row 2; space → col 6;
        //              "test"(4) doesn't fit → row 3; space → col 5;
        //              "abc"(3) doesn't fit → row 4.
        assert_eq!(line_row_count(b"hello world test abc", 7), 4);
    }

    #[test]
    fn test_line_row_count_long_word_spans_many_rows() {
        // Single word of 15 chars in width 5 → ceil(15/5) = 3 rows
        assert_eq!(line_row_count(b"aaaaaaaaaaaaaaa", 5), 3);
    }

    #[test]
    fn test_line_row_count_long_word_plus_short_word() {
        // "aaaaaaaaaa b" — long word (10 chars) in width 7, then " b"
        // Long word: col=0, 10>7 → rows += ceil(10/7)-1=1 → rows=2, col=10%7=3
        // space: col+1=4 ≤ 7 → col=4
        // "b" (1 char): col+1=5 ≤ 7 → col=5
        // Result: 2 rows
        assert_eq!(line_row_count(b"aaaaaaaaaa b", 7), 2);
    }

    #[test]
    fn test_line_row_count_exact_width() {
        assert_eq!(line_row_count(b"12345", 5), 1);
    }

    // -----------------------------------------------------------------------
    // count_wrapped_lines
    // -----------------------------------------------------------------------

    #[test]
    fn test_count_wrapped_lines_empty() {
        assert_eq!(count_wrapped_lines("", 80), 1);
    }

    #[test]
    fn test_count_wrapped_lines_zero_width() {
        assert_eq!(count_wrapped_lines("hello world", 0), 1);
    }

    #[test]
    fn test_count_wrapped_lines_single_word() {
        assert_eq!(count_wrapped_lines("hello", 80), 1);
    }

    #[test]
    fn test_count_wrapped_lines_wraps() {
        // "hello world" with width 6 → "hello" (5) then "world" (5) doesn't fit on same line
        assert!(count_wrapped_lines("hello world", 6) >= 2);
    }

    #[test]
    fn test_count_wrapped_lines_exact_fit() {
        // "ab cd" = 5 chars content, width 5 → fits in 1 line
        assert_eq!(count_wrapped_lines("ab cd", 5), 1);
    }

    // -----------------------------------------------------------------------
    // get_col
    // -----------------------------------------------------------------------

    fn make_parts<'a>() -> DisplayParts<'a> {
        DisplayParts {
            timestamp: Some("2024-01-01T00:00:00Z"),
            level: Some("INFO"),
            target: Some("myapp"),
            span: Some(SpanInfo {
                name: "handler",
                fields: vec![("method", "GET")],
            }),
            extra_fields: vec![(crate::parser::FieldSemantic::Extra, "count", "42")],
            message: Some("hello world"),
        }
    }

    #[test]
    fn test_get_col_timestamp() {
        let p = make_parts();
        assert_eq!(
            get_col(&p, "timestamp", false, None),
            Some("2024-01-01 00:00:00.000".to_string())
        );
    }

    #[test]
    fn test_get_col_timestamp_nano_epoch_converted() {
        let p = DisplayParts {
            timestamp: Some("1700046000000000000"),
            level: Some("INFO"),
            ..Default::default()
        };
        let col = get_col(&p, "timestamp", false, None).unwrap();
        assert!(
            !col.contains("1700046000000000000"),
            "raw nanos should not appear"
        );
        assert!(col.starts_with("2023-11-15"), "should be canonical date");
    }

    #[test]
    fn test_apply_field_layout_default_nano_epoch_converted() {
        let p = DisplayParts {
            timestamp: Some("1700046000000000000"),
            level: Some("INFO"),
            message: Some("server started"),
            ..Default::default()
        };
        let hidden = HashSet::new();
        let cols = apply_field_layout(&p, &FieldLayout { columns: None }, &hidden, false, None);
        assert!(
            cols[0].starts_with("2023-11-15"),
            "timestamp col should be canonical"
        );
    }

    #[test]
    fn test_get_col_level() {
        let p = make_parts();
        let result = get_col(&p, "level", false, None).unwrap();
        assert!(result.starts_with("INFO"));
    }

    #[test]
    fn test_get_col_message() {
        let p = make_parts();
        assert_eq!(
            get_col(&p, "message", false, None),
            Some("hello world".to_string())
        );
    }

    #[test]
    fn test_get_col_span_name() {
        let p = make_parts();
        assert_eq!(
            get_col(&p, "span.name", false, None),
            Some("handler".to_string())
        );
    }

    #[test]
    fn test_get_col_dotted_span_field() {
        let p = make_parts();
        assert_eq!(
            get_col(&p, "span.method", false, None),
            Some("GET".to_string())
        );
    }

    #[test]
    fn test_get_col_dotted_fields_field() {
        let p = make_parts();
        // "fields.message" should resolve to the message slot
        assert_eq!(
            get_col(&p, "fields.message", false, None),
            Some("hello world".to_string())
        );
    }

    #[test]
    fn test_get_col_extra_field() {
        let p = make_parts();
        assert_eq!(get_col(&p, "count", false, None), Some("42".to_string()));
    }

    #[test]
    fn test_get_col_unknown_returns_none() {
        let p = make_parts();
        assert_eq!(get_col(&p, "nonexistent", false, None), None);
    }

    #[test]
    fn test_get_col_alias_resolution() {
        use crate::parser::{FieldSemantic, push_field_as};
        // push_field_as stores canonical key — "pid" resolves directly for any source
        let mut extra_fields = vec![];
        push_field_as(&mut extra_fields, FieldSemantic::Pid, "1234");
        push_field_as(&mut extra_fields, FieldSemantic::Hostname, "myhost");
        let p = DisplayParts {
            extra_fields,
            ..Default::default()
        };
        assert_eq!(get_col(&p, "pid", false, None), Some("1234".to_string()));
        assert_eq!(
            get_col(&p, "hostname", false, None),
            Some("myhost".to_string())
        );
    }

    #[test]
    fn test_get_col_span_show_keys() {
        let p = make_parts();
        // show_keys=false: values only
        assert_eq!(
            get_col(&p, "span", false, None),
            Some("handler: GET".to_string())
        ); // single value, no separator difference
        // show_keys=true: key=value pairs
        assert_eq!(
            get_col(&p, "span", true, None),
            Some("handler: method=GET".to_string())
        );
    }

    // -----------------------------------------------------------------------
    // default_cols
    // -----------------------------------------------------------------------

    #[test]
    fn test_default_cols_all_fields() {
        let p = make_parts();
        let cols = default_cols(&p, false);
        // Should have: timestamp, level, target, span, extra(count), message = 6
        assert_eq!(cols.len(), 6);
        assert!(cols[0].contains("2024"));
        assert!(cols[1].starts_with("INFO"));
        assert_eq!(cols[2], "myapp");
        assert!(cols[5].contains("hello world"));
    }

    #[test]
    fn test_default_cols_minimal() {
        let p = DisplayParts {
            timestamp: None,
            level: None,
            target: None,
            span: None,
            extra_fields: vec![],
            message: Some("only message"),
        };
        let cols = default_cols(&p, false);
        assert_eq!(cols.len(), 1);
        assert_eq!(cols[0], "only message");
    }

    // -----------------------------------------------------------------------
    // apply_field_layout
    // -----------------------------------------------------------------------

    #[test]
    fn test_apply_field_layout_default_no_hidden() {
        let p = make_parts();
        let layout = FieldLayout::default();
        let hidden = HashSet::new();
        let cols = apply_field_layout(&p, &layout, &hidden, false, None);
        assert_eq!(cols.len(), 6);
    }

    #[test]
    fn test_apply_field_layout_explicit_columns() {
        let p = make_parts();
        let layout = FieldLayout {
            columns: Some(vec!["level".to_string(), "message".to_string()]),
        };
        let hidden = HashSet::new();
        let cols = apply_field_layout(&p, &layout, &hidden, false, None);
        assert_eq!(cols.len(), 2);
    }

    #[test]
    fn test_apply_field_layout_hidden_fields_default() {
        let p = make_parts();
        let layout = FieldLayout::default();
        let mut hidden = HashSet::new();
        hidden.insert("timestamp".to_string());
        let cols = apply_field_layout(&p, &layout, &hidden, false, None);
        // Should have 5 (all minus timestamp)
        assert_eq!(cols.len(), 5);
    }

    #[test]
    fn test_apply_field_layout_hidden_fields_explicit() {
        let p = make_parts();
        let layout = FieldLayout {
            columns: Some(vec![
                "timestamp".to_string(),
                "level".to_string(),
                "message".to_string(),
            ]),
        };
        let mut hidden = HashSet::new();
        hidden.insert("timestamp".to_string());
        let cols = apply_field_layout(&p, &layout, &hidden, false, None);
        assert_eq!(cols.len(), 2); // level + message
    }

    // -----------------------------------------------------------------------
    // effective_row_count
    // -----------------------------------------------------------------------

    #[test]
    fn test_effective_row_count_no_parser_uses_raw_bytes() {
        let hidden = HashSet::new();
        let layout = FieldLayout::default();
        assert_eq!(
            effective_row_count(b"hello world", 80, None, &layout, &hidden, false),
            1
        );
        // ceil(11/5) = 3
        assert_eq!(
            effective_row_count(b"hello world", 5, None, &layout, &hidden, false),
            3
        );
    }

    #[test]
    fn test_effective_row_count_with_parser_uses_rendered_width() {
        // A JSON line that is long in raw bytes but short when structured-rendered.
        let json = br#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","target":"app","fields":{"message":"ok"}}"#;
        let parser = crate::parser::detect_format(&[br#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","target":"app","fields":{"message":"ok"}}"#]).unwrap();
        let layout = FieldLayout::default();
        let hidden = HashSet::new();
        // Raw bytes are ~94 chars; at width=20 that's 5 rows.
        assert_eq!(line_row_count(json, 20), 5);
        // Structured render is much shorter; effective_row_count should be < 5.
        let result = effective_row_count(json, 20, Some(parser.as_ref()), &layout, &hidden, false);
        assert!(
            result < 5,
            "structured rendering should produce fewer rows than raw bytes"
        );
    }

    #[test]
    fn test_effective_row_count_parse_failure_falls_back_to_raw() {
        let parser = crate::parser::detect_format(&[br#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","target":"app","fields":{"message":"ok"}}"#]).unwrap();
        let layout = FieldLayout::default();
        let hidden = HashSet::new();
        // Non-JSON input: parse returns None → falls back to raw byte width.
        let raw = b"plain text log line that is not json";
        assert_eq!(
            effective_row_count(raw, 20, Some(parser.as_ref()), &layout, &hidden, false),
            line_row_count(raw, 20)
        );
    }

    #[test]
    fn test_effective_row_count_all_hidden_falls_back_to_raw() {
        let parser = crate::parser::detect_format(&[br#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","target":"app","fields":{"message":"ok"}}"#]).unwrap();
        let layout = FieldLayout::default();
        // Hide every known field so cols is empty → falls back to raw.
        let mut hidden = HashSet::new();
        for key in ["timestamp", "level", "target", "message"] {
            hidden.insert(key.to_string());
        }
        let json = br#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","target":"app","fields":{"message":"ok"}}"#;
        let raw_rows = line_row_count(json, 20);
        assert_eq!(
            effective_row_count(json, 20, Some(parser.as_ref()), &layout, &hidden, false),
            raw_rows
        );
    }

    #[test]
    fn test_hiding_span_subfield_filters_it_from_default_layout() {
        let p = DisplayParts {
            timestamp: Some("2024-01-01T00:00:00Z"),
            level: Some("INFO"),
            target: Some("app"),
            span: Some(SpanInfo {
                name: "request",
                fields: vec![("request_id", "abc-123"), ("method", "GET")],
            }),
            extra_fields: vec![],
            message: Some("hello"),
        };
        let layout = FieldLayout::default();
        let mut hidden = HashSet::new();
        hidden.insert("span.request_id".to_string());
        let cols = apply_field_layout(&p, &layout, &hidden, true, None);
        let span_col = cols.iter().find(|c| c.contains("request")).unwrap();
        assert!(
            !span_col.contains("request_id"),
            "hidden span sub-field should not appear: {span_col}"
        );
        assert!(
            span_col.contains("method"),
            "non-hidden span sub-field should still appear: {span_col}"
        );
    }

    #[test]
    fn test_hiding_span_subfield_via_hidden_fields_explicit_layout() {
        let p = DisplayParts {
            timestamp: None,
            level: None,
            target: None,
            span: Some(SpanInfo {
                name: "request",
                fields: vec![("request_id", "abc-123"), ("method", "GET")],
            }),
            extra_fields: vec![],
            message: None,
        };
        let layout = FieldLayout {
            columns: Some(vec!["span".to_string()]),
        };
        let mut hidden = HashSet::new();
        hidden.insert("span.request_id".to_string());
        let cols = apply_field_layout(&p, &layout, &hidden, true, None);
        assert_eq!(cols.len(), 1);
        assert!(
            !cols[0].contains("request_id"),
            "hidden span sub-field should not appear in explicit layout: {}",
            cols[0]
        );
        assert!(cols[0].contains("method"));
    }

    #[test]
    fn test_hiding_span_subfield_via_select_fields() {
        // Simulates the select-fields path: field_layout.columns has all fields
        // ordered, and span.request_id is disabled via hidden_fields.
        let p = DisplayParts {
            timestamp: None,
            level: None,
            target: None,
            span: Some(SpanInfo {
                name: "request",
                fields: vec![("request_id", "abc-123"), ("method", "GET")],
            }),
            extra_fields: vec![],
            message: None,
        };
        let layout = FieldLayout {
            columns: Some(vec![
                "span".to_string(),
                "span.request_id".to_string(),
                "span.method".to_string(),
            ]),
        };
        let mut hidden = HashSet::new();
        hidden.insert("span.request_id".to_string());
        let cols = apply_field_layout(&p, &layout, &hidden, true, None);
        // "span" column should render without request_id (it is in hidden_fields)
        let span_col = cols.iter().find(|c| c.contains("request")).unwrap();
        assert!(
            !span_col.contains("request_id"),
            "disabled span sub-field should be filtered: {span_col}"
        );
        assert!(span_col.contains("method"));
    }

    #[test]
    fn test_hiding_all_span_subfields_leaves_span_name() {
        let p = DisplayParts {
            timestamp: None,
            level: None,
            target: None,
            span: Some(SpanInfo {
                name: "request",
                fields: vec![("request_id", "abc-123")],
            }),
            extra_fields: vec![],
            message: None,
        };
        let layout = FieldLayout::default();
        let mut hidden = HashSet::new();
        hidden.insert("span.request_id".to_string());
        let cols = apply_field_layout(&p, &layout, &hidden, false, None);
        assert!(
            cols.iter().any(|c| c == "request"),
            "span name should remain when all sub-fields are hidden"
        );
    }

    #[test]
    fn test_apply_field_layout_hidden_alias() {
        let p = make_parts();
        let layout = FieldLayout::default();
        let mut hidden = HashSet::new();
        // canonical name for level — hiding it should hide the level column
        hidden.insert("level".to_string());
        let cols = apply_field_layout(&p, &layout, &hidden, false, None);
        // Should have 5 (all minus level)
        assert_eq!(cols.len(), 5);
    }
}