leptos_struct_table/
table_row.rs

1use crate::{ChangeEvent, ColumnSort, EventHandler, TableClassesProvider, TableHeadEvent};
2use leptos::*;
3use std::collections::VecDeque;
4
5/// This trait has to implemented in order for [`TableContent`] to be able to render rows and the head row of the table.
6/// Usually this is done by `#[derive(TableRow, Clone)]`.
7///
8/// Please see the [simple example](https://github.com/Synphonyte/leptos-struct-table/blob/master/examples/simple/src/main.rs)
9/// for how to use.
10pub trait TableRow: Clone {
11    type ClassesProvider: TableClassesProvider + Copy;
12
13    /// How many columns this row has (i.e. the number of fields in the struct)
14    const COLUMN_COUNT: usize;
15
16    /// Renders the inner of one row of the table using the cell renderers.
17    /// This produces the children that go into the `row_renderer` given to [`TableContent`].
18    ///
19    /// This render function has to render exactly one root element.
20    fn render_row(&self, index: usize, on_change: EventHandler<ChangeEvent<Self>>)
21        -> impl IntoView;
22
23    /// Render the head row of the table.
24    fn render_head_row<F>(
25        sorting: Signal<VecDeque<(usize, ColumnSort)>>,
26        on_head_click: F,
27    ) -> impl IntoView
28    where
29        F: Fn(TableHeadEvent) + Clone + 'static;
30
31    /// The name of the column (= struct field name) at the given index. This can be used to implement
32    /// sorting in a database. It takes the `#[table(skip)]` attributes into account. `col_index`
33    /// refers to the index of the field in the struct while ignoring skipped ones.
34    ///
35    /// For example:
36    /// ```
37    /// # use leptos_struct_table::*;
38    /// # use leptos::*;
39    /// #
40    /// #[derive(TableRow, Clone)]
41    /// struct Person {
42    ///     #[table(skip)]
43    ///     id: i64,            // -> ignored
44    ///
45    ///     name: String,       // -> col_index = 0
46    ///
47    ///     #[table(skip)]
48    ///     internal: usize,    // -> ignored
49    ///
50    ///     age: u16,           // -> col_index = 1
51    /// }
52    ///
53    /// assert_eq!(Person::col_name(0), "name");
54    /// assert_eq!(Person::col_name(1), "age");
55    /// ```
56    fn col_name(col_index: usize) -> &'static str;
57
58    /// Converts the given sorting to an SQL statement.
59    /// Return `None` when there is nothing to be sorted otherwise `Some("ORDER BY ...")`.
60    /// Uses [`Self::col_name`] to get the column names for sorting.
61    fn sorting_to_sql(sorting: &VecDeque<(usize, ColumnSort)>) -> Option<String> {
62        let mut sort = vec![];
63
64        for (col, col_sort) in sorting {
65            if let Some(col_sort) = col_sort.as_sql() {
66                sort.push(format!("{} {}", Self::col_name(*col), col_sort))
67            }
68        }
69
70        if sort.is_empty() {
71            return None;
72        }
73
74        Some(format!("ORDER BY {}", sort.join(", ")))
75    }
76}
77
78pub fn get_sorting_for_column(
79    col_index: usize,
80    sorting: Signal<VecDeque<(usize, ColumnSort)>>,
81) -> ColumnSort {
82    sorting.with(|sorting| {
83        sorting
84            .into_iter()
85            .find(|(col, _)| *col == col_index)
86            .map(|(_, sort)| *sort)
87            .unwrap_or(ColumnSort::None)
88    })
89}