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