r3bl_tuify 0.3.0

DEPRECATED: Use r3bl_tui instead. Lightweight TUI capabilities for CLI apps
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
/*
 *   Copyright (c) 2023 R3BL LLC
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

use std::io::stdout;

use clap::ValueEnum;
use crossterm::style::Stylize;
use r3bl_ansi_color::AnsiStyledText;
use r3bl_core::{call_if_true, ch, get_size, Size};

use crate::{enter_event_loop,
            CalculateResizeHint,
            CaretVerticalViewportLocation,
            CrosstermKeyPressReader,
            EventLoopResult,
            KeyPress,
            SelectComponent,
            State,
            StyleSheet,
            DEVELOPMENT_MODE};

pub const DEFAULT_HEIGHT: usize = 5;

/// This function does the work of rendering the TUI.
///
/// It takes a list of items, and returns the selected item or items (depending on the
/// selection mode). If the user does not select anything, it returns `None`. The function
/// also takes the maximum height and width of the display, and the selection mode (single
/// select or multiple select).
///
/// If the terminal is *fully* uninteractive, it returns `None`. This is useful so that it
/// won't block `cargo test` or when run in non-interactive CI/CD environments.
pub fn select_from_list(
    header: String,
    items: Vec<String>,
    max_height_row_count: usize,
    // If you pass 0, then the width of your terminal gets set as max_width_col_count.
    max_width_col_count: usize,
    selection_mode: SelectionMode,
    style: StyleSheet,
) -> Option<Vec<String>> {
    // There are fewer items than viewport height. So make viewport shorter.
    let max_height_row_count = if items.len() <= max_height_row_count {
        items.len()
    } else {
        max_height_row_count
    };

    let mut state = State {
        max_display_height: ch!(max_height_row_count),
        max_display_width: ch!(max_width_col_count),
        items,
        header,
        selection_mode,
        ..Default::default()
    };

    let mut function_component = SelectComponent {
        write: stdout(),
        style,
    };

    if let Ok(size) = get_size() {
        state.set_size(size);
    }

    let result_user_input = enter_event_loop(
        &mut state,
        &mut function_component,
        |state, key_press| keypress_handler(state, key_press),
        &mut CrosstermKeyPressReader {},
    );

    match result_user_input {
        Ok(EventLoopResult::ExitWithResult(it)) => Some(it),
        _ => None,
    }
}

pub fn select_from_list_with_multi_line_header(
    multi_line_header: Vec<Vec<AnsiStyledText<'_>>>,
    items: Vec<String>,
    maybe_max_height_row_count: Option<usize>,
    // If you pass None, then the width of your terminal gets used.
    maybe_max_width_col_count: Option<usize>,
    selection_mode: SelectionMode,
    style: StyleSheet,
) -> Option<Vec<String>> {
    // There are fewer items than viewport height. So make viewport shorter.
    let max_height_row_count = match maybe_max_height_row_count {
        Some(requested_height) => sanitize_height(&items, requested_height),
        None => sanitize_height(&items, DEFAULT_HEIGHT),
    };

    let max_width_col_count = maybe_max_width_col_count.unwrap_or(0);

    let mut state = State {
        max_display_height: ch!(max_height_row_count),
        max_display_width: ch!(max_width_col_count),
        items,
        multi_line_header,
        selection_mode,
        ..Default::default()
    };

    let mut function_component = SelectComponent {
        write: stdout(),
        style,
    };

    if let Ok(size) = get_size() {
        state.set_size(size);
    }

    let result_user_input = enter_event_loop(
        &mut state,
        &mut function_component,
        |state, key_press| keypress_handler(state, key_press),
        &mut CrosstermKeyPressReader {},
    );

    match result_user_input {
        Ok(EventLoopResult::ExitWithResult(it)) => Some(it),
        _ => None,
    }
}

fn sanitize_height(items: &[String], requested_height: usize) -> usize {
    let num_items = items.len();
    if num_items > requested_height {
        requested_height
    } else {
        num_items
    }
}

fn keypress_handler(state: &mut State<'_>, key_press: KeyPress) -> EventLoopResult {
    call_if_true!(DEVELOPMENT_MODE, {
        tracing::debug!(
            "🔆🔆🔆 *before* keypress: locate_cursor_in_viewport(): {}",
            format!("{:?}", state.locate_cursor_in_viewport()).magenta()
        );
    });

    let selection_mode = state.selection_mode;

    let return_it = match key_press {
        // Resize.
        KeyPress::Resize(Size {
            col_count,
            row_count,
        }) => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!(
                    "\n🍎🍎🍎\nNew size width:{} x height:{}",
                    format!("{col_count}").green(),
                    format!("{row_count}").green(),
                );
            });
            state.set_resize_hint(Size {
                col_count,
                row_count,
            });
            EventLoopResult::ContinueAndRerenderAndClear
        }

        // Down.
        KeyPress::Down => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!("Down");
            });
            let caret_location = state.locate_cursor_in_viewport();
            match caret_location {
                CaretVerticalViewportLocation::AtAbsoluteTop
                | CaretVerticalViewportLocation::AboveTopOfViewport
                | CaretVerticalViewportLocation::AtTopOfViewport
                | CaretVerticalViewportLocation::InMiddleOfViewport => {
                    state.raw_caret_row_index += 1;
                }

                CaretVerticalViewportLocation::AtBottomOfViewport
                | CaretVerticalViewportLocation::BelowBottomOfViewport => {
                    state.scroll_offset_row_index += 1;
                }

                CaretVerticalViewportLocation::AtAbsoluteBottom
                | CaretVerticalViewportLocation::NotFound => {
                    // Do nothing.
                }
            }
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!(
                    "enter_event_loop()::state: {}",
                    format!("{state:?}").blue()
                );
            });

            EventLoopResult::ContinueAndRerender
        }

        // Up.
        KeyPress::Up => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!("Up");
            });

            match state.locate_cursor_in_viewport() {
                CaretVerticalViewportLocation::NotFound
                | CaretVerticalViewportLocation::AtAbsoluteTop => {
                    // Do nothing.
                }

                CaretVerticalViewportLocation::AboveTopOfViewport
                | CaretVerticalViewportLocation::AtTopOfViewport => {
                    state.scroll_offset_row_index -= 1;
                }

                CaretVerticalViewportLocation::InMiddleOfViewport => {
                    state.raw_caret_row_index -= 1;
                }

                CaretVerticalViewportLocation::AtBottomOfViewport
                | CaretVerticalViewportLocation::BelowBottomOfViewport
                | CaretVerticalViewportLocation::AtAbsoluteBottom => {
                    state.raw_caret_row_index -= 1;
                }
            }

            EventLoopResult::ContinueAndRerender
        }

        // Enter on multi-select.
        KeyPress::Enter if selection_mode == SelectionMode::Multiple => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!(
                    "Enter: {}",
                    format!("{:?}", state.selected_items).green()
                );
            });
            if state.selected_items.is_empty() {
                EventLoopResult::ExitWithoutResult
            } else {
                EventLoopResult::ExitWithResult(state.selected_items.clone())
            }
        }

        // Enter.
        KeyPress::Enter => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!(
                    "Enter: {}",
                    format!("{:?}", state.get_focused_index()).green()
                );
            });
            let selection_index: usize = ch!(@to_usize state.get_focused_index());
            let maybe_item: Option<&String> = state.items.get(selection_index);
            match maybe_item {
                Some(it) => EventLoopResult::ExitWithResult(vec![it.to_string()]),
                None => EventLoopResult::ExitWithoutResult,
            }
        }

        // Escape or Ctrl + c.
        KeyPress::Esc | KeyPress::CtrlC => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!("Esc");
            });
            EventLoopResult::ExitWithoutResult
        }

        // Space on multi-select.
        KeyPress::Space if selection_mode == SelectionMode::Multiple => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!(
                    "Space: {}",
                    format!("{:?}", state.get_focused_index()).magenta()
                );
            });
            let selection_index: usize = ch!(@to_usize state.get_focused_index());
            let maybe_item: Option<&String> = state.items.get(selection_index);
            let maybe_index: Option<usize> = state
                .selected_items
                .iter()
                .position(|x| Some(x) == maybe_item);
            match (maybe_item, maybe_index) {
                // No selected_item.
                (None, _) => (),
                // Item already in selected_items so remove it.
                (Some(_), Some(it)) => {
                    state.selected_items.remove(it);
                }
                // Item not found in selected_items so add it.
                (Some(it), None) => state.selected_items.push(it.to_string()),
            };

            EventLoopResult::ContinueAndRerender
        }

        // Noop, default behavior on Space
        KeyPress::Noop | KeyPress::Space => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!("Noop");
            });
            EventLoopResult::Continue
        }

        // Error.
        KeyPress::Error => {
            call_if_true!(DEVELOPMENT_MODE, {
                tracing::debug!("Exit with error");
            });
            EventLoopResult::ExitWithError
        }
    };

    call_if_true!(DEVELOPMENT_MODE, {
        tracing::debug!(
            "👉 *after* keypress: locate_cursor_in_viewport(): {}",
            format!("{:?}", state.locate_cursor_in_viewport()).blue()
        );
    });

    return_it
}

#[derive(
    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default, Hash,
)]
pub enum SelectionMode {
    /// Select only one option from list.
    #[default]
    Single,
    /// Select multiple options from list.
    Multiple,
}

#[cfg(test)]
mod test_select_from_list {
    use r3bl_ansi_color::{is_fully_uninteractive_terminal, TTYResult};
    use r3bl_core::assert_eq2;

    use super::*;
    use crate::{TestStringWriter, TestVecKeyPressReader};

    fn create_state<'a>() -> State<'a> {
        State {
            max_display_height: ch!(10),
            items: ["a", "b", "c"].iter().map(|it| it.to_string()).collect(),
            ..Default::default()
        }
    }

    #[test]
    fn enter_pressed() {
        let mut state = create_state();
        let string_writer = TestStringWriter::new();
        let style_sheet = StyleSheet::default();

        let mut function_component = SelectComponent {
            write: string_writer,
            style: style_sheet,
        };

        let mut reader = TestVecKeyPressReader {
            key_press_vec: vec![KeyPress::Down, KeyPress::Down, KeyPress::Enter],
            index: None,
        };

        let result_event_loop_result = enter_event_loop(
            &mut state,
            &mut function_component,
            |state, key_press| keypress_handler(state, key_press),
            &mut reader,
        );

        assert_eq2!(
            result_event_loop_result.unwrap(),
            if let TTYResult::IsNotInteractive = is_fully_uninteractive_terminal() {
                EventLoopResult::ExitWithError
            } else {
                EventLoopResult::ExitWithResult(vec!["c".to_string()])
            }
        );
    }

    #[test]
    fn ctrl_c_pressed() {
        let mut state = create_state();
        let string_writer = TestStringWriter::new();
        let style_sheet = StyleSheet::default();

        let mut function_component = SelectComponent {
            write: string_writer,
            style: style_sheet,
        };

        let mut reader = TestVecKeyPressReader {
            key_press_vec: vec![KeyPress::Down, KeyPress::Down, KeyPress::CtrlC],
            index: None,
        };

        let result_event_loop_result = enter_event_loop(
            &mut state,
            &mut function_component,
            |state, key_press| keypress_handler(state, key_press),
            &mut reader,
        );

        assert_eq2!(
            result_event_loop_result.unwrap(),
            if let TTYResult::IsNotInteractive = is_fully_uninteractive_terminal() {
                EventLoopResult::ExitWithError
            } else {
                EventLoopResult::ExitWithoutResult
            }
        );
    }
}