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        div()
104            .id(self.id)
105            .test_support()
106            .size_full()
107            .flex()
108            .gap(px(if single { 0. } else { 24. }))
109            .when(rtl, Styled::flex_row_reverse)
110            .children(list.map(|list| {
111                div()
112                    .id("list-pane")
113                    .test_support()
114                    .min_w_0()
115                    .min_h_0()
116                    .flex()
117                    .flex_col()
118                    .when_else(single, Styled::flex_1, |pane| {
119                        pane.w(self.list_width.min(self.width / 2.)).flex_none()
120                    })
121                    .child(list)
122            }))
123            .children(show_detail.then(|| {
124                div()
125                    .id("detail-pane")
126                    .test_support()
127                    .min_w_0()
128                    .min_h_0()
129                    .flex()
130                    .flex_col()
131                    .flex_1()
132                    .child(self.detail)
133            }))
134    }
135}
136
137/// A main workspace with an optional trailing support pane. In single-pane
138/// mode the caller can show the supporting pane as a full-width view.
139#[derive(IntoElement)]
140pub struct SupportingPane {
141    id: ElementId,
142    primary: AnyElement,
143    supporting: AnyElement,
144    width: Pixels,
145    show_support: bool,
146}
147
148impl SupportingPane {
149    /// Creates a supporting-pane layout for the given available width, primary pane, and supporting pane.
150    pub fn new(
151        id: impl Into<ElementId>,
152        width: Pixels,
153        primary: impl IntoElement,
154        supporting: impl IntoElement,
155    ) -> Self {
156        Self {
157            id: id.into(),
158            primary: primary.into_any_element(),
159            supporting: supporting.into_any_element(),
160            width,
161            show_support: false,
162        }
163    }
164
165    /// Creates the adaptive form with a workspace and a supporting pane that
166    /// reflows underneath it when the directive allows a tall single column.
167    pub fn adaptive(
168        id: impl Into<ElementId>,
169        viewport: Size<Pixels>,
170        state: &Entity<AdaptivePaneState>,
171        primary: AdaptivePane,
172        supporting: AdaptivePane,
173    ) -> AdaptivePaneLayout {
174        let supporting = if supporting.has_adaptation() {
175            supporting
176        } else {
177            supporting.adapt(PaneAdaptStrategy::Reflow(PaneRole::Primary))
178        };
179        AdaptivePaneLayout::new(id, viewport, state)
180            .pane(PaneRole::Primary, primary)
181            .pane(PaneRole::Secondary, supporting)
182    }
183
184    /// Controls whether the supporting pane is shown full-width in single-pane mode (default `false`).
185    pub fn show_support(mut self, show_support: bool) -> Self {
186        self.show_support = show_support;
187        self
188    }
189}
190
191impl RenderOnce for SupportingPane {
192    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
193        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
194        let single = ListDetail::is_single_pane(self.width);
195        div()
196            .id(self.id)
197            .test_support()
198            .size_full()
199            .flex()
200            .gap(px(if single { 0. } else { 24. }))
201            .when(rtl, Styled::flex_row_reverse)
202            .children((!single || !self.show_support).then(|| {
203                div()
204                    .id("primary-pane")
205                    .test_support()
206                    .min_w_0()
207                    .min_h_0()
208                    .flex()
209                    .flex_col()
210                    .flex_1()
211                    .child(self.primary)
212            }))
213            .children((!single || self.show_support).then(|| {
214                div()
215                    .id("supporting-pane")
216                    .test_support()
217                    .min_w_0()
218                    .min_h_0()
219                    .flex()
220                    .flex_col()
221                    .when_else(single, Styled::flex_1, |pane| {
222                        pane.w((self.width / 3.).min(px(360.))).flex_none()
223                    })
224                    .child(self.supporting)
225            }))
226    }
227}
228
229/// An ordered, vertically scrolling feed. Supply the same scroll handle when
230/// the number of columns changes. Cards are placed in reading order.
231#[derive(IntoElement)]
232pub struct Feed {
233    id: ElementId,
234    width: Pixels,
235    scroll: gpui::ScrollHandle,
236    cards: Vec<AnyElement>,
237    accessible_label: Option<SharedString>,
238}
239
240impl Feed {
241    /// Creates a responsive multi-column feed bound to the caller's scroll handle.
242    pub fn new(id: impl Into<ElementId>, width: Pixels, scroll: &gpui::ScrollHandle) -> Self {
243        Self {
244            id: id.into(),
245            width,
246            scroll: scroll.clone(),
247            cards: Vec::new(),
248            accessible_label: None,
249        }
250    }
251
252    /// Names the feed container (`Role::List`) for assistive technology.
253    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
254        self.accessible_label = Some(label.into());
255        self
256    }
257
258    /// Returns the number of columns used for `width` according to Material width classes.
259    pub fn columns(width: Pixels) -> usize {
260        match WidthClass::from_width(width.into()) {
261            WidthClass::Compact => 1,
262            WidthClass::Medium => 2,
263            WidthClass::Expanded => 3,
264            WidthClass::Large | WidthClass::ExtraLarge => 4,
265        }
266    }
267}
268
269impl ParentElement for Feed {
270    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
271        self.cards.extend(elements);
272    }
273}
274
275impl RenderOnce for Feed {
276    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
277        let columns = Self::columns(self.width);
278        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
279        let state = window.use_keyed_state((self.id.clone(), "feed-columns"), cx, |_, _| columns);
280        state.update(cx, |previous, _| {
281            if *previous != columns && !self.cards.is_empty() {
282                let first_card = (self.scroll.top_item() * *previous).min(self.cards.len() - 1);
283                self.scroll.scroll_to_top_of_item(first_card / columns);
284            }
285            *previous = columns;
286        });
287        let mut cards = self.cards.into_iter();
288        let rows = std::iter::from_fn(move || {
289            let card = cards.next()?;
290            let row = std::iter::once(card).chain(cards.by_ref().take(columns - 1));
291            let mut len = 0;
292            let mut line = div()
293                .flex()
294                .flex_none()
295                .gap(px(16.))
296                .when(rtl, Styled::flex_row_reverse)
297                .children(row.map(|card| {
298                    len += 1;
299                    div().flex_1().min_w_0().child(card)
300                }));
301            line.extend((len..columns).map(|_| div().flex_1().min_w_0().into_any_element()));
302            Some(line)
303        });
304        gpui_material_foundation::isolated_scroll(self.id, &self.scroll)
305            .test_support()
306            .role(Role::List)
307            .when_some(self.accessible_label, |feed, label| feed.aria_label(label))
308            .flex_1()
309            .w_full()
310            .min_w_0()
311            .flex()
312            .flex_col()
313            .gap(px(16.))
314            .p(px(16.))
315            .children(rows)
316    }
317}