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 = self.bottom_sheet.is_some()
152            || overlay.is_some()
153            || insets != ScaffoldInsets::default()
154            || matches!(self.content, Content::Builder(_));
155        let geometry = Rc::new(ScaffoldGeometry::default());
156        let body_geometry = geometry.clone();
157        let body = div()
158            .id("scaffold-content")
159            .test_support()
160            .relative()
161            .flex()
162            .flex_col()
163            .flex_1()
164            .min_w_0()
165            .min_h_0();
166        let body =
167            match self.content {
168                Content::Element(content) if !needs_layout => body
169                    .child(body_wrapper().child(content))
170                    .children(standard_overlay(
171                        fab,
172                        snackbar,
173                        position,
174                        insets.resolve(direction),
175                        direction,
176                    )),
177                content => body.child(
178                    laid_out_slot(move |bounds, window, cx| {
179                        let layout = body_geometry.resolve(bounds, insets, direction);
180                        let padding = layout.padding.resolve(direction);
181                        let content = match content {
182                            Content::Element(content) => body_wrapper()
183                                .pt(padding.top)
184                                .pr(padding.right)
185                                .pb(padding.bottom)
186                                .pl(padding.left)
187                                .child(content),
188                            Content::Builder(build) => {
189                                body_wrapper().child(build(layout, window, cx))
190                            }
191                        };
192                        div().relative().flex().flex_col().child(content).children(
193                            standard_overlay(fab, snackbar, position, padding, direction),
194                        )
195                    })
196                    .size_full(),
197                ),
198            };
199        let column = match self.bottom_sheet {
200            Some(sheet) => div()
201                .flex_1()
202                .min_w_0()
203                .min_h_0()
204                .child(
205                    laid_out_slot(move |bounds, _, _| {
206                        div()
207                            .flex()
208                            .flex_col()
209                            .child(body)
210                            .child(div().flex_none().child(sheet.in_scaffold(bounds.size)))
211                    })
212                    .size_full(),
213                )
214                .into_any_element(),
215            None => body.into_any_element(),
216        };
217        let root_geometry = geometry.clone();
218        div()
219            .id(self.id)
220            .test_support()
221            .size_full()
222            .min_h_0()
223            .min_w_0()
224            .flex()
225            .flex_col()
226            .when(needs_layout, move |root| {
227                root.relative().child(
228                    canvas(
229                        move |bounds, _, _| root_geometry.root.set(Some(bounds)),
230                        |_, (), _, _| {},
231                    )
232                    .absolute()
233                    .inset_0(),
234                )
235            })
236            .children(self.app_bar.map(|bar| div().flex_none().child(bar)))
237            .child(
238                div()
239                    .flex_1()
240                    .min_h_0()
241                    .flex()
242                    .when(direction == Direction::Rtl, Styled::flex_row_reverse)
243                    .children(self.rail.map(|rail| div().flex_none().h_full().child(rail)))
244                    .child(column),
245            )
246            .children(self.bottom_bar.map(|bar| div().flex_none().child(bar)))
247            .children(overlay.map(move |(fab, snackbar)| {
248                laid_out_slot(move |root, _, _| {
249                    let layout = geometry
250                        .layout
251                        .get()
252                        .unwrap_or_else(|| geometry.resolve(root, insets, direction));
253                    end_overlay(fab, snackbar, root, layout, insets.bottom)
254                })
255                .absolute()
256                .inset_0()
257            }))
258    }
259}
260
261fn body_wrapper() -> Div {
262    div().flex_1().min_h_0().min_w_0().flex().flex_col()
263}
264
265#[derive(Default)]
266struct ScaffoldGeometry {
267    root: Cell<Option<Bounds<Pixels>>>,
268    layout: Cell<Option<ScaffoldContentLayout>>,
269}
270
271impl ScaffoldGeometry {
272    fn resolve(
273        &self,
274        bounds: Bounds<Pixels>,
275        requested: ScaffoldInsets,
276        direction: Direction,
277    ) -> ScaffoldContentLayout {
278        let root = self.root.get().unwrap_or(bounds);
279        let occupied = ScaffoldInsets {
280            top: (bounds.top() - root.top()).max(px(0.)),
281            start: if direction == Direction::Rtl {
282                (root.right() - bounds.right()).max(px(0.))
283            } else {
284                (bounds.left() - root.left()).max(px(0.))
285            },
286            bottom: (root.bottom() - bounds.bottom()).max(px(0.)),
287            end: px(0.),
288        };
289        let top = (requested.top - occupied.top)
290            .max(px(0.))
291            .min(bounds.size.height);
292        let start = (requested.start - occupied.start)
293            .max(px(0.))
294            .min(bounds.size.width);
295        let padding = ScaffoldInsets {
296            top,
297            start,
298            bottom: (requested.bottom - occupied.bottom)
299                .max(px(0.))
300                .min(bounds.size.height - top),
301            end: requested.end.min(bounds.size.width - start),
302        };
303        let layout = ScaffoldContentLayout {
304            bounds,
305            occupied,
306            padding,
307            direction,
308        };
309        self.layout.set(Some(layout));
310        layout
311    }
312}
313
314// Resolve the body against the outer flex layout before building its contents.
315// The resulting child is laid out, prepainted, and painted exactly once.
316fn laid_out_slot(
317    build: impl FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> Div + 'static,
318) -> Canvas<AnyElement> {
319    canvas(
320        move |bounds, window, cx| {
321            let mut child = build(bounds, window, cx)
322                .w(bounds.size.width)
323                .h(bounds.size.height)
324                .into_any_element();
325            child.layout_as_root(bounds.size.map(AvailableSpace::Definite), window, cx);
326            child.prepaint_at(bounds.origin, window, cx);
327            child
328        },
329        |_, mut child, window, cx| child.paint(window, cx),
330    )
331}
332
333fn fab_row(position: ScaffoldFabPosition, direction: Direction) -> Div {
334    let row = div().flex();
335    match (position, direction) {
336        (ScaffoldFabPosition::Center, _) => row.justify_center(),
337        (ScaffoldFabPosition::Start, Direction::Ltr)
338        | (ScaffoldFabPosition::End | ScaffoldFabPosition::EndOverlay, Direction::Rtl) => {
339            row.justify_start()
340        }
341        _ => row.justify_end(),
342    }
343}
344
345fn standard_overlay(
346    fab: Option<AnyElement>,
347    snackbar: Option<AnyElement>,
348    position: ScaffoldFabPosition,
349    padding: Edges<Pixels>,
350    direction: Direction,
351) -> Option<Div> {
352    (fab.is_some() || snackbar.is_some()).then(|| {
353        div()
354            .absolute()
355            .left(padding.left)
356            .right(padding.right)
357            .bottom(padding.bottom)
358            .min_w_0()
359            .flex()
360            .flex_col()
361            .gap(px(8.))
362            .p(px(16.))
363            .children(fab.map(|fab| fab_row(position, direction).child(fab)))
364            .children(snackbar)
365    })
366}
367
368fn end_overlay(
369    fab: AnyElement,
370    snackbar: Option<AnyElement>,
371    root: Bounds<Pixels>,
372    layout: ScaffoldContentLayout,
373    bottom_inset: Pixels,
374) -> Div {
375    let padding = layout.padding.resolve(layout.direction);
376    let bottom = bottom_inset.min(root.size.height);
377    let fab = fab_row(ScaffoldFabPosition::EndOverlay, layout.direction)
378        .items_end()
379        .pb(px(16.))
380        .when(snackbar.is_some(), |fab| {
381            // Reserve the taller of the bottom bar and the FAB band. The
382            // button stays at the bottom of the band even with a tall bar.
383            fab.min_h((layout.occupied.bottom + px(16.) - bottom).max(px(0.)))
384                .pt(px(8.))
385        })
386        .child(fab);
387    div().relative().child(
388        div()
389            .absolute()
390            .left(layout.bounds.left() - root.left() + padding.left)
391            .right(root.right() - layout.bounds.right() + padding.right)
392            .bottom(bottom)
393            .min_w_0()
394            .flex()
395            .flex_col()
396            .px(px(16.))
397            .children(snackbar)
398            .child(fab),
399    )
400}