Skip to main content

bitbucket_cli/tui/
app.rs

1use anyhow::Result;
2use crossterm::{
3    event::{DisableMouseCapture, EnableMouseCapture},
4    execute,
5    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
6};
7use ratatui::{Terminal, backend::CrosstermBackend};
8use std::future::Future;
9use std::io;
10use tokio::task::JoinSet;
11
12use super::event::{Event, EventHandler};
13use super::ui;
14use super::views::{View, ViewState};
15use crate::api::BitbucketClient;
16use crate::models::{Issue, Paginated, Pipeline, PullRequest, Repository};
17
18/// Application state
19pub struct App {
20    /// Is the application running
21    pub running: bool,
22    /// Current view
23    pub current_view: View,
24    /// View-specific state
25    pub view_state: ViewState,
26    /// API client
27    pub client: Option<BitbucketClient>,
28    /// Current workspace
29    pub workspace: Option<String>,
30    /// Status message
31    pub status: Option<String>,
32    /// Is loading data
33    pub loading: bool,
34    /// Error message
35    pub error: Option<String>,
36
37    // Data
38    pub repositories: Vec<Repository>,
39    pub pull_requests: Vec<PullRequest>,
40    pub issues: Vec<Issue>,
41    pub pipelines: Vec<Pipeline>,
42}
43
44impl App {
45    pub fn new() -> Self {
46        Self {
47            running: true,
48            current_view: View::Dashboard,
49            view_state: ViewState::default(),
50            client: None,
51            workspace: None,
52            status: None,
53            loading: false,
54            error: None,
55            repositories: Vec::new(),
56            pull_requests: Vec::new(),
57            issues: Vec::new(),
58            pipelines: Vec::new(),
59        }
60    }
61
62    /// Initialize the application with API client
63    pub fn with_client(mut self, client: BitbucketClient) -> Self {
64        self.client = Some(client);
65        self
66    }
67
68    /// Set the workspace
69    pub fn with_workspace(mut self, workspace: String) -> Self {
70        self.workspace = Some(workspace);
71        self
72    }
73
74    /// Set status message
75    pub fn set_status(&mut self, message: &str) {
76        self.status = Some(message.to_string());
77    }
78
79    /// Clear status message
80    pub fn clear_status(&mut self) {
81        self.status = None;
82    }
83
84    /// Set error message
85    pub fn set_error(&mut self, message: &str) {
86        self.error = Some(message.to_string());
87    }
88
89    /// Clear error
90    pub fn clear_error(&mut self) {
91        self.error = None;
92    }
93
94    /// Switch to a different view
95    pub fn switch_view(&mut self, view: View) {
96        self.current_view = view;
97        self.view_state.selected_index = 0;
98        self.clear_error();
99    }
100
101    /// Handle keyboard input
102    pub fn handle_key(&mut self, key: crossterm::event::KeyEvent) {
103        use crossterm::event::KeyCode;
104
105        // Global keys
106        match key.code {
107            KeyCode::Char('q') => {
108                self.running = false;
109                return;
110            }
111            KeyCode::Char('1') => {
112                self.switch_view(View::Dashboard);
113                return;
114            }
115            KeyCode::Char('2') => {
116                self.switch_view(View::Repositories);
117                return;
118            }
119            KeyCode::Char('3') => {
120                self.switch_view(View::PullRequests);
121                return;
122            }
123            KeyCode::Char('4') => {
124                self.switch_view(View::Issues);
125                return;
126            }
127            KeyCode::Char('5') => {
128                self.switch_view(View::Pipelines);
129                return;
130            }
131            KeyCode::Esc => {
132                self.clear_error();
133                return;
134            }
135            _ => {}
136        }
137
138        // View-specific keys
139        match key.code {
140            KeyCode::Up | KeyCode::Char('k') => {
141                self.view_state.previous();
142            }
143            KeyCode::Down | KeyCode::Char('j') => {
144                let max = match self.current_view {
145                    View::Dashboard => 4,
146                    View::Repositories => self.repositories.len(),
147                    View::PullRequests => self.pull_requests.len(),
148                    View::Issues => self.issues.len(),
149                    View::Pipelines => self.pipelines.len(),
150                };
151                self.view_state.next(max);
152            }
153            KeyCode::Enter => {
154                self.handle_select();
155            }
156            KeyCode::Char('r') => {
157                // Refresh will be handled in main loop
158            }
159            _ => {}
160        }
161    }
162
163    /// Handle selection
164    fn handle_select(&mut self) {
165        match self.current_view {
166            View::Dashboard => {
167                // Navigate to selected section
168                match self.view_state.selected_index {
169                    0 => self.switch_view(View::Repositories),
170                    1 => self.switch_view(View::PullRequests),
171                    2 => self.switch_view(View::Issues),
172                    3 => self.switch_view(View::Pipelines),
173                    _ => {}
174                }
175            }
176            View::Repositories => {
177                if let Some(repo) = self.repositories.get(self.view_state.selected_index) {
178                    self.set_status(&format!("Selected: {}", repo.full_name));
179                }
180            }
181            View::PullRequests => {
182                if let Some(pr) = self.pull_requests.get(self.view_state.selected_index) {
183                    self.set_status(&format!("Selected PR #{}: {}", pr.id, pr.title));
184                }
185            }
186            View::Issues => {
187                if let Some(issue) = self.issues.get(self.view_state.selected_index) {
188                    self.set_status(&format!("Selected Issue #{}: {}", issue.id, issue.title));
189                }
190            }
191            View::Pipelines => {
192                if let Some(pipeline) = self.pipelines.get(self.view_state.selected_index) {
193                    self.set_status(&format!("Selected Pipeline #{}", pipeline.build_number));
194                }
195            }
196        }
197    }
198
199    /// Quit the application
200    pub fn quit(&mut self) {
201        self.running = false;
202    }
203
204    /// Load repositories
205    pub async fn load_repositories(&mut self) -> Result<()> {
206        if let (Some(client), Some(workspace)) = (&self.client, &self.workspace) {
207            self.loading = true;
208            match client.list_repositories(workspace, None, Some(50)).await {
209                Ok(result) => {
210                    self.repositories = result.values;
211                    self.clear_error();
212                }
213                Err(e) => {
214                    self.set_error(&format!("Failed to load repositories: {}", e));
215                }
216            }
217            self.loading = false;
218        } else {
219            self.set_error("No workspace configured");
220        }
221        Ok(())
222    }
223
224    /// Get repository slugs for the workspace, fetching them only when not already loaded
225    async fn workspace_repo_slugs(
226        &mut self,
227        client: &BitbucketClient,
228        workspace: &str,
229    ) -> Option<Vec<String>> {
230        if !self.repositories.is_empty() {
231            return Some(
232                self.repositories
233                    .iter()
234                    .map(|repo| repo.slug.clone().unwrap_or_else(|| repo.name.clone()))
235                    .collect(),
236            );
237        }
238        match client.list_repositories(workspace, None, Some(50)).await {
239            Ok(result) => Some(
240                result
241                    .values
242                    .into_iter()
243                    .map(|repo| repo.slug.unwrap_or(repo.name))
244                    .collect(),
245            ),
246            Err(e) => {
247                self.set_error(&format!("Failed to load repositories: {}", e));
248                None
249            }
250        }
251    }
252
253    /// Fetch paginated data from every repository in parallel.
254    ///
255    /// Spawns one request per repository slug and drains them, returning the
256    /// collected values along with the number of repositories whose request
257    /// failed (API error or task panic).
258    async fn fetch_from_all_repos<T, F, Fut>(
259        client: &BitbucketClient,
260        workspace: &str,
261        repo_slugs: Vec<String>,
262        fetch: F,
263    ) -> (Vec<T>, usize)
264    where
265        F: Fn(BitbucketClient, String, String) -> Fut + Clone + Send + 'static,
266        Fut: Future<Output = Result<Paginated<T>>> + Send + 'static,
267        T: Send + 'static,
268    {
269        let mut requests = JoinSet::new();
270        for repo_slug in repo_slugs {
271            let client = client.clone();
272            let workspace = workspace.to_string();
273            let fetch = fetch.clone();
274            requests.spawn(async move { fetch(client, workspace, repo_slug).await });
275        }
276
277        let mut values = Vec::new();
278        let mut failures: usize = 0;
279        while let Some(result) = requests.join_next().await {
280            match result {
281                Ok(Ok(page)) => values.extend(page.values),
282                Ok(Err(_)) | Err(_) => failures += 1,
283            }
284        }
285        (values, failures)
286    }
287
288    /// Sort newest-first, restoring a deterministic order after the
289    /// concurrent fetch tasks complete in arbitrary order. Items without a
290    /// timestamp (`None`) sort last.
291    fn sort_newest_first<T, K: Ord>(items: &mut [T], key: impl Fn(&T) -> K) {
292        items.sort_by_key(|item| std::cmp::Reverse(key(item)));
293    }
294
295    /// Apply the shared post-fetch error rule: clear the error when at least
296    /// one repository succeeded (or there were no repositories to query), but
297    /// surface an error when every repository request failed.
298    fn apply_fetch_outcome(&mut self, repo_count: usize, failures: usize) {
299        if failures > 0 && failures == repo_count {
300            self.set_error(&format!(
301                "Failed to load data from all {} repositories",
302                failures
303            ));
304        } else {
305            self.clear_error();
306        }
307    }
308
309    /// Load pull requests for the current workspace
310    pub async fn load_pull_requests(&mut self) -> Result<()> {
311        if let (Some(client), Some(workspace)) = (self.client.clone(), self.workspace.clone()) {
312            self.loading = true;
313            self.pull_requests.clear();
314
315            // Load PRs from all repositories
316            let repo_slugs = match self.workspace_repo_slugs(&client, &workspace).await {
317                Some(slugs) => slugs,
318                None => {
319                    self.loading = false;
320                    return Ok(());
321                }
322            };
323            let repo_count = repo_slugs.len();
324
325            let (values, failures) = Self::fetch_from_all_repos(
326                &client,
327                &workspace,
328                repo_slugs,
329                |client, workspace, repo_slug| async move {
330                    client
331                        .list_pull_requests(&workspace, &repo_slug, None, None, Some(10))
332                        .await
333                },
334            )
335            .await;
336            self.pull_requests.extend(values);
337            Self::sort_newest_first(&mut self.pull_requests, |pr| pr.updated_on);
338
339            self.apply_fetch_outcome(repo_count, failures);
340            self.loading = false;
341        } else {
342            self.set_error("No workspace configured");
343        }
344        Ok(())
345    }
346
347    /// Load issues for the current workspace
348    pub async fn load_issues(&mut self) -> Result<()> {
349        if let (Some(client), Some(workspace)) = (self.client.clone(), self.workspace.clone()) {
350            self.loading = true;
351            self.issues.clear();
352
353            // Load issues from all repositories
354            let repo_slugs = match self.workspace_repo_slugs(&client, &workspace).await {
355                Some(slugs) => slugs,
356                None => {
357                    self.loading = false;
358                    return Ok(());
359                }
360            };
361
362            let repo_count = repo_slugs.len();
363
364            let (values, failures) = Self::fetch_from_all_repos(
365                &client,
366                &workspace,
367                repo_slugs,
368                |client, workspace, repo_slug| async move {
369                    client
370                        .list_issues(&workspace, &repo_slug, None, None, Some(10))
371                        .await
372                },
373            )
374            .await;
375            self.issues.extend(values);
376            Self::sort_newest_first(&mut self.issues, |issue| issue.created_on);
377
378            self.apply_fetch_outcome(repo_count, failures);
379            self.loading = false;
380        } else {
381            self.set_error("No workspace configured");
382        }
383        Ok(())
384    }
385
386    /// Load pipelines for the current workspace
387    pub async fn load_pipelines(&mut self) -> Result<()> {
388        if let (Some(client), Some(workspace)) = (self.client.clone(), self.workspace.clone()) {
389            self.loading = true;
390            self.pipelines.clear();
391
392            // Load pipelines from all repositories
393            let repo_slugs = match self.workspace_repo_slugs(&client, &workspace).await {
394                Some(slugs) => slugs,
395                None => {
396                    self.loading = false;
397                    return Ok(());
398                }
399            };
400
401            let repo_count = repo_slugs.len();
402
403            let (values, failures) = Self::fetch_from_all_repos(
404                &client,
405                &workspace,
406                repo_slugs,
407                |client, workspace, repo_slug| async move {
408                    client
409                        .list_pipelines(&workspace, &repo_slug, None, Some(10))
410                        .await
411                },
412            )
413            .await;
414            self.pipelines.extend(values);
415            Self::sort_newest_first(&mut self.pipelines, |pipeline| pipeline.created_on);
416
417            self.apply_fetch_outcome(repo_count, failures);
418            self.loading = false;
419        } else {
420            self.set_error("No workspace configured");
421        }
422        Ok(())
423    }
424
425    /// Load all data
426    pub async fn load_all_data(&mut self) -> Result<()> {
427        self.load_repositories().await?;
428        self.load_pull_requests().await?;
429        self.load_issues().await?;
430        self.load_pipelines().await?;
431        Ok(())
432    }
433}
434
435impl Default for App {
436    fn default() -> Self {
437        Self::new()
438    }
439}
440
441/// Run the TUI application
442pub async fn run_tui(workspace: Option<String>) -> Result<()> {
443    // Setup terminal
444    enable_raw_mode()?;
445    let mut stdout = io::stdout();
446    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
447    let backend = CrosstermBackend::new(stdout);
448    let mut terminal = Terminal::new(backend)?;
449
450    // Create app
451    let mut app = App::new();
452
453    // Try to get API client
454    match BitbucketClient::from_stored().await {
455        Ok(client) => {
456            app = app.with_client(client);
457            if let Some(ws) = workspace {
458                app = app.with_workspace(ws);
459            } else {
460                app.set_error("No workspace specified. Use: bitbucket tui --workspace <workspace>");
461            }
462        }
463        Err(e) => {
464            app.set_error(&format!("Not authenticated: {}", e));
465        }
466    }
467
468    // Load initial data if we have a workspace
469    if app.workspace.is_some() && app.client.is_some() {
470        app.set_status("Loading data...");
471        terminal.draw(|f| ui::draw(f, &app))?;
472
473        if let Err(e) = app.load_repositories().await {
474            app.set_error(&format!("Failed to load data: {}", e));
475        } else {
476            app.set_status("Data loaded. Press 'r' to refresh.");
477        }
478    }
479
480    // Create event handler
481    let event_handler = EventHandler::new(250);
482    let mut should_refresh = false;
483
484    // Main loop
485    while app.running {
486        // Draw UI
487        terminal.draw(|f| ui::draw(f, &app))?;
488
489        // Handle refresh if requested
490        if should_refresh && app.workspace.is_some() && app.client.is_some() {
491            should_refresh = false;
492            app.set_status("Refreshing...");
493            terminal.draw(|f| ui::draw(f, &app))?;
494
495            match app.current_view {
496                View::Dashboard | View::Repositories => {
497                    let _ = app.load_repositories().await;
498                }
499                View::PullRequests => {
500                    let _ = app.load_pull_requests().await;
501                }
502                View::Issues => {
503                    let _ = app.load_issues().await;
504                }
505                View::Pipelines => {
506                    let _ = app.load_pipelines().await;
507                }
508            }
509
510            app.set_status("Refreshed");
511        }
512
513        // Handle events
514        match event_handler.next()? {
515            Event::Key(key) => {
516                // Check if refresh was requested
517                if let crossterm::event::KeyCode::Char('r') = key.code {
518                    should_refresh = true;
519                }
520                app.handle_key(key);
521            }
522            Event::Tick => {
523                // Periodic tick for animations, etc.
524            }
525            Event::Resize(_, _) => {
526                // Terminal will redraw automatically
527            }
528            _ => {}
529        }
530    }
531
532    // Restore terminal
533    disable_raw_mode()?;
534    execute!(
535        terminal.backend_mut(),
536        LeaveAlternateScreen,
537        DisableMouseCapture
538    )?;
539    terminal.show_cursor()?;
540
541    Ok(())
542}
543
544#[cfg(test)]
545mod tests {
546    use super::App;
547
548    #[test]
549    fn sort_newest_first_is_deterministic_regardless_of_arrival_order() {
550        // Simulates items arriving in arbitrary JoinSet completion order,
551        // keyed by Option timestamps as the real models are.
552        let mut items: Vec<(Option<i64>, &str)> = vec![
553            (Some(2), "middle"),
554            (None, "undated"),
555            (Some(3), "newest"),
556            (Some(1), "oldest"),
557        ];
558        App::sort_newest_first(&mut items, |item| item.0);
559        let order: Vec<&str> = items.iter().map(|item| item.1).collect();
560        assert_eq!(order, vec!["newest", "middle", "oldest", "undated"]);
561    }
562}