summaryrefslogtreecommitdiffstats
path: root/src/tuice/component/base/text_table.rs
blob: 782313b9c3d05c99343fb5c5e38bb81d40a882e1 (plain)
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
pub mod table_column;
mod table_scroll_state;

use std::{borrow::Cow, cmp::min};

use tui::{
    backend::Backend,
    layout::{Constraint, Rect},
    style::Style,
    widgets::{Row, Table},
    Frame,
};
use unicode_segmentation::UnicodeSegmentation;

use crate::{
    constants::TABLE_GAP_HEIGHT_LIMIT,
    tuice::{Component, DrawContext, Element, Event, Properties, Status},
};

pub use self::table_column::{TextColumn, TextColumnConstraint};
use self::table_scroll_state::ScrollState as TextTableState;

/// Styles for a [`TextTable`].
#[derive(Clone, Debug, Default)]
pub struct StyleSheet {
    text: Style,
    selected_text: Style,
    table_header: Style,
}

/// Properties for a [`TextTable`].
#[derive(PartialEq, Clone, Debug)]
pub struct TextTableProps {}

impl Properties for TextTableProps {}

/// A sortable, scrollable table for text data.
pub struct TextTable<'a, Message> {
    state: TextTableState,
    column_widths: Vec<u16>,
    columns: Vec<TextColumn>,
    show_gap: bool,
    show_selected_entry: bool,
    rows: Vec<Row<'a>>,
    style_sheet: StyleSheet,
    sortable: bool,
    table_gap: u16,
    on_select: Option<Box<dyn Fn(usize) -> Message>>,
    on_selected_click: Option<Box<dyn Fn(usize) -> Message>>,
}

impl<'a, Message> TextTable<'a, Message> {
    pub fn new<S: Into<Cow<'static, str>>>(columns: Vec<S>) -> Self {
        Self {
            state: TextTableState::default(),
            column_widths: vec![0; columns.len()],
            columns: columns
                .into_iter()
                .map(|name| TextColumn::new(name))
                .collect(),
            show_gap: true,
            show_selected_entry: true,
            rows: Vec::default(),
            style_sheet: StyleSheet::default(),
            sortable: false,
            table_gap: 0,
            on_select: None,
            on_selected_click: None,
        }
    }

    /// Sets the row to display in the table.
    ///
    /// Defaults to displaying no data if not set.
    pub fn rows(mut self, rows: Vec<Row<'a>>) -> Self {
        self.rows = rows;
        self
    }

    /// Whether to try to show a gap between the table headers and data.
    /// Note that if there isn't enough room, the gap will still be hidden.
    ///
    /// Defaults to `true` if not set.
    pub fn show_gap(mut self, show_gap: bool) -> Self {
        self.show_gap = show_gap;
        self
    }

    /// Whether to highlight the selected entry.
    ///
    /// Defaults to `true` if not set.
    pub fn show_selected_entry(mut self, show_selected_entry: bool) -> Self {
        self.show_selected_entry = show_selected_entry;
        self
    }

    /// Whether the table should display as sortable.
    ///
    /// Defaults to `false` if not set.
    pub fn sortable(mut self, sortable: bool) -> Self {
        self.sortable = sortable;
        self
    }

    /// What to do when selecting an entry. Expects a boxed function that takes in
    /// the currently selected index and returns a [`Message`].
    ///
    /// Defaults to `None` if not set.
    pub fn on_select(mut self, on_select: Option<Box<dyn Fn(usize) -> Message>>) -> Self {
        self.on_select = on_select;
        self
    }

    /// What to do when clicking on an entry that is already selected.
    ///
    /// Defaults to `None` if not set.
    pub fn on_selected_click(
        mut self, on_selected_click: Option<Box<dyn Fn(usize) -> Message>>,
    ) -> Self {
        self.on_selected_click = on_selected_click;
        self
    }

    fn update_column_widths(&mut self, bounds: Rect) {
        let total_width = bounds.width;
        let mut width_remaining = bounds.width;

        let mut column_widths: Vec<u16> = self
            .columns
            .iter()
            .map(|column| {
                let width = match column.width_constraint {
                    TextColumnConstraint::Fill => {
                        let desired = column.name.graphemes(true).count().saturating_add(1) as u16;
                        min(desired, width_remaining)
                    }
                    TextColumnConstraint::Length(length) => min(length, width_remaining),
                    TextColumnConstraint::Percentage(percentage) => {
                        let length = total_width * percentage / 100;
                        min(length, width_remaining)
                    }
                    TextColumnConstraint::MaxLength(length) => {
                        let desired = column.name.graphemes(true).count().saturating_add(1) as u16;
                        min(min(length, desired), width_remaining)
                    }
                    TextColumnConstraint::MaxPercentage(percentage) => {
                        let desired = column.name.graphemes(true).count().saturating_add(1) as u16;
                        let length = total_width * percentage / 100;
                        min(min(desired, length), width_remaining)
                    }
                };
                width_remaining -= width;
                width
            })
            .collect();

        if !column_widths.is_empty() {
            let amount_per_slot = width_remaining / column_widths.len() as u16;
            width_remaining %= column_widths.len() as u16;
            for (index, width) in column_widths.iter_mut().enumerate() {
                if (index as u16) < width_remaining {
                    *width += amount_per_slot + 1;
                } else {
                    *width += amount_per_slot;
                }
            }
        }

        self.column_widths = column_widths;
    }
}

impl<'a, Message, B: Backend> Component<Message, B> for TextTable<'a, Message> {
    fn draw(&mut self, context: DrawContext<'_>, frame: &mut Frame<'_, B>) {
        let rect = context.rect();

        self.table_gap = if !self.show_gap
            || (self.rows.len() + 2 > rect.height.into() && rect.height < TABLE_GAP_HEIGHT_LIMIT)
        {
            0
        } else {
            1
        };

        let table_extras = 1 + self.table_gap;
        let scrollable_height = rect.height.saturating_sub(table_extras);
        self.update_column_widths(rect);

        // Calculate widths first, since we need them later.
        let widths = self
            .column_widths
            .iter()
            .map(|column| Constraint::Length(*column))
            .collect::<Vec<_>>();

        // Then calculate rows. We truncate the amount of data read based on height,
        // as well as truncating some entries based on available width.
        let data_slice = {
            // Note: `get_list_start` already ensures `start` is within the bounds of the number of items, so no need to check!
            let start = self
                .state
                .display_start_index(rect, scrollable_height as usize);
            let end = min(self.state.num_items(), start + scrollable_height as usize);

            self.rows[start..end].to_vec()
        };

        // Now build up our headers...
        let header = Row::new(self.columns.iter().map(|column| column.name.clone()))
            .style(self.style_sheet.table_header)
            .bottom_margin(self.table_gap);

        let mut table = Table::new(data_slice)
            .header(header)
            .style(self.style_sheet.text);

        if self.show_selected_entry {
            table = table.highlight_style(self.style_sheet.selected_text);
        }

        frame.render_stateful_widget(table.widths(&widths), rect, self.state.tui_state());
    }

    fn on_event(&mut self, area: Rect, event: Event, messages: &mut Vec<Message>) -> Status {
        use crate::tuice::MouseBoundIntersect;
        use crossterm::event::{MouseButton, MouseEventKind};

        match event {
            Event::Keyboard(key_event) => {
                if key_event.modifiers.is_empty() {
                    match key_event.code {
                        _ => Status::Ignored,
                    }
                } else {
                    Status::Ignored
                }
            }
            Event::Mouse(mouse_event) => {
                if mouse_event.does_mouse_intersect_bounds(area) {
                    match mouse_event.kind {
                        MouseEventKind::Down(MouseButton::Left<