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