yew_table/
table.rs

1use yew::Html;
2use serde::{Serialize};
3use serde_value::Value;
4use std::fmt;
5use crate::error::*;
6
7pub trait TableData: 'static + Default + Clone + Ord + Serialize {
8    /// Returns the Html representation of a field. When None, the field is not rendered.
9    fn get_field_as_html(&self, field_name: &str) -> Result<Html<Table<Self>>>;
10
11    /// Returns a table value given its field name. This value is used as a sorting key for the corresponding column.
12    fn get_field_as_value(&self, field_name: &str) -> Result<Value>;
13}
14
15#[derive(Clone, PartialEq, Default, Debug)]
16pub struct Column {
17    pub name: String,
18    pub short_name: Option<String>,
19    pub data_property: Option<String>,
20}
21
22impl fmt::Display for Column {
23    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
24        write!(f, "{}", self.short_name.as_ref().unwrap_or(&self.name))
25    }
26}
27
28#[derive(Clone, PartialEq)]
29pub struct TableOptions {
30    pub orderable: bool,
31}
32
33#[derive(Copy, Clone, PartialEq)]
34pub enum TableOrder {
35    Unordered = 0,
36    Ascending,
37    Descending,
38}
39
40impl Default for TableOrder {
41    fn default() -> Self { TableOrder::Unordered }
42}
43
44impl TableOrder {
45    pub fn rotate(&self) -> Self {
46        use TableOrder::*;
47        match *self {
48            Unordered => Ascending,
49            Ascending => Descending,
50            Descending => Unordered,
51        }
52    }
53}
54
55#[derive(Clone, PartialEq, Default)]
56pub struct TableState {
57    pub order: Vec<TableOrder>,
58}
59
60/// The a table with columns holding data.
61#[derive(Clone, PartialEq, Default)]
62pub struct Table<T> where T: TableData {
63    /// The order of the columns determines the order in which they are displayed.
64    pub (crate) columns: Vec<Column>,
65    pub (crate) data: Vec<T>,
66    pub (crate) options: Option<TableOptions>,
67    pub (crate) state: TableState,
68}
69
70impl<T> Table<T> where T: TableData {
71    pub fn is_orderable(&self) -> bool {
72        if let Some(options) = &self.options {
73            options.orderable
74        } else {
75            false
76        }
77    }
78}