tix-tracker 0.7.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
//! The Config mode surface (FR: board/column configuration, tui-config-mode).
//!
//! One sectioned view over the three configuration areas — **dashboards**,
//! **cycles**, and **milestones** — reached with F12. The dashboards section 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, Clear, 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 the dashboards section: the display settings
/// (title wrap toggle, line limit, ordering). The app uses this to size the
/// browse 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 the dashboards section: 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 of the Config mode's two panes holds the focus.
///
/// The surface is the standard two-pane shape: the **section rail** on the
/// left and the active section's **body** on the right. `h`/`l` (and
/// `←`/`→`) move the focus between them, clamped at the ends; `j`/`k` (and
/// `↓`/`↑`) move inside whichever pane is focused — the selected section in
/// the rail, the row cursor in the body.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfigPane {
    /// The left rail: the sections (Dashboards / Cycles / Milestones).
    #[default]
    Sections,
    /// The right body: the active section's rows.
    Body,
}

impl ConfigPane {
    /// The pane's position on the horizontal axis, left to right.
    pub const fn index(self) -> usize {
        match self {
            Self::Sections => 0,
            Self::Body => 1,
        }
    }
}

/// 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 focused pane, the
/// dashboards row cursor, and an optional inline prompt.
#[derive(Debug, Clone, Default)]
pub struct SettingsModal {
    /// Row cursor within the dashboards section (a board's columns, then the
    /// display toggles, then the general rows).
    pub selected: usize,
    /// Active inline prompt (None = browsing the checkbox list).
    pub prompt: Option<SettingsPrompt>,
    /// The active section.
    pub section: ConfigSection,
    /// Which pane holds the focus (the section rail or the body).
    pub pane: ConfigPane,
}

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

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

    /// Move the pane focus `delta` panes along the horizontal axis, clamped at
    /// the ends (`Sections` on the left, `Body` on the right) rather than
    /// wrapping — the same rule the board's columns follow.
    pub fn move_pane(&mut self, delta: isize) {
        let next = self.pane.index() as isize + delta;
        self.pane = if next <= 0 {
            ConfigPane::Sections
        } else {
            ConfigPane::Body
        };
    }

    /// Switch to `section`, putting the dashboards cursor back at the top when
    /// the section changes (the cursor is per-section state).
    pub fn set_section(&mut self, section: ConfigSection) {
        if self.section != section {
            self.section = section;
            self.selected = 0;
        }
    }

    /// Move the row cursor (clamped to `total_rows`, i.e. the board's columns
    /// plus [`DISPLAY_ROWS`] and [`GENERAL_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;
    }

    /// Jump the row 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);
    }

    /// Render the dashboards rows into `rect`: the column checkboxes, the
    /// display toggles, the general rows, and the active prompt. Shared by the
    /// Config mode's dashboards section and the widget's own tests.
    ///
    /// `focused` is whether the body pane holds the Config mode's focus; the
    /// focused pane's border is accented and the other pane's is dimmed, so the
    /// two panes read apart at a glance.
    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.selected { "> " } else { "  " };
            let style = row_style(i == self.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.selected);
            let cursor = if idx == self.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!(
                    "{}: toggle · {}: new column · {}: activate row · {}: new board · {}: rename board · {}: delete board · {}: switch board · {} / {}: pane · {}: close",
                    bindings.label(context, crate::keybindings::TuiAction::Toggle),
                    bindings.label(context, crate::keybindings::TuiAction::AddColumn),
                    bindings.label(context, crate::keybindings::TuiAction::Submit),
                    bindings.label(context, crate::keybindings::TuiAction::NewBoard),
                    bindings.label(context, crate::keybindings::TuiAction::EditPlanningItem),
                    bindings.label(context, crate::keybindings::TuiAction::Delete),
                    bindings.label(context, crate::keybindings::TuiAction::NextBoard),
                    bindings.label(context, crate::keybindings::TuiAction::MoveLeft),
                    bindings.label(context, crate::keybindings::TuiAction::MoveRight),
                    bindings.label(context, crate::keybindings::TuiAction::Close),
                ),
                Style::default().fg(Color::DarkGray),
            )));
        }

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

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 on the left and the active
/// section's body to its right. Records a click target per rail entry and per
/// body 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;
    };
    let body_focused = modal.pane == ConfigPane::Body;
    // The Milestones mode borrows this surface pinned to the milestones section;
    // in it the section rail is hidden and the body owns the whole area, so the
    // F5 mode reads as its own view rather than "Config with one section".
    let body = if app.milestone_mode {
        area
    } else {
        render_section_rail(
            app,
            f,
            area,
            modal.section,
            modal.pane == ConfigPane::Sections,
        );
        config_body_rect(area)
    };
    match modal.section {
        ConfigSection::Dashboards => {
            modal.render_body(f, body, view, &app.bindings, body_focused);
            for row in 0..board_rows_len(view.board) {
                app.record_region(body_row_rect(body, row), Action::SettingsRow(row));
            }
        }
        ConfigSection::Cycles => {
            render_planning_section(app, f, body, "Cycles", cycles, body_focused);
        }
        ConfigSection::Milestones => {
            if app.milestone_mode {
                // The F5 mode shows the focused milestone's issues beneath the
                // registry: registry on top, flat issue table below, the same
                // table the Cycle mode draws.
                let chunks = Layout::default()
                    .direction(Direction::Vertical)
                    .constraints([Constraint::Percentage(55), Constraint::Percentage(45)])
                    .split(body);
                render_planning_section(app, f, chunks[0], "Milestones", milestones, body_focused);
                render_milestone_issues(app, f, chunks[1]);
            } else {
                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);
        }
        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);
        }
    }
}

/// 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]) {
    let (selected, prompt, focused) = app
        .settings
        .as_ref()
        .map(|modal| {
            (
                modal.selected,
                modal.prompt.as_ref(),
                modal.pane == ConfigPane::Body,
            )
        })
        .unwrap_or((0, None, false));
    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 · {} / {}: pane · {}: 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 dashboards row `row`: the body's first inner line is row
/// 0, exactly where [`SettingsModal::render_body`] draws it.
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 three 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 · {}: edit · {}: delete · {}: activate row · {} / {}: pane · {}: 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 crate::ui::modal::modal_rect;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    /// Draw the dashboards body in the old centered modal geometry 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 body's pane-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,
                    modal_rect(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 {
            selected: 1,
            prompt,
            ..SettingsModal::default()
        };
        let _ = draw(&modal, &test_board(), w, h);
    }

    #[test]
    fn renders_display_rows_after_columns() {
        let modal = SettingsModal {
            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 (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 defaults_to_first_row() {
        assert_eq!(SettingsModal::new().selected, 0);
        assert_eq!(SettingsModal::new().prompt, None);
        assert_eq!(SettingsModal::new().section, ConfigSection::Dashboards);
    }

    #[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_row_cursor_only_on_a_change() {
        let mut modal = SettingsModal {
            selected: 2,
            ..SettingsModal::default()
        };
        modal.set_section(ConfigSection::Cycles);
        assert_eq!(modal.selected, 0);
        modal.selected = 1;
        modal.set_section(ConfigSection::Cycles);
        assert_eq!(
            modal.selected, 1,
            "re-selecting the same section keeps the 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 pane_focus_defaults_to_the_section_rail() {
        let modal = SettingsModal::new();
        assert_eq!(modal.pane, ConfigPane::Sections);
        assert_eq!(ConfigPane::Sections.index(), 0);
        assert_eq!(ConfigPane::Body.index(), 1);
    }

    #[test]
    fn move_pane_clamps_at_both_ends() {
        let mut modal = SettingsModal::new();
        modal.move_pane(1);
        assert_eq!(modal.pane, ConfigPane::Body);
        modal.move_pane(1);
        assert_eq!(modal.pane, ConfigPane::Body, "the right end clamps");
        modal.move_pane(-1);
        assert_eq!(modal.pane, ConfigPane::Sections);
        modal.move_pane(-1);
        assert_eq!(modal.pane, ConfigPane::Sections, "the left end clamps");
        modal.focus(ConfigPane::Body);
        assert_eq!(modal.pane, ConfigPane::Body);
    }

    #[test]
    fn focused_pane_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 = modal_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 pane's border is accented"
        );
        assert_eq!(
            border(&unfocused),
            Color::DarkGray,
            "the unfocused pane's border is dimmed"
        );
        assert_ne!(border(&focused), border(&unfocused));
    }
}