plannotator-tui 0.15.0

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
//! The summary before a post to GitHub, drawn over the review, and the words it is made of.

use plannotator_tui_review::post::{Event, InBody, InlineComment, MAX_BODY_CHARS, Plan, Skip};
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};

use super::Screen;
use super::post::{Confirm, Head, short};
use crate::keys::Action;
use crate::theme::palette;
use crate::wrap::wrap_line;

/// The summary's widest.
const WIDTH: u16 = 76;

impl Screen {
    pub(super) fn draw_post(&self, frame: &mut Frame, area: Rect, confirm: &Confirm) {
        let lines = self.post_lines(confirm);
        let help = self.post_help(confirm);
        let width = area.width.min(WIDTH);
        let inner_width = usize::from(width.saturating_sub(4)).max(1);
        let rows: Vec<Line<'static>> = lines
            .iter()
            .flat_map(|line| {
                let wrapped = wrap_line(line, &[], inner_width);
                if wrapped.is_empty() {
                    vec![Line::default()]
                } else {
                    wrapped.into_iter().map(|r| r.line).collect()
                }
            })
            .collect();
        let height = (rows.len() as u16 + 2).min(area.height);
        let rect = Rect {
            x: area.x + area.width.saturating_sub(width) / 2,
            y: area.y + area.height.saturating_sub(height) / 2,
            width,
            height,
        };
        frame.render_widget(Clear, rect);
        let boxed = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(palette().accent))
            .title(Span::styled(" post to GitHub ", Style::new().dim()))
            .title_bottom(Span::styled(format!(" {help} "), Style::new().dim()));
        let inner = boxed.inner(rect);
        frame.render_widget(boxed, rect);
        let text_area = Rect { x: inner.x + 1, width: inner.width.saturating_sub(2), ..inner };
        frame.render_widget(Paragraph::new(rows), text_area);
    }

    fn post_lines(&self, confirm: &Confirm) -> Vec<Line<'static>> {
        let Some(pull) = &self.capture.pull else { return Vec::new() };
        let accent = Style::new().fg(palette().accent).bold();
        let warn = Style::new().fg(palette().comment).bold();
        let refused = Style::new().fg(palette().delete).bold();
        let mut lines: Vec<Line<'static>> = vec![
            Line::from(vec![
                Span::styled(format!("{}#{}", pull.view.repo.slug(), pull.view.number), accent),
                Span::raw(format!(" \u{b7} {}", pull.view.title)),
            ]),
            Line::from(Span::styled(
                format!("anchored to {}, the commit you reviewed", short(&confirm.plan.commit_id)),
                Style::new().dim(),
            )),
            Line::default(),
        ];
        lines.extend(summary(&confirm.plan).into_iter().map(Line::from));
        let mut note = |text: String, style: Style| {
            lines.push(Line::default());
            lines.push(Line::from(Span::styled(text, style)));
        };
        match &confirm.head {
            Head::Reviewed => {}
            Head::Checking => note("Checking the PR on GitHub\u{2026}".into(), Style::new().dim()),
            Head::Moved { now } => {
                let reload = self.keys.labelled(Action::Reload, "reloads it first").unwrap_or_default();
                note(
                    format!(
                        "The PR moved on: its head is {} now. Comments stay on {}, the lines you saw; \
                         GitHub shows them as outdated where the code changed since. {reload}",
                        short(now),
                        short(&confirm.plan.commit_id)
                    ),
                    warn,
                );
            }
            Head::Unknown(why) => note(format!("Could not check the PR's head: {why}"), warn),
        }
        if let Some(ended) = confirm.ended {
            note(format!("The PR is {ended}. GitHub still takes a review on it."), warn);
        }
        for problem in too_long(&confirm.plan) {
            note(problem, refused);
        }
        let mut choices = vec![Span::raw("verdict  ")];
        for event in Event::ALL {
            let chosen = event == confirm.event;
            let mark = if chosen { "(\u{2022})" } else { "( )" };
            let style = if chosen { Style::new().bold() } else { Style::new().dim() };
            choices.push(Span::styled(format!("{mark} {}   ", event.label()), style));
        }
        lines.push(Line::default());
        lines.push(Line::from(choices));
        if confirm.posting {
            lines.push(Line::default());
            lines.push(Line::from(Span::styled("Posting to GitHub\u{2026}", warn)));
        } else if let Some(failed) = &confirm.failed {
            lines.push(Line::default());
            lines.push(Line::from(Span::styled(failed.clone(), refused)));
        }
        lines
    }

    /// The bottom line: what the keys do now.
    fn post_help(&self, confirm: &Confirm) -> String {
        if confirm.posting {
            return "waiting for GitHub's answer".to_owned();
        }
        let verb = match confirm.event {
            Event::Comment => "posts",
            Event::Approve => "posts and approves",
            Event::RequestChanges => "posts and requests changes",
        };
        let moves: Vec<String> = [Action::Left, Action::Right]
            .map(|a| self.keys.hint(a))
            .into_iter()
            .filter(|k| !k.is_empty())
            .collect();
        let help: Vec<String> = [
            (confirm.head != Head::Checking).then(|| self.keys.labelled(Action::Confirm, verb)).flatten(),
            (!moves.is_empty()).then(|| format!("{} verdict", moves.join("/"))),
            self.keys.labelled(Action::Back, "cancels"),
        ]
        .into_iter()
        .flatten()
        .collect();
        help.join(" \u{b7} ")
    }
}

/// `app.py:9 new` or `app.py:3-5 old`.
fn place(comment: &InlineComment) -> String {
    let side = if comment.side == "LEFT" { "old" } else { "new" };
    match comment.start_line {
        Some(start) => format!("{}:{start}-{} {side}", comment.path, comment.line),
        None => format!("{}:{} {side}", comment.path, comment.line),
    }
}

/// `app.py:9 new, app.py:3-5 old`.
pub(super) fn comment_places(plan: &Plan) -> String {
    plan.comments.iter().map(place).collect::<Vec<_>>().join(", ")
}

/// What GitHub would refuse for its length, naming the note or the kind of notes to shorten.
pub(super) fn too_long(plan: &Plan) -> Vec<String> {
    let mut problems: Vec<String> = plan
        .too_long_comments()
        .into_iter()
        .map(|(comment, chars)| {
            format!(
                "The note on {} is {chars} characters; GitHub takes {MAX_BODY_CHARS} at most. Shorten it.",
                place(comment)
            )
        })
        .collect();
    if plan.body_too_long() {
        let kinds: Vec<String> = plan
            .body_size_by_kind()
            .into_iter()
            .map(|(kind, chars)| format!("{} {chars}", body_kind(kind)))
            .collect();
        problems.push(format!(
            "The review body is {} characters; GitHub takes {MAX_BODY_CHARS} at most. It holds {}: \
             shorten or remove some of those notes.",
            plan.body.chars().count(),
            kinds.join(", ")
        ));
    }
    problems
}

fn body_kind(kind: InBody) -> &'static str {
    match kind {
        InBody::Change => "whole-change notes",
        InBody::File => "file notes",
        InBody::OutsideDiff => "notes outside the diff, with their quoted code,",
        InBody::OffDiff => "outdated line notes, with their quoted code,",
    }
}

/// The summary's lines about what goes where.
pub(super) fn summary(plan: &Plan) -> Vec<String> {
    let plural = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many });
    let mut lines = vec![plural(plan.comments.len(), "inline comment", "inline comments")];
    if !plan.plain_suggestions.is_empty() {
        lines.push(format!(
            "  {} on removed lines, as plain comments: GitHub applies suggestions to new lines only",
            plural(plan.plain_suggestions.len(), "suggestion", "suggestions")
        ));
    }
    let body: Vec<String> = [
        (InBody::Change, "whole-change note", "whole-change notes"),
        (InBody::File, "file note", "file notes"),
        (
            InBody::OutsideDiff,
            "note outside the diff, quoted with a link",
            "notes outside the diff, quoted with a link",
        ),
        (
            InBody::OffDiff,
            "line note outdated or no longer in the diff, quoted",
            "line notes outdated or no longer in the diff, quoted",
        ),
    ]
    .into_iter()
    .filter_map(|(kind, one, many)| {
        let n = plan.count_in_body(kind);
        (n > 0).then(|| format!("  {}", plural(n, one, many)))
    })
    .collect();
    if body.is_empty() {
        lines.push("nothing else in the review body".to_owned());
    } else {
        lines.push(format!("{} in the review body:", plan.in_body.len()));
        lines.extend(body);
    }
    if !plan.reposted.is_empty() {
        lines.push(format!(
            "{} edited since posted: posted again as new comments (the earlier ones stay on GitHub)",
            plan.reposted.len()
        ));
    }
    let skipped: Vec<String> = [(Skip::AlreadyPosted, "already posted"), (Skip::Empty, "empty")]
        .into_iter()
        .filter_map(|(why, label)| {
            let n = plan.count_skipped(why);
            (n > 0).then(|| format!("{n} {label}"))
        })
        .collect();
    if !skipped.is_empty() {
        lines.push(format!("skipped: {}", skipped.join(", ")));
    }
    lines
}