summaryrefslogtreecommitdiffstats
path: root/src/tuine/component/text_table.rs
blob: bdfb104b7220f8b0ad3c57f38cf1e6ec36a37db2 (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
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,
    tuine::{Event, Status},
};

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

use super::{Component, ShouldRender};

#[derive(Clone, Debug, Default)]
pub struct StyleSheet {
    text: Style,
    selected_text: Style,
    table_header: Style,
}

pub enum TextTableMsg {}

/// A sortable, scrollable table for text data.
pub struct TextTable<'a> {
    state: TextTableState,
    column_widths: Vec<u16>,
    columns: Vec<TextColumn>,
    show_gap: bool,
    show_selected_entry: bool,
    data: Vec<Row<'a>>,
    style_sheet: StyleSheet,
    sortable: bool,
    table_gap: u16,
}

impl<'a> TextTable<'a> {
    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,
            data: Vec::default(),
            style_sheet: StyleSheet::default(),
            sortable: false,
            table_gap: 0,
        }
    }

    /// 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`.
    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`.
    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`.
    pub fn sortable(mut self, sortable: bool) -> Self {
        self.sortable = sortable;
        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> Component for TextTable<'a> {
    type Message = TextTableMsg;

    type Properties = ();

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

        match event {
            Event::Keyboard(_) => Status::Ignored,
            Event::Mouse(mouse_event) => {
                if mouse_event.does_mouse_intersect_bounds(bounds) {
                    match mouse_event.kind {
                        MouseEventKind::Down(MouseButton::Left) => {
                            let y = mouse_event.row - bounds.top();

                            if self.sortable && y == 0 {
                                // TODO: Do this
                                Status::Captured
                            } else if y > self.table_gap {
                                let visual_index = usize::from(y - self.table_gap);
                                self.state.set_visual_index(visual_index)
                            } else {
                                Status::Ignored
                            }
                        }
                        MouseEventKind::ScrollDown => self.state.move_down(1),
                        MouseEventKind::ScrollUp => self.state.move_up(1),
                        _ => Status::Ignored,
                    }
                } else {
                    Status::Ignored
                }
            }
        }
    }

    fn update(&mut self, message: Self::Message) -> ShouldRender {
        match message {}

        true
    }

    fn draw<B: Backend>(&mut self, bounds: Rect, frame: &mut Frame<'_, B>) {
        self.table_gap = if !self.show_gap
            || (self.data.len() + 2 > bounds.height.into()
                && bounds.height < TABLE_GAP_HEIGHT_LIMIT)
        {
            0
        } else {
            1
        };

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

        // 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(bounds, scrollable_height as usize);
            let end = min(self.state.num_items(), start + scrollable_height as usize);

            self.data[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), bounds, self.state.tui_state());
    }
}

#[cfg(test)]
mod tests {}