From 69eada8a1ef504fac3debfbd76243d3c0ef3f248 Mon Sep 17 00:00:00 2001 From: zombocoder Date: Wed, 28 Oct 2026 13:24:11 +0200 Subject: [PATCH] feat: add issues mode toggled with `i` The dashboard starts on pull requests as before; `i` switches the whole view (nav tree, inbox, all-items list, per-repo lists, counts) to open issues and back. Issue lists are fetched lazily on first switch and cached under keys that include visibility and the issue filter. - New `[issues] filter` config: GitHub search qualifiers appended to every issue search, inbox included. Empty means all open issues. - Issue inbox lists issues assigned to the viewer. - Refresh only refetches the current mode; the other mode refetches when next shown. - PR-only keys (l, d, f) are no-ops in issues mode. - Content tables now keep the cursor row in view when scrolling; both the PR and issue tables previously rendered from row 0 regardless of the cursor. --- README.md | 28 +- src/app/actions.rs | 17 +- src/app/event_loop.rs | 153 +++++++++-- src/app/state.rs | 122 ++++++++- src/app/update.rs | 44 +++- src/github/graphql.rs | 155 ++++++++++- src/github/models.rs | 23 ++ src/github/queries.rs | 42 +++ src/ui/widgets.rs | 223 +++++++++++++--- src/util/config.rs | 28 ++ tests/graphql_parse_tests.rs | 4 + tests/issues_tests.rs | 482 +++++++++++++++++++++++++++++++++++ tests/state_tests.rs | 3 +- tests/visibility_tests.rs | 1 + 14 files changed, 1248 insertions(+), 77 deletions(-) create mode 100644 tests/issues_tests.rs diff --git a/README.md b/README.md index 792ca88..0fb9d5f 100644 --- a/README.md +++ b/README.md @@ -5,13 +5,14 @@ [![GitHub release](https://img.shields.io/github/v/release/zombocoder/ghdash)](https://github.com/zombocoder/ghdash/releases/latest) [![License](https://img.shields.io/github/license/zombocoder/ghdash)](LICENSE) -A terminal UI dashboard for monitoring GitHub repositories, pull requests, and your review inbox. Built with Rust, ratatui, and the GitHub GraphQL API. +A terminal UI dashboard for monitoring GitHub repositories, pull requests, issues, and your review inbox. Built with Rust, ratatui, and the GitHub GraphQL API. ## Features - Monitor repos across multiple GitHub organizations and personal accounts - View all open pull requests in one place - Inbox view for PRs where you're requested for review or assigned +- Switch the whole dashboard between pull requests and issues with one key, with an optional search filter for issues - Expand/collapse organizations in the navigation tree - Client-side search filtering across PR titles, authors, and repos - Restrict the whole dashboard to public-only or private-only repos (handy for streaming) @@ -102,6 +103,10 @@ ttl_secs = 600 [ui] # Navigation pane width percentage (default: 30) nav_width_percent = 30 + +[issues] +# Optional: extra GitHub search qualifiers for issues mode (default: all open issues) +# filter = "label:bug -label:wontfix" ``` On macOS, `~/Library/Application Support/ghdash/config.toml` is also supported. @@ -121,6 +126,20 @@ screen. Keep a separate config for it and start with `ghdash --config ~/stream.t Cached PR lists are keyed by visibility, so switching modes never serves data fetched under the other one. +### Issues mode + +ghdash starts on pull requests. Press `i` to switch the whole dashboard to +issues: the nav tree shows open-issue counts per repo, "All Issues" lists every +open issue across your orgs and users, and the inbox lists issues assigned to +you. Press `i` again to go back. Issues are only fetched the first time you +switch, then cached like PRs. + +`issues.filter` narrows every issue list (including the inbox). It takes +[GitHub search syntax](https://docs.github.com/en/search-github/searching-on-github/searching-issues-and-pull-requests) +and is appended to `is:open is:issue`, so anything the GitHub search box +understands works here: `label:bug`, `-label:wontfix`, `no:assignee`, +`milestone:v1`, `author:alice`. `github.visibility` applies to issues too. + ## Usage ```sh @@ -143,6 +162,7 @@ ghdash --help # Show all options | `Tab` / `Shift+Tab` | Switch between nav and content panes | | `r` | Refresh all data | | `o` | Open selected item in browser | +| `i` | Switch between pull requests and issues | | `/` | Toggle search filter | | `q` / `Ctrl+C` | Quit | @@ -150,7 +170,7 @@ ghdash --help # Show all options | Key | Action | | --------------- | ------------------------------------ | -| Type | Filter PRs by title, author, or repo | +| Type | Filter by title, author, or repo (issues also by label) | | `Backspace` | Delete character | | `Esc` / `Enter` | Close search | @@ -168,14 +188,14 @@ src/ view.rs Layout composition github/ auth.rs Token resolution (gh CLI / env vars) - models.rs Repo, PullRequest, RateLimit types + models.rs Repo, PullRequest, Issue, RateLimit types queries.rs GraphQL query strings graphql.rs GithubClient with pagination cache/ store.rs JSON file cache with TTL ui/ theme.rs Style constants - widgets.rs Rendering functions (nav, PR table, status bar, overlays) + widgets.rs Rendering functions (nav, PR/issue tables, status bar, overlays) util/ config.rs TOML config with XDG paths time.rs Relative time formatting diff --git a/src/app/actions.rs b/src/app/actions.rs index 050d989..e01c991 100644 --- a/src/app/actions.rs +++ b/src/app/actions.rs @@ -1,4 +1,5 @@ -use crate::github::models::{PrDetail, PullRequest, RateLimit, Repo}; +use crate::app::state::ListMode; +use crate::github::models::{Issue, PrDetail, PullRequest, RateLimit, Repo}; #[derive(Debug)] #[allow(dead_code)] @@ -16,6 +17,7 @@ pub enum Action { CloseOverlay, ToggleHelp, CycleMergeFilter, + ToggleListMode, SearchInput(char), SearchBackspace, SearchClear, @@ -41,6 +43,14 @@ pub enum DataPayload { prs: Vec, rate_limit: RateLimit, }, + IssueInbox { + issues: Vec, + rate_limit: RateLimit, + }, + AllOpenIssues { + issues: Vec, + rate_limit: RateLimit, + }, PrDetailLoaded { /// PR url — the key into `AppState::pr_details`. key: String, @@ -64,11 +74,14 @@ pub enum DataPayload { #[derive(Debug)] pub enum SideEffect { - RefreshAll, + /// Refetch repos plus the lists backing the given mode. + RefreshAll(ListMode), FetchOrgRepos(String), FetchUserRepos(String), FetchInbox, FetchAllOpenPrs, + FetchIssueInbox, + FetchAllOpenIssues, FetchPrDetail { owner: String, name: String, diff --git a/src/app/event_loop.rs b/src/app/event_loop.rs index 4c7e686..a06dda5 100644 --- a/src/app/event_loop.rs +++ b/src/app/event_loop.rs @@ -13,7 +13,7 @@ use tokio::sync::{Semaphore, mpsc}; use tracing::{debug, error}; use crate::app::actions::{Action, DataPayload, SideEffect}; -use crate::app::state::{AppState, DiffEntry, FocusedPane, Overlay, PrDetailEntry}; +use crate::app::state::{AppState, DiffEntry, FocusedPane, ListMode, Overlay, PrDetailEntry}; use crate::app::update::update; use crate::app::view; use crate::cache::CacheStore; @@ -71,7 +71,7 @@ async fn run_loop( let semaphore = Arc::new(Semaphore::new(4)); // Initial data fetch - let effects = vec![SideEffect::RefreshAll]; + let effects = vec![SideEffect::RefreshAll(state.mode)]; for effect in effects { spawn_side_effect( effect, @@ -293,6 +293,7 @@ fn map_event_to_action(event: &Event, state: &AppState) -> Option { KeyCode::Char('r') => Some(Action::Refresh), KeyCode::Char('o') => Some(Action::OpenInBrowser), KeyCode::Char('f') => Some(Action::CycleMergeFilter), + KeyCode::Char('i') => Some(Action::ToggleListMode), KeyCode::Char('?') => Some(Action::ToggleHelp), KeyCode::Char('/') => Some(Action::ToggleSearch), _ => None, @@ -309,7 +310,7 @@ fn spawn_side_effect( semaphore: &Arc, ) { match effect { - SideEffect::RefreshAll => { + SideEffect::RefreshAll(mode) => { // Invalidate cache so refresh fetches fresh data if let Some(cache) = cache_store && let Err(e) = cache.invalidate_all() @@ -340,26 +341,23 @@ fn spawn_side_effect( semaphore, ); } - // Fetch inbox - spawn_side_effect( - SideEffect::FetchInbox, - config, - client, - viewer_login, - cache_store, - action_tx, - semaphore, - ); - // Fetch all open PRs - spawn_side_effect( - SideEffect::FetchAllOpenPrs, - config, - client, - viewer_login, - cache_store, - action_tx, - semaphore, - ); + // Fetch only the lists the current mode shows; the other mode's + // lists are fetched when it is toggled to. + let (inbox, all_open) = match mode { + ListMode::PullRequests => (SideEffect::FetchInbox, SideEffect::FetchAllOpenPrs), + ListMode::Issues => (SideEffect::FetchIssueInbox, SideEffect::FetchAllOpenIssues), + }; + for effect in [inbox, all_open] { + spawn_side_effect( + effect, + config, + client, + viewer_login, + cache_store, + action_tx, + semaphore, + ); + } } SideEffect::FetchOrgRepos(org) => { let client = client.clone(); @@ -574,6 +572,115 @@ fn spawn_side_effect( } }); } + SideEffect::FetchIssueInbox => { + let client = client.clone(); + let tx = action_tx.clone(); + let sem = semaphore.clone(); + let cache = cache_store.clone(); + let login = viewer_login.to_string(); + let visibility = config.github.visibility; + let filter = config.issues.filter.clone(); + let filter_suffix = config.issues.cache_suffix(); + + tokio::spawn(async move { + let _permit = sem.acquire().await; + debug!("Fetching issue inbox"); + + // Visibility and filter are part of the key, so neither a + // visibility switch nor a filter edit serves stale issues. + let cache_key = format!( + "issue_inbox_{}_{}_{}", + login, + visibility.cache_suffix(), + filter_suffix + ); + if let Some(ref cache) = cache + && let Some(issues) = cache.get::>(&cache_key) + { + let _ = tx.send(Action::DataLoaded(DataPayload::IssueInbox { + issues, + rate_limit: crate::github::RateLimit::default(), + })); + return; + } + + match client.fetch_issue_inbox(&login, visibility, &filter).await { + Ok((issues, rate_limit)) => { + if let Some(ref cache) = cache + && let Err(e) = cache.set(&cache_key, &issues) + { + error!(error = %e, "Failed to cache issue inbox"); + } + let _ = tx.send(Action::DataLoaded(DataPayload::IssueInbox { + issues, + rate_limit, + })); + } + Err(e) => { + error!(error = %e, "Failed to fetch issue inbox"); + let _ = tx.send(Action::LoadError(format!( + "Failed to fetch issue inbox: {}", + e + ))); + } + } + }); + } + SideEffect::FetchAllOpenIssues => { + let client = client.clone(); + let tx = action_tx.clone(); + let sem = semaphore.clone(); + let cache = cache_store.clone(); + let orgs = config.github.orgs.clone(); + let users = config.github.users.clone(); + let visibility = config.github.visibility; + let filter = config.issues.filter.clone(); + let filter_suffix = config.issues.cache_suffix(); + + tokio::spawn(async move { + let _permit = sem.acquire().await; + debug!("Fetching all open issues"); + + let cache_key = format!( + "all_open_issues_{}_{}", + visibility.cache_suffix(), + filter_suffix + ); + if let Some(ref cache) = cache + && let Some(issues) = cache.get::>(&cache_key) + { + let _ = tx.send(Action::DataLoaded(DataPayload::AllOpenIssues { + issues, + rate_limit: crate::github::RateLimit::default(), + })); + return; + } + + match client + .fetch_all_open_issues(&orgs, &users, visibility, &filter) + .await + { + Ok((issues, rate_limit)) => { + if let Some(ref cache) = cache + && let Err(e) = cache.set(&cache_key, &issues) + { + error!(error = %e, "Failed to cache all open issues"); + } + let _ = tx.send(Action::DataLoaded(DataPayload::AllOpenIssues { + issues, + rate_limit, + })); + } + Err(e) => { + error!(error = %e, "Failed to fetch all open issues"); + let _ = tx.send(Action::LoadError(format!( + "Failed to fetch all open issues: {}", + e + ))); + } + } + }); + } SideEffect::FetchPrDetail { owner, name, diff --git a/src/app/state.rs b/src/app/state.rs index 06f64d4..6eab79f 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -1,6 +1,7 @@ +use std::cell::Cell; use std::collections::{HashMap, HashSet}; -use crate::github::models::{PrDetail, PullRequest, RateLimit, Repo, RepoVisibility}; +use crate::github::models::{Issue, PrDetail, PullRequest, RateLimit, Repo, RepoVisibility}; /// State of an on-demand PR detail fetch, keyed by PR url in `AppState::pr_details`. #[derive(Debug, Clone)] @@ -64,12 +65,31 @@ impl MergeFilter { } } +/// What the whole dashboard lists: pull requests (default) or issues. +/// Toggled with `i`; the nav tree, content views and counts follow it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ListMode { + PullRequests, + Issues, +} + +impl ListMode { + pub fn toggle(self) -> Self { + match self { + ListMode::PullRequests => ListMode::Issues, + ListMode::Issues => ListMode::PullRequests, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum FocusedPane { Navigation, Content, } +/// The PR-named variants are shared by both modes: in `ListMode::Issues`, +/// `RepoPrList`/`AllOpenPrs`/`Inbox` show the matching issue lists. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ContentView { OrgOverview(String), @@ -84,7 +104,8 @@ pub enum NavNode { Repo { owner: String, name: String, - open_prs: u32, + /// Open PRs or open issues, depending on the current `ListMode`. + open_count: u32, }, AllPrs, MyInbox, @@ -104,10 +125,17 @@ pub struct AppState { pub orgs: HashMap, pub all_open_prs: Vec, pub inbox: Vec, + pub all_open_issues: Vec, + pub issue_inbox: Vec, pub viewer_login: String, pub rate_limit: RateLimit, pub last_refresh: Option>, + // List mode. `loaded_modes` tracks which modes' lists have been fetched + // since the last refresh, so toggling only fetches what's missing. + pub mode: ListMode, + pub loaded_modes: HashSet, + // Navigation pub nav_nodes: Vec, pub nav_cursor: usize, @@ -115,6 +143,10 @@ pub struct AppState { pub focused_pane: FocusedPane, pub content_view: ContentView, pub content_cursor: usize, + /// First visible row of the content table. Owned by the renderer, which + /// is the only place that knows the viewport height; kept across frames + /// so the view only scrolls when the cursor leaves it. + pub content_offset: Cell, // Search pub search_active: bool, @@ -163,15 +195,20 @@ impl AppState { orgs, all_open_prs: Vec::new(), inbox: Vec::new(), + all_open_issues: Vec::new(), + issue_inbox: Vec::new(), viewer_login, rate_limit: RateLimit::default(), last_refresh: None, + mode: ListMode::PullRequests, + loaded_modes: HashSet::from([ListMode::PullRequests]), nav_nodes: Vec::new(), nav_cursor: 0, nav_expanded, focused_pane: FocusedPane::Navigation, content_view: ContentView::Inbox, content_cursor: 0, + content_offset: Cell::new(0), search_active: false, search_query: String::new(), overlay: Overlay::None, @@ -210,8 +247,8 @@ impl AppState { { let mut repos: Vec<_> = org_data.repos.iter().filter(|r| !r.is_archived).collect(); repos.sort_by(|a, b| { - b.open_pr_count - .cmp(&a.open_pr_count) + self.repo_open_count(b) + .cmp(&self.repo_open_count(a)) .then(a.name.cmp(&b.name)) }); @@ -219,7 +256,7 @@ impl AppState { nodes.push(NavNode::Repo { owner: repo.owner.clone(), name: repo.name.clone(), - open_prs: repo.open_pr_count, + open_count: self.repo_open_count(repo), }); } } @@ -233,6 +270,14 @@ impl AppState { } } + /// Open PRs or open issues for `repo`, depending on the current mode. + pub fn repo_open_count(&self, repo: &Repo) -> u32 { + match self.mode { + ListMode::PullRequests => repo.open_pr_count, + ListMode::Issues => repo.open_issue_count, + } + } + pub fn filtered_prs(&self, prs: &[PullRequest]) -> Vec { let query = self.search_query.to_lowercase(); prs.iter() @@ -248,7 +293,12 @@ impl AppState { .collect() } + /// The PRs listed in the content pane. Empty in issues mode, which keeps + /// the PR-only overlays (git log / diff) from ever targeting a row. pub fn current_pr_list(&self) -> Vec { + if self.mode == ListMode::Issues { + return Vec::new(); + } let prs = match &self.content_view { ContentView::Inbox => &self.inbox, ContentView::AllOpenPrs => &self.all_open_prs, @@ -267,9 +317,67 @@ impl AppState { self.filtered_prs(prs) } + pub fn filtered_issues(&self, issues: &[Issue]) -> Vec { + let query = self.search_query.to_lowercase(); + issues + .iter() + .filter(|issue| { + query.is_empty() + || issue.title.to_lowercase().contains(&query) + || issue.author.to_lowercase().contains(&query) + || issue.repo_full_name().to_lowercase().contains(&query) + || issue + .labels + .iter() + .any(|l| l.to_lowercase().contains(&query)) + }) + .cloned() + .collect() + } + + /// The issues listed in the content pane. Empty in PR mode. + pub fn current_issue_list(&self) -> Vec { + if self.mode == ListMode::PullRequests { + return Vec::new(); + } + let issues = match &self.content_view { + ContentView::Inbox => &self.issue_inbox, + ContentView::AllOpenPrs => &self.all_open_issues, + ContentView::RepoPrList { owner, name } => { + let full_name = format!("{}/{}", owner, name); + let filtered: Vec = self + .all_open_issues + .iter() + .filter(|issue| issue.repo_full_name() == full_name) + .cloned() + .collect(); + return self.filtered_issues(&filtered); + } + ContentView::OrgOverview(_) => return Vec::new(), + }; + self.filtered_issues(issues) + } + + /// Number of rows in the content pane for the current mode. + pub fn current_item_count(&self) -> usize { + match self.mode { + ListMode::PullRequests => self.current_pr_list().len(), + ListMode::Issues => self.current_issue_list().len(), + } + } + + /// URL of the highlighted row (PR or issue) in the content pane. pub fn selected_pr_url(&self) -> Option { - let prs = self.current_pr_list(); - prs.get(self.content_cursor).map(|pr| pr.url.clone()) + match self.mode { + ListMode::PullRequests => self + .current_pr_list() + .get(self.content_cursor) + .map(|pr| pr.url.clone()), + ListMode::Issues => self + .current_issue_list() + .get(self.content_cursor) + .map(|issue| issue.url.clone()), + } } /// The currently highlighted PR (in the content pane), cloned. diff --git a/src/app/update.rs b/src/app/update.rs index 20f7463..954102c 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -1,6 +1,7 @@ use crate::app::actions::{Action, DataPayload, SideEffect}; use crate::app::state::{ - AppState, ContentView, DiffEntry, FocusedPane, NavNode, OrgData, Overlay, PrDetailEntry, + AppState, ContentView, DiffEntry, FocusedPane, ListMode, NavNode, OrgData, Overlay, + PrDetailEntry, }; pub fn update(state: &mut AppState, action: Action) -> Vec { @@ -48,7 +49,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { } } FocusedPane::Content => { - let max = state.current_pr_list().len().saturating_sub(1); + let max = state.current_item_count().saturating_sub(1); if state.content_cursor < max { state.content_cursor += 1; } @@ -123,7 +124,11 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { // Drop cached PR details / diffs so they are re-fetched fresh. state.pr_details.clear(); state.pr_diffs.clear(); - vec![SideEffect::RefreshAll] + // Refresh wipes the disk cache, so the other mode's lists are stale + // too; they are refetched the next time that mode is shown. + state.loaded_modes.clear(); + state.loaded_modes.insert(state.mode); + vec![SideEffect::RefreshAll(state.mode)] } Action::OpenInBrowser => { let url = match state.focused_pane { @@ -147,6 +152,9 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { vec![] } Action::ToggleGitLog => { + if state.mode == ListMode::Issues { + return vec![]; + } // Only meaningful in the content pane; the event loop fetches the PR's // commits (debounced) while the overlay is open. state.overlay = if state.overlay == Overlay::GitLog { @@ -157,6 +165,9 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { vec![] } Action::ToggleDiff => { + if state.mode == ListMode::Issues { + return vec![]; + } state.diff_scroll = 0; state.overlay = if state.overlay == Overlay::Diff { Overlay::None @@ -174,11 +185,30 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { vec![] } Action::CycleMergeFilter => { + if state.mode == ListMode::Issues { + return vec![]; + } state.merge_filter = state.merge_filter.next(); // Row set changed; reset the cursor so it stays in range. state.content_cursor = 0; vec![] } + Action::ToggleListMode => { + state.mode = state.mode.toggle(); + state.overlay = Overlay::None; + state.content_cursor = 0; + state.rebuild_nav_tree(); + if !state.loaded_modes.insert(state.mode) { + return vec![]; + } + state.loading = true; + match state.mode { + ListMode::PullRequests => vec![SideEffect::FetchInbox, SideEffect::FetchAllOpenPrs], + ListMode::Issues => { + vec![SideEffect::FetchIssueInbox, SideEffect::FetchAllOpenIssues] + } + } + } Action::SearchInput(ch) => { if state.search_active { state.search_query.push(ch); @@ -218,6 +248,14 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { state.rate_limit = rate_limit; state.all_open_prs = prs; } + DataPayload::IssueInbox { issues, rate_limit } => { + state.rate_limit = rate_limit; + state.issue_inbox = issues; + } + DataPayload::AllOpenIssues { issues, rate_limit } => { + state.rate_limit = rate_limit; + state.all_open_issues = issues; + } DataPayload::PrDetailLoaded { key, detail, diff --git a/src/github/graphql.rs b/src/github/graphql.rs index d76e6d6..4e3e8fb 100644 --- a/src/github/graphql.rs +++ b/src/github/graphql.rs @@ -262,6 +262,75 @@ impl GithubClient { self.search_prs(&query_string).await } + pub async fn search_issues(&self, query_string: &str) -> Result<(Vec, RateLimit)> { + let mut all_issues = Vec::new(); + let mut cursor: Option = None; + let mut rate_limit; + + loop { + let variables = json!({ + "query": query_string, + "cursor": cursor, + }); + + let data = self.query(queries::SEARCH_ISSUES_QUERY, variables).await?; + rate_limit = Self::extract_rate_limit(&data); + + let search_data = &data["data"]["search"]; + let nodes = search_data["nodes"] + .as_array() + .context("Missing search nodes")?; + + for node in nodes { + if node.get("number").is_none() { + continue; + } + all_issues.push(parse_search_issue(node)); + } + + let page_info = &search_data["pageInfo"]; + if page_info["hasNextPage"].as_bool().unwrap_or(false) { + cursor = page_info["endCursor"].as_str().map(|s| s.to_string()); + } else { + break; + } + } + + debug!( + query = query_string, + count = all_issues.len(), + "Search issues complete" + ); + Ok((all_issues, rate_limit)) + } + + /// Open issues assigned to the viewer, narrowed to `visibility` and `filter`. + pub async fn fetch_issue_inbox( + &self, + viewer_login: &str, + visibility: RepoVisibility, + filter: &str, + ) -> Result<(Vec, RateLimit)> { + let query_string = build_issue_inbox_query(viewer_login, visibility, filter); + let (mut issues, rate_limit) = self.search_issues(&query_string).await?; + issues.sort_by_key(|item| std::cmp::Reverse(item.updated_at)); + Ok((issues, rate_limit)) + } + + pub async fn fetch_all_open_issues( + &self, + orgs: &[String], + users: &[String], + visibility: RepoVisibility, + filter: &str, + ) -> Result<(Vec, RateLimit)> { + let query_string = build_all_open_issues_query(orgs, users, visibility, filter); + let (mut issues, rate_limit) = self.search_issues(&query_string).await?; + // Search returns best-match order; list most recently updated first. + issues.sort_by_key(|item| std::cmp::Reverse(item.updated_at)); + Ok((issues, rate_limit)) + } + /// Fetch on-demand detail for a single PR (fresh merge state, recent commits, /// CI rollup). Used by the detail-on-highlight pane. pub async fn fetch_pr_detail( @@ -367,6 +436,51 @@ pub fn build_inbox_queries(viewer_login: &str, visibility: RepoVisibility) -> (S ) } +/// Search query for the "All Issues" view: every open issue across the +/// configured orgs and users, narrowed to `visibility`, with the user's +/// `issues.filter` appended verbatim. +pub fn build_all_open_issues_query( + orgs: &[String], + users: &[String], + visibility: RepoVisibility, + filter: &str, +) -> String { + let mut parts = vec![ + "is:open".to_string(), + "is:issue".to_string(), + "archived:false".to_string(), + ]; + parts.extend(orgs.iter().map(|o| format!("org:{}", o))); + parts.extend(users.iter().map(|u| format!("user:{}", u))); + parts.extend(visibility.search_qualifier().map(|q| q.to_string())); + push_filter(&mut parts, filter); + parts.join(" ") +} + +/// Search query for the issues inbox: open issues assigned to the viewer. +pub fn build_issue_inbox_query( + viewer_login: &str, + visibility: RepoVisibility, + filter: &str, +) -> String { + let mut parts = vec![ + "is:open".to_string(), + "is:issue".to_string(), + format!("assignee:{}", viewer_login), + "archived:false".to_string(), + ]; + parts.extend(visibility.search_qualifier().map(|q| q.to_string())); + push_filter(&mut parts, filter); + parts.join(" ") +} + +fn push_filter(parts: &mut Vec, filter: &str) { + let filter = filter.trim(); + if !filter.is_empty() { + parts.push(filter.to_string()); + } +} + fn parse_repo(node: &Value) -> Repo { Repo { name: node["name"].as_str().unwrap_or("").to_string(), @@ -374,6 +488,7 @@ fn parse_repo(node: &Value) -> Repo { url: node["url"].as_str().unwrap_or("").to_string(), description: node["description"].as_str().map(|s| s.to_string()), open_pr_count: node["pullRequests"]["totalCount"].as_u64().unwrap_or(0) as u32, + open_issue_count: node["issues"]["totalCount"].as_u64().unwrap_or(0) as u32, is_archived: node["isArchived"].as_bool().unwrap_or(false), is_private: node["isPrivate"].as_bool().unwrap_or(false), } @@ -417,15 +532,49 @@ fn parse_pr_detail(node: &Value) -> PrDetail { } } -fn parse_search_pr(node: &Value) -> PullRequest { - let labels = node["labels"]["nodes"] +fn parse_labels(node: &Value) -> Vec { + node["labels"]["nodes"] .as_array() .map(|arr| { arr.iter() .filter_map(|l| l["name"].as_str().map(|s| s.to_string())) .collect() }) - .unwrap_or_default(); + .unwrap_or_default() +} + +pub fn parse_search_issue(node: &Value) -> Issue { + Issue { + number: node["number"].as_u64().unwrap_or(0) as u32, + title: node["title"].as_str().unwrap_or("").to_string(), + author: node["author"]["login"] + .as_str() + .unwrap_or("ghost") + .to_string(), + repo_owner: node["repository"]["owner"]["login"] + .as_str() + .unwrap_or("") + .to_string(), + repo_name: node["repository"]["name"] + .as_str() + .unwrap_or("") + .to_string(), + url: node["url"].as_str().unwrap_or("").to_string(), + created_at: node["createdAt"] + .as_str() + .and_then(|s| s.parse().ok()) + .unwrap_or_default(), + updated_at: node["updatedAt"] + .as_str() + .and_then(|s| s.parse().ok()) + .unwrap_or_default(), + labels: parse_labels(node), + comment_count: node["comments"]["totalCount"].as_u64().unwrap_or(0) as u32, + } +} + +fn parse_search_pr(node: &Value) -> PullRequest { + let labels = parse_labels(node); PullRequest { number: node["number"].as_u64().unwrap_or(0) as u32, diff --git a/src/github/models.rs b/src/github/models.rs index 00e2a3a..7e64287 100644 --- a/src/github/models.rs +++ b/src/github/models.rs @@ -67,6 +67,9 @@ pub struct Repo { pub url: String, pub description: Option, pub open_pr_count: u32, + /// Required for the same reason as `is_private`: cache entries written + /// before issues mode existed are refetched instead of showing 0 issues. + pub open_issue_count: u32, pub is_archived: bool, /// Required (not `#[serde(default)]`) on purpose: cache entries written /// before this field existed must fail to parse and be refetched rather @@ -112,6 +115,26 @@ pub struct PullRequest { pub checks_status: Option, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Issue { + pub number: u32, + pub title: String, + pub author: String, + pub repo_owner: String, + pub repo_name: String, + pub url: String, + pub created_at: DateTime, + pub updated_at: DateTime, + pub labels: Vec, + pub comment_count: u32, +} + +impl Issue { + pub fn repo_full_name(&self) -> String { + format!("{}/{}", self.repo_owner, self.repo_name) + } +} + /// Coarse CI outcome derived from `checks_status`, decoupled from the raw GitHub /// enum so the UI (and tests) don't hard-code string matching. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/src/github/queries.rs b/src/github/queries.rs index 3892e39..2b60ffb 100644 --- a/src/github/queries.rs +++ b/src/github/queries.rs @@ -29,6 +29,9 @@ query($org: String!, $cursor: String) { pullRequests(states: OPEN) { totalCount } + issues(states: OPEN) { + totalCount + } } } } @@ -58,6 +61,9 @@ query($user: String!, $cursor: String) { pullRequests(states: OPEN) { totalCount } + issues(states: OPEN) { + totalCount + } } } } @@ -156,6 +162,42 @@ query($query: String!, $cursor: String) { } "#; +pub const SEARCH_ISSUES_QUERY: &str = r#" +query($query: String!, $cursor: String) { + search(query: $query, type: ISSUE, first: 50, after: $cursor) { + pageInfo { + hasNextPage + endCursor + } + nodes { + ... on Issue { + number + title + author { login } + repository { + name + owner { login } + } + url + createdAt + updatedAt + comments { + totalCount + } + labels(first: 10) { + nodes { name } + } + } + } + } + rateLimit { + remaining + limit + resetAt + } +} +"#; + /// Detail for a single PR, fetched on-demand when a row is highlighted. /// Accessing the PR directly (vs. the search API) makes GitHub compute a fresh /// `mergeable`/`mergeStateStatus`, and lets us pull the recent commits + CI rollup. diff --git a/src/ui/widgets.rs b/src/ui/widgets.rs index 68b2076..475add0 100644 --- a/src/ui/widgets.rs +++ b/src/ui/widgets.rs @@ -2,11 +2,11 @@ use ratatui::{ Frame, layout::{Constraint, Rect}, text::{Line, Span}, - widgets::{Block, Borders, Cell, Clear, List, ListItem, Paragraph, Row, Table}, + widgets::{Block, Borders, Cell, Clear, List, ListItem, Paragraph, Row, Table, TableState}, }; use crate::app::state::{ - AppState, ContentView, DiffEntry, FocusedPane, NavNode, Overlay, PrDetailEntry, + AppState, ContentView, DiffEntry, FocusedPane, ListMode, NavNode, Overlay, PrDetailEntry, }; use crate::github::models::{CiStatus, PrDetail, PullRequest}; use crate::ui::theme; @@ -19,8 +19,12 @@ pub fn render_nav_pane(f: &mut Frame, area: Rect, state: &AppState) { theme::BORDER_UNFOCUSED }; + let nav_title = match state.mode { + ListMode::PullRequests => " Pull Requests ", + ListMode::Issues => " Issues ", + }; let block = Block::default() - .title(" Navigation ") + .title(nav_title) .borders(Borders::ALL) .border_style(border_style); @@ -31,7 +35,10 @@ pub fn render_nav_pane(f: &mut Frame, area: Rect, state: &AppState) { .map(|(i, node)| { let (text, style) = match node { NavNode::MyInbox => { - let count = state.inbox.len(); + let count = match state.mode { + ListMode::PullRequests => state.inbox.len(), + ListMode::Issues => state.issue_inbox.len(), + }; let label = if count > 0 { format!(" Inbox ({})", count) } else { @@ -40,11 +47,14 @@ pub fn render_nav_pane(f: &mut Frame, area: Rect, state: &AppState) { (label, theme::NAV_VIRTUAL) } NavNode::AllPrs => { - let count = state.all_open_prs.len(); + let (name, count) = match state.mode { + ListMode::PullRequests => ("All PRs", state.all_open_prs.len()), + ListMode::Issues => ("All Issues", state.all_open_issues.len()), + }; let label = if count > 0 { - format!(" All PRs ({})", count) + format!(" {} ({})", name, count) } else { - " All PRs".to_string() + format!(" {}", name) }; (label, theme::NAV_VIRTUAL) } @@ -69,9 +79,11 @@ pub fn render_nav_pane(f: &mut Frame, area: Rect, state: &AppState) { }; (format!("{} {}{}", icon, name, suffix), theme::NAV_ORG) } - NavNode::Repo { name, open_prs, .. } => { - let pr_info = if *open_prs > 0 { - format!(" [{}]", open_prs) + NavNode::Repo { + name, open_count, .. + } => { + let pr_info = if *open_count > 0 { + format!(" [{}]", open_count) } else { String::new() }; @@ -100,6 +112,25 @@ pub fn render_content_pane(f: &mut Frame, area: Rect, state: &AppState) { theme::BORDER_UNFOCUSED }; + if state.mode == ListMode::Issues { + match &state.content_view { + ContentView::Inbox => { + render_issue_table(f, area, state, "Issue Inbox", border_style); + } + ContentView::AllOpenPrs => { + render_issue_table(f, area, state, "All Open Issues", border_style); + } + ContentView::RepoPrList { owner, name } => { + let title = format!("{}/{} issues", owner, name); + render_issue_table(f, area, state, &title, border_style); + } + ContentView::OrgOverview(org) => { + render_org_overview(f, area, state, org, border_style); + } + } + return; + } + match &state.content_view { ContentView::Inbox => { render_pr_table(f, area, state, "Inbox", border_style); @@ -265,12 +296,103 @@ fn render_pr_table( Constraint::Length(10), ]; - let table = Table::new(rows, widths) - .header(header) - .block(block) - .row_highlight_style(theme::HIGHLIGHT); + let table = Table::new(rows, widths).header(header).block(block); + render_scrolled_table(f, area, table, state); +} + +fn render_issue_table( + f: &mut Frame, + area: Rect, + state: &AppState, + title: &str, + border_style: ratatui::style::Style, +) { + let issues = state.current_issue_list(); + + let search_suffix = if state.search_active && !state.search_query.is_empty() { + format!(" [filter: {}]", state.search_query) + } else { + String::new() + }; + let title = format!(" {} ({}){} ", title, issues.len(), search_suffix); + + let block = Block::default() + .title(title) + .borders(Borders::ALL) + .border_style(border_style); - f.render_widget(table, area); + if issues.is_empty() { + let msg = if state.loading { + "Loading..." + } else if state.search_active && !state.search_query.is_empty() { + "No matching issues" + } else { + "No open issues" + }; + let para = Paragraph::new(msg).style(theme::DIM).block(block); + f.render_widget(para, area); + return; + } + + let header = Row::new(vec![ + Cell::from("#").style(theme::HEADER), + Cell::from("Title").style(theme::HEADER), + Cell::from("Labels").style(theme::HEADER), + Cell::from("Author").style(theme::HEADER), + Cell::from("Repo").style(theme::HEADER), + Cell::from("💬").style(theme::HEADER), + Cell::from("Updated").style(theme::HEADER), + ]) + .height(1); + + let rows: Vec = issues + .iter() + .enumerate() + .map(|(i, issue)| { + let highlighted = + i == state.content_cursor && state.focused_pane == FocusedPane::Content; + let style = if highlighted { + theme::HIGHLIGHT + } else { + ratatui::style::Style::default() + }; + let or_highlight = |s: ratatui::style::Style| if highlighted { style } else { s }; + + Row::new(vec![ + Cell::from(format!("#{}", issue.number)).style(or_highlight(theme::PR_NUMBER)), + Cell::from(issue.title.as_str()).style(style), + Cell::from(issue.labels.join(", ")).style(or_highlight(theme::DIM)), + Cell::from(issue.author.as_str()).style(or_highlight(theme::PR_AUTHOR)), + Cell::from(issue.repo_name.as_str()).style(style), + Cell::from(issue.comment_count.to_string()).style(or_highlight(theme::DIM)), + Cell::from(relative_time(&issue.updated_at)).style(or_highlight(theme::DIM)), + ]) + .height(1) + }) + .collect(); + + let widths = [ + Constraint::Length(7), + Constraint::Min(20), + Constraint::Length(14), + Constraint::Length(16), + Constraint::Length(24), + Constraint::Length(3), + Constraint::Length(10), + ]; + + let table = Table::new(rows, widths).header(header).block(block); + render_scrolled_table(f, area, table, state); +} + +/// Render a content table scrolled so the cursor row stays visible. Rows are +/// already highlighted by hand, so the selection only drives the offset. +fn render_scrolled_table(f: &mut Frame, area: Rect, table: Table, state: &AppState) { + let mut table_state = TableState::default() + .with_offset(state.content_offset.get()) + .with_selected(Some(state.content_cursor)); + f.render_stateful_widget(table, area, &mut table_state); + state.content_offset.set(table_state.offset()); } fn render_org_overview( @@ -296,35 +418,41 @@ fn render_org_overview( ]; if let Some(data) = org_data { + let unit = match state.mode { + ListMode::PullRequests => "PRs", + ListMode::Issues => "issues", + }; let active_repos = data.repos.iter().filter(|r| !r.is_archived).count(); - let total_prs: u32 = data + let total: u32 = data .repos .iter() .filter(|r| !r.is_archived) - .map(|r| r.open_pr_count) + .map(|r| state.repo_open_count(r)) .sum(); lines.push(Line::from(format!("Repositories: {}", active_repos))); - lines.push(Line::from(format!("Open PRs: {}", total_prs))); + lines.push(Line::from(format!("Open {}: {}", unit, total))); lines.push(Line::from("")); - // Top repos by PR count - let mut repos_with_prs: Vec<_> = data + // Top repos by open PR / issue count + let mut busy_repos: Vec<_> = data .repos .iter() - .filter(|r| !r.is_archived && r.open_pr_count > 0) + .filter(|r| !r.is_archived && state.repo_open_count(r) > 0) .collect(); - repos_with_prs.sort_by_key(|r| std::cmp::Reverse(r.open_pr_count)); + busy_repos.sort_by_key(|r| std::cmp::Reverse(state.repo_open_count(r))); - if !repos_with_prs.is_empty() { + if !busy_repos.is_empty() { lines.push(Line::from(Span::styled( - "Top repos by open PRs:", + format!("Top repos by open {}:", unit), theme::HEADER, ))); - for repo in repos_with_prs.iter().take(10) { + for repo in busy_repos.iter().take(10) { lines.push(Line::from(format!( - " {} — {} PRs", - repo.name, repo.open_pr_count + " {} — {} {}", + repo.name, + state.repo_open_count(repo), + unit ))); } } @@ -357,9 +485,13 @@ fn truncate_status(status: &str, center_width: usize) -> String { format!("{}...", &status[..end]) } -/// Right-hand side of the status bar: visibility restriction (when any), -/// API budget, and time since the last refresh. +/// Right-hand side of the status bar: issues mode (when on), visibility +/// restriction (when any), API budget, and time since the last refresh. fn right_status_text(state: &AppState) -> String { + let mode_info = match state.mode { + ListMode::PullRequests => "", + ListMode::Issues => "issues | ", + }; let visibility_info = state .visibility .label() @@ -373,8 +505,12 @@ fn right_status_text(state: &AppState) -> String { .unwrap_or_default(); format!( - "{}API: {}/{}{}", - visibility_info, state.rate_limit.remaining, state.rate_limit.limit, refresh_info + "{}{}API: {}/{}{}", + mode_info, + visibility_info, + state.rate_limit.remaining, + state.rate_limit.limit, + refresh_info ) } @@ -382,7 +518,14 @@ pub fn render_status_bar(f: &mut Frame, area: Rect, state: &AppState) { let key_hints = if state.search_active { "Esc: close search | Enter: filter" } else { - "j/k: nav | Enter: select | l: log | d: diff | f: filter | /: search | r: refresh | o: open | ?: help | q: quit" + match state.mode { + ListMode::PullRequests => { + "j/k: nav | Enter: select | l: log | d: diff | f: filter | i: issues | /: search | r: refresh | o: open | ?: help | q: quit" + } + ListMode::Issues => { + "j/k: nav | Enter: select | i: PRs | /: search | r: refresh | o: open | ?: help | q: quit" + } + } }; let status = if state.loading { @@ -682,7 +825,7 @@ pub fn render_help_overlay(f: &mut Frame, state: &AppState) { let area = f.area(); let modal_width = 66u16.clamp(40, area.width.saturating_sub(4)); - let modal_height = 18u16.min(area.height.saturating_sub(2)); + let modal_height = 19u16.min(area.height.saturating_sub(2)); let x = (area.width.saturating_sub(modal_width)) / 2; let y = (area.height.saturating_sub(modal_height)) / 2; let modal_area = Rect { @@ -711,6 +854,7 @@ pub fn render_help_overlay(f: &mut Frame, state: &AppState) { key("l", "git-log overlay (content pane)"), key("d", "diff overlay (content pane)"), key("f", "cycle merge filter: all -> conflicting -> clean"), + key("i", "switch between pull requests and issues"), key("/", "search r refresh o open in browser"), key("Tab", "switch pane h / Esc back / close q quit"), Line::from(""), @@ -790,7 +934,7 @@ mod status_truncate_tests { #[cfg(test)] mod right_status_text_tests { use super::right_status_text; - use crate::app::state::AppState; + use crate::app::state::{AppState, ListMode}; use crate::github::models::{RateLimit, RepoVisibility}; fn state() -> AppState { @@ -816,6 +960,17 @@ mod right_status_text_tests { assert_eq!(right_status_text(&s), "public only | API: 4999/5000"); } + #[test] + fn announces_issues_mode_before_visibility() { + let mut s = state(); + s.mode = ListMode::Issues; + s.visibility = RepoVisibility::Public; + assert_eq!( + right_status_text(&s), + "issues | public only | API: 4999/5000" + ); + } + #[test] fn announces_a_private_only_session() { let mut s = state(); diff --git a/src/util/config.rs b/src/util/config.rs index f71630b..ccc54d4 100644 --- a/src/util/config.rs +++ b/src/util/config.rs @@ -15,6 +15,8 @@ pub struct AppConfig { pub cache: CacheConfig, #[serde(default)] pub ui: UiConfig, + #[serde(default)] + pub issues: IssuesConfig, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -57,6 +59,32 @@ pub struct UiConfig { pub nav_width_percent: u16, } +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct IssuesConfig { + /// Extra GitHub search qualifiers appended to every issue search + /// (e.g. `label:bug -label:wontfix`). Empty = all open issues. + #[serde(default)] + pub filter: String, +} + +impl IssuesConfig { + /// Discriminator for cache keys, so issue lists fetched under one filter + /// are never served after the filter changes. FNV-1a keeps it stable + /// across runs and filesystem-safe. + pub fn cache_suffix(&self) -> String { + let filter = self.filter.trim(); + if filter.is_empty() { + return "nofilter".to_string(); + } + let mut hash: u64 = 0xcbf29ce484222325; + for byte in filter.bytes() { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x100000001b3); + } + format!("{:016x}", hash) + } +} + fn default_api_url() -> String { "https://api.github.com/graphql".to_string() } diff --git a/tests/graphql_parse_tests.rs b/tests/graphql_parse_tests.rs index a6b1cd8..f86da64 100644 --- a/tests/graphql_parse_tests.rs +++ b/tests/graphql_parse_tests.rs @@ -8,6 +8,7 @@ fn test_repo_full_name() { url: "https://github.com/my-org/my-repo".into(), description: Some("A repo".into()), open_pr_count: 5, + open_issue_count: 0, is_archived: false, is_private: false, }; @@ -45,6 +46,7 @@ fn test_repo_serialization_roundtrip() { url: "https://github.com/test-owner/test-repo".into(), description: None, open_pr_count: 3, + open_issue_count: 0, is_archived: false, is_private: false, }; @@ -110,6 +112,7 @@ fn test_repo_with_description() { url: "https://github.com/owner/repo".into(), description: Some("A cool project".into()), open_pr_count: 0, + open_issue_count: 0, is_archived: true, is_private: false, }; @@ -266,6 +269,7 @@ fn test_repo_visibility_survives_serialization_roundtrip() { url: "https://github.com/acme/secret".into(), description: None, open_pr_count: 0, + open_issue_count: 0, is_archived: false, is_private: true, }; diff --git a/tests/issues_tests.rs b/tests/issues_tests.rs new file mode 100644 index 0000000..fcf9713 --- /dev/null +++ b/tests/issues_tests.rs @@ -0,0 +1,482 @@ +use std::io::Write; +use tempfile::NamedTempFile; + +use ghdash::app::actions::{Action, DataPayload, SideEffect}; +use ghdash::app::state::{AppState, ContentView, FocusedPane, ListMode, NavNode, Overlay}; +use ghdash::app::update::update; +use ghdash::github::graphql::{ + build_all_open_issues_query, build_issue_inbox_query, parse_search_issue, +}; +use ghdash::github::models::{Issue, PullRequest, RateLimit, Repo, RepoVisibility}; +use ghdash::util::config::{AppConfig, IssuesConfig}; + +fn make_state() -> AppState { + AppState::new("testuser".into(), vec!["org-a".into()]) +} + +fn make_repo(name: &str, open_prs: u32, open_issues: u32) -> Repo { + Repo { + name: name.into(), + owner: "org-a".into(), + url: format!("https://github.com/org-a/{}", name), + description: None, + open_pr_count: open_prs, + open_issue_count: open_issues, + is_archived: false, + is_private: false, + } +} + +fn make_issue(repo_name: &str, number: u32, title: &str, labels: &[&str]) -> Issue { + Issue { + number, + title: title.into(), + author: "author".into(), + repo_owner: "org-a".into(), + repo_name: repo_name.into(), + url: format!("https://github.com/org-a/{}/issues/{}", repo_name, number), + created_at: chrono::Utc::now(), + updated_at: chrono::Utc::now(), + labels: labels.iter().map(|l| l.to_string()).collect(), + comment_count: 0, + } +} + +fn make_pr(repo_name: &str, number: u32) -> PullRequest { + PullRequest { + number, + title: "pr".into(), + author: "author".into(), + repo_owner: "org-a".into(), + repo_name: repo_name.into(), + url: format!("https://github.com/org-a/{}/pull/{}", repo_name, number), + created_at: chrono::Utc::now(), + updated_at: chrono::Utc::now(), + is_draft: false, + additions: 0, + deletions: 0, + review_decision: None, + mergeable: None, + merge_state_status: None, + checks_status: None, + labels: vec![], + } +} + +fn load_issues(state: &mut AppState, issues: Vec) { + update( + state, + Action::DataLoaded(DataPayload::AllOpenIssues { + issues, + rate_limit: RateLimit::default(), + }), + ); +} + +// --- Query building --- + +#[test] +fn all_open_issues_query_without_filter() { + let q = + build_all_open_issues_query(&["acme".into()], &["alice".into()], RepoVisibility::All, ""); + assert_eq!(q, "is:open is:issue archived:false org:acme user:alice"); +} + +#[test] +fn all_open_issues_query_appends_visibility_and_filter() { + let q = build_all_open_issues_query( + &["acme".into()], + &[], + RepoVisibility::Public, + " label:bug -label:wontfix ", + ); + assert_eq!( + q, + "is:open is:issue archived:false org:acme is:public label:bug -label:wontfix" + ); +} + +#[test] +fn issue_inbox_query_is_assigned_to_viewer() { + let q = build_issue_inbox_query("me", RepoVisibility::All, ""); + assert_eq!(q, "is:open is:issue assignee:me archived:false"); +} + +#[test] +fn issue_inbox_query_applies_visibility_and_filter() { + let q = build_issue_inbox_query("me", RepoVisibility::Private, "label:bug"); + assert_eq!( + q, + "is:open is:issue assignee:me archived:false is:private label:bug" + ); +} + +// --- Parsing --- + +#[test] +fn parses_issue_search_node() { + let node = serde_json::json!({ + "number": 42, + "title": "Crash on start", + "author": { "login": "bob" }, + "repository": { "name": "app", "owner": { "login": "acme" } }, + "url": "https://github.com/acme/app/issues/42", + "createdAt": "2026-01-01T00:00:00Z", + "updatedAt": "2026-01-02T00:00:00Z", + "comments": { "totalCount": 3 }, + "labels": { "nodes": [{ "name": "bug" }, { "name": "p1" }] } + }); + let issue = parse_search_issue(&node); + assert_eq!(issue.number, 42); + assert_eq!(issue.title, "Crash on start"); + assert_eq!(issue.author, "bob"); + assert_eq!(issue.repo_full_name(), "acme/app"); + assert_eq!(issue.comment_count, 3); + assert_eq!(issue.labels, vec!["bug", "p1"]); +} + +#[test] +fn parses_issue_with_deleted_author_as_ghost() { + let node = serde_json::json!({ + "number": 1, + "title": "t", + "author": null, + "repository": { "name": "app", "owner": { "login": "acme" } }, + "url": "u", + "createdAt": "2026-01-01T00:00:00Z", + "updatedAt": "2026-01-01T00:00:00Z", + "comments": { "totalCount": 0 }, + "labels": { "nodes": [] } + }); + assert_eq!(parse_search_issue(&node).author, "ghost"); +} + +// --- Config --- + +#[test] +fn issues_filter_defaults_to_empty() { + let mut f = NamedTempFile::new().unwrap(); + f.write_all(b"[github]\norgs = [\"acme\"]\n").unwrap(); + let config = AppConfig::load(Some(f.path())).unwrap(); + assert_eq!(config.issues.filter, ""); +} + +#[test] +fn loads_issues_filter() { + let mut f = NamedTempFile::new().unwrap(); + f.write_all(b"[issues]\nfilter = \"label:bug -label:wontfix\"\n") + .unwrap(); + let config = AppConfig::load(Some(f.path())).unwrap(); + assert_eq!(config.issues.filter, "label:bug -label:wontfix"); +} + +#[test] +fn issues_cache_suffix_tracks_filter() { + let none = IssuesConfig::default(); + let blank = IssuesConfig { + filter: " ".into(), + }; + let bug = IssuesConfig { + filter: "label:bug".into(), + }; + let feature = IssuesConfig { + filter: "label:feature".into(), + }; + assert_eq!(none.cache_suffix(), blank.cache_suffix()); + assert_ne!(none.cache_suffix(), bug.cache_suffix()); + assert_ne!(bug.cache_suffix(), feature.cache_suffix()); + assert_eq!(bug.cache_suffix(), bug.clone().cache_suffix()); + assert!( + bug.cache_suffix() + .chars() + .all(|c| c.is_ascii_alphanumeric()) + ); +} + +// --- Mode toggling --- + +#[test] +fn starts_in_pull_request_mode() { + let state = make_state(); + assert_eq!(state.mode, ListMode::PullRequests); +} + +#[test] +fn first_toggle_to_issues_fetches_issue_lists() { + let mut state = make_state(); + let effects = update(&mut state, Action::ToggleListMode); + assert_eq!(state.mode, ListMode::Issues); + assert!(state.loading); + assert_eq!(effects.len(), 2); + assert!(matches!(effects[0], SideEffect::FetchIssueInbox)); + assert!(matches!(effects[1], SideEffect::FetchAllOpenIssues)); +} + +#[test] +fn toggling_back_and_forth_does_not_refetch() { + let mut state = make_state(); + update(&mut state, Action::ToggleListMode); + let back = update(&mut state, Action::ToggleListMode); + assert_eq!(state.mode, ListMode::PullRequests); + assert!(back.is_empty()); + let again = update(&mut state, Action::ToggleListMode); + assert!(again.is_empty()); +} + +#[test] +fn refresh_only_targets_current_mode_and_marks_other_stale() { + let mut state = make_state(); + update(&mut state, Action::ToggleListMode); + let effects = update(&mut state, Action::Refresh); + assert!(matches!( + effects[0], + SideEffect::RefreshAll(ListMode::Issues) + )); + + // PR lists were dropped from the cache by the refresh, so going back + // to PR mode refetches them. + let back = update(&mut state, Action::ToggleListMode); + assert_eq!(back.len(), 2); + assert!(matches!(back[0], SideEffect::FetchInbox)); + assert!(matches!(back[1], SideEffect::FetchAllOpenPrs)); +} + +#[test] +fn toggle_resets_cursor_and_closes_overlay() { + let mut state = make_state(); + state.content_cursor = 3; + state.overlay = Overlay::GitLog; + update(&mut state, Action::ToggleListMode); + assert_eq!(state.content_cursor, 0); + assert_eq!(state.overlay, Overlay::None); +} + +#[test] +fn nav_counts_and_order_follow_mode() { + let mut state = make_state(); + update( + &mut state, + Action::DataLoaded(DataPayload::OrgRepos { + org: "org-a".into(), + repos: vec![make_repo("few-prs", 1, 9), make_repo("many-prs", 5, 2)], + rate_limit: RateLimit::default(), + }), + ); + + let repos = |state: &AppState| -> Vec<(String, u32)> { + state + .nav_nodes + .iter() + .filter_map(|n| match n { + NavNode::Repo { + name, open_count, .. + } => Some((name.clone(), *open_count)), + _ => None, + }) + .collect() + }; + + assert_eq!( + repos(&state), + vec![("many-prs".into(), 5), ("few-prs".into(), 1)] + ); + update(&mut state, Action::ToggleListMode); + assert_eq!( + repos(&state), + vec![("few-prs".into(), 9), ("many-prs".into(), 2)] + ); +} + +// --- Issue lists --- + +#[test] +fn issue_lists_follow_content_view() { + let mut state = make_state(); + update(&mut state, Action::ToggleListMode); + load_issues( + &mut state, + vec![ + make_issue("a", 1, "one", &[]), + make_issue("b", 2, "two", &[]), + ], + ); + update( + &mut state, + Action::DataLoaded(DataPayload::IssueInbox { + issues: vec![make_issue("a", 1, "one", &[])], + rate_limit: RateLimit::default(), + }), + ); + + state.content_view = ContentView::Inbox; + assert_eq!(state.current_issue_list().len(), 1); + + state.content_view = ContentView::AllOpenPrs; + assert_eq!(state.current_issue_list().len(), 2); + + state.content_view = ContentView::RepoPrList { + owner: "org-a".into(), + name: "b".into(), + }; + let issues = state.current_issue_list(); + assert_eq!(issues.len(), 1); + assert_eq!(issues[0].number, 2); +} + +#[test] +fn modes_do_not_leak_into_each_other() { + let mut state = make_state(); + state.content_view = ContentView::AllOpenPrs; + update( + &mut state, + Action::DataLoaded(DataPayload::AllOpenPrs { + prs: vec![make_pr("a", 7)], + rate_limit: RateLimit::default(), + }), + ); + load_issues(&mut state, vec![make_issue("a", 1, "one", &[])]); + + assert_eq!(state.current_pr_list().len(), 1); + assert!(state.current_issue_list().is_empty()); + + update(&mut state, Action::ToggleListMode); + assert!(state.current_pr_list().is_empty()); + assert!(state.selected_pr().is_none()); + assert_eq!(state.current_issue_list().len(), 1); +} + +#[test] +fn search_matches_issue_labels() { + let mut state = make_state(); + update(&mut state, Action::ToggleListMode); + state.content_view = ContentView::AllOpenPrs; + load_issues( + &mut state, + vec![ + make_issue("a", 1, "one", &["Bug"]), + make_issue("a", 2, "two", &["feature"]), + ], + ); + update(&mut state, Action::ToggleSearch); + for ch in "bug".chars() { + update(&mut state, Action::SearchInput(ch)); + } + let issues = state.current_issue_list(); + assert_eq!(issues.len(), 1); + assert_eq!(issues[0].number, 1); +} + +#[test] +fn enter_and_open_use_selected_issue_url() { + let mut state = make_state(); + update(&mut state, Action::ToggleListMode); + state.content_view = ContentView::AllOpenPrs; + state.focused_pane = FocusedPane::Content; + load_issues( + &mut state, + vec![ + make_issue("a", 1, "one", &[]), + make_issue("a", 2, "two", &[]), + ], + ); + + update(&mut state, Action::MoveDown); + assert_eq!(state.content_cursor, 1); + update(&mut state, Action::MoveDown); + assert_eq!(state.content_cursor, 1, "cursor stays on the last issue"); + + let effects = update(&mut state, Action::OpenInBrowser); + assert!(matches!( + &effects[0], + SideEffect::OpenUrl(url) if url == "https://github.com/org-a/a/issues/2" + )); +} + +#[test] +fn pr_only_keys_do_nothing_in_issues_mode() { + let mut state = make_state(); + update(&mut state, Action::ToggleListMode); + state.focused_pane = FocusedPane::Content; + + update(&mut state, Action::ToggleGitLog); + assert_eq!(state.overlay, Overlay::None); + update(&mut state, Action::ToggleDiff); + assert_eq!(state.overlay, Overlay::None); + let before = state.merge_filter; + update(&mut state, Action::CycleMergeFilter); + assert_eq!(state.merge_filter, before); +} + +// --- Scrolling --- + +fn render_content(state: &AppState, height: u16) -> String { + use ratatui::{Terminal, backend::TestBackend}; + let mut terminal = Terminal::new(TestBackend::new(120, height)).unwrap(); + terminal + .draw(|f| ghdash::ui::widgets::render_content_pane(f, f.area(), state)) + .unwrap(); + let buffer = terminal.backend().buffer(); + buffer + .content() + .chunks(buffer.area.width as usize) + .map(|row| row.iter().map(|c| c.symbol()).collect::()) + .collect::>() + .join("\n") +} + +#[test] +fn issue_table_scrolls_to_keep_cursor_visible() { + let mut state = make_state(); + update(&mut state, Action::ToggleListMode); + state.content_view = ContentView::AllOpenPrs; + state.focused_pane = FocusedPane::Content; + load_issues( + &mut state, + (1..=60) + .map(|n| make_issue("a", n, &format!("issue-{n}"), &[])) + .collect(), + ); + for _ in 0..50 { + update(&mut state, Action::MoveDown); + } + + let screen = render_content(&state, 15); + assert!( + screen.contains("issue-51"), + "cursor row must be on screen:\n{screen}" + ); + assert!( + !screen.contains("issue-1 "), + "top rows scrolled away:\n{screen}" + ); + + // Moving back up a little keeps the viewport where it was instead of + // jumping, until the cursor reaches its top edge. + update(&mut state, Action::MoveUp); + let screen = render_content(&state, 15); + assert!(screen.contains("issue-50")); + assert!(screen.contains("issue-51")); +} + +#[test] +fn pr_table_scrolls_to_keep_cursor_visible() { + let mut state = make_state(); + state.content_view = ContentView::AllOpenPrs; + state.focused_pane = FocusedPane::Content; + update( + &mut state, + Action::DataLoaded(DataPayload::AllOpenPrs { + prs: (1..=60).map(|n| make_pr("a", n)).collect(), + rate_limit: RateLimit::default(), + }), + ); + for _ in 0..50 { + update(&mut state, Action::MoveDown); + } + + let screen = render_content(&state, 15); + assert!( + screen.contains("#51 "), + "cursor row must be on screen:\n{screen}" + ); +} diff --git a/tests/state_tests.rs b/tests/state_tests.rs index fce751a..2598e9a 100644 --- a/tests/state_tests.rs +++ b/tests/state_tests.rs @@ -14,6 +14,7 @@ fn make_repo(owner: &str, name: &str, open_prs: u32) -> Repo { url: format!("https://github.com/{}/{}", owner, name), description: None, open_pr_count: open_prs, + open_issue_count: 0, is_archived: false, is_private: false, } @@ -279,7 +280,7 @@ fn test_refresh_returns_side_effect() { assert!(state.loading); assert!(state.error_message.is_none()); assert_eq!(effects.len(), 1); - assert!(matches!(effects[0], SideEffect::RefreshAll)); + assert!(matches!(effects[0], SideEffect::RefreshAll(_))); } // --- Search --- diff --git a/tests/visibility_tests.rs b/tests/visibility_tests.rs index ed71c8d..76176b1 100644 --- a/tests/visibility_tests.rs +++ b/tests/visibility_tests.rs @@ -9,6 +9,7 @@ fn repo(name: &str, is_private: bool) -> Repo { url: format!("https://github.com/acme/{}", name), description: None, open_pr_count: 0, + open_issue_count: 0, is_archived: false, is_private, }