Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
137
crates/luxe-tui/src/github_panel/keys.rs
Normal file
137
crates/luxe-tui/src/github_panel/keys.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
//! GitHub panel keys — the list's own keys, and the detail's answers turned into what the panel
|
||||
//! asks of the app, for the pull request or issue on screen.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GithubPanel {
|
||||
/// A key while the detail has focus, answered for the item its row names; a detail that no
|
||||
/// longer matches its row hands focus back and takes nothing.
|
||||
pub(super) fn detail_key_outcome(&mut self, key: &KeyEvent) -> GithubKey {
|
||||
let target = self.selected_target();
|
||||
// the detail and its row are one pull request; one that disagrees takes no key at all,
|
||||
// rather than acting and then having its request dropped
|
||||
let agreed = self.detail().zip(target).filter(|(d, (n, _))| d.subject.number() == *n);
|
||||
let Some((_, (_, repository))) = agreed else {
|
||||
self.focus = Focus::List;
|
||||
return GithubKey::Held;
|
||||
};
|
||||
let Some(detail) = self.detail_mut() else {
|
||||
self.focus = Focus::List;
|
||||
return GithubKey::Held;
|
||||
};
|
||||
let answer = detail.on_key(key);
|
||||
if answer == DetailKey::Leave {
|
||||
self.focus = Focus::List;
|
||||
return GithubKey::Held;
|
||||
}
|
||||
detail_request(&detail.subject, repository, answer)
|
||||
}
|
||||
|
||||
/// A key while the list has focus: tabs, the cursor, the search field, and the row's actions.
|
||||
pub(super) fn list_key_outcome(&mut self, key: &KeyEvent) -> GithubKey {
|
||||
if self.editing.is_some() {
|
||||
return self.on_editing_key(key);
|
||||
}
|
||||
let count = self.sections.as_ref().map_or(0, Vec::len);
|
||||
let rows = self.rows().len();
|
||||
match key.code {
|
||||
KeyCode::Esc => return GithubKey::Close,
|
||||
KeyCode::Char('r') => return GithubKey::Refresh,
|
||||
KeyCode::Char('/') if count > 0 => self.start_editing(),
|
||||
KeyCode::Char('s') if count > 0 => return self.cycle_state(),
|
||||
KeyCode::Char('x') if self.edited(self.section) => return self.reset(),
|
||||
KeyCode::Tab if count > 0 => {
|
||||
self.section = (self.section + 1) % count;
|
||||
self.selected = 0;
|
||||
}
|
||||
KeyCode::BackTab if count > 0 => {
|
||||
self.section = self.section.checked_sub(1).unwrap_or(count - 1);
|
||||
self.selected = 0;
|
||||
}
|
||||
KeyCode::Right if self.detail().is_some() => self.focus = Focus::Detail,
|
||||
KeyCode::Down if rows > 0 => {
|
||||
self.selected = (self.selected + 1).min(rows - 1);
|
||||
return self.next_page_if_due();
|
||||
}
|
||||
KeyCode::PageDown if rows > 0 => {
|
||||
self.selected = (self.selected + PAGE_ROWS).min(rows - 1);
|
||||
return self.next_page_if_due();
|
||||
}
|
||||
KeyCode::End if rows > 0 => {
|
||||
self.selected = rows - 1;
|
||||
return self.next_page_if_due();
|
||||
}
|
||||
KeyCode::Up => self.selected = self.selected.saturating_sub(1),
|
||||
KeyCode::PageUp => self.selected = self.selected.saturating_sub(PAGE_ROWS),
|
||||
KeyCode::Home => self.selected = 0,
|
||||
KeyCode::Enter | KeyCode::Char('c') | KeyCode::Char('o') => {
|
||||
return self.row_action(key.code);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
GithubKey::Held
|
||||
}
|
||||
|
||||
/// What Enter, `c` and `o` do with the row under the cursor.
|
||||
fn row_action(&self, code: KeyCode) -> GithubKey {
|
||||
let Some(item) = self.rows().get(self.selected).copied().cloned() else {
|
||||
return GithubKey::Held;
|
||||
};
|
||||
let elsewhere = self.elsewhere(&item);
|
||||
match code {
|
||||
KeyCode::Char('o') => GithubKey::Open(item.url),
|
||||
KeyCode::Char('c') => GithubKey::Refer(Box::new(item)),
|
||||
_ if item.pull_request => GithubKey::Review {
|
||||
number: item.number,
|
||||
repository: elsewhere.then(|| item.repository.clone()),
|
||||
},
|
||||
_ if elsewhere => GithubKey::Refused(format!(
|
||||
"#{} is on {}; a session on it starts from a checkout of {}.",
|
||||
item.number, item.repository, item.repository
|
||||
)),
|
||||
// Your own session on it, when one took it up, before a second one
|
||||
_ => match self.details.get(&item.url).and_then(|d| d.local.as_ref()) {
|
||||
Some(local) => GithubKey::Resume(local.session.clone()),
|
||||
None => GithubKey::TakeUpIssue(item.number),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a detail's answer asks of the app, for `subject` in `repository`.
|
||||
fn detail_request(
|
||||
subject: &crate::github_detail::Subject,
|
||||
repository: Option<String>,
|
||||
answer: DetailKey,
|
||||
) -> GithubKey {
|
||||
match answer {
|
||||
DetailKey::Held | DetailKey::Leave => GithubKey::Held,
|
||||
DetailKey::Open(url) => GithubKey::Open(url),
|
||||
DetailKey::Act(action) => match subject {
|
||||
crate::github_detail::Subject::PullRequest(pr) => {
|
||||
GithubKey::Act { repository, overview: pr.clone(), action }
|
||||
}
|
||||
crate::github_detail::Subject::Issue(_) => GithubKey::Held,
|
||||
},
|
||||
DetailKey::Merge(write) => GithubKey::Merge { repository, number: subject.number(), write },
|
||||
DetailKey::Resume(session) => GithubKey::Resume(session),
|
||||
DetailKey::ReadConversation => {
|
||||
let number = subject.number();
|
||||
let pull_request = matches!(subject, crate::github_detail::Subject::PullRequest(_));
|
||||
GithubKey::ReadConversation { repository, number, pull_request }
|
||||
}
|
||||
DetailKey::Post(request) => GithubKey::Post(luxe_core::engine::GithubPost {
|
||||
repository,
|
||||
number: subject.number(),
|
||||
thread: request.thread,
|
||||
answering: request.answering,
|
||||
body: request.body,
|
||||
}),
|
||||
DetailKey::EditExternally(text) => GithubKey::EditExternally(text),
|
||||
DetailKey::Draft(ask) => {
|
||||
let number = subject.number();
|
||||
let pull_request = matches!(subject, crate::github_detail::Subject::PullRequest(_));
|
||||
GithubKey::Draft { repository, number, pull_request, ask }
|
||||
}
|
||||
}
|
||||
}
|
||||
126
crates/luxe-tui/src/github_panel/reads.rs
Normal file
126
crates/luxe-tui/src/github_panel/reads.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Reads — when `/github` asks for a row's detail, and where the answer lands.
|
||||
//!
|
||||
//! The cursor has to rest on a row for a moment before it is read, so holding Down through a list
|
||||
//! asks for the row you stop on rather than every row you passed; each row is read once, until a
|
||||
//! refresh forgets them all. An answer is matched to its row by repository and number, so one that
|
||||
//! arrives after the reader moved on still lands where it belongs.
|
||||
|
||||
use luxe_core::github::ListItem;
|
||||
|
||||
use super::GithubPanel;
|
||||
use crate::github_detail::GithubDetail;
|
||||
|
||||
/// How long the cursor rests on a row before its overview is read: holding Down through a list
|
||||
/// asks for the row you stop on, not every row you passed.
|
||||
const SETTLE: std::time::Duration = std::time::Duration::from_millis(250);
|
||||
|
||||
/// An overview to ask the engine for.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OverviewRead {
|
||||
/// `owner/name` when it is not the checkout's repository
|
||||
pub repository: Option<String>,
|
||||
/// Its number
|
||||
pub number: u64,
|
||||
/// Whether it is a pull request, rather than an issue
|
||||
pub pull_request: bool,
|
||||
}
|
||||
|
||||
impl GithubPanel {
|
||||
/// Watches the cursor, and answers the read to send once it has rested on a row that has not
|
||||
/// been read: one read per row, however often the cursor passes through it.
|
||||
pub fn due_read(&mut self, now: std::time::Instant) -> Option<OverviewRead> {
|
||||
let item = self.rows().get(self.selected).copied().cloned()?;
|
||||
let known = self.details.contains_key(&item.url)
|
||||
|| self.failures.contains_key(&item.url)
|
||||
|| self.asked.contains(&item.url);
|
||||
match &self.settling {
|
||||
Some((url, _)) if *url != item.url => {
|
||||
self.settling = Some((item.url, now));
|
||||
None
|
||||
}
|
||||
None => {
|
||||
self.settling = Some((item.url, now));
|
||||
None
|
||||
}
|
||||
Some((_, since)) if known || now.duration_since(*since) < SETTLE => None,
|
||||
Some(_) => {
|
||||
self.asked.insert(item.url.clone());
|
||||
let repository = self.elsewhere(&item).then(|| item.repository.clone());
|
||||
Some(OverviewRead {
|
||||
repository,
|
||||
number: item.number,
|
||||
pull_request: item.pull_request,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the row under the cursor is still waiting on its overview.
|
||||
pub fn reading(&self) -> bool {
|
||||
self.rows().get(self.selected).is_some_and(|item| {
|
||||
!self.details.contains_key(&item.url) && !self.failures.contains_key(&item.url)
|
||||
})
|
||||
}
|
||||
|
||||
/// Lands an overview, or why there is none, in the detail of the row it answers.
|
||||
///
|
||||
/// Args: `(repository, number, overview, error, local, branch)` — `repository` as asked, `None`
|
||||
/// for the checkout's; `branch` the number of the checked-out branch's pull request, the only
|
||||
/// one whose threads can be worked through here.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn land(
|
||||
&mut self,
|
||||
repository: Option<&str>,
|
||||
number: u64,
|
||||
overview: Option<luxe_core::github::overview::Overview>,
|
||||
error: Option<String>,
|
||||
local: Option<luxe_core::github::overview::LocalSession>,
|
||||
branch: Option<u64>,
|
||||
) {
|
||||
let here = self.repository.clone();
|
||||
let matches = |item: &ListItem| {
|
||||
item.number == number
|
||||
&& match repository {
|
||||
Some(slug) => item.repository.eq_ignore_ascii_case(slug),
|
||||
None => here
|
||||
.as_deref()
|
||||
.is_none_or(|here| here.eq_ignore_ascii_case(&item.repository)),
|
||||
}
|
||||
};
|
||||
let Some(url) = self
|
||||
.sections
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|section| §ion.items)
|
||||
.find(|item| matches(item))
|
||||
.map(|item| item.url.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.asked.remove(&url);
|
||||
match overview {
|
||||
Some(overview) => {
|
||||
let on_branch = repository.is_none()
|
||||
&& matches!(overview, luxe_core::github::overview::Overview::PullRequest(_))
|
||||
&& branch == Some(number);
|
||||
let mut detail = GithubDetail::new(overview);
|
||||
detail.on_branch = on_branch;
|
||||
detail.local = local;
|
||||
self.failures.remove(&url);
|
||||
self.details.insert(url, detail);
|
||||
}
|
||||
None => {
|
||||
let reason = error.unwrap_or_else(|| "No answer from GitHub".into());
|
||||
self.failures.insert(url, reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets every overview read, so the next look at each row reads it again.
|
||||
pub fn forget_details(&mut self) {
|
||||
self.details.clear();
|
||||
self.failures.clear();
|
||||
self.asked.clear();
|
||||
self.settling = None;
|
||||
}
|
||||
}
|
||||
146
crates/luxe-tui/src/github_panel/render.rs
Normal file
146
crates/luxe-tui/src/github_panel/render.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
//! The GitHub panel's drawing — its chrome, the list of each tab, the detail, and a failed read.
|
||||
|
||||
use super::{rows, Focus, GithubPanel, SPLIT_MIN_WIDTH};
|
||||
use crate::glyphs::Icon;
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Clear, Padding, Paragraph};
|
||||
use ratatui::Frame;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// The icon a section's tab wears, read from what it searches for: your review, issues, your own,
|
||||
/// pull requests, or anything else a configured section asks GitHub.
|
||||
pub fn section_icon(query: &str) -> Icon {
|
||||
let has = |qualifier: &str| query.split_whitespace().any(|term| term.starts_with(qualifier));
|
||||
if has("review-requested:") {
|
||||
Icon::ReviewRequested
|
||||
} else if has("is:issue") {
|
||||
Icon::Issue
|
||||
} else if has("author:@me") {
|
||||
Icon::Mine
|
||||
} else if has("is:pr") {
|
||||
Icon::PullRequest
|
||||
} else {
|
||||
Icon::Search
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws `/github` over `area`, the whole terminal, less a margin.
|
||||
///
|
||||
/// Args: `(frame, area, panel, styles, spinner frame)`.
|
||||
pub fn render(f: &mut Frame, area: Rect, panel: &GithubPanel, styles: &ThemeStyles, frame: usize) {
|
||||
// The whole screen goes, not just the frame: a sliver of dock beside a modal this size reads
|
||||
// as a rendering fault
|
||||
f.render_widget(Clear, area);
|
||||
f.render_widget(Paragraph::new("").style(styles.background), area);
|
||||
let modal = crate::widgets::centered_rect(
|
||||
area.width.saturating_sub(2).min(200),
|
||||
area.height.saturating_sub(2),
|
||||
area,
|
||||
);
|
||||
f.render_widget(Clear, modal);
|
||||
let title = match &panel.repository {
|
||||
Some(repository) => format!("GitHub · {repository}"),
|
||||
None => "GitHub".into(),
|
||||
};
|
||||
let block = crate::widgets::titled_panel(crate::glyphs::Icon::GitHub.glyph(), &title, styles)
|
||||
.padding(Padding::horizontal(1));
|
||||
let rows = panel.rows().len();
|
||||
let count = (rows > 0).then(|| format!("{}/{rows}", panel.selected + 1));
|
||||
let body =
|
||||
crate::widgets::render_footed(f, block, modal, &panel.hint(), count.as_deref(), styles);
|
||||
let now = panel.now();
|
||||
let detail = panel.detail();
|
||||
let list_focused = panel.focus == Focus::List || detail.is_none();
|
||||
|
||||
// The tabs choose what the whole panel shows, so they run across all of it
|
||||
let body = if panel.sections.is_some() && body.height > 2 {
|
||||
let tabs = rows::tab_line(panel, usize::from(body.width), styles);
|
||||
f.render_widget(Paragraph::new(tabs), Rect { height: 1, ..body });
|
||||
let rule = Span::styled("─".repeat(usize::from(body.width)), styles.border_muted);
|
||||
f.render_widget(
|
||||
Paragraph::new(Line::from(rule)),
|
||||
Rect { y: body.y + 1, height: 1, ..body },
|
||||
);
|
||||
Rect { y: body.y + 3, height: body.height - 3, ..body }
|
||||
} else {
|
||||
body
|
||||
};
|
||||
|
||||
if body.width < SPLIT_MIN_WIDTH {
|
||||
match detail.filter(|_| !list_focused) {
|
||||
Some(detail) => crate::github_detail::render(f, body, detail, true, now, styles),
|
||||
None => draw_list(f, body, panel, true, now, styles, frame),
|
||||
}
|
||||
} else {
|
||||
let list_width = (body.width * 2 / 5).clamp(56, 76);
|
||||
let list = Rect { width: list_width, ..body };
|
||||
draw_list(f, list, panel, list_focused, now, styles, frame);
|
||||
let rule: Vec<Line> =
|
||||
(0..body.height).map(|_| Line::from(Span::styled("│", styles.border_muted))).collect();
|
||||
f.render_widget(Paragraph::new(rule), Rect { x: list.right() + 1, width: 1, ..body });
|
||||
let pane =
|
||||
Rect { x: list.right() + 3, width: body.width.saturating_sub(list_width + 3), ..body };
|
||||
match detail {
|
||||
Some(detail) => {
|
||||
crate::github_detail::render(f, pane, detail, !list_focused, now, styles)
|
||||
}
|
||||
None if panel.rows().is_empty() => {}
|
||||
None if failed(panel).is_some() => {
|
||||
let reason = failed(panel).unwrap_or_default();
|
||||
let line = Line::from(crate::widgets::code_spans(&reason, styles.error, styles));
|
||||
f.render_widget(
|
||||
Paragraph::new(line).wrap(ratatui::widgets::Wrap { trim: false }),
|
||||
pane,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
let spinner = crate::statusline::spinner(frame);
|
||||
let line = Line::from(Span::styled(format!("{spinner} Reading it…"), styles.muted));
|
||||
f.render_widget(Paragraph::new(line), pane);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(detail) = panel.detail() {
|
||||
crate::github_detail::render_overlays(f, modal, detail, frame, styles);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the row under the cursor has no overview, when reading it failed.
|
||||
fn failed(panel: &GithubPanel) -> Option<String> {
|
||||
let item = panel.rows().get(panel.selected).copied()?;
|
||||
panel.failures.get(&item.url).cloned()
|
||||
}
|
||||
|
||||
fn draw_list(
|
||||
f: &mut Frame,
|
||||
area: Rect,
|
||||
panel: &GithubPanel,
|
||||
focused: bool,
|
||||
now: u64,
|
||||
styles: &ThemeStyles,
|
||||
frame: usize,
|
||||
) {
|
||||
let lines = rows::list_lines(
|
||||
panel,
|
||||
usize::from(area.width),
|
||||
usize::from(area.height),
|
||||
focused,
|
||||
now,
|
||||
styles,
|
||||
frame,
|
||||
);
|
||||
f.render_widget(Paragraph::new(lines), area);
|
||||
// The search being typed, over its line, with the terminal's cursor where typing goes
|
||||
if let Some(editor) = &panel.editing {
|
||||
let count = rows::query_count(panel, frame).width() as u16;
|
||||
let field = Rect {
|
||||
x: area.x + rows::QUERY_INSET,
|
||||
width: area.width.saturating_sub(rows::QUERY_INSET + count + 1),
|
||||
height: 1,
|
||||
..area
|
||||
};
|
||||
crate::widgets::text_field::render(f, field, editor, styles);
|
||||
}
|
||||
}
|
||||
421
crates/luxe-tui/src/github_panel/rows.rs
Normal file
421
crates/luxe-tui/src/github_panel/rows.rs
Normal file
@@ -0,0 +1,421 @@
|
||||
//! The list side of `/github`: the tabs across the top, then the search a tab ran and each pull
|
||||
//! request or issue it found on two lines.
|
||||
//!
|
||||
//! Line one is what it is — a state mark, the number, the title, how long ago it changed. Line two
|
||||
//! is where it stands, quiet: who opened it, how big it is, and on the right its status in words.
|
||||
//! Every mark sits beside a word, so nothing here depends on a glyph to be understood.
|
||||
|
||||
use luxe_core::github::overview::RowFacts;
|
||||
use luxe_core::github::{rfc3339_seconds, Author, ListItem, ReviewDecision};
|
||||
use ratatui::text::{Line, Span};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
use super::GithubPanel;
|
||||
use crate::github_detail::{ago, author_spans, diff_counts, lift_dim, state_word};
|
||||
use crate::glyphs::{Icon, Mark};
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
|
||||
/// Lines each row takes: its two, and the gap under it.
|
||||
pub(super) const ROW_LINES: usize = 3;
|
||||
|
||||
/// Where the search being typed starts on its line: after the `/ ` that says what the line is.
|
||||
pub(super) const QUERY_INSET: u16 = 4;
|
||||
|
||||
/// Qualifiers worth knowing, offered under a search being typed, most useful first.
|
||||
const QUALIFIERS: &[&str] = &[
|
||||
"is:closed",
|
||||
"is:merged",
|
||||
"is:draft",
|
||||
"label:bug",
|
||||
"author:@me",
|
||||
"assignee:@me",
|
||||
"review-requested:@me",
|
||||
"no:assignee",
|
||||
"sort:updated-desc",
|
||||
"sort:created-asc",
|
||||
];
|
||||
|
||||
/// The tabs, on one line `width` wide: each named with its count, then without when the counts
|
||||
/// will not fit, then a run of them around the open one, with `‹` and `›` saying more are aside.
|
||||
pub(super) fn tab_line(panel: &GithubPanel, width: usize, styles: &ThemeStyles) -> Line<'static> {
|
||||
let Some(sections) = &panel.sections else {
|
||||
return Line::default();
|
||||
};
|
||||
let label = |index: usize, counted: bool| {
|
||||
let section = §ions[index];
|
||||
let edited = if panel.edited(index) { "*" } else { "" };
|
||||
let text = match counted {
|
||||
true => {
|
||||
let count = section.total.unwrap_or(section.items.len() as u64);
|
||||
format!("{}{edited} {}", section.name, grouped(count))
|
||||
}
|
||||
false => format!("{}{edited}", section.name),
|
||||
};
|
||||
match panel.icons.get(index) {
|
||||
Some(icon) => crate::glyphs::icon_label(icon.glyph(), &text),
|
||||
None => text,
|
||||
}
|
||||
};
|
||||
let cells = |labels: &[String]| -> usize {
|
||||
labels.iter().map(|label| label.width() + crate::widgets::SLAB_FRAME).sum()
|
||||
};
|
||||
let counted: Vec<String> = (0..sections.len()).map(|index| label(index, true)).collect();
|
||||
let labels = if cells(&counted) <= width {
|
||||
counted
|
||||
} else {
|
||||
(0..sections.len()).map(|index| label(index, false)).collect()
|
||||
};
|
||||
let open = panel.section.min(labels.len().saturating_sub(1));
|
||||
let (first, last) = window(&labels, open, width);
|
||||
let shown: Vec<&str> = labels[first..last].iter().map(String::as_str).collect();
|
||||
let mut line = crate::picker::tab_line(&shown, open - first, styles);
|
||||
if first > 0 {
|
||||
line.spans.insert(0, Span::styled("‹", styles.muted));
|
||||
}
|
||||
if last < labels.len() {
|
||||
line.spans.push(Span::styled("›", styles.muted));
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// The run of `labels` around `open` that fits `width` with room for a marker each side, as a
|
||||
/// half-open range: the open one always, then a neighbor at a time, right first.
|
||||
fn window(labels: &[String], open: usize, width: usize) -> (usize, usize) {
|
||||
let cells = |label: &String| label.width() + crate::widgets::SLAB_FRAME;
|
||||
let total: usize = labels.iter().map(cells).sum();
|
||||
if total <= width || labels.is_empty() {
|
||||
return (0, labels.len());
|
||||
}
|
||||
let room = width.saturating_sub(2);
|
||||
let (mut first, mut last) = (open, open + 1);
|
||||
let mut used = cells(&labels[open]);
|
||||
loop {
|
||||
let mut grew = false;
|
||||
if last < labels.len() && used + cells(&labels[last]) <= room {
|
||||
used += cells(&labels[last]);
|
||||
last += 1;
|
||||
grew = true;
|
||||
}
|
||||
if first > 0 && used + cells(&labels[first - 1]) <= room {
|
||||
used += cells(&labels[first - 1]);
|
||||
first -= 1;
|
||||
grew = true;
|
||||
}
|
||||
if !grew {
|
||||
return (first, last);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `count` with its thousands set apart: `3,250`.
|
||||
fn grouped(count: u64) -> String {
|
||||
let digits = count.to_string();
|
||||
let mut out = String::new();
|
||||
for (index, digit) in digits.chars().enumerate() {
|
||||
if index > 0 && (digits.len() - index).is_multiple_of(3) {
|
||||
out.push(',');
|
||||
}
|
||||
out.push(digit);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What the line over the rows says on its right: how many are here of how many there are, or
|
||||
/// that the tab is being searched again.
|
||||
pub(super) fn query_count(panel: &GithubPanel, frame: usize) -> String {
|
||||
let Some(section) = panel.sections.as_ref().and_then(|sections| sections.get(panel.section))
|
||||
else {
|
||||
return String::new();
|
||||
};
|
||||
if panel.researching(panel.section) {
|
||||
return format!("{} Searching…", crate::statusline::spinner(frame));
|
||||
}
|
||||
if section.error.is_some() {
|
||||
return String::new();
|
||||
}
|
||||
let loaded = section.items.len() as u64;
|
||||
if panel.editing.is_some() {
|
||||
let rows = panel.rows().len();
|
||||
return format!("{} of {} match", grouped(rows as u64), grouped(loaded));
|
||||
}
|
||||
match section.total {
|
||||
Some(total) if total > loaded => format!("{} of {}", grouped(loaded), grouped(total)),
|
||||
_ => format!("{} shown", grouped(loaded)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The list's lines for a pane `width` wide and `height` tall: the search, then its rows. A search
|
||||
/// being typed is drawn over the first line by the caller, which owns the terminal's cursor.
|
||||
///
|
||||
/// Args: `(panel, width, height, focused, now, styles, spinner frame)`.
|
||||
pub(super) fn list_lines(
|
||||
panel: &GithubPanel,
|
||||
width: usize,
|
||||
height: usize,
|
||||
focused: bool,
|
||||
now: u64,
|
||||
styles: &ThemeStyles,
|
||||
frame: usize,
|
||||
) -> Vec<Line<'static>> {
|
||||
let Some(sections) = &panel.sections else {
|
||||
let spinner = crate::statusline::spinner(frame);
|
||||
return vec![Line::from(Span::styled(
|
||||
format!("{spinner} Fetching data from GitHub…"),
|
||||
styles.muted,
|
||||
))];
|
||||
};
|
||||
let count = query_count(panel, frame);
|
||||
let query = match &panel.editing {
|
||||
Some(_) => String::new(),
|
||||
None => panel.shown_query(panel.section),
|
||||
};
|
||||
let query_style = if panel.edited(panel.section) { styles.text } else { styles.muted };
|
||||
let left = vec![
|
||||
Span::styled(" / ", styles.accent),
|
||||
Span::styled(if query.is_empty() { "everything".into() } else { query }, query_style),
|
||||
];
|
||||
let mut lines = vec![Line::from(spread(left, vec![Span::styled(count, styles.muted)], width))];
|
||||
if panel.editing.is_some() {
|
||||
lines.push(Line::from(hints(width, styles)));
|
||||
}
|
||||
lines.push(Line::default());
|
||||
let head = lines.len();
|
||||
|
||||
let Some(section) = sections.get(panel.section) else {
|
||||
return lines;
|
||||
};
|
||||
if let Some(error) = §ion.error {
|
||||
let mut spans = vec![Span::raw(" ")];
|
||||
spans.extend(crate::widgets::code_spans(error, styles.error, styles));
|
||||
lines.push(Line::from(spans));
|
||||
return lines;
|
||||
}
|
||||
if panel.researching(panel.section) {
|
||||
let spinner = crate::statusline::spinner(frame);
|
||||
lines
|
||||
.push(Line::from(Span::styled(format!(" {spinner} Searching GitHub…"), styles.muted)));
|
||||
return lines;
|
||||
}
|
||||
let rows = panel.rows();
|
||||
if rows.is_empty() {
|
||||
let said = match panel.editing {
|
||||
Some(_) => "No loaded row matches · enter searches GitHub",
|
||||
None => "Nothing matches this search",
|
||||
};
|
||||
lines.push(Line::from(Span::styled(format!(" {said}"), styles.muted)));
|
||||
return lines;
|
||||
}
|
||||
let more = more_line(panel, section, frame, styles);
|
||||
let room = height.saturating_sub(head + usize::from(more.is_some()));
|
||||
let fits = (room / ROW_LINES).max(1);
|
||||
let first = (panel.selected + 1).saturating_sub(fits);
|
||||
for (index, item) in rows.iter().enumerate().skip(first).take(fits) {
|
||||
let selected = index == panel.selected;
|
||||
let facts = item.facts.as_ref();
|
||||
lines.extend(row(
|
||||
item,
|
||||
facts,
|
||||
panel.elsewhere(item),
|
||||
width,
|
||||
selected,
|
||||
focused,
|
||||
now,
|
||||
styles,
|
||||
));
|
||||
lines.push(Line::default());
|
||||
}
|
||||
if let Some(more) = more.filter(|_| first + fits >= rows.len()) {
|
||||
lines.push(more);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// The line under the last row when the search has more than it brought: how many, or that the
|
||||
/// next page is on its way. Not while a search is being typed, when the rows are only a preview.
|
||||
fn more_line(
|
||||
panel: &GithubPanel,
|
||||
section: &luxe_core::github::ListedSection,
|
||||
frame: usize,
|
||||
styles: &ThemeStyles,
|
||||
) -> Option<Line<'static>> {
|
||||
if panel.editing.is_some() {
|
||||
return None;
|
||||
}
|
||||
if panel.paging(panel.section) {
|
||||
let spinner = crate::statusline::spinner(frame);
|
||||
return Some(Line::from(Span::styled(format!(" {spinner} Loading more…"), styles.muted)));
|
||||
}
|
||||
section.next.as_ref()?;
|
||||
let loaded = section.items.len() as u64;
|
||||
let left = section.total.unwrap_or(loaded).saturating_sub(loaded);
|
||||
let said = match left {
|
||||
0 => "More below".to_owned(),
|
||||
left => format!("{} more below", grouped(left)),
|
||||
};
|
||||
Some(Line::from(Span::styled(format!(" {said}"), styles.muted)))
|
||||
}
|
||||
|
||||
/// Qualifiers for the line under a search being typed, as many as fit.
|
||||
fn hints(width: usize, styles: &ThemeStyles) -> Vec<Span<'static>> {
|
||||
let lead = " try ";
|
||||
let mut spans = vec![Span::styled(lead, styles.dim)];
|
||||
let mut used = lead.width();
|
||||
for (index, qualifier) in QUALIFIERS.iter().enumerate() {
|
||||
let gap = if index == 0 { 0 } else { 2 };
|
||||
if used + gap + qualifier.width() > width {
|
||||
break;
|
||||
}
|
||||
if gap > 0 {
|
||||
spans.push(Span::raw(" "));
|
||||
}
|
||||
spans.push(Span::styled(*qualifier, styles.muted));
|
||||
used += gap + qualifier.width();
|
||||
}
|
||||
spans
|
||||
}
|
||||
|
||||
/// One pull request or issue on its two lines, cut into one slab when it is under the cursor.
|
||||
///
|
||||
/// Args: `(item, facts, elsewhere, width, selected, focused, now, styles)` — `focused` dims the
|
||||
/// slab when the keys are in the detail, so the row still says which one the detail is about.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn row(
|
||||
item: &ListItem,
|
||||
facts: Option<&RowFacts>,
|
||||
elsewhere: bool,
|
||||
width: usize,
|
||||
selected: bool,
|
||||
focused: bool,
|
||||
now: u64,
|
||||
styles: &ThemeStyles,
|
||||
) -> Vec<Line<'static>> {
|
||||
let room = width.saturating_sub(crate::widgets::SELECTION_FRAME);
|
||||
let issue = !item.pull_request;
|
||||
let (_, state_style) = state_word(item.state, item.draft, issue, styles);
|
||||
let icon = if issue { Icon::Issue } else { Icon::PullRequest };
|
||||
let mark = icon.prefix();
|
||||
let inset = mark.width();
|
||||
|
||||
let age = rfc3339_seconds(&item.updated_at)
|
||||
.map(|at| ago(at, now).trim_end_matches(" ago").to_owned())
|
||||
.unwrap_or_default();
|
||||
let title_style = styles.label_on(selected && focused);
|
||||
let first = spread(
|
||||
vec![
|
||||
Span::styled(mark, state_style),
|
||||
Span::styled(format!("#{} ", item.number), styles.muted),
|
||||
Span::styled(item.title.clone(), title_style),
|
||||
],
|
||||
vec![Span::styled(age, styles.muted)],
|
||||
room,
|
||||
);
|
||||
|
||||
let author = Author { login: item.author.clone(), bot: facts.is_some_and(|f| f.author_bot) };
|
||||
let mut left = vec![Span::raw(" ".repeat(inset))];
|
||||
left.extend(author_spans(&author, styles));
|
||||
let dot = || Span::styled(" · ", styles.dim);
|
||||
if elsewhere {
|
||||
left.extend([dot(), Span::styled(item.repository.clone(), styles.muted)]);
|
||||
}
|
||||
let status = status(item, facts, styles);
|
||||
match (issue, facts) {
|
||||
(false, Some(facts)) => {
|
||||
// Whole or not at all: cut to fit, `+96 −31` came out `+…`, which says nothing
|
||||
let counts = diff_counts(facts.additions, facts.deletions, styles);
|
||||
let width = |spans: &[Span]| spans.iter().map(Span::width).sum::<usize>();
|
||||
if width(&left) + 3 + width(&counts) + 1 + width(&status) <= room {
|
||||
left.push(dot());
|
||||
left.extend(counts);
|
||||
}
|
||||
}
|
||||
(true, Some(facts)) if !facts.labels.is_empty() => {
|
||||
let names: Vec<&str> = facts.labels.iter().map(|label| label.name.as_str()).collect();
|
||||
left.extend([dot(), Span::styled(names.join(", "), styles.muted)]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let second = spread(left, status, room);
|
||||
|
||||
let (mut first, mut second) = (first, second);
|
||||
if selected && focused {
|
||||
lift_dim(&mut first, styles);
|
||||
lift_dim(&mut second, styles);
|
||||
}
|
||||
let mut lines =
|
||||
crate::widgets::selection_block(vec![first, second], width, selected && focused, styles);
|
||||
// With the keys in the detail, the row it is about keeps a cursor mark in the inset the slab
|
||||
// would have used, so the detail still says which row it belongs to
|
||||
if selected && !focused {
|
||||
if let Some(inset) = lines.first_mut().and_then(|line| line.spans.first_mut()) {
|
||||
*inset = Span::styled(Mark::Cursor.gutter(true), styles.accent);
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Where it stands, in words, for the right of line two: `✗ 1 failing · changes requested`.
|
||||
fn status(item: &ListItem, facts: Option<&RowFacts>, styles: &ThemeStyles) -> Vec<Span<'static>> {
|
||||
let mut parts: Vec<Span<'static>> = Vec::new();
|
||||
let mut push = |text: String, style| {
|
||||
if !parts.is_empty() {
|
||||
parts.push(Span::styled(" · ", styles.dim));
|
||||
}
|
||||
parts.push(Span::styled(text, style));
|
||||
};
|
||||
let (word, style) = state_word(item.state, item.draft, !item.pull_request, styles);
|
||||
if item.draft || item.state != luxe_core::github::PullRequestState::Open {
|
||||
push(word.to_owned(), style);
|
||||
}
|
||||
let Some(facts) = facts else {
|
||||
return parts;
|
||||
};
|
||||
if !item.pull_request {
|
||||
match facts.linked_pull_request {
|
||||
Some(number) => push(format!("{} PR #{number}", Mark::Waiting.glyph()), styles.warning),
|
||||
None if facts.comments > 0 => {
|
||||
let noun = if facts.comments == 1 { "comment" } else { "comments" };
|
||||
push(format!("{} {noun}", facts.comments), styles.muted);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
let checks = &facts.checks;
|
||||
if checks.failed > 0 {
|
||||
push(format!("{} {} failing", Mark::No.glyph(), checks.failed), styles.error);
|
||||
} else if checks.pending > 0 {
|
||||
push(format!("{} running", Mark::Waiting.glyph()), styles.warning);
|
||||
} else if checks.passed > 0 {
|
||||
push(format!("{} checks", Mark::Yes.glyph()), styles.success);
|
||||
}
|
||||
match facts.review_decision {
|
||||
Some(ReviewDecision::ChangesRequested) => push("changes requested".into(), styles.error),
|
||||
Some(ReviewDecision::Approved) => push("approved".into(), styles.success),
|
||||
Some(ReviewDecision::ReviewRequired) => push("needs review".into(), styles.muted),
|
||||
None => {}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// `left`, then `right` against the edge of `room`, the left cut short to make the room.
|
||||
fn spread(left: Vec<Span<'static>>, right: Vec<Span<'static>>, room: usize) -> Vec<Span<'static>> {
|
||||
let right_cells: usize = right.iter().map(|span| span.content.width()).sum();
|
||||
let budget = room.saturating_sub(right_cells + usize::from(right_cells > 0));
|
||||
let mut spans = Vec::new();
|
||||
let mut used = 0;
|
||||
for span in left {
|
||||
let cells = span.content.width();
|
||||
if used + cells <= budget {
|
||||
used += cells;
|
||||
spans.push(span);
|
||||
continue;
|
||||
}
|
||||
let cut = crate::widgets::truncate_end(&span.content, budget.saturating_sub(used));
|
||||
used += cut.width();
|
||||
spans.push(Span::styled(cut, span.style));
|
||||
break;
|
||||
}
|
||||
spans.push(Span::raw(" ".repeat(room.saturating_sub(used + right_cells))));
|
||||
spans.extend(right);
|
||||
spans
|
||||
}
|
||||
220
crates/luxe-tui/src/github_panel/search.rs
Normal file
220
crates/luxe-tui/src/github_panel/search.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
//! Searches — each tab's query as the reader edits it, and the pages that answer it.
|
||||
//!
|
||||
//! The rewriting is `luxe_core::github::query`'s, so a scoped tab stays in the checkout's repository
|
||||
//! whatever is typed. Here is only where the keys go and where the answers land: an answer is
|
||||
//! matched by the id it was asked under, and one for a search since replaced is dropped rather than
|
||||
//! put over the newer one.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use luxe_core::github::{query, ListedSection};
|
||||
|
||||
use super::{GithubKey, GithubPanel};
|
||||
|
||||
/// Request ids, unique for the process: a panel closed and opened again must not take an answer
|
||||
/// meant for the last one's search.
|
||||
static REQUESTS: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// A search asked for on its own and not yet answered.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Pending {
|
||||
/// The tab it fills
|
||||
pub section: usize,
|
||||
/// Whether it brings the next page, rather than replacing the tab's rows
|
||||
pub page: bool,
|
||||
}
|
||||
|
||||
impl GithubPanel {
|
||||
/// The tab's search as the line over its rows shows it, without the scope it never says.
|
||||
pub fn shown_query(&self, section: usize) -> String {
|
||||
self.searches.get(section).map(|search| query::shown(&search.query)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether tab `section` searches something other than what it was configured to.
|
||||
pub fn edited(&self, section: usize) -> bool {
|
||||
match (self.searches.get(section), self.configured.get(section)) {
|
||||
(Some(search), Some(configured)) => search.query != configured.query,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether tab `section` is being searched again, its old rows already gone.
|
||||
pub fn researching(&self, section: usize) -> bool {
|
||||
self.pending.values().any(|pending| pending.section == section && !pending.page)
|
||||
}
|
||||
|
||||
/// Whether tab `section` is waiting on its next page.
|
||||
pub fn paging(&self, section: usize) -> bool {
|
||||
self.pending.values().any(|pending| pending.section == section && pending.page)
|
||||
}
|
||||
|
||||
/// Whether anything asked of GitHub on its own is still out.
|
||||
pub fn searching(&self) -> bool {
|
||||
!self.pending.is_empty()
|
||||
}
|
||||
|
||||
/// The words typed beyond the tab's own search, lowercased: what the loaded rows are narrowed
|
||||
/// by while a search is being typed. Qualifiers wait for GitHub.
|
||||
pub(super) fn preview(&self) -> Vec<String> {
|
||||
let Some(editor) = &self.editing else {
|
||||
return Vec::new();
|
||||
};
|
||||
let shown = self.shown_query(self.section).to_lowercase();
|
||||
let had: Vec<&str> = shown.split_whitespace().collect();
|
||||
editor
|
||||
.current_input()
|
||||
.to_lowercase()
|
||||
.split_whitespace()
|
||||
.filter(|word| !word.contains(':') && !word.starts_with('-') && !had.contains(word))
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn start_editing(&mut self) {
|
||||
let mut editor = crate::editor::Editor::new();
|
||||
let shown = self.shown_query(self.section);
|
||||
// A space after, so a word typed straight away is a word of its own
|
||||
editor.insert_text(&if shown.is_empty() { shown } else { format!("{shown} ") });
|
||||
self.editing = Some(editor);
|
||||
}
|
||||
|
||||
/// A pasted line, into the search being typed; whether there was one to take it.
|
||||
pub fn paste(&mut self, text: &str) -> bool {
|
||||
let Some(editor) = self.editing.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
editor.insert_text(&crate::editor::single_line_paste(text));
|
||||
self.selected = 0;
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn on_editing_key(&mut self, key: &KeyEvent) -> GithubKey {
|
||||
match key.code {
|
||||
KeyCode::Esc => {
|
||||
self.editing = None;
|
||||
self.selected = 0;
|
||||
GithubKey::Held
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
let typed = self.editing.take().map(|editor| editor.current_input().to_owned());
|
||||
self.selected = 0;
|
||||
let typed = typed.unwrap_or_default();
|
||||
let configured = self.configured.get(self.section).map(|c| c.query.clone());
|
||||
let Some(configured) = configured else {
|
||||
return GithubKey::Held;
|
||||
};
|
||||
// Emptied is the way back to the tab's own search
|
||||
let wanted = match typed.trim() {
|
||||
"" => configured,
|
||||
typed => query::edited(&configured, typed),
|
||||
};
|
||||
self.run(self.section, wanted)
|
||||
}
|
||||
_ => {
|
||||
if let Some(editor) = self.editing.as_mut() {
|
||||
editor.handle_key(*key);
|
||||
}
|
||||
self.selected = 0;
|
||||
GithubKey::Held
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Steps the tab on screen to the next state: open, closed, merged, all.
|
||||
pub(super) fn cycle_state(&mut self) -> GithubKey {
|
||||
let Some(current) = self.searches.get(self.section).map(|s| s.query.clone()) else {
|
||||
return GithubKey::Held;
|
||||
};
|
||||
let wanted = query::with_state(¤t, query::next_state(¤t));
|
||||
self.run(self.section, wanted)
|
||||
}
|
||||
|
||||
/// Puts the tab on screen back to its configured search.
|
||||
pub(super) fn reset(&mut self) -> GithubKey {
|
||||
let Some(configured) = self.configured.get(self.section).map(|c| c.query.clone()) else {
|
||||
return GithubKey::Held;
|
||||
};
|
||||
self.run(self.section, configured)
|
||||
}
|
||||
|
||||
/// Runs tab `section` with `wanted`, unless that is what it already ran. Whatever was still out
|
||||
/// for the tab is forgotten, so its answer cannot land over this one's.
|
||||
fn run(&mut self, section: usize, wanted: String) -> GithubKey {
|
||||
let Some(search) = self.searches.get_mut(section) else {
|
||||
return GithubKey::Held;
|
||||
};
|
||||
if search.query == wanted {
|
||||
return GithubKey::Held;
|
||||
}
|
||||
search.query = wanted;
|
||||
let search = search.clone();
|
||||
self.pending.retain(|_, pending| pending.section != section);
|
||||
let request = REQUESTS.fetch_add(1, Ordering::Relaxed);
|
||||
self.pending.insert(request, super::Pending { section, page: false });
|
||||
GithubKey::Search { request, section: search, after: None }
|
||||
}
|
||||
|
||||
/// The next page of the tab on screen, once the cursor is on its last row and there is one.
|
||||
pub(super) fn next_page_if_due(&mut self) -> GithubKey {
|
||||
let rows = self.rows().len();
|
||||
if rows == 0 || self.selected + 1 < rows {
|
||||
return GithubKey::Held;
|
||||
}
|
||||
if self.paging(self.section) {
|
||||
return GithubKey::Held;
|
||||
}
|
||||
let next = self
|
||||
.sections
|
||||
.as_ref()
|
||||
.and_then(|sections| sections.get(self.section))
|
||||
.and_then(|section| section.next.clone());
|
||||
let (Some(after), Some(search)) = (next, self.searches.get(self.section).cloned()) else {
|
||||
return GithubKey::Held;
|
||||
};
|
||||
let request = REQUESTS.fetch_add(1, Ordering::Relaxed);
|
||||
self.pending.insert(request, Pending { section: self.section, page: true });
|
||||
GithubKey::Search { request, section: search, after: Some(after) }
|
||||
}
|
||||
|
||||
/// Takes back a search the engine never got, so the tab is not left waiting on it.
|
||||
pub fn unasked(&mut self, request: u64) {
|
||||
self.pending.remove(&request);
|
||||
}
|
||||
|
||||
/// Lands a search's answer in the tab that asked: a new search's rows in place of the old, or a
|
||||
/// page after them. Answers why a page failed, for the reader to be told, since its tab keeps
|
||||
/// the rows it has; an answer to a search since replaced is dropped.
|
||||
pub fn land_search(
|
||||
&mut self,
|
||||
request: u64,
|
||||
repository: Option<String>,
|
||||
found: ListedSection,
|
||||
) -> Option<String> {
|
||||
let pending = self.pending.remove(&request)?;
|
||||
let section = self.sections.as_mut()?.get_mut(pending.section)?;
|
||||
if repository.is_some() {
|
||||
self.repository = repository;
|
||||
}
|
||||
if !pending.page {
|
||||
// The tab keeps its own name, whatever the answer echoes
|
||||
*section = ListedSection { name: std::mem::take(&mut section.name), ..found };
|
||||
if pending.section == self.section {
|
||||
self.selected = 0;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
if let Some(error) = found.error {
|
||||
section.next = None;
|
||||
return Some(error);
|
||||
}
|
||||
for item in found.items {
|
||||
if !section.items.iter().any(|kept| kept.url == item.url) {
|
||||
section.items.push(item);
|
||||
}
|
||||
}
|
||||
section.total = found.total.or(section.total);
|
||||
section.next = found.next;
|
||||
None
|
||||
}
|
||||
}
|
||||
635
crates/luxe-tui/src/github_panel/tests.rs
Normal file
635
crates/luxe-tui/src/github_panel/tests.rs
Normal file
@@ -0,0 +1,635 @@
|
||||
//! `/github`'s keys and layout.
|
||||
|
||||
use super::*;
|
||||
use crate::github_detail::Subject;
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use ratatui::layout::Rect;
|
||||
|
||||
mod collision;
|
||||
|
||||
fn item(pull_request: bool, number: u64, title: &str, repository: &str) -> ListItem {
|
||||
ListItem {
|
||||
pull_request,
|
||||
number,
|
||||
title: title.into(),
|
||||
url: format!("https://github.com/{repository}/pull/{number}"),
|
||||
repository: repository.into(),
|
||||
author: "mara".into(),
|
||||
draft: number == 12,
|
||||
updated_at: String::new(),
|
||||
state: luxe_core::github::PullRequestState::Open,
|
||||
facts: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Two tabs kept to the checkout's repository, and a configured one searching everywhere.
|
||||
fn searches() -> Vec<GithubSection> {
|
||||
let section =
|
||||
|name: &str, query: &str| GithubSection { name: name.into(), query: query.into() };
|
||||
vec![
|
||||
section("Mine", "is:open is:pr author:@me repo:{repo}"),
|
||||
section("Assigned issues", "is:open is:issue assignee:@me repo:{repo}"),
|
||||
section("Review requested", "is:open is:pr review-requested:@me"),
|
||||
]
|
||||
}
|
||||
|
||||
fn panel() -> GithubPanel {
|
||||
let searches = searches();
|
||||
GithubPanel {
|
||||
repository: Some("acme/app".into()),
|
||||
sections: Some(vec![
|
||||
ListedSection {
|
||||
name: "Mine".into(),
|
||||
items: vec![
|
||||
item(true, 12, "Parse categories", "acme/app"),
|
||||
item(true, 13, "Route by category", "upstream/app"),
|
||||
],
|
||||
error: None,
|
||||
total: None,
|
||||
next: None,
|
||||
},
|
||||
ListedSection {
|
||||
name: "Assigned issues".into(),
|
||||
items: vec![
|
||||
item(false, 7, "Total skips a number", "acme/app"),
|
||||
item(false, 8, "Elsewhere", "other/lib"),
|
||||
],
|
||||
error: None,
|
||||
total: None,
|
||||
next: None,
|
||||
},
|
||||
ListedSection {
|
||||
name: "Review requested".into(),
|
||||
items: Vec::new(),
|
||||
error: Some("GitHub refused the search.".into()),
|
||||
total: None,
|
||||
next: None,
|
||||
},
|
||||
]),
|
||||
clock: Some(0),
|
||||
..GithubPanel::with_searches(&searches, searches.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn typed(panel: &mut GithubPanel, text: &str) {
|
||||
for character in text.chars() {
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Char(character))), GithubKey::Held);
|
||||
}
|
||||
}
|
||||
|
||||
fn key(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
fn styles() -> ThemeStyles {
|
||||
let registry = luxe_core::theme::ThemeRegistry::new();
|
||||
let resolved = registry.resolve("dark").expect("dark theme resolves");
|
||||
ThemeStyles::from_resolved(&resolved, "dark")
|
||||
}
|
||||
|
||||
/// Enter reviews a pull request — naming its repository when it is not the checkout's — or
|
||||
/// starts a session on an issue here, and refuses one elsewhere; `c` refers, `o` opens.
|
||||
#[test]
|
||||
fn each_row_leads_to_its_own_action() {
|
||||
let mut panel = panel();
|
||||
assert_eq!(
|
||||
panel.on_key(&key(KeyCode::Enter)),
|
||||
GithubKey::Review { number: 12, repository: None }
|
||||
);
|
||||
let refer = |key: GithubKey| match key {
|
||||
GithubKey::Refer(item) => crate::mentions::github_token(&item),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert_eq!(refer(panel.on_key(&key(KeyCode::Char('c')))), "@[github:acme/app/pull/12]");
|
||||
panel.on_key(&key(KeyCode::Down));
|
||||
assert_eq!(
|
||||
panel.on_key(&key(KeyCode::Enter)),
|
||||
GithubKey::Review { number: 13, repository: Some("upstream/app".into()) }
|
||||
);
|
||||
assert_eq!(refer(panel.on_key(&key(KeyCode::Char('c')))), "@[github:upstream/app/pull/13]");
|
||||
assert_eq!(
|
||||
panel.on_key(&key(KeyCode::Char('o'))),
|
||||
GithubKey::Open("https://github.com/upstream/app/pull/13".into())
|
||||
);
|
||||
panel.on_key(&key(KeyCode::Down));
|
||||
assert_eq!(panel.selected, 1, "the last row stays the last");
|
||||
|
||||
panel.on_key(&key(KeyCode::Tab));
|
||||
assert_eq!((panel.section, panel.selected), (1, 0), "a new section starts at its top");
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Enter)), GithubKey::TakeUpIssue(7));
|
||||
panel.on_key(&key(KeyCode::Down));
|
||||
assert!(
|
||||
matches!(panel.on_key(&key(KeyCode::Enter)), GithubKey::Refused(said) if said.contains("other/lib"))
|
||||
);
|
||||
panel.on_key(&key(KeyCode::Up));
|
||||
panel.on_key(&key(KeyCode::Up));
|
||||
assert_eq!(panel.selected, 0);
|
||||
panel.on_key(&key(KeyCode::Tab));
|
||||
panel.on_key(&key(KeyCode::Tab));
|
||||
assert_eq!(panel.section, 0, "round to the first");
|
||||
panel.on_key(&key(KeyCode::BackTab));
|
||||
assert_eq!(panel.section, 2, "and back to the last");
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Enter)), GithubKey::Held, "no rows, nothing to do");
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Char('r'))), GithubKey::Refresh);
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Esc)), GithubKey::Close);
|
||||
}
|
||||
|
||||
/// `/` opens the tab's search to edit, without the scope it never says. Plain words typed after it
|
||||
/// narrow the loaded rows by title, author or number at once; Esc puts it all back.
|
||||
#[test]
|
||||
fn a_search_being_typed_previews_over_the_loaded_rows() {
|
||||
let mut panel = panel();
|
||||
panel.on_key(&key(KeyCode::Char('/')));
|
||||
let editor = panel.editing.as_ref().expect("editing");
|
||||
assert_eq!(editor.current_input(), "is:open is:pr author:@me ");
|
||||
typed(&mut panel, "route");
|
||||
assert_eq!(panel.rows().iter().map(|row| row.number).collect::<Vec<_>>(), [13]);
|
||||
typed(&mut panel, " label:bug");
|
||||
assert_eq!(panel.rows().len(), 1, "a qualifier waits for GitHub");
|
||||
for code in [KeyCode::Up, KeyCode::Down, KeyCode::Tab, KeyCode::BackTab] {
|
||||
assert_eq!(panel.on_key(&key(code)), GithubKey::Held, "{code:?}: a fresh line ignores it");
|
||||
}
|
||||
assert_eq!(panel.section, 0, "Tab is the search's while it is typed, not the tabs'");
|
||||
typed(&mut panel, "!");
|
||||
assert!(panel.editing.as_ref().unwrap().current_input().ends_with("label:bug!"), "caret kept");
|
||||
panel.on_key(&key(KeyCode::Backspace));
|
||||
for _ in 0.."route label:bug".len() {
|
||||
panel.on_key(&key(KeyCode::Backspace));
|
||||
}
|
||||
typed(&mut panel, "#12");
|
||||
assert_eq!(panel.rows().len(), 1, "by number");
|
||||
panel.on_key(&key(KeyCode::Backspace));
|
||||
panel.on_key(&key(KeyCode::Backspace));
|
||||
panel.on_key(&key(KeyCode::Backspace));
|
||||
typed(&mut panel, "MARA");
|
||||
assert_eq!(panel.rows().len(), 2, "by author, any case");
|
||||
assert_eq!(panel.hint(), "enter search GitHub · esc cancel");
|
||||
panel.on_key(&key(KeyCode::Esc));
|
||||
assert!(panel.editing.is_none());
|
||||
assert_eq!(panel.rows().len(), 2);
|
||||
assert!(panel.pending.is_empty(), "Esc asks nothing of GitHub");
|
||||
}
|
||||
|
||||
/// Enter runs the tab again with what was typed, kept to the checkout's repository however hard
|
||||
/// the reader tries to leave it; the rows go until the answer arrives, and the tab is marked as
|
||||
/// edited. Enter on what it already searched asks nothing, and an emptied search is the way back.
|
||||
#[test]
|
||||
fn enter_runs_the_tab_again_with_what_was_typed() {
|
||||
let mut panel = panel();
|
||||
panel.on_key(&key(KeyCode::Char('/')));
|
||||
typed(&mut panel, "label:bug repo:other/lib");
|
||||
let GithubKey::Search { request, section, after } = panel.on_key(&key(KeyCode::Enter)) else {
|
||||
panic!("expected a search");
|
||||
};
|
||||
assert_eq!(section.query, "is:open is:pr author:@me label:bug repo:{repo}");
|
||||
assert_eq!((section.name.as_str(), after), ("Mine", None));
|
||||
assert!(panel.editing.is_none() && panel.researching(0) && panel.rows().is_empty());
|
||||
assert!(panel.edited(0) && !panel.edited(1));
|
||||
assert!(panel.hint().contains("x reset"), "{}", panel.hint());
|
||||
|
||||
panel.on_key(&key(KeyCode::Char('/')));
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Enter)), GithubKey::Held, "the same search again");
|
||||
assert!(panel.pending.contains_key(&request), "and the one out is still awaited");
|
||||
|
||||
panel.on_key(&key(KeyCode::Char('/')));
|
||||
for _ in 0..80 {
|
||||
panel.on_key(&key(KeyCode::Backspace));
|
||||
}
|
||||
let GithubKey::Search { request: again, section, .. } = panel.on_key(&key(KeyCode::Enter))
|
||||
else {
|
||||
panic!("expected the configured search back");
|
||||
};
|
||||
assert_eq!(section.query, "is:open is:pr author:@me repo:{repo}");
|
||||
assert!(!panel.edited(0));
|
||||
assert!(!panel.pending.contains_key(&request), "the replaced search is forgotten");
|
||||
assert!(panel.pending.contains_key(&again));
|
||||
}
|
||||
|
||||
/// A configured tab that searches everywhere is run as typed: its scope is the reader's.
|
||||
#[test]
|
||||
fn a_tab_searching_everywhere_runs_as_typed() {
|
||||
let mut panel = panel();
|
||||
panel.section = 2;
|
||||
panel.on_key(&key(KeyCode::Char('/')));
|
||||
typed(&mut panel, "repo:cli/cli");
|
||||
let GithubKey::Search { section, .. } = panel.on_key(&key(KeyCode::Enter)) else {
|
||||
panic!("expected a search");
|
||||
};
|
||||
assert_eq!(section.query, "is:open is:pr review-requested:@me repo:cli/cli");
|
||||
}
|
||||
|
||||
/// `s` steps the tab through its states, an issues tab skipping merged, and `x` puts the configured
|
||||
/// search back; neither does anything with no sections to act on.
|
||||
#[test]
|
||||
fn s_steps_the_state_and_x_resets_it() {
|
||||
let mut panel = panel();
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Char('x'))), GithubKey::Held, "nothing to reset");
|
||||
let query = |key: GithubKey| match key {
|
||||
GithubKey::Search { section, .. } => section.query,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
panel.section = 1;
|
||||
assert_eq!(
|
||||
query(panel.on_key(&key(KeyCode::Char('s')))),
|
||||
"is:closed is:issue assignee:@me repo:{repo}"
|
||||
);
|
||||
assert_eq!(query(panel.on_key(&key(KeyCode::Char('s')))), "is:issue assignee:@me repo:{repo}");
|
||||
assert_eq!(
|
||||
query(panel.on_key(&key(KeyCode::Char('x')))),
|
||||
"is:open is:issue assignee:@me repo:{repo}"
|
||||
);
|
||||
assert_eq!(panel.pending.len(), 1, "one search out for the tab, the latest");
|
||||
|
||||
let mut loading = GithubPanel::new(&searches());
|
||||
assert_eq!(loading.on_key(&key(KeyCode::Char('s'))), GithubKey::Held);
|
||||
assert_eq!(loading.on_key(&key(KeyCode::Char('/'))), GithubKey::Held);
|
||||
assert!(loading.editing.is_none());
|
||||
}
|
||||
|
||||
/// The cursor reaching the last row asks for the next page, once; the page lands after the rows it
|
||||
/// follows without repeating one, and the last page leaves nothing more to ask for. A page that
|
||||
/// fails keeps the rows and says why.
|
||||
#[test]
|
||||
fn the_last_row_brings_the_next_page() {
|
||||
let mut panel = panel();
|
||||
let mine = &mut panel.sections.as_mut().unwrap()[0];
|
||||
mine.total = Some(3);
|
||||
mine.next = Some("c1".into());
|
||||
let GithubKey::Search { request, after, .. } = panel.on_key(&key(KeyCode::End)) else {
|
||||
panic!("expected the next page");
|
||||
};
|
||||
assert_eq!(after.as_deref(), Some("c1"));
|
||||
assert!(panel.paging(0) && !panel.researching(0));
|
||||
assert_eq!(panel.rows().len(), 2, "the rows stay while the page is out");
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Down)), GithubKey::Held, "asked once");
|
||||
let page = ListedSection {
|
||||
name: "ignored".into(),
|
||||
items: vec![
|
||||
item(true, 13, "Route by category", "upstream/app"),
|
||||
item(true, 14, "New", "acme/app"),
|
||||
],
|
||||
error: None,
|
||||
total: Some(3),
|
||||
next: None,
|
||||
};
|
||||
assert_eq!(panel.land_search(request, None, page.clone()), None);
|
||||
let numbers: Vec<u64> = panel.rows().iter().map(|row| row.number).collect();
|
||||
assert_eq!(numbers, [12, 13, 14]);
|
||||
assert_eq!(panel.sections.as_ref().unwrap()[0].name, "Mine");
|
||||
assert_eq!(panel.on_key(&key(KeyCode::End)), GithubKey::Held, "nothing more to ask for");
|
||||
assert_eq!(panel.land_search(request, None, page), None, "an answer lands once");
|
||||
|
||||
// Only the last row asks, and a page out for another tab is not this one's
|
||||
let mut longer = self::panel();
|
||||
let assigned = &mut longer.sections.as_mut().unwrap()[1];
|
||||
assigned.next = Some("other".into());
|
||||
longer.section = 1;
|
||||
let GithubKey::Search { .. } = longer.on_key(&key(KeyCode::End)) else {
|
||||
panic!("expected the other tab's page");
|
||||
};
|
||||
longer.section = 0;
|
||||
longer.selected = 0;
|
||||
let mine = &mut longer.sections.as_mut().unwrap()[0];
|
||||
mine.items.push(item(true, 15, "Third", "acme/app"));
|
||||
mine.next = Some("c1".into());
|
||||
assert_eq!(longer.on_key(&key(KeyCode::Down)), GithubKey::Held, "not the last row yet");
|
||||
assert!(!longer.paging(0));
|
||||
assert!(matches!(longer.on_key(&key(KeyCode::Down)), GithubKey::Search { .. }));
|
||||
|
||||
let mut failing = self::panel();
|
||||
failing.sections.as_mut().unwrap()[0].next = Some("c1".into());
|
||||
let GithubKey::Search { request, .. } = failing.on_key(&key(KeyCode::End)) else {
|
||||
panic!("expected the next page");
|
||||
};
|
||||
let refused = ListedSection {
|
||||
name: "Mine".into(),
|
||||
items: Vec::new(),
|
||||
error: Some("GitHub is rate limiting.".into()),
|
||||
total: None,
|
||||
next: None,
|
||||
};
|
||||
assert_eq!(
|
||||
failing.land_search(request, None, refused).as_deref(),
|
||||
Some("GitHub is rate limiting.")
|
||||
);
|
||||
assert_eq!(failing.rows().len(), 2);
|
||||
assert_eq!(failing.on_key(&key(KeyCode::Down)), GithubKey::Held, "and it stops asking");
|
||||
}
|
||||
|
||||
/// A new search's rows replace the tab's, and the cursor goes back to the top of them.
|
||||
#[test]
|
||||
fn a_new_search_replaces_the_rows() {
|
||||
let mut panel = panel();
|
||||
panel.on_key(&key(KeyCode::Down));
|
||||
let GithubKey::Search { request, .. } = panel.on_key(&key(KeyCode::Char('s'))) else {
|
||||
panic!("expected a search");
|
||||
};
|
||||
let found = ListedSection {
|
||||
name: "whatever the answer echoes".into(),
|
||||
items: vec![item(true, 40, "Closed one", "acme/app")],
|
||||
error: None,
|
||||
total: Some(1),
|
||||
next: None,
|
||||
};
|
||||
assert_eq!(panel.land_search(request, Some("acme/app".into()), found), None);
|
||||
assert_eq!((panel.selected, panel.rows().len()), (0, 1));
|
||||
assert_eq!(panel.sections.as_ref().unwrap()[0].name, "Mine", "the tab keeps its name");
|
||||
assert!(!panel.searching());
|
||||
}
|
||||
|
||||
/// A search the engine never got is taken back, so its tab is not left waiting on it.
|
||||
#[test]
|
||||
fn a_search_never_sent_leaves_nothing_waiting() {
|
||||
let mut panel = panel();
|
||||
let GithubKey::Search { request, .. } = panel.on_key(&key(KeyCode::Char('s'))) else {
|
||||
panic!("expected a search");
|
||||
};
|
||||
assert!(panel.researching(0));
|
||||
panel.unasked(request);
|
||||
assert!(!panel.researching(0) && !panel.searching());
|
||||
}
|
||||
|
||||
/// Nothing to move among is no reason to fall over: arrows on a loading panel, or an empty
|
||||
/// section, do nothing; and a control key typed into the search is not a letter.
|
||||
#[test]
|
||||
fn keys_with_nothing_to_move_among_do_nothing() {
|
||||
let mut loading = GithubPanel::default();
|
||||
for code in [
|
||||
KeyCode::Right,
|
||||
KeyCode::Left,
|
||||
KeyCode::Tab,
|
||||
KeyCode::Down,
|
||||
KeyCode::Up,
|
||||
KeyCode::End,
|
||||
KeyCode::PageDown,
|
||||
KeyCode::Char('s'),
|
||||
KeyCode::Char('/'),
|
||||
] {
|
||||
assert_eq!(loading.on_key(&key(code)), GithubKey::Held, "{code:?}");
|
||||
}
|
||||
assert_eq!((loading.section, loading.selected, loading.focus), (0, 0, Focus::List));
|
||||
let mut empty = panel();
|
||||
empty.section = 2;
|
||||
empty.on_key(&key(KeyCode::Down));
|
||||
assert_eq!(empty.selected, 0);
|
||||
|
||||
let mut searching = panel();
|
||||
searching.on_key(&key(KeyCode::Char('/')));
|
||||
for modifiers in [KeyModifiers::CONTROL, KeyModifiers::ALT] {
|
||||
searching.on_key(&KeyEvent::new(KeyCode::Char('q'), modifiers));
|
||||
}
|
||||
searching.on_key(&KeyEvent::new(KeyCode::Char('R'), KeyModifiers::SHIFT));
|
||||
let typed = searching.editing.as_ref().unwrap().current_input();
|
||||
assert!(typed.ends_with("@me R"), "a capital is a letter; a chord is not: {typed}");
|
||||
}
|
||||
|
||||
/// PageDown and PageUp move ten rows at a time, Home and End to either end.
|
||||
#[test]
|
||||
fn page_keys_move_by_ten() {
|
||||
let mut panel = panel();
|
||||
let mine = &mut panel.sections.as_mut().unwrap()[0];
|
||||
mine.items = (1..=25).map(|number| item(true, number, "Row", "acme/app")).collect();
|
||||
panel.on_key(&key(KeyCode::PageDown));
|
||||
assert_eq!(panel.selected, 10);
|
||||
panel.on_key(&key(KeyCode::PageUp));
|
||||
assert_eq!(panel.selected, 0);
|
||||
panel.on_key(&key(KeyCode::End));
|
||||
assert_eq!(panel.selected, 24);
|
||||
panel.on_key(&key(KeyCode::PageDown));
|
||||
assert_eq!(panel.selected, 24, "the last row stays the last");
|
||||
panel.on_key(&key(KeyCode::Home));
|
||||
assert_eq!(panel.selected, 0);
|
||||
}
|
||||
|
||||
/// `→` hands the keys to the detail of the row under the cursor, once it is read; `←` hands
|
||||
/// them back, and the hint follows the keys.
|
||||
#[test]
|
||||
fn the_keys_move_between_the_list_and_the_detail() {
|
||||
let mut panel = panel();
|
||||
panel.on_key(&key(KeyCode::Right));
|
||||
assert_eq!(panel.focus, Focus::List, "nothing read yet, nothing to move to");
|
||||
assert!(!panel.hint().contains("→ details"));
|
||||
|
||||
let overview = luxe_core::github::overview::IssueOverview {
|
||||
number: 12,
|
||||
title: "Parse categories".into(),
|
||||
body: String::new(),
|
||||
url: "https://github.com/acme/app/pull/12".into(),
|
||||
repository: "acme/app".into(),
|
||||
author: luxe_core::github::Author { login: "mara".into(), bot: false },
|
||||
state: luxe_core::github::PullRequestState::Open,
|
||||
updated_at: 0,
|
||||
labels: Vec::new(),
|
||||
assignees: Vec::new(),
|
||||
milestone: None,
|
||||
linked: Vec::new(),
|
||||
conversation_count: 0,
|
||||
};
|
||||
panel
|
||||
.details
|
||||
.insert(overview.url.clone(), GithubDetail::new(Subject::Issue(Box::new(overview))));
|
||||
assert!(panel.hint().starts_with("enter review · → details"));
|
||||
panel.on_key(&key(KeyCode::Right));
|
||||
assert_eq!(panel.focus, Focus::Detail);
|
||||
assert!(panel.hint().contains("tab conversation"), "{}", panel.hint());
|
||||
panel.on_key(&key(KeyCode::Tab));
|
||||
assert_eq!(
|
||||
panel.detail().map(|detail| detail.tab),
|
||||
Some(crate::github_detail::DetailTab::Conversation),
|
||||
"Tab is the detail's now, not the sections'"
|
||||
);
|
||||
assert_eq!(panel.section, 0);
|
||||
panel.on_key(&key(KeyCode::Esc));
|
||||
assert_eq!(panel.focus, Focus::List, "Esc leaves the detail before it closes anything");
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Esc)), GithubKey::Close);
|
||||
}
|
||||
|
||||
fn drawn(panel: &GithubPanel, width: u16, height: u16) -> Vec<String> {
|
||||
let backend = ratatui::backend::TestBackend::new(width, height);
|
||||
let mut terminal = ratatui::Terminal::new(backend).unwrap();
|
||||
terminal.draw(|f| render(f, Rect::new(0, 0, width, height), panel, &styles(), 0)).unwrap();
|
||||
let buffer = terminal.backend().buffer().clone();
|
||||
(0..height).map(|y| (0..width).map(|x| buffer[(x, y)].symbol().to_string()).collect()).collect()
|
||||
}
|
||||
|
||||
/// Each row takes two lines — the title, then who opened it — and the tabs count each section.
|
||||
/// Too narrow for the counts, the tabs drop them; too narrow for the names, they show a run around
|
||||
/// the open one and say more are aside.
|
||||
#[test]
|
||||
fn the_list_puts_each_row_on_two_lines() {
|
||||
let narrow = drawn(&panel(), 64, 24);
|
||||
let tabs = narrow.iter().position(|row| row.contains("Mine")).expect("tabs");
|
||||
assert!(
|
||||
narrow[tabs].contains("Review requested") && !narrow[tabs].contains("Mine 2"),
|
||||
"names before counts: {:?}",
|
||||
narrow[tabs]
|
||||
);
|
||||
let mut aside = panel();
|
||||
aside.section = 2;
|
||||
let tight = drawn(&aside, 44, 24);
|
||||
let tabs = tight.iter().position(|row| row.contains("Review requested")).expect("tabs");
|
||||
assert!(tight[tabs].contains('‹') && !tight[tabs].contains("Mine"), "{:?}", tight[tabs]);
|
||||
|
||||
let rows = drawn(&panel(), 120, 24);
|
||||
let tabs = rows.iter().position(|row| row.contains("Mine 2")).expect("tabs");
|
||||
assert!(rows[tabs].contains("Assigned issues 2") && rows[tabs].contains("Review requested 0"));
|
||||
let title = rows.iter().position(|row| row.contains("#12 Parse categories")).expect("row");
|
||||
assert!(rows[title + 1].contains("mara"), "{rows:#?}");
|
||||
let elsewhere = rows.iter().position(|row| row.contains("#13 Route")).expect("second");
|
||||
assert!(rows[elsewhere + 1].contains("upstream/app"), "a row elsewhere names where");
|
||||
assert!(rows.iter().any(|row| row.contains("enter review")), "{rows:#?}");
|
||||
assert!(rows.iter().any(|row| row.contains("1/2")), "where the cursor is");
|
||||
assert!(
|
||||
rows.iter().any(|row| row.contains("GitHub · acme/app")),
|
||||
"the repository, in the title"
|
||||
);
|
||||
}
|
||||
|
||||
/// The line over the rows says what the tab searched for, without its scope, and how many of how
|
||||
/// many; an empty tab says nothing matched rather than that there are no items, and a search with
|
||||
/// more says so under the last row.
|
||||
#[test]
|
||||
fn the_tab_says_what_it_searched_for() {
|
||||
let mut panel = panel();
|
||||
let mine = &mut panel.sections.as_mut().unwrap()[0];
|
||||
mine.total = Some(3_250);
|
||||
mine.next = Some("c1".into());
|
||||
let rows = drawn(&panel, 120, 30);
|
||||
let line = rows.iter().find(|row| row.contains("/ is:open")).expect("the search");
|
||||
assert!(line.contains("/ is:open is:pr author:@me") && !line.contains("repo:"), "{line}");
|
||||
assert!(line.contains("2 of 3,250"), "{line}");
|
||||
assert!(rows.iter().any(|row| row.contains("Mine 3,250")), "the tab counts them all");
|
||||
assert!(rows.iter().any(|row| row.contains("3,248 more below")), "{rows:#?}");
|
||||
|
||||
panel.sections.as_mut().unwrap()[1].items.clear();
|
||||
panel.section = 1;
|
||||
let rows = drawn(&panel, 120, 30);
|
||||
assert!(rows.iter().any(|row| row.contains("Nothing matches this search")), "{rows:#?}");
|
||||
assert!(!rows.iter().any(|row| row.contains("No items")));
|
||||
|
||||
panel.section = 0;
|
||||
let GithubKey::Search { .. } = panel.on_key(&key(KeyCode::Char('s'))) else {
|
||||
panic!("expected a search");
|
||||
};
|
||||
let rows = drawn(&panel, 120, 30);
|
||||
assert!(rows.iter().any(|row| row.contains("Searching GitHub")), "{rows:#?}");
|
||||
assert!(rows.iter().any(|row| row.contains("Mine* ")), "an edited tab is marked");
|
||||
}
|
||||
|
||||
/// The row the cursor rests on is read once, a quarter second after it arrives: passing through a
|
||||
/// row reads nothing, and a row elsewhere is asked for on its own repository.
|
||||
#[test]
|
||||
fn a_row_is_read_once_the_cursor_settles_on_it() {
|
||||
let mut panel = panel();
|
||||
let start = std::time::Instant::now();
|
||||
let later = |ms| start + std::time::Duration::from_millis(ms);
|
||||
assert_eq!(panel.due_read(start), None, "it has only just arrived");
|
||||
assert!(panel.reading());
|
||||
assert_eq!(panel.due_read(later(100)), None, "not settled yet");
|
||||
assert_eq!(
|
||||
panel.due_read(later(300)),
|
||||
Some(OverviewRead { repository: None, number: 12, pull_request: true })
|
||||
);
|
||||
assert_eq!(panel.due_read(later(900)), None, "asked once");
|
||||
|
||||
panel.on_key(&key(KeyCode::Down));
|
||||
assert_eq!(panel.due_read(later(1_000)), None, "a new row starts the clock again");
|
||||
assert_eq!(
|
||||
panel.due_read(later(1_300)),
|
||||
Some(OverviewRead {
|
||||
repository: Some("upstream/app".into()),
|
||||
number: 13,
|
||||
pull_request: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// An answer lands in the detail of the row it answers: the branch's own pull request can have its
|
||||
/// threads worked through here, another cannot, and a failure is kept to say why.
|
||||
#[test]
|
||||
fn an_answer_lands_in_its_own_row() {
|
||||
use luxe_core::github::overview::Overview;
|
||||
let mut panel = panel();
|
||||
let overview = |number| {
|
||||
Overview::PullRequest(Box::new(luxe_core::github::overview::PullRequestOverview {
|
||||
number,
|
||||
..crate::fixture::pull_request_overview()
|
||||
}))
|
||||
};
|
||||
panel.land(None, 12, Some(overview(12)), None, None, Some(12));
|
||||
let mine = panel.details.get("https://github.com/acme/app/pull/12").expect("landed");
|
||||
assert!(mine.on_branch);
|
||||
assert!(!panel.reading());
|
||||
|
||||
panel.land(Some("upstream/app"), 13, Some(overview(13)), None, None, Some(13));
|
||||
let theirs = panel.details.get("https://github.com/upstream/app/pull/13").expect("landed");
|
||||
assert!(!theirs.on_branch, "a fork's pull request is not the branch checked out here");
|
||||
|
||||
panel.land(Some("nobody/else"), 99, Some(overview(99)), None, None, None);
|
||||
assert_eq!(panel.details.len(), 2, "an answer for no row is dropped");
|
||||
|
||||
panel.section = 1;
|
||||
panel.land(None, 7, None, Some("GitHub has no such issue.".into()), None, None);
|
||||
assert!(!panel.reading(), "a failure is an answer");
|
||||
let drawn = drawn(&panel, 150, 30);
|
||||
assert!(drawn.iter().any(|row| row.contains("GitHub has no such issue.")), "{drawn:#?}");
|
||||
}
|
||||
|
||||
/// Enter on an issue one of your sessions took up resumes that session rather than starting a
|
||||
/// second; without one, it starts a session on the issue as before.
|
||||
#[test]
|
||||
fn enter_on_an_issue_you_took_up_resumes_your_session() {
|
||||
use luxe_core::github::overview::{IssueOverview, LocalSession, Overview};
|
||||
let mut panel = panel();
|
||||
panel.section = 1;
|
||||
let issue = IssueOverview {
|
||||
number: 7,
|
||||
title: "Total skips a number".into(),
|
||||
body: String::new(),
|
||||
url: "https://github.com/acme/app/pull/7".into(),
|
||||
repository: "acme/app".into(),
|
||||
author: luxe_core::github::Author { login: "mara".into(), bot: false },
|
||||
state: luxe_core::github::PullRequestState::Open,
|
||||
updated_at: 0,
|
||||
labels: Vec::new(),
|
||||
assignees: Vec::new(),
|
||||
milestone: None,
|
||||
linked: Vec::new(),
|
||||
conversation_count: 1,
|
||||
};
|
||||
let local =
|
||||
LocalSession { session: "s-7".into(), branch: Some("7-total".into()), last_used: 0 };
|
||||
panel.land(None, 7, Some(Overview::Issue(Box::new(issue))), None, Some(local), None);
|
||||
assert!(panel.hint().starts_with("enter resume"));
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Enter)), GithubKey::Resume("s-7".into()));
|
||||
panel.details.clear();
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Enter)), GithubKey::TakeUpIssue(7));
|
||||
}
|
||||
|
||||
/// A row's diff counts are shown whole or not at all: cut to fit, `+96 −31` came out `+…`. The
|
||||
/// status on the right, the part that says what to do, keeps its place either way.
|
||||
#[test]
|
||||
fn a_row_drops_its_counts_rather_than_cutting_them() {
|
||||
let rows_at = |width: u16| {
|
||||
let mut app = crate::fixture::seeded_app("nord", crate::fixture::FixtureScenario::ChatIdle)
|
||||
.expect("fixture app");
|
||||
crate::fixture::seed_github(&mut app, "github");
|
||||
let backend = ratatui::backend::TestBackend::new(width, 34);
|
||||
let mut terminal = ratatui::Terminal::new(backend).expect("terminal");
|
||||
app.update(crate::app::Msg::TerminalResized { width, height: 34 });
|
||||
terminal.draw(|frame| crate::view::render(frame, &mut app)).expect("draw");
|
||||
let buffer = terminal.backend().buffer().clone();
|
||||
(0..34)
|
||||
.map(|y| (0..width).map(|x| buffer[(x, y)].symbol().to_string()).collect::<String>())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for width in [140, 220] {
|
||||
let rows = rows_at(width);
|
||||
let line = rows.iter().find(|row| row.contains("1 failing")).expect("the row's status");
|
||||
assert!(!line.contains("+…"), "{line}");
|
||||
assert!(line.contains("changes requested"), "{line}");
|
||||
}
|
||||
let wide = rows_at(220);
|
||||
assert!(wide.iter().any(|row| row.contains("+96 −31")), "with room, the counts are there");
|
||||
}
|
||||
157
crates/luxe-tui/src/github_panel/tests/collision.rs
Normal file
157
crates/luxe-tui/src/github_panel/tests/collision.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
//! Two repositories' pull requests with one number: a detail acts on the one it shows.
|
||||
|
||||
use super::*;
|
||||
use luxe_core::github::overview::{
|
||||
ConversationEntry, MergeStatus, PullRequestOverview, Reviewer, ReviewerKind, Verdict, Viewer,
|
||||
};
|
||||
use luxe_core::github::{CheckRollup, ConversationComment, ReviewDecision};
|
||||
|
||||
/// `acme/app#142` (the checkout's) above `upstream/app#142`, both read.
|
||||
fn colliding(draft: bool) -> GithubPanel {
|
||||
let rows = vec![item(true, 142, "Ours", "acme/app"), item(true, 142, "Theirs", "upstream/app")];
|
||||
let mut panel = GithubPanel {
|
||||
repository: Some("acme/app".into()),
|
||||
sections: Some(vec![ListedSection {
|
||||
name: "Mine".into(),
|
||||
items: rows.clone(),
|
||||
error: None,
|
||||
total: None,
|
||||
next: None,
|
||||
}]),
|
||||
clock: Some(0),
|
||||
..GithubPanel::with_searches(&searches(), searches())
|
||||
};
|
||||
for row in &rows {
|
||||
let overview = PullRequestOverview {
|
||||
number: 142,
|
||||
url: row.url.clone(),
|
||||
repository: row.repository.clone(),
|
||||
draft,
|
||||
merge_status: MergeStatus::Clean,
|
||||
review_decision: Some(ReviewDecision::Approved),
|
||||
reviewers: vec![Reviewer {
|
||||
login: "jon".into(),
|
||||
kind: ReviewerKind::User,
|
||||
verdict: Verdict::Approved,
|
||||
at: Some(0),
|
||||
}],
|
||||
checks: CheckRollup { passed: 3, ..CheckRollup::default() },
|
||||
failing: Vec::new(),
|
||||
unresolved_threads: 0,
|
||||
viewer: Viewer { author: true, can_push: true, can_merge: true },
|
||||
..crate::fixture::pull_request_overview()
|
||||
};
|
||||
let mut detail = GithubDetail::new(Subject::PullRequest(Box::new(overview)));
|
||||
detail.conversation = Some(vec![ConversationEntry::Comment(ConversationComment {
|
||||
id: "c1".into(),
|
||||
author: "jon".into(),
|
||||
bot: false,
|
||||
mine: false,
|
||||
body: "Why this way?".into(),
|
||||
created_at: "1970-01-01T00:16:40Z".into(),
|
||||
url: String::new(),
|
||||
})]);
|
||||
panel.details.insert(row.url.clone(), detail);
|
||||
}
|
||||
panel
|
||||
}
|
||||
|
||||
/// The panel with row `index` selected and its detail focused.
|
||||
fn on_row(draft: bool, index: usize) -> GithubPanel {
|
||||
let mut panel = colliding(draft);
|
||||
panel.selected = index;
|
||||
panel.focus = Focus::Detail;
|
||||
panel
|
||||
}
|
||||
|
||||
/// Every write and read a detail sends names the repository of the row it shows, in both
|
||||
/// directions, whichever row with that number came first.
|
||||
#[test]
|
||||
fn detail_actions_keep_the_selected_repository_when_numbers_collide() {
|
||||
for (index, repository) in [(0, None), (1, Some("upstream/app".to_string()))] {
|
||||
let mut merging = on_row(false, index);
|
||||
assert_eq!(merging.on_key(&key(KeyCode::Enter)), GithubKey::Held, "opens the confirmation");
|
||||
match merging.on_key(&key(KeyCode::Enter)) {
|
||||
GithubKey::Merge { repository: chosen, number: 142, .. } => {
|
||||
assert_eq!(chosen, repository, "merge")
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
|
||||
let mut acting = on_row(true, index);
|
||||
match acting.on_key(&key(KeyCode::Enter)) {
|
||||
GithubKey::Act { repository: chosen, .. } => assert_eq!(chosen, repository, "act"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
|
||||
let mut reading = on_row(false, index);
|
||||
match reading.on_key(&key(KeyCode::Tab)) {
|
||||
GithubKey::ReadConversation { repository: chosen, number: 142, .. } => {
|
||||
assert_eq!(chosen, repository, "conversation")
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
match reading.on_key(&key(KeyCode::Char('d'))) {
|
||||
GithubKey::Draft { repository: chosen, number: 142, .. } => {
|
||||
assert_eq!(chosen, repository, "draft")
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
|
||||
let mut posting = on_row(false, index);
|
||||
posting.on_key(&key(KeyCode::Tab));
|
||||
posting.on_key(&key(KeyCode::Char('r')));
|
||||
typed(&mut posting, "Because.");
|
||||
posting.on_key(&KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL));
|
||||
match posting.on_key(&key(KeyCode::Enter)) {
|
||||
GithubKey::Post(post) => assert_eq!(post.repository, repository, "post"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enter on a merge row in `/github` shows the confirmation, with its method and branch choice,
|
||||
/// before any write: at full width and in the narrow single pane. Esc backs out; Enter again sends
|
||||
/// the write as shown. The same for turning on auto-merge.
|
||||
#[test]
|
||||
fn github_panel_draws_merge_confirmation_before_emitting_write() {
|
||||
for (width, auto) in [(180, false), (90, false), (180, true), (90, true)] {
|
||||
let mut panel = on_row(false, 0);
|
||||
if auto {
|
||||
for detail in panel.details.values_mut() {
|
||||
if let Subject::PullRequest(pr) = &mut detail.subject {
|
||||
pr.merge_settings.can_auto_merge = true;
|
||||
pr.merge_status = MergeStatus::Blocked;
|
||||
}
|
||||
}
|
||||
}
|
||||
let title = if auto { "Enable auto-merge" } else { "Merge pull request" };
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Enter)), GithubKey::Held, "no write yet");
|
||||
let screen = drawn(&panel, width, 40).join("\n");
|
||||
assert!(screen.contains(title) && screen.contains("Method"), "{width}: {screen}");
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Esc)), GithubKey::Held);
|
||||
assert!(!drawn(&panel, width, 40).join("\n").contains(title), "Esc backed out");
|
||||
panel.on_key(&key(KeyCode::Enter));
|
||||
let write = match panel.on_key(&key(KeyCode::Enter)) {
|
||||
GithubKey::Merge { write, .. } => write,
|
||||
other => panic!("{width} {auto}: {other:?}"),
|
||||
};
|
||||
use luxe_core::engine::PullRequestWrite;
|
||||
assert_eq!(matches!(write, PullRequestWrite::EnableAutoMerge { .. }), auto, "{write:?}");
|
||||
assert_eq!(matches!(write, PullRequestWrite::Merge(_)), !auto, "{write:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A detail that is not the pull request of the row it hangs off takes no key: nothing is sent,
|
||||
/// and nothing in it changes, rather than a confirmation sent and then dropped.
|
||||
#[test]
|
||||
fn a_detail_that_disagrees_with_its_row_takes_no_key() {
|
||||
let mut panel = on_row(false, 0);
|
||||
let url = panel.rows()[0].url.clone();
|
||||
if let Some(Subject::PullRequest(pr)) = panel.details.get_mut(&url).map(|d| &mut d.subject) {
|
||||
pr.number = 999;
|
||||
}
|
||||
assert_eq!(panel.on_key(&key(KeyCode::Enter)), GithubKey::Held);
|
||||
assert!(panel.details[&url].merging.is_none(), "the detail did not act");
|
||||
assert_eq!(panel.focus, Focus::List);
|
||||
}
|
||||
Reference in New Issue
Block a user