use std::path::Path;
use anyhow::Result;
use plannotator_tui_review::progress;
use super::Screen;
pub(super) fn saving(data_dir: &Path) -> bool {
let env = std::env::var("PLANNOTATOR_REVIEW_PROGRESS").ok();
let config = std::fs::read_to_string(data_dir.join("config.json")).ok();
progress::enabled(env.as_deref(), config.as_deref())
}
impl Screen {
pub(super) fn viewed_label(&self) -> String {
let total = self.capture.files.len();
let viewed = self.progress.count(self.capture.files.iter().map(|f| f.path.as_str()));
format!("{viewed}/{total} viewed")
}
pub(super) fn cursor_file_viewed(&self) -> bool {
self.file_under_cursor().is_some_and(|p| self.progress.is_viewed(&p))
}
pub(super) fn file_under_cursor(&self) -> Option<String> {
if let Some(lines) = self.diff.selection() {
return Some(lines.path);
}
self.diff.cursor_file().and_then(|i| self.diff.paths().get(i).cloned())
}
pub(super) fn toggle_viewed(&mut self) {
let Some(path) = self.file_under_cursor() else {
self.status = Some("move the cursor onto a line of the file first".into());
return;
};
self.toggle_viewed_of(&path);
}
pub(super) fn toggle_viewed_of(&mut self, path: &str) {
let viewed = !self.progress.is_viewed(path);
let saved = self.progress.set(path, viewed);
let count = self.viewed_label();
self.status = Some(match (saved, viewed) {
(Err(err), _) => format!("{path}: for this session only, the mark was not saved: {err}"),
(Ok(()), true) if !self.progress.is_saved(path) => {
format!("\u{2713} {path} viewed for this session \u{b7} {count}")
}
(Ok(()), true) => format!("\u{2713} {path} viewed \u{b7} {count}"),
(Ok(()), false) => format!("{path} not viewed \u{b7} {count}"),
});
if let Err(err) = self.after_viewed_change(path) {
self.status = Some(format!("{err:#}"));
}
}
pub(super) fn jump_unviewed(&mut self, forward: bool) -> Result<()> {
let paths = self.diff.paths().to_vec();
if paths.is_empty() {
return Ok(());
}
let here = match self.diff.selection() {
Some(lines) => paths.iter().position(|q| *q == lines.path),
None => self.diff.cursor_file(),
};
let here_path = here.and_then(|i| paths.get(i));
let count = paths.len();
let start = here.unwrap_or(if forward { count - 1 } else { 0 });
let target = (1..=count)
.map(|step| if forward { (start + step) % count } else { (start + count - step % count) % count })
.find(|&i| paths.get(i).is_some_and(|p| Some(p) != here_path && !self.progress.is_viewed(p)));
let Some(index) = target else {
let all = paths.iter().all(|p| self.progress.is_viewed(p));
self.status = Some(if all { "every file is viewed" } else { "no other file to view" }.into());
return Ok(());
};
self.goto_index(index)?;
let path = paths.get(index).cloned().unwrap_or_default();
let left = paths
.iter()
.filter(|p| !self.progress.is_viewed(p))
.collect::<std::collections::BTreeSet<_>>()
.len();
self.status = Some(format!("{path} \u{b7} {left} not viewed"));
Ok(())
}
}