Skip to main content

gpui_component/setting/
page.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, Entity, InteractiveElement as _, IntoElement, ListAlignment, ListOffset,
5    ListState, ParentElement as _, SharedString, StyleRefinement, Styled, Window, div, list,
6    prelude::FluentBuilder as _, px,
7};
8use rust_i18n::t;
9
10use crate::{
11    ActiveTheme, Icon, IconName, Sizable, StyledExt,
12    button::{Button, ButtonVariants},
13    h_flex,
14    label::Label,
15    scroll::ScrollableElement,
16    setting::{RenderOptions, SettingGroup, settings::SettingsState},
17    v_flex,
18};
19
20/// A setting page that can contain multiple setting groups.
21#[derive(Clone)]
22pub struct SettingPage {
23    pub(super) icon: Option<Icon>,
24    resettable: bool,
25    pub(super) default_open: bool,
26    pub(super) title: SharedString,
27    pub(super) title_suffix: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>>,
28    pub(super) description: Option<SharedString>,
29    pub(super) groups: Vec<SettingGroup>,
30    pub(super) header_style: StyleRefinement,
31}
32
33impl SettingPage {
34    pub fn new(title: impl Into<SharedString>) -> Self {
35        Self {
36            icon: None,
37            resettable: true,
38            default_open: false,
39            title: title.into(),
40            title_suffix: None,
41            description: None,
42            groups: Vec::new(),
43            header_style: StyleRefinement::default(),
44        }
45    }
46
47    /// Set the title of the setting page.
48    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
49        self.title = title.into();
50        self
51    }
52
53    /// Set a custom element to render after the title in the page header.
54    ///
55    /// For example, an info icon button that opens the help documentation.
56    pub fn title_suffix<F, E>(mut self, suffix: F) -> Self
57    where
58        E: IntoElement,
59        F: Fn(&mut Window, &mut App) -> E + 'static,
60    {
61        self.title_suffix = Some(Rc::new(move |window, cx| {
62            suffix(window, cx).into_any_element()
63        }));
64        self
65    }
66
67    /// Set the icon of the setting page.
68    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
69        self.icon = Some(icon.into());
70        self
71    }
72
73    /// Set the description of the setting page, default is None.
74    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
75        self.description = Some(description.into());
76        self
77    }
78
79    /// Set the default open state of the setting page, default is false.
80    pub fn default_open(mut self, default_open: bool) -> Self {
81        self.default_open = default_open;
82        self
83    }
84
85    /// Set whether the setting page is resettable, default is true.
86    ///
87    /// If true and the items in this page has changed, the reset button will appear.
88    pub fn resettable(mut self, resettable: bool) -> Self {
89        self.resettable = resettable;
90        self
91    }
92
93    /// Add a setting group to the page.
94    pub fn group(mut self, group: SettingGroup) -> Self {
95        self.groups.push(group);
96        self
97    }
98
99    /// Add multiple setting groups to the page.
100    pub fn groups(mut self, groups: impl IntoIterator<Item = SettingGroup>) -> Self {
101        self.groups.extend(groups);
102        self
103    }
104
105    /// Set the style refinement for the header of the setting page.
106    pub fn header_style(mut self, style: &StyleRefinement) -> Self {
107        self.header_style = style.clone();
108        self
109    }
110
111    fn is_resettable(&self, query: &str, cx: &App) -> bool {
112        self.resettable
113            && self
114                .groups
115                .iter()
116                .any(|group| group.is_resettable(query, cx))
117    }
118
119    fn reset_all(&self, query: &str, window: &mut Window, cx: &mut App) {
120        for group in &self.groups {
121            group.reset(query, window, cx);
122        }
123    }
124
125    pub(super) fn render(
126        &self,
127        ix: usize,
128        group_indices: &[usize],
129        state: &Entity<SettingsState>,
130        options: &RenderOptions,
131        window: &mut Window,
132        cx: &mut App,
133    ) -> impl IntoElement {
134        let search_input = state.read(cx).search_input.clone();
135        let query = search_input.read(cx).value();
136        let groups = group_indices
137            .iter()
138            .map(|&ix| (ix, self.groups[ix].clone()))
139            .collect::<Vec<_>>();
140        let groups_count = groups.len();
141
142        let page_state = window.use_keyed_state(
143            SharedString::from(format!("list-state:{}", ix)),
144            cx,
145            |_, _| PageState {
146                list: ListState::new(groups_count, ListAlignment::Top, px(100.)),
147                query: query.clone(),
148                groups: group_indices.to_vec(),
149            },
150        );
151        let changed =
152            page_state.read(cx).query != query || page_state.read(cx).groups != group_indices;
153        let list_state = page_state.read(cx).list.clone();
154        if changed {
155            page_state.update(cx, |state, _| {
156                state.list.reset(groups_count);
157                state.query = query.clone();
158                state.groups = group_indices.to_vec();
159            });
160        }
161
162        let deferred_scroll_group_ix = state.read(cx).deferred_scroll_group_ix;
163        let scroll_group_ix = deferred_scroll_group_ix.or_else(|| {
164            changed
165                .then_some(state.read(cx).selected_index.group_ix)
166                .flatten()
167        });
168        if deferred_scroll_group_ix.is_some() {
169            state.update(cx, |state, _| state.deferred_scroll_group_ix = None);
170        }
171        if let Some(group_ix) = scroll_group_ix
172            && let Some(visible_ix) = group_indices.iter().position(|&ix| ix == group_ix)
173        {
174            // Scroll by index: after a page switch the list is rebuilt unmeasured,
175            // and `scroll_to_reveal_item` would resolve to the top.
176            list_state.scroll_to(ListOffset {
177                item_ix: visible_ix,
178                offset_in_item: px(0.),
179            });
180        }
181
182        v_flex()
183            .id(ix)
184            .size_full()
185            .child(
186                v_flex()
187                    .p_4()
188                    .gap_3()
189                    .border_b_1()
190                    .border_color(cx.theme().border)
191                    .refine_style(&self.header_style)
192                    .child(
193                        h_flex()
194                            .justify_between()
195                            .child(
196                                h_flex()
197                                    .gap_1()
198                                    .child(self.title.clone())
199                                    .when_some(self.title_suffix.clone(), |this, suffix| {
200                                        this.child(suffix(window, cx))
201                                    }),
202                            )
203                            .when(self.is_resettable(&query, cx), |this| {
204                                this.child(
205                                    Button::new("reset")
206                                        .icon(IconName::Undo2)
207                                        .ghost()
208                                        .small()
209                                        .tooltip(t!("Settings.Reset All"))
210                                        .on_click({
211                                            let page = self.clone();
212                                            let query = query.clone();
213                                            move |_, window, cx| {
214                                                page.reset_all(&query, window, cx);
215                                            }
216                                        }),
217                                )
218                            }),
219                    )
220                    .when_some(self.description.clone(), |this, description| {
221                        this.child(
222                            Label::new(description)
223                                .text_sm()
224                                .text_color(cx.theme().muted_foreground),
225                        )
226                    }),
227            )
228            .child(
229                div()
230                    .px_4()
231                    .relative()
232                    .flex_1()
233                    .w_full()
234                    .child(
235                        list(list_state.clone(), {
236                            let query = query.clone();
237                            let options = *options;
238                            move |visible_ix, window, cx| {
239                                let (group_ix, group) = groups[visible_ix].clone();
240                                group
241                                    .py_4()
242                                    .render(
243                                        &query,
244                                        &options.with_page_ix(ix).with_group_ix(group_ix),
245                                        window,
246                                        cx,
247                                    )
248                                    .into_any_element()
249                            }
250                        })
251                        .size_full(),
252                    )
253                    .vertical_scrollbar(&list_state),
254            )
255    }
256}
257
258struct PageState {
259    list: ListState,
260    query: SharedString,
261    groups: Vec<usize>,
262}