rnk 0.19.1

A React-like declarative terminal UI framework for Rust, inspired by Ink and Bubbletea
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Text measurement utilities

use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

#[inline]
fn grapheme_width(grapheme: &str) -> usize {
    UnicodeWidthStr::width(grapheme)
}

#[inline]
fn fits_within_width(text: &str, max_width: usize) -> bool {
    if let Some(width) = ascii_width_fast_path(text) {
        return width <= max_width;
    }

    let mut width = 0;
    for grapheme in text.graphemes(true) {
        width += grapheme_width(grapheme);
        if width > max_width {
            return false;
        }
    }
    true
}

fn take_prefix_by_width(text: &str, max_width: usize) -> String {
    if let Some(width) = ascii_width_fast_path(text) {
        if width <= max_width {
            return text.to_string();
        }
        return text[..max_width].to_string();
    }

    let mut result = String::new();
    let mut width = 0;
    for grapheme in text.graphemes(true) {
        let grapheme_width = grapheme_width(grapheme);
        if width + grapheme_width > max_width {
            break;
        }
        result.push_str(grapheme);
        width += grapheme_width;
    }
    result
}

/// Measure the display width of text using grapheme clusters
///
/// This function properly handles:
/// - CJK characters (width = 2)
/// - Emoji sequences (including ZWJ sequences like ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ)
/// - Combining characters (e.g., รฉ = e + combining acute)
/// - Zero-width characters
pub fn measure_text_width(text: &str) -> usize {
    if let Some(width) = ascii_width_fast_path(text) {
        return width;
    }

    text.graphemes(true).map(grapheme_width).sum()
}

/// Measure the display width using grapheme clusters (alias for measure_text_width)
pub fn display_width(text: &str) -> usize {
    measure_text_width(text)
}

/// Measure text dimensions (width, height)
pub fn measure_text(text: &str) -> (usize, usize) {
    if let Some(dimensions) = ascii_measure_text_dimensions_fast_path(text) {
        return dimensions;
    }

    let mut height = 0usize;
    let mut width = 0usize;

    for line in text.lines() {
        height += 1;
        width = width.max(measure_text_width(line));
    }

    if height == 0 {
        height = 1;
    }

    (width, height)
}

/// Wrap text to fit within a maximum width (grapheme-aware)
pub fn wrap_text(text: &str, max_width: usize) -> String {
    if max_width == 0 {
        return String::new();
    }

    if text.is_empty() {
        return String::new();
    }

    if let Some(width) = ascii_width_fast_path(text) {
        if width <= max_width {
            return text.to_string();
        }

        let line_breaks = width.div_ceil(max_width).saturating_sub(1);
        let mut result = String::with_capacity(text.len() + line_breaks);
        let mut start = 0usize;
        while start < width {
            let end = (start + max_width).min(width);
            result.push_str(&text[start..end]);
            if end < width {
                result.push('\n');
            }
            start = end;
        }
        return result;
    }

    let mut result = String::with_capacity(text.len());
    let mut current_width = 0;

    for grapheme in text.graphemes(true) {
        let grapheme_width = grapheme_width(grapheme);

        if grapheme == "\n" {
            result.push('\n');
            current_width = 0;
        } else if current_width + grapheme_width > max_width {
            result.push('\n');
            result.push_str(grapheme);
            current_width = grapheme_width;
        } else {
            result.push_str(grapheme);
            current_width += grapheme_width;
        }
    }

    result
}

/// Truncate text to fit within a maximum width (grapheme-aware)
pub fn truncate_text(text: &str, max_width: usize, ellipsis: &str) -> String {
    if let (Some(text_width), Some(ellipsis_width)) =
        (ascii_width_fast_path(text), ascii_width_fast_path(ellipsis))
    {
        if text_width <= max_width {
            return text.to_string();
        }

        if max_width <= ellipsis_width {
            return ellipsis[..max_width].to_string();
        }

        let target_width = max_width - ellipsis_width;
        let mut result = String::with_capacity(max_width);
        result.push_str(&text[..target_width]);
        result.push_str(ellipsis);
        return result;
    }

    if fits_within_width(text, max_width) {
        return text.to_string();
    }

    let ellipsis_width = measure_text_width(ellipsis);
    if max_width <= ellipsis_width {
        return take_prefix_by_width(ellipsis, max_width);
    }

    let target_width = max_width - ellipsis_width;
    let mut result = String::new();
    let mut current_width = 0;

    for grapheme in text.graphemes(true) {
        let grapheme_width = grapheme_width(grapheme);
        if current_width + grapheme_width > target_width {
            break;
        }
        result.push_str(grapheme);
        current_width += grapheme_width;
    }

    result.push_str(ellipsis);
    result
}

/// Truncate text from the start (grapheme-aware)
pub fn truncate_start(text: &str, max_width: usize, ellipsis: &str) -> String {
    if let (Some(text_width), Some(ellipsis_width)) =
        (ascii_width_fast_path(text), ascii_width_fast_path(ellipsis))
    {
        if text_width <= max_width {
            return text.to_string();
        }

        if max_width <= ellipsis_width {
            return ellipsis[..max_width].to_string();
        }

        let target_width = max_width - ellipsis_width;
        let start = text_width - target_width;
        let mut result = String::with_capacity(max_width);
        result.push_str(ellipsis);
        result.push_str(&text[start..]);
        return result;
    }

    if fits_within_width(text, max_width) {
        return text.to_string();
    }

    let ellipsis_width = measure_text_width(ellipsis);
    if max_width <= ellipsis_width {
        return take_prefix_by_width(ellipsis, max_width);
    }

    let target_width = max_width - ellipsis_width;
    let mut result = String::new();
    let mut current_width = 0;
    let mut end_graphemes = Vec::new();

    for grapheme in text.graphemes(true).rev() {
        let grapheme_width = grapheme_width(grapheme);
        if current_width + grapheme_width > target_width {
            break;
        }
        end_graphemes.push(grapheme);
        current_width += grapheme_width;
    }

    end_graphemes.reverse();
    result.push_str(ellipsis);
    for g in end_graphemes {
        result.push_str(g);
    }
    result
}

/// Truncate text from the middle (grapheme-aware)
pub fn truncate_middle(text: &str, max_width: usize, ellipsis: &str) -> String {
    if let (Some(text_width), Some(ellipsis_width)) =
        (ascii_width_fast_path(text), ascii_width_fast_path(ellipsis))
    {
        if text_width <= max_width {
            return text.to_string();
        }

        if max_width <= ellipsis_width {
            return ellipsis[..max_width].to_string();
        }

        let available = max_width - ellipsis_width;
        let left_width = available / 2;
        let right_width = available - left_width;
        let right_start = text_width - right_width;

        let mut result = String::with_capacity(max_width);
        result.push_str(&text[..left_width]);
        result.push_str(ellipsis);
        result.push_str(&text[right_start..]);
        return result;
    }

    if fits_within_width(text, max_width) {
        return text.to_string();
    }

    let ellipsis_width = measure_text_width(ellipsis);
    if max_width <= ellipsis_width {
        return take_prefix_by_width(ellipsis, max_width);
    }

    let available = max_width - ellipsis_width;
    let left_width = available / 2;
    let right_width = available - left_width;

    // Build left part
    let mut left = String::new();
    let mut current_width = 0;
    for grapheme in text.graphemes(true) {
        let grapheme_width = grapheme_width(grapheme);
        if current_width + grapheme_width > left_width {
            break;
        }
        left.push_str(grapheme);
        current_width += grapheme_width;
    }

    // Build right part
    let mut right_graphemes = Vec::new();
    current_width = 0;
    for grapheme in text.graphemes(true).rev() {
        let grapheme_width = grapheme_width(grapheme);
        if current_width + grapheme_width > right_width {
            break;
        }
        right_graphemes.push(grapheme);
        current_width += grapheme_width;
    }
    right_graphemes.reverse();

    let mut right = String::new();
    for g in right_graphemes {
        right.push_str(g);
    }

    format!("{}{}{}", left, ellipsis, right)
}

/// Count wrapped lines for a text block without allocating wrapped content.
pub(crate) fn count_wrapped_lines_by_width(text: &str, max_width: usize) -> usize {
    if text.is_empty() {
        return 1;
    }

    if max_width == 0 {
        return 1;
    }

    if let Some(lines) = ascii_wrapped_line_count_fast_path(text, max_width) {
        return lines;
    }

    let mut lines = 1usize;
    let mut current_width = 0usize;
    let mut ends_with_newline = false;

    for grapheme in text.graphemes(true) {
        if grapheme.ends_with('\n') {
            lines += 1;
            current_width = 0;
            ends_with_newline = true;
            continue;
        }
        ends_with_newline = false;

        let grapheme_width = grapheme_width(grapheme);
        if current_width + grapheme_width > max_width {
            lines += 1;
            current_width = grapheme_width;
        } else {
            current_width += grapheme_width;
        }
    }

    // Match `str::lines()` semantics used by the previous implementation:
    // a trailing '\n' does not produce an extra final empty line.
    if ends_with_newline && lines > 1 {
        lines -= 1;
    }

    lines.max(1)
}

fn ascii_measure_text_dimensions_fast_path(text: &str) -> Option<(usize, usize)> {
    if text.is_empty() {
        return Some((0, 1));
    }

    let bytes = text.as_bytes();
    let mut max_width = 0usize;
    let mut current_width = 0usize;
    let mut height = 1usize;
    let mut ends_with_line_break = false;
    let mut i = 0usize;

    while i < bytes.len() {
        let byte = bytes[i];

        if byte == b'\n' {
            max_width = max_width.max(current_width);
            current_width = 0;
            height += 1;
            ends_with_line_break = true;
            i += 1;
            continue;
        }

        if byte == b'\r' && i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
            max_width = max_width.max(current_width);
            current_width = 0;
            height += 1;
            ends_with_line_break = true;
            i += 2;
            continue;
        }

        if !byte.is_ascii() || byte < 0x20 || byte == 0x7f {
            return None;
        }

        current_width += 1;
        ends_with_line_break = false;
        i += 1;
    }

    max_width = max_width.max(current_width);
    if ends_with_line_break && height > 1 {
        height -= 1;
    }

    Some((max_width, height.max(1)))
}

fn ascii_wrapped_line_count_fast_path(text: &str, max_width: usize) -> Option<usize> {
    if text.is_empty() {
        return Some(1);
    }

    let bytes = text.as_bytes();
    let mut lines = 1usize;
    let mut current_width = 0usize;
    let mut ends_with_line_break = false;
    let mut i = 0usize;

    while i < bytes.len() {
        let byte = bytes[i];

        if byte == b'\n' {
            lines += 1;
            current_width = 0;
            ends_with_line_break = true;
            i += 1;
            continue;
        }

        if byte == b'\r' && i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
            lines += 1;
            current_width = 0;
            ends_with_line_break = true;
            i += 2;
            continue;
        }

        if !byte.is_ascii() || byte < 0x20 || byte == 0x7f {
            return None;
        }

        if current_width == max_width {
            lines += 1;
            current_width = 1;
        } else {
            current_width += 1;
        }
        ends_with_line_break = false;
        i += 1;
    }

    if ends_with_line_break && lines > 1 {
        lines -= 1;
    }

    Some(lines.max(1))
}

fn ascii_width_fast_path(text: &str) -> Option<usize> {
    let bytes = text.as_bytes();

    if !bytes.iter().all(|b| b.is_ascii() && *b > 0x1f && *b < 0x7f) {
        return None;
    }

    Some(bytes.len())
}

/// Pad text to a specific width
pub fn pad_text(text: &str, width: usize, align: TextAlign) -> String {
    let text_width = measure_text_width(text);

    if text_width >= width {
        return text.to_string();
    }

    let padding = width - text_width;

    let mut result = String::with_capacity(text.len() + padding);

    match align {
        TextAlign::Left => {
            result.push_str(text);
            result.extend(std::iter::repeat_n(' ', padding));
        }
        TextAlign::Right => {
            result.extend(std::iter::repeat_n(' ', padding));
            result.push_str(text);
        }
        TextAlign::Center => {
            let left_pad = padding / 2;
            let right_pad = padding - left_pad;
            result.extend(std::iter::repeat_n(' ', left_pad));
            result.push_str(text);
            result.extend(std::iter::repeat_n(' ', right_pad));
        }
    }

    result
}

/// Text alignment
#[derive(Debug, Clone, Copy, Default)]
pub enum TextAlign {
    #[default]
    Left,
    Right,
    Center,
}

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

    #[test]
    fn test_measure_ascii() {
        assert_eq!(measure_text_width("hello"), 5);
        assert_eq!(measure_text_width("hello world"), 11);
    }

    #[test]
    fn test_measure_unicode() {
        // Chinese characters are typically 2 cells wide
        assert_eq!(measure_text_width("ไฝ ๅฅฝ"), 4);
        assert_eq!(measure_text_width("Hello ไธ–็•Œ"), 10);
    }

    #[test]
    fn test_measure_text_dimensions() {
        let (w, h) = measure_text("hello\nworld");
        assert_eq!(w, 5);
        assert_eq!(h, 2);
    }

    #[test]
    fn test_wrap_text() {
        let wrapped = wrap_text("hello world", 6);
        assert!(wrapped.contains('\n'));
    }

    #[test]
    fn test_wrap_text_ascii_exact_chunks() {
        assert_eq!(wrap_text("abcdefgh", 3), "abc\ndef\ngh");
    }

    #[test]
    fn test_wrap_text_ascii_exact_multiple_chunks() {
        assert_eq!(wrap_text("abcdef", 3), "abc\ndef");
    }

    #[test]
    fn test_truncate_text() {
        let truncated = truncate_text("hello world", 8, "...");
        assert_eq!(truncated, "hello...");
    }

    #[test]
    fn test_truncate_start() {
        let truncated = truncate_start("hello world", 8, "...");
        assert_eq!(truncated, "...world");
    }

    #[test]
    fn test_truncate_middle() {
        let truncated = truncate_middle("hello world", 9, "...");
        assert_eq!(truncated, "hel...rld");
    }

    #[test]
    fn test_pad_text() {
        assert_eq!(pad_text("hi", 5, TextAlign::Left), "hi   ");
        assert_eq!(pad_text("hi", 5, TextAlign::Right), "   hi");
        assert_eq!(pad_text("hi", 5, TextAlign::Center), " hi  ");
    }

    #[test]
    fn test_grapheme_clusters_emoji() {
        // Family emoji (ZWJ sequence) - should be treated as 1 grapheme with width 2
        let family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ";
        let graphemes: Vec<&str> = family.graphemes(true).collect();
        assert_eq!(graphemes.len(), 1, "Family emoji should be 1 grapheme");
        // Note: Width may vary by terminal, but grapheme count should be 1
    }

    #[test]
    fn test_grapheme_clusters_combining() {
        // e + combining acute accent = 1 grapheme
        let combined = "รฉ"; // This is e + combining acute (2 code points)
        let graphemes: Vec<&str> = combined.graphemes(true).collect();
        // Note: The actual behavior depends on the string encoding
        // If it's precomposed (1 code point), it's 1 grapheme
        // If it's decomposed (2 code points), it should still be 1 grapheme
        assert!(graphemes.len() <= 2); // Either 1 or at most 2
    }

    #[test]
    fn test_truncate_preserves_graphemes() {
        // Truncating should not split grapheme clusters
        let text = "hello ไฝ ๅฅฝ";
        let truncated = truncate_text(text, 8, "โ€ฆ");
        // Should truncate cleanly without splitting Chinese characters
        assert!(measure_text_width(&truncated) <= 8);
    }

    #[test]
    fn test_zero_width_characters() {
        // Zero-width joiner should have width 0
        let zwj = "\u{200D}"; // Zero Width Joiner
        assert_eq!(measure_text_width(zwj), 0);
    }

    #[test]
    fn test_count_wrapped_lines_handles_crlf_like_lines() {
        let text = "line1\r\nline2\r\n";
        assert_eq!(
            count_wrapped_lines_by_width(text, 80),
            text.lines().count().max(1)
        );
    }

    #[test]
    fn test_measure_text_ascii_crlf() {
        assert_eq!(measure_text("ab\r\nc"), (2, 2));
    }

    #[test]
    fn test_measure_text_trailing_newline_semantics() {
        assert_eq!(measure_text("ab\n"), (2, 1));
        assert_eq!(measure_text("ab\r\n"), (2, 1));
    }

    #[test]
    fn test_count_wrapped_lines_ascii_with_wrap() {
        assert_eq!(count_wrapped_lines_by_width("abcdef", 3), 2);
    }
}