text_align/
text_align.rs

1/// Naive version (does not account for Unicode display widths)
2///
3/// Uses `chars().count()` to center content,
4/// which fails for emoji and CJK characters in terminal environments.
5pub fn print_naive_centered_box(content: &str) {
6    let total_width = 120;
7    let content_width = total_width - 2; // borders
8
9    let naive_pad = (content_width - content.chars().count()) / 2;
10
11    println!();
12    println!("┏{}┓", "━".repeat(content_width));
13    println!("┃{:width$}┃", "", width = content_width);
14    println!("┃{:pad$}{}{:pad$}┃", "", content, "", pad = naive_pad);
15    println!("┃{:width$}┃", "", width = content_width);
16    println!("┗{}┛", "━".repeat(content_width));
17}
18
19/// Fixed version using `runefix_core` for proper Unicode width support.
20///
21/// Uses `.rune_width()` to handle fullwidth CJK and emoji correctly.
22pub fn print_fixed_centered_box(content: &str) {
23    use runefix_core::RuneDisplayWidth;
24
25    let total_width = 120;
26    let content_width = total_width - 2;
27
28    let width = content.width();
29    let left_pad = (content_width - width) / 2;
30    let right_pad = content_width - width - left_pad;
31
32    println!();
33    println!("┏{}┓", "━".repeat(content_width));
34    println!("┃{:width$}┃", "", width = content_width);
35    println!("┃{:left$}{}{:right$}┃", "", content, "", left = left_pad, right = right_pad);
36    println!("┃{:width$}┃", "", width = content_width);
37    println!("┗{}┛", "━".repeat(content_width));
38}
39
40fn main() {
41    // ASCII only – looks the same
42    print_naive_centered_box("[NAIVE] Lorem ipsum dolor sit amet consectetur adipisicing elit.");
43    print_fixed_centered_box("[FIXED] Lorem ipsum dolor sit amet consectetur adipisicing elit.");
44
45    // Emoji – misaligned vs fixed
46    print_naive_centered_box("[NAIVE] National Language: 🇨🇳 🇯🇵 🇰🇷 🇫🇷 🇩🇪 🇪🇸 🇷🇺 🇬🇧 🇸🇬 🇦🇺 🇨🇦 🇺🇸");
47    print_fixed_centered_box("[FIXED] National Language: 🇨🇳 🇯🇵 🇰🇷 🇫🇷 🇩🇪 🇪🇸 🇷🇺 🇬🇧 🇸🇬 🇦🇺 🇨🇦 🇺🇸");
48
49    // CJK text – broken vs aligned
50    print_naive_centered_box("[NAIVE]《诗》「字」方正于九州,「かな」散らす桜の韻,「한글」물결처럼 퍼지네~");
51    print_fixed_centered_box("[FIXED]《诗》「字」方正于九州,「かな」散らす桜の韻,「한글」물결처럼 퍼지네~");
52}