boxen 0.4.0

A Rust library for creating styled terminal boxes around text with performance optimizations
Documentation
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! # Border Style Implementations and Utilities
//!
//! This module provides implementations and utilities for working with different border styles.
//! It includes methods for converting between style names and enums, validating custom styles,
//! and providing utilities for border style operations.
//!
//! ## Available Operations
//!
//! - **Style Conversion**: Convert between string names and `BorderStyle` enums
//! - **Character Retrieval**: Get the appropriate `BorderChars` for each style
//! - **Validation**: Validate custom border styles and characters
//! - **Comparison**: Compare border styles for equality
//! - **Preview**: Generate visual previews of border styles
//!
//! ## Usage Examples
//!
//! ```rust
//! use ::boxen::BorderStyle;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Parse style from string
//! let style = BorderStyle::from_name("double")?;
//!
//! // Get characters for a style
//! let chars = style.get_chars()?;
//!
//! // Check if style is visible
//! assert!(style.is_visible());
//! # Ok(())
//! # }
//! ```

use crate::error::BoxenError;
use crate::options::{BorderChars, BorderStyle};

impl BorderStyle {
    /// Get the `BorderChars` for this style
    ///
    /// # Errors
    ///
    /// Returns an error if the border style is custom and contains invalid characters.
    pub fn get_chars(&self) -> Result<BorderChars, BoxenError> {
        match self {
            BorderStyle::None => Ok(BorderChars::uniform(' ')),
            BorderStyle::Single => Ok(BorderChars::single()),
            BorderStyle::Double => Ok(BorderChars::double()),
            BorderStyle::Round => Ok(BorderChars::round()),
            BorderStyle::Bold => Ok(BorderChars::bold()),
            BorderStyle::SingleDouble => Ok(BorderChars::single_double()),
            BorderStyle::DoubleSingle => Ok(BorderChars::double_single()),
            BorderStyle::Classic => Ok(BorderChars::classic()),
            BorderStyle::Custom(chars) => {
                chars.validate().map_err(|msg| {
                    BoxenError::invalid_border_style(
                        format!("Custom border validation failed: {msg}"),
                        vec![crate::error::ErrorRecommendation::suggestion_only(
                            "Border validation failed".to_string(),
                            "Check that all border characters are valid and visible".to_string(),
                        )],
                    )
                })?;
                Ok(*chars)
            }
        }
    }

    /// Check if this border style is visible (not None)
    #[must_use]
    pub fn is_visible(&self) -> bool {
        !matches!(self, BorderStyle::None)
    }

    /// Get the display name of this border style
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            BorderStyle::None => "none",
            BorderStyle::Single => "single",
            BorderStyle::Double => "double",
            BorderStyle::Round => "round",
            BorderStyle::Bold => "bold",
            BorderStyle::SingleDouble => "singleDouble",
            BorderStyle::DoubleSingle => "doubleSingle",
            BorderStyle::Classic => "classic",
            BorderStyle::Custom(_) => "custom",
        }
    }

    /// Parse a border style from a string name
    ///
    /// # Errors
    ///
    /// Returns an error if the style name is not recognized.
    pub fn from_name(name: &str) -> Result<BorderStyle, BoxenError> {
        match name.to_lowercase().as_str() {
            "none" => Ok(BorderStyle::None),
            "single" => Ok(BorderStyle::Single),
            "double" => Ok(BorderStyle::Double),
            "round" => Ok(BorderStyle::Round),
            "bold" => Ok(BorderStyle::Bold),
            "singledouble" | "single_double" => Ok(BorderStyle::SingleDouble),
            "doublesingle" | "double_single" => Ok(BorderStyle::DoubleSingle),
            "classic" => Ok(BorderStyle::Classic),
            _ => Err(BoxenError::invalid_border_style(
                format!(
                    "Unknown border style: '{name}'. Valid styles are: none, single, double, round, bold, singleDouble, doubleSingle, classic"
                ),
                vec![
                    crate::error::ErrorRecommendation::suggestion_only(
                        "Unknown border style".to_string(),
                        "Use one of the predefined styles: single, double, round, bold, etc."
                            .to_string(),
                    ),
                    crate::error::ErrorRecommendation::with_auto_fix(
                        "Use default style".to_string(),
                        "Try using the default single border style".to_string(),
                        "BorderStyle::Single".to_string(),
                    ),
                ],
            )),
        }
    }

    /// Get all available predefined border style names
    #[must_use]
    pub fn available_styles() -> Vec<&'static str> {
        vec![
            "none",
            "single",
            "double",
            "round",
            "bold",
            "singleDouble",
            "doubleSingle",
            "classic",
        ]
    }

    /// Create a custom border style with validation
    ///
    /// # Errors
    ///
    /// Returns an error if the border characters are invalid.
    pub fn custom(chars: BorderChars) -> Result<BorderStyle, BoxenError> {
        chars.validate().map_err(|msg| {
            BoxenError::invalid_border_style(
                format!("Custom border validation failed: {msg}"),
                vec![crate::error::ErrorRecommendation::suggestion_only(
                    "Border validation failed".to_string(),
                    "Ensure all border characters are valid and visible".to_string(),
                )],
            )
        })?;
        Ok(BorderStyle::Custom(chars))
    }
}

/// Utility functions for working with border styles
pub struct BorderStyleUtils;

impl BorderStyleUtils {
    /// Get the effective border width for a style (0 for None, 1 for others)
    #[must_use]
    pub fn get_border_width(style: &BorderStyle) -> usize {
        match style {
            BorderStyle::None => 0,
            _ => 1,
        }
    }

    /// Check if two border styles are equivalent
    #[must_use]
    pub fn styles_equal(a: &BorderStyle, b: &BorderStyle) -> bool {
        match (a, b) {
            (BorderStyle::None, BorderStyle::None)
            | (BorderStyle::Single, BorderStyle::Single)
            | (BorderStyle::Double, BorderStyle::Double)
            | (BorderStyle::Round, BorderStyle::Round)
            | (BorderStyle::Bold, BorderStyle::Bold)
            | (BorderStyle::SingleDouble, BorderStyle::SingleDouble)
            | (BorderStyle::DoubleSingle, BorderStyle::DoubleSingle)
            | (BorderStyle::Classic, BorderStyle::Classic) => true,
            (BorderStyle::Custom(a_chars), BorderStyle::Custom(b_chars)) => {
                a_chars.top_left == b_chars.top_left
                    && a_chars.top_right == b_chars.top_right
                    && a_chars.bottom_left == b_chars.bottom_left
                    && a_chars.bottom_right == b_chars.bottom_right
                    && a_chars.left == b_chars.left
                    && a_chars.right == b_chars.right
                    && a_chars.top == b_chars.top
                    && a_chars.bottom == b_chars.bottom
            }
            _ => false,
        }
    }

    /// Get a preview string showing what the border style looks like
    ///
    /// # Errors
    ///
    /// Returns an error if the border style contains invalid characters.
    pub fn preview(style: &BorderStyle) -> Result<String, BoxenError> {
        let chars = style.get_chars()?;
        if matches!(style, BorderStyle::None) {
            return Ok("(no border)".to_string());
        }

        Ok(format!(
            "{}{}{}\n{} {}\n{}{}{}",
            chars.top_left,
            chars.top,
            chars.top_right,
            chars.left,
            chars.right,
            chars.bottom_left,
            chars.bottom,
            chars.bottom_right
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_border_style_get_chars() {
        assert!(BorderStyle::Single.get_chars().is_ok());
        assert!(BorderStyle::Double.get_chars().is_ok());
        assert!(BorderStyle::Round.get_chars().is_ok());
        assert!(BorderStyle::Bold.get_chars().is_ok());
        assert!(BorderStyle::SingleDouble.get_chars().is_ok());
        assert!(BorderStyle::DoubleSingle.get_chars().is_ok());
        assert!(BorderStyle::Classic.get_chars().is_ok());
        assert!(BorderStyle::None.get_chars().is_ok());
    }

    #[test]
    fn test_border_style_visibility() {
        assert!(!BorderStyle::None.is_visible());
        assert!(BorderStyle::Single.is_visible());
        assert!(BorderStyle::Double.is_visible());
        assert!(BorderStyle::Round.is_visible());
        assert!(BorderStyle::Bold.is_visible());
        assert!(BorderStyle::Classic.is_visible());
    }

    #[test]
    fn test_border_style_names() {
        assert_eq!(BorderStyle::None.name(), "none");
        assert_eq!(BorderStyle::Single.name(), "single");
        assert_eq!(BorderStyle::Double.name(), "double");
        assert_eq!(BorderStyle::Round.name(), "round");
        assert_eq!(BorderStyle::Bold.name(), "bold");
        assert_eq!(BorderStyle::SingleDouble.name(), "singleDouble");
        assert_eq!(BorderStyle::DoubleSingle.name(), "doubleSingle");
        assert_eq!(BorderStyle::Classic.name(), "classic");
        assert_eq!(BorderStyle::Custom(BorderChars::single()).name(), "custom");
    }

    #[test]
    fn test_border_style_from_name() {
        assert!(matches!(
            BorderStyle::from_name("single").unwrap(),
            BorderStyle::Single
        ));
        assert!(matches!(
            BorderStyle::from_name("double").unwrap(),
            BorderStyle::Double
        ));
        assert!(matches!(
            BorderStyle::from_name("round").unwrap(),
            BorderStyle::Round
        ));
        assert!(matches!(
            BorderStyle::from_name("bold").unwrap(),
            BorderStyle::Bold
        ));
        assert!(matches!(
            BorderStyle::from_name("classic").unwrap(),
            BorderStyle::Classic
        ));
        assert!(matches!(
            BorderStyle::from_name("none").unwrap(),
            BorderStyle::None
        ));

        // Test case insensitive
        assert!(matches!(
            BorderStyle::from_name("SINGLE").unwrap(),
            BorderStyle::Single
        ));

        // Test underscore variants
        assert!(matches!(
            BorderStyle::from_name("single_double").unwrap(),
            BorderStyle::SingleDouble
        ));
        assert!(matches!(
            BorderStyle::from_name("double_single").unwrap(),
            BorderStyle::DoubleSingle
        ));
    }

    #[test]
    fn test_border_style_from_name_invalid() {
        let result = BorderStyle::from_name("invalid");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unknown border style")
        );
    }

    #[test]
    fn test_available_styles() {
        let styles = BorderStyle::available_styles();
        assert!(styles.contains(&"single"));
        assert!(styles.contains(&"double"));
        assert!(styles.contains(&"round"));
        assert!(styles.contains(&"bold"));
        assert!(styles.contains(&"classic"));
        assert!(styles.contains(&"none"));
        assert_eq!(styles.len(), 8);
    }

    #[test]
    fn test_custom_border_style() {
        let chars = BorderChars::single();
        let style = BorderStyle::custom(chars).unwrap();
        assert!(matches!(style, BorderStyle::Custom(_)));
    }

    #[test]
    fn test_custom_border_style_validation_error() {
        let chars = BorderChars {
            top_left: ' ', // Invalid whitespace
            ..BorderChars::single()
        };
        let result = BorderStyle::custom(chars);
        assert!(result.is_err());
    }

    #[test]
    fn test_border_width() {
        assert_eq!(BorderStyleUtils::get_border_width(&BorderStyle::None), 0);
        assert_eq!(BorderStyleUtils::get_border_width(&BorderStyle::Single), 1);
        assert_eq!(BorderStyleUtils::get_border_width(&BorderStyle::Double), 1);
        assert_eq!(BorderStyleUtils::get_border_width(&BorderStyle::Round), 1);
        assert_eq!(BorderStyleUtils::get_border_width(&BorderStyle::Bold), 1);
        assert_eq!(BorderStyleUtils::get_border_width(&BorderStyle::Classic), 1);
    }

    #[test]
    fn test_styles_equal() {
        assert!(BorderStyleUtils::styles_equal(
            &BorderStyle::Single,
            &BorderStyle::Single
        ));
        assert!(BorderStyleUtils::styles_equal(
            &BorderStyle::None,
            &BorderStyle::None
        ));
        assert!(!BorderStyleUtils::styles_equal(
            &BorderStyle::Single,
            &BorderStyle::Double
        ));

        let custom1 = BorderStyle::Custom(BorderChars::single());
        let custom2 = BorderStyle::Custom(BorderChars::single());
        let custom3 = BorderStyle::Custom(BorderChars::double());

        assert!(BorderStyleUtils::styles_equal(&custom1, &custom2));
        assert!(!BorderStyleUtils::styles_equal(&custom1, &custom3));
    }

    #[test]
    fn test_border_preview() {
        let preview = BorderStyleUtils::preview(&BorderStyle::Single).unwrap();
        assert!(preview.contains(''));
        assert!(preview.contains(''));
        assert!(preview.contains(''));
        assert!(preview.contains(''));

        let none_preview = BorderStyleUtils::preview(&BorderStyle::None).unwrap();
        assert_eq!(none_preview, "(no border)");
    }

    #[test]
    fn test_custom_border_get_chars() {
        let chars = BorderChars::single();
        let style = BorderStyle::Custom(chars);
        let retrieved_chars = style.get_chars().unwrap();

        assert_eq!(retrieved_chars.top_left, chars.top_left);
        assert_eq!(retrieved_chars.top_right, chars.top_right);
        assert_eq!(retrieved_chars.bottom_left, chars.bottom_left);
        assert_eq!(retrieved_chars.bottom_right, chars.bottom_right);
    }

    #[test]
    fn test_custom_border_validation_in_get_chars() {
        let invalid_chars = BorderChars {
            top_left: ' ', // Invalid whitespace
            ..BorderChars::single()
        };
        let style = BorderStyle::Custom(invalid_chars);
        let result = style.get_chars();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Custom border validation failed")
        );
    }
}