Skip to main content

tui/app/
pending.rs

1//! Pending-form lifecycle: a submitted form stays on screen, locked, until its
2//! own request settles, and every outcome is terminal.
3
4use cli_core::render::{FieldError, RenderError};
5
6use crate::app::App;
7use crate::form::Form;
8use crate::modal::Modal;
9
10/// A form that was dispatched and awaits the reply to `request_id`.
11///
12/// Input is swallowed while pending, `Esc` included: the mutation is already
13/// in flight, so cancelling would hide an outcome the user must see.
14#[derive(Debug)]
15pub struct PendingForm {
16    pub request_id: i64,
17    pub form: Form,
18}
19
20impl App {
21    pub(crate) fn lock_pending_form(&mut self, request_id: i64, form: Form) {
22        self.pending_form = Some(PendingForm { request_id, form });
23    }
24
25    /// Whether no dialog is open or awaiting its reply; otherwise `what` is
26    /// reported as dropped. Every late opener asks before it shows anything.
27    pub(super) fn dialog_free(&mut self, what: &str) -> bool {
28        let busy = self.pending_form.is_some() || !self.overlays.is_empty();
29        if busy {
30            self.set_status(format!("{what} dropped: another dialog is open"));
31        }
32        !busy
33    }
34
35    /// Takes the pending form only when `request_id` is its own request.
36    pub(super) fn take_pending_form(&mut self, request_id: i64) -> Option<Form> {
37        self.pending_form
38            .take_if(|p| p.request_id == request_id)
39            .map(|p| p.form)
40    }
41
42    /// Reopens `form` with its values intact, the rejection shown and the
43    /// first rejected field focused.
44    pub(super) fn unlock_pending_form(&mut self, mut form: Form, errors: Vec<FieldError>) {
45        form.show_errors(&errors);
46        if let Some(first) = form.errors.first() {
47            self.status = format!("submit failed: {first}");
48        }
49        if form.is_stale(&errors) {
50            self.status
51                .push_str(" (close the form and open it again to reload)");
52        }
53        self.overlays.push(Modal::Form(form));
54    }
55}
56
57fn form_level(message: &str) -> FieldError {
58    FieldError {
59        field: String::new(),
60        message: message.to_string(),
61    }
62}
63
64/// Field errors of a rejected submit; anything but `form-invalid` with a
65/// readable detail is one form-level error.
66pub(super) fn rejection(error: &RenderError) -> Vec<FieldError> {
67    let RenderError::Server(reply) = error else {
68        return vec![form_level(&error.to_string())];
69    };
70    match reply.field_errors() {
71        fields if fields.is_empty() => vec![form_level(&reply.message)],
72        fields => fields,
73    }
74}