superconsole 0.2.0

A simple but powerful Text-based User Interface (TUI) framework
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under both the MIT license found in the
 * LICENSE-MIT file in the root directory of this source tree and the Apache
 * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
 * of this source tree.
 */

//! Splitting is one of the most primitive building blocks of a fully featured UI.
//! This module contains components and enums that allow for splits along either dimension.

use std::fmt::Debug;

use crate::Component;
use crate::Dimensions;
use crate::Direction;
use crate::DrawMode;
use crate::Lines;

/// Controls the way the splitter displays its children.
#[derive(Clone, Debug)]
pub enum SplitKind {
    // Each child component takes up area proportional to its size relative to the other sizes.
    Sized(Vec<f64>),
    // Each child component takes up an equal % of the area long the given dimension.
    Equal,
    // Each child may take as much space as it would like along the given dimension.
    // No extra padding is given between children.
    Adaptive,
}

/// Internally, we want to alias away the Equal case
#[derive(Clone, Debug)]
enum InternalSplitKind {
    SizedNormalized(Vec<f64>),
    Adaptive,
}

impl SplitKind {
    fn to_internal_split_kind(&self, children_len: usize) -> InternalSplitKind {
        match self {
            SplitKind::Sized(sizes) => {
                assert_eq!(
                    sizes.len(),
                    children_len,
                    "There must be an equal number of ratios and children."
                );

                let total: f64 = sizes.iter().sum();
                let normalized_sizes = sizes.iter().map(|size| size / total).collect();

                InternalSplitKind::SizedNormalized(normalized_sizes)
            }
            SplitKind::Equal => {
                InternalSplitKind::SizedNormalized(vec![1.0 / children_len as f64; children_len])
            }
            SplitKind::Adaptive => InternalSplitKind::Adaptive,
        }
    }
}

impl InternalSplitKind {
    pub fn draw<'a, C: Component + 'a>(
        &self,
        children: impl IntoIterator<Item = &'a C>,
        direction: Direction,

        dimensions: Dimensions,
        mode: DrawMode,
    ) -> anyhow::Result<Vec<Lines>> {
        match self {
            InternalSplitKind::SizedNormalized(sizes) => children
                .into_iter()
                .zip(sizes.iter())
                .map(|(child, size)| -> anyhow::Result<_> {
                    // allocate alloted size
                    let child_dimension = dimensions.multiply(*size, direction);
                    let mut output = child.draw(child_dimension, mode)?;

                    // bound non-splitting direction, pad splitting direction
                    match direction {
                        Direction::Horizontal => {
                            output.truncate_lines_bottom(child_dimension.height);
                            output.set_lines_to_exact_width(child_dimension.width);
                        }
                        Direction::Vertical => {
                            output.truncate_lines(child_dimension.width);
                            output.set_lines_to_exact_length(child_dimension.height);
                        }
                    }

                    Ok(output)
                })
                .collect(),
            InternalSplitKind::Adaptive => {
                let mut available = dimensions;
                children
                    .into_iter()
                    .map(|child| {
                        let mut output = child.draw(available, mode)?;
                        output.shrink_lines_to_dimensions(dimensions);

                        // decrease size by however much was just used
                        let used = Dimensions::dimension_from_output_truncated(&output, direction);
                        available = available.saturating_sub(used, direction);

                        Ok(output)
                    })
                    .collect()
            }
        }
    }
}

/// [`Splits`](SplitKind) along a given [`direction`](crate::Direction) for its child [`components`](Component).
/// Child components are truncated to the bounds passed to them.
pub struct Split<C = Box<dyn Component>> {
    children: Vec<C>,
    direction: Direction,
    split: InternalSplitKind,
}

impl<C> Debug for Split<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Split")
            .field("children", &self.children.len())
            .field("direction", &self.direction)
            .field("split", &self.split)
            .finish()
    }
}

impl<C: Component> Split<C> {
    /// Preconditions:
    /// * At least one child.
    /// * If Sized, then ratios must sum to approximately 1.
    /// * If Sized, then there must be as many ratios as components
    pub fn new(children: Vec<C>, direction: Direction, split: SplitKind) -> Self {
        let split = split.to_internal_split_kind(children.len());

        Self {
            children,
            direction,
            split,
        }
    }
}

impl<C: Component> Component for Split<C> {
    fn draw_unchecked(&self, dimensions: Dimensions, mode: DrawMode) -> anyhow::Result<Lines> {
        let outputs = self
            .split
            .draw(&self.children, self.direction, dimensions, mode)?;

        Ok(match self.direction {
            Direction::Horizontal => Lines::join_horizontally(outputs),
            Direction::Vertical => outputs.into_iter().flatten().collect(),
        })
    }
}

#[cfg(test)]
mod tests {
    use std::iter;

    use derive_more::AsRef;

    use super::Split;
    use super::SplitKind;
    use crate::Component;
    use crate::Direction;
    use crate::DrawMode;
    use crate::Line;
    use crate::Lines;

    #[derive(AsRef, Debug)]
    struct Echo1(Lines);
    #[derive(AsRef, Debug)]
    struct Echo2(Lines);

    #[derive(AsRef, Debug)]
    struct Echo3(Lines);

    mod horizontal {
        use super::*;
        use crate::components::echo::Echo;
        use crate::Dimensions;
        #[test]
        fn test_adaptive() {
            let kind = SplitKind::Adaptive;
            let dimension = Direction::Horizontal;

            // left rows all the same length
            let mut left_msg = Lines(vec![
                vec!["test"].try_into().unwrap(),
                vec!["ok", "so"].try_into().unwrap(),
                vec!["sync"].try_into().unwrap(),
            ]);
            let right_msg = Lines(vec![
                vec!["xx"].try_into().unwrap(),
                vec!["yyy"].try_into().unwrap(),
                vec!["z"].try_into().unwrap(),
            ]);
            let splitter = Split::new(
                vec![Echo(left_msg.clone()), Echo(right_msg.clone())],
                dimension,
                kind.clone(),
            );
            let horizontal = Lines(vec![
                vec!["test", "xx", " "].try_into().unwrap(),
                vec!["ok", "so", "yyy"].try_into().unwrap(),
                vec!["sync", "z", "  "].try_into().unwrap(),
            ]);

            let output = splitter
                .draw(Dimensions::new(10, 10), DrawMode::Normal)
                .unwrap();
            assert_eq!(output, horizontal);

            // uneven left row
            left_msg.0[0] = vec!["hello world"].try_into().unwrap();
            let horizontal = Lines(vec![
                vec!["hello world", "xx", " "].try_into().unwrap(),
                vec!["ok", "so", &" ".repeat(7), "yyy"].try_into().unwrap(),
                vec!["sync", &" ".repeat(7), "z", "  "].try_into().unwrap(),
            ]);

            let splitter = Split::new(vec![Echo(left_msg), Echo(right_msg)], dimension, kind);

            let output = splitter
                .draw(Dimensions::new(15, 15), DrawMode::Normal)
                .unwrap();
            assert_eq!(output, horizontal);
        }

        #[test]
        fn test_equal() {
            let kind = SplitKind::Equal;
            let dimension = Direction::Horizontal;

            // left rows all the same length
            let mut left_msg = Lines(vec![
                vec!["test"].try_into().unwrap(),
                vec!["ok", "so"].try_into().unwrap(),
                vec!["sync"].try_into().unwrap(),
            ]);
            let right_msg = Lines(vec![
                vec!["xx"].try_into().unwrap(),
                vec!["yyy"].try_into().unwrap(),
                vec!["z"].try_into().unwrap(),
            ]);
            let splitter = Split::new(
                vec![Echo(left_msg.clone()), Echo(right_msg.clone())],
                dimension,
                kind.clone(),
            );
            let horizontal = Lines(vec![
                vec!["test", &" ".repeat(6), "xx", &" ".repeat(8)]
                    .try_into()
                    .unwrap(),
                vec!["ok", "so", &" ".repeat(6), "yyy", &" ".repeat(7)]
                    .try_into()
                    .unwrap(),
                vec!["sync", &" ".repeat(6), "z", &" ".repeat(9)]
                    .try_into()
                    .unwrap(),
            ]);

            let output = splitter
                .draw(Dimensions::new(20, 20), DrawMode::Normal)
                .unwrap();
            assert_eq!(output, horizontal);

            // uneven left row
            left_msg.0[0] = vec!["hello worl"].try_into().unwrap();
            let horizontal = Lines(vec![
                vec!["hello worl", "xx", &" ".repeat(8)].try_into().unwrap(),
                vec!["ok", "so", &" ".repeat(6), "yyy", &" ".repeat(7)]
                    .try_into()
                    .unwrap(),
                vec!["sync", &" ".repeat(6), "z", &" ".repeat(9)]
                    .try_into()
                    .unwrap(),
            ]);

            let splitter = Split::new(vec![Echo(left_msg), Echo(right_msg)], dimension, kind);

            let output = splitter
                .draw(Dimensions::new(20, 20), DrawMode::Normal)
                .unwrap();
            assert_eq!(output, horizontal);
        }

        #[test]
        fn test_many_sized() {
            let msg1 = Lines(vec![
                vec!["test", "ok"].try_into().unwrap(),
                vec!["also"].try_into().unwrap(),
            ]);
            let msg2 = Lines(vec![vec!["hola"].try_into().unwrap()]);
            let msg3 = Lines(vec![vec!["way way way way too long"].try_into().unwrap()]);
            let splitter = Split::new(
                vec![Echo(msg1), Echo(msg2), Echo(msg3)],
                Direction::Horizontal,
                SplitKind::Sized(vec![0.25, 0.5, 0.25]),
            );

            let output = splitter
                .draw(Dimensions::new(20, 20), DrawMode::Normal)
                .unwrap();

            let expected = Lines(vec![
                vec!["test", "o", "hola", &" ".repeat(6), "way w"]
                    .try_into()
                    .unwrap(),
                vec!["also", " ", &" ".repeat(10), &" ".repeat(5)]
                    .try_into()
                    .unwrap(),
            ]);

            assert_eq!(output, expected);
        }
    }

    mod vertical {
        use super::*;
        use crate::components::echo::Echo;
        use crate::Dimensions;

        #[test]
        fn test_equal() {
            let kind = SplitKind::Equal;
            let dimension = Direction::Vertical;

            let top = Lines(vec![
                vec!["Line 1"].try_into().unwrap(),
                vec!["Line 2222"].try_into().unwrap(),
            ]);
            let mut bottom = Lines(vec![
                vec!["Line 11"].try_into().unwrap(),
                vec!["Line 12"].try_into().unwrap(),
                vec!["Last line just kiddi"].try_into().unwrap(),
            ]);
            let splitter = Split::new(
                vec![Echo(top.clone()), Echo(bottom.clone())],
                dimension,
                kind,
            );

            let mut output = top;
            output.0.extend(iter::repeat(Line::default()).take(8));
            output.0.append(&mut bottom.0);
            output.0.extend(iter::repeat(Line::default()).take(7));

            let drawn = splitter
                .draw(Dimensions::new(20, 20), DrawMode::Normal)
                .unwrap();

            assert_eq!(drawn, output);
        }

        #[test]
        fn test_adaptive() {
            let kind = SplitKind::Adaptive;
            let dimension = Direction::Vertical;

            let top = Lines(vec![
                vec!["Line 1"].try_into().unwrap(),
                vec!["Line 2222"].try_into().unwrap(),
            ]);
            let mut bottom = Lines(vec![
                vec!["Line 11"].try_into().unwrap(),
                vec!["Line 12"].try_into().unwrap(),
                vec!["Last line just kiddi"].try_into().unwrap(),
            ]);
            let splitter = Split::new(
                vec![Echo(top.clone()), Echo(bottom.clone())],
                dimension,
                kind,
            );

            let mut output = top;
            output.0.append(&mut bottom.0);

            let drawn = splitter
                .draw(Dimensions::new(20, 20), DrawMode::Normal)
                .unwrap();
            assert_eq!(drawn, output);
        }

        #[test]
        fn test_many_sized() {
            let msg1 = Lines(vec![
                vec!["line1"].try_into().unwrap(),
                vec!["line2"].try_into().unwrap(),
                vec!["line3"].try_into().unwrap(),
                vec!["line4"].try_into().unwrap(),
                vec!["line5"].try_into().unwrap(),
                vec!["line6"].try_into().unwrap(),
            ]);
            let msg2 = Lines(vec![vec!["line7"].try_into().unwrap()]);
            let msg3 = Lines(vec![vec!["line8"].try_into().unwrap()]);
            let splitter = Split::new(
                vec![Echo(msg1), Echo(msg2), Echo(msg3)],
                Direction::Vertical,
                SplitKind::Sized(vec![0.25, 0.5, 0.25]),
            );

            let output = splitter
                .draw(Dimensions::new(20, 20), DrawMode::Normal)
                .unwrap();

            let expected = Lines(vec![
                vec!["line1"].try_into().unwrap(),
                vec!["line2"].try_into().unwrap(),
                vec!["line3"].try_into().unwrap(),
                vec!["line4"].try_into().unwrap(),
                vec!["line5"].try_into().unwrap(),
                vec!["line7"].try_into().unwrap(),
                Line::default(),
                Line::default(),
                Line::default(),
                Line::default(),
                Line::default(),
                Line::default(),
                Line::default(),
                Line::default(),
                Line::default(),
                vec!["line8"].try_into().unwrap(),
                Line::default(),
                Line::default(),
                Line::default(),
                Line::default(),
            ]);

            assert_eq!(output, expected);
        }
    }

    mod panics {
        use super::*;
        use crate::components::Blank;
        use crate::Dimensions;

        #[test]
        fn test_no_children() {
            let lines = Split::<Blank>::new(vec![], Direction::Horizontal, SplitKind::Equal)
                .draw(Dimensions::new(20, 20), DrawMode::Normal)
                .unwrap();
            assert!(lines.is_empty());
        }

        #[test]
        #[should_panic(expected = "There must be an equal number of ratios and children.")]
        fn test_different_ratio_count() {
            Split::new(
                vec![Box::new(Blank), Box::new(Blank), Box::new(Blank)],
                Direction::Vertical,
                SplitKind::Sized(vec![0.4, 0.4]),
            );
        }
    }
}