Skip to main content

gpui_table_runtime/
generated_filters.rs

1use gpui_kit::{AnyElement, IntoElement, SharedString};
2use gpui_table_schema::{filter::FacetedFilterIcon, registry::RegistryFilterType};
3
4/// One generated filter rendered as sidebar-ready erased GPUI content.
5pub struct FilterSidebarItem {
6    field_id: SharedString,
7    label: SharedString,
8    filter_type: RegistryFilterType,
9    active: bool,
10    element: AnyElement,
11}
12
13impl FilterSidebarItem {
14    /// Create sidebar metadata and erase the concrete filter element type.
15    pub fn new(
16        field_id: impl Into<SharedString>,
17        label: impl Into<SharedString>,
18        filter_type: RegistryFilterType,
19        active: bool,
20        element: impl IntoElement,
21    ) -> Self {
22        Self {
23            field_id: field_id.into(),
24            label: label.into(),
25            filter_type,
26            active,
27            element: element.into_any_element(),
28        }
29    }
30
31    /// Stable table-and-field identifier for this filter.
32    pub fn field_id(&self) -> &SharedString {
33        &self.field_id
34    }
35
36    /// Localized field label.
37    pub fn label(&self) -> &SharedString {
38        &self.label
39    }
40
41    /// Semantic filter group.
42    pub fn filter_type(&self) -> RegistryFilterType {
43        self.filter_type
44    }
45
46    /// Whether the filter currently narrows the row set.
47    pub fn is_active(&self) -> bool {
48        self.active
49    }
50
51    /// Consume the descriptor and return its erased filter element.
52    pub fn into_element(self) -> AnyElement {
53        self.element
54    }
55}
56
57/// A nonempty semantic group of generated sidebar filters.
58pub struct FilterSidebarGroup {
59    filter_type: RegistryFilterType,
60    items: Vec<FilterSidebarItem>,
61}
62
63impl FilterSidebarGroup {
64    /// Semantic type shared by every item in this group.
65    pub fn filter_type(&self) -> RegistryFilterType {
66        self.filter_type
67    }
68
69    /// Sidebar items in source-field order.
70    pub fn items(&self) -> &[FilterSidebarItem] {
71        &self.items
72    }
73
74    /// Consume the group and return its sidebar items.
75    pub fn into_items(self) -> Vec<FilterSidebarItem> {
76        self.items
77    }
78}
79
80/// Grouped render data for one generated filter-entity collection.
81pub struct FilterSidebarData {
82    groups: Vec<FilterSidebarGroup>,
83    active_count: usize,
84}
85
86impl FilterSidebarData {
87    /// Group generated filters in the stable Text, Faceted, Number, Date order.
88    pub fn new(items: Vec<FilterSidebarItem>) -> Self {
89        let active_count = items.iter().filter(|item| item.is_active()).count();
90        let mut items = items.into_iter().map(Some).collect::<Vec<_>>();
91        let groups = [
92            RegistryFilterType::Text,
93            RegistryFilterType::Faceted,
94            RegistryFilterType::NumberRange,
95            RegistryFilterType::DateRange,
96        ]
97        .into_iter()
98        .filter_map(|filter_type| {
99            let grouped_items = items
100                .iter_mut()
101                .filter_map(|item| {
102                    (item.as_ref()?.filter_type() == filter_type)
103                        .then(|| item.take().expect("matching filter remains available"))
104                })
105                .collect::<Vec<_>>();
106            (!grouped_items.is_empty()).then_some(FilterSidebarGroup {
107                filter_type,
108                items: grouped_items,
109            })
110        })
111        .collect();
112
113        Self {
114            groups,
115            active_count,
116        }
117    }
118
119    /// Nonempty semantic groups in stable sidebar order.
120    pub fn groups(&self) -> &[FilterSidebarGroup] {
121        &self.groups
122    }
123
124    /// Number of active generated filters.
125    pub fn active_count(&self) -> usize {
126        self.active_count
127    }
128
129    /// Consume the data and return its groups.
130    pub fn into_groups(self) -> Vec<FilterSidebarGroup> {
131        self.groups
132    }
133}
134
135/// Trait for generated filter entity collections that can read and render their current values.
136///
137/// The derive macro also emits inherent `read_values()`, `apply_values()`,
138/// `filter_sidebar_data()`, `active_filter_count()`, and `reset_filters()`
139/// methods on each generated `XxxFilterEntities` type. This trait remains
140/// useful for generic helper code that wants to work across multiple generated
141/// filter collections.
142pub trait FilterEntitiesExt {
143    /// The filter values type that this entity collection produces.
144    type Values: gpui_table_core::filter::FilterValuesExt;
145
146    /// Read all current filter values into the generated filter-values struct.
147    ///
148    /// Individual wrapper fields can then be serialized with
149    /// `gpui_table_component::QueryFilterValue` when their wrapped type
150    /// supports query-string conversion.
151    fn read_values(&self, cx: &gpui_kit::App) -> Self::Values;
152
153    /// Replace every generated filter from a typed preset and notify once.
154    fn apply_values(
155        &self,
156        values: Self::Values,
157        window: &mut gpui_kit::Window,
158        cx: &mut gpui_kit::App,
159    );
160
161    /// Build grouped, sidebar-ready render data for all generated filters.
162    fn filter_sidebar_data(&self, cx: &gpui_kit::App) -> FilterSidebarData;
163
164    /// Count generated filters that currently narrow the row set.
165    fn active_filter_count(&self, cx: &gpui_kit::App) -> usize;
166
167    /// Reset every generated filter and notify the configured change callback once.
168    fn reset_filters(&self, window: &mut gpui_kit::Window, cx: &mut gpui_kit::App);
169}
170
171/// Convert a `gpui-kit` icon token into UI-neutral filter metadata.
172pub fn icon_from_name(name: impl gpui_kit::component::IconNamed) -> FacetedFilterIcon {
173    FacetedFilterIcon::from_path(name.path().to_string())
174}
175
176#[cfg(test)]
177mod tests {
178    use super::{FilterSidebarData, FilterSidebarItem, icon_from_name};
179    use gpui_kit::{SharedString, div};
180    use gpui_table_schema::registry::RegistryFilterType;
181
182    struct TestIcon;
183
184    impl gpui_kit::component::IconNamed for TestIcon {
185        fn path(self) -> SharedString {
186            "icons/test.svg".into()
187        }
188    }
189
190    #[test]
191    fn icon_names_convert_to_ui_neutral_metadata() {
192        assert_eq!(icon_from_name(TestIcon).path(), "icons/test.svg");
193    }
194
195    #[test]
196    fn sidebar_data_groups_in_stable_semantic_order_and_counts_active_items() {
197        let data = FilterSidebarData::new(vec![
198            FilterSidebarItem::new("date", "Date", RegistryFilterType::DateRange, false, div()),
199            FilterSidebarItem::new("status", "Status", RegistryFilterType::Faceted, true, div()),
200            FilterSidebarItem::new("name", "Name", RegistryFilterType::Text, true, div()),
201            FilterSidebarItem::new(
202                "amount",
203                "Amount",
204                RegistryFilterType::NumberRange,
205                false,
206                div(),
207            ),
208        ]);
209
210        assert_eq!(data.active_count(), 2);
211        assert_eq!(
212            data.groups()
213                .iter()
214                .map(|group| group.filter_type())
215                .collect::<Vec<_>>(),
216            vec![
217                RegistryFilterType::Text,
218                RegistryFilterType::Faceted,
219                RegistryFilterType::NumberRange,
220                RegistryFilterType::DateRange,
221            ]
222        );
223        assert_eq!(data.groups()[0].items()[0].field_id().as_ref(), "name");
224        assert!(data.groups()[0].items()[0].is_active());
225    }
226}