use anyhow::Result;
use diffs_rs::engine::{DiffRowKind, Inset, InsetAnchor, InsetSpan};
use plannotator_tui_review::Side;
use ratatui::layout::Rect;
use super::{Diff, engine_side};
pub(in crate::review) use diffs_rs::engine::InsetArea as BoxArea;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::review) struct Slot<'a> {
pub(in crate::review) id: u64,
pub(in crate::review) path: &'a str,
pub(in crate::review) line: Option<(Side, u32)>,
pub(in crate::review) over: Option<Side>,
pub(in crate::review) height: u16,
}
impl Diff {
pub(in crate::review) fn set_boxes(&mut self, slots: &[Slot<'_>]) -> Result<bool> {
let review = self.engine.review_id();
let index: std::collections::HashMap<&str, usize> =
self.paths.iter().enumerate().map(|(i, path)| (path.as_str(), i)).collect();
let insets: Vec<Inset> = slots
.iter()
.filter_map(|slot| {
let file = *index.get(slot.path)?;
let anchor = match slot.line {
Some((side, line)) if line >= 1 => InsetAnchor::Line { side: engine_side(side), line },
Some(_) => return None,
None => InsetAnchor::FileHeading,
};
Some(Inset::new(review, slot.id, file, anchor, slot.height).with_span(span(slot.over)))
})
.collect();
if self.engine.insets() == insets.as_slice() {
return Ok(false);
}
self.engine.set_insets(&insets)?;
Ok(true)
}
pub(in crate::review) fn box_areas(&self) -> &[BoxArea] {
self.engine.inset_areas()
}
pub(in crate::review) fn hidden_boxes(&self) -> Vec<u64> {
self.engine.hidden_insets()
}
pub(in crate::review) fn keeps_box(&self, id: u64) -> bool {
self.engine.insets().iter().any(|inset| inset.id == id) && !self.engine.hidden_insets().contains(&id)
}
pub(in crate::review) fn box_width(&self, area: Rect, path: &str, over: Option<Side>) -> Option<u16> {
self.engine.inset_width_in(area, self.index(path)?, span(over))
}
pub(in crate::review) fn cursor_box(&self) -> Option<u64> {
match self.engine.cursor_row()?.kind {
DiffRowKind::Inset { id } => Some(id),
_ => None,
}
}
pub(in crate::review) fn box_at(&self, column: u16, row: u16) -> Option<u64> {
match self.engine.row_at(column, row)?.kind {
DiffRowKind::Inset { id } => Some(id),
_ => None,
}
}
pub(in crate::review) fn under_boxes(&self, row: u16) -> u16 {
let column = self.area.right().saturating_sub(2);
let mut last = row;
while last + 1 < self.area.bottom() && self.box_at(column, last + 1).is_some() {
last += 1;
}
last
}
}
fn span(over: Option<Side>) -> InsetSpan {
over.map_or(InsetSpan::Full, |side| InsetSpan::Side(engine_side(side)))
}
#[cfg(test)]
impl Diff {
pub(in crate::review) fn boxes_set(&self) -> Vec<Inset> {
self.engine.insets().to_vec()
}
}