quetty 0.1.9

Terminal-based Azure Service Bus queue manager with intuitive TUI interface
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
use crate::components::base_popup::PopupBuilder;
use crate::components::common::{Msg, ThemeActivityMsg};
use crate::components::state::ComponentState;
use crate::error::AppResult;
use crate::theme::ThemeManager;
use crate::theme::types::ThemeCollectionWithMetadata;
use tuirealm::command::{Cmd, CmdResult};
use tuirealm::event::{Key, KeyEvent};
use tuirealm::props::{Alignment, Style, TextModifiers};
use tuirealm::ratatui::layout::Rect;
use tuirealm::ratatui::widgets::{List, ListItem};
use tuirealm::{
    AttrValue, Attribute, Component, Event, Frame, MockComponent, NoUserEvent, State, StateValue,
};

const CMD_RESULT_THEME_SELECTED: &str = "ThemeSelected";
const CMD_RESULT_CLOSE_PICKER: &str = "ClosePicker";

/// Interactive theme picker component for selecting application themes and flavors.
///
/// Provides a two-level selection interface where users first choose a theme family,
/// then select a specific flavor within that theme. Displays theme metadata including
/// icons and descriptions for better user experience.
///
/// # Navigation
///
/// - **Arrow Keys** - Navigate between themes and flavors
/// - **Enter** - Confirm selection and apply theme
/// - **Tab** - Switch between theme and flavor selection modes
/// - **Escape** - Cancel and close picker
///
/// # Examples
///
/// ```ignore
/// use quetty::components::theme_picker::ThemePicker;
/// use quetty::components::state::ComponentState;
///
/// let mut picker = ThemePicker::new();
/// picker.mount()?; // Loads available themes
///
/// // Component handles user input and theme selection
/// ```
pub struct ThemePicker {
    themes: ThemeCollectionWithMetadata, // (theme_name, [(flavor_name, theme_icon, flavor_icon)])
    theme_selected: usize,               // Selected theme index
    flavor_selected: usize,              // Selected flavor index for current theme
    mode: PickerMode,
}

#[derive(Debug, PartialEq)]
enum PickerMode {
    SelectingTheme,
    SelectingFlavor,
}

impl ThemePicker {
    pub fn new() -> Self {
        Self {
            themes: Vec::new(),
            theme_selected: 0,
            flavor_selected: 0,
            mode: PickerMode::SelectingTheme,
        }
    }

    pub fn load_themes(&mut self) {
        match ThemeManager::global_discover_themes_with_metadata() {
            Ok(themes) => {
                self.themes = themes;
                if !self.themes.is_empty() {
                    self.theme_selected = 0;
                    self.flavor_selected = 0;
                }
            }
            Err(e) => {
                log::error!("Failed to discover themes: {e}");
                // Fallback to default themes with generic icons
                self.themes = vec![(
                    "quetty".to_string(),
                    vec![
                        ("dark".to_string(), "🎨".to_string(), "🎭".to_string()),
                        ("light".to_string(), "🎨".to_string(), "🎭".to_string()),
                    ],
                )];
            }
        }
    }

    fn get_current_theme(&self) -> Option<&String> {
        self.themes.get(self.theme_selected).map(|(name, _)| name)
    }

    fn get_current_flavor(&self) -> Option<&String> {
        self.themes
            .get(self.theme_selected)
            .and_then(|(_, flavors)| flavors.get(self.flavor_selected).map(|(name, _, _)| name))
    }

    fn get_display_items(&self) -> Vec<String> {
        match self.mode {
            PickerMode::SelectingTheme => self
                .themes
                .iter()
                .map(|(name, flavors)| {
                    // Get theme icon from first flavor's metadata (they should all have the same theme icon)
                    let icon = flavors
                        .first()
                        .map(|(_, theme_icon, _)| theme_icon.as_str())
                        .unwrap_or("🎨");
                    format!("{icon} {name}")
                })
                .collect(),
            PickerMode::SelectingFlavor => {
                if let Some((theme_name, flavors)) = self.themes.get(self.theme_selected) {
                    flavors
                        .iter()
                        .map(|(flavor_name, _, flavor_icon)| {
                            format!("{flavor_icon} {flavor_name} ({theme_name})")
                        })
                        .collect()
                } else {
                    vec![]
                }
            }
        }
    }
}

impl MockComponent for ThemePicker {
    fn view(&mut self, frame: &mut Frame, area: Rect) {
        let display_items = self.get_display_items();

        let items: Vec<ListItem> = display_items
            .iter()
            .enumerate()
            .map(|(i, item)| {
                let mut list_item = ListItem::new(item.clone());
                let selected_index = match self.mode {
                    PickerMode::SelectingTheme => self.theme_selected,
                    PickerMode::SelectingFlavor => self.flavor_selected,
                };

                if i == selected_index {
                    list_item = list_item.style(
                        Style::default()
                            .fg(ThemeManager::namespace_list_item())
                            .bg(ThemeManager::surface())
                            .add_modifier(TextModifiers::BOLD),
                    );
                } else {
                    list_item = list_item.style(Style::default().fg(ThemeManager::text_primary()));
                }
                list_item
            })
            .collect();

        let title = match self.mode {
            PickerMode::SelectingTheme => "  🎨 Select Theme  ".to_string(),
            PickerMode::SelectingFlavor => {
                if let Some(theme_name) = self.get_current_theme() {
                    format!("  🎭 Select {theme_name} Flavor  ")
                } else {
                    "  🎭 Select Flavor  ".to_string()
                }
            }
        };

        let instructions = match self.mode {
            PickerMode::SelectingTheme => "↑/↓/j/k: Navigate, Enter: Select Theme, Esc: Close",
            PickerMode::SelectingFlavor => "↑/↓/j/k: Navigate, Enter: Apply, Backspace/Esc: Back",
        };

        // Use PopupBuilder for consistent styling
        let popup_block = PopupBuilder::new("Theme Picker").create_block_with_title(title);

        let list = List::new(items)
            .block(popup_block)
            .highlight_style(
                Style::default()
                    .fg(ThemeManager::selection_fg())
                    .bg(ThemeManager::selection_bg())
                    .add_modifier(TextModifiers::BOLD),
            )
            .highlight_symbol("â–¶ ");

        frame.render_widget(list, area);

        // Render instructions at the bottom
        let instruction_area = Rect {
            x: area.x,
            y: area.y + area.height - 1,
            width: area.width,
            height: 1,
        };

        if instruction_area.y < area.y + area.height {
            let instruction_widget = tuirealm::ratatui::widgets::Paragraph::new(instructions)
                .style(Style::default().fg(ThemeManager::text_muted()))
                .alignment(Alignment::Center);
            frame.render_widget(instruction_widget, instruction_area);
        }
    }

    fn query(&self, _attr: Attribute) -> Option<AttrValue> {
        None
    }

    fn attr(&mut self, _attr: Attribute, _value: AttrValue) {}

    fn state(&self) -> State {
        if let (Some(theme), Some(flavor)) = (self.get_current_theme(), self.get_current_flavor()) {
            State::One(StateValue::String(format!("{theme}:{flavor}")))
        } else {
            State::None
        }
    }

    fn perform(&mut self, _cmd: Cmd) -> CmdResult {
        CmdResult::None
    }
}

impl Component<Msg, NoUserEvent> for ThemePicker {
    fn on(&mut self, ev: Event<NoUserEvent>) -> Option<Msg> {
        let cmd_result = match ev {
            Event::Keyboard(KeyEvent {
                code: Key::Down, ..
            }) => {
                match self.mode {
                    PickerMode::SelectingTheme => {
                        if self.theme_selected + 1 < self.themes.len() {
                            self.theme_selected += 1;
                            self.flavor_selected = 0; // Reset flavor selection
                        }
                    }
                    PickerMode::SelectingFlavor => {
                        if let Some((_, flavors)) = self.themes.get(self.theme_selected) {
                            if self.flavor_selected + 1 < flavors.len() {
                                self.flavor_selected += 1;
                            }
                        }
                    }
                }
                CmdResult::Changed(State::One(StateValue::Usize(match self.mode {
                    PickerMode::SelectingTheme => self.theme_selected,
                    PickerMode::SelectingFlavor => self.flavor_selected,
                })))
            }
            Event::Keyboard(KeyEvent { code: Key::Up, .. }) => {
                match self.mode {
                    PickerMode::SelectingTheme => {
                        if self.theme_selected > 0 {
                            self.theme_selected -= 1;
                            self.flavor_selected = 0; // Reset flavor selection
                        }
                    }
                    PickerMode::SelectingFlavor => {
                        if self.flavor_selected > 0 {
                            self.flavor_selected -= 1;
                        }
                    }
                }
                CmdResult::Changed(State::One(StateValue::Usize(match self.mode {
                    PickerMode::SelectingTheme => self.theme_selected,
                    PickerMode::SelectingFlavor => self.flavor_selected,
                })))
            }
            Event::Keyboard(KeyEvent {
                code: Key::Enter, ..
            }) => {
                match self.mode {
                    PickerMode::SelectingTheme => {
                        // Move to flavor selection
                        self.mode = PickerMode::SelectingFlavor;
                        self.flavor_selected = 0;
                        CmdResult::Changed(State::One(StateValue::String(
                            "flavor_mode".to_string(),
                        )))
                    }
                    PickerMode::SelectingFlavor => {
                        // Apply the selected theme
                        if let (Some(theme), Some(flavor)) =
                            (self.get_current_theme(), self.get_current_flavor())
                        {
                            CmdResult::Custom(
                                CMD_RESULT_THEME_SELECTED,
                                State::One(StateValue::String(format!("{theme}:{flavor}"))),
                            )
                        } else {
                            CmdResult::None
                        }
                    }
                }
            }
            Event::Keyboard(KeyEvent {
                code: Key::Backspace,
                ..
            }) => {
                if self.mode == PickerMode::SelectingFlavor {
                    self.mode = PickerMode::SelectingTheme;
                    CmdResult::Changed(State::One(StateValue::String("theme_mode".to_string())))
                } else {
                    CmdResult::None
                }
            }
            Event::Keyboard(KeyEvent { code: Key::Esc, .. }) => {
                match self.mode {
                    PickerMode::SelectingFlavor => {
                        // Go back to theme selection mode
                        self.mode = PickerMode::SelectingTheme;
                        CmdResult::Changed(State::One(StateValue::String("theme_mode".to_string())))
                    }
                    PickerMode::SelectingTheme => {
                        // Close the picker
                        CmdResult::Custom(CMD_RESULT_CLOSE_PICKER, State::None)
                    }
                }
            }
            Event::Keyboard(KeyEvent {
                code: Key::Char(c), ..
            }) => {
                let keys = crate::config::get_config_or_panic().keys();
                if c == keys.up() {
                    match self.mode {
                        PickerMode::SelectingTheme => {
                            if self.theme_selected > 0 {
                                self.theme_selected -= 1;
                                self.flavor_selected = 0; // Reset flavor selection
                            }
                        }
                        PickerMode::SelectingFlavor => {
                            if self.flavor_selected > 0 {
                                self.flavor_selected -= 1;
                            }
                        }
                    }
                    CmdResult::Changed(State::One(StateValue::Usize(match self.mode {
                        PickerMode::SelectingTheme => self.theme_selected,
                        PickerMode::SelectingFlavor => self.flavor_selected,
                    })))
                } else if c == keys.down() {
                    match self.mode {
                        PickerMode::SelectingTheme => {
                            if self.theme_selected + 1 < self.themes.len() {
                                self.theme_selected += 1;
                                self.flavor_selected = 0; // Reset flavor selection
                            }
                        }
                        PickerMode::SelectingFlavor => {
                            if let Some((_, flavors)) = self.themes.get(self.theme_selected) {
                                if self.flavor_selected + 1 < flavors.len() {
                                    self.flavor_selected += 1;
                                }
                            }
                        }
                    }
                    CmdResult::Changed(State::One(StateValue::Usize(match self.mode {
                        PickerMode::SelectingTheme => self.theme_selected,
                        PickerMode::SelectingFlavor => self.flavor_selected,
                    })))
                } else {
                    CmdResult::None
                }
            }
            _ => CmdResult::None,
        };

        match cmd_result {
            CmdResult::Custom(CMD_RESULT_THEME_SELECTED, state) => {
                if let State::One(StateValue::String(theme_flavor)) = state {
                    let parts: Vec<&str> = theme_flavor.split(':').collect();
                    if parts.len() == 2 {
                        Some(Msg::ThemeActivity(ThemeActivityMsg::ThemeSelected(
                            parts[0].to_string(),
                            parts[1].to_string(),
                        )))
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
            CmdResult::Custom(CMD_RESULT_CLOSE_PICKER, _) => {
                Some(Msg::ThemeActivity(ThemeActivityMsg::ThemePickerClosed))
            }
            _ => Some(Msg::ForceRedraw),
        }
    }
}

impl ComponentState for ThemePicker {
    fn mount(&mut self) -> AppResult<()> {
        // Load themes during component mounting
        self.load_themes();
        Ok(())
    }
}

impl Default for ThemePicker {
    fn default() -> Self {
        Self::new()
    }
}