Skip to main content

gpui_deck/
styled.rs

1// Modified for GPUI Deck: update references to the extracted crate.
2use gpui::{
3    App, BoxShadow, Corners, DefiniteLength, Div, Edges, FocusHandle, Hsla, Pixels,
4    Refineable as _, Role, StyleRefinement, Styled, Window, div, hsla, point,
5};
6
7#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
8pub enum RoleOverride {
9    #[default]
10    Implicit,
11    Presentational,
12    Role(Role),
13}
14
15impl RoleOverride {
16    pub fn resolve(self, default: impl FnOnce() -> Role) -> Option<Role> {
17        match self {
18            Self::Implicit => Some(default()),
19            Self::Presentational => None,
20            Self::Role(role) => Some(role),
21        }
22    }
23}
24impl From<Role> for RoleOverride {
25    fn from(role: Role) -> Self {
26        Self::Role(role)
27    }
28}
29impl From<Option<Role>> for RoleOverride {
30    fn from(role: Option<Role>) -> Self {
31        role.map_or(Self::Presentational, Self::Role)
32    }
33}
34
35/// A row that centers its children on the cross axis.
36///
37/// See [`StyledExt::h_flex`] for the cross-axis rule, which is not symmetric
38/// with [`v_flex`].
39pub fn h_flex() -> Div {
40    div().h_flex()
41}
42
43/// A column whose children stretch across the cross axis.
44///
45/// See [`StyledExt::v_flex`] for the cross-axis rule, which is not symmetric
46/// with [`h_flex`].
47pub fn v_flex() -> Div {
48    div().v_flex()
49}
50
51pub fn box_shadow(
52    x: impl Into<Pixels>,
53    y: impl Into<Pixels>,
54    blur: impl Into<Pixels>,
55    spread: impl Into<Pixels>,
56    color: Hsla,
57) -> BoxShadow {
58    BoxShadow {
59        offset: point(x.into(), y.into()),
60        blur_radius: blur.into(),
61        spread_radius: spread.into(),
62        inset: false,
63        color,
64    }
65}
66
67macro_rules! font_weight {
68    ($method:ident, $weight:ident) => {
69        fn $method(self) -> Self {
70            self.font_weight(gpui::FontWeight::$weight)
71        }
72    };
73}
74
75#[cfg_attr(
76    any(feature = "inspector", debug_assertions),
77    gpui_macros::derive_inspector_reflection
78)]
79pub trait StyledExt: Styled + Sized {
80    fn refine_style(mut self, style: &StyleRefinement) -> Self {
81        self.style().refine(style);
82        self
83    }
84
85    /// Lays children out in a row, centered on the cross axis.
86    ///
87    /// The centering is the desktop default for a row of controls — an icon
88    /// beside its label lines up without either side asking for it — but it is
89    /// **not** the mirror image of [`Self::v_flex`], which leaves the cross axis
90    /// stretching. A column placed in a row therefore does not take the row's
91    /// height: it takes its content's height and is centered inside the row.
92    /// When its content is taller than the row, it overflows equally above and
93    /// below, so the column's header is pushed off the top edge and clipped.
94    ///
95    /// Give a full-height column `h_full()` (or the row `items_start()` /
96    /// `items_stretch()`) whenever the child owns a header, a footer, or a
97    /// scroll region that has to resolve against the row's height.
98    ///
99    /// ```
100    /// use gpui_deck::StyledExt as _;
101    /// use gpui::{ParentElement as _, Styled as _, div};
102    ///
103    /// // A sidebar beside a detail pane, both spanning the full height.
104    /// div().h_flex().size_full().child(div().w_64().h_full());
105    /// ```
106    fn h_flex(self) -> Self {
107        self.flex().flex_row().items_center()
108    }
109
110    /// Lays children out in a column, stretching them across the cross axis.
111    ///
112    /// Unlike [`Self::h_flex`] this installs no cross-axis alignment, so a child
113    /// without a width fills the column. See `h_flex` for the asymmetry.
114    fn v_flex(self) -> Self {
115        self.flex().flex_col()
116    }
117
118    fn paddings<L>(self, paddings: impl Into<Edges<L>>) -> Self
119    where
120        L: Into<DefiniteLength> + Clone + Default + std::fmt::Debug + PartialEq,
121    {
122        let paddings = paddings.into();
123        self.pt(paddings.top.into())
124            .pb(paddings.bottom.into())
125            .pl(paddings.left.into())
126            .pr(paddings.right.into())
127    }
128
129    fn margins<L>(self, margins: impl Into<Edges<L>>) -> Self
130    where
131        L: Into<DefiniteLength> + Clone + Default + std::fmt::Debug + PartialEq,
132    {
133        let margins = margins.into();
134        self.mt(margins.top.into())
135            .mb(margins.bottom.into())
136            .ml(margins.left.into())
137            .mr(margins.right.into())
138    }
139
140    fn debug_red(self) -> Self {
141        if cfg!(debug_assertions) {
142            self.border_1().border_color(hsl(0., 72.2, 50.6))
143        } else {
144            self
145        }
146    }
147
148    fn debug_blue(self) -> Self {
149        if cfg!(debug_assertions) {
150            self.border_1().border_color(hsl(217.2, 91.2, 59.8))
151        } else {
152            self
153        }
154    }
155
156    fn debug_yellow(self) -> Self {
157        if cfg!(debug_assertions) {
158            self.border_1().border_color(hsl(47.9, 95.8, 53.1))
159        } else {
160            self
161        }
162    }
163
164    fn debug_green(self) -> Self {
165        if cfg!(debug_assertions) {
166            self.border_1().border_color(hsl(142.1, 70.6, 45.3))
167        } else {
168            self
169        }
170    }
171
172    fn debug_pink(self) -> Self {
173        if cfg!(debug_assertions) {
174            self.border_1().border_color(hsl(330.4, 81.2, 60.4))
175        } else {
176            self
177        }
178    }
179
180    fn debug_focused(self, focus_handle: &FocusHandle, window: &Window, cx: &App) -> Self {
181        if cfg!(debug_assertions) && focus_handle.contains_focused(window, cx) {
182            self.debug_blue()
183        } else {
184            self
185        }
186    }
187
188    font_weight!(font_thin, THIN);
189    font_weight!(font_extralight, EXTRA_LIGHT);
190    font_weight!(font_light, LIGHT);
191    font_weight!(font_normal, NORMAL);
192    font_weight!(font_medium, MEDIUM);
193    font_weight!(font_semibold, SEMIBOLD);
194    font_weight!(font_bold, BOLD);
195    font_weight!(font_extrabold, EXTRA_BOLD);
196    font_weight!(font_black, BLACK);
197
198    fn corner_radii(self, radius: Corners<Pixels>) -> Self {
199        self.rounded_tl(radius.top_left)
200            .rounded_tr(radius.top_right)
201            .rounded_bl(radius.bottom_left)
202            .rounded_br(radius.bottom_right)
203    }
204}
205
206impl<E: Styled> StyledExt for E {}
207
208#[cfg(any(feature = "inspector", debug_assertions))]
209pub fn styled_ext_reflection_methods<T: Styled + 'static>()
210-> Vec<gpui::inspector_reflection::FunctionReflection<T>> {
211    styled_ext_reflection::methods::<T>()
212}
213
214fn hsl(hue: f32, saturation: f32, lightness: f32) -> Hsla {
215    hsla(hue / 360., saturation / 100., lightness / 100., 1.)
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use gpui::{
222        Context, InteractiveElement as _, IntoElement, ParentElement as _, Render, TestAppContext,
223        px,
224    };
225
226    fn column(selector: &'static str, height: f32) -> Div {
227        div()
228            .w(px(20.))
229            .h(px(height))
230            .flex_shrink_0()
231            .debug_selector(move || selector.to_string())
232    }
233
234    struct CrossAxisTest;
235
236    impl Render for CrossAxisTest {
237        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
238            div()
239                .w(px(200.))
240                .h(px(100.))
241                .child(
242                    h_flex()
243                        .size_full()
244                        .child(column("row-child", 40.))
245                        .child(column("row-overflowing-child", 140.))
246                        .child(
247                            div()
248                                .w(px(20.))
249                                .debug_selector(|| "row-stretch".to_string()),
250                        ),
251                )
252                .child(
253                    v_flex().size_full().child(
254                        div()
255                            .h(px(20.))
256                            .debug_selector(|| "col-stretch".to_string()),
257                    ),
258                )
259        }
260    }
261
262    /// `h_flex` centers on the cross axis while `v_flex` leaves the default
263    /// stretch. The asymmetry is deliberate but easy to trip over, so lock it.
264    #[gpui::test]
265    fn h_flex_centers_and_v_flex_stretches_on_the_cross_axis(cx: &mut TestAppContext) {
266        let (_, cx) = cx.add_window_view(|_, _| CrossAxisTest);
267        cx.run_until_parked();
268        cx.update(|window, cx| {
269            _ = window.draw(cx);
270        });
271
272        // A shorter child of a 100px row sits at (100 - 40) / 2, not at the top,
273        // and a height-less child keeps its content height instead of filling.
274        let child = cx.debug_bounds("row-child").unwrap();
275        assert_eq!(child.top(), px(30.));
276        assert_eq!(cx.debug_bounds("row-stretch").unwrap().size.height, px(0.));
277
278        // And a child taller than the row is centered too, so its top — a
279        // column's header, in a real layout — is pushed off the top edge.
280        let overflowing = cx.debug_bounds("row-overflowing-child").unwrap();
281        assert_eq!(overflowing.top(), px(-20.));
282
283        // A width-less child of a column does fill the cross axis.
284        assert_eq!(cx.debug_bounds("col-stretch").unwrap().size.width, px(200.));
285    }
286}