bath 0.5.0

A TUI tool to manage and export environment variable profiles
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
use crate::catalog::Catalog;
use crate::config::{CatalogItem, CustomVarDef, ItemKind, VarKind};
use crate::tui::util::{centered_rect, is_ctrl_c, next_key_press};
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    backend::Backend,
    widgets::{Block, Borders, Clear, Paragraph},
    Terminal,
};

/// What a dialog should do after handling one key press.
enum DialogAction<T> {
    Continue,
    Cancel,
    Save(T),
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum VarField {
    Name,
    Kind,
    Separator,
}

const MAX_NAME_SUGGESTIONS: usize = 6;

struct CustomVarDialogState<'a> {
    catalog: &'a Catalog,
    name: String,
    kind: VarKind,
    separator: String,
    field: VarField,
    hint: Option<String>,
    suggestions: Vec<String>,
    picked: usize,
    browsed: bool,
    origin: Option<String>,
    kind_touched: bool,
}

impl<'a> CustomVarDialogState<'a> {
    fn new(catalog: &'a Catalog) -> Self {
        Self {
            catalog,
            name: String::new(),
            kind: VarKind::List,
            separator: ":".to_string(),
            field: VarField::Name,
            hint: None,
            suggestions: Vec::new(),
            picked: 0,
            browsed: false,
            origin: None,
            kind_touched: false,
        }
    }

    fn toggle_kind(&mut self) {
        self.kind_touched = true;
        self.kind = match self.kind {
            VarKind::Scalar => VarKind::List,
            VarKind::List => VarKind::Scalar,
        };
        if self.kind == VarKind::List && self.separator.is_empty() {
            self.separator = ":".to_string();
        }
    }

    /// Recompute suggestions and, until the user edits kind or separator,
    /// infer both from the catalog.
    fn refresh_from_name(&mut self) {
        self.suggestions = self
            .catalog
            .complete(&self.name)
            .into_iter()
            .take(MAX_NAME_SUGGESTIONS)
            .map(|v| v.name.clone())
            .collect();
        self.picked = 0;
        self.browsed = false;
        let found = self.catalog.lookup(self.name.trim());
        self.origin = found.as_ref().map(|m| m.label());
        if self.kind_touched {
            return;
        }
        let Some(m) = found else {
            self.kind = VarKind::List;
            self.separator = ":".to_string();
            return;
        };
        self.kind = m.def.kind;
        self.separator = m.def.separator;
    }

    /// Tab on the name field completes the picked suggestion when it extends
    /// what was typed, or when the user picked it with Up/Down; returns false
    /// when there is nothing to complete.
    fn complete_name(&mut self) -> bool {
        let Some(pick) = self.suggestions.get(self.picked).cloned() else {
            return false;
        };
        if pick == self.name {
            return false;
        }
        let extends_typed = pick
            .to_lowercase()
            .starts_with(&self.name.trim().to_lowercase());
        if !self.browsed && !extends_typed {
            return false;
        }
        self.name = pick;
        self.refresh_from_name();
        true
    }

    fn handle_key(&mut self, key: KeyEvent) -> DialogAction<CustomVarDef> {
        self.hint = None;
        // Ctrl+C cancels like Esc so the global quit chord is never dead here.
        if is_ctrl_c(&key) {
            return DialogAction::Cancel;
        }
        match key.code {
            KeyCode::Esc => DialogAction::Cancel,
            KeyCode::Enter => {
                let trimmed = self.name.trim();
                if trimmed.is_empty() {
                    return DialogAction::Cancel;
                }
                if self.kind == VarKind::List && self.separator.is_empty() {
                    self.hint = Some("separator must not be empty".to_string());
                    return DialogAction::Continue;
                }
                DialogAction::Save(CustomVarDef {
                    name: trimmed.to_string(),
                    kind: self.kind.clone(),
                    separator: if self.kind == VarKind::List {
                        self.separator.clone()
                    } else {
                        String::new()
                    },
                })
            }
            KeyCode::Tab => {
                if self.field == VarField::Name && self.complete_name() {
                    return DialogAction::Continue;
                }
                self.field = match self.field {
                    VarField::Name => VarField::Kind,
                    VarField::Kind => VarField::Separator,
                    VarField::Separator => VarField::Name,
                };
                DialogAction::Continue
            }
            KeyCode::Up if self.field == VarField::Name => {
                self.picked = self.picked.saturating_sub(1);
                self.browsed = true;
                DialogAction::Continue
            }
            KeyCode::Down if self.field == VarField::Name => {
                self.picked = (self.picked + 1).min(self.suggestions.len().saturating_sub(1));
                self.browsed = true;
                DialogAction::Continue
            }
            // Kind toggling lives on Ctrl+T so bare 't'/'T' reach the focused
            // text field; this arm must precede the catch-all that drops
            // modified keys.
            KeyCode::Char('t') | KeyCode::Char('T')
                if key.modifiers.contains(KeyModifiers::CONTROL) =>
            {
                self.toggle_kind();
                DialogAction::Continue
            }
            KeyCode::Backspace => {
                match self.field {
                    VarField::Name => {
                        self.name.pop();
                        self.refresh_from_name();
                    }
                    VarField::Kind => {}
                    VarField::Separator => {
                        if self.kind == VarKind::List {
                            self.separator.pop();
                            self.kind_touched = true;
                        }
                    }
                }
                DialogAction::Continue
            }
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                match self.field {
                    VarField::Name => {
                        self.name.push(c);
                        self.refresh_from_name();
                    }
                    VarField::Kind => {}
                    VarField::Separator => {
                        if self.kind == VarKind::List {
                            self.separator.push(c);
                            self.kind_touched = true;
                        }
                    }
                }
                DialogAction::Continue
            }
            _ => DialogAction::Continue,
        }
    }
}

pub fn create_custom_var_dialog<B: Backend>(
    terminal: &mut Terminal<B>,
    catalog: &Catalog,
) -> Result<Option<CustomVarDef>> {
    let mut st = CustomVarDialogState::new(catalog);

    loop {
        terminal.draw(|f| {
            let area = centered_rect(70, 50, f.size());
            f.render_widget(Clear, area);
            let title =
                "Create custom env var (Tab: complete/next, Ctrl+T: toggle kind, Enter: save, Esc: cancel)";
            let block = Block::default().borders(Borders::ALL).title(title);

            let kind_s = match st.kind {
                VarKind::Scalar => "Scalar",
                VarKind::List => "List",
            };

            let name_prefix = if st.field == VarField::Name { "> " } else { "  " };
            let kind_prefix = if st.field == VarField::Kind { "> " } else { "  " };
            let sep_prefix = if st.field == VarField::Separator {
                "> "
            } else {
                "  "
            };

            let sep_line = if st.kind == VarKind::List {
                format!("{sep_prefix}Separator: {}", st.separator)
            } else {
                format!("{sep_prefix}Separator: (n/a)")
            };

            let mut text = format!(
                "{name_prefix}Name: {}\n{kind_prefix}Kind: {kind_s}\n{sep_line}\n\nNote: list vars are edited as parts; export joins parts using Separator.",
                st.name
            );
            if let Some(origin) = &st.origin {
                text.push_str(&format!("\nKnown: {origin} (kind and separator filled in)"));
            }
            if st.field == VarField::Name && !st.suggestions.is_empty() {
                text.push_str("\n\nSuggestions (Up/Down: pick, Tab: complete)");
                for (i, s) in st.suggestions.iter().enumerate() {
                    let marker = if i == st.picked { "» " } else { "  " };
                    text.push_str(&format!("\n{marker}{s}"));
                }
            }
            if let Some(h) = &st.hint {
                text.push_str(&format!("\n\n{h}"));
            }
            let p = Paragraph::new(text).block(block);
            f.render_widget(p, area);
        })?;

        if let Some(key) = next_key_press(std::time::Duration::from_millis(100))? {
            match st.handle_key(key) {
                DialogAction::Continue => {}
                DialogAction::Cancel => return Ok(None),
                DialogAction::Save(def) => return Ok(Some(def)),
            }
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ItemField {
    Kind,
    Value,
    Program,
    Version,
    Tags,
}

struct ItemDialogState {
    id: Option<i64>,
    kind: ItemKind,
    value: String,
    program: String,
    version: String,
    tags: String,
    field: ItemField,
}

impl ItemDialogState {
    fn new(initial: Option<&CatalogItem>) -> Self {
        Self {
            id: initial.and_then(|i| i.id),
            kind: initial.map(|i| i.kind.clone()).unwrap_or(ItemKind::Text),
            value: initial.map(|i| i.value.clone()).unwrap_or_default(),
            program: initial.and_then(|i| i.program.clone()).unwrap_or_default(),
            version: initial.and_then(|i| i.version.clone()).unwrap_or_default(),
            tags: initial.map(|i| i.tags.join(",")).unwrap_or_default(),
            field: ItemField::Value,
        }
    }

    fn handle_key(&mut self, key: KeyEvent) -> DialogAction<CatalogItem> {
        // Ctrl+C cancels like Esc so the global quit chord is never dead here.
        if is_ctrl_c(&key) {
            return DialogAction::Cancel;
        }
        match key.code {
            KeyCode::Esc => DialogAction::Cancel,
            KeyCode::Enter => {
                let trimmed = self.value.trim();
                if trimmed.is_empty() {
                    return DialogAction::Cancel;
                }
                let tags_vec = self
                    .tags
                    .split(',')
                    .map(|t| t.trim())
                    .filter(|t| !t.is_empty())
                    .map(|t| t.to_string())
                    .collect::<Vec<_>>();
                DialogAction::Save(CatalogItem {
                    id: self.id,
                    kind: self.kind.clone(),
                    value: trimmed.to_string(),
                    program: if self.kind == ItemKind::Path && !self.program.trim().is_empty() {
                        Some(self.program.trim().to_string())
                    } else {
                        None
                    },
                    version: if self.kind == ItemKind::Path && !self.version.trim().is_empty() {
                        Some(self.version.trim().to_string())
                    } else {
                        None
                    },
                    tags: tags_vec,
                })
            }
            KeyCode::Tab => {
                self.field = match self.field {
                    ItemField::Kind => ItemField::Value,
                    ItemField::Value => ItemField::Program,
                    ItemField::Program => ItemField::Version,
                    ItemField::Version => ItemField::Tags,
                    ItemField::Tags => ItemField::Kind,
                };
                if self.kind == ItemKind::Text
                    && matches!(self.field, ItemField::Program | ItemField::Version)
                {
                    self.field = ItemField::Tags;
                }
                DialogAction::Continue
            }
            // Kind toggling lives on Ctrl+T so bare 't'/'T' reach the focused
            // text field; this arm must precede the catch-all that drops
            // modified keys. The program/version buffers are kept so an
            // accidental toggle-and-back loses nothing typed; Enter only
            // includes them in the saved item for Path kind.
            KeyCode::Char('t') | KeyCode::Char('T')
                if key.modifiers.contains(KeyModifiers::CONTROL) =>
            {
                self.kind = match self.kind {
                    ItemKind::Text => ItemKind::Path,
                    ItemKind::Path => ItemKind::Text,
                };
                if self.kind == ItemKind::Text
                    && matches!(self.field, ItemField::Program | ItemField::Version)
                {
                    self.field = ItemField::Tags;
                }
                DialogAction::Continue
            }
            KeyCode::Backspace => {
                match self.field {
                    ItemField::Kind => {}
                    ItemField::Value => {
                        self.value.pop();
                    }
                    ItemField::Program => {
                        if self.kind == ItemKind::Path {
                            self.program.pop();
                        }
                    }
                    ItemField::Version => {
                        if self.kind == ItemKind::Path {
                            self.version.pop();
                        }
                    }
                    ItemField::Tags => {
                        self.tags.pop();
                    }
                }
                DialogAction::Continue
            }
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                match self.field {
                    ItemField::Kind => {}
                    ItemField::Value => self.value.push(c),
                    ItemField::Program => {
                        if self.kind == ItemKind::Path {
                            self.program.push(c);
                        }
                    }
                    ItemField::Version => {
                        if self.kind == ItemKind::Path {
                            self.version.push(c);
                        }
                    }
                    ItemField::Tags => self.tags.push(c),
                }
                DialogAction::Continue
            }
            _ => DialogAction::Continue,
        }
    }
}

pub fn create_or_edit_item_dialog<B: Backend>(
    terminal: &mut Terminal<B>,
    initial: Option<&CatalogItem>,
) -> Result<Option<CatalogItem>> {
    let mut st = ItemDialogState::new(initial);

    loop {
        terminal.draw(|f| {
            let area = centered_rect(80, 45, f.size());
            f.render_widget(Clear, area);

            let title = "🗃️ Item (Tab: next, Ctrl+T: toggle kind, Enter: save, Esc: cancel)";
            let block = Block::default().borders(Borders::ALL).title(title);

            let kind_s = match st.kind {
                ItemKind::Text => "Text",
                ItemKind::Path => "Path",
            };

            let prefix = |want: ItemField| if st.field == want { "> " } else { "  " };

            let program_line = if st.kind == ItemKind::Path {
                format!("{}Program: {}", prefix(ItemField::Program), st.program)
            } else {
                format!("{}Program: (n/a)", prefix(ItemField::Program))
            };
            let version_line = if st.kind == ItemKind::Path {
                format!("{}Version: {}", prefix(ItemField::Version), st.version)
            } else {
                format!("{}Version: (n/a)", prefix(ItemField::Version))
            };

            let text = format!(
                "{}Kind: {kind_s}\n{}Value: {}\n{program_line}\n{version_line}\n{}Tags: {}\n\nTip: Use Tags to filter; drop items only works for list-like vars.",
                prefix(ItemField::Kind),
                prefix(ItemField::Value),
                st.value,
                prefix(ItemField::Tags),
                st.tags,
            );
            let p = Paragraph::new(text).block(block);
            f.render_widget(p, area);
        })?;

        if let Some(key) = next_key_press(std::time::Duration::from_millis(100))? {
            match st.handle_key(key) {
                DialogAction::Continue => {}
                DialogAction::Cancel => return Ok(None),
                DialogAction::Save(item) => return Ok(Some(item)),
            }
        }
    }
}

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

    fn press(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn ctrl(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
    }

    fn type_str(mut feed: impl FnMut(KeyEvent), s: &str) {
        for c in s.chars() {
            feed(press(KeyCode::Char(c)));
        }
    }

    fn builtin_catalog() -> &'static Catalog {
        static CATALOG: std::sync::OnceLock<Catalog> = std::sync::OnceLock::new();
        CATALOG.get_or_init(Catalog::builtin)
    }

    #[test]
    fn var_dialog_fills_kind_and_separator_from_catalog() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "PGHOST");
        assert_eq!(st.kind, VarKind::Scalar);
        assert_eq!(st.origin.as_deref(), Some("postgres"));
        match st.handle_key(press(KeyCode::Enter)) {
            DialogAction::Save(def) => {
                assert_eq!(def.kind, VarKind::Scalar);
                assert_eq!(def.separator, "");
            }
            _ => panic!("expected save"),
        }
    }

    #[test]
    fn var_dialog_tab_completes_then_moves_on() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "no_pro");
        assert_eq!(st.suggestions.first().map(String::as_str), Some("NO_PROXY"));
        st.handle_key(press(KeyCode::Tab));
        assert_eq!(st.name, "NO_PROXY");
        assert_eq!(st.kind, VarKind::List);
        assert_eq!(st.separator, ",");
        assert!(st.field == VarField::Name);
        st.handle_key(press(KeyCode::Tab));
        assert!(st.field == VarField::Kind);
    }

    #[test]
    fn var_dialog_tab_keeps_custom_name_that_only_appears_inside_suggestions() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "HOST");
        assert!(!st.suggestions.is_empty());
        st.handle_key(press(KeyCode::Tab));
        assert_eq!(st.name, "HOST");
        assert!(st.field == VarField::Kind);
    }

    #[test]
    fn var_dialog_tab_takes_browsed_suggestion_even_if_not_a_prefix() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "HOST");
        let second = st.suggestions[1].clone();
        st.handle_key(press(KeyCode::Down));
        st.handle_key(press(KeyCode::Tab));
        assert_eq!(st.name, second);
    }

    #[test]
    fn var_dialog_down_picks_next_suggestion() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "PGSSL");
        let second = st.suggestions[1].clone();
        st.handle_key(press(KeyCode::Down));
        st.handle_key(press(KeyCode::Tab));
        assert_eq!(st.name, second);
    }

    #[test]
    fn var_dialog_keeps_manual_kind_when_name_changes() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        st.handle_key(ctrl('t'));
        assert_eq!(st.kind, VarKind::Scalar);
        type_str(|k| drop(st.handle_key(k)), "GOPATH");
        assert_eq!(st.kind, VarKind::Scalar);
    }

    #[test]
    fn var_dialog_resets_to_default_when_name_stops_matching() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "PGHOST");
        assert_eq!(st.kind, VarKind::Scalar);
        for _ in 0.."PGHOST".len() {
            st.handle_key(press(KeyCode::Backspace));
        }
        type_str(|k| drop(st.handle_key(k)), "MYLIST");
        assert_eq!(st.kind, VarKind::List);
        assert_eq!(st.separator, ":");
        assert_eq!(st.origin, None);
    }

    // F10: bare 't'/'T' must be typed into the focused field, not toggle kind.
    #[test]
    fn var_dialog_types_t_into_name_instead_of_toggling_kind() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "PYTHONPATH");
        assert_eq!(st.name, "PYTHONPATH");
        assert_eq!(st.kind, VarKind::List);
    }

    // Ctrl+C must cancel a dialog like Esc; the global quit chord is never
    // a dead key inside a modal loop.
    #[test]
    fn var_dialog_ctrl_c_cancels() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        assert!(matches!(st.handle_key(ctrl('c')), DialogAction::Cancel));
        let mut st = CustomVarDialogState::new(builtin_catalog());
        assert!(matches!(st.handle_key(ctrl('C')), DialogAction::Cancel));
    }

    #[test]
    fn item_dialog_ctrl_c_cancels() {
        let mut st = ItemDialogState::new(None);
        assert!(matches!(st.handle_key(ctrl('c')), DialogAction::Cancel));
        let mut st = ItemDialogState::new(None);
        assert!(matches!(st.handle_key(ctrl('C')), DialogAction::Cancel));
    }

    // F10: the kind toggle stays available on Ctrl+T.
    #[test]
    fn var_dialog_ctrl_t_toggles_kind() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        assert!(matches!(st.handle_key(ctrl('t')), DialogAction::Continue));
        assert_eq!(st.kind, VarKind::Scalar);
        assert!(matches!(st.handle_key(ctrl('T')), DialogAction::Continue));
        assert_eq!(st.kind, VarKind::List);
    }

    // C3: an empty List separator must not be saved; the dialog stays open.
    #[test]
    fn var_dialog_rejects_empty_list_separator() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "MYLIST");
        st.separator.clear();
        assert!(matches!(
            st.handle_key(press(KeyCode::Enter)),
            DialogAction::Continue
        ));
        assert!(st.hint.is_some());
    }

    #[test]
    fn var_dialog_saves_valid_list_var() {
        let mut st = CustomVarDialogState::new(builtin_catalog());
        type_str(|k| drop(st.handle_key(k)), "MYLIST");
        match st.handle_key(press(KeyCode::Enter)) {
            DialogAction::Save(def) => {
                assert_eq!(def.name, "MYLIST");
                assert_eq!(def.kind, VarKind::List);
                assert_eq!(def.separator, ":");
            }
            _ => panic!("expected save"),
        }
    }

    fn path_item() -> CatalogItem {
        CatalogItem {
            id: None,
            kind: ItemKind::Path,
            value: String::new(),
            program: Some("python".to_string()),
            version: Some("3.12".to_string()),
            tags: vec![],
        }
    }

    // F10: typing a path containing 't' must not flip kind or wipe fields.
    #[test]
    fn item_dialog_types_t_into_value_without_toggling_or_wiping() {
        let initial = path_item();
        let mut st = ItemDialogState::new(Some(&initial));
        type_str(|k| drop(st.handle_key(k)), "/opt/tools");
        assert_eq!(st.value, "/opt/tools");
        assert_eq!(st.kind, ItemKind::Path);
        assert_eq!(st.program, "python");
        assert_eq!(st.version, "3.12");
    }

    // F10: Ctrl+T toggles kind but keeps the program/version buffers, so an
    // accidental toggle-and-back loses nothing.
    #[test]
    fn item_dialog_ctrl_t_toggle_keeps_program_and_version() {
        let initial = path_item();
        let mut st = ItemDialogState::new(Some(&initial));
        st.handle_key(ctrl('t'));
        assert_eq!(st.kind, ItemKind::Text);
        st.handle_key(ctrl('t'));
        assert_eq!(st.kind, ItemKind::Path);
        assert_eq!(st.program, "python");
        assert_eq!(st.version, "3.12");
    }

    // Program/version are still omitted from the saved item for Text kind.
    #[test]
    fn item_dialog_save_omits_program_and_version_for_text_kind() {
        let initial = path_item();
        let mut st = ItemDialogState::new(Some(&initial));
        type_str(|k| drop(st.handle_key(k)), "hello");
        st.handle_key(ctrl('t'));
        assert_eq!(st.kind, ItemKind::Text);
        match st.handle_key(press(KeyCode::Enter)) {
            DialogAction::Save(item) => {
                assert_eq!(item.value, "hello");
                assert_eq!(item.program, None);
                assert_eq!(item.version, None);
            }
            _ => panic!("expected save"),
        }
    }
}