rnk 0.17.3

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
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
//! Layout utility functions
//!
//! Provides helper functions for common layout operations,
//! inspired by Lip Gloss's layout functions.

use crate::components::Box as RnkBox;
use crate::core::{AlignItems, Element, FlexDirection, JustifyContent};

/// Position for alignment operations
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Position {
    /// Align to the start (left or top)
    #[default]
    Start,
    /// Align to the center
    Center,
    /// Align to the end (right or bottom)
    End,
    /// Custom position (0.0 = start, 0.5 = center, 1.0 = end)
    At(f32),
}

impl Position {
    /// Convert to a float value (0.0 to 1.0)
    pub fn as_f32(&self) -> f32 {
        match self {
            Position::Start => 0.0,
            Position::Center => 0.5,
            Position::End => 1.0,
            Position::At(v) => v.clamp(0.0, 1.0),
        }
    }
}

impl From<f32> for Position {
    fn from(v: f32) -> Self {
        Position::At(v)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PositionBucket {
    Start,
    Center,
    End,
}

fn position_bucket(pos: Position) -> PositionBucket {
    match pos {
        Position::Start => PositionBucket::Start,
        Position::Center => PositionBucket::Center,
        Position::End => PositionBucket::End,
        Position::At(v) if v <= 0.33 => PositionBucket::Start,
        Position::At(v) if v >= 0.67 => PositionBucket::End,
        Position::At(_) => PositionBucket::Center,
    }
}

fn position_to_align_items(pos: Position) -> AlignItems {
    match position_bucket(pos) {
        PositionBucket::Start => AlignItems::FlexStart,
        PositionBucket::Center => AlignItems::Center,
        PositionBucket::End => AlignItems::FlexEnd,
    }
}

fn position_to_justify_content(pos: Position) -> JustifyContent {
    match position_bucket(pos) {
        PositionBucket::Start => JustifyContent::FlexStart,
        PositionBucket::Center => JustifyContent::Center,
        PositionBucket::End => JustifyContent::FlexEnd,
    }
}

/// Join multiple elements horizontally (in a row)
///
/// # Arguments
/// * `align` - Vertical alignment of elements
/// * `elements` - Elements to join
///
/// # Example
///
/// ```ignore
/// use rnk::layout::{join_horizontal, Position};
///
/// let row = join_horizontal(Position::Center, vec![elem1, elem2, elem3]);
/// ```
pub fn join_horizontal(align: Position, elements: Vec<Element>) -> Element {
    let align_items = position_to_align_items(align);

    let mut container = RnkBox::new()
        .flex_direction(FlexDirection::Row)
        .align_items(align_items);

    for elem in elements {
        container = container.child(elem);
    }

    container.into_element()
}

/// Join multiple elements vertically (in a column)
///
/// # Arguments
/// * `align` - Horizontal alignment of elements
/// * `elements` - Elements to join
///
/// # Example
///
/// ```ignore
/// use rnk::layout::{join_vertical, Position};
///
/// let column = join_vertical(Position::Center, vec![elem1, elem2, elem3]);
/// ```
pub fn join_vertical(align: Position, elements: Vec<Element>) -> Element {
    let align_items = position_to_align_items(align);

    let mut container = RnkBox::new()
        .flex_direction(FlexDirection::Column)
        .align_items(align_items);

    for elem in elements {
        container = container.child(elem);
    }

    container.into_element()
}

/// Place an element horizontally within a given width
///
/// # Arguments
/// * `width` - Total width to place within
/// * `pos` - Horizontal position
/// * `element` - Element to place
///
/// # Example
///
/// ```ignore
/// use rnk::layout::{place_horizontal, Position};
///
/// let centered = place_horizontal(80, Position::Center, my_element);
/// ```
pub fn place_horizontal(width: u16, pos: Position, element: Element) -> Element {
    let justify = position_to_justify_content(pos);

    RnkBox::new()
        .flex_direction(FlexDirection::Row)
        .justify_content(justify)
        .width(width)
        .child(element)
        .into_element()
}

/// Place an element vertically within a given height
///
/// # Arguments
/// * `height` - Total height to place within
/// * `pos` - Vertical position
/// * `element` - Element to place
///
/// # Example
///
/// ```ignore
/// use rnk::layout::{place_vertical, Position};
///
/// let centered = place_vertical(24, Position::Center, my_element);
/// ```
pub fn place_vertical(height: u16, pos: Position, element: Element) -> Element {
    let justify = position_to_justify_content(pos);

    RnkBox::new()
        .flex_direction(FlexDirection::Column)
        .justify_content(justify)
        .height(height)
        .child(element)
        .into_element()
}

/// Place an element within a given area
///
/// # Arguments
/// * `width` - Total width
/// * `height` - Total height
/// * `h_pos` - Horizontal position
/// * `v_pos` - Vertical position
/// * `element` - Element to place
///
/// # Example
///
/// ```ignore
/// use rnk::layout::{place, Position};
///
/// let centered = place(80, 24, Position::Center, Position::Center, my_element);
/// ```
pub fn place(
    width: u16,
    height: u16,
    h_pos: Position,
    v_pos: Position,
    element: Element,
) -> Element {
    let h_justify = position_to_justify_content(h_pos);
    let v_justify = position_to_justify_content(v_pos);

    // Create inner container for horizontal positioning
    let inner = RnkBox::new()
        .flex_direction(FlexDirection::Row)
        .justify_content(h_justify)
        .width(width)
        .child(element)
        .into_element();

    // Create outer container for vertical positioning
    RnkBox::new()
        .flex_direction(FlexDirection::Column)
        .justify_content(v_justify)
        .width(width)
        .height(height)
        .child(inner)
        .into_element()
}

/// Create a horizontal spacer that fills available space
pub fn h_spacer() -> Element {
    RnkBox::new().flex_grow(1.0).into_element()
}

/// Create a vertical spacer that fills available space
pub fn v_spacer() -> Element {
    RnkBox::new()
        .flex_grow(1.0)
        .flex_direction(FlexDirection::Column)
        .into_element()
}

/// Create a fixed-width horizontal gap
pub fn h_gap(width: u16) -> Element {
    RnkBox::new().width(width).into_element()
}

/// Create a fixed-height vertical gap
pub fn v_gap(height: u16) -> Element {
    RnkBox::new().height(height).into_element()
}

/// Center an element horizontally within a given width
pub fn center_horizontal(width: u16, element: Element) -> Element {
    place_horizontal(width, Position::Center, element)
}

/// Center an element vertically within a given height
pub fn center_vertical(height: u16, element: Element) -> Element {
    place_vertical(height, Position::Center, element)
}

/// Center an element both horizontally and vertically
pub fn center(width: u16, height: u16, element: Element) -> Element {
    place(width, height, Position::Center, Position::Center, element)
}

/// Create a row of elements with equal spacing between them
pub fn space_between(elements: Vec<Element>) -> Element {
    RnkBox::new()
        .flex_direction(FlexDirection::Row)
        .justify_content(JustifyContent::SpaceBetween)
        .children(elements)
        .into_element()
}

/// Create a row of elements with equal spacing around them
pub fn space_around(elements: Vec<Element>) -> Element {
    RnkBox::new()
        .flex_direction(FlexDirection::Row)
        .justify_content(JustifyContent::SpaceAround)
        .children(elements)
        .into_element()
}

/// Create a row of elements with equal spacing (including edges)
pub fn space_evenly(elements: Vec<Element>) -> Element {
    RnkBox::new()
        .flex_direction(FlexDirection::Row)
        .justify_content(JustifyContent::SpaceEvenly)
        .children(elements)
        .into_element()
}

/// Pad text to a specific width with alignment
pub fn pad_to_width(text: &str, width: usize, align: Position) -> String {
    let text_width = unicode_width::UnicodeWidthStr::width(text);
    if text_width >= width {
        return text.to_string();
    }

    let padding = width - text_width;
    match align {
        Position::Start => format!("{}{}", text, " ".repeat(padding)),
        Position::End => format!("{}{}", " ".repeat(padding), text),
        Position::Center => {
            let left = padding / 2;
            let right = padding - left;
            format!("{}{}{}", " ".repeat(left), text, " ".repeat(right))
        }
        Position::At(v) => {
            let left = ((padding as f32) * v) as usize;
            let right = padding - left;
            format!("{}{}{}", " ".repeat(left), text, " ".repeat(right))
        }
    }
}

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

    #[test]
    fn test_position_as_f32() {
        assert_eq!(Position::Start.as_f32(), 0.0);
        assert_eq!(Position::Center.as_f32(), 0.5);
        assert_eq!(Position::End.as_f32(), 1.0);
        assert_eq!(Position::At(0.25).as_f32(), 0.25);
    }

    #[test]
    fn test_position_from_f32() {
        let pos: Position = 0.75.into();
        assert_eq!(pos, Position::At(0.75));
    }

    #[test]
    fn test_position_clamp() {
        assert_eq!(Position::At(1.5).as_f32(), 1.0);
        assert_eq!(Position::At(-0.5).as_f32(), 0.0);
    }

    #[test]
    fn test_position_threshold_mapping() {
        assert_eq!(
            position_to_justify_content(Position::At(0.33)),
            JustifyContent::FlexStart
        );
        assert_eq!(
            position_to_justify_content(Position::At(0.34)),
            JustifyContent::Center
        );
        assert_eq!(
            position_to_justify_content(Position::At(0.67)),
            JustifyContent::FlexEnd
        );
        assert_eq!(
            position_to_align_items(Position::At(0.66)),
            AlignItems::Center
        );
    }

    #[test]
    fn test_pad_to_width_start() {
        let result = pad_to_width("hello", 10, Position::Start);
        assert_eq!(result, "hello     ");
    }

    #[test]
    fn test_pad_to_width_end() {
        let result = pad_to_width("hello", 10, Position::End);
        assert_eq!(result, "     hello");
    }

    #[test]
    fn test_pad_to_width_center() {
        let result = pad_to_width("hello", 11, Position::Center);
        assert_eq!(result, "   hello   ");
    }

    #[test]
    fn test_pad_to_width_no_padding_needed() {
        let result = pad_to_width("hello", 3, Position::Center);
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_join_horizontal() {
        let elem1 = Text::new("A").into_element();
        let elem2 = Text::new("B").into_element();
        let result = join_horizontal(Position::Center, vec![elem1, elem2]);
        assert!(!result.children.is_empty());
    }

    #[test]
    fn test_join_vertical() {
        let elem1 = Text::new("A").into_element();
        let elem2 = Text::new("B").into_element();
        let result = join_vertical(Position::Center, vec![elem1, elem2]);
        assert!(!result.children.is_empty());
    }

    #[test]
    fn test_place_horizontal() {
        let elem = Text::new("Test").into_element();
        let result = place_horizontal(80, Position::Center, elem);
        assert_eq!(result.style.width, crate::core::Dimension::Points(80.0));
    }

    #[test]
    fn test_place_vertical() {
        let elem = Text::new("Test").into_element();
        let result = place_vertical(24, Position::Center, elem);
        assert_eq!(result.style.height, crate::core::Dimension::Points(24.0));
    }

    #[test]
    fn test_place() {
        let elem = Text::new("Test").into_element();
        let result = place(80, 24, Position::Center, Position::Center, elem);
        assert_eq!(result.style.width, crate::core::Dimension::Points(80.0));
        assert_eq!(result.style.height, crate::core::Dimension::Points(24.0));
    }

    #[test]
    fn test_center() {
        let elem = Text::new("Test").into_element();
        let result = center(80, 24, elem);
        assert_eq!(result.style.width, crate::core::Dimension::Points(80.0));
        assert_eq!(result.style.height, crate::core::Dimension::Points(24.0));
    }

    #[test]
    fn test_h_gap() {
        let gap = h_gap(10);
        assert_eq!(gap.style.width, crate::core::Dimension::Points(10.0));
    }

    #[test]
    fn test_v_gap() {
        let gap = v_gap(5);
        assert_eq!(gap.style.height, crate::core::Dimension::Points(5.0));
    }

    #[test]
    fn test_space_between() {
        let elem1 = Text::new("A").into_element();
        let elem2 = Text::new("B").into_element();
        let result = space_between(vec![elem1, elem2]);
        assert_eq!(result.style.justify_content, JustifyContent::SpaceBetween);
    }

    #[test]
    fn test_space_around() {
        let elem1 = Text::new("A").into_element();
        let elem2 = Text::new("B").into_element();
        let result = space_around(vec![elem1, elem2]);
        assert_eq!(result.style.justify_content, JustifyContent::SpaceAround);
    }

    #[test]
    fn test_space_evenly() {
        let elem1 = Text::new("A").into_element();
        let elem2 = Text::new("B").into_element();
        let result = space_evenly(vec![elem1, elem2]);
        assert_eq!(result.style.justify_content, JustifyContent::SpaceEvenly);
    }
}