seer-cli 0.56.0

Interactive CLI for Seer domain name utilities
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Reads `&App` and draws the full frame: top bar, nav, main pane, status/cmd
//! bar, and the help overlay.

use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
use ratatui::Frame;
use seer_core::output::sanitize_line;

use crate::tui::action::{EditTarget, Focus, InputMode, LensData, LensKey, LensState};
use crate::tui::app::{App, SPIN};
use crate::tui::lenses::{self};
use crate::tui::line_editor::LineEditor;
use crate::tui::theme::Theme;
use crate::tui::widgets::{inspector, page, panel};

/// The in-progress editor for `target`, if a matching field is active (the
/// editor, not just its text, so renderers can place the caret at the cursor).
fn field_buf(mode: &InputMode, target: EditTarget) -> Option<&LineEditor> {
    match mode {
        InputMode::Field { target: t, buf } if *t == target => Some(buf),
        _ => None,
    }
}

/// Status-bar prompt for edit fields that no pane draws inline. `None` means
/// the field is rendered elsewhere (top bar, its lens, or the filter line) —
/// the match is exhaustive so a new field can't silently go undrawn again.
fn status_prompt(app: &App, target: EditTarget) -> Option<String> {
    let follow = &app.panes.follow;
    match target {
        EditTarget::FollowInterval => {
            Some(format!("interval seconds (now {})> ", follow.interval_secs))
        }
        EditTarget::FollowCount => Some(format!("check count (now {})> ", follow.count)),
        EditTarget::BulkPath => Some("domains file> ".to_string()),
        EditTarget::WatchAdd => Some("watch add> ".to_string()),
        EditTarget::Target
        | EditTarget::DiffB
        | EditTarget::BulkDomains
        | EditTarget::TldFilter
        | EditTarget::LensFilter
        | EditTarget::Switcher => None,
    }
}

pub fn view(f: &mut Frame, app: &App, theme: &Theme) {
    let area = f.area();
    // Paint the whole canvas before any widget: both themes must be
    // self-contained on any terminal. Cells no widget backfills otherwise
    // keep the terminal's own background, which renders Latte in a dark
    // terminal as light bars floating on a dark canvas. The mantle bars and
    // selection stripes then read as the intended contrast against base.
    f.render_widget(
        Block::default().style(Style::default().bg(theme.base).fg(theme.text)),
        area,
    );
    // Top bar, the group row, the active group's lenses, the lens, status.
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Min(0),
            Constraint::Length(1),
        ])
        .split(area);

    top_bar(f, rows[0], app, theme);
    strip_groups(f, rows[1], app, theme);
    strip_lenses(f, rows[2], app, theme);
    main_pane(f, rows[3], app, theme);
    status_or_command(f, rows[4], app, theme);

    if let Some(buf) = field_buf(&app.input_mode, EditTarget::Switcher) {
        switcher(f, area, buf, theme);
    }
    if app.help {
        help_overlay(f, area, app, theme);
    }
}

fn top_bar(f: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let domain = app.domain.as_deref().unwrap_or("(no target)");
    let target = match &app.input_mode {
        InputMode::Field {
            target: EditTarget::Target,
            buf,
        } => format!("⌕ {}", buf.with_caret("▏")),
        // Other field targets are rendered inside their panes; top-bar shows current domain.
        _ => format!("⌕ {domain}"),
    };
    let ip = match app.state_of(app.lens) {
        LensState::Loading => format!("{} resolving…", SPIN[app.spin]),
        _ => String::new(),
    };
    let mode = if app.focus == Focus::Pane {
        "‹pane›"
    } else {
        "‹nav›"
    };
    let mut spans = vec![
        Span::styled(
            "🔮 seer",
            Style::default()
                .fg(theme.mauve)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("  │  ", Style::default().fg(theme.surface1)),
        Span::styled("target ", Style::default().fg(theme.overlay)),
        Span::styled(target, Style::default().fg(theme.text)),
        Span::styled(format!("  {ip}  "), Style::default().fg(theme.teal)),
    ];
    if app.format != seer_core::output::OutputFormat::Human {
        spans.push(Span::styled(
            format!(" --format {:?} ", app.format).to_lowercase(),
            Style::default().fg(theme.green),
        ));
    }
    spans.push(Span::styled(
        format!("  {mode}  "),
        Style::default().fg(theme.lavender),
    ));
    spans.push(Span::styled(
        format!("│ v{}", env!("CARGO_PKG_VERSION")),
        Style::default().fg(theme.overlay0),
    ));
    f.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(theme.mantle)),
        area,
    );
}

/// The nav groups, the active one highlighted.
fn strip_groups(f: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let active = app.current_lens().group;
    let mut spans = vec![Span::raw(" ")];
    for group in lenses::groups() {
        let style = if group == active {
            Style::default()
                .fg(theme.base)
                .bg(theme.mauve)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme.subtext)
        };
        spans.push(Span::styled(format!(" {group} "), style));
        spans.push(Span::raw(" "));
    }
    f.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(theme.mantle)),
        area,
    );
}

/// The active group's lenses, numbered for `1`–`9`. When they are wider
/// than the row, leading lenses give way until the active one fits, and a
/// `‹` / `›` marks each clipped edge.
fn strip_lenses(f: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let all = lenses::lenses();
    let members = lenses::group_members(app.current_lens().group);
    let items: Vec<Span> = members
        .iter()
        .enumerate()
        .map(|(n, &i)| {
            let l = &all[i];
            let text = format!(" {} {} {} ", n + 1, l.glyph, l.label);
            let style = if i == app.lens {
                Style::default()
                    .fg(theme.text)
                    .bg(theme.surface0)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(theme.subtext)
            };
            Span::styled(text, style)
        })
        .collect();
    let active = members.iter().position(|&i| i == app.lens).unwrap_or(0);
    let width = usize::from(area.width);
    let span_w = |range: &[Span]| range.iter().map(Span::width).sum::<usize>();
    // Room for the marks either side.
    const MARK: usize = 2;
    let mut start = 0;
    while start < active && MARK + span_w(&items[start..=active]) + MARK > width {
        start += 1;
    }
    let mut end = start;
    while end < items.len() {
        let more = end + 1 < items.len();
        let reserve = if more { MARK } else { 0 };
        if MARK + span_w(&items[start..=end]) + reserve > width && end > active {
            break;
        }
        end += 1;
    }
    let mut spans = vec![Span::styled(
        if start > 0 { "‹ " } else { "  " },
        Style::default().fg(theme.overlay0),
    )];
    spans.extend(items[start..end].iter().cloned());
    if end < items.len() {
        spans.push(Span::styled(" ›", Style::default().fg(theme.overlay0)));
    }
    f.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(theme.mantle)),
        area,
    );
}

fn main_pane(f: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let lens = app.current_lens();

    // Sub-tab bar (human view only) for lenses that have tabs.
    let content = if !lens.tabs.is_empty() && app.format == seer_core::output::OutputFormat::Human {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(1), Constraint::Min(0)])
            .split(area);
        sub_tabs(f, chunks[0], app, theme);
        chunks[1]
    } else {
        area
    };

    // Pane-driven interactive lenses render from `app.panes` state, not from a
    // fetched `LensData`, so they never reach `LensState::Loaded`. They have no
    // raw serialization either, so render them the same way in every format —
    // otherwise toggling `r` would drop them to the generic "press /" idle hint.
    let pane_page = match lens.key {
        LensKey::Follow => Some(lenses::follow::page(theme, &app.panes.follow, app.spin)),
        LensKey::Diff => {
            let domain_a = app.panes.diff.effective_a(app.domain.as_deref());
            Some(lenses::diff::page(
                theme,
                domain_a.as_deref(),
                &app.panes.diff.b,
                field_buf(&app.input_mode, EditTarget::DiffB),
                app.focus == Focus::Pane,
                app.state_of(app.lens),
            ))
        }
        LensKey::Bulk => Some(lenses::bulk::page(
            theme,
            &app.panes.bulk,
            field_buf(&app.input_mode, EditTarget::BulkDomains),
            app.spin,
        )),
        LensKey::Tld => {
            let (loaded, loading) = match app.state_of(app.lens) {
                LensState::Loaded(LensData::Tld(t)) => (Some(t.as_ref()), false),
                LensState::Loading => (None, true),
                _ => (None, false),
            };
            Some(lenses::tld::page(
                theme,
                &app.panes.tld,
                loaded,
                loading,
                field_buf(&app.input_mode, EditTarget::TldFilter),
            ))
        }
        _ => None,
    };
    if let Some(p) = pane_page {
        page::draw(f, content, theme, p, app.focus == Focus::Pane);
        return;
    }

    match app.state_of(app.lens) {
        LensState::Loading => {
            // Name what is actually being queried: an explicit request
            // (`:rdap 8.8.8.8`, `:rdap AS15169`) targets something other
            // than the session domain.
            let target = app
                .pending_target(app.lens)
                .or_else(|| app.domain.clone())
                .unwrap_or_default();
            let line = Line::from(Span::styled(
                format!("{} querying {target}…", SPIN[app.spin]),
                Style::default().fg(theme.overlay),
            ));
            f.render_widget(Paragraph::new(line), content);
            return;
        }
        LensState::Error(e) => {
            let inner = panel::render(f, content, theme, lens.label, theme.red, false);
            // Errors quote remote servers: one sanitized line, wrapped to
            // the panel rather than clipped at its edge.
            f.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    sanitize_line(e),
                    Style::default().fg(theme.red),
                )))
                .wrap(Wrap { trim: false }),
                inner,
            );
            return;
        }
        LensState::Idle => {
            let hint_text = match (lens.key, app.tab, app.domain.as_deref()) {
                // Tab-specific idle hints for the RDAP lens.
                (LensKey::Rdap, 2, _) => "use :rdap AS<number>  (e.g. :rdap AS15169)".to_string(),
                (LensKey::Rdap, 1, _) => {
                    "use :rdap <ip>  or navigate to a domain first".to_string()
                }
                // A heavy lens waits for ↵ rather than scanning on navigation.
                (_, _, Some(domain)) if lens.heavy => format!(
                    "press ↵ to run {} for {domain}  (active scan: CT logs + HTTP probes)",
                    lens.label
                ),
                _ => "press / to look up a domain".to_string(),
            };
            let hint = Line::from(Span::styled(hint_text, Style::default().fg(theme.overlay0)));
            f.render_widget(Paragraph::new(hint), content);
            return;
        }
        LensState::Loaded(_) => {}
    }

    // Raw view takes over for non-human formats. It scrolls (PgUp/PgDn, or
    // j/k once focused); each line is sanitized, since serializers escape
    // control characters but pass other terminal sequences (U+009B CSI).
    if app.format != seer_core::output::OutputFormat::Human {
        if let LensState::Loaded(data) = app.state_of(app.lens) {
            let text = crate::payload::serialize(data, app.format);
            let lines: Vec<Line> = text.lines().map(|l| Line::from(sanitize_line(l))).collect();
            let total = lines.len();
            let raw_title = format!("{} · raw", lens.label);
            let inner = panel::render(
                f,
                content,
                theme,
                &raw_title,
                theme.green,
                app.focus == Focus::Pane,
            );
            // Stop once the last line reaches the panel's bottom.
            let max = total.saturating_sub(usize::from(inner.height));
            let top = usize::from(app.raw_scroll).min(max);
            let top = u16::try_from(top).unwrap_or(u16::MAX);
            f.render_widget(
                Paragraph::new(lines)
                    .style(Style::default().fg(theme.subtext))
                    .scroll((top, 0)),
                inner,
            );
        }
        return;
    }

    // Human view: dispatch to the lens renderer. Row-based lenses are filtered
    // centrally here (same `filter::apply` used by `App::row_count`) so the
    // renderer, selection, and scroll all see the same visible subset.
    if let LensState::Loaded(data) = app.state_of(app.lens) {
        let focused = app.focus == Focus::Pane;
        let filter = app.active_filter();
        let filtered = crate::tui::filter::apply(data, &filter);
        let render_data = filtered.as_ref().unwrap_or(data);
        lenses::render(
            f,
            content,
            theme,
            lens.key,
            app.tab,
            render_data,
            &filter,
            focused,
            app.sel,
            &app.panes,
        );
    }
}

fn sub_tabs(f: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let lens = app.current_lens();
    let mut spans = Vec::new();
    for (i, t) in lens.tabs.iter().enumerate() {
        let on = i == app.tab;
        spans.push(Span::styled(
            format!(" {t} "),
            Style::default().fg(if on { theme.mauve } else { theme.subtext }),
        ));
        spans.push(Span::raw(" "));
    }
    spans.push(Span::styled(
        "[ ] switch tab",
        Style::default().fg(theme.overlay0),
    ));
    f.render_widget(Paragraph::new(Line::from(spans)), area);
}

fn status_or_command(f: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    if let InputMode::Field {
        target: EditTarget::LensFilter,
        buf,
    } = &app.input_mode
    {
        let matches = app.row_count();
        let line = Line::from(vec![
            Span::styled(
                "filter> ",
                Style::default()
                    .fg(theme.mauve)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(buf.with_caret("█"), Style::default().fg(theme.text)),
            Span::styled(
                format!("   {matches} match(es)  [enter apply · esc cancel]"),
                Style::default().fg(theme.overlay0),
            ),
        ]);
        f.render_widget(
            Paragraph::new(line).style(Style::default().bg(theme.mantle)),
            area,
        );
        return;
    }
    if let InputMode::Command(buf) = &app.input_mode {
        let line = Line::from(vec![
            Span::styled(
                "seer> ",
                Style::default()
                    .fg(theme.mauve)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(buf.with_caret("█"), Style::default().fg(theme.text)),
        ]);
        f.render_widget(
            Paragraph::new(line).style(Style::default().bg(theme.mantle)),
            area,
        );
        return;
    }
    // Generic fallback for edit fields no pane draws inline (Follow
    // interval/count, bulk file path, watch add): without it the typed text
    // is invisible.
    if let InputMode::Field { target, buf } = &app.input_mode {
        if let Some(prompt) = status_prompt(app, *target) {
            let line = Line::from(vec![
                Span::styled(
                    prompt,
                    Style::default()
                        .fg(theme.mauve)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(buf.with_caret("█"), Style::default().fg(theme.text)),
                Span::styled(
                    "   [enter apply · esc cancel]",
                    Style::default().fg(theme.overlay0),
                ),
            ]);
            f.render_widget(
                Paragraph::new(line).style(Style::default().bg(theme.mantle)),
                area,
            );
            return;
        }
    }
    let lens = app.current_lens();
    let mut spans = vec![Span::styled(
        format!("{} {}  ", lens.glyph, lens.label),
        Style::default().fg(theme.lavender),
    )];
    if let Some(t) = &app.toast {
        spans.push(Span::styled(
            format!("● {}", sanitize_line(&t.msg)),
            Style::default().fg(theme.tone(&t.tone)),
        ));
    }
    // Show an active committed in-lens filter (press `/` on the pane to edit).
    let active_filter = app.active_filter();
    if !active_filter.is_empty() {
        spans.push(Span::styled(
            format!("filter:/{}/  ", active_filter),
            Style::default().fg(theme.mauve),
        ));
    }
    spans.push(Span::raw(" "));
    // A focused pane lists its own keys; otherwise the global ones.
    let lens_keys: Vec<(String, &str)> = lens.keys.iter().map(|h| (h.label(), h.what)).collect();
    let keys: Vec<(String, &str)> = if app.focus == Focus::Pane && !lens_keys.is_empty() {
        let mut keys = lens_keys;
        if lens.filterable() {
            keys.push(("/".to_string(), "filter"));
        }
        keys.extend([("h".to_string(), "back"), ("?".to_string(), "help")]);
        keys
    } else {
        // `[ ] tab` only where there are sub-tabs, so `? help` still fits at
        // 80 columns.
        let tabs = (!lens.tabs.is_empty()).then_some(("[ ]", "tab"));
        [("j/k", "move"), ("␣", "go to"), ("tab", "focus")]
            .into_iter()
            .chain(tabs)
            .chain([
                ("r", "raw"),
                ("y", "copy"),
                ("/", "lookup"),
                (":", "cmd"),
                ("?", "help"),
            ])
            .map(|(k, t)| (k.to_string(), t))
            .collect()
    };
    for (k, t) in keys {
        spans.push(Span::styled(
            format!(" {k}"),
            Style::default().fg(theme.crust).bg(theme.overlay),
        ));
        spans.push(Span::styled(
            format!(" {t} "),
            Style::default().fg(theme.overlay0),
        ));
    }
    f.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::default().bg(theme.mantle)),
        area,
    );
}

/// The `Space` switcher: the query, then the lenses it matches, best first
/// (highlighted: the one `↵` goes to).
fn switcher(f: &mut Frame, area: Rect, buf: &LineEditor, theme: &Theme) {
    let all = lenses::lenses();
    let matches = lenses::switch_matches(buf.as_str());
    let mut lines = vec![Line::from(vec![
        Span::styled("> ", Style::default().fg(theme.mauve)),
        Span::styled(buf.with_caret("▏"), Style::default().fg(theme.text)),
    ])];
    if matches.is_empty() {
        lines.push(Line::from(Span::styled(
            "no lens matches",
            Style::default().fg(theme.overlay0),
        )));
    }
    for (n, &i) in matches.iter().enumerate() {
        let l = &all[i];
        lines.push(
            Line::from(vec![
                Span::styled(format!("{} ", l.glyph), Style::default().fg(theme.lavender)),
                Span::raw(format!("{:<14}", l.label)),
                Span::styled(l.group, Style::default().fg(theme.overlay0)),
            ])
            .style(crate::tui::widgets::row_style(theme, n == 0)),
        );
    }
    let w = 40u16.min(area.width.saturating_sub(4));
    let h = u16::try_from(lines.len() + 2)
        .unwrap_or(u16::MAX)
        .min(area.height.saturating_sub(2));
    let popup = Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 3,
        width: w,
        height: h,
    };
    f.render_widget(Clear, popup);
    f.render_widget(
        Block::default().style(Style::default().bg(theme.base).fg(theme.text)),
        popup,
    );
    let inner = panel::render(f, popup, theme, "go to", theme.mauve, true);
    f.render_widget(Paragraph::new(lines), inner);
}

/// Width of the key column in the help overlay.
const HELP_KEY_COL: usize = 16;

fn help_overlay(f: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let global = [
        ("j / k  ·  ↑ ↓", "move selection (nav or pane)"),
        ("1 … 9", "lens in the current group"),
        ("{ / }", "previous / next group"),
        ("Space", "go to any lens by name"),
        ("Tab", "toggle focus: nav ⇄ pane"),
        ("[ / ]", "switch sub-tabs (RDAP)"),
        ("↵ / l", "enter the pane · run Subdomains / Takeover"),
        ("h / Esc", "back to nav"),
        ("g / G", "jump to top / bottom"),
        ("r", "raw output ⇄ human view"),
        ("PgUp / PgDn", "scroll the raw view (j / k once focused)"),
        ("y", "copy current output to clipboard"),
        ("/", "look up a domain"),
        (":", "command (lookup · dig · ssl · set output · theme · q)"),
        ("?", "this help · Esc closes"),
    ];
    let lens = app.current_lens();
    let lens_rows: Vec<(String, &str)> = lens.keys.iter().map(|h| (h.label(), h.what)).collect();
    let row = |(k, t): (&str, &str)| {
        Line::from(vec![
            Span::styled(
                format!("{k:<HELP_KEY_COL$}"),
                Style::default().fg(theme.peach),
            ),
            Span::styled(t.to_string(), Style::default().fg(theme.subtext)),
        ])
    };
    // The focused lens's own keys lead, so on a short terminal the rows cut
    // off (and marked) are global ones the status bar also lists.
    let mut lines: Vec<Line> = Vec::new();
    if !lens_rows.is_empty() {
        lines.push(Line::from(Span::styled(
            format!("{} {} keys", lens.glyph, lens.label),
            Style::default().fg(theme.lavender),
        )));
        lines.extend(lens_rows.iter().map(|(k, t)| row((k.as_str(), *t))));
        lines.push(Line::default());
    }
    lines.extend(global.iter().copied().map(row));
    // Wide enough for the longest row (border + padding), never past the frame.
    let longest = lines.iter().map(Line::width).max().unwrap_or(0);
    let w = u16::try_from(longest + 4)
        .unwrap_or(u16::MAX)
        .max(60)
        .min(area.width.saturating_sub(4));
    let rows = u16::try_from(lines.len() + 4).unwrap_or(u16::MAX);
    let h = rows.min(area.height.saturating_sub(2));
    let popup = Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    };
    f.render_widget(Clear, popup);
    // Clear resets the popup cells to the terminal default; re-apply the
    // theme base so the overlay stays self-contained like the main canvas.
    f.render_widget(
        Block::default().style(Style::default().bg(theme.base).fg(theme.text)),
        popup,
    );
    let inner = panel::render(f, popup, theme, "keybindings", theme.lavender, true);
    inspector::draw(f, inner, theme, lines);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::app::App;
    use crate::tui::test_util::{render_buffer, render_lines, render_text};

    fn full_buf(app: &App, theme: &Theme) -> String {
        render_text(100, 30, |f| view(f, app, theme))
    }

    #[test]
    fn strip_shows_groups_and_the_active_groups_lenses() {
        let mut app = App::new(None);
        app.lens = LensKey::Dnssec.index();
        let s = render_lines(140, 30, |f| view(f, &app, app.theme()));
        let rows: Vec<&str> = s.lines().collect();
        assert!(
            rows[1].contains("LOOKUP") && rows[1].contains("POWER"),
            "{s}"
        );
        assert!(
            rows[2].contains("1 ≣ Records") && rows[2].contains("2 ◑ DNSSEC"),
            "{s}"
        );
        assert!(!rows[2].contains("WHOIS"), "{s}");
        // No sidebar: the lens (here its idle hint) starts at column 0.
        assert!(rows[3].starts_with("press /"), "{s}");
    }

    #[test]
    fn a_narrow_strip_keeps_the_active_lens_visible() {
        let mut app = App::new(None);
        app.lens = LensKey::Follow.index();
        let s = render_lines(40, 20, |f| view(f, &app, app.theme()));
        let row = s.lines().nth(2).unwrap_or_default();
        assert!(row.contains("Follow") && row.starts_with('‹'), "{s}");
    }

    #[test]
    fn switcher_popup_lists_matches() {
        use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
        let mut app = App::new(None);
        for c in [' ', 's', 'u', 'b'] {
            app.update(crate::tui::action::Msg::Input(Event::Key(KeyEvent::new(
                KeyCode::Char(c),
                KeyModifiers::NONE,
            ))));
        }
        let s = render_lines(100, 30, |f| view(f, &app, app.theme()));
        assert!(s.contains("go to"), "{s}");
        assert!(s.contains("Subdomains") && s.contains("SECURITY"), "{s}");
    }

    /// At 80 columns the global hints still end with `? help`: `[ ] tab`
    /// shows only on a lens that has sub-tabs.
    #[test]
    fn the_status_bar_fits_its_help_hint_at_80_columns() {
        let mut app = App::new(None);
        app.lens = LensKey::Audit.index();
        let s = render_lines(80, 24, |f| view(f, &app, app.theme()));
        let status = s.lines().last().unwrap_or_default();
        assert!(status.contains("? help"), "{status}");
        assert!(!status.contains("[ ] tab"), "{status}");
        app.lens = LensKey::Rdap.index();
        let s = render_lines(140, 24, |f| view(f, &app, app.theme()));
        assert!(
            s.lines().last().is_some_and(|l| l.contains("[ ] tab")),
            "{s}"
        );
    }

    #[test]
    fn help_overlay_rows_are_not_clipped() {
        let mut app = App::new(None);
        app.help = true;
        let s = render_lines(100, 30, |f| view(f, &app, app.theme()));
        assert!(s.contains("theme · q)"), "the : row must render whole: {s}");
    }

    /// On an 80×24 terminal the lens's own keys come first, so a long list
    /// (Bulk has seven) is never the part cut off.
    #[test]
    fn help_overlay_keeps_every_lens_key_on_a_small_terminal() {
        let mut app = App::new(None);
        app.lens = LensKey::Bulk.index();
        app.help = true;
        let s = render_lines(80, 24, |f| view(f, &app, app.theme()));
        assert!(s.contains(&format!("{:<16}export", "e")), "{s}");
        assert!(
            s.contains("more lines"),
            "the cut global rows are marked: {s}"
        );
    }

    #[test]
    fn help_overlay_lists_the_current_lens_keys() {
        let mut app = App::new(None);
        app.lens = LensKey::Follow.index();
        app.help = true;
        let s = render_lines(100, 40, |f| view(f, &app, app.theme()));
        // The overlay's own row format: the key padded to its 16-col column.
        // (The Follow pane behind it also says "interval".)
        assert!(s.contains("Follow keys"), "{s}");
        assert!(s.contains(&format!("{:<16}interval", "i")), "{s}");
    }

    #[test]
    fn status_bar_shows_lens_keys_when_the_pane_is_focused() {
        let mut app = App::new(None);
        app.lens = LensKey::Follow.index();
        // Only the status bar (last row) is checked: the Follow pane itself
        // also prints its interval.
        let status = |app: &App| {
            render_lines(140, 30, |f| view(f, app, app.theme()))
                .lines()
                .last()
                .unwrap_or_default()
                .to_string()
        };
        assert!(!status(&app).contains("interval"), "{}", status(&app));
        app.focus = Focus::Pane;
        assert!(status(&app).contains("interval"), "{}", status(&app));
    }

    #[test]
    fn follow_lens_renders_its_pane_not_the_generic_hint() {
        let theme = Theme::frappe();
        let mut app = App::new(None);
        app.lens = lenses::find_by_cmd_or_key("follow").unwrap();
        let s = full_buf(&app, &theme);
        assert!(s.contains("s start"), "Follow pane (hints) should render");
        assert!(
            !s.contains("press / to look up a domain"),
            "Follow must not fall back to the generic idle hint"
        );
    }

    #[test]
    fn fields_without_an_inline_editor_are_echoed_in_the_status_bar() {
        let theme = Theme::frappe();
        let mut app = App::new(None);
        app.lens = lenses::find_by_cmd_or_key("follow").unwrap();
        let mut buf: LineEditor = "60".into();
        buf.left();
        app.input_mode = InputMode::Field {
            target: EditTarget::FollowInterval,
            buf,
        };
        let s = full_buf(&app, &theme);
        assert!(
            s.contains("interval seconds (now 30)> 6█0"),
            "typed interval (with caret at the cursor) must be visible"
        );

        for (target, prompt) in [
            (EditTarget::FollowCount, "check count (now 20)> "),
            (EditTarget::BulkPath, "domains file> "),
            (EditTarget::WatchAdd, "watch add> "),
        ] {
            app.input_mode = InputMode::Field {
                target,
                buf: "abc".into(),
            };
            let s = full_buf(&app, &theme);
            assert!(s.contains(&format!("{prompt}abc█")), "{target:?}");
        }
    }

    /// A lens error quotes the remote server: it was rendered raw and
    /// clipped at the panel edge.
    #[test]
    fn lens_errors_are_sanitized_and_wrapped() {
        let theme = Theme::frappe();
        let mut app = App::new(None);
        app.update(crate::tui::action::Msg::Data {
            lens: LensKey::Overview,
            gen: 0,
            result: Err(format!(
                "whois.example.test said \u{1b}[2J{} END",
                "x ".repeat(60)
            )),
        });
        let s = render_text(100, 30, |f| view(f, &app, &theme));
        assert!(!s.contains('\u{1b}'), "{s:?}");
        assert!(s.contains("END"), "the tail wraps into view: {s}");
    }

    /// Navigating onto a heavy lens says how to run it.
    #[test]
    fn a_heavy_lens_waits_for_enter() {
        let theme = Theme::frappe();
        let mut app = App::new(Some("example.com".into()));
        let _ = app.take_startup_actions();
        app.lens = LensKey::Takeover.index();
        let s = full_buf(&app, &theme);
        assert!(s.contains("press ↵ to run Takeover for example.com"), "{s}");
    }

    #[test]
    fn the_raw_view_scrolls() {
        use crate::payload::fixtures;
        use seer_core::RecordType;

        let theme = Theme::frappe();
        let mut app = App::new(None);
        app.lens = LensKey::Dns.index();
        app.update(crate::tui::action::Msg::Data {
            lens: LensKey::Dns,
            gen: 0,
            result: Ok(LensData::Dig(Box::new(fixtures::dig(
                RecordType::A,
                vec![fixtures::a("www.seer.test", "192.0.2.7")],
            )))),
        });
        app.format = seer_core::output::OutputFormat::Json;
        let top = render_text(100, 14, |f| view(f, &app, &theme));
        assert!(top.contains("\"status\": \"NOERROR\""), "{top}");
        app.raw_scroll = 6;
        let scrolled = render_text(100, 14, |f| view(f, &app, &theme));
        assert!(!scrolled.contains("\"status\": \"NOERROR\""), "{scrolled}");
    }

    #[test]
    fn loading_indicator_names_the_requested_target() {
        use crate::tui::action::Msg;
        use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};

        let theme = Theme::frappe();
        let mut app = App::new(Some("example.com".into()));
        let _ = app.take_startup_actions();
        let press = |app: &mut App, code: KeyCode| {
            let _ = app.update(Msg::Input(Event::Key(KeyEvent::new(
                code,
                KeyModifiers::NONE,
            ))));
        };
        press(&mut app, KeyCode::Char(':'));
        for c in "rdap 8.8.8.8".chars() {
            press(&mut app, KeyCode::Char(c));
        }
        press(&mut app, KeyCode::Enter);
        let s = full_buf(&app, &theme);
        assert!(s.contains("querying 8.8.8.8"), "not the session domain");
    }

    /// `r` swaps the DNS lens for the raw dig result: the JSON object the
    /// CLI's `seer dig --format json` prints.
    #[test]
    fn raw_view_shows_the_dig_result_object() {
        use crate::payload::fixtures;
        use seer_core::RecordType;

        let theme = Theme::frappe();
        let mut app = App::new(None);
        app.lens = lenses::find_by_cmd_or_key("dns").unwrap();
        app.update(crate::tui::action::Msg::Data {
            lens: LensKey::Dns,
            gen: 0,
            result: Ok(LensData::Dig(Box::new(fixtures::dig(
                RecordType::A,
                vec![fixtures::a("www.seer.test", "192.0.2.7")],
            )))),
        });
        let human = full_buf(&app, &theme);
        assert!(human.contains("● NOERROR"), "{human}");
        app.format = seer_core::output::OutputFormat::Json;
        let raw = full_buf(&app, &theme);
        assert!(raw.contains("Records · raw"), "{raw}");
        assert!(raw.contains("\"status\": \"NOERROR\""), "{raw}");
        assert!(raw.contains("\"address\": \"192.0.2.7\""), "{raw}");
    }

    #[test]
    fn shell_renders_without_panicking() {
        let theme = Theme::frappe();
        let app = App::new(None);
        let s = full_buf(&app, &theme);
        assert!(s.contains("seer"), "top-bar brand missing");
        assert!(s.contains("Overview"), "first lens label missing");
        assert!(s.contains("LOOKUP"), "group header missing");
    }

    /// Every canvas cell must carry the theme's base background: with Latte
    /// in a dark terminal, cells no widget paints otherwise keep the
    /// terminal's own background, rendering the theme as light bars floating
    /// on a dark canvas with near-invisible dark text.
    #[test]
    fn frame_canvas_is_painted_with_theme_base() {
        let mut app = App::new(None);
        assert!(app.set_theme_by_name("latte"));
        let buffer = render_buffer(100, 30, |f| view(f, &app, app.theme()));
        let latte = Theme::latte();
        // Main-pane interior and nav-column cells that no widget backfills.
        for (x, y) in [(60u16, 15u16), (2, 20)] {
            assert_eq!(buffer[(x, y)].bg, latte.base, "cell ({x},{y})");
        }
    }

    /// The help popup must stay theme-painted too: `Clear` resets its cells
    /// to the terminal default, so the overlay needs its own base fill or it
    /// renders as a hole of terminal-default color in the painted canvas.
    #[test]
    fn help_overlay_keeps_theme_base_background() {
        let mut app = App::new(None);
        assert!(app.set_theme_by_name("latte"));
        app.help = true;
        let buffer = render_buffer(100, 30, |f| view(f, &app, app.theme()));
        // Popup interior on a 100x30 frame (popup is 60x16 centered).
        assert_eq!(buffer[(50, 15)].bg, Theme::latte().base);
    }

    /// Draw with the App-owned theme (the call `mod.rs` makes each frame) and
    /// verify a live `:theme latte` swap actually recolors the frame.
    #[test]
    fn live_theme_swap_recolors_the_frame() {
        let top_bar_bg =
            |app: &App| render_buffer(100, 30, |f| view(f, app, app.theme()))[(0, 0)].bg;

        let mut app = App::new(None);
        assert_eq!(top_bar_bg(&app), Theme::frappe().mantle);

        assert!(app.set_theme_by_name("latte"));
        assert_eq!(top_bar_bg(&app), Theme::latte().mantle);
        assert_ne!(Theme::frappe().mantle, Theme::latte().mantle);
    }
}