mnml-rs 0.2.14

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! Settings overlay renderer. Paints a centered bordered overlay
//! showing every `SettingItem` from `app::settings::build_settings`
//! — section headers as `── <name> ──`, rows as
//! `▸ <label>:  [active] / other  *`. See the "Family settings UI
//! convention" in CLAUDE.md.
//!
//! Sizing: overlay takes ~60% of the screen width (clamped 60..=120)
//! and ~70% of the height (clamped 20..=60). Scrolls when the row
//! list exceeds the visible area.

use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph};

use crate::app::App;
use crate::app::settings::{RESET_ALL_KEY, SettingItem};
use crate::ui::theme;

/// Compute the overlay rect — centered, ~60% width × ~70% height,
/// clamped to comfortable terminal sizes.
fn overlay_rect(parent: Rect) -> Rect {
    let w = ((parent.width as f32) * 0.6) as u16;
    let w = w.clamp(60, 120).min(parent.width.saturating_sub(4));
    let h = ((parent.height as f32) * 0.7) as u16;
    let h = h.clamp(20, 60).min(parent.height.saturating_sub(4));
    Rect {
        x: parent.x + (parent.width.saturating_sub(w)) / 2,
        y: parent.y + (parent.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    }
}

/// Paint the settings overlay. No-op when the overlay is closed.
pub fn draw(frame: &mut Frame, app: &mut App, parent: Rect) {
    // Clear stale hit-test rects every frame whether or not the
    // overlay is open — they'd otherwise survive between opens.
    app.rects.settings_overlay_rect = None;
    app.rects.settings_rows.clear();
    app.rects.settings_row_options.clear();
    // qa-7th code-review W-4 2026-06-30 — clear Save/Cancel chip
    // rects too so the mouse handler can't pick up stale coords.
    app.rects.settings_save_button = None;
    app.rects.settings_cancel_button = None;
    if app.settings_overlay.is_none() {
        return;
    }
    let area = overlay_rect(parent);
    app.rects.settings_overlay_rect = Some(area);
    let t = theme::cur();

    // Solid background — Clear wipes whatever the editor painted underneath.
    frame.render_widget(Clear, area);

    // Outer block — title "Settings", blue bg / dark fg accent chip.
    // Version chip on the title bar's right edge so the user can
    // match what they're running against the release tag /
    // changelog. 2026-06-08 family-wide ask.
    let version_title = concat!(" v", env!("CARGO_PKG_VERSION"), " ");
    let block = crate::ui::design_tokens::modal_panel("Settings").title_top(
        ratatui::text::Line::from(Span::styled(
            version_title,
            Style::default().fg(t.comment).add_modifier(Modifier::DIM),
        ))
        .right_aligned(),
    );
    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Row 0 of the inner area is the filter input — `/` focuses, chars
    // type, Esc clears. Sits above the settings list; the rest of the
    // rendered rows shift down by 1.
    let filter_focused = app
        .settings_overlay
        .as_ref()
        .is_some_and(|s| s.filter_focused);
    let filter_text = app
        .settings_overlay
        .as_ref()
        .map(|s| s.filter.clone())
        .unwrap_or_default();
    let filter_display = if filter_text.is_empty() {
        if filter_focused {
            "type to filter…".to_string()
        } else {
            "/ filter".to_string()
        }
    } else {
        filter_text.clone()
    };
    let filter_fg = if !filter_text.is_empty() {
        t.fg
    } else if filter_focused {
        t.cyan
    } else {
        t.comment
    };
    let cursor = if filter_focused { "" } else { "" };
    let search_glyph = if app.config.ui.ascii_icons {
        "/"
    } else {
        "\u{f002}"
    };
    let filter_row_rect = Rect {
        x: inner.x,
        y: inner.y,
        width: inner.width,
        height: 1,
    };
    // mouse-round-12 SEV-2 F3 2026-07-14 — register the filter row
    // as a click target so mouse-first users can focus it without
    // needing to press `/` on the keyboard.
    app.rects.settings_filter_row = Some(filter_row_rect);
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(
                format!(" {search_glyph} "),
                Style::default().fg(t.comment).bg(t.bg_dark),
            ),
            Span::styled(filter_display, Style::default().fg(filter_fg).bg(t.bg_dark)),
            Span::styled(cursor, Style::default().fg(t.cyan).bg(t.bg_dark)),
        ])),
        filter_row_rect,
    );
    // Body area for the settings list — starts one row below.
    let body_area = Rect {
        x: inner.x,
        y: inner.y + 1,
        width: inner.width,
        height: inner.height.saturating_sub(1),
    };

    // Build rows + paint. Uses the app-side filtered projection so
    // `selected_row` maps 1:1 to the visible list.
    let items = app.filtered_settings_items();
    let selected = app
        .settings_overlay
        .as_ref()
        .map(|s| s.selected_row)
        .unwrap_or(0);

    // Find the `items`-level index of the focused row (skipping section
    // headers, which selected_row doesn't count).
    let mut row_counter = 0usize;
    let mut focused_item_idx: Option<usize> = None;
    for (i, item) in items.iter().enumerate() {
        if item.is_row() {
            if row_counter == selected {
                focused_item_idx = Some(i);
                break;
            }
            row_counter += 1;
        }
    }

    // Build rendered lines. We keep a parallel `line_row_counter`
    // vector so the windowing loop below can map a visible line back
    // to its 0-based row index — what `settings_move_row` /
    // `apply_setting` use. Section headers get `None`.
    //
    // Also track per-option column ranges within each row so the
    // click handler can jump-to-value instead of just cycling. Each
    // entry: (row_counter_idx, option_idx, col_start, col_end) with
    // columns relative to the start of the row line.
    // vscode-user-mouse SEV-2 2026-07-10.
    let mut lines: Vec<Line<'static>> = Vec::with_capacity(items.len());
    let mut line_row_counter: Vec<Option<usize>> = Vec::with_capacity(items.len());
    let mut option_col_ranges: Vec<(usize, usize, usize, usize)> = Vec::new();
    let mut rc = 0usize;
    for (i, item) in items.iter().enumerate() {
        match item {
            SettingItem::Section(name) => {
                lines.push(Line::from(Span::styled(
                    format!("── {name} ──"),
                    Style::default()
                        .fg(t.comment)
                        .add_modifier(Modifier::BOLD | Modifier::DIM),
                )));
                line_row_counter.push(None);
            }
            SettingItem::Row(row) => {
                let is_focused = Some(i) == focused_item_idx;
                let marker = if is_focused { "" } else { "  " };

                let mut spans = vec![
                    Span::styled(
                        marker,
                        Style::default().fg(if is_focused { t.blue } else { t.bg2 }),
                    ),
                    Span::styled(
                        format!("{:30}  ", row.label),
                        Style::default().fg(if is_focused { t.fg } else { t.comment }),
                    ),
                ];

                if row.key == RESET_ALL_KEY {
                    // Sentinel row — paint a red-tinted "Enter to reset" hint.
                    spans.push(Span::styled(
                        "(Enter to reset)",
                        Style::default().fg(t.red).add_modifier(if is_focused {
                            Modifier::BOLD
                        } else {
                            Modifier::DIM
                        }),
                    ));
                } else {
                    // Column ruler: marker (2) + label ("{:30}  " = 32).
                    let mut col: usize = 2 + 32;
                    for (j, opt) in row.options.iter().enumerate() {
                        let is_current = j == row.current_idx;
                        if j > 0 {
                            spans.push(Span::styled(" / ", Style::default().fg(t.bg2)));
                            col += 3;
                        }
                        let opt_width = opt.chars().count() + if is_current { 2 } else { 0 };
                        // Include the surrounding brackets in the click
                        // rect so clicking `[on]` counts the same as
                        // clicking `on`.
                        option_col_ranges.push((rc, j, col, col + opt_width));
                        col += opt_width;
                        if is_current {
                            spans.push(Span::styled(
                                format!("[{opt}]"),
                                Style::default()
                                    .fg(if is_focused { t.cyan } else { t.fg })
                                    .add_modifier(Modifier::BOLD),
                            ));
                        } else {
                            spans.push(Span::styled(opt.clone(), Style::default().fg(t.bg2)));
                        }
                    }
                    if row.modified {
                        spans.push(Span::styled(
                            "  *",
                            Style::default().fg(t.yellow).add_modifier(Modifier::BOLD),
                        ));
                    }
                }

                lines.push(Line::from(spans));
                line_row_counter.push(Some(rc));
                rc += 1;
            }
            SettingItem::Number(num) => {
                let is_focused = Some(i) == focused_item_idx;
                let marker = if is_focused { "" } else { "  " };
                let mut spans = vec![
                    Span::styled(
                        marker,
                        Style::default().fg(if is_focused { t.blue } else { t.bg2 }),
                    ),
                    Span::styled(
                        format!("{:30}  ", num.label),
                        Style::default().fg(if is_focused { t.fg } else { t.comment }),
                    ),
                    Span::styled(
                        format!("[ {}{} ]", num.value, num.unit),
                        Style::default()
                            .fg(if is_focused { t.cyan } else { t.fg })
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(
                        format!(
                            "  ({}{} · step {} · default {})",
                            num.min, num.max, num.step, num.default
                        ),
                        Style::default().fg(t.comment).add_modifier(Modifier::DIM),
                    ),
                ];
                if num.modified {
                    spans.push(Span::styled(
                        "  *",
                        Style::default().fg(t.yellow).add_modifier(Modifier::BOLD),
                    ));
                }
                lines.push(Line::from(spans));
                line_row_counter.push(Some(rc));
                rc += 1;
            }
            SettingItem::Text(row) => {
                let is_focused = Some(i) == focused_item_idx;
                let marker = if is_focused { "" } else { "  " };
                let in_edit = is_focused
                    && app
                        .settings_overlay
                        .as_ref()
                        .and_then(|s| s.text_edit.as_ref())
                        .map(|e| e.key == row.key)
                        .unwrap_or(false);
                let value_display = if in_edit {
                    format!("[ \"{}\" ]", row.value)
                } else {
                    format!("[ \"{}\" ]", row.value)
                };
                let hint = if in_edit {
                    "  (editing · Enter commit · Esc cancel)".to_string()
                } else {
                    format!("  (text · default \"{}\" · Enter to edit)", row.default)
                };
                let mut spans = vec![
                    Span::styled(
                        marker,
                        Style::default().fg(if is_focused { t.blue } else { t.bg2 }),
                    ),
                    Span::styled(
                        format!("{:30}  ", row.label),
                        Style::default().fg(if is_focused { t.fg } else { t.comment }),
                    ),
                    Span::styled(
                        value_display,
                        Style::default()
                            .fg(if is_focused { t.cyan } else { t.fg })
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(
                        hint,
                        Style::default().fg(t.comment).add_modifier(Modifier::DIM),
                    ),
                ];
                if row.modified {
                    spans.push(Span::styled(
                        "  *",
                        Style::default().fg(t.yellow).add_modifier(Modifier::BOLD),
                    ));
                }
                lines.push(Line::from(spans));
                line_row_counter.push(Some(rc));
                rc += 1;
            }
            SettingItem::Color(row) => {
                let is_focused = Some(i) == focused_item_idx;
                let marker = if is_focused { "" } else { "  " };
                let parsed = parse_hex_rgb(&row.value);
                let swatch_color = parsed.unwrap_or(t.fg);
                let suffix_text = if parsed.is_some() {
                    format!("  (color · default #{} · TOML to edit)", row.default)
                } else {
                    format!(
                        "  (color · default #{} · invalid hex · TOML to edit)",
                        row.default
                    )
                };
                let mut spans = vec![
                    Span::styled(
                        marker,
                        Style::default().fg(if is_focused { t.blue } else { t.bg2 }),
                    ),
                    Span::styled(
                        format!("{:30}  ", row.label),
                        Style::default().fg(if is_focused { t.fg } else { t.comment }),
                    ),
                    Span::styled(
                        format!("[ #{} ]  ", row.value),
                        Style::default()
                            .fg(if is_focused { t.cyan } else { t.fg })
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled("████", Style::default().fg(swatch_color)),
                    Span::styled(
                        suffix_text,
                        Style::default().fg(t.comment).add_modifier(Modifier::DIM),
                    ),
                ];
                if row.modified {
                    spans.push(Span::styled(
                        "  *",
                        Style::default().fg(t.yellow).add_modifier(Modifier::BOLD),
                    ));
                }
                lines.push(Line::from(spans));
                line_row_counter.push(Some(rc));
                rc += 1;
            }
        }
    }

    // Scroll-window the lines so the focused row stays visible. Reserve
    // a 1-row hint bar at the bottom of the outer inner rect (the
    // filter input already took the top row via body_area).
    let body_h = (body_area.height as usize).saturating_sub(1);
    let focused_line_idx = focused_item_idx.unwrap_or(0);
    let scroll = if focused_line_idx >= body_h {
        focused_line_idx + 1 - body_h
    } else {
        0
    };
    // Truncate each line to fit body_area.width — without this, long
    // descriptions used to cut mid-word at the right border with no
    // indicator (looked broken). 2026-06-07 bug-hunt SEV-3.
    let window: Vec<Line<'static>> = lines
        .iter()
        .skip(scroll)
        .take(body_h)
        .map(|l| truncate_line_to_width(l, body_area.width as usize))
        .collect();
    let body_rect = Rect {
        x: body_area.x,
        y: body_area.y,
        width: body_area.width,
        height: body_h as u16,
    };
    // Hit-test rects: one per visible Row line, mapped to the
    // row_counter index `settings_move_row` / `apply_setting` use.
    // Section-header lines are excluded (None in line_row_counter).
    for (visible_y, line_idx) in (scroll..scroll + window.len()).enumerate() {
        if let Some(Some(rc_idx)) = line_row_counter.get(line_idx).copied() {
            let row_y = body_rect.y + visible_y as u16;
            app.rects.settings_rows.push((
                Rect {
                    x: body_rect.x,
                    y: row_y,
                    width: body_rect.width,
                    height: 1,
                },
                rc_idx,
            ));
            // Per-option sub-rects for this visible row. Cull ones
            // that are wholly outside the panel width — the row
            // clips at `body_rect.width` and clicks past it belong
            // to no option.
            for &(orc, opt_idx, c0, c1) in &option_col_ranges {
                if orc != rc_idx {
                    continue;
                }
                let width = c1.saturating_sub(c0) as u16;
                if width == 0 || c0 as u16 >= body_rect.width {
                    continue;
                }
                let visible_width = width.min(body_rect.width - c0 as u16);
                app.rects.settings_row_options.push((
                    Rect {
                        x: body_rect.x + c0 as u16,
                        y: row_y,
                        width: visible_width,
                        height: 1,
                    },
                    rc_idx,
                    opt_idx,
                ));
            }
        }
    }
    frame.render_widget(Paragraph::new(window), body_rect);

    // 1-line hint bar at the bottom. Truncated to the inner panel
    // width so a narrow terminal doesn't punch through the right
    // border — the content `window` above already gets the same
    // treatment via `truncate_line_to_width`.
    // 2026-06-19 — earlier hint said "Enter save" but Enter on a
    // Text row entered edit mode (then Enter again to commit +
    // persist). Now distinguishes the two roles.
    let hint =
        // qa-8th design MED-2 2026-06-30 — was "click out / Esc done"
        // which falsely framed those as equivalent (click-out saves,
        // Esc cancels). Explicit Save vs Cancel disambiguation now.
        "←→ adjust · ↑↓ move · Enter/click out: save · r reset · R reset all · Esc: cancel";
    // qa-6th mouse SEV-3 2026-06-29: settings overlay had no
    // visible Save / Cancel buttons — mouse-only users had to
    // type Enter/Esc despite the rest of the app having clickable
    // affordances. Paint two right-aligned chips + register click
    // rects.
    // qa-8th design LOW-5 2026-06-30 — was " [Save] " / " [Cancel] "
    // but the settings overlay also uses [bracketed] notation for
    // the currently-selected option value, so chip brackets read
    // as another option marker. close_prompt.rs intentionally
    // dropped brackets for the same reason. Use plain text with
    // solid-color bg styling instead.
    const SAVE_CHIP: &str = "  Save  ";
    const CANCEL_CHIP: &str = "  Cancel  ";
    let chips_w = (SAVE_CHIP.len() + CANCEL_CHIP.len()) as u16;
    let hint_visible_w = inner.width.saturating_sub(chips_w + 1);
    let hint_line = truncate_line_to_width(
        &Line::from(Span::styled(
            hint.to_string(),
            Style::default().fg(t.comment).add_modifier(Modifier::DIM),
        )),
        hint_visible_w as usize,
    );
    let hint_rect = Rect {
        x: inner.x,
        y: inner.y + inner.height.saturating_sub(1),
        width: hint_visible_w,
        height: 1,
    };
    frame.render_widget(Paragraph::new(hint_line), hint_rect);
    // qa-8th render N-1 2026-06-30 — skip the chips entirely when
    // the overlay is too narrow to fit both. Was: chips painted
    // with overlapping rects (Save would land at x=0, off the
    // overlay's left border) on terminals < ~64 columns.
    if inner.width < chips_w + 2 {
        return;
    }
    // Chips paint right-aligned on the same row.
    let cancel_rect = Rect {
        x: inner.x + inner.width.saturating_sub(CANCEL_CHIP.len() as u16),
        y: hint_rect.y,
        width: CANCEL_CHIP.len() as u16,
        height: 1,
    };
    let save_rect = Rect {
        x: cancel_rect.x.saturating_sub(SAVE_CHIP.len() as u16),
        y: hint_rect.y,
        width: SAVE_CHIP.len() as u16,
        height: 1,
    };
    frame.render_widget(
        Paragraph::new(SAVE_CHIP).style(
            Style::default()
                .fg(t.bg_dark)
                .bg(t.green)
                .add_modifier(Modifier::BOLD),
        ),
        save_rect,
    );
    frame.render_widget(
        Paragraph::new(CANCEL_CHIP).style(
            Style::default()
                .fg(t.fg)
                .bg(t.bg2)
                .add_modifier(Modifier::BOLD),
        ),
        cancel_rect,
    );
    app.rects.settings_save_button = Some(save_rect);
    app.rects.settings_cancel_button = Some(cancel_rect);
}

/// Parse a 6-char `RRGGBB` hex (no `#`) into a `ratatui::Color::Rgb`.
/// Returns `None` for invalid input. Used to render the color-row
/// swatch in `ColorRow`'s parsed color.
fn parse_hex_rgb(hex: &str) -> Option<Color> {
    let bytes = hex.as_bytes();
    if bytes.len() != 6 || !bytes.iter().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
    let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
    let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
    Some(Color::Rgb(r, g, b))
}

/// Truncate a `Line<'static>` (span-by-span) so its total char count
/// doesn't exceed `max_width`. If truncation happens, append `…` as
/// a final span to surface that something was cut (without it, the
/// row reads as broken mid-word at the right border). Width is char
/// count, not display width — sufficient for the settings overlay
/// where labels + values are ASCII/Latin.
fn truncate_line_to_width(line: &Line<'static>, max_width: usize) -> Line<'static> {
    let total: usize = line.spans.iter().map(|s| s.content.chars().count()).sum();
    if total <= max_width {
        return line.clone();
    }
    // Reserve 1 char for the trailing `…` marker.
    let budget = max_width.saturating_sub(1);
    let mut used = 0usize;
    let mut out_spans: Vec<Span<'static>> = Vec::with_capacity(line.spans.len() + 1);
    for span in &line.spans {
        let span_len = span.content.chars().count();
        if used + span_len <= budget {
            out_spans.push(span.clone());
            used += span_len;
        } else {
            let take = budget.saturating_sub(used);
            if take > 0 {
                let s: String = span.content.chars().take(take).collect();
                out_spans.push(Span::styled(s, span.style));
            }
            break;
        }
    }
    out_spans.push(Span::styled("", Style::default().fg(Color::DarkGray)));
    Line::from(out_spans)
}