1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/boxx/0.0.3-beta")]

//! boxx
//!
//! The `boxx` crate provides a convenient, high-level API
//! for creating boxes in the terminal.

mod config;
mod visual;

pub use config::{Alignment, BorderColor, BorderComponents, BorderStyle, Config};
use visual::{visual_width, VisualWidthError};

use console::Style;
use std::cmp;

const SPACE: &str = " ";
const NEWLINE: &str = "\n";

/// `Boxx` is a customizable data structure that will pretty print content
/// separated by newlines (`\n`).
#[derive(PartialEq, Clone, Debug)]
pub struct Boxx {
    /// Display configuration of the `Boxx`. This field dictates how a `Boxx` will
    /// be displayed in the terminal.
    pub config: Config,
}

impl Boxx {
    /// Create a `Boxx` with deafult configuration.
    ///
    /// # Example
    ///
    /// ```
    /// use boxx::Boxx;
    ///
    /// let boxx = Boxx::default();
    /// ```
    pub fn default() -> Boxx {
        Config::default().build()
    }

    /// Creates a new `Boxx` from a pre-made `Config`.
    ///
    /// # Example
    ///
    /// ```
    /// use boxx::{Boxx, Config};
    ///
    /// let config = Config::default();
    /// let boxx = Boxx::new(config);
    /// ```
    pub fn new(config: Config) -> Boxx {
        Boxx { config }
    }

    /// Get a configuration builder to customize the appearance of a `Boxx`.
    ///
    /// # Example
    ///
    /// ```
    /// use boxx::Boxx;
    ///
    /// let boxx = Boxx::builder().padding(3).margin(1).build();
    /// ```
    pub fn builder() -> Config {
        Config::default()
    }

    /// Prints your `Boxx`ed content to `stdout`
    /// If your content is long, separate it with line breaks (`\n`).
    ///
    /// If the user's terminal is too small, or something goes wrong with displaying
    /// your content in a box, this function will print the content passed to it
    /// with no modifications.
    ///
    /// If you would like to handle specific error cases, it is recommended to use
    /// `.as_str()` directly.
    ///
    /// # Example
    ///
    /// ```
    /// use boxx::Boxx;
    ///
    /// Boxx::default().display("Hello, World!\nNew lines can be created with the newline separator :).");
    /// ```
    pub fn display(&self, content: &str) {
        println!("{}", self.as_str(content).unwrap_or(content.to_string()));
    }

    /// Get your content in a `Boxx` as a `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use boxx::Boxx;
    ///
    /// let result = Boxx::default().as_str("Hello, World!")?;
    /// println!("{}", result);
    /// ```
    pub fn as_str(&self, content: &str) -> Result<String, VisualWidthError> {
        let border_color = match self.config.border_color {
            Some(color) => Style::from_dotted_str(&format!("{:?}", color).to_lowercase()),
            None => Style::default(),
        };
        let mut lines: Vec<String> = Vec::new();
        lines.push(SPACE.repeat(self.config.padding.top));
        for line in content.split_terminator(NEWLINE) {
            lines.push(line.to_string());
        }
        lines.push(SPACE.repeat(self.config.padding.bottom));
        let mut widest_length: usize = 0;
        for line in lines.clone() {
            widest_length = cmp::max(widest_length, visual_width(line.as_str())?);
        }
        for (i, line) in lines.clone().iter().enumerate() {
            let padding = widest_length - visual_width(line.as_str())?;
            lines[i] = match &self.config.text_alignment {
                Alignment::Left => line.clone(),
                Alignment::Right => format!("{}{}", SPACE.repeat(padding), line),
                Alignment::Center => format!("{}{}", SPACE.repeat(padding / 2), line),
            };
        }
        let content_width = widest_length + self.config.padding.left + self.config.padding.right;
        let output = if let Some((max_width, _)) = term_size::dimensions() {
            if content_width > max_width {
                return Ok(content.to_string());
            }
            let padding_left = SPACE.repeat(self.config.padding.left);
            let margin_left = match &self.config.box_alignment {
                Alignment::Left => SPACE.repeat(self.config.padding.left),
                Alignment::Center => {
                    let space_width = cmp::max((max_width - content_width) / 2, 0);
                    SPACE.repeat(space_width)
                }
                Alignment::Right => {
                    let space_width =
                        cmp::max(max_width - content_width - self.config.margin.right - 2, 0);
                    SPACE.repeat(space_width)
                }
            };
            let mut horizontal_str = self.config.border_components.horizontal.to_string();
            let mut horizontal_str_width = visual_width(horizontal_str.as_str())?;
            if horizontal_str_width == 0 {
                horizontal_str.push_str(" ");
                horizontal_str_width = 1;
            }
            let mut horizontal = horizontal_str.repeat(
                (content_width % horizontal_str_width) + (content_width / horizontal_str_width),
            );
            while visual_width(horizontal.as_str())? > content_width {
                horizontal.pop();
            }
            let top = format!(
                "{}{}{}{}{}",
                NEWLINE.repeat(self.config.margin.top),
                margin_left,
                border_color.apply_to(&self.config.border_components.top_left),
                border_color.apply_to(&horizontal),
                border_color.apply_to(&self.config.border_components.top_right)
            );
            let bottom = format!(
                "{}{}{}{}{}",
                margin_left,
                border_color.apply_to(&self.config.border_components.bottom_left),
                border_color.apply_to(&horizontal),
                border_color.apply_to(&self.config.border_components.bottom_right),
                NEWLINE.repeat(self.config.margin.bottom)
            );
            let mut middle = String::from("\n");
            let mut vertical = self.config.border_components.vertical.to_string();
            if visual_width(vertical.as_str())? == 0 {
                vertical.push_str(" ");
            }
            let vertical = vertical.repeat(lines.len());
            let mut vertical_chars = vertical.chars();
            for line in lines {
                let vertical = border_color
                    .apply_to(&vertical_chars.next().unwrap())
                    .to_string();
                middle.push_str(&margin_left);
                middle.push_str(&vertical);
                middle.push_str(&padding_left);
                middle.push_str(&line);
                middle.push_str(&SPACE.repeat(
                    content_width - visual_width(line.as_str())? - &self.config.padding.left,
                ));
                middle.push_str(&vertical);
                middle.push_str(NEWLINE);
            }
            format!("{}{}{}", top, middle, bottom)
        } else {
            content.to_string()
        };
        Ok(output)
    }
}