mod card;
mod paint;
use std::collections::HashMap;
use anyhow::Result;
use plannotator_tui_review::{CodeAnnotation, NoteScope, Side};
use ratatui::crossterm::event::KeyEvent;
use super::compose_at::{MAX_WIDTH, MIN_SIDE_WIDTH};
use super::diff::{Lines, Slot};
use super::{Screen, notes};
use crate::config::review::Notes;
use crate::keys::{self, Action};
const MIN_WIDTH: u16 = 12;
pub(super) const MIN_PANE_ROWS: u16 = 10;
#[derive(Debug, Default)]
pub(super) struct Inline {
ids: HashMap<String, u64>,
notes: HashMap<u64, String>,
cards: HashMap<u64, card::Card>,
skipped: usize,
small: bool,
pub(super) saved: Option<String>,
pub(super) rail: bool,
pub(super) view: Notes,
}
impl Inline {
pub(super) fn new(view: Notes) -> Self {
Self { view, ..Self::default() }
}
fn id(&mut self, note: &str) -> u64 {
if let Some(&id) = self.ids.get(note) {
return id;
}
let id = self.ids.len() as u64 + 1;
self.ids.insert(note.to_owned(), id);
self.notes.insert(id, note.to_owned());
id
}
fn card(&mut self, id: u64, note: &CodeAnnotation, width: u16) -> &card::Card {
let card = self.cards.entry(id).or_insert_with(|| card::Card::of(note, width));
if !card.is_for(note, width) {
*card = card::Card::of(note, width);
}
card
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Place {
Line(Side, u32),
Heading,
}
fn place(note: &CodeAnnotation) -> Option<Place> {
match note.scope {
NoteScope::Line if notes::in_diff(note) => Some(Place::Line(note.side, note.line_end)),
NoteScope::File if !notes::is_outdated(note) => Some(Place::Heading),
_ => None,
}
}
type Widths = [Option<u16>; 3];
fn width(widths: Widths, over: Option<Side>) -> Option<u16> {
let [old, new, across] = widths;
match over {
Some(Side::Old) => old,
Some(Side::New) => new,
None => across,
}
}
fn over(place: Place, split: bool, widths: Widths) -> Option<Side> {
let Place::Line(side, _) = place else { return None };
let [old, new, _] = widths;
let width = if side == Side::Old { old } else { new };
(split && width.is_some_and(|w| w >= MIN_SIDE_WIDTH)).then_some(side)
}
impl Screen {
pub(super) fn notes_inline(&self) -> bool {
self.settings.now.notes != Notes::Panel
}
pub(super) fn sync_boxes(&mut self) -> bool {
let notes = self.store.annotations();
let mut slots = Vec::new();
let mut skipped = 0;
let small = self.geometry.diff.height < MIN_PANE_ROWS;
if self.settings.now.notes != Notes::Panel && !small {
let area = self.geometry.diff;
let split = self.diff.split();
let mut widths: HashMap<&str, Widths> = HashMap::new();
let mut order: Vec<usize> = (0..notes.len()).collect();
order.sort_by_key(|&i| (notes.get(i).map_or(0, |note| note.created_at), i));
for note in order.into_iter().filter_map(|i| notes.get(i)) {
let path = note.file_path.as_str();
let widths = *widths.entry(path).or_insert_with(|| {
[Some(Side::Old), Some(Side::New), None].map(|over| self.diff.box_width(area, path, over))
});
let Some(place) = place(note) else {
skipped += 1;
continue;
};
let over = over(place, split, widths);
let width = width(widths, over).unwrap_or(0).min(MAX_WIDTH);
if width < MIN_WIDTH {
skipped += 1;
continue;
}
let id = self.inline.id(¬e.id);
let height = self.inline.card(id, note, width).height();
let line = match place {
Place::Line(side, line) => Some((side, line)),
Place::Heading => None,
};
slots.push(Slot { id, path, line, over, height });
}
}
self.inline.skipped = skipped;
self.inline.small = small;
match self.diff.set_boxes(&slots) {
Ok(changed) => changed,
Err(error) => {
self.status = Some(format!("could not show the notes in the diff: {error:#}"));
false
}
}
}
pub(super) fn box_columns(&self, pane: ratatui::layout::Rect, lines: &Lines) -> Option<(u16, u16)> {
self.columns_at(pane, &lines.path, Place::Line(lines.side, lines.last))
}
pub(super) fn heading_box_columns(&self, pane: ratatui::layout::Rect, path: &str) -> Option<(u16, u16)> {
self.columns_at(pane, path, Place::Heading)
}
fn columns_at(&self, pane: ratatui::layout::Rect, path: &str, place: Place) -> Option<(u16, u16)> {
let split = self.diff.split();
let widths =
[Some(Side::Old), Some(Side::New), None].map(|over| self.diff.box_width(pane, path, over));
let over = over(place, split, widths);
let full = width(widths, over)?;
let right = match over {
Some(Side::Old) => self.diff.split_line()?,
_ => pane.right(),
};
Some((right.checked_sub(full)?, full.min(MAX_WIDTH))).filter(|&(_, width)| width >= MIN_WIDTH)
}
pub(super) fn notes_not_inline(&self) -> usize {
if !self.notes_inline() || self.whole.is_some() || self.inline.small {
return 0;
}
self.inline.skipped + self.diff.hidden_boxes().len()
}
pub(super) fn too_small_for_boxes(&self) -> bool {
self.notes_inline()
&& self.whole.is_none()
&& self.inline.small
&& !self.store.annotations().is_empty()
}
pub(super) fn tell_saved_below(&mut self) {
let Some(note) = self.inline.saved.take() else { return };
if self.whole.is_some() || !self.notes_inline() || self.status.as_deref() != Some("note saved") {
return;
}
let Some(&id) = self.inline.ids.get(¬e) else { return };
if self.drawn_box(¬e).is_some() || !self.diff.keeps_box(id) {
return;
}
let down = KeyEvent::from(ratatui::crossterm::event::KeyCode::Down);
let key = if self.keys.is(Action::Down, &down) {
"\u{2193}".to_owned()
} else {
self.keys.hint(Action::Down)
};
self.status = Some(format!("note saved \u{b7} below, {key} shows it"));
}
pub(super) fn cursor_note(&self) -> Option<&CodeAnnotation> {
if self.whole.is_some() || !self.notes_inline() {
return None;
}
let id = self.inline.notes.get(&self.diff.cursor_box()?)?;
self.store.annotations().iter().find(|note| note.id == *id)
}
pub(super) fn box_key(&mut self, key: &KeyEvent) -> Result<bool> {
let Some(id) = self.cursor_note().map(|note| note.id.clone()) else { return Ok(false) };
let diff = self.keys.action(key, keys::DIFF);
let free = |action| diff.is_none() && self.keys.is(action, key);
if diff == Some(Action::Confirm) || free(Action::Edit) {
self.edit_note(&id);
} else if free(Action::Remove) {
self.remove_note(&id)?;
} else {
return Ok(false);
}
Ok(true)
}
pub(super) fn box_help(&self) -> Vec<(String, &'static str)> {
if !self.notes_inline() {
return Vec::new();
}
let edit = [self.keys.hint(Action::Confirm), self.keys.hint_besides(Action::Edit, keys::DIFF)];
let edit = edit.into_iter().filter(|k| !k.is_empty()).collect::<Vec<_>>().join(" ");
let remove = self.keys.hint_besides(Action::Remove, keys::DIFF);
vec![(edit, "on a note's box in the diff: edit it"), (remove, "on a note's box: remove it")]
}
pub(super) fn drawn_box(&self, id: &str) -> Option<ratatui::layout::Rect> {
let id = self.inline.ids.get(id)?;
self.geometry.boxes.iter().find(|(_, drawn)| drawn == id).map(|(rect, _)| *rect)
}
pub(super) fn follow_box(&mut self) {
let Some(id) = self.cursor_note().map(|note| note.id.clone()) else { return };
self.select_note(&id);
}
pub(super) fn select_note(&mut self, id: &str) {
if let Some(position) = self.rail_order().iter().position(|&i| self.note_id(i) == Some(id)) {
self.rail_cursor = position;
}
}
pub(super) fn notes_view_changed(&mut self) {
self.inline.rail = false;
if !self.rail_shown() && self.focus == super::Focus::Notes {
self.focus = super::Focus::Diff;
}
self.sync_boxes();
}
}
#[cfg(test)]
impl Screen {
pub(super) fn note_of_box(&self, id: u64) -> Option<&CodeAnnotation> {
let note = self.inline.notes.get(&id)?;
self.store.annotations().iter().find(|n| n.id == *note)
}
pub(super) fn box_label(note: &CodeAnnotation) -> String {
card::label(note)
}
}