Skip to main content

gpui_material_extras/toolbar/bar/
layout.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, AvailableSpace, BorderStyle, Corners, ElementId, FocusHandle, Hsla,
5    InteractiveElement, IntoElement, IsZero, ParentElement, Pixels, Point, Size, Styled,
6    TextStyleRefinement, Window, canvas, div, prelude::FluentBuilder, px, quad, size,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{animate, elevation_shadows};
10use gpui_material_theme::{CornerShape, Direction, Elevation, MotionSpec};
11
12use super::{focus_handle, length};
13
14/// How a horizontal docked toolbar distributes unused width.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum ToolbarArrangement {
17    /// Packs actions toward the leading edge (respects RTL).
18    #[default]
19    Start,
20    /// Centers actions horizontally within the toolbar strip.
21    Center,
22    /// Packs actions toward the trailing edge (respects RTL).
23    End,
24    /// Distributes remaining space evenly between actions.
25    SpaceBetween,
26    /// Distributes remaining space around each action, with half-size outer margins.
27    SpaceAround,
28    /// Distributes remaining space equally between actions and both outer edges.
29    SpaceEvenly,
30}
31
32/// Logical insets in a toolbar's content area.
33#[derive(Clone, Copy, Debug, Default, PartialEq)]
34pub struct ToolbarPadding {
35    /// Top inset in logical pixels.
36    pub top: Pixels,
37    /// Leading-edge inset in logical pixels (mirrored in RTL).
38    pub start: Pixels,
39    /// Bottom inset in logical pixels.
40    pub bottom: Pixels,
41    /// Trailing-edge inset in logical pixels (mirrored in RTL).
42    pub end: Pixels,
43}
44
45impl ToolbarPadding {
46    pub(super) fn apply<E: Styled>(
47        self,
48        strip: E,
49        direction: Direction,
50        viewport: Size<Pixels>,
51    ) -> E {
52        let dimension = |side, extent| px(length(side).unwrap_or(0.)).min(extent / 2.);
53        let (left, right) = match direction {
54            Direction::Ltr => (self.start, self.end),
55            Direction::Rtl => (self.end, self.start),
56        };
57        strip
58            .pt(dimension(self.top, viewport.height))
59            .pb(dimension(self.bottom, viewport.height))
60            .pl(dimension(left, viewport.width))
61            .pr(dimension(right, viewport.width))
62    }
63}
64
65/// Elevations of an expanded and collapsed toolbar strip.
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
67pub struct ToolbarElevations {
68    /// Shadow elevation when the toolbar is expanded.
69    pub expanded: Option<Elevation>,
70    /// Shadow elevation when the toolbar is collapsed.
71    pub collapsed: Option<Elevation>,
72}
73
74/// Uses nonnegative flexible gaps so constrained children still flow forward.
75/// Each item is at index `2 * item + 1` before any direction reversal.
76pub(super) fn arrange_horizontal(
77    children: Vec<AnyElement>,
78    arrangement: ToolbarArrangement,
79    spacing: Pixels,
80) -> Vec<AnyElement> {
81    if children.is_empty() {
82        return children;
83    }
84    let (before, between, after) = match arrangement {
85        ToolbarArrangement::Start => (0., 0., 1.),
86        ToolbarArrangement::Center => (1., 0., 1.),
87        ToolbarArrangement::End => (1., 0., 0.),
88        ToolbarArrangement::SpaceBetween => (0., 1., 0.),
89        ToolbarArrangement::SpaceAround => (0.5, 1., 0.5),
90        ToolbarArrangement::SpaceEvenly => (1., 1., 1.),
91    };
92    let spacer = |weight, minimum| {
93        div()
94            .min_w(minimum)
95            .flex_grow(weight)
96            .flex_shrink(0.)
97            .flex_basis(minimum)
98            .into_any_element()
99    };
100    let mut result = Vec::with_capacity(children.len() * 2 + 1);
101    result.push(spacer(before, px(0.)));
102    let mut children = children.into_iter().peekable();
103    while let Some(child) = children.next() {
104        result.push(child);
105        if children.peek().is_some() {
106            result.push(spacer(between, spacing));
107        }
108    }
109    result.push(spacer(after, px(0.)));
110    result
111}
112
113pub(super) struct ToolbarSlot {
114    id: ElementId,
115    focus: FocusHandle,
116    element: AnyElement,
117}
118
119impl ToolbarSlot {
120    pub(super) fn new(
121        toolbar: &ElementId,
122        part: &'static str,
123        element: AnyElement,
124        window: &mut Window,
125        cx: &mut App,
126    ) -> Self {
127        let id = ElementId::from((toolbar.clone(), part));
128        let focus = focus_handle(&id, "scope", window, cx);
129        Self { id, focus, element }
130    }
131
132    pub(super) fn content(self) -> (AnyElement, FocusHandle) {
133        let host = div()
134            .id(self.id)
135            .test_support()
136            .track_focus(&self.focus)
137            .tab_stop(false)
138            .min_w_0()
139            .min_h_0()
140            .max_w_full()
141            .max_h_full()
142            .overflow_hidden()
143            .flex_none()
144            .child(self.element);
145        (host.into_any_element(), self.focus)
146    }
147
148    pub(super) fn expandable(
149        self,
150        expanded: bool,
151        horizontal: bool,
152        motion: MotionSpec,
153        ink: Hsla,
154        window: &mut Window,
155        cx: &mut App,
156    ) -> Option<(AnyElement, FocusHandle)> {
157        let shown = expanded || self.focus.contains_focused(window, cx);
158        let key = self.id.clone();
159        let fraction = animate(
160            (key.clone(), "slot-expansion"),
161            f32::from(shown),
162            motion,
163            window,
164            cx,
165        )
166        .clamp(0., 1.);
167        if fraction == 0. {
168            return None;
169        }
170        let bounds = window.use_keyed_state((key, "slot-intrinsic"), cx, |_, _| {
171            Size::<Pixels>::default()
172        });
173        let focus = self.focus.clone();
174        let child = shown.then(|| {
175            let (mut child, _) = self.content();
176            let measured = window.with_text_style(
177                Some(TextStyleRefinement {
178                    color: Some(ink),
179                    ..Default::default()
180                }),
181                |window| {
182                    child.layout_as_root(
183                        size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
184                        window,
185                        cx,
186                    )
187                },
188            );
189            bounds.update(cx, |size, _| *size = measured);
190            child
191        });
192        let preferred = *bounds.read(cx);
193        let footprint = if horizontal {
194            size(preferred.width * fraction, preferred.height)
195        } else {
196            size(preferred.width, preferred.height * fraction)
197        };
198        let host = div()
199            .w(footprint.width)
200            .h(footprint.height)
201            .min_w_0()
202            .min_h_0()
203            .max_w_full()
204            .max_h_full()
205            .flex_none()
206            .overflow_hidden()
207            .children(child.map(|mut child| {
208                canvas(
209                    move |bounds, window, cx| {
210                        child.prepaint_as_root(
211                            bounds.origin,
212                            bounds.size.map(AvailableSpace::Definite),
213                            window,
214                            cx,
215                        );
216                        child
217                    },
218                    |_, mut child, window, cx| child.paint(window, cx),
219                )
220                .size_full()
221            }));
222        Some((host.into_any_element(), focus))
223    }
224}
225
226pub(super) struct StripGeometry {
227    pub horizontal: bool,
228    pub docked: bool,
229    pub direction: Direction,
230    pub footprint: Rc<Cell<Size<Pixels>>>,
231    pub track_footprint: bool,
232    pub shape: CornerShape,
233    pub surface: Hsla,
234    pub shadow: Hsla,
235    pub elevation: f32,
236    pub slide: Point<Pixels>,
237    pub hidden: bool,
238}
239
240impl StripGeometry {
241    pub(super) fn frame(self, strip: impl IntoElement) -> AnyElement {
242        let frame = || {
243            div()
244                .relative()
245                .flex()
246                .items_center()
247                .min_w_0()
248                .min_h_0()
249                .max_w_full()
250                .max_h_full()
251                .flex_shrink(1.)
252                .when(self.docked && self.horizontal, Styled::w_full)
253                .when(self.docked && !self.horizontal, Styled::h_full)
254        };
255        let mut host = frame();
256        if self.hidden {
257            let previous = self.footprint.get();
258            host = host
259                .when(!(self.docked && self.horizontal), |host| {
260                    host.w(previous.width)
261                })
262                .when(!(self.docked && !self.horizontal), |host| {
263                    host.h(previous.height)
264                });
265        } else {
266            let shape = self.shape;
267            let direction = self.direction;
268            let surface = self.surface;
269            let shadow = self.shadow;
270            let elevation = self.elevation;
271            let paint = canvas(
272                |_, _, _| (),
273                move |bounds, (), window, _| {
274                    let [top_left, top_right, bottom_right, bottom_left] = shape
275                        .radii(
276                            bounds.size.width.into(),
277                            bounds.size.height.into(),
278                            direction,
279                        )
280                        .map(px);
281                    let corners = Corners {
282                        top_left,
283                        top_right,
284                        bottom_right,
285                        bottom_left,
286                    };
287                    if elevation > 0. {
288                        window.paint_drop_shadows(
289                            bounds,
290                            corners,
291                            &elevation_shadows(elevation, 1., shadow),
292                        );
293                    }
294                    if surface.a > 0. {
295                        window.paint_quad(quad(
296                            bounds,
297                            corners,
298                            surface,
299                            px(0.),
300                            gpui::transparent_black(),
301                            BorderStyle::Solid,
302                        ));
303                    }
304                },
305            )
306            .absolute()
307            .inset_0();
308            host = host
309                .when(!self.slide.is_zero(), Styled::overflow_hidden)
310                .child(
311                    frame()
312                        .left(self.slide.x)
313                        .top(self.slide.y)
314                        .child(paint)
315                        .child(strip),
316                );
317        }
318        host.child(
319            canvas(
320                move |bounds, window, _| {
321                    if self.footprint.replace(bounds.size) != bounds.size && self.track_footprint {
322                        window.request_animation_frame();
323                    }
324                },
325                |_, _, _, _| {},
326            )
327            .absolute()
328            .inset_0(),
329        )
330        .into_any_element()
331    }
332}