rusty-bubbles 2.1.0

Cleanroom Rust port of charm.land/bubbles/v2: TUI components for Bubble Tea applications
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
//! Cleanroom Rust port of upstream Go source file: `table/table.go`
//! Upstream Target Tag / Version: `v2.1.0`
//!
//! <public-docs>
//! # Table
//!
//! A simple table component for Bubble Tea applications.
//! </public-docs>

use crate::help;
use crate::key::{self, Binding};
use crate::viewport;
use rusty_bubbletea::key::KeyPressMsg;
use rusty_bubbletea::model::{Cmd, Msg};
use rusty_lipgloss::{self, Style};
use rusty_x_ansi;

/// Model defines a state for the table widget.
#[derive(Debug)]
pub struct Model {
    /// The key bindings for the table.
    pub key_map: KeyMap,
    /// The help view for the table.
    pub help: help::Model,

    cols: Vec<Column>,
    rows: Vec<Row>,
    cursor: usize,
    focus: bool,
    styles: Styles,

    viewport: viewport::Model,
    start: usize,
    end: usize,
}

/// Row represents one line in the table.
pub type Row = Vec<String>;

/// Column defines the table structure.
#[derive(Debug, Clone)]
pub struct Column {
    /// The title of the column.
    pub title: String,
    /// The width of the column.
    pub width: usize,
}

/// KeyMap defines keybindings. It satisfies to the help.KeyMap interface,
/// which is used to render the help menu.
#[derive(Debug, Clone)]
pub struct KeyMap {
    /// LineUp binding.
    pub line_up: Binding,
    /// LineDown binding.
    pub line_down: Binding,
    /// PageUp binding.
    pub page_up: Binding,
    /// PageDown binding.
    pub page_down: Binding,
    /// HalfPageUp binding.
    pub half_page_up: Binding,
    /// HalfPageDown binding.
    pub half_page_down: Binding,
    /// GotoTop binding.
    pub goto_top: Binding,
    /// GotoBottom binding.
    pub goto_bottom: Binding,
}

/// ShortHelp implements the KeyMap interface.
impl KeyMap {
    /// ShortHelp returns the bindings shown in the abbreviated help view.
    pub fn short_help(&self) -> Vec<Binding> {
        vec![self.line_up.clone(), self.line_down.clone()]
    }

    /// FullHelp returns the bindings shown in the full help view.
    pub fn full_help(&self) -> Vec<Vec<Binding>> {
        vec![
            vec![
                self.line_up.clone(),
                self.line_down.clone(),
                self.goto_top.clone(),
                self.goto_bottom.clone(),
            ],
            vec![
                self.page_up.clone(),
                self.page_down.clone(),
                self.half_page_up.clone(),
                self.half_page_down.clone(),
            ],
        ]
    }
}

impl help::KeyMap for KeyMap {
    fn short_help(&self) -> Vec<Binding> {
        KeyMap::short_help(self)
    }

    fn full_help(&self) -> Vec<Vec<Binding>> {
        KeyMap::full_help(self)
    }
}

/// DefaultKeyMap returns a default set of keybindings.
pub fn default_key_map() -> KeyMap {
    KeyMap {
        line_up: key::new_binding(vec![
            key::with_keys(&["up", "k"]),
            key::with_help("↑/k", "up"),
        ]),
        line_down: key::new_binding(vec![
            key::with_keys(&["down", "j"]),
            key::with_help("↓/j", "down"),
        ]),
        page_up: key::new_binding(vec![
            key::with_keys(&["b", "pgup"]),
            key::with_help("b/pgup", "page up"),
        ]),
        page_down: key::new_binding(vec![
            key::with_keys(&["f", "pgdown", "space"]),
            key::with_help("f/pgdn", "page down"),
        ]),
        half_page_up: key::new_binding(vec![
            key::with_keys(&["u", "ctrl+u"]),
            key::with_help("u", "½ page up"),
        ]),
        half_page_down: key::new_binding(vec![
            key::with_keys(&["d", "ctrl+d"]),
            key::with_help("d", "½ page down"),
        ]),
        goto_top: key::new_binding(vec![
            key::with_keys(&["home", "g"]),
            key::with_help("g/home", "go to start"),
        ]),
        goto_bottom: key::new_binding(vec![
            key::with_keys(&["end", "G"]),
            key::with_help("G/end", "go to end"),
        ]),
    }
}

/// Styles contains style definitions for this list component. By default,
/// these values are generated by [`default_styles`].
#[derive(Debug, Clone)]
pub struct Styles {
    /// The style for the header row.
    pub header: Style,
    /// The style for cells.
    pub cell: Style,
    /// The style for the selected row.
    pub selected: Style,
}

/// DefaultStyles returns a set of default style definitions for this table.
pub fn default_styles() -> Styles {
    Styles {
        selected: rusty_lipgloss::new_style().bold(true).foreground("212"),
        header: rusty_lipgloss::new_style().bold(true).padding(&[0, 1]),
        cell: rusty_lipgloss::new_style().padding(&[0, 1]),
    }
}

/// Option is used to set options in [`new`]. For example:
///
/// ```rust
/// # use rusty_bubbles::table;
/// let table = table::new(vec![table::with_columns(&[table::Column {
///     title: "ID".to_string(),
///     width: 10,
/// }])]);
/// ```
pub type Option = Box<dyn FnOnce(&mut Model)>; // (std::option::Option is used for optionals)

/// New creates a new model for the table widget.
pub fn new(opts: Vec<Option>) -> Model {
    let mut m = Model {
        cursor: 0,
        viewport: viewport::new(vec![viewport::with_height(20)]),

        key_map: default_key_map(),
        help: help::new(),
        styles: default_styles(),

        cols: vec![],
        rows: vec![],
        focus: false,
        start: 0,
        end: 0,
    };

    for opt in opts {
        opt(&mut m);
    }

    m.update_viewport();

    m
}

/// WithColumns sets the table columns (headers).
pub fn with_columns(cols: &[Column]) -> Option {
    let cols = cols.to_vec();
    Box::new(move |m: &mut Model| {
        m.cols = cols;
    })
}

/// WithRows sets the table rows (data).
pub fn with_rows(rows: &[Row]) -> Option {
    let rows = rows.to_vec();
    Box::new(move |m: &mut Model| {
        m.rows = rows;
    })
}

/// WithHeight sets the height of the table.
pub fn with_height(h: usize) -> Option {
    Box::new(move |m: &mut Model| {
        let hh = rusty_lipgloss::size::height(&m.headers_view());
        m.viewport.set_height(h - hh);
    })
}

/// WithWidth sets the width of the table.
pub fn with_width(w: usize) -> Option {
    Box::new(move |m: &mut Model| {
        m.viewport.set_width(w);
    })
}

/// WithFocused sets the focus state of the table.
pub fn with_focused(f: bool) -> Option {
    Box::new(move |m: &mut Model| {
        m.focus = f;
    })
}

/// WithStyles sets the table styles.
pub fn with_styles(s: Styles) -> Option {
    Box::new(move |m: &mut Model| {
        m.styles = s;
    })
}

/// WithKeyMap sets the key map.
pub fn with_key_map(km: KeyMap) -> Option {
    Box::new(move |m: &mut Model| {
        m.key_map = km;
    })
}

impl Model {
    /// SetStyles sets the table styles.
    pub fn set_styles(&mut self, s: Styles) {
        self.styles = s;
        self.update_viewport();
    }

    /// Update is the Bubble Tea update loop.
    pub fn update(&mut self, msg: &dyn Msg) -> Cmd {
        if !self.focus {
            return None;
        }

        if let Some(m) = msg.as_any().downcast_ref::<KeyPressMsg>() {
            let k = &m.0;
            if key::matches(k, std::slice::from_ref(&self.key_map.line_up)) {
                self.move_up(1);
            } else if key::matches(k, std::slice::from_ref(&self.key_map.line_down)) {
                self.move_down(1);
            } else if key::matches(k, std::slice::from_ref(&self.key_map.page_up)) {
                self.move_up(self.viewport.height());
            } else if key::matches(k, std::slice::from_ref(&self.key_map.page_down)) {
                self.move_down(self.viewport.height());
            } else if key::matches(k, std::slice::from_ref(&self.key_map.half_page_up)) {
                self.move_up(self.viewport.height() / 2);
            } else if key::matches(k, std::slice::from_ref(&self.key_map.half_page_down)) {
                self.move_down(self.viewport.height() / 2);
            } else if key::matches(k, std::slice::from_ref(&self.key_map.goto_top)) {
                self.goto_top();
            } else if key::matches(k, std::slice::from_ref(&self.key_map.goto_bottom)) {
                self.goto_bottom();
            }
        }

        None
    }

    /// Focused returns the focus state of the table.
    pub fn focused(&self) -> bool {
        self.focus
    }

    /// Focus focuses the table, allowing the user to move around the rows
    /// and interact.
    pub fn focus(&mut self) {
        self.focus = true;
        self.update_viewport();
    }

    /// Blur blurs the table, preventing selection or movement.
    pub fn blur(&mut self) {
        self.focus = false;
        self.update_viewport();
    }

    /// View renders the component.
    pub fn view(&self) -> String {
        self.headers_view() + "\n" + &self.viewport.view()
    }

    /// HelpView is a helper method for rendering the help menu from the
    /// keymap. Note that this view is not rendered by default and you must
    /// call it manually in your application, where applicable.
    pub fn help_view(&self) -> String {
        self.help.view(&self.key_map)
    }

    /// UpdateViewport updates the list content based on the previously
    /// defined columns and rows.
    pub fn update_viewport(&mut self) {
        let mut rendered_rows: Vec<String> = Vec::with_capacity(self.rows.len());

        // Render only rows from: m.cursor-m.viewport.Height to:
        // m.cursor+m.viewport.Height. Constant runtime, independent of
        // number of rows in a table. Limits the number of renderedRows to a
        // maximum of 2*m.viewport.Height.
        self.start = clamp(
            self.cursor.saturating_sub(self.viewport.height()),
            0,
            self.cursor,
        );
        self.end = clamp(
            self.cursor + self.viewport.height(),
            self.cursor,
            self.rows.len(),
        );
        for i in self.start..self.end {
            rendered_rows.push(self.render_row(i));
        }

        let refs: Vec<&str> = rendered_rows.iter().map(|s| s.as_str()).collect();
        self.viewport
            .set_content(&rusty_lipgloss::join::join_vertical(
                rusty_lipgloss::LEFT,
                &refs,
            ));
    }

    /// SelectedRow returns the selected row.
    pub fn selected_row(&self) -> std::option::Option<Row> {
        if self.cursor >= self.rows.len() {
            return None;
        }

        Some(self.rows[self.cursor].clone())
    }

    /// Rows returns the current rows.
    pub fn rows(&self) -> &[Row] {
        &self.rows
    }

    /// Columns returns the current columns.
    pub fn columns(&self) -> &[Column] {
        &self.cols
    }

    /// SetRows sets a new rows state.
    pub fn set_rows(&mut self, r: &[Row]) {
        self.rows = r.to_vec();

        if self.cursor > self.rows.len().saturating_sub(1) {
            self.cursor = self.rows.len().saturating_sub(1);
        }

        self.update_viewport();
    }

    /// SetColumns sets a new columns state.
    pub fn set_columns(&mut self, c: &[Column]) {
        self.cols = c.to_vec();
        self.update_viewport();
    }

    /// SetWidth sets the width of the viewport of the table.
    pub fn set_width(&mut self, w: usize) {
        self.viewport.set_width(w);
        self.update_viewport();
    }

    /// SetHeight sets the height of the viewport of the table.
    pub fn set_height(&mut self, h: usize) {
        let hh = rusty_lipgloss::size::height(&self.headers_view());
        self.viewport.set_height(h - hh);
        self.update_viewport();
    }

    /// Height returns the viewport height of the table.
    pub fn height(&self) -> usize {
        self.viewport.height()
    }

    /// Width returns the viewport width of the table.
    pub fn width(&self) -> usize {
        self.viewport.width()
    }

    /// Cursor returns the index of the selected row.
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// SetCursor sets the cursor position in the table.
    pub fn set_cursor(&mut self, n: usize) {
        self.cursor = clamp(n, 0, self.rows.len().saturating_sub(1));
        self.update_viewport();
    }

    /// MoveUp moves the selection up by any number of rows.
    /// It can not go above the first row.
    pub fn move_up(&mut self, n: usize) {
        // Upstream uses signed ints and clamps to 0; saturating subtraction
        // mirrors that without overflowing.
        self.cursor = clamp(
            self.cursor.saturating_sub(n),
            0,
            self.rows.len().saturating_sub(1),
        );

        let mut offset = self.viewport.y_offset();
        if self.start == 0 {
            offset = clamp(offset, 0, self.cursor);
        } else if self.start < self.viewport.height() {
            offset = clamp(clamp(offset + n, 0, self.cursor), 0, self.viewport.height());
        } else if offset >= 1 {
            offset = clamp(offset + n, 1, self.viewport.height());
        }
        self.viewport.set_y_offset(offset);
        self.update_viewport();
    }

    /// MoveDown moves the selection down by any number of rows.
    /// It can not go below the last row.
    pub fn move_down(&mut self, n: usize) {
        self.cursor = clamp(self.cursor + n, 0, self.rows.len().saturating_sub(1));
        self.update_viewport();

        let mut offset = self.viewport.y_offset();
        if self.end == self.rows.len() && offset > 0 {
            offset = clamp(offset - n, 1, self.viewport.height());
        } else if self.cursor > (self.end - self.start) / 2 && offset > 0 {
            offset = clamp(offset - n, 1, self.cursor);
        } else if offset > 1 {
            // no-op
        } else if self.cursor > offset + self.viewport.height() - 1 {
            offset = clamp(offset + 1, 0, 1);
        }
        self.viewport.set_y_offset(offset);
    }

    /// GotoTop moves the selection to the first row.
    pub fn goto_top(&mut self) {
        let n = self.cursor;
        self.move_up(n);
    }

    /// GotoBottom moves the selection to the last row.
    pub fn goto_bottom(&mut self) {
        let n = self.rows.len();
        self.move_down(n);
    }

    /// FromValues create the table rows from a simple string. It uses `\n`
    /// by default for getting all the rows and the given separator for the
    /// fields on each row.
    pub fn from_values(&mut self, value: &str, separator: &str) {
        let mut rows: Vec<Row> = vec![];
        for line in value.split('\n') {
            let mut r: Row = vec![];
            for field in line.split(separator) {
                r.push(field.to_string());
            }
            rows.push(r);
        }

        self.set_rows(&rows);
    }

    fn headers_view(&self) -> String {
        let mut s: Vec<String> = Vec::with_capacity(self.cols.len());
        for col in &self.cols {
            if col.width == 0 {
                continue;
            }
            let style = rusty_lipgloss::new_style()
                .width(col.width)
                .max_width(col.width)
                .inline(true);
            let rendered_cell = style.render(&rusty_x_ansi::truncate(&col.title, col.width, ""));
            s.push(self.styles.header.clone().render(&rendered_cell));
        }
        let refs: Vec<&str> = s.iter().map(|x| x.as_str()).collect();
        rusty_lipgloss::join::join_horizontal(rusty_lipgloss::TOP, &refs)
    }

    fn render_row(&self, r: usize) -> String {
        let mut s: Vec<String> = Vec::with_capacity(self.cols.len());
        for (i, value) in self.rows[r].iter().enumerate() {
            if self.cols[i].width == 0 {
                continue;
            }
            let style = rusty_lipgloss::new_style()
                .width(self.cols[i].width)
                .max_width(self.cols[i].width)
                .inline(true);
            let rendered_cell =
                style.render(&rusty_x_ansi::truncate(value, self.cols[i].width, ""));
            s.push(self.styles.cell.clone().render(&rendered_cell));
        }

        let refs: Vec<&str> = s.iter().map(|x| x.as_str()).collect();
        let row = rusty_lipgloss::join::join_horizontal(rusty_lipgloss::TOP, &refs);

        if r == self.cursor {
            return self.styles.selected.clone().render(&row);
        }

        row
    }
}

fn clamp(v: usize, low: usize, high: usize) -> usize {
    v.max(low).min(high)
}