1use forms::{Field as Descriptor, FormValues, Kind};
5use tvui::{ColorDepth, Theme};
6
7use super::{Form, FormKind};
8use crate::event::Intent;
9use crate::keymap::Keys;
10use crate::modal::Spec;
11use crate::widgets::{SelectOption, Widget};
12
13pub const OPTIONS_BUTTONS: [Spec; 3] = [
15 ("~O~K", Intent::Submit),
16 ("~C~ancel", Intent::CloseTopmost),
17 ("A~p~ply", Intent::ApplyOptions),
18];
19
20const fn choice(key: &'static str, label: &'static str) -> Descriptor {
21 Descriptor {
22 key,
23 label,
24 kind: Kind::Choice {
25 options: &[],
26 default: None,
27 },
28 required: true,
29 }
30}
31
32const fn text_area(key: &'static str, label: &'static str) -> Descriptor {
33 Descriptor {
34 key,
35 label,
36 kind: Kind::Text {
37 multiline: true,
38 suggest: None,
39 },
40 required: false,
41 }
42}
43
44pub(super) const OPTIONS: forms::Form = forms::Form {
45 name: "options",
46 title: "Options",
47 fields: &[
48 choice("theme", "Theme"),
49 choice("keymap", "Keymap"),
50 choice("colors", "Colours"),
51 text_area("theme-overrides", "Theme overrides"),
52 text_area("keymap-overrides", "Keymap overrides"),
53 ],
54 action: forms::Action::Mutation,
55};
56
57fn colour_names() -> impl Iterator<Item = &'static str> {
58 let depths = [ColorDepth::Rgb, ColorDepth::Indexed256, ColorDepth::Ansi16];
59 std::iter::once("auto").chain(depths.map(ColorDepth::name))
60}
61
62fn options_of<'a>(names: impl Iterator<Item = &'a str>) -> Vec<SelectOption> {
63 names
64 .map(|name| SelectOption {
65 id: name.to_string(),
66 label: name.to_string(),
67 })
68 .collect()
69}
70
71impl Form {
72 #[must_use]
74 pub fn options(shown: &FormValues) -> Self {
75 let mut form = Self::from_descriptor(&OPTIONS, FormKind::Options);
76 let lists = [
77 ("theme", options_of(Theme::preset_names())),
78 ("keymap", options_of(Keys::preset_names())),
79 ("colors", options_of(colour_names())),
80 ];
81 for (key, options) in lists {
82 if let Some(select) = form.select_mut(key) {
83 select.set_options(options);
84 }
85 }
86 form.load(shown);
87 form
88 }
89
90 pub fn lock_choice(&mut self, key: &str, id: &str, flag: &str) {
92 if let Some(select) = self.select_mut(key) {
93 select.set_options(vec![SelectOption {
94 id: id.to_string(),
95 label: format!("{id} (set by {flag})"),
96 }]);
97 }
98 }
99
100 fn select_mut(&mut self, key: &str) -> Option<&mut crate::widgets::SelectWidget> {
101 self.fields
102 .iter_mut()
103 .find(|field| field.key == Some(key))
104 .and_then(|field| match &mut field.widget {
105 Widget::Select(select) => Some(select),
106 _ => None,
107 })
108 }
109
110 #[must_use]
112 pub fn buttons(&self) -> &'static [Spec] {
113 match self.kind {
114 FormKind::Options => &OPTIONS_BUTTONS,
115 _ => &super::BUTTONS,
116 }
117 }
118}