summaryrefslogtreecommitdiff
path: root/schist_desktop_gui/src/gui/components/table/view_table.rs
blob: 725c5ff7ee5849b6e530e2e172231e43db7783c6 (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
use std::{fmt::Debug, hash::Hash};

use iced::widget::{
    column, container, row, scrollable, scrollable::Direction as ScrollableDirection,
};

use crate::{gui::components::Text, style::SPACING_MD, traits::Viewable};

use super::{Message, Table, Value};

impl<'a, Ix> Viewable<'a, Message> for Table<Ix>
where
    Ix: Clone + Debug + Eq + Hash,
{
    fn view(&'a self) -> iced::Element<'a, Message> {
        let headers = row(self.cols.iter().map(|col| {
            container(Text::default(&col.name))
                .width(iced::Length::Fixed(col.width))
                .into()
        }))
        .spacing(u32::from(SPACING_MD));

        let rows = column(self.rows.iter().map(|row_data| {
            row(self.cols.iter().map(|col| {
                container(
                    row_data
                        .get(&col.index)
                        .map(|datum| match datum {
                            Value::String(text) => format_string(text),
                            Value::Currency(amount) => format_currency(*amount),
                        })
                        .unwrap_or_else(|| Text::default("")),
                )
                .width(iced::Length::Fixed(col.width))
                .into()
            }))
            .spacing(u32::from(SPACING_MD))
            .into()
        }));

        scrollable(column![headers, rows].spacing(u32::from(SPACING_MD)))
            .direction(ScrollableDirection::Both {
                horizontal: Default::default(),
                vertical: Default::default(),
            })
            .into()
    }
}

fn format_string(text: &String) -> Text {
    Text::default(text).weak().small()
}

fn format_currency(amount: i32) -> Text {
    let text = if amount >= 0 {
        format!(" {} · {} ", amount / 100, amount % 100)
    } else {
        format!("({} · {})", -amount / 100, -amount % 100)
    };
    format_string(&text).align_right().width(iced::Length::Fill)
}