ratada 0.3.0

A ratatui widget toolkit: driver, modals, forms, pickers, theming
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
//! Reusable modal widgets. Each is a thin wrapper over [`overlay::popup`]: it
//! sets up its state and closures and returns a [`ModalSignal`]. The dimmed
//! backdrop, box centering and event loop live in [`overlay`], not here.
//!
//! Yes/no questions go through [`confirm`], which lets `Enter` mean yes. A
//! destructive action goes through [`confirm_default`] with
//! [`Question::declining`] instead, so a stray `Enter` cannot confirm the
//! deletion.
//!
//! Every modal takes a [`Skin`], whose palette drives the colors.

use std::{collections::HashSet, io};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    Frame,
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{List, ListItem, ListState, Paragraph, Wrap},
};
use unicode_width::UnicodeWidthStr;

use super::{
    chrome,
    input::{self, TextCursor},
    layout::{centered_rect, fit},
    nav,
    overlay::{self, PopupFlow, popup},
    scroll, shortcut_hints, style,
    terminal::Tui,
};
use crate::theme::{Palette, Skin};

/// Rows a modal's hint block occupies while the hints are shown: a blank
/// spacer and the hint line itself.
const HINT_BLOCK_ROWS: u16 = 2;

/// Outcome of a modal interaction.
pub enum ModalSignal<T> {
    /// The user confirmed with a value.
    Value(T),
    /// The user dismissed the modal (Esc).
    Cancelled,
    /// The global quit chord was pressed inside the modal.
    Quit,
}

/// Asks a yes/no question. `Enter`/`y` confirm, `Esc`/`n` decline.
///
/// For a destructive prompt reach for [`confirm_default`] with
/// [`Question::declining`], which makes `Enter` decline instead.
pub fn confirm(
    tui: &mut Tui,
    skin: &Skin,
    prompt: &str,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<bool>> {
    confirm_default(tui, skin, &Question::new(prompt), render_bg)
}

/// A yes/no question and which way a bare `Enter` answers it.
#[derive(Debug, Clone, Copy)]
pub struct Question<'a> {
    /// The question shown in the dialog.
    pub prompt: &'a str,
    /// What `Enter` answers. `y`/`n` always answer explicitly, `Esc` declines.
    pub default_yes: bool,
}

impl<'a> Question<'a> {
    /// A question a bare `Enter` confirms.
    #[must_use]
    pub fn new(prompt: &'a str) -> Self {
        Self {
            prompt,
            default_yes: true,
        }
    }

    /// A question a bare `Enter` declines - the safe default for a destructive
    /// action, where an absent-minded `Enter` must not delete anything.
    #[must_use]
    pub fn declining(prompt: &'a str) -> Self {
        Self {
            prompt,
            default_yes: false,
        }
    }

    /// The footer hints, binding `enter` to whichever answer it gives.
    fn hints(&self) -> [(&'static str, &'static str); 2] {
        if self.default_yes {
            [("enter/y", "yes"), ("n", "no")]
        } else {
            [("y", "yes"), ("enter/n", "no")]
        }
    }
}

/// Asks a yes/no question whose `Enter` answer the caller chooses.
///
/// `y` confirms and `n` declines regardless; `Esc` always declines. Use
/// [`Question::declining`] for a destructive prompt so `Enter` cannot confirm
/// it by accident, and [`confirm`] when `Enter` should mean yes.
pub fn confirm_default(
    tui: &mut Tui,
    skin: &Skin,
    question: &Question<'_>,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<bool>> {
    let prompt = question.prompt;
    let default_yes = question.default_yes;
    let mut state = ();
    popup(
        tui,
        &mut state,
        |area, (): &()| {
            let width = fit(prompt.width() as u16 + 6, 28, area.width);
            centered_rect(width, hinted_box_height(), area)
        },
        |frame, (): &()| render_bg(frame),
        |frame, rect, (): &()| render_confirm(frame, skin, question, rect),
        |(): &mut (), key| match key.code {
            KeyCode::Char('y' | 'Y') => PopupFlow::Done(true),
            KeyCode::Char('n' | 'N') | KeyCode::Esc => PopupFlow::Done(false),
            KeyCode::Enter => PopupFlow::Done(default_yes),
            _ => PopupFlow::Continue,
        },
    )
}

/// Prompts for a single line of text. `Enter` accepts, `Esc` cancels.
pub fn input(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    initial: &str,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<String>> {
    input_impl(tui, skin, title, initial, input_area, render_bg)
}

/// Like [`input()`], but the box spans most of the terminal width, so a long
/// value (such as a file path) stays visible instead of scrolling in a narrow
/// box. `Enter` accepts, `Esc` cancels.
pub fn input_wide(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    initial: &str,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<String>> {
    input_impl(tui, skin, title, initial, input_area_wide, render_bg)
}

/// Shared single-line text prompt; `area` sizes the box from the frame.
fn input_impl(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    initial: &str,
    area: impl Fn(Rect) -> Rect,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<String>> {
    let mut state = TextField {
        cursor: TextCursor::at_end(initial),
        text: initial.to_string(),
    };
    popup(
        tui,
        &mut state,
        |rect, _| area(rect),
        |frame, _| render_bg(frame),
        |frame, rect, field: &TextField| {
            render_input(frame, skin, title, &field.text, &field.cursor, rect);
        },
        |field, key| match key.code {
            KeyCode::Enter => PopupFlow::Done(field.text.clone()),
            KeyCode::Esc => PopupFlow::Cancelled,
            _ => {
                input::apply_edit_key(
                    &mut field.text,
                    &mut field.cursor,
                    key,
                    input::EditMode::SingleLine,
                    None,
                );
                PopupFlow::Continue
            }
        },
    )
}

/// Lets the user pick one entry from a list. `Esc` cancels.
pub fn select(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    items: &[String],
    initial: usize,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<usize>> {
    if items.is_empty() {
        return Ok(ModalSignal::Cancelled);
    }
    let mut cursor = initial.min(items.len() - 1);
    popup(
        tui,
        &mut cursor,
        |area, _| picker_area(area, items.len()),
        |frame, _| render_bg(frame),
        |frame, rect, cursor: &usize| {
            render_picker(frame, skin, title, items, *cursor, None, rect);
        },
        |cursor, key| match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                *cursor = nav::cycle(*cursor, items.len(), -1);
                PopupFlow::Continue
            }
            KeyCode::Down | KeyCode::Char('j') => {
                *cursor = nav::cycle(*cursor, items.len(), 1);
                PopupFlow::Continue
            }
            KeyCode::Enter => PopupFlow::Done(*cursor),
            KeyCode::Esc => PopupFlow::Cancelled,
            _ => PopupFlow::Continue,
        },
    )
}

/// Lets the user toggle several entries. `Space` toggles, `Enter` confirms the
/// selected set, `Esc` cancels.
pub fn multi_select(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    items: &[String],
    initial: &[usize],
    check: &str,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<Vec<usize>>> {
    if items.is_empty() {
        return Ok(ModalSignal::Cancelled);
    }
    let mut state = MultiSelect::new(initial);
    popup(
        tui,
        &mut state,
        |area, _| picker_area(area, items.len()),
        |frame, _| render_bg(frame),
        |frame, rect, state: &MultiSelect| {
            let checked = Some((&state.checked, check));
            render_picker(
                frame,
                skin,
                title,
                items,
                state.cursor,
                checked,
                rect,
            );
        },
        |state, key| state.handle_key(key, items.len()),
    )
}

/// Outcome of [`select_reorderable`]: a final pick or a reorder request that
/// the caller applies before reopening.
pub enum ListAction {
    /// The user picked the item at this index.
    Pick(usize),
    /// The user asked to move the item at `index` by `delta` positions.
    Move {
        /// The index of the item to move.
        index: usize,
        /// The signed number of positions to move it by.
        delta: i32,
    },
}

/// Like [`select`] but `Alt+Up`/`Alt+Down` return a [`ListAction::Move`] so the
/// caller can reorder the list and reopen.
pub fn select_reorderable(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    items: &[String],
    initial: usize,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<ListAction>> {
    if items.is_empty() {
        return Ok(ModalSignal::Cancelled);
    }
    let mut cursor = initial.min(items.len() - 1);
    popup(
        tui,
        &mut cursor,
        |area, _| picker_area(area, items.len()),
        |frame, _| render_bg(frame),
        |frame, rect, cursor: &usize| {
            render_picker(frame, skin, title, items, *cursor, None, rect);
        },
        |cursor, key| {
            let alt = key.modifiers.contains(KeyModifiers::ALT);
            match key.code {
                KeyCode::Up if alt => PopupFlow::Done(ListAction::Move {
                    index: *cursor,
                    delta: -1,
                }),
                KeyCode::Down if alt => PopupFlow::Done(ListAction::Move {
                    index: *cursor,
                    delta: 1,
                }),
                KeyCode::Up | KeyCode::Char('k') => {
                    *cursor = nav::cycle(*cursor, items.len(), -1);
                    PopupFlow::Continue
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    *cursor = nav::cycle(*cursor, items.len(), 1);
                    PopupFlow::Continue
                }
                KeyCode::Enter => PopupFlow::Done(ListAction::Pick(*cursor)),
                KeyCode::Esc => PopupFlow::Cancelled,
                _ => PopupFlow::Continue,
            }
        },
    )
}

/// Like [`select`] but each item carries its own style (for coloured glyphs).
pub fn select_styled(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    items: &[(String, Style)],
    initial: usize,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<usize>> {
    if items.is_empty() {
        return Ok(ModalSignal::Cancelled);
    }
    let mut cursor = initial.min(items.len() - 1);
    popup(
        tui,
        &mut cursor,
        |area, _| picker_area(area, items.len()),
        |frame, _| render_bg(frame),
        |frame, rect, cursor: &usize| {
            render_styled_picker(
                frame, skin, title, items, *cursor, None, rect,
            );
        },
        |cursor, key| match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                *cursor = nav::cycle(*cursor, items.len(), -1);
                PopupFlow::Continue
            }
            KeyCode::Down | KeyCode::Char('j') => {
                *cursor = nav::cycle(*cursor, items.len(), 1);
                PopupFlow::Continue
            }
            KeyCode::Enter => PopupFlow::Done(*cursor),
            KeyCode::Esc => PopupFlow::Cancelled,
            _ => PopupFlow::Continue,
        },
    )
}

/// Like [`multi_select`] but each item carries its own style.
pub fn multi_select_styled(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    items: &[(String, Style)],
    initial: &[usize],
    check: &str,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<Vec<usize>>> {
    if items.is_empty() {
        return Ok(ModalSignal::Cancelled);
    }
    let mut state = MultiSelect::new(initial);
    popup(
        tui,
        &mut state,
        |area, _| picker_area(area, items.len()),
        |frame, _| render_bg(frame),
        |frame, rect, state: &MultiSelect| {
            let checked = Some((&state.checked, check));
            let cursor = state.cursor;
            render_styled_picker(
                frame, skin, title, items, cursor, checked, rect,
            );
        },
        |state, key| state.handle_key(key, items.len()),
    )
}

/// Prompts for an integer, accepting digits (and a leading minus) only.
pub fn number_input(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    initial: i64,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<i64>> {
    number_impl(tui, skin, title, initial, None, render_bg)
}

/// Like [`number_input`], but the accepted value is clamped to `[min, max]`.
/// `Enter` accepts (clamping), `Esc` cancels.
pub fn number_input_bounded(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    initial: i64,
    min: i64,
    max: i64,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<i64>> {
    number_impl(tui, skin, title, initial, Some((min, max)), render_bg)
}

/// Shared integer prompt; `bounds` clamps the accepted value when set.
fn number_impl(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    initial: i64,
    bounds: Option<(i64, i64)>,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<i64>> {
    let mut text = initial.to_string();
    popup(
        tui,
        &mut text,
        |area, _| input_area(area),
        |frame, _| render_bg(frame),
        |frame, rect, text: &String| {
            let cursor = TextCursor::at_end(text);
            render_input(frame, skin, title, text, &cursor, rect);
        },
        |text, key| match key.code {
            KeyCode::Enter => {
                let value = text.parse::<i64>().unwrap_or(initial);
                let value =
                    bounds.map_or(value, |(min, max)| value.clamp(min, max));
                PopupFlow::Done(value)
            }
            KeyCode::Esc => PopupFlow::Cancelled,
            KeyCode::Backspace => {
                text.pop();
                PopupFlow::Continue
            }
            KeyCode::Char(ch)
                if ch.is_ascii_digit() || (ch == '-' && text.is_empty()) =>
            {
                text.push(ch);
                PopupFlow::Continue
            }
            _ => PopupFlow::Continue,
        },
    )
}

/// Shows an informational message until any key is pressed.
pub fn message(
    tui: &mut Tui,
    skin: &Skin,
    title: &str,
    body: &str,
    render_bg: impl Fn(&mut Frame),
) -> io::Result<ModalSignal<()>> {
    let mut state = ();
    popup(
        tui,
        &mut state,
        |area, (): &()| {
            let width = fit(body.width() as u16 + 6, 28, area.width);
            centered_rect(width, 5, area)
        },
        |frame, (): &()| render_bg(frame),
        |frame, rect, (): &()| render_message(frame, skin, title, body, rect),
        |(): &mut (), _| PopupFlow::Done(()),
    )
}

/// The text field state shared by [`input`]: an edit buffer plus its caret.
struct TextField {
    text: String,
    cursor: TextCursor,
}

/// The state shared by the multi-select modals: the cursor plus the toggled set.
struct MultiSelect {
    cursor: usize,
    checked: HashSet<usize>,
}

impl MultiSelect {
    fn new(initial: &[usize]) -> Self {
        Self {
            cursor: 0,
            checked: initial.iter().copied().collect(),
        }
    }

    fn handle_key(
        &mut self,
        key: KeyEvent,
        len: usize,
    ) -> PopupFlow<Vec<usize>> {
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                self.cursor = nav::cycle(self.cursor, len, -1);
                PopupFlow::Continue
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.cursor = nav::cycle(self.cursor, len, 1);
                PopupFlow::Continue
            }
            KeyCode::Char(' ') => {
                if !self.checked.insert(self.cursor) {
                    self.checked.remove(&self.cursor);
                }
                PopupFlow::Continue
            }
            KeyCode::Enter => {
                let mut chosen: Vec<usize> =
                    self.checked.iter().copied().collect();
                chosen.sort_unstable();
                PopupFlow::Done(chosen)
            }
            KeyCode::Esc => PopupFlow::Cancelled,
            _ => PopupFlow::Continue,
        }
    }
}

fn render_confirm(
    frame: &mut Frame,
    skin: &Skin,
    question: &Question<'_>,
    rect: Rect,
) {
    let inner = overlay::framed(frame, rect, skin, " Confirm ");
    let width = inner.width as usize;
    let mut lines = vec![Line::from(question.prompt.to_string())];
    lines.extend(hint_block(&question.hints(), &skin.palette, width));
    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: true });
    frame.render_widget(paragraph, inner);
}

fn render_input(
    frame: &mut Frame,
    skin: &Skin,
    title: &str,
    text: &str,
    cursor: &TextCursor,
    rect: Rect,
) {
    let inner = overlay::framed(frame, rect, skin, title);
    let width = inner.width as usize;
    let line = input::render_line(text, cursor, &skin.palette, width, true);
    let mut lines = vec![line];
    lines.extend(hint_block(
        &[("enter", "ok"), ("esc", "cancel")],
        &skin.palette,
        width,
    ));
    frame.render_widget(Paragraph::new(lines), inner);
}

fn render_message(
    frame: &mut Frame,
    skin: &Skin,
    title: &str,
    body: &str,
    rect: Rect,
) {
    let inner = overlay::framed(frame, rect, skin, title);
    let paragraph = Paragraph::new(body.to_string()).wrap(Wrap { trim: true });
    frame.render_widget(paragraph, inner);
}

fn render_picker(
    frame: &mut Frame,
    skin: &Skin,
    title: &str,
    items: &[String],
    cursor: usize,
    checked: Option<(&HashSet<usize>, &str)>,
    rect: Rect,
) {
    let inner = overlay::framed(frame, rect, skin, title);
    let entries: Vec<ListItem> = items
        .iter()
        .enumerate()
        .map(|(index, label)| {
            let prefix = check_prefix(checked, index);
            ListItem::new(Line::from(format!("{prefix}{label}")))
        })
        .collect();
    render_picker_list(frame, inner, entries, items.len(), cursor, skin);
    render_picker_badge(frame, rect, skin, items.len(), cursor);
}

fn render_styled_picker(
    frame: &mut Frame,
    skin: &Skin,
    title: &str,
    items: &[(String, Style)],
    cursor: usize,
    checked: Option<(&HashSet<usize>, &str)>,
    rect: Rect,
) {
    let inner = overlay::framed(frame, rect, skin, title);
    let entries: Vec<ListItem> = items
        .iter()
        .enumerate()
        .map(|(index, (label, item_style))| {
            let prefix = check_prefix(checked, index);
            ListItem::new(Line::from(vec![
                Span::raw(prefix),
                Span::styled(label.clone(), *item_style),
            ]))
        })
        .collect();
    render_picker_list(frame, inner, entries, items.len(), cursor, skin);
    render_picker_badge(frame, rect, skin, items.len(), cursor);
}

/// Draws the `position/total` badge into the picker frame's bottom border.
/// `rect` is the framed box, not the list inside it.
fn render_picker_badge(
    frame: &mut Frame,
    rect: Rect,
    skin: &Skin,
    total: usize,
    cursor: usize,
) {
    let badge = chrome::position_badge(cursor, total);
    chrome::render_badge(frame, rect, skin, &badge);
}

/// Renders a picker's list into `inner` with the cursor highlighted, then a
/// scrollbar on the right whenever the entries overflow the visible rows.
fn render_picker_list(
    frame: &mut Frame,
    inner: Rect,
    entries: Vec<ListItem<'_>>,
    total: usize,
    cursor: usize,
    skin: &Skin,
) {
    let mut state = picker_state(cursor);
    frame.render_stateful_widget(picker_list(entries, skin), inner, &mut state);
    scroll::render_scrollbar(
        frame,
        inner,
        skin,
        nav::ScrollView {
            total,
            offset: state.offset(),
            viewport: inner.height as usize,
        },
    );
}

/// The check-mark (or blank) prefix for a multi-select row, or empty for a
/// single-select list.
fn check_prefix(
    checked: Option<(&HashSet<usize>, &str)>,
    index: usize,
) -> String {
    match checked {
        Some((set, glyph)) if set.contains(&index) => format!("{glyph} "),
        Some(_) => "  ".to_string(),
        None => String::new(),
    }
}

fn picker_list<'a>(entries: Vec<ListItem<'a>>, skin: &Skin) -> List<'a> {
    List::new(entries).highlight_style(
        style::bg(skin.palette.selection).add_modifier(Modifier::BOLD),
    )
}

fn picker_state(cursor: usize) -> ListState {
    let mut state = ListState::default();
    state.select(Some(cursor));
    state
}

/// The popup rect for the list pickers: half the width, one row per item.
fn picker_area(area: Rect, item_count: usize) -> Rect {
    let height = fit(item_count as u16 + 2, 5, area.height.saturating_sub(2));
    let width = fit(area.width / 2, 30, area.width.saturating_sub(4));
    centered_rect(width, height, area)
}

/// The popup rect for the single-line text inputs.
fn input_area(area: Rect) -> Rect {
    let width = area.width.saturating_sub(8).clamp(20, 60);
    centered_rect(width, hinted_box_height(), area)
}

/// A wide input box (~90% of the terminal width), for long values.
fn input_area_wide(area: Rect) -> Rect {
    let width = fit(area.width * 9 / 10, 20, area.width);
    centered_rect(width, hinted_box_height(), area)
}

/// The blank spacer and the hint line closing a modal body. Both vanish
/// together while the hints are hidden, which is why the spacer lives here and
/// not at the call site.
fn hint_block(
    items: &[(&str, &str)],
    palette: &Palette,
    width: usize,
) -> Vec<Line<'static>> {
    shortcut_hints::lines(items, palette.accent, width)
        .into_iter()
        .take(1)
        .flat_map(|hint| [Line::from(""), hint])
        .collect()
}

/// The height of a modal box whose body is one row plus a [`hint_block`]:
/// two border rows, the row itself, and the hint block when shown.
fn hinted_box_height() -> u16 {
    3 + shortcut_hints::footer_height(HINT_BLOCK_ROWS)
}

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

    /// Every popup wants a minimum width or height. A terminal smaller than
    /// that must shrink the popup, not panic: these helpers used to reach
    /// `clamp(min, max)` with `max < min`.
    #[test]
    fn popup_geometry_survives_a_terminal_below_its_minimum() {
        for (width, height) in [(1, 1), (4, 2), (20, 6), (27, 10)] {
            let area = Rect::new(0, 0, width, height);
            for rect in [
                picker_area(area, 40),
                input_area(area),
                input_area_wide(area),
            ] {
                assert!(rect.width <= area.width, "{rect:?} in {area:?}");
                assert!(rect.height <= area.height, "{rect:?} in {area:?}");
            }
        }
    }

    #[test]
    fn a_roomy_terminal_still_gets_the_preferred_size() {
        let area = Rect::new(0, 0, 100, 40);
        let picker = picker_area(area, 4);
        assert_eq!(picker.width, 50); // half the width
        assert_eq!(picker.height, 6); // one row per item, plus borders
    }

    #[test]
    fn a_plain_question_lets_enter_confirm() {
        let question = Question::new("Save the file?");
        assert!(question.default_yes);
        assert_eq!(question.hints(), [("enter/y", "yes"), ("n", "no")]);
    }

    /// The point of `declining`: a stray `Enter` on a destructive prompt must
    /// answer "no", and the footer must advertise that binding.
    #[test]
    fn a_declining_question_lets_enter_decline() {
        let question = Question::declining("Delete everything?");
        assert!(!question.default_yes);
        assert_eq!(question.hints(), [("y", "yes"), ("enter/n", "no")]);
    }
}