rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The "new pull request" screen: a title, the branch to merge into and a description, then
//! a page saying exactly what will happen, which has to be confirmed. This is its state and
//! keys; `draw.rs` draws it.

use super::{Click, Job, Request, ReviewView, Screen};
use crate::review::forge::PullRequest;
use crate::review::propose::{Of, Proposal, Start};
use crate::settings::Input;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Field {
    Title,
    Base,
    Description,
    /// The button that goes on to the confirmation.
    Continue,
}

const FIELDS: [Field; 4] = [Field::Title, Field::Base, Field::Description, Field::Continue];

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Press {
    Focus(Field),
    /// On from the form, or confirm the confirmation.
    Accept,
    Cancel,
    Review,
    Open,
    Copy,
}

pub enum Stage {
    /// Looking at the branch.
    Loading,
    Failed(String),
    Form,
    Confirm,
    /// On its way to the host.
    Sending,
    /// The pull request is there: just made, or made before.
    Done {
        pull: Box<PullRequest>,
        created: Option<&'static str>,
    },
}

pub struct CreateView {
    pub stage: Stage,
    pub proposal: Option<Box<Proposal>>,
    pub field: Field,
    /// Something was typed, so leaving takes two presses.
    edited: bool,
    leaving: bool,
    /// The review it was opened from, which leaving goes back to.
    back: Option<Job>,
}

impl Default for CreateView {
    fn default() -> Self {
        CreateView {
            stage: Stage::Loading,
            proposal: None,
            field: Field::Title,
            edited: false,
            leaving: false,
            back: None,
        }
    }
}

impl CreateView {
    /// The text being typed in, if the chosen thing takes text.
    fn text(&mut self) -> Option<&mut String> {
        if !matches!(self.stage, Stage::Form) {
            return None;
        }
        let pull = &mut self.proposal.as_mut()?.pull;
        match self.field {
            Field::Title => Some(&mut pull.title),
            Field::Base => Some(&mut pull.base),
            Field::Description => Some(&mut pull.body),
            Field::Continue => None,
        }
    }

    fn typed(&mut self, add: &str) {
        let many_lines = self.field == Field::Description;
        let clean: String = add
            .replace("\r\n", "\n")
            .replace('\t', "    ")
            .chars()
            .filter(|&c| !c.is_control() || (c == '\n' && many_lines))
            .collect();
        if let Some(text) = self.text() {
            text.push_str(&clean);
            self.edited = true;
        }
    }

    pub fn paste(&mut self, text: &str) {
        if self.field == Field::Description {
            self.typed(text);
        } else {
            self.typed(text.lines().next().unwrap_or_default().trim());
        }
    }

    fn step(&mut self, by: usize) {
        let at = FIELDS.iter().position(|&f| f == self.field).unwrap_or(0);
        self.field = FIELDS[(at + by) % FIELDS.len()];
    }

    pub fn receive_start(&mut self, result: Result<Start, String>) {
        self.stage = match result {
            Ok(Start::New(p)) => {
                self.proposal = Some(p);
                Stage::Form
            }
            Ok(Start::Exists(pull)) => Stage::Done { pull, created: None },
            Err(e) => Stage::Failed(e),
        };
    }

    /// The host's answer to creating it. Returns what to say. After a failure the form is
    /// back, with everything that was typed.
    pub fn receive_created(&mut self, result: Result<(&'static str, PullRequest), String>) -> (String, bool) {
        match result {
            Ok((host, pull)) => {
                let said = format!("Created #{} on {host}", pull.number);
                self.stage = Stage::Done { pull: Box::new(pull), created: Some(host) };
                (said, false)
            }
            Err(e) => {
                self.stage = Stage::Form;
                self.edited = true;
                (e, true)
            }
        }
    }
}

impl ReviewView {
    pub(super) fn create_press(&mut self, press: Press) -> Request {
        let Screen::Create(view) = &mut self.screen else { return Request::Nothing };
        if press != Press::Cancel {
            view.leaving = false;
        }
        match press {
            Press::Focus(field) => view.field = field,
            Press::Accept => match view.stage {
                Stage::Form => {
                    let Some(p) = &view.proposal else { return Request::Nothing };
                    let problem = if p.pull.title.trim().is_empty() {
                        Some("A pull request needs a title")
                    } else if p.pull.base.trim().is_empty() {
                        Some("Name the branch to merge into")
                    } else {
                        None
                    };
                    match problem {
                        Some(problem) => self.status = Some((problem.to_string(), true)),
                        None => {
                            view.stage = Stage::Confirm;
                            self.status = None;
                            self.scroll = 0.0;
                        }
                    }
                }
                Stage::Confirm => {
                    let Some(p) = view.proposal.clone() else { return Request::Nothing };
                    view.stage = Stage::Sending;
                    self.status = None;
                    return Request::Create(p);
                }
                _ => {}
            },
            Press::Cancel => match view.stage {
                Stage::Confirm => {
                    view.stage = Stage::Form;
                    self.status = None;
                }
                // The answer is still wanted, so the screen stays; the panel can be closed.
                Stage::Sending => return Request::Close,
                Stage::Form if view.edited && !view.leaving => {
                    view.leaving = true;
                    self.status = Some(("Press esc again to throw away what you typed".to_string(), true));
                }
                _ => {
                    let back = view.back.take().unwrap_or(Job::List);
                    self.start(back);
                    return Request::Load;
                }
            },
            Press::Review => {
                if let Stage::Done { pull, .. } = &view.stage {
                    let target = format!("#{}", pull.number);
                    self.start(Job::Open(vec![target]));
                    return Request::Load;
                }
            }
            Press::Open | Press::Copy => {
                if let Stage::Done { pull, .. } = &view.stage
                    && pull.url.starts_with("https://")
                {
                    let url = pull.url.clone();
                    return if press == Press::Open {
                        Request::OpenUrl(url)
                    } else {
                        Request::Copy(url, "Copied the link".into())
                    };
                }
            }
        }
        self.reveal = true;
        Request::Nothing
    }

    pub(super) fn create_input(&mut self, input: Input) -> Request {
        let Screen::Create(view) = &mut self.screen else { return Request::Nothing };
        if input == Input::Escape {
            return self.create_press(Press::Cancel);
        }
        match view.stage {
            Stage::Form => match input {
                Input::Tab | Input::Down => view.step(1),
                Input::BackTab | Input::Up => view.step(FIELDS.len() - 1),
                Input::Enter => match view.field {
                    Field::Description => view.typed("\n"),
                    Field::Continue => return self.create_press(Press::Accept),
                    _ => view.step(1),
                },
                Input::Text(t) => view.typed(&t),
                Input::Space => view.typed(" "),
                Input::Backspace | Input::ClearAll => {
                    let word = input == Input::ClearAll;
                    if let Some(text) = view.text() {
                        if word {
                            // One word, not the lot: a description takes a while to write.
                            let kept = text.trim_end().trim_end_matches(|c: char| !c.is_whitespace()).len();
                            text.truncate(kept);
                        } else {
                            text.pop();
                        }
                        view.edited = true;
                    }
                }
                Input::PageUp => self.scroll = (self.scroll - 200.0).max(0.0),
                Input::PageDown => self.scroll = (self.scroll + 200.0).min(self.max_scroll),
                _ => return Request::Nothing,
            },
            Stage::Confirm if input == Input::Enter => return self.create_press(Press::Accept),
            Stage::Done { .. } => match input {
                Input::Enter => return self.create_press(Press::Review),
                Input::Text(t) if t.eq_ignore_ascii_case("o") => return self.create_press(Press::Open),
                Input::Text(t) if t.eq_ignore_ascii_case("c") => return self.create_press(Press::Copy),
                Input::Backspace => return self.create_press(Press::Cancel),
                _ => return Request::Nothing,
            },
            Stage::Failed(_) => match input {
                Input::Text(t) if t.eq_ignore_ascii_case("r") => {
                    let back = view.back.take();
                    self.start(self.job.clone());
                    if let Screen::Create(view) = &mut self.screen {
                        view.back = back;
                    }
                    return Request::Load;
                }
                Input::Backspace => return self.create_press(Press::Cancel),
                _ => return Request::Nothing,
            },
            _ => return Request::Nothing,
        }
        // Typing follows the field being typed in.
        self.reveal = true;
        Request::Nothing
    }

    /// Start the screen for the branch checked out.
    pub(super) fn start_proposal(&mut self) -> Request {
        self.start(Job::Propose(None));
        Request::Load
    }

    /// Start it for the branch being reviewed, to come back to the review afterwards.
    pub(super) fn propose_reviewed(&mut self) -> Request {
        let Some(of): Option<Of> = self.opened().and_then(|o| o.change.branch.clone()) else {
            return Request::Nothing;
        };
        let review = self.job.clone();
        self.start(Job::Propose(Some(of)));
        if let Screen::Create(view) = &mut self.screen {
            view.back = Some(review);
        }
        Request::Load
    }

    pub(super) fn create_click(&mut self, click: &Click) -> Option<Request> {
        match click {
            Click::Create(press) => Some(self.create_press(press.clone())),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::super::Message;
    use super::*;
    use crate::review::forge::NewPull;

    fn proposal() -> Proposal {
        Proposal {
            root: PathBuf::from("."),
            reference: "refs/heads/search".into(),
            remote: "origin".into(),
            host: "bitbucket.org".into(),
            pull: NewPull {
                title: "Add search".into(),
                body: String::new(),
                head: "search".into(),
                base: "main".into(),
            },
            sha: "abc".into(),
            commits: vec!["Add search".into()],
            push: true,
            dirty: 0,
        }
    }

    fn form() -> ReviewView {
        let mut view = ReviewView::new(PathBuf::from("."), Job::Propose(None), None);
        let number = view.number;
        view.receive(Message::Proposed(number, Ok(Start::New(Box::new(proposal())))));
        view
    }

    fn state(view: &ReviewView) -> &CreateView {
        let Screen::Create(c) = &view.screen else { panic!("not on the create screen") };
        c
    }

    #[test]
    fn nothing_is_sent_until_it_is_confirmed() {
        let mut view = form();
        view.input(Input::Text("!".into()));
        assert_eq!(view.input(Input::Enter), Request::Nothing, "enter moves on from the title");
        view.input(Input::Tab);
        view.input(Input::Text("Why".into()));
        assert_eq!(view.input(Input::Enter), Request::Nothing, "a new line in the description");
        view.paste("two\r\nlines");
        view.input(Input::ClearAll);
        view.input(Input::Tab);
        assert_eq!(view.input(Input::Enter), Request::Nothing, "only shows what will happen");
        assert!(matches!(state(&view).stage, Stage::Confirm));
        assert_eq!(view.input(Input::Escape), Request::Nothing);
        assert!(matches!(state(&view).stage, Stage::Form));
        view.input(Input::Enter);
        let Request::Create(sent) = view.input(Input::Enter) else { panic!("confirming sends it") };
        assert_eq!((sent.pull.title.as_str(), sent.pull.body.as_str()), ("Add search!", "Why\ntwo\n"));
        assert_eq!(view.input(Input::Enter), Request::Nothing, "and only once");
    }

    #[test]
    fn a_refusal_keeps_what_was_typed_and_leaving_takes_two_presses() {
        let mut view = form();
        view.input(Input::Text(" now".into()));
        view.create_press(Press::Accept);
        view.create_press(Press::Accept);
        let number = view.number;
        view.receive(Message::Created(number, Err("the host said no".into())));
        assert!(matches!(state(&view).stage, Stage::Form));
        assert_eq!(state(&view).proposal.as_ref().unwrap().pull.title, "Add search now");
        assert_eq!(view.status, Some(("the host said no".into(), true)));
        assert_eq!(view.input(Input::Escape), Request::Nothing);
        assert!(matches!(view.screen, Screen::Create(_)));
        assert_eq!(view.input(Input::Escape), Request::Load);
        assert!(matches!(view.screen, Screen::Pick(_)));
    }

    #[test]
    fn a_new_pull_request_can_be_reviewed_or_opened() {
        let mut view = form();
        let pull =
            PullRequest { number: 7, url: "https://bitbucket.org/x/y/pull-requests/7".into(), ..Default::default() };
        let number = view.number;
        view.receive(Message::Created(number, Ok(("Bitbucket", pull.clone()))));
        assert_eq!(view.status, Some(("Created #7 on Bitbucket".into(), false)));
        assert_eq!(view.input(Input::Text("o".into())), Request::OpenUrl(pull.url));
        assert_eq!(view.input(Input::Enter), Request::Load);
        assert_eq!(view.job, Job::Open(vec!["#7".into()]));
    }
}