use jj_compose_core::{Field, HEADER_HARD_LIMIT, HEADER_SOFT_LIMIT, Split, overview};
use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style, Stylize},
text::{Line, Span},
widgets::{Block, Paragraph},
};
use ratatui_textarea::{CursorMove, TextArea, WrapMode};
use super::{App, Focus, Keymap, Status, View, plural};
use crate::{diff::Mark, vim};
const SIDE_BY_SIDE_MIN_WIDTH: u16 = 100;
impl App {
pub(super) fn draw(&mut self, frame: &mut Frame<'_>) {
let [main, status] =
Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(frame.area());
self.zoomed &= self.focus == Focus::Diff;
self.is_vertical = main.width < SIDE_BY_SIDE_MIN_WIDTH;
let [diff_area, form_area] = if self.zoomed {
[main, Rect::default()]
} else if !self.is_vertical {
Layout::horizontal([Constraint::Percentage(50); 2]).areas(main)
} else {
Layout::vertical([Constraint::Percentage(40), Constraint::Fill(1)]).areas(main)
};
let accent = self.accent();
if self.overview.is_some() && self.choosing() {
self.draw_overview(frame, diff_area, status, accent);
return;
}
if self.choosing() {
if self.split.as_ref().is_some_and(Split::is_divided) {
self.draw_divided(frame, diff_area, status);
} else {
self.draw_hunk(frame, diff_area, status, accent);
}
return;
}
let mut title = vec![
Span::raw(format!(" Diff {} ", self.change_id)),
immutable_marker(self.target.immutable),
];
title.retain(|span| !span.content.is_empty());
if let Some((n, file)) = self.diff.current_file() {
let count = self.diff.file_count();
title.push(Span::raw(format!("· {n}/{count} {} ", file.path)));
title.push(Span::styled(format!("+{} ", file.added), Color::Green));
title.push(Span::styled(format!("-{} ", file.removed), Color::Red));
}
if let Some((query, n, count)) = self.diff.search_status() {
title.push(Span::raw(format!("· /{query} {n}/{count} ")));
}
let block = pane(
Line::from(title),
(self.focus == Focus::Diff).then_some(accent),
);
self.diff.render(frame, diff_area, block);
if !self.zoomed {
match self.view {
View::Structured => self.draw_form(frame, form_area),
View::Raw => self.draw_raw(frame, form_area),
}
}
frame.render_widget(self.status_line(), status);
}
fn draw_overview(&self, frame: &mut Frame<'_>, area: Rect, status: Rect, accent: Color) {
let Some(cursor) = self.overview else {
return;
};
let rows = self.overview_rows();
let assigned = self.split.as_ref().map_or(0, Split::assigned);
let hunks = rows.iter().filter(|r| r.hunk.is_some()).count();
let boxes = self.split.as_ref().map_or_else(Vec::new, Split::pending);
let mut title = Line::from(vec![
Span::raw(format!(" Hunks in {} ", self.change_id)),
immutable_marker(self.target.immutable),
Span::styled(format!("· {assigned} of {hunks} assigned "), Color::Green),
]);
for span in legend(&boxes) {
title.push_span(span);
}
let selected = self.visual.map(|from| {
let to = self.split.as_ref().map_or(from, Split::at);
from.min(to)..=from.max(to)
});
if let Some(range) = &selected {
let n = range.end() - range.start() + 1;
title.spans.push(Span::styled(
format!("· VISUAL {n} selected "),
Style::new().fg(Color::Magenta).add_modifier(Modifier::BOLD),
));
}
let mut hunk_of = Vec::with_capacity(rows.len());
let mut next = 0;
for row in &rows {
hunk_of.push(row.hunk.map(|_| {
next += 1;
next - 1
}));
}
let block = pane(title, Some(accent));
let inner = block.inner(area);
frame.render_widget(block, area);
let height = usize::from(inner.height).max(1);
let top = cursor
.saturating_sub(height / 2)
.min(rows.len().saturating_sub(height));
let lines: Vec<Line<'static>> = rows
.iter()
.enumerate()
.skip(top)
.take(height)
.map(|(i, row)| {
let in_selection = selected
.as_ref()
.zip(hunk_of[i])
.is_some_and(|(range, k)| range.contains(&k));
overview_line(row, i == cursor, in_selection)
})
.collect();
frame.render_widget(Paragraph::new(lines), inner);
frame.render_widget(self.status_line(), status);
}
fn draw_divided(&mut self, frame: &mut Frame<'_>, area: Rect, status: Rect) {
let Some(split) = self.split.as_ref() else {
return;
};
let (at, total, path) = (split.at(), split.total(), split.path().to_owned());
let plan = split.line_plan().unwrap_or_default().to_vec();
let cursor = split.line_at();
let selection = self.visual_line.map(|from| (from, cursor));
let Some(rows) = self.divided_rows(at, &plan, cursor, selection) else {
return;
};
let taken = plan.iter().flatten().count();
let mut title = vec![
Span::raw(format!(" Divide {} ", self.change_id)),
immutable_marker(self.target.immutable),
Span::raw(format!("· hunk {}/{total} ", at + 1)),
Span::raw(format!("· {path} · ")),
];
for (i, slot) in plan.iter().enumerate() {
let (text, color) = match slot {
Some(n) if *n < 10 => (char::from(b'0' + n).to_string(), box_color(*n)),
Some(_) => ("+".to_owned(), Color::Gray),
None => ("·".to_owned(), Color::DarkGray),
};
let text = if i == cursor {
format!("[{text}]")
} else {
text
};
title.push(Span::styled(text, color));
}
title.push(Span::styled(
format!(" · {taken}/{} taken ", plan.len()),
Color::DarkGray,
));
title.retain(|span| !span.content.is_empty());
let line_box = split.box_of_line();
let block = pane(
Line::from(title),
Some(line_box.map_or(Color::DarkGray, box_color)),
);
self.diff.render_divided(frame, area, block, at, &rows);
frame.render_widget(self.status_line(), status);
}
fn divided_rows(
&self,
at: usize,
plan: &[Option<u8>],
cursor: usize,
selection: Option<(usize, usize)>,
) -> Option<Vec<(usize, Mark)>> {
let id = self.diff.hunks().get(at)?.id;
let patch = self.diff.patch();
let hunk = patch.files().get(id.file)?.hunks.get(id.hunk)?;
let mut nth = 0;
Some(
patch
.ordered_lines(hunk)
.into_iter()
.map(|l| {
if matches!(patch.line(l).as_bytes().first(), Some(b'+' | b'-')) {
let mark = Mark::Line {
commit: plan.get(nth).copied().flatten(),
cursor: nth == cursor,
selected: selection
.is_some_and(|(lo, hi)| nth >= lo.min(hi) && nth <= lo.max(hi)),
};
nth += 1;
(l, mark)
} else {
(l, Mark::Context)
}
})
.collect(),
)
}
fn draw_hunk(&mut self, frame: &mut Frame<'_>, area: Rect, status: Rect, accent: Color) {
let Some(split) = self.split.as_ref() else {
return;
};
let (at, total, path) = (split.at(), split.total(), split.path().to_owned());
let (assigned, commit) = (split.assigned(), split.box_of());
let mut title = vec![
Span::raw(format!(" Split {} ", self.change_id)),
immutable_marker(self.target.immutable),
Span::raw(format!("· hunk {}/{total} ", at + 1)),
Span::raw(format!("· {path} · ")),
];
title.extend(strip_spans(split.plan(), at));
title.push(Span::styled(
commit.map_or_else(
|| " · unassigned ".to_owned(),
|n| format!(" · commit {n} "),
),
commit.map_or(Color::DarkGray, box_color),
));
title.push(Span::styled(
format!("· {assigned}/{total} planned "),
Color::DarkGray,
));
title.retain(|span| !span.content.is_empty());
let block = pane(Line::from(title), Some(commit.map_or(accent, box_color)));
self.diff.render_hunk(frame, area, block, at);
frame.render_widget(self.status_line(), status);
}
fn draw_form(&mut self, frame: &mut Frame<'_>, area: Rect) {
let trailer_rows = self.fields[Field::Trailers as usize].lines().len();
let trailer_height = u16::try_from(trailer_rows.clamp(1, 4)).unwrap_or(4) + 2;
let [top, subject, body, problem, solution, trailers] = Layout::vertical([
Constraint::Length(3),
Constraint::Length(3),
Constraint::Fill(1),
Constraint::Fill(1),
Constraint::Fill(1),
Constraint::Length(trailer_height),
])
.areas(area);
let [ty, scope] =
Layout::horizontal([Constraint::Percentage(40), Constraint::Fill(1)]).areas(top);
let areas = [ty, scope, subject, body, problem, solution, trailers];
let header_len = self.draft().header().chars().count();
let accent = self.accent();
for (field, area) in Field::ALL.into_iter().zip(areas) {
let focused = self.focus == Focus::Editor && self.field == field;
let editor = &mut self.fields[field as usize];
editor.set_block(pane(
field_title(field, header_len),
focused.then_some(accent),
));
editor.set_cursor_style(cursor_style(focused));
frame.render_widget(&*editor, area);
}
}
fn draw_raw(&mut self, frame: &mut Frame<'_>, area: Rect) {
let header_len = self.raw.lines()[0].chars().count();
let title = Line::from(vec![
Span::raw(" Message (raw) "),
header_counter(header_len),
]);
let focused = self.focus == Focus::Editor;
let accent = self.accent();
self.raw.set_block(pane(title, focused.then_some(accent)));
self.raw.set_cursor_style(cursor_style(focused));
frame.render_widget(&self.raw, area);
}
const fn accent(&self) -> Color {
match (self.keymap, self.vim.mode) {
(Keymap::Vim, vim::Mode::Insert) | (Keymap::Default, _) => Color::Yellow,
(Keymap::Vim, _) => Color::Green,
}
}
pub(super) fn status_line(&self) -> Line<'static> {
if let Some(prompt) = &self.search_prompt {
return Line::from(format!("/{prompt}▏"));
}
match &self.status {
Some(Status::Error(err)) => return Line::from(format!(" ✗ {err}")).red().bold(),
Some(Status::Info(info)) => return Line::from(format!(" {info}")).cyan(),
Some(Status::ConfirmQuit) => {
return Line::from(
" Unsaved changes. Quit again to discard them, or press any other key to keep editing.",
)
.yellow()
.bold();
}
None => {}
}
if self.overview.is_some() && self.choosing() && self.visual.is_some() {
let keys =
" 1-9 commit selection · 0/d none · j/k ]/[ g/G extend · o other end · Esc cancel";
return Line::from(vec![Span::raw(keys).magenta()]);
}
if self.overview.is_some() && self.choosing() {
let keys = " 1-9 commit · 0 none · j/k row · V select · a/d file · Enter read it · f close · Esc leave";
return Line::from(vec![Span::raw(keys).dark_gray()]);
}
if self.choosing()
&& self.split.as_ref().is_some_and(Split::is_divided)
&& self.visual_line.is_some()
{
let keys =
" 1-9 commit selection · 0/d none · j/k g/G extend · o other end · Esc cancel";
return Line::from(vec![Span::raw(keys).magenta()]);
}
if self.choosing() && self.split.as_ref().is_some_and(Split::is_divided) {
let keys =
" 1-9 commit · 0 none · j/k line · V select · e close · Enter message · Esc leave";
return Line::from(vec![Span::raw(keys).dark_gray()]);
}
if self.choosing() {
let keys = " 1-9 commit · 0 none · n/p hunk · a/d file · e divide · f list · Enter message · Esc leave";
return Line::from(vec![Span::raw(keys).dark_gray()]);
}
let keys = match (self.focus, self.keymap, self.vim.mode) {
(Focus::Diff, ..) => {
let open = self.diff_tool.as_deref().unwrap_or("open");
format!(
" j/k scroll · [/] file · {{/}} hunk · f files · / search · z zoom · s split · o/O {open} · l back"
)
}
(Focus::Editor, Keymap::Default, _) => self
.split
.as_ref()
.and_then(Split::next_box)
.map_or_else(
|| " Tab next · Enter next/newline · Alt-← diff · Alt-s split · ^t raw/form · ^s save · Esc quit".to_owned(),
|commit| {
let held = self.split.as_ref().map_or(0, |s| s.count(commit));
format!(
" Tab next · Alt-← hunks · ^s commit {commit} ({held} {}) · ^t raw/form · Esc quit",
plural(held, "hunk")
)
},
),
(Focus::Editor, Keymap::Vim, vim::Mode::Insert) => {
" Esc normal · Tab next · Enter next/newline · ^t raw/form · ^s save".to_owned()
}
(Focus::Editor, Keymap::Vim, vim::Mode::Visual) => {
" d/c/y operate · Esc cancel".to_owned()
}
(Focus::Editor, Keymap::Vim, _) => {
" i insert · hjkl past an edge: next box · ^d/^u scroll diff · ^t raw/form · ^s save · q quit".to_owned()
}
};
let mut spans = Vec::new();
if self.keymap == Keymap::Vim {
let badge = Span::raw(self.vim.mode.label()).black();
spans.push(badge.bg(self.accent()));
}
spans.push(Span::raw(keys).dark_gray());
Line::from(spans)
}
}
const fn cursor_style(focused: bool) -> Style {
if focused {
Style::new().add_modifier(Modifier::REVERSED)
} else {
Style::new()
}
}
pub(super) fn raw_editor(text: &str) -> TextArea<'static> {
let mut editor = TextArea::new(text.split('\n').map(str::to_owned).collect());
editor.set_cursor_line_style(Style::new());
editor.set_wrap_mode(WrapMode::WordOrGlyph);
editor
}
pub(super) fn field_editor(field: Field, text: &str) -> TextArea<'static> {
let mut editor = TextArea::new(text.split('\n').map(str::to_owned).collect());
editor.set_placeholder_text(field.placeholder());
editor.set_cursor_line_style(Style::new());
if field.is_multiline() {
editor.set_wrap_mode(WrapMode::WordOrGlyph);
}
editor.move_cursor(CursorMove::Bottom);
editor.move_cursor(CursorMove::End);
editor
}
pub const fn box_color(n: u8) -> Color {
const WHEEL: [Color; 6] = [
Color::Cyan,
Color::Magenta,
Color::Yellow,
Color::Blue,
Color::LightGreen,
Color::LightMagenta,
];
WHEEL[(n as usize).saturating_sub(1) % WHEEL.len()]
}
fn legend(boxes: &[u8]) -> Vec<Span<'static>> {
if boxes.is_empty() {
return Vec::new();
}
let mut out = vec![Span::raw(format!(
"\u{b7} {} {} ",
boxes.len(),
plural(boxes.len(), "commit")
))];
out.extend(
boxes
.iter()
.map(|&n| Span::styled(format!("{n} "), box_color(n))),
);
out
}
fn strip_spans(plan: &[Option<u8>], at: usize) -> Vec<Span<'static>> {
plan.iter()
.enumerate()
.map(|(i, slot)| {
let (text, color) = match slot {
Some(n) if *n < 10 => (char::from(b'0' + n).to_string(), box_color(*n)),
Some(_) => ("+".to_owned(), Color::Gray),
None => ("·".to_owned(), Color::DarkGray),
};
let text = if i == at { format!("[{text}]") } else { text };
Span::styled(text, color)
})
.collect()
}
fn pane(title: Line<'static>, accent: Option<Color>) -> Block<'static> {
let style = Style::new().fg(accent.unwrap_or(Color::DarkGray));
Block::bordered()
.title(title)
.border_style(style)
.title_style(style)
}
fn field_title(field: Field, header_len: usize) -> Line<'static> {
let title = format!(" {} ", field.title());
if field != Field::Subject {
return Line::from(title);
}
Line::from(vec![Span::raw(title), header_counter(header_len)])
}
fn header_counter(len: usize) -> Span<'static> {
let color = match len {
0..=HEADER_SOFT_LIMIT => Color::Green,
n if n <= HEADER_HARD_LIMIT => Color::Yellow,
_ => Color::Red,
};
Span::styled(
format!("{len}/{HEADER_HARD_LIMIT} "),
Style::new().fg(color),
)
}
fn overview_line(row: &overview::Row, cursor: bool, selected: bool) -> Line<'static> {
let color = match row.kind {
overview::Kind::File => Color::White,
overview::Kind::InBox(n) => box_color(n),
overview::Kind::Divided => Color::Gray,
overview::Kind::Loose => Color::DarkGray,
};
let mut style = Style::new().fg(color);
if row.kind == overview::Kind::File {
style = style.add_modifier(Modifier::BOLD);
}
if cursor {
style = style.add_modifier(Modifier::REVERSED);
} else if selected {
style = style.bg(Color::DarkGray);
}
let gutter = if selected { '▌' } else { ' ' };
Line::styled(format!("{gutter}{}", row.text), style)
}
pub(super) fn immutable_marker(immutable: bool) -> Span<'static> {
if immutable {
Span::styled("· immutable ", Color::Red)
} else {
Span::raw("")
}
}
#[cfg(test)]
mod tests {
use super::{Color, box_color, immutable_marker, legend, strip_spans};
#[test]
fn the_box_colors_wrap_rather_than_running_out() {
assert_eq!(box_color(1), box_color(7));
assert_ne!(box_color(1), box_color(2));
assert_eq!(box_color(1), ratatui::style::Color::Cyan);
}
#[test]
fn the_legend_pairs_every_box_with_its_color() {
let spans = legend(&[1, 3]);
let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert_eq!(text, "\u{b7} 2 commits 1 3 ");
let digits: Vec<_> = spans[1..]
.iter()
.map(|s| (s.content.trim().to_owned(), s.style.fg))
.collect();
assert_eq!(
digits,
[
("1".to_owned(), Some(box_color(1))),
("3".to_owned(), Some(box_color(3))),
],
"box 3 is box 3's color, not the second color in the wheel"
);
assert!(legend(&[]).is_empty(), "no boxes, no legend");
}
#[test]
fn the_strip_colors_each_hunk_by_its_box() {
let spans = strip_spans(&[Some(1), None, Some(2)], 1);
let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert_eq!(text, "1[\u{b7}]2");
assert_eq!(spans[0].style.fg, Some(box_color(1)));
assert_eq!(spans[2].style.fg, Some(box_color(2)));
assert_eq!(
spans[1].style.fg,
Some(Color::DarkGray),
"a hunk no commit takes is not any box's color"
);
}
#[test]
fn the_immutable_marker_shows_only_on_protected_history() {
assert_eq!(immutable_marker(false).content, "");
assert!(immutable_marker(true).content.contains("immutable"));
}
}