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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/// Text alignment functionality
use crate::memory::pool::with_pooled_string;
use crate::options::{Spacing, TextAlignment};
use crate::text::measurement::text_width;

/// Align a single line of text within a given width.
///
/// Optimized version that pre-allocates string capacity and uses efficient
/// string building to minimize allocations.
#[must_use]
pub fn align_line(line: &str, alignment: TextAlignment, width: usize) -> String {
    let line_width = text_width(line);

    // If line is already wider than target width, return as-is
    if line_width >= width {
        return line.to_string();
    }

    let padding_needed = width - line_width;

    // Use pooled buffer for result
    with_pooled_string(|result| {
        // Reserve capacity upfront to avoid reallocations
        result.reserve(width);

        match alignment {
            TextAlignment::Left => {
                result.push_str(line);
                result.extend(std::iter::repeat_n(' ', padding_needed));
            }
            TextAlignment::Right => {
                result.extend(std::iter::repeat_n(' ', padding_needed));
                result.push_str(line);
            }
            TextAlignment::Center => {
                let left_padding = padding_needed / 2;
                let right_padding = padding_needed - left_padding;
                result.extend(std::iter::repeat_n(' ', left_padding));
                result.push_str(line);
                result.extend(std::iter::repeat_n(' ', right_padding));
            }
        }

        result.as_str().to_string()
    })
}

/// Align multiple lines of text within a given width.
///
/// Optimized version that pre-allocates the result vector to avoid reallocations.
#[must_use]
pub fn align_lines(lines: &[String], alignment: TextAlignment, width: usize) -> Vec<String> {
    let mut result = Vec::with_capacity(lines.len());

    for line in lines {
        result.push(align_line(line, alignment, width));
    }

    result
}

/// Apply padding to text content
#[must_use]
pub fn apply_padding(lines: &[String], padding: &Spacing, content_width: usize) -> Vec<String> {
    let mut result = Vec::new();

    // Add top padding (empty lines)
    for _ in 0..padding.top {
        result.push(" ".repeat(content_width));
    }

    // Add left and right padding to each content line
    for line in lines {
        let mut padded_line = String::with_capacity(content_width);

        // Left padding
        padded_line.push_str(&" ".repeat(padding.left));

        // Original content
        padded_line.push_str(line);

        // Right padding (fill to content width)
        let current_width = text_width(&padded_line);
        if current_width < content_width {
            padded_line.push_str(&" ".repeat(content_width - current_width));
        }

        result.push(padded_line);
    }

    // Add bottom padding (empty lines)
    for _ in 0..padding.bottom {
        result.push(" ".repeat(content_width));
    }

    result
}

/// Calculate the content width needed for text with padding
#[must_use]
pub fn calculate_content_width(text_lines: &[String], padding: &Spacing) -> usize {
    let max_text_width = text_lines
        .iter()
        .map(|line| text_width(line))
        .max()
        .unwrap_or(0);

    max_text_width + padding.left + padding.right
}

/// Calculate the content height needed for text with padding
#[must_use]
pub fn calculate_content_height(text_lines: &[String], padding: &Spacing) -> usize {
    text_lines.len() + padding.top + padding.bottom
}

/// Process text with alignment and padding
#[must_use]
pub fn process_text_alignment(
    text: &str,
    alignment: TextAlignment,
    padding: &Spacing,
    target_width: Option<usize>,
) -> Vec<String> {
    // Handle empty text case - create one empty line
    let lines: Vec<String> = if text.is_empty() {
        vec![String::new()]
    } else {
        text.lines().map(std::string::ToString::to_string).collect()
    };

    // Calculate dimensions
    let content_width = if let Some(width) = target_width {
        // Use specified width, accounting for padding
        if width > padding.left + padding.right {
            width - padding.left - padding.right
        } else {
            // When target width is too small, use natural content width
            lines.iter().map(|line| text_width(line)).max().unwrap_or(0)
        }
    } else {
        // Use natural width of content
        lines.iter().map(|line| text_width(line)).max().unwrap_or(0)
    };

    // Align the text lines
    let aligned_lines = align_lines(&lines, alignment, content_width);

    // Apply padding
    let total_content_width = content_width + padding.left + padding.right;
    apply_padding(&aligned_lines, padding, total_content_width)
}

/// Process text with alignment, padding, and height constraints
#[must_use]
pub fn process_text_with_height_constraints(
    text: &str,
    alignment: TextAlignment,
    padding: &Spacing,
    target_width: Option<usize>,
    max_content_height: Option<usize>,
) -> Vec<String> {
    // Handle empty text case - create one empty line
    let lines: Vec<String> = if text.is_empty() {
        vec![String::new()]
    } else {
        text.lines().map(std::string::ToString::to_string).collect()
    };

    // Calculate dimensions
    let content_width = if let Some(width) = target_width {
        // Use specified width, accounting for padding
        if width > padding.left + padding.right {
            width - padding.left - padding.right
        } else {
            // When target width is too small, use natural content width
            lines.iter().map(|line| text_width(line)).max().unwrap_or(0)
        }
    } else {
        // Use natural width of content
        lines.iter().map(|line| text_width(line)).max().unwrap_or(0)
    };

    // Apply height constraints if specified
    let constrained_lines = if let Some(max_height) = max_content_height {
        apply_height_constraints(&lines, max_height)
    } else {
        lines
    };

    // Align the text lines
    let aligned_lines = align_lines(&constrained_lines, alignment, content_width);

    // Apply padding
    let total_content_width = content_width + padding.left + padding.right;
    apply_padding(&aligned_lines, padding, total_content_width)
}

/// Apply height constraints to text lines - truncate or pad as needed
#[must_use]
pub fn apply_height_constraints(lines: &[String], max_height: usize) -> Vec<String> {
    if max_height == 0 {
        // If max height is 0, return empty content
        return vec![];
    }

    if lines.len() <= max_height {
        // Content fits within height constraint - pad if needed
        let mut result = lines.to_vec();

        // Add empty lines to reach the target height
        while result.len() < max_height {
            result.push(String::new());
        }

        result
    } else {
        // Content exceeds height constraint - truncate
        lines[..max_height].to_vec()
    }
}

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

    #[test]
    fn test_align_line_left() {
        assert_eq!(align_line("hello", TextAlignment::Left, 10), "hello     ");
        assert_eq!(align_line("", TextAlignment::Left, 5), "     ");
        assert_eq!(align_line("exact", TextAlignment::Left, 5), "exact");
    }

    #[test]
    fn test_align_line_right() {
        assert_eq!(align_line("hello", TextAlignment::Right, 10), "     hello");
        assert_eq!(align_line("", TextAlignment::Right, 5), "     ");
        assert_eq!(align_line("exact", TextAlignment::Right, 5), "exact");
    }

    #[test]
    fn test_align_line_center() {
        assert_eq!(align_line("hello", TextAlignment::Center, 10), "  hello   ");
        assert_eq!(align_line("hi", TextAlignment::Center, 6), "  hi  ");
        assert_eq!(align_line("odd", TextAlignment::Center, 7), "  odd  "); // Left-biased for odd padding
        assert_eq!(align_line("", TextAlignment::Center, 4), "    ");
    }

    #[test]
    fn test_align_line_with_unicode() {
        // Wide characters should be handled correctly
        assert_eq!(align_line("你好", TextAlignment::Left, 6), "你好  ");
        assert_eq!(align_line("你好", TextAlignment::Right, 6), "  你好");
        assert_eq!(align_line("你好", TextAlignment::Center, 6), " 你好 ");
    }

    #[test]
    fn test_align_line_with_ansi() {
        let colored_text = "\x1b[31mred\x1b[0m";
        assert_eq!(
            align_line(colored_text, TextAlignment::Left, 6),
            format!("{colored_text}   ")
        );
        assert_eq!(
            align_line(colored_text, TextAlignment::Right, 6),
            format!("   {colored_text}")
        );
    }

    #[test]
    fn test_align_line_overflow() {
        // When text is wider than target, return as-is
        assert_eq!(align_line("toolong", TextAlignment::Left, 5), "toolong");
        assert_eq!(align_line("toolong", TextAlignment::Right, 5), "toolong");
        assert_eq!(align_line("toolong", TextAlignment::Center, 5), "toolong");
    }

    #[test]
    fn test_align_lines() {
        let lines = vec!["hello".to_string(), "world".to_string()];
        let result = align_lines(&lines, TextAlignment::Center, 10);
        assert_eq!(result, vec!["  hello   ", "  world   "]);
    }

    #[test]
    fn test_apply_padding_basic() {
        let lines = vec!["hello".to_string(), "world".to_string()];
        let padding = Spacing {
            top: 1,
            right: 2,
            bottom: 1,
            left: 2,
        };
        let result = apply_padding(&lines, &padding, 9); // 5 + 2 + 2 = 9

        assert_eq!(result.len(), 4); // 1 top + 2 content + 1 bottom
        assert_eq!(result[0], "         "); // Top padding line
        assert_eq!(result[1], "  hello  "); // First content line with padding
        assert_eq!(result[2], "  world  "); // Second content line with padding
        assert_eq!(result[3], "         "); // Bottom padding line
    }

    #[test]
    fn test_apply_padding_no_padding() {
        let lines = vec!["hello".to_string()];
        let padding = Spacing::default();
        let result = apply_padding(&lines, &padding, 5);

        assert_eq!(result.len(), 1);
        assert_eq!(result[0], "hello");
    }

    #[test]
    fn test_calculate_content_width() {
        let lines = vec!["hello".to_string(), "world!".to_string()];
        let padding = Spacing {
            top: 0,
            right: 2,
            bottom: 0,
            left: 3,
        };

        assert_eq!(calculate_content_width(&lines, &padding), 11); // 6 + 3 + 2
    }

    #[test]
    fn test_calculate_content_height() {
        let lines = vec!["hello".to_string(), "world".to_string()];
        let padding = Spacing {
            top: 1,
            right: 0,
            bottom: 2,
            left: 0,
        };

        assert_eq!(calculate_content_height(&lines, &padding), 5); // 2 + 1 + 2
    }

    #[test]
    fn test_process_text_alignment_basic() {
        let text = "hello\nworld";
        let padding = Spacing {
            top: 1,
            right: 1,
            bottom: 1,
            left: 1,
        };
        let result = process_text_alignment(text, TextAlignment::Center, &padding, Some(10));

        assert_eq!(result.len(), 4); // 1 top + 2 content + 1 bottom
        // Content width should be 10 - 1 - 1 = 8
        // "hello" centered in 8 chars: " hello  "
        // With left/right padding: " " + " hello  " + " " = "  hello   "
        assert_eq!(result[1], "  hello   ");
        assert_eq!(result[2], "  world   ");
    }

    #[test]
    fn test_process_text_alignment_no_target_width() {
        let text = "hello\nworld!";
        let padding = Spacing {
            top: 0,
            right: 1,
            bottom: 0,
            left: 1,
        };
        let result = process_text_alignment(text, TextAlignment::Left, &padding, None);

        // Natural width is 6 ("world!"), with padding becomes 8
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], " hello  ");
        assert_eq!(result[1], " world! ");
    }

    #[test]
    fn test_process_text_alignment_with_unicode() {
        let text = "你好\nworld";
        let padding = Spacing {
            top: 0,
            right: 1,
            bottom: 0,
            left: 1,
        };
        let result = process_text_alignment(text, TextAlignment::Right, &padding, Some(10));

        // Content width: 10 - 1 - 1 = 8
        // "你好" (width 4) right-aligned in 8: "    你好"
        // "world" (width 5) right-aligned in 8: "   world"
        assert_eq!(result[0], "     你好 ");
        assert_eq!(result[1], "    world ");
    }

    #[test]
    fn test_process_text_alignment_minimum_width() {
        let text = "hello";
        let padding = Spacing {
            top: 0,
            right: 5,
            bottom: 0,
            left: 5,
        };
        let result = process_text_alignment(text, TextAlignment::Left, &padding, Some(5));

        // Target width 5 is less than padding (5+5=10), so use natural content width (5)
        // Total width becomes 5 (content) + 5 (left) + 5 (right) = 15
        assert_eq!(result[0], "     hello     ");
    }

    #[test]
    fn test_empty_text() {
        let text = "";
        let padding = Spacing {
            top: 1,
            right: 1,
            bottom: 1,
            left: 1,
        };
        let result = process_text_alignment(text, TextAlignment::Center, &padding, Some(6));

        assert_eq!(result.len(), 3); // 1 top + 1 content + 1 bottom
        assert_eq!(result[0], "      "); // Top padding
        assert_eq!(result[1], "      "); // Empty content with padding  
        assert_eq!(result[2], "      "); // Bottom padding
    }

    #[test]
    fn test_apply_height_constraints_no_constraint() {
        let lines = vec![
            "line1".to_string(),
            "line2".to_string(),
            "line3".to_string(),
        ];
        let result = apply_height_constraints(&lines, 5);

        // Should pad to reach target height
        assert_eq!(result.len(), 5);
        assert_eq!(result[0], "line1");
        assert_eq!(result[1], "line2");
        assert_eq!(result[2], "line3");
        assert_eq!(result[3], ""); // Padding
        assert_eq!(result[4], ""); // Padding
    }

    #[test]
    fn test_apply_height_constraints_truncation() {
        let lines = vec![
            "line1".to_string(),
            "line2".to_string(),
            "line3".to_string(),
            "line4".to_string(),
            "line5".to_string(),
        ];
        let result = apply_height_constraints(&lines, 3);

        // Should truncate to max height
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], "line1");
        assert_eq!(result[1], "line2");
        assert_eq!(result[2], "line3");
    }

    #[test]
    fn test_apply_height_constraints_exact_fit() {
        let lines = vec!["line1".to_string(), "line2".to_string()];
        let result = apply_height_constraints(&lines, 2);

        // Should return as-is when exact fit
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], "line1");
        assert_eq!(result[1], "line2");
    }

    #[test]
    fn test_apply_height_constraints_zero_height() {
        let lines = vec!["line1".to_string(), "line2".to_string()];
        let result = apply_height_constraints(&lines, 0);

        // Should return empty when max height is 0
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_apply_height_constraints_empty_input() {
        let lines: Vec<String> = vec![];
        let result = apply_height_constraints(&lines, 3);

        // Should pad empty input to target height
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], "");
        assert_eq!(result[1], "");
        assert_eq!(result[2], "");
    }

    #[test]
    fn test_process_text_with_height_constraints_padding() {
        let text = "hello\nworld";
        let padding = Spacing {
            top: 1,
            right: 1,
            bottom: 1,
            left: 1,
        };
        let result = process_text_with_height_constraints(
            text,
            TextAlignment::Left,
            &padding,
            Some(10),
            Some(4), // Max content height of 4, but we only have 2 lines
        );

        // Should have: 1 top padding + 4 content lines (2 actual + 2 empty) + 1 bottom padding = 6 total
        assert_eq!(result.len(), 6);

        // Check content lines (accounting for left/right padding)
        assert_eq!(result[1], " hello    "); // Content with padding
        assert_eq!(result[2], " world    "); // Content with padding
        assert_eq!(result[3], "          "); // Empty content line with padding
        assert_eq!(result[4], "          "); // Empty content line with padding
    }

    #[test]
    fn test_process_text_with_height_constraints_truncation() {
        let text = "line1\nline2\nline3\nline4\nline5";
        let padding = Spacing {
            top: 0,
            right: 1,
            bottom: 0,
            left: 1,
        };
        let result = process_text_with_height_constraints(
            text,
            TextAlignment::Left,
            &padding,
            Some(10),
            Some(3), // Max content height of 3, but we have 5 lines
        );

        // Should have exactly 3 content lines (truncated)
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], " line1    ");
        assert_eq!(result[1], " line2    ");
        assert_eq!(result[2], " line3    ");
    }

    #[test]
    fn test_process_text_with_height_constraints_no_constraint() {
        let text = "hello\nworld";
        let padding = Spacing {
            top: 0,
            right: 1,
            bottom: 0,
            left: 1,
        };
        let result = process_text_with_height_constraints(
            text,
            TextAlignment::Center,
            &padding,
            Some(10),
            None, // No height constraint
        );

        // Should process normally without height constraints
        assert_eq!(result.len(), 2);
        assert!(result[0].contains("hello"));
        assert!(result[1].contains("world"));
    }

    #[test]
    fn test_process_text_with_height_constraints_empty_text() {
        let text = "";
        let padding = Spacing {
            top: 0,
            right: 1,
            bottom: 0,
            left: 1,
        };
        let result = process_text_with_height_constraints(
            text,
            TextAlignment::Center,
            &padding,
            Some(8),
            Some(3), // Height constraint of 3
        );

        // Should create 3 empty lines
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], "        "); // Empty line with padding
        assert_eq!(result[1], "        "); // Empty line with padding
        assert_eq!(result[2], "        "); // Empty line with padding
    }

    #[test]
    fn test_height_constraints_with_unicode() {
        let text = "你好\n世界\n测试\n内容";
        let padding = Spacing::default();
        let result = process_text_with_height_constraints(
            text,
            TextAlignment::Left,
            &padding,
            None,
            Some(2), // Truncate to 2 lines
        );

        assert_eq!(result.len(), 2);
        assert_eq!(result[0], "你好");
        assert_eq!(result[1], "世界");
    }
}