leptos_struct_table/components/
thead.rs

1use crate::wrapper_render_fn;
2use crate::{ColumnSort, TableHeadEvent};
3use leptos::*;
4
5wrapper_render_fn!(
6    /// thead
7    DefaultTableHeadRenderer,
8    thead,
9);
10
11wrapper_render_fn!(
12    /// thead row
13    DefaultTableHeadRowRenderer,
14    tr,
15);
16
17/// The default table header renderer. Renders roughly
18/// ```html
19/// <th>
20///    <span>Title</span>
21/// </th>
22/// ```
23#[component]
24pub fn DefaultTableHeaderCellRenderer<F>(
25    /// The class attribute for the head element. Generated by the classes provider.
26    #[prop(into)]
27    class: Signal<String>,
28    /// The class attribute for the inner element. Generated by the classes provider.
29    #[prop(into)]
30    inner_class: String,
31    /// The index of the column. Starts at 0 for the first column. The order of the columns is the same as the order of the fields in the struct.
32    index: usize,
33    /// The sort priority of the column. `None` if the column is not sorted. `0` means the column is the primary sort column.
34    #[prop(into)]
35    sort_priority: Signal<Option<usize>>,
36    /// The sort direction of the column. See [`ColumnSort`].
37    #[prop(into)]
38    sort_direction: Signal<ColumnSort>,
39    /// The event handler for the click event. Has to be called with [`TableHeadEvent`].
40    on_click: F,
41    children: Children,
42) -> impl IntoView
43where
44    F: Fn(TableHeadEvent) + 'static,
45{
46    let style = default_th_sorting_style(sort_priority, sort_direction);
47
48    view! {
49        <th class=class
50            on:click=move |mouse_event| on_click(TableHeadEvent {
51                index,
52                mouse_event,
53            })
54            style=style
55        >
56            <span class=inner_class>
57                {children()}
58            </span>
59        </th>
60    }
61}
62
63/// You can use this function to implement your own custom table header cell renderer.
64///
65/// See the implementation of [`DefaultTableHeaderCellRenderer`].
66pub fn default_th_sorting_style(
67    sort_priority: Signal<Option<usize>>,
68    sort_direction: Signal<ColumnSort>,
69) -> Signal<String> {
70    Signal::derive(move || {
71        let sort = match sort_direction.get() {
72            ColumnSort::Ascending => "--sort-icon: '▲';",
73            ColumnSort::Descending => "--sort-icon: '▼';",
74            ColumnSort::None => "--sort-icon: '';",
75        };
76
77        let priority = match sort_priority.get() {
78            Some(priority) => format!("--sort-priority: '{}';", priority + 1),
79            None => "--sort-priority: '';".to_string(),
80        };
81
82        format!("{} {}", sort, &priority)
83    })
84}