tix-tracker 0.10.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
//! The Config mode surface (FR: board/column configuration, tui-config-mode).
//!
//! One sectioned view over the configuration areas — **dashboards**,
//! **cycles**, **milestones**, **types**, and **attributes** — reached with F12.
//! The surface is a three-level drill-down (tui-config-mode): the **section
//! rail** on the left, the active section's **index** beside it, and a selected
//! record's **detail** over the whole content area. `h`/`l` (and `←`/`→`) move
//! one level; `j`/`k` (and `↓`/`↑`) move inside the current level.
//!
//! The dashboards index lists every configured board; its detail is the former
//! settings modal's row list (column visibility checkboxes, the display toggles,
//! and the `$EDITOR` override). The cycles and milestones sections render the
//! same [`PlanningRow`]s the planning surface does, through the same
//! `rows_lines` helper, so the two surfaces cannot disagree.
//!
//! Like `filter_modal`, this widget is a **pure view + model**: it does not
//! read keys or mutate the config — the app routes keys and applies mutations
//! (`App::handle_settings_key`). It does record its click targets through
//! [`App::record_region`] so pointer hits run the same actions the keys do
//! (D3/D6).

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, Paragraph};

use crate::app::{Action, App};
use crate::keybindings::{EffectiveBindings, InputContext};
use crate::ui::planning::{PlanningRow, prompt_line, rows_lines};

/// Number of non-column rows in a dashboard's detail: the display settings
/// (title wrap toggle, line limit, ordering). The app uses this to size the
/// detail cursor and to route toggles; the widget uses it to render the rows.
pub const DISPLAY_ROWS: usize = 3;

/// Non-column rows beyond the display toggles: the `$EDITOR` override and the
/// read-only viewer, both `tix.toml` settings rather than per-record metadata
/// files.
pub const GENERAL_ROWS: usize = 2;

/// Every row in a dashboard's detail: the board's columns, the display
/// toggles, and the general settings.
pub fn board_rows_len(board: &crate::config::BoardConfiguration) -> usize {
    board.columns.len() + DISPLAY_ROWS + GENERAL_ROWS
}

/// The width of the section rail, in columns. Wide enough for the longest
/// label ("Attributes") plus the cursor and border.
pub const SECTION_RAIL_WIDTH: u16 = 21;

/// The body area to the right of the section rail, where a section's rows are
/// drawn. Shared by the renderer and the pointer-hit tests so the two never
/// compute different geometry.
pub fn config_body_rect(area: Rect) -> Rect {
    let rail = SECTION_RAIL_WIDTH.min(area.width);
    Rect {
        x: area.x + rail,
        width: area.width - rail,
        ..area
    }
}

/// One configuration section of the Config mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfigSection {
    /// Boards: columns, display toggles, and the editor override.
    #[default]
    Dashboards,
    /// Cycles, from `docs/cycles/` (or legacy `tix.toml`).
    Cycles,
    /// Milestones, from `docs/milestones/`.
    Milestones,
    /// The allowed issue `type:` values (`custom_types` in `tix.toml`).
    Types,
    /// The declared custom frontmatter keys (`[custom_attributes].keys`).
    CustomAttributes,
}

impl ConfigSection {
    /// The sections, in rail order.
    pub const ALL: [Self; 5] = [
        Self::Dashboards,
        Self::Cycles,
        Self::Milestones,
        Self::Types,
        Self::CustomAttributes,
    ];

    /// The rail label.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Dashboards => "Dashboards",
            Self::Cycles => "Cycles",
            Self::Milestones => "Milestones",
            Self::Types => "Types",
            Self::CustomAttributes => "Attributes",
        }
    }

    /// The next section, wrapping.
    pub fn next(self) -> Self {
        let index = self.index();
        Self::ALL[(index + 1) % Self::ALL.len()]
    }

    /// The previous section, wrapping.
    pub fn prev(self) -> Self {
        let index = self.index();
        Self::ALL[(index + Self::ALL.len() - 1) % Self::ALL.len()]
    }

    /// The section's position in the rail.
    pub const fn index(self) -> usize {
        match self {
            Self::Dashboards => 0,
            Self::Cycles => 1,
            Self::Milestones => 2,
            Self::Types => 3,
            Self::CustomAttributes => 4,
        }
    }

    /// Whether the section edits one of the two string lists (`Types` /
    /// `Attributes`) rather than a planning or board surface.
    pub const fn is_list(self) -> bool {
        matches!(self, Self::Types | Self::CustomAttributes)
    }
}

/// Which level of the Config mode's drill-down holds the focus.
///
/// The surface is a hierarchy: the **section rail** (`Sections`), the active
/// section's **index** of records (`Index`), and the selected record's
/// **detail** (`Detail`, drawn over the whole content area with the rail
/// hidden). `h`/`l` (and `←`/`→`) step one level; `j`/`k` (and `↓`/`↑`) move
/// inside the current level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfigLevel {
    /// The left rail: the sections (Dashboards / Cycles / Milestones / …).
    #[default]
    Sections,
    /// The active section's index of records.
    Index,
    /// The selected record's detail, over the whole content area.
    Detail,
}

impl ConfigLevel {
    /// The level's position on the vertical axis, top to bottom.
    pub const fn index(self) -> usize {
        match self {
            Self::Sections => 0,
            Self::Index => 1,
            Self::Detail => 2,
        }
    }

    /// The level one step deeper, clamped at [`ConfigLevel::Detail`].
    pub const fn deeper(self) -> Self {
        match self {
            Self::Sections => Self::Index,
            Self::Index | Self::Detail => Self::Detail,
        }
    }

    /// The level one step shallower, clamped at [`ConfigLevel::Sections`].
    pub const fn shallower(self) -> Self {
        match self {
            Self::Sections | Self::Index => Self::Sections,
            Self::Detail => Self::Index,
        }
    }
}

/// The dashboards section's data: the active board, its name, and the
/// `$EDITOR` override. Bundled so the render entry points stay within a sane
/// argument count.
#[derive(Debug, Clone, Copy)]
pub struct DashboardView<'a> {
    /// The active board's name.
    pub name: &'a str,
    /// The active board's configuration.
    pub board: &'a crate::config::BoardConfiguration,
    /// The configured editor override, if any.
    pub editor: Option<&'a str>,
    /// The Viewer row's label: the configured override, or the resolved auto
    /// viewer (tix #1507).
    pub viewer: &'a str,
}

/// An active inline prompt inside the Config mode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SettingsPrompt {
    /// Naming a new column (`a`).
    AddColumn(String),
    /// Naming a new board (`n`).
    NewBoard(String),
    /// Renaming the current board (`e`), seeded with its current name.
    RenameBoard {
        /// The board's current name.
        old: String,
        /// The in-progress new name.
        buffer: String,
    },
    /// Confirming deletion of the current board (`x`), naming how many issues
    /// reference it (always 0 today: nothing in issue frontmatter names a
    /// board, but the count is reported rather than assumed).
    ConfirmDeleteBoard {
        /// The board's name.
        name: String,
        /// Issues that reference the board (0 — see the variant docs).
        referencing: usize,
    },
    /// Setting the `$EDITOR` override in `tix.toml`.
    SetEditor(String),
    /// Setting the read-only `viewer` of the TUI's `v` key in `tix.toml`
    /// (tix #1507).
    SetViewer(String),
    /// Naming a new `custom_types` entry (`n` in the Types section).
    AddType(String),
    /// Naming a new `[custom_attributes].keys` entry (`n` in the Custom
    /// attributes section).
    AddAttribute(String),
}

impl SettingsPrompt {
    /// The single-line prompt text shown under the active section's rows.
    pub fn line(&self) -> String {
        match self {
            Self::AddColumn(buffer) => format!("New column: {buffer}_"),
            Self::NewBoard(buffer) => format!("New board: {buffer}_"),
            Self::RenameBoard { buffer, .. } => format!("Rename board to: {buffer}_"),
            Self::ConfirmDeleteBoard { name, referencing } => format!(
                "Delete board '{name}'? {referencing} {} reference it. [y/N]",
                crate::ui::planning::issues_word(*referencing)
            ),
            Self::SetEditor(buffer) => format!("Editor: {buffer}_"),
            Self::SetViewer(buffer) => format!("Viewer: {buffer}_"),
            Self::AddType(buffer) => format!("New type: {buffer}_"),
            Self::AddAttribute(buffer) => format!("New attribute: {buffer}_"),
        }
    }
}

/// The Config mode's cursor state: the active section, the drill-down level,
/// the index cursor (one row per record in the section), the dashboard detail
/// cursor, and an optional inline prompt.
#[derive(Debug, Clone, Default)]
pub struct SettingsModal {
    /// Row cursor within the active section's **index** (one row per board,
    /// cycle, milestone, type, or attribute).
    pub selected: usize,
    /// Row cursor within a dashboard's **detail** (a board's columns, then the
    /// display toggles, then the general rows).
    pub detail_selected: usize,
    /// Active inline prompt (None = browsing).
    pub prompt: Option<SettingsPrompt>,
    /// The active section.
    pub section: ConfigSection,
    /// Which level of the drill-down holds the focus.
    pub level: ConfigLevel,
}

impl SettingsModal {
    pub fn new() -> Self {
        Self::default()
    }

    /// Focus `level` (an `h`/`l` step, or a click on that level).
    pub fn focus(&mut self, level: ConfigLevel) {
        self.level = level;
    }

    /// Move the level focus `delta` levels along the vertical axis, clamped at
    /// the ends (`Sections` at the top, `Detail` at the bottom) rather than
    /// wrapping.
    pub fn move_level(&mut self, delta: isize) {
        let next = self.level.index() as isize + delta;
        self.level = match next {
            n if n <= 0 => ConfigLevel::Sections,
            1 => ConfigLevel::Index,
            _ => ConfigLevel::Detail,
        };
    }

    /// Switch to `section`, putting the index and detail cursors back at the
    /// top when the section changes (the cursors are per-section state).
    pub fn set_section(&mut self, section: ConfigSection) {
        if self.section != section {
            self.section = section;
            self.selected = 0;
            self.detail_selected = 0;
        }
    }

    /// Move the **index** cursor (clamped to `total_rows`).
    pub fn move_selected(&mut self, delta: isize, total_rows: usize) {
        if total_rows == 0 {
            self.selected = 0;
            return;
        }
        let next = self.selected as isize + delta;
        self.selected = next.clamp(0, total_rows as isize - 1) as usize;
    }

    /// Move the **detail** cursor (clamped to `total_rows`).
    pub fn move_detail(&mut self, delta: isize, total_rows: usize) {
        if total_rows == 0 {
            self.detail_selected = 0;
            return;
        }
        let next = self.detail_selected as isize + delta;
        self.detail_selected = next.clamp(0, total_rows as isize - 1) as usize;
    }

    /// Jump the index cursor straight to `row` (a row click, D6), clamped to
    /// the same range the arrow keys navigate.
    pub fn move_selected_to(&mut self, row: usize, total_rows: usize) {
        if total_rows == 0 {
            self.selected = 0;
            return;
        }
        self.selected = row.min(total_rows - 1);
    }

    /// Jump the detail cursor straight to `row` (a row click, D6), clamped to
    /// the same range the arrow keys navigate.
    pub fn move_detail_to(&mut self, row: usize, total_rows: usize) {
        if total_rows == 0 {
            self.detail_selected = 0;
            return;
        }
        self.detail_selected = row.min(total_rows - 1);
    }

    /// Render the board rows of the dashboards **detail**: the column
    /// checkboxes, the display toggles, the general rows, and the active
    /// prompt. Shared by the Config mode's dashboards detail and the widget's
    /// own tests.
    ///
    /// `focused` is whether the detail owns the Config mode's focus; the
    /// focused detail's border is accented and an unfocused one dimmed.
    pub fn render_body(
        &self,
        f: &mut Frame,
        rect: Rect,
        view: DashboardView<'_>,
        bindings: &EffectiveBindings,
        focused: bool,
    ) {
        let DashboardView {
            name: board_name,
            board,
            editor,
            viewer,
        } = view;
        let context = InputContext::Settings;
        let columns = &board.columns;
        let hidden = &board.hidden_columns;
        let wrap_titles = board.wrap_titles;
        let title_lines = board.title_lines;
        let order_by = board.order_by;
        let mut rows: Vec<Line> = Vec::new();

        for (i, col) in columns.iter().enumerate() {
            let is_hidden = hidden.iter().any(|h| h == col);
            let mark = if is_hidden { "[ ]" } else { "[x]" };
            let cursor = if i == self.detail_selected {
                "> "
            } else {
                "  "
            };
            let style = row_style(i == self.detail_selected);
            let hidden_suffix = if is_hidden { " (hidden)" } else { "" };
            rows.push(Line::from(vec![
                ratatui::text::Span::styled(cursor, style),
                ratatui::text::Span::styled(format!("{mark} {col}{hidden_suffix}"), style),
            ]));
        }

        let display_texts = [
            format!("Wrap titles: {}", if wrap_titles { "[x]" } else { "[ ]" }),
            format!("Title lines: {title_lines}"),
            format!("Order by: {}", order_by.as_str()),
            format!("Editor: {}", editor.unwrap_or("(default)")),
            format!("Viewer: {viewer}"),
        ];
        for (row, text) in display_texts.into_iter().enumerate() {
            let idx = columns.len() + row;
            let style = row_style(idx == self.detail_selected);
            let cursor = if idx == self.detail_selected {
                "> "
            } else {
                "  "
            };
            rows.push(Line::from(vec![
                ratatui::text::Span::styled(cursor, style),
                ratatui::text::Span::styled(text, style),
            ]));
        }

        if let Some(prompt) = &self.prompt {
            rows.push(Line::from(""));
            let line = prompt.line();
            rows.push(Line::from(ratatui::text::Span::styled(
                line,
                Style::default().fg(Color::Cyan),
            )));
        } else {
            rows.push(Line::from(""));
            rows.push(Line::from(ratatui::text::Span::styled(
                format!(
                    "{}: activate · {}: toggle · {}: new column · {} / {}: move column · {}: back · {}: close",
                    bindings.label(context, crate::keybindings::TuiAction::Submit),
                    bindings.label(context, crate::keybindings::TuiAction::Toggle),
                    bindings.label(context, crate::keybindings::TuiAction::AddColumn),
                    bindings.label(context, crate::keybindings::TuiAction::MoveColumnUp),
                    bindings.label(context, crate::keybindings::TuiAction::MoveColumnDown),
                    bindings.label(context, crate::keybindings::TuiAction::MoveLeft),
                    bindings.label(context, crate::keybindings::TuiAction::Close),
                ),
                Style::default().fg(Color::DarkGray),
            )));
        }

        let block = Block::default()
            .borders(Borders::ALL)
            .title(format!(" {board_name} — columns & display "))
            .style(pane_style(focused));
        let para = Paragraph::new(rows).block(block).style(Style::default());
        f.render_widget(para, rect);
    }
}

/// The rows of the dashboards index: every configured board's name and its
/// ordered column names, in configuration order.
pub fn dashboard_index_rows(config: &crate::config::Config) -> Vec<(String, String)> {
    config
        .configs()
        .map(|(name, board)| (name.to_string(), board.columns.join(" · ")))
        .collect()
}

fn row_style(selected: bool) -> Style {
    if selected {
        Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::White)
    }
}

/// A pane's border/title style: the focused pane is accented, the unfocused
/// one dimmed. The pane that owns the keys is visible at a glance, and the
/// focused pane's selected entry keeps the [`row_style`] cursor.
fn pane_style(focused: bool) -> Style {
    if focused {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::DarkGray)
    }
}

/// Render the Config mode: the section rail plus the active section's index,
/// or — at the dashboards detail level — the board's detail over the whole
/// content area. Records a click target per rail entry, index row, and detail
/// row so pointer hits run the same actions the keys do (D3/D6).
pub fn render_config(
    app: &App,
    f: &mut Frame,
    area: Rect,
    view: DashboardView<'_>,
    cycles: &[PlanningRow],
    milestones: &[PlanningRow],
) {
    let Some(modal) = app.settings.as_ref() else {
        return;
    };
    // The Milestones mode borrows this surface pinned to the milestones
    // section: registry on top, flat issue table below, the same table the
    // Cycle mode draws. It has no rail, so the registry owns the upper area.
    if app.milestone_mode {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Percentage(55), Constraint::Percentage(45)])
            .split(area);
        render_planning_section(app, f, chunks[0], "Milestones", milestones, true);
        render_milestone_issues(app, f, chunks[1]);
        return;
    }
    // A selected dashboard's detail owns the whole content area — the rail is
    // hidden so the editing surface gets the full width ("complete widget
    // screen space").
    if modal.level == ConfigLevel::Detail && modal.section == ConfigSection::Dashboards {
        modal.render_body(f, area, view, &app.bindings, true);
        for row in 0..board_rows_len(view.board) {
            app.record_region(body_row_rect(area, row), Action::ConfigDetailRow(row));
        }
        return;
    }
    render_section_rail(
        app,
        f,
        area,
        modal.section,
        modal.level == ConfigLevel::Sections,
    );
    let body = config_body_rect(area);
    let body_focused = modal.level == ConfigLevel::Index;
    match modal.section {
        ConfigSection::Dashboards => {
            let rows = dashboard_index_rows(&app.store.config);
            render_dashboard_index(app, f, body, &rows, body_focused);
        }
        ConfigSection::Cycles => {
            render_planning_section(app, f, body, "Cycles", cycles, body_focused);
        }
        ConfigSection::Milestones => {
            render_planning_section(app, f, body, "Milestones", milestones, body_focused);
        }
        ConfigSection::Types => {
            let rows = app.store.config.custom_types();
            render_list_section(app, f, body, "Types", &rows, body_focused);
        }
        ConfigSection::CustomAttributes => {
            // The effective attribute list: declared keys, or the built-in
            // attributes when none are declared (mirrors the Types section).
            let rows = app.store.config.attributes();
            render_list_section(app, f, body, "Attributes", &rows, body_focused);
        }
    }
}

/// Render the dashboards **index**: one row per configured board, showing its
/// name and its ordered columns. Records a click target per row
/// ([`Action::SettingsRow`]).
fn render_dashboard_index(
    app: &App,
    f: &mut Frame,
    body: Rect,
    rows: &[(String, String)],
    focused: bool,
) {
    let selected = app.settings.as_ref().map(|m| m.selected).unwrap_or(0);
    let prompt = app.settings.as_ref().and_then(|m| m.prompt.as_ref());
    let mut lines: Vec<Line> = Vec::new();
    if rows.is_empty() && prompt.is_none() {
        lines.push(Line::from("No dashboards configured — press n to add one."));
    } else {
        for (index, (name, columns)) in rows.iter().enumerate() {
            let style = row_style(index == selected);
            let cursor = if index == selected { "> " } else { "  " };
            lines.push(Line::from(vec![
                ratatui::text::Span::styled(cursor, style),
                ratatui::text::Span::styled(format!("{name:<18}"), style),
                ratatui::text::Span::styled(columns.clone(), Style::default().fg(Color::DarkGray)),
            ]));
        }
    }
    lines.push(Line::from(""));
    match prompt {
        Some(prompt) => lines.push(Line::from(ratatui::text::Span::styled(
            prompt.line(),
            Style::default().fg(Color::Cyan),
        ))),
        None => lines.push(Line::from(ratatui::text::Span::styled(
            format!(
                "{}: open detail · {}: new board · {}: rename board · {}: delete board · {}: switch board · {}: close",
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::MoveRight
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::NewBoard
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::EditPlanningItem
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::Delete
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::NextBoard
                ),
                app.bindings
                    .label(InputContext::Settings, crate::keybindings::TuiAction::Close),
            ),
            Style::default().fg(Color::DarkGray),
        ))),
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Dashboards — {} boards ", rows.len()))
        .style(pane_style(focused));
    f.render_widget(Paragraph::new(lines).block(block), body);
    for index in 0..rows.len() {
        app.record_region(body_row_rect(body, index), Action::SettingsRow(index));
    }
}

/// Render one of the Config mode's string-list sections (`Types` / `Custom
/// attributes`): one row per entry with the same cursor affordance the
/// dashboards rows use, an inline prompt when one is active, and a key hint
/// line. Records a click target per row.
fn render_list_section(
    app: &App,
    f: &mut Frame,
    body: Rect,
    title: &str,
    rows: &[String],
    focused: bool,
) {
    let (selected, prompt) = app
        .settings
        .as_ref()
        .map(|modal| (modal.selected, modal.prompt.as_ref()))
        .unwrap_or((0, None));
    let mut lines: Vec<Line> = Vec::new();
    if rows.is_empty() && prompt.is_none() {
        lines.push(Line::from(format!(
            "No {title} configured — press n to add one."
        )));
    } else {
        for (index, row) in rows.iter().enumerate() {
            let cursor = if index == selected { "> " } else { "  " };
            let style = row_style(index == selected);
            lines.push(Line::from(vec![
                ratatui::text::Span::styled(cursor, style),
                ratatui::text::Span::styled(row.clone(), style),
            ]));
        }
    }
    lines.push(Line::from(""));
    match prompt {
        Some(prompt) => lines.push(Line::from(ratatui::text::Span::styled(
            prompt.line(),
            Style::default().fg(Color::Cyan),
        ))),
        None => lines.push(Line::from(ratatui::text::Span::styled(
            format!(
                "{}: new · {}: remove selected · {} / {}: level · {}: close",
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::NewBoard
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::Delete
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::MoveLeft
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::MoveRight
                ),
                app.bindings
                    .label(InputContext::Settings, crate::keybindings::TuiAction::Close),
            ),
            Style::default().fg(Color::DarkGray),
        ))),
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" {title} — {} items ", rows.len()))
        .style(pane_style(focused));
    f.render_widget(Paragraph::new(lines).block(block), body);
    for index in 0..rows.len() {
        app.record_region(body_row_rect(body, index), Action::ConfigListRow(index));
    }
}

/// The click target of row `row`: the body's first inner line is row 0, exactly
/// where the row lists are drawn.
fn body_row_rect(body: Rect, row: usize) -> Rect {
    Rect {
        x: body.x + 1,
        y: body.y + 1 + row as u16,
        width: body.width.saturating_sub(2),
        height: 1,
    }
}

/// The section rail: the sections as a vertical list, the active one
/// highlighted, each entry a click target. `focused` accents the rail's border
/// when it holds the Config mode's focus.
fn render_section_rail(app: &App, f: &mut Frame, area: Rect, active: ConfigSection, focused: bool) {
    let rail = Rect {
        width: SECTION_RAIL_WIDTH.min(area.width),
        ..area
    };
    let mut lines: Vec<Line> = Vec::new();
    for section in ConfigSection::ALL {
        let style = if section == active {
            row_style(true)
        } else if app.is_hovered(&Action::ConfigSection(section)) {
            // Hover highlight only — the active section is untouched.
            Style::default()
                .fg(Color::Black)
                .bg(Color::DarkGray)
                .add_modifier(Modifier::BOLD)
        } else {
            row_style(false)
        };
        let cursor = if section == active { "> " } else { "  " };
        lines.push(Line::from(vec![
            ratatui::text::Span::styled(cursor, style),
            ratatui::text::Span::styled(section.label(), style),
        ]));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Sections ")
        .style(pane_style(focused));
    f.render_widget(Paragraph::new(lines).block(block), rail);
    for section in ConfigSection::ALL {
        let hit = Rect {
            x: rail.x + 1,
            y: rail.y + 1 + section.index() as u16,
            width: rail.width.saturating_sub(2),
            height: 1,
        };
        app.record_region(hit, Action::ConfigSection(section));
    }
}

/// Render one of the Config mode's planning sections (cycles or milestones):
/// the same rows and prompt the planning surface draws, plus this mode's key
/// hints. Records a click target per row. `focused` accents the border when the
/// body pane holds the Config mode's focus.
fn render_planning_section(
    app: &App,
    f: &mut Frame,
    body: Rect,
    label: &str,
    rows: &[PlanningRow],
    focused: bool,
) {
    let selected = app.planning.as_ref().map(|p| p.selected).unwrap_or(0);
    let prompt = app.planning.as_ref().and_then(|p| p.prompt.as_ref());
    let inner = body.height.saturating_sub(2) as usize;
    let view_h = inner.saturating_sub(2);

    let mut lines: Vec<Line> = Vec::new();
    if rows.is_empty() {
        if prompt.is_none() {
            lines.push(Line::from(format!(
                "No {} yet — press n to create one.",
                label.to_lowercase()
            )));
        }
    } else {
        lines.extend(rows_lines(rows, selected, view_h));
    }
    lines.push(Line::from(""));
    match prompt {
        Some(prompt) => lines.push(prompt_line(prompt)),
        None => lines.push(Line::from(ratatui::text::Span::styled(
            format!(
                "{}: new · {}: open/edit · {}: delete · {}: open detail · {} / {}: level · {}: close",
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::NewBoard
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::EditPlanningItem
                ),
                // `delete` is the bound action in this context (x / Shift+X).
                // `delete_planning_item` is the planning surface's own name for the
                // same key and is not bound here, so its label would be "—".
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::Delete
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::Submit
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::MoveLeft
                ),
                app.bindings.label(
                    InputContext::Settings,
                    crate::keybindings::TuiAction::MoveRight
                ),
                app.bindings
                    .label(InputContext::Settings, crate::keybindings::TuiAction::Close),
            ),
            Style::default().fg(Color::DarkGray),
        ))),
    }

    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" {label} — {} items ", rows.len()))
        .style(pane_style(focused));
    f.render_widget(Paragraph::new(lines).block(block), body);
    // Rows are drawn from the body's first inner line, so a click on row `i`
    // resolves to `ConfigPlanningRow(i)` — the same index the cursor uses.
    for i in 0..rows.len() {
        app.record_region(body_row_rect(body, i), Action::ConfigPlanningRow(i));
    }
}

/// The focused milestone's flat issue table, drawn by the F5 Milestones mode
/// beneath the registry — the same shared table the Cycle mode draws.
///
/// The name comes from [`App::active_milestone_name`], so the table cannot
/// list one milestone while the rail bolds another.
fn render_milestone_issues(app: &App, f: &mut Frame, area: Rect) {
    let (title, rows) = match app.active_milestone_name() {
        Some(name) => (
            format!("issues — {name}"),
            crate::ui::issue_table::milestone_rows(&app.store, &name),
        ),
        None => ("issues".to_string(), Vec::new()),
    };
    crate::ui::issue_table::render(app, f, area, &title, &rows);
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    /// Draw the dashboard detail over a full 80x24 area and return the
    /// terminal, so a test can inspect the buffer.
    fn draw(
        modal: &SettingsModal,
        board: &crate::config::BoardConfiguration,
        w: u16,
        h: u16,
    ) -> Terminal<TestBackend> {
        draw_focused(modal, board, w, h, false)
    }

    /// [`draw`], with the detail's focus flag under test's control.
    fn draw_focused(
        modal: &SettingsModal,
        board: &crate::config::BoardConfiguration,
        w: u16,
        h: u16,
        focused: bool,
    ) -> Terminal<TestBackend> {
        let backend = TestBackend::new(w, h);
        let mut terminal = Terminal::new(backend).unwrap();
        let bindings =
            crate::keybindings::KeyBindings::resolve(&crate::keybindings::KeyBindings::default())
                .expect("built-in bindings are valid");
        terminal
            .draw(|f| {
                modal.render_body(
                    f,
                    f.area(),
                    DashboardView {
                        name: "default",
                        board,
                        editor: None,
                        viewer: "mdterm (auto)",
                    },
                    &bindings,
                    focused,
                );
            })
            .unwrap();
        terminal
    }

    fn rows_of(terminal: &Terminal<TestBackend>) -> Vec<String> {
        let buffer = terminal.backend().buffer();
        (0..buffer.area().height)
            .map(|y| {
                (0..buffer.area().width)
                    .map(|x| buffer[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect()
            })
            .collect()
    }

    fn test_board() -> crate::config::BoardConfiguration {
        crate::config::BoardConfiguration {
            columns: vec!["todo".to_string(), "done".to_string()],
            hidden_columns: vec!["done".to_string()],
            ..Default::default()
        }
    }

    fn render_smoke(prompt: Option<SettingsPrompt>, w: u16, h: u16) {
        let modal = SettingsModal {
            detail_selected: 1,
            prompt,
            ..SettingsModal::default()
        };
        let _ = draw(&modal, &test_board(), w, h);
    }

    #[test]
    fn renders_display_rows_after_columns() {
        let modal = SettingsModal {
            detail_selected: 2,
            prompt: None,
            ..SettingsModal::default()
        };
        let board = crate::config::BoardConfiguration {
            columns: vec!["todo".to_string(), "done".to_string()],
            hidden_columns: vec![],
            wrap_titles: false,
            title_lines: 5,
            order_by: crate::config::OrderBy::None,
            ..Default::default()
        };
        let terminal = draw(&modal, &board, 80, 24);
        let buffer = terminal.backend().buffer();
        let rows = rows_of(&terminal);

        let row_of =
            |needle: &str| -> Option<usize> { rows.iter().position(|r| r.contains(needle)) };

        let wrap_row = row_of("Wrap titles: [ ]").expect("wrap row shows unchecked mark");
        let lines_row = row_of("Title lines: 5").expect("line-limit row shows the value");
        let order_row = row_of("Order by: none").expect("ordering row shows the value");
        let editor_row = row_of("Editor: (default)").expect("general row shows the editor");
        let viewer_row = row_of("Viewer: mdterm (auto)").expect("general row shows the viewer");
        assert!(
            wrap_row < lines_row
                && lines_row < order_row
                && order_row < editor_row
                && editor_row < viewer_row,
            "display and general rows render beneath the columns in order"
        );

        // The selected display row (detail_selected=2 → first display row) is highlighted.
        assert!(
            rows[wrap_row].contains('>'),
            "selected display row shows the cursor: {:?}",
            rows[wrap_row]
        );
        assert!(
            !rows[lines_row].contains('>'),
            "unselected display row has no cursor: {:?}",
            rows[lines_row]
        );
        let selection_x = rows[wrap_row].find('>').expect("cursor sits in the row") as u16;
        let selected = &buffer[(selection_x + 2, wrap_row as u16)];
        assert_eq!(selected.fg, Color::Yellow, "selected row gets cursor style");
    }

    #[test]
    fn renders_at_80x24() {
        render_smoke(None, 80, 24);
    }

    #[test]
    fn renders_prompt_at_80x24() {
        render_smoke(Some(SettingsPrompt::AddColumn("".into())), 80, 24);
    }

    #[test]
    fn renders_rename_and_delete_prompts_at_80x24() {
        render_smoke(
            Some(SettingsPrompt::RenameBoard {
                old: "default".into(),
                buffer: "ops".into(),
            }),
            80,
            24,
        );
        render_smoke(
            Some(SettingsPrompt::ConfirmDeleteBoard {
                name: "default".into(),
                referencing: 0,
            }),
            80,
            24,
        );
        render_smoke(Some(SettingsPrompt::SetEditor("nvim".into())), 80, 24);
        render_smoke(Some(SettingsPrompt::SetViewer("less".into())), 80, 24);
    }

    #[test]
    fn renders_at_tiny_20x5() {
        render_smoke(None, 20, 5);
    }

    #[test]
    fn move_selected_clamps_within_columns() {
        let mut modal = SettingsModal::new();
        modal.move_selected(-1, 3);
        assert_eq!(modal.selected, 0);
        modal.move_selected(5, [0usize, 1, 2, 3].len());
        assert_eq!(modal.selected, 3);
        modal.move_selected(1, 0);
        assert_eq!(modal.selected, 0);
    }

    #[test]
    fn move_detail_clamps_within_rows() {
        let mut modal = SettingsModal::new();
        modal.move_detail(-1, 4);
        assert_eq!(modal.detail_selected, 0);
        modal.move_detail(9, 4);
        assert_eq!(modal.detail_selected, 3);
        modal.move_detail(1, 0);
        assert_eq!(modal.detail_selected, 0);
    }

    #[test]
    fn defaults_to_first_row() {
        assert_eq!(SettingsModal::new().selected, 0);
        assert_eq!(SettingsModal::new().detail_selected, 0);
        assert_eq!(SettingsModal::new().prompt, None);
        assert_eq!(SettingsModal::new().section, ConfigSection::Dashboards);
        assert_eq!(SettingsModal::new().level, ConfigLevel::Sections);
    }

    #[test]
    fn sections_cycle_in_both_directions_and_wrap() {
        assert_eq!(ConfigSection::Dashboards.next(), ConfigSection::Cycles);
        assert_eq!(ConfigSection::Cycles.next(), ConfigSection::Milestones);
        assert_eq!(ConfigSection::Milestones.next(), ConfigSection::Types);
        assert_eq!(ConfigSection::Types.next(), ConfigSection::CustomAttributes);
        assert_eq!(
            ConfigSection::CustomAttributes.next(),
            ConfigSection::Dashboards
        );
        assert_eq!(
            ConfigSection::Dashboards.prev(),
            ConfigSection::CustomAttributes
        );
        assert_eq!(ConfigSection::CustomAttributes.prev(), ConfigSection::Types);
        assert_eq!(ConfigSection::ALL.len(), 5);
        // The section is labelled "Attributes", not "Custom attributes".
        assert_eq!(ConfigSection::CustomAttributes.label(), "Attributes");
    }

    #[test]
    fn set_section_resets_the_cursors_only_on_a_change() {
        let mut modal = SettingsModal {
            selected: 2,
            detail_selected: 1,
            ..SettingsModal::default()
        };
        modal.set_section(ConfigSection::Cycles);
        assert_eq!(modal.selected, 0);
        assert_eq!(modal.detail_selected, 0);
        modal.selected = 1;
        modal.detail_selected = 2;
        modal.set_section(ConfigSection::Cycles);
        assert_eq!(
            modal.selected, 1,
            "re-selecting the same section keeps the index cursor"
        );
        assert_eq!(
            modal.detail_selected, 2,
            "re-selecting the same section keeps the detail cursor"
        );
    }

    #[test]
    fn board_rows_len_counts_columns_display_and_general_rows() {
        let board = crate::config::BoardConfiguration {
            columns: vec!["todo".into(), "done".into()],
            ..Default::default()
        };
        assert_eq!(board_rows_len(&board), 2 + DISPLAY_ROWS + GENERAL_ROWS);
    }

    #[test]
    fn dashboard_index_rows_list_every_board_with_its_columns() {
        let mut config = crate::config::Config::default();
        config.kanban.configurations.clear();
        config
            .kanban
            .configurations
            .insert("default".into(), crate::config::starter_board());
        let ops = crate::config::BoardConfiguration {
            columns: vec!["backlog".into(), "shipped".into()],
            ..Default::default()
        };
        config.kanban.configurations.insert("ops".into(), ops);

        let rows = dashboard_index_rows(&config);
        assert_eq!(rows.len(), 2, "every configured board is listed: {rows:?}");
        let (_, columns) = rows
            .iter()
            .find(|(name, _)| name == "ops")
            .expect("the `ops` board is listed");
        assert!(
            columns.contains("backlog") && columns.contains("shipped"),
            "the row shows the board's columns: {columns}"
        );
    }

    #[test]
    fn level_focus_defaults_to_the_section_rail() {
        let modal = SettingsModal::new();
        assert_eq!(modal.level, ConfigLevel::Sections);
        assert_eq!(ConfigLevel::Sections.index(), 0);
        assert_eq!(ConfigLevel::Index.index(), 1);
        assert_eq!(ConfigLevel::Detail.index(), 2);
    }

    #[test]
    fn move_level_clamps_at_both_ends() {
        let mut modal = SettingsModal::new();
        modal.move_level(1);
        assert_eq!(modal.level, ConfigLevel::Index);
        modal.move_level(1);
        assert_eq!(modal.level, ConfigLevel::Detail);
        modal.move_level(1);
        assert_eq!(modal.level, ConfigLevel::Detail, "the bottom end clamps");
        modal.move_level(-1);
        assert_eq!(modal.level, ConfigLevel::Index);
        modal.move_level(-1);
        assert_eq!(modal.level, ConfigLevel::Sections);
        modal.move_level(-1);
        assert_eq!(modal.level, ConfigLevel::Sections, "the top end clamps");
        modal.focus(ConfigLevel::Detail);
        assert_eq!(modal.level, ConfigLevel::Detail);
    }

    #[test]
    fn focused_detail_border_is_rendered_distinctly() {
        let board = test_board();
        let modal = SettingsModal::new();
        let focused = draw_focused(&modal, &board, 80, 24, true);
        let unfocused = draw_focused(&modal, &board, 80, 24, false);
        let rect = focused.backend().buffer().area;
        let border = |term: &Terminal<TestBackend>| term.backend().buffer()[(rect.x, rect.y)].fg;
        assert_eq!(
            border(&focused),
            Color::Yellow,
            "the focused detail's border is accented"
        );
        assert_eq!(
            border(&unfocused),
            Color::DarkGray,
            "the unfocused detail's border is dimmed"
        );
        assert_ne!(border(&focused), border(&unfocused));
    }
}