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