rnk 0.17.2

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
//! Test renderer for unit testing
//!
//! Provides a side-effect-free renderer that can be used to verify
//! layout and rendering output without terminal interaction.

use std::collections::HashMap;
use unicode_width::UnicodeWidthChar;

use crate::core::{Display, Element, ElementId, Position};
use crate::layout::{Layout, LayoutEngine};
use crate::renderer::Output;

/// Test renderer configuration
#[derive(Debug, Clone)]
pub struct TestRenderer {
    width: u16,
    height: u16,
}

impl TestRenderer {
    /// Create a new test renderer with specified dimensions
    pub fn new(width: u16, height: u16) -> Self {
        Self { width, height }
    }

    /// Create a standard 80x24 terminal renderer
    pub fn standard() -> Self {
        Self::new(80, 24)
    }

    /// Get the width
    pub fn width(&self) -> u16 {
        self.width
    }

    /// Get the height
    pub fn height(&self) -> u16 {
        self.height
    }

    /// Render element and return plain text (no ANSI codes)
    pub fn render_to_plain(&self, element: &Element) -> String {
        let ansi = self.render_to_ansi(element);
        strip_ansi_codes(&ansi)
    }

    /// Render element and return string with ANSI codes
    pub fn render_to_ansi(&self, element: &Element) -> String {
        let mut engine = LayoutEngine::new();
        engine.compute(element, self.width, self.height);

        let mut output = Output::new(self.width, self.height);
        self.render_element(element, &engine, &mut output, 0.0, 0.0);
        output.render()
    }

    /// Get computed layouts for all elements
    pub fn get_layouts(&self, element: &Element) -> HashMap<ElementId, Layout> {
        let mut engine = LayoutEngine::new();
        engine.compute(element, self.width, self.height);
        engine.get_all_layouts()
    }

    /// Get layout for a specific element
    pub fn get_layout(&self, element: &Element) -> Option<Layout> {
        let mut engine = LayoutEngine::new();
        engine.compute(element, self.width, self.height);
        engine.get_layout(element.id)
    }

    /// Validate layout constraints
    pub fn validate_layout(&self, element: &Element) -> Result<(), LayoutError> {
        let layouts = self.get_layouts(element);

        for (id, layout) in &layouts {
            // Check non-negative coordinates
            if layout.x < 0.0 {
                return Err(LayoutError::NegativeCoordinate {
                    element_id: *id,
                    axis: "x",
                    value: layout.x,
                });
            }
            if layout.y < 0.0 {
                return Err(LayoutError::NegativeCoordinate {
                    element_id: *id,
                    axis: "y",
                    value: layout.y,
                });
            }

            // Check non-negative dimensions
            if layout.width < 0.0 {
                return Err(LayoutError::NegativeDimension {
                    element_id: *id,
                    dimension: "width",
                    value: layout.width,
                });
            }
            if layout.height < 0.0 {
                return Err(LayoutError::NegativeDimension {
                    element_id: *id,
                    dimension: "height",
                    value: layout.height,
                });
            }

            // Check bounds within terminal
            if layout.x + layout.width > self.width as f32 + 0.5 {
                return Err(LayoutError::OutOfBounds {
                    element_id: *id,
                    axis: "x",
                    position: layout.x + layout.width,
                    limit: self.width as f32,
                });
            }
            if layout.y + layout.height > self.height as f32 + 0.5 {
                return Err(LayoutError::OutOfBounds {
                    element_id: *id,
                    axis: "y",
                    position: layout.y + layout.height,
                    limit: self.height as f32,
                });
            }
        }

        Ok(())
    }

    /// Render a single element recursively
    fn render_element(
        &self,
        element: &Element,
        engine: &LayoutEngine,
        output: &mut Output,
        offset_x: f32,
        offset_y: f32,
    ) {
        if element.style.display == Display::None {
            return;
        }

        let layout = match engine.get_layout(element.id) {
            Some(l) => l,
            None => return,
        };

        let x = (offset_x + layout.x) as u16;
        let y = (offset_y + layout.y) as u16;
        let w = layout.width as u16;
        let h = layout.height as u16;

        // Background
        if element.style.background_color.is_some() {
            for row in 0..h {
                output.write(x, y + row, &" ".repeat(w as usize), &element.style);
            }
        }

        // Border
        if element.style.has_border() {
            let (tl, tr, bl, br, hz, vt) = element.style.border_style.chars();
            let mut style = element.style.clone();

            style.color = element.style.get_border_top_color();
            output.write(
                x,
                y,
                &format!("{}{}{}", tl, hz.repeat((w as usize).saturating_sub(2)), tr),
                &style,
            );

            style.color = element.style.get_border_bottom_color();
            output.write(
                x,
                y + h.saturating_sub(1),
                &format!("{}{}{}", bl, hz.repeat((w as usize).saturating_sub(2)), br),
                &style,
            );

            for row in 1..h.saturating_sub(1) {
                style.color = element.style.get_border_left_color();
                output.write(x, y + row, vt, &style);
                style.color = element.style.get_border_right_color();
                output.write(x + w.saturating_sub(1), y + row, vt, &style);
            }
        }

        // Text content
        if let Some(text) = &element.text_content {
            let text_x = x
                + if element.style.has_border() { 1 } else { 0 }
                + element.style.padding.left as u16;
            let text_y = y
                + if element.style.has_border() { 1 } else { 0 }
                + element.style.padding.top as u16;
            output.write(text_x, text_y, text, &element.style);
        }

        // Children
        let cx = offset_x + layout.x;
        let cy = offset_y + layout.y;

        for child in element.children.iter() {
            if child.style.position == Position::Absolute {
                self.render_element(
                    child,
                    engine,
                    output,
                    child.style.left.unwrap_or(0.0),
                    child.style.top.unwrap_or(0.0),
                );
            } else {
                self.render_element(child, engine, output, cx, cy);
            }
        }
    }
}

impl Default for TestRenderer {
    fn default() -> Self {
        Self::standard()
    }
}

/// Layout validation error
#[derive(Debug, Clone, PartialEq)]
pub enum LayoutError {
    NegativeCoordinate {
        element_id: ElementId,
        axis: &'static str,
        value: f32,
    },
    NegativeDimension {
        element_id: ElementId,
        dimension: &'static str,
        value: f32,
    },
    OutOfBounds {
        element_id: ElementId,
        axis: &'static str,
        position: f32,
        limit: f32,
    },
    ChildOutsideParent {
        child_id: ElementId,
        parent_id: ElementId,
    },
    InvalidUnicodeWidth {
        text: String,
        expected: usize,
        actual: usize,
    },
}

impl std::fmt::Display for LayoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NegativeCoordinate {
                element_id,
                axis,
                value,
            } => {
                write!(
                    f,
                    "Element {:?} has negative {} coordinate: {}",
                    element_id, axis, value
                )
            }
            Self::NegativeDimension {
                element_id,
                dimension,
                value,
            } => {
                write!(
                    f,
                    "Element {:?} has negative {}: {}",
                    element_id, dimension, value
                )
            }
            Self::OutOfBounds {
                element_id,
                axis,
                position,
                limit,
            } => {
                write!(
                    f,
                    "Element {:?} {} position {} exceeds limit {}",
                    element_id, axis, position, limit
                )
            }
            Self::ChildOutsideParent {
                child_id,
                parent_id,
            } => {
                write!(
                    f,
                    "Child {:?} is outside parent {:?} bounds",
                    child_id, parent_id
                )
            }
            Self::InvalidUnicodeWidth {
                text,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "Text '{}' has width {} but expected {}",
                    text, actual, expected
                )
            }
        }
    }
}

impl std::error::Error for LayoutError {}

/// Strip ANSI escape codes from a string
pub fn strip_ansi_codes(s: &str) -> String {
    let mut result = String::new();
    let mut chars = s.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            // Skip escape sequence
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                // Skip until we hit a letter
                while let Some(&c) = chars.peek() {
                    chars.next();
                    if c.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            result.push(ch);
        }
    }

    result
}

/// Calculate display width of text accounting for Unicode
pub fn display_width(s: &str) -> usize {
    s.chars().filter_map(|c| c.width()).sum()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::{Box as RnkBox, Text};

    #[test]
    fn test_strip_ansi_codes() {
        assert_eq!(strip_ansi_codes("\x1b[31mred\x1b[0m"), "red");
        assert_eq!(strip_ansi_codes("plain text"), "plain text");
        assert_eq!(
            strip_ansi_codes("\x1b[1;32mbold green\x1b[0m"),
            "bold green"
        );
    }

    #[test]
    fn test_display_width() {
        assert_eq!(display_width("hello"), 5);
        assert_eq!(display_width("你好"), 4); // CJK characters are 2 wide
        assert_eq!(display_width("hello 世界"), 10);
    }

    #[test]
    fn test_render_to_plain() {
        let renderer = TestRenderer::new(80, 24);
        let element = Text::new("Hello World").into_element();
        let output = renderer.render_to_plain(&element);
        assert!(output.contains("Hello World"));
    }

    #[test]
    fn test_layout_validation() {
        let renderer = TestRenderer::new(80, 24);
        let element = RnkBox::new()
            .width(20)
            .height(5)
            .child(Text::new("Test").into_element())
            .into_element();

        assert!(renderer.validate_layout(&element).is_ok());
    }

    #[test]
    fn test_get_layouts() {
        let renderer = TestRenderer::new(80, 24);
        let element = RnkBox::new().width(20).height(5).into_element();

        let layouts = renderer.get_layouts(&element);
        assert!(!layouts.is_empty());

        let layout = layouts.get(&element.id).unwrap();
        assert_eq!(layout.width, 20.0);
        assert_eq!(layout.height, 5.0);
    }
}