patternfly_yew/components/table/
header.rs

1use super::column::TableColumn;
2use crate::core::Order;
3use std::fmt::Debug;
4use yew::prelude::*;
5
6#[derive(Clone, Debug, PartialEq, Copy)]
7pub struct TableHeaderSortBy<K>
8where
9    K: Clone + Eq,
10{
11    pub index: K,
12    pub order: Order,
13}
14
15impl<K> TableHeaderSortBy<K>
16where
17    K: Clone + Eq,
18{
19    pub fn ascending(index: K) -> Self {
20        Self {
21            index,
22            order: Order::Ascending,
23        }
24    }
25
26    pub fn descending(index: K) -> Self {
27        Self {
28            index,
29            order: Order::Descending,
30        }
31    }
32}
33
34#[derive(Clone, Debug, PartialEq)]
35pub struct TableHeaderContext<K>
36where
37    K: Clone + Eq,
38{
39    pub sortby: Option<TableHeaderSortBy<K>>,
40    pub onsort: Callback<TableHeaderSortBy<K>>,
41}
42
43/// Properties for [`TableHeader`]
44#[derive(Debug, PartialEq, Clone, Properties)]
45pub struct TableHeaderProperties<K>
46where
47    K: Clone + Eq + 'static,
48{
49    #[prop_or_default]
50    pub sticky: bool,
51    #[prop_or_default]
52    pub children: ChildrenWithProps<TableColumn<K>>,
53    #[prop_or_default]
54    pub(crate) expandable: bool,
55    #[prop_or_default]
56    pub hide_actions: bool,
57}
58
59/// The Table Header component.
60///
61/// ## Properties
62///
63/// Defined by [`TableHeaderProperties`].
64#[function_component(TableHeader)]
65pub fn table_header<K>(props: &TableHeaderProperties<K>) -> Html
66where
67    K: Clone + Eq + 'static,
68{
69    let sortby: UseStateHandle<Option<TableHeaderSortBy<K>>> = use_state_eq(|| None);
70    let onsort = use_callback(sortby.clone(), |val: TableHeaderSortBy<K>, sortby| {
71        sortby.set(Some(val));
72    });
73
74    let table_header_context = TableHeaderContext {
75        onsort,
76        sortby: (*sortby).clone(),
77    };
78
79    html! (
80        <thead class="pf-v5-c-table__thead">
81
82            <tr class="pf-v5-c-table__tr" role="row">
83
84                if props.expandable {
85                    <td class="pf-v5-c-table__td pf-v5-c-table__toggle" role="cell"></td>
86                }
87
88                <ContextProvider<TableHeaderContext<K>> context={table_header_context}>
89                    { for props.children.iter() }
90                </ContextProvider<TableHeaderContext<K>>>
91
92                if !props.hide_actions {
93                    <td class="pf-v5-c-table__td"></td>
94                }
95
96            </tr>
97
98        </thead>
99    )
100}