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