Skip to main content

gpui_material_components/navigation/
scaffold.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, AvailableSpace, Bounds, Canvas, Div, Edges, ElementId, InteractiveElement,
5    IntoElement, ParentElement, Pixels, RenderOnce, Styled, Window, canvas, div,
6    prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::current_material_theme;
10use gpui_material_theme::Direction;
11
12use crate::{ScaffoldInsets, Sheet};
13
14/// Positions a scaffold's floating action within the usable content width.
15#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
16pub enum ScaffoldFabPosition {
17    Start,
18    Center,
19    #[default]
20    End,
21    /// At the logical end of the scaffold, over the bottom bar.
22    EndOverlay,
23}
24
25/// Resolved body layout before the content builder applies its padding.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct ScaffoldContentLayout {
28    /// Window-local bounds after the scaffold has allocated its bars and rail.
29    pub bounds: Bounds<Pixels>,
30    /// Space already allocated to the bars and rail.
31    pub occupied: ScaffoldInsets,
32    /// Remaining insets for the body or a child inside its scroll area.
33    pub padding: ScaffoldInsets,
34    pub direction: Direction,
35}
36
37type ContentBuilder = Box<dyn FnOnce(ScaffoldContentLayout, &mut Window, &mut App) -> AnyElement>;
38
39enum Content {
40    Element(AnyElement),
41    Builder(ContentBuilder),
42}
43
44/// Arranges the top app bar, leading rail, content and bottom bar. The floating
45/// action and snackbar are anchored within the content region above bottom
46/// navigation. Give the scaffold a bounded size and give its content a scroll
47/// viewport if needed.
48#[derive(IntoElement)]
49pub struct Scaffold {
50    id: ElementId,
51    content: Content,
52    app_bar: Option<AnyElement>,
53    rail: Option<AnyElement>,
54    bottom_bar: Option<AnyElement>,
55    bottom_sheet: Option<Sheet>,
56    fab: Option<AnyElement>,
57    snackbar: Option<AnyElement>,
58    fab_position: ScaffoldFabPosition,
59    content_insets: ScaffoldInsets,
60}
61
62impl Scaffold {
63    pub fn new(id: impl Into<ElementId>, content: impl IntoElement) -> Self {
64        Self::with_content(id.into(), Content::Element(content.into_any_element()))
65    }
66
67    /// Builds the body with its current layout. Apply `layout.padding` once;
68    /// the scaffold has already allocated `layout.occupied`.
69    pub fn with_layout<E: IntoElement>(
70        id: impl Into<ElementId>,
71        content: impl FnOnce(ScaffoldContentLayout, &mut Window, &mut App) -> E + 'static,
72    ) -> Self {
73        Self::with_content(
74            id.into(),
75            Content::Builder(Box::new(move |layout, window, cx| {
76                content(layout, window, cx).into_any_element()
77            })),
78        )
79    }
80
81    fn with_content(id: ElementId, content: Content) -> Self {
82        Self {
83            id,
84            content,
85            app_bar: None,
86            rail: None,
87            bottom_bar: None,
88            bottom_sheet: None,
89            fab: None,
90            snackbar: None,
91            fab_position: ScaffoldFabPosition::default(),
92            content_insets: ScaffoldInsets::default(),
93        }
94    }
95
96    pub fn app_bar(mut self, element: impl IntoElement) -> Self {
97        self.app_bar = Some(element.into_any_element());
98        self
99    }
100
101    pub fn rail(mut self, element: impl IntoElement) -> Self {
102        self.rail = Some(element.into_any_element());
103        self
104    }
105
106    pub fn bottom_bar(mut self, element: impl IntoElement) -> Self {
107        self.bottom_bar = Some(element.into_any_element());
108        self
109    }
110
111    /// Places a Standard bottom sheet beneath the measured content column.
112    pub fn bottom_sheet(mut self, sheet: Sheet) -> Self {
113        self.bottom_sheet = Some(sheet);
114        self
115    }
116
117    pub fn fab(mut self, element: impl IntoElement) -> Self {
118        self.fab = Some(element.into_any_element());
119        self
120    }
121
122    pub fn snackbar(mut self, element: impl IntoElement) -> Self {
123        self.snackbar = Some(element.into_any_element());
124        self
125    }
126
127    pub fn fab_position(mut self, position: ScaffoldFabPosition) -> Self {
128        self.fab_position = position;
129        self
130    }
131
132    /// Sets minimum distances from the scaffold's edges to usable content.
133    /// Space occupied by bars and the rail counts toward those distances.
134    pub fn content_insets(mut self, insets: ScaffoldInsets) -> Self {
135        self.content_insets = insets.normalized();
136        self
137    }
138}
139
140impl RenderOnce for Scaffold {
141    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
142        let direction = current_material_theme(window, cx).layout.direction;
143        let position = self.fab_position;
144        let insets = self.content_insets;
145        let (fab, snackbar, overlay) = match (position, self.fab) {
146            (ScaffoldFabPosition::EndOverlay, Some(fab)) => {
147                (None, None, Some((fab, self.snackbar)))
148            }
149            (_, fab) => (fab, self.snackbar, None),
150        };
151        let needs_layout = overlay.is_some()
152            || insets != ScaffoldInsets::default()
153            || matches!(self.content, Content::Builder(_));
154        let geometry = Rc::new(ScaffoldGeometry::default());
155        let body_geometry = geometry.clone();
156        let body = div()
157            .id("scaffold-content")
158            .test_support()
159            .relative()
160            .flex()
161            .flex_col()
162            .flex_1()
163            .min_w_0()
164            .min_h_0();
165        let body =
166            match self.content {
167                Content::Element(content) if !needs_layout => body
168                    .child(body_wrapper().child(content))
169                    .children(standard_overlay(
170                        fab,
171                        snackbar,
172                        position,
173                        insets.resolve(direction),
174                        direction,
175                    )),
176                content => body.child(
177                    laid_out_slot(move |bounds, window, cx| {
178                        let layout = body_geometry.resolve(bounds, insets, direction);
179                        let padding = layout.padding.resolve(direction);
180                        let content = match content {
181                            Content::Element(content) => body_wrapper()
182                                .pt(padding.top)
183                                .pr(padding.right)
184                                .pb(padding.bottom)
185                                .pl(padding.left)
186                                .child(content),
187                            Content::Builder(build) => {
188                                body_wrapper().child(build(layout, window, cx))
189                            }
190                        };
191                        div().relative().flex().flex_col().child(content).children(
192                            standard_overlay(fab, snackbar, position, padding, direction),
193                        )
194                    })
195                    .size_full(),
196                ),
197            };
198        let column = match self.bottom_sheet {
199            Some(sheet) => div()
200                .flex_1()
201                .min_w_0()
202                .min_h_0()
203                .child(
204                    laid_out_slot(move |bounds, _, _| {
205                        div()
206                            .flex()
207                            .flex_col()
208                            .child(body)
209                            .child(div().flex_none().child(sheet.in_scaffold(bounds.size)))
210                    })
211                    .size_full(),
212                )
213                .into_any_element(),
214            None => body.into_any_element(),
215        };
216        let root_geometry = geometry.clone();
217        div()
218            .id(self.id)
219            .test_support()
220            .size_full()
221            .min_h_0()
222            .min_w_0()
223            .flex()
224            .flex_col()
225            .when(needs_layout, move |root| {
226                root.relative().child(
227                    canvas(
228                        move |bounds, _, _| root_geometry.root.set(Some(bounds)),
229                        |_, (), _, _| {},
230                    )
231                    .absolute()
232                    .inset_0(),
233                )
234            })
235            .children(self.app_bar.map(|bar| div().flex_none().child(bar)))
236            .child(
237                div()
238                    .flex_1()
239                    .min_h_0()
240                    .flex()
241                    .when(direction == Direction::Rtl, Styled::flex_row_reverse)
242                    .children(self.rail.map(|rail| div().flex_none().h_full().child(rail)))
243                    .child(column),
244            )
245            .children(self.bottom_bar.map(|bar| div().flex_none().child(bar)))
246            .children(overlay.map(move |(fab, snackbar)| {
247                laid_out_slot(move |root, _, _| {
248                    let layout = geometry
249                        .layout
250                        .get()
251                        .unwrap_or_else(|| geometry.resolve(root, insets, direction));
252                    end_overlay(fab, snackbar, root, layout, insets.bottom)
253                })
254                .absolute()
255                .inset_0()
256            }))
257    }
258}
259
260fn body_wrapper() -> Div {
261    div().flex_1().min_h_0().min_w_0().flex().flex_col()
262}
263
264#[derive(Default)]
265struct ScaffoldGeometry {
266    root: Cell<Option<Bounds<Pixels>>>,
267    layout: Cell<Option<ScaffoldContentLayout>>,
268}
269
270impl ScaffoldGeometry {
271    fn resolve(
272        &self,
273        bounds: Bounds<Pixels>,
274        requested: ScaffoldInsets,
275        direction: Direction,
276    ) -> ScaffoldContentLayout {
277        let root = self.root.get().unwrap_or(bounds);
278        let occupied = ScaffoldInsets {
279            top: (bounds.top() - root.top()).max(px(0.)),
280            start: if direction == Direction::Rtl {
281                (root.right() - bounds.right()).max(px(0.))
282            } else {
283                (bounds.left() - root.left()).max(px(0.))
284            },
285            bottom: (root.bottom() - bounds.bottom()).max(px(0.)),
286            end: px(0.),
287        };
288        let top = (requested.top - occupied.top)
289            .max(px(0.))
290            .min(bounds.size.height);
291        let start = (requested.start - occupied.start)
292            .max(px(0.))
293            .min(bounds.size.width);
294        let padding = ScaffoldInsets {
295            top,
296            start,
297            bottom: (requested.bottom - occupied.bottom)
298                .max(px(0.))
299                .min(bounds.size.height - top),
300            end: requested.end.min(bounds.size.width - start),
301        };
302        let layout = ScaffoldContentLayout {
303            bounds,
304            occupied,
305            padding,
306            direction,
307        };
308        self.layout.set(Some(layout));
309        layout
310    }
311}
312
313// Resolve the body against the outer flex layout before building its contents.
314// The resulting child is laid out, prepainted, and painted exactly once.
315fn laid_out_slot(
316    build: impl FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> Div + 'static,
317) -> Canvas<AnyElement> {
318    canvas(
319        move |bounds, window, cx| {
320            let mut child = build(bounds, window, cx)
321                .w(bounds.size.width)
322                .h(bounds.size.height)
323                .into_any_element();
324            child.layout_as_root(bounds.size.map(AvailableSpace::Definite), window, cx);
325            child.prepaint_at(bounds.origin, window, cx);
326            child
327        },
328        |_, mut child, window, cx| child.paint(window, cx),
329    )
330}
331
332fn fab_row(position: ScaffoldFabPosition, direction: Direction) -> Div {
333    let row = div().flex();
334    match (position, direction) {
335        (ScaffoldFabPosition::Center, _) => row.justify_center(),
336        (ScaffoldFabPosition::Start, Direction::Ltr)
337        | (ScaffoldFabPosition::End | ScaffoldFabPosition::EndOverlay, Direction::Rtl) => {
338            row.justify_start()
339        }
340        _ => row.justify_end(),
341    }
342}
343
344fn standard_overlay(
345    fab: Option<AnyElement>,
346    snackbar: Option<AnyElement>,
347    position: ScaffoldFabPosition,
348    padding: Edges<Pixels>,
349    direction: Direction,
350) -> Option<Div> {
351    (fab.is_some() || snackbar.is_some()).then(|| {
352        div()
353            .absolute()
354            .left(padding.left)
355            .right(padding.right)
356            .bottom(padding.bottom)
357            .min_w_0()
358            .flex()
359            .flex_col()
360            .gap(px(8.))
361            .p(px(16.))
362            .children(fab.map(|fab| fab_row(position, direction).child(fab)))
363            .children(snackbar)
364    })
365}
366
367fn end_overlay(
368    fab: AnyElement,
369    snackbar: Option<AnyElement>,
370    root: Bounds<Pixels>,
371    layout: ScaffoldContentLayout,
372    bottom_inset: Pixels,
373) -> Div {
374    let padding = layout.padding.resolve(layout.direction);
375    let bottom = bottom_inset.min(root.size.height);
376    let fab = fab_row(ScaffoldFabPosition::EndOverlay, layout.direction)
377        .items_end()
378        .pb(px(16.))
379        .when(snackbar.is_some(), |fab| {
380            // Reserve the taller of the bottom bar and the FAB band. The
381            // button stays at the bottom of the band even with a tall bar.
382            fab.min_h((layout.occupied.bottom + px(16.) - bottom).max(px(0.)))
383                .pt(px(8.))
384        })
385        .child(fab);
386    div().relative().child(
387        div()
388            .absolute()
389            .left(layout.bounds.left() - root.left() + padding.left)
390            .right(root.right() - layout.bounds.right() + padding.right)
391            .bottom(bottom)
392            .min_w_0()
393            .flex()
394            .flex_col()
395            .px(px(16.))
396            .children(snackbar)
397            .child(fab),
398    )
399}