Skip to main content

gpui_material_components/navigation/
adaptive.rs

1use gpui::{
2    AnyElement, App, ElementId, Entity, InteractiveElement, IntoElement, ParentElement, Pixels,
3    RenderOnce, Role, SharedString, Size, StatefulInteractiveElement, Styled, Window, div,
4    prelude::FluentBuilder, px,
5};
6use gpui_base::TestSupportExt;
7use gpui_material_foundation::current_material_theme;
8use gpui_material_theme::{Direction, WidthClass};
9
10use super::{AdaptivePane, AdaptivePaneLayout, AdaptivePaneState, PaneAdaptStrategy, PaneRole};
11
12/// Which pane is visible in a single-pane [`ListDetail`] layout.
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum ListDetailPane {
15    /// Show the master list pane.
16    #[default]
17    List,
18    /// Show the detail pane.
19    Detail,
20}
21
22/// Shows a list or detail at compact and medium widths, and both at expanded
23/// widths. The owner retains pane entities and scroll handles, selects the
24/// narrow pane and supplies the back command.
25#[derive(IntoElement)]
26pub struct ListDetail {
27    id: ElementId,
28    list: Option<AnyElement>,
29    detail: AnyElement,
30    width: Pixels,
31    active: ListDetailPane,
32    list_width: Pixels,
33}
34
35impl ListDetail {
36    /// Creates a list-detail layout for the given available width, list pane, and detail pane.
37    pub fn new(
38        id: impl Into<ElementId>,
39        width: Pixels,
40        list: impl IntoElement,
41        detail: impl IntoElement,
42    ) -> Self {
43        Self {
44            id: id.into(),
45            list: Some(list.into_any_element()),
46            detail: detail.into_any_element(),
47            width,
48            active: ListDetailPane::List,
49            list_width: px(360.),
50        }
51    }
52
53    /// Creates the adaptive three-role form with the list at logical start.
54    pub fn adaptive(
55        id: impl Into<ElementId>,
56        viewport: Size<Pixels>,
57        state: &Entity<AdaptivePaneState>,
58        list: AdaptivePane,
59        detail: AdaptivePane,
60    ) -> AdaptivePaneLayout {
61        AdaptivePaneLayout::new(id, viewport, state)
62            .order([PaneRole::Secondary, PaneRole::Primary, PaneRole::Tertiary])
63            .pane(PaneRole::Secondary, list)
64            .pane(PaneRole::Primary, detail)
65    }
66
67    /// Shows detail full-width when the app has hidden its list.
68    pub fn detail_only(mut self, detail_only: bool) -> Self {
69        if detail_only {
70            self.list = None;
71            self.active = ListDetailPane::Detail;
72        }
73        self
74    }
75
76    /// Selects which pane is displayed when the layout is in single-pane mode (default [`ListDetailPane::List`]).
77    pub fn active_pane(mut self, pane: ListDetailPane) -> Self {
78        self.active = pane;
79        self
80    }
81
82    /// Sets the preferred width of the list pane in two-pane mode (default 360 px, capped at half the available width).
83    pub fn list_width(mut self, width: Pixels) -> Self {
84        self.list_width = width.max(px(0.));
85        self
86    }
87
88    /// Returns whether `width` falls in a single-pane breakpoint (`Compact` or `Medium`).
89    pub fn is_single_pane(width: Pixels) -> bool {
90        matches!(
91            WidthClass::from_width(width.into()),
92            WidthClass::Compact | WidthClass::Medium
93        )
94    }
95}
96
97impl RenderOnce for ListDetail {
98    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
99        let single = Self::is_single_pane(self.width);
100        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
101        let show_detail = !single || self.active == ListDetailPane::Detail || self.list.is_none();
102        let list = self.list.filter(|_| !single || !show_detail);
103        let root_id = self.id.clone();
104        div()
105            .id(self.id)
106            .test_support()
107            .size_full()
108            .flex()
109            .gap(px(if single { 0. } else { 24. }))
110            .when(rtl, Styled::flex_row_reverse)
111            .children(list.map(|list| {
112                div()
113                    .id((root_id.clone(), "list-pane"))
114                    .test_support()
115                    .min_w_0()
116                    .min_h_0()
117                    .flex()
118                    .flex_col()
119                    .when_else(single, Styled::flex_1, |pane| {
120                        pane.w(self.list_width.min(self.width / 2.)).flex_none()
121                    })
122                    .child(list)
123            }))
124            .children(show_detail.then(|| {
125                div()
126                    .id((root_id, "detail-pane"))
127                    .test_support()
128                    .min_w_0()
129                    .min_h_0()
130                    .flex()
131                    .flex_col()
132                    .flex_1()
133                    .child(self.detail)
134            }))
135    }
136}
137
138/// A main workspace with an optional trailing support pane. In single-pane
139/// mode the caller can show the supporting pane as a full-width view.
140#[derive(IntoElement)]
141pub struct SupportingPane {
142    id: ElementId,
143    primary: AnyElement,
144    supporting: AnyElement,
145    width: Pixels,
146    show_support: bool,
147}
148
149impl SupportingPane {
150    /// Creates a supporting-pane layout for the given available width, primary pane, and supporting pane.
151    pub fn new(
152        id: impl Into<ElementId>,
153        width: Pixels,
154        primary: impl IntoElement,
155        supporting: impl IntoElement,
156    ) -> Self {
157        Self {
158            id: id.into(),
159            primary: primary.into_any_element(),
160            supporting: supporting.into_any_element(),
161            width,
162            show_support: false,
163        }
164    }
165
166    /// Creates the adaptive form with a workspace and a supporting pane that
167    /// reflows underneath it when the directive allows a tall single column.
168    pub fn adaptive(
169        id: impl Into<ElementId>,
170        viewport: Size<Pixels>,
171        state: &Entity<AdaptivePaneState>,
172        primary: AdaptivePane,
173        supporting: AdaptivePane,
174    ) -> AdaptivePaneLayout {
175        let supporting = if supporting.has_adaptation() {
176            supporting
177        } else {
178            supporting.adapt(PaneAdaptStrategy::Reflow(PaneRole::Primary))
179        };
180        AdaptivePaneLayout::new(id, viewport, state)
181            .pane(PaneRole::Primary, primary)
182            .pane(PaneRole::Secondary, supporting)
183    }
184
185    /// Controls whether the supporting pane is shown full-width in single-pane mode (default `false`).
186    pub fn show_support(mut self, show_support: bool) -> Self {
187        self.show_support = show_support;
188        self
189    }
190}
191
192impl RenderOnce for SupportingPane {
193    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
194        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
195        let single = ListDetail::is_single_pane(self.width);
196        let root_id = self.id.clone();
197        div()
198            .id(self.id)
199            .test_support()
200            .size_full()
201            .flex()
202            .gap(px(if single { 0. } else { 24. }))
203            .when(rtl, Styled::flex_row_reverse)
204            .children((!single || !self.show_support).then(|| {
205                div()
206                    .id((root_id.clone(), "primary-pane"))
207                    .test_support()
208                    .min_w_0()
209                    .min_h_0()
210                    .flex()
211                    .flex_col()
212                    .flex_1()
213                    .child(self.primary)
214            }))
215            .children((!single || self.show_support).then(|| {
216                div()
217                    .id((root_id, "supporting-pane"))
218                    .test_support()
219                    .min_w_0()
220                    .min_h_0()
221                    .flex()
222                    .flex_col()
223                    .when_else(single, Styled::flex_1, |pane| {
224                        pane.w((self.width / 3.).min(px(360.))).flex_none()
225                    })
226                    .child(self.supporting)
227            }))
228    }
229}
230
231/// An ordered, vertically scrolling feed. Supply the same scroll handle when
232/// the number of columns changes. Cards are placed in reading order.
233#[derive(IntoElement)]
234pub struct Feed {
235    id: ElementId,
236    width: Pixels,
237    scroll: gpui::ScrollHandle,
238    cards: Vec<AnyElement>,
239    accessible_label: Option<SharedString>,
240}
241
242impl Feed {
243    /// Creates a responsive multi-column feed bound to the caller's scroll handle.
244    pub fn new(id: impl Into<ElementId>, width: Pixels, scroll: &gpui::ScrollHandle) -> Self {
245        Self {
246            id: id.into(),
247            width,
248            scroll: scroll.clone(),
249            cards: Vec::new(),
250            accessible_label: None,
251        }
252    }
253
254    /// Names the feed container (`Role::List`) for assistive technology.
255    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
256        self.accessible_label = Some(label.into());
257        self
258    }
259
260    /// Returns the number of columns used for `width` according to Material width classes.
261    pub fn columns(width: Pixels) -> usize {
262        match WidthClass::from_width(width.into()) {
263            WidthClass::Compact => 1,
264            WidthClass::Medium => 2,
265            WidthClass::Expanded => 3,
266            WidthClass::Large | WidthClass::ExtraLarge => 4,
267        }
268    }
269}
270
271impl ParentElement for Feed {
272    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
273        self.cards.extend(elements);
274    }
275}
276
277impl RenderOnce for Feed {
278    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
279        let columns = Self::columns(self.width);
280        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
281        let state = window.use_keyed_state((self.id.clone(), "feed-columns"), cx, |_, _| columns);
282        state.update(cx, |previous, _| {
283            if *previous != columns && !self.cards.is_empty() {
284                let first_card = (self.scroll.top_item() * *previous).min(self.cards.len() - 1);
285                self.scroll.scroll_to_top_of_item(first_card / columns);
286            }
287            *previous = columns;
288        });
289        let mut cards = self.cards.into_iter();
290        let rows = std::iter::from_fn(move || {
291            let card = cards.next()?;
292            let row = std::iter::once(card).chain(cards.by_ref().take(columns - 1));
293            let mut len = 0;
294            let mut line = div()
295                .flex()
296                .flex_none()
297                .gap(px(16.))
298                .when(rtl, Styled::flex_row_reverse)
299                .children(row.map(|card| {
300                    len += 1;
301                    div().flex_1().min_w_0().child(card)
302                }));
303            line.extend((len..columns).map(|_| div().flex_1().min_w_0().into_any_element()));
304            Some(line)
305        });
306        gpui_material_foundation::isolated_scroll(self.id, &self.scroll)
307            .test_support()
308            .role(Role::List)
309            .when_some(self.accessible_label, |feed, label| feed.aria_label(label))
310            .flex_1()
311            .w_full()
312            .min_w_0()
313            .flex()
314            .flex_col()
315            .gap(px(16.))
316            .p(px(16.))
317            .children(rows)
318    }
319}