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
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
use crate::components::common::{Msg, PopupActivityMsg};
use crate::components::state::ComponentState;
use crate::config::limits::{MAX_PAGE_SIZE, MIN_PAGE_SIZE};
use crate::theme::ThemeManager;
use tuirealm::{
    Component, Event, MockComponent, NoUserEvent, State, StateValue,
    command::{Cmd, CmdResult},
    event::{Key, KeyEvent, KeyModifiers},
    ratatui::{
        Frame,
        layout::{Alignment, Rect},
        style::{Modifier, Style},
        text::{Line, Span, Text},
        widgets::{Block, BorderType, Borders, Paragraph, Wrap},
    },
};

/// A popup component for selecting page size with predefined options.
///
/// This component provides a user-friendly interface for selecting the number
/// of messages to display per page, with options from 100 to 1000 in 100-message intervals.
///
/// # Usage
///
/// ```rust
/// use quetty::components::page_size_popup::PageSizePopup;
///
/// let popup = PageSizePopup::new();
/// ```
///
/// # Events
///
/// - `KeyEvent::Enter` - Submits the selected page size
/// - `KeyEvent::Esc` - Cancels the selection
/// - Arrow keys - Navigate through options
/// - Number keys - Jump to specific option
///
/// # Messages
///
/// Emits `Msg::PopupActivity(PopupActivityMsg::PageSizeResult(size))` on successful selection.
pub struct PageSizePopup {
    options: Vec<u32>,
    selected_index: usize,
    is_mounted: bool,
}

impl PageSizePopup {
    /// Creates a new page size selection popup.
    ///
    /// # Returns
    ///
    /// A new `PageSizePopup` instance ready for mounting.
    pub fn new() -> Self {
        // Generate options from 100 to 1000 in 100-message intervals
        let options: Vec<u32> = (MIN_PAGE_SIZE..=MAX_PAGE_SIZE).step_by(100).collect();

        Self {
            options,
            selected_index: 0, // Default to first option (100)
            is_mounted: false,
        }
    }

    /// Gets the currently selected page size.
    ///
    /// # Returns
    ///
    /// The selected page size value.
    pub fn get_selected_size(&self) -> u32 {
        self.options[self.selected_index]
    }

    /// Renders the list of page size options.
    fn render_options(&self) -> Vec<Line> {
        self.options
            .iter()
            .enumerate()
            .map(|(index, &size)| {
                let is_selected = index == self.selected_index;
                let prefix = if is_selected { "" } else { "" };
                let style = if is_selected {
                    Style::default()
                        .fg(ThemeManager::primary_accent())
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(ThemeManager::text_primary())
                };

                Line::from(vec![
                    Span::styled(prefix, style),
                    Span::styled(format!("{size} messages per page"), style),
                ])
            })
            .collect()
    }
}

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

impl MockComponent for PageSizePopup {
    fn view(&mut self, frame: &mut Frame, area: Rect) {
        // Create the border block
        let block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(ThemeManager::primary_accent()))
            .title(" Page Size Selection ")
            .title_alignment(Alignment::Center);

        // Create content lines
        let mut lines = Vec::new();

        // Add empty line at the top for better spacing
        lines.push(Line::from(""));

        // Add description
        lines.push(Line::from(vec![Span::styled(
            "Select the number of messages to display per page:",
            Style::default().fg(ThemeManager::text_primary()),
        )]));

        lines.push(Line::from(""));

        // Add options
        for option_line in self.render_options() {
            lines.push(option_line);
        }

        lines.push(Line::from(""));

        // Add instructions
        lines.push(Line::from(vec![Span::styled(
            "Use ↑/↓ or j/k to navigate, Enter to select, Esc to cancel",
            Style::default().fg(ThemeManager::text_muted()),
        )]));

        // Create the text widget
        let text = Text::from(lines);
        let paragraph = Paragraph::new(text)
            .block(block)
            .alignment(Alignment::Left)
            .wrap(Wrap { trim: true });

        frame.render_widget(paragraph, area);
    }

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

    fn attr(&mut self, _attr: tuirealm::Attribute, _value: tuirealm::AttrValue) {
        // No attributes to set
    }

    fn state(&self) -> State {
        State::One(StateValue::Usize(self.selected_index))
    }

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

impl Component<Msg, NoUserEvent> for PageSizePopup {
    fn on(&mut self, ev: Event<NoUserEvent>) -> Option<Msg> {
        match ev {
            Event::Keyboard(KeyEvent {
                code: Key::Enter,
                modifiers: KeyModifiers::NONE,
            }) => {
                // Submit the selected page size
                Some(Msg::PopupActivity(PopupActivityMsg::PageSizeResult(
                    self.get_selected_size() as usize,
                )))
            }
            Event::Keyboard(KeyEvent {
                code: Key::Esc,
                modifiers: KeyModifiers::NONE,
            }) => {
                // Cancel the selection
                Some(Msg::PopupActivity(PopupActivityMsg::ClosePageSize))
            }
            Event::Keyboard(KeyEvent {
                code: Key::Up,
                modifiers: KeyModifiers::NONE,
            }) => {
                // Move to previous option
                if self.selected_index > 0 {
                    self.selected_index -= 1;
                    Some(Msg::ForceRedraw)
                } else {
                    None
                }
            }
            Event::Keyboard(KeyEvent {
                code: Key::Down,
                modifiers: KeyModifiers::NONE,
            }) => {
                // Move to next option
                if self.selected_index < self.options.len() - 1 {
                    self.selected_index += 1;
                    Some(Msg::ForceRedraw)
                } else {
                    None
                }
            }
            Event::Keyboard(KeyEvent {
                code: Key::Char('k'),
                modifiers: KeyModifiers::NONE,
            }) => {
                // Move to previous option (vim-style)
                if self.selected_index > 0 {
                    self.selected_index -= 1;
                    Some(Msg::ForceRedraw)
                } else {
                    None
                }
            }
            Event::Keyboard(KeyEvent {
                code: Key::Char('j'),
                modifiers: KeyModifiers::NONE,
            }) => {
                // Move to next option (vim-style)
                if self.selected_index < self.options.len() - 1 {
                    self.selected_index += 1;
                    Some(Msg::ForceRedraw)
                } else {
                    None
                }
            }
            Event::Keyboard(KeyEvent {
                code: Key::Char(c),
                modifiers: KeyModifiers::NONE,
            }) => {
                // Jump to specific option based on number key
                if let Some(digit) = c.to_digit(10) {
                    let target_size = digit * 100;
                    if let Some(index) = self.options.iter().position(|&size| size == target_size) {
                        self.selected_index = index;
                        Some(Msg::ForceRedraw)
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

impl ComponentState for PageSizePopup {
    fn mount(&mut self) -> crate::error::AppResult<()> {
        log::debug!("Mounting PageSizePopup component");

        if self.is_mounted {
            log::warn!("PageSizePopup is already mounted");
            return Ok(());
        }

        self.is_mounted = true;
        log::debug!("PageSizePopup component mounted successfully");
        Ok(())
    }
}

impl Drop for PageSizePopup {
    fn drop(&mut self) {
        if self.is_mounted {
            log::debug!("PageSizePopup component dropped");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tuirealm::event::{Key, KeyEvent, KeyModifiers};

    #[test]
    fn test_page_size_popup_creation() {
        let popup = PageSizePopup::new();
        assert_eq!(popup.options.len(), 10); // 100, 200, ..., 1000
        assert_eq!(popup.options[0], 100);
        assert_eq!(popup.options[9], 1000);
        assert_eq!(popup.selected_index, 0);
    }

    #[test]
    fn test_get_selected_size() {
        let mut popup = PageSizePopup::new();
        assert_eq!(popup.get_selected_size(), 100);

        popup.selected_index = 4;
        assert_eq!(popup.get_selected_size(), 500);
    }

    #[test]
    fn test_options_generation() {
        let popup = PageSizePopup::new();
        let expected: Vec<u32> = (100..=1000).step_by(100).collect();
        assert_eq!(popup.options, expected);
    }

    #[test]
    fn test_navigation() {
        let mut popup = PageSizePopup::new();

        // Test initial state
        assert_eq!(popup.selected_index, 0);
        assert_eq!(popup.get_selected_size(), 100);

        // Test moving down
        popup.selected_index = 1;
        assert_eq!(popup.get_selected_size(), 200);

        // Test moving to middle
        popup.selected_index = 4;
        assert_eq!(popup.get_selected_size(), 500);

        // Test moving to end
        popup.selected_index = 9;
        assert_eq!(popup.get_selected_size(), 1000);
    }

    #[test]
    fn test_number_key_navigation() {
        let mut popup = PageSizePopup::new();

        // Test number key '3' should select 300
        if let Some(digit) = '3'.to_digit(10) {
            let target_size = digit * 100;
            if let Some(index) = popup.options.iter().position(|&size| size == target_size) {
                popup.selected_index = index;
            }
        }
        assert_eq!(popup.get_selected_size(), 300);

        // Test number key '7' should select 700
        if let Some(digit) = '7'.to_digit(10) {
            let target_size = digit * 100;
            if let Some(index) = popup.options.iter().position(|&size| size == target_size) {
                popup.selected_index = index;
            }
        }
        assert_eq!(popup.get_selected_size(), 700);
    }

    #[test]
    fn test_arrow_key_events() {
        let mut popup = PageSizePopup::new();
        assert_eq!(popup.selected_index, 0);

        // Test down arrow
        let down_event = Event::Keyboard(KeyEvent {
            code: Key::Down,
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(down_event);
        assert_eq!(result, Some(Msg::ForceRedraw));
        assert_eq!(popup.selected_index, 1);

        // Test up arrow
        let up_event = Event::Keyboard(KeyEvent {
            code: Key::Up,
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(up_event);
        assert_eq!(result, Some(Msg::ForceRedraw));
        assert_eq!(popup.selected_index, 0);

        // Test up arrow at top (should not change)
        let up_event = Event::Keyboard(KeyEvent {
            code: Key::Up,
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(up_event);
        assert_eq!(result, None);
        assert_eq!(popup.selected_index, 0);

        // Test down arrow at bottom (should not change)
        popup.selected_index = popup.options.len() - 1;
        let down_event = Event::Keyboard(KeyEvent {
            code: Key::Down,
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(down_event);
        assert_eq!(result, None);
        assert_eq!(popup.selected_index, popup.options.len() - 1);
    }

    #[test]
    fn test_jk_navigation() {
        let mut popup = PageSizePopup::new();
        assert_eq!(popup.selected_index, 0);

        // Test 'j' key (move down)
        let j_event = Event::Keyboard(KeyEvent {
            code: Key::Char('j'),
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(j_event);
        assert_eq!(result, Some(Msg::ForceRedraw));
        assert_eq!(popup.selected_index, 1);

        // Test 'k' key (move up)
        let k_event = Event::Keyboard(KeyEvent {
            code: Key::Char('k'),
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(k_event);
        assert_eq!(result, Some(Msg::ForceRedraw));
        assert_eq!(popup.selected_index, 0);

        // Test 'k' key at top (should not change)
        let k_event = Event::Keyboard(KeyEvent {
            code: Key::Char('k'),
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(k_event);
        assert_eq!(result, None);
        assert_eq!(popup.selected_index, 0);

        // Test 'j' key at bottom (should not change)
        popup.selected_index = popup.options.len() - 1;
        let j_event = Event::Keyboard(KeyEvent {
            code: Key::Char('j'),
            modifiers: KeyModifiers::NONE,
        });
        let result = popup.on(j_event);
        assert_eq!(result, None);
        assert_eq!(popup.selected_index, popup.options.len() - 1);
    }

    #[test]
    fn test_enter_and_escape_events() {
        let mut popup = PageSizePopup::new();

        // Test Enter should return PageSizeResult
        let enter_event = Event::Keyboard(KeyEvent {
            code: Key::Enter,
            modifiers: KeyModifiers::NONE,
        });

        if let Some(msg) = popup.on(enter_event) {
            match msg {
                Msg::PopupActivity(PopupActivityMsg::PageSizeResult(size)) => {
                    assert_eq!(size, 100); // Default selection
                }
                _ => panic!("Enter should return PageSizeResult message"),
            }
        } else {
            panic!("Enter should return a message");
        }

        // Test Escape should return ClosePageSize
        let escape_event = Event::Keyboard(KeyEvent {
            code: Key::Esc,
            modifiers: KeyModifiers::NONE,
        });

        if let Some(msg) = popup.on(escape_event) {
            match msg {
                Msg::PopupActivity(PopupActivityMsg::ClosePageSize) => {
                    // Expected
                }
                _ => panic!("Escape should return ClosePageSize message"),
            }
        } else {
            panic!("Escape should return a message");
        }
    }
}