scarb_ui/components/
status.rs

1use console::{Alignment, Style, pad_str};
2use serde::{Serialize, Serializer};
3
4use crate::Message;
5
6/// Indication of starting or finishing of a significant process in the application.
7///
8/// The `status` part categorizes the process, and should always be a single verb, for example:
9/// _Compiling_, _Running_.
10/// In text mode, status messages are coloured and right-padded for better aesthetics.
11/// Padding is hardcoded to **12** characters, therefore avoid using words longer than
12/// **11** characters.
13/// The `message` part is a free-form text describing the details of what's going on.
14#[derive(Serialize)]
15pub struct Status<'a> {
16    status: &'a str,
17    #[serde(skip)]
18    color: &'a str,
19    message: &'a str,
20}
21
22impl<'a> Status<'a> {
23    /// Create a new [`Status`] with default color (green).
24    pub fn new(status: &'a str, message: &'a str) -> Self {
25        Self::with_color(status, "green", message)
26    }
27
28    /// Create a new [`Status`] with the given color.
29    pub fn with_color(status: &'a str, color: &'a str, message: &'a str) -> Self {
30        Self {
31            status,
32            color,
33            message,
34        }
35    }
36}
37
38impl Message for Status<'_> {
39    fn text(self) -> String {
40        format!(
41            "{} {}",
42            Style::from_dotted_str(self.color).bold().apply_to(pad_str(
43                self.status,
44                12,
45                Alignment::Right,
46                None,
47            )),
48            self.message
49        )
50    }
51
52    fn structured<S: Serializer>(self, ser: S) -> Result<S::Ok, S::Error> {
53        let status = self.status.to_lowercase();
54        Status {
55            status: &status,
56            color: self.color,
57            message: self.message,
58        }
59        .serialize(ser)
60    }
61}