Skip to main content

gpui_component/
styled.rs

1pub use crate::component_traits::{Collapsible, Disableable, Selectable};
2pub use crate::sizing::{Sizable, Size, StyleSized};
3use gpui::{
4    App, BoxShadow, Corners, Edges, Hsla, ParentElement, Pixels, StyleRefinement, Styled, Window,
5    div, hsla, px,
6};
7pub use gpui_base::{FocusableExt, RoleOverride, StyledExt, box_shadow, h_flex, v_flex};
8
9use crate::ActiveTheme as _;
10
11const FOCUS_RING_WIDTH: Pixels = px(3.);
12const FOCUS_RING_OPACITY: f32 = 0.5;
13
14/// Ink every layer of a surface's shadow carries — the `rgb(0 0 0 / 0.1)`
15/// shadcn/ui spends at each elevation.
16const SURFACE_SHADOW_INK: f32 = 0.1;
17
18/// Ink of the hairline ring standing in for a popover's border.
19///
20/// shadcn/ui draws no border on a popup surface at all: its edge is a 1px
21/// `rgb(0 0 0 / 0.1)` ring spent as a shadow layer. Because the ring is
22/// translucent the shadow shows *through* it, which is what makes the edge read
23/// as part of one grounded surface rather than as an outline with a separate
24/// shadow below it. An opaque border cannot reproduce that — a border composites
25/// over the element's own background, not over the shadow.
26const POPOVER_RING_INK: f32 = 0.1;
27
28/// The colour of a popup surface's hairline ring in this theme.
29///
30/// shadcn spends black on it in light mode and white in dark
31/// (`oklch(1 0 0 / 10%)`), so it follows the foreground rather than the border
32/// token: a fixed black ring would all but vanish on a dark surface.
33///
34pub(crate) fn popover_ring(cx: &App) -> Hsla {
35    with_alpha(cx.theme().foreground, POPOVER_RING_INK)
36}
37
38fn with_alpha(color: Hsla, alpha: f32) -> Hsla {
39    hsla(
40        color.color.hue.into_degrees() / 360.,
41        color.color.saturation,
42        color.color.lightness,
43        alpha.clamp(0., 1.),
44    )
45}
46
47/// shadcn/ui's popup surface shadow — a hairline `ring` plus `shadow-md` — at
48/// `strength` of its full ink.
49///
50/// Callers animating a surface in pass a rising `strength`; a resting surface
51/// passes `1.0`.
52///
53/// The two blurred layers use Tailwind's radii **halved**, which is the
54/// conversion CSS requires and not a taste adjustment. CSS defines a box
55/// shadow's blur radius as twice the gaussian's standard deviation, while GPUI's
56/// shader takes the field as the deviation itself (`gaussian(y, sigma)`).
57/// Copying Tailwind's `6px` and `4px` across therefore spreads the shadow over
58/// twice the distance, which is why [`Styled::shadow_md`] reads as a wide grey
59/// haze next to a browser's compact one.
60///
61/// Measured against shadcn's own render, this lands within a luminance step of
62/// it the whole way down the falloff.
63///
64/// The ring is taken as a colour rather than read from the theme here so that an
65/// animation can hold it across frames, where no `App` is in hand.
66pub(crate) fn popover_shadow(ring: Hsla, strength: f32) -> Vec<BoxShadow> {
67    let strength = strength.clamp(0., 1.);
68    let ink = hsla(0., 0., 0., SURFACE_SHADOW_INK * strength);
69    vec![
70        // The ring, sitting in the 1px band outside the surface. No blur, so it
71        // takes the shader's crisp path rather than the gaussian one.
72        BoxShadow::new(px(0.), px(0.), with_alpha(ring, ring.alpha * strength))
73            .blur_radius(px(0.))
74            .spread_radius(px(1.)),
75        BoxShadow::new(px(0.), px(4.), ink)
76            .blur_radius(px(3.))
77            .spread_radius(px(-1.)),
78        BoxShadow::new(px(0.), px(2.), ink)
79            .blur_radius(px(2.))
80            .spread_radius(px(-2.)),
81    ]
82}
83
84/// shadcn/ui's `shadow-lg`, the elevation it lifts a toast to, at `strength` of
85/// its full ink.
86///
87/// A toast sits higher than a popover and is built differently: shadcn gives it
88/// a real 1px border rather than the translucent ring it puts on a popup, so
89/// there is no ring layer here. Its corner radius is left to the caller.
90///
91/// The radii are Tailwind's halved, for the reason [`popover_shadow`] explains.
92pub(crate) fn toast_shadow(strength: f32) -> Vec<BoxShadow> {
93    let ink = hsla(0., 0., 0., SURFACE_SHADOW_INK * strength.clamp(0., 1.));
94    vec![
95        BoxShadow::new(px(0.), px(10.), ink)
96            .blur_radius(px(7.5))
97            .spread_radius(px(-3.)),
98        BoxShadow::new(px(0.), px(4.), ink)
99            .blur_radius(px(3.))
100            .spread_radius(px(-4.)),
101    ]
102}
103
104/// shadcn/ui's `shadow-sm`, the elevation it spends on a control raised out of
105/// the container it sits in — the active pill of a segmented tab bar — at full
106/// ink.
107///
108/// Unlike a popover or a toast this surface is not floating over the page: it
109/// sits *inside* a trough only a few pixels wider than itself, and that trough
110/// clips. Both are reasons to keep the falloff tight — there is no room for a
111/// wide one, and a wide one would read as grime against the trough wall rather
112/// than as lift.
113///
114/// The radii are Tailwind's halved, for the reason [`popover_shadow`] explains:
115/// CSS defines a box shadow's blur radius as twice the gaussian's standard
116/// deviation, while GPUI's shader takes the field as the deviation itself
117/// (`gaussian(y, sigma)`). Copying Tailwind's `3px` and `2px` across therefore
118/// spreads the shadow over twice the distance, which is why
119/// [`Styled::shadow_sm`] leaves a haze around a 24px pill where shadcn draws a
120/// compact line.
121pub(crate) fn raised_shadow() -> Vec<BoxShadow> {
122    let ink = hsla(0., 0., 0., SURFACE_SHADOW_INK);
123    vec![
124        BoxShadow::new(px(0.), px(1.), ink).blur_radius(px(1.5)),
125        BoxShadow::new(px(0.), px(1.), ink)
126            .blur_radius(px(1.))
127            .spread_radius(px(-1.)),
128    ]
129}
130
131/// Finished styles that read the theme.
132///
133/// Separate from [`StyledExt`], which holds neutral helpers that make no
134/// visual decisions. Everything here does: it reaches into the theme and
135/// produces a specific look, which is why it belongs above the base layer.
136pub trait ThemeStyled: Styled + Sized {
137    /// Give this element the focus appearance the framework's own controls
138    /// use: its border tinted with the focus colour, and the ring outside it.
139    ///
140    /// The ring is dropped when [`crate::Theme::focus_ring`] is off, leaving
141    /// the tinted border — an application whose layout clips its containers can
142    /// turn it off rather than finding room for the ring in each of them.
143    ///
144    /// Calling this turns the ring on; gate it with `when` for the conditions
145    /// that decide whether the control shows one at all — its focus state,
146    /// [`FocusableExt::focus_ring`], appearance, and so on.
147    ///
148    /// The ring sits outside the element's border, so an ancestor that clips
149    /// its content will cut it off — leave it a few pixels of room, or don't
150    /// clip.
151    fn focus_ring_style(self, window: &Window, cx: &App) -> Self
152    where
153        Self: ParentElement;
154
155    /// Give this element the surface, edge, shadow and radius of a popover.
156    ///
157    /// This is the one surface every popup shares — Popover, PopupMenu, Select,
158    /// Combobox, DatePicker and the editor's hover popovers — so they cannot
159    /// drift apart. See [`popover_shadow`] for what the shadow is modelled on.
160    fn popover_style(self, cx: &App) -> Self;
161
162    /// Round this element as far as its size allows — a circle if it is square,
163    /// a pill if it is not — unless the theme squares its corners.
164    ///
165    /// Use this instead of [`gpui::Styled::rounded_full`] on anything the theme
166    /// owns. A hardcoded `rounded_full` survives [`crate::Theme::radius`] being
167    /// set to zero, which leaves avatars, badge dots and slider thumbs round in
168    /// a UI that is square everywhere else. See [`crate::Theme::radius_full`].
169    fn rounded_full_style(self, cx: &App) -> Self {
170        self.rounded(cx.theme().radius_full())
171    }
172}
173
174impl<T: Styled + Sized> ThemeStyled for T {
175    /// Draw the focus ring the framework's own controls use.
176    ///
177    /// Calling this turns the ring on; gate it with `when` for the conditions
178    /// that decide whether the control shows one at all — its focus state,
179    /// [`crate::FocusableExt::focus_ring`], appearance, and so on.
180    ///
181    /// The ring sits outside the element's border, so an ancestor that clips
182    /// its content will cut it off — leave it a few pixels of room, or don't
183    /// clip.
184    fn focus_ring_style(mut self, window: &Window, cx: &App) -> Self
185    where
186        Self: ParentElement,
187    {
188        // The ring is painted outside the border, so a clipping ancestor cuts
189        // it off. An application whose layout clips heavily turns it off in the
190        // theme and keeps the tinted border, which takes no space.
191        if !cx.theme().focus_ring {
192            return self.border_color(cx.theme().ring);
193        }
194
195        let rem_size = window.rem_size();
196        let style = self.style();
197        let border_widths = Edges::<Pixels> {
198            top: style
199                .border_widths
200                .top
201                .map(|v| v.to_pixels(rem_size))
202                .unwrap_or_default(),
203            bottom: style
204                .border_widths
205                .bottom
206                .map(|v| v.to_pixels(rem_size))
207                .unwrap_or_default(),
208            left: style
209                .border_widths
210                .left
211                .map(|v| v.to_pixels(rem_size))
212                .unwrap_or_default(),
213            right: style
214                .border_widths
215                .right
216                .map(|v| v.to_pixels(rem_size))
217                .unwrap_or_default(),
218        };
219        let radius = Corners::<Pixels> {
220            top_left: style
221                .corner_radii
222                .top_left
223                .map(|v| v.to_pixels(rem_size))
224                .unwrap_or_default(),
225            top_right: style
226                .corner_radii
227                .top_right
228                .map(|v| v.to_pixels(rem_size))
229                .unwrap_or_default(),
230            bottom_left: style
231                .corner_radii
232                .bottom_left
233                .map(|v| v.to_pixels(rem_size))
234                .unwrap_or_default(),
235            bottom_right: style
236                .corner_radii
237                .bottom_right
238                .map(|v| v.to_pixels(rem_size))
239                .unwrap_or_default(),
240        }
241        .map(|value| *value + FOCUS_RING_WIDTH);
242        let mut ring_style = StyleRefinement::default();
243        ring_style.corner_radii.top_left = Some(radius.top_left.into());
244        ring_style.corner_radii.top_right = Some(radius.top_right.into());
245        ring_style.corner_radii.bottom_left = Some(radius.bottom_left.into());
246        ring_style.corner_radii.bottom_right = Some(radius.bottom_right.into());
247        let inset = FOCUS_RING_WIDTH;
248
249        self.border_color(cx.theme().ring).child(
250            div()
251                .flex_none()
252                .absolute()
253                .top(-(inset + border_widths.top))
254                .left(-(inset + border_widths.left))
255                .right(-(inset + border_widths.right))
256                .bottom(-(inset + border_widths.bottom))
257                .border(FOCUS_RING_WIDTH)
258                .border_color(with_alpha(cx.theme().ring, FOCUS_RING_OPACITY))
259                .refine_style(&ring_style),
260        )
261    }
262
263    fn popover_style(self, cx: &App) -> Self {
264        let theme = cx.theme();
265        // No border: the edge is the ring inside `popover_shadow`, which is how
266        // shadcn draws it and the only way the shadow can show through it.
267        self.bg(theme.popover)
268            .text_color(theme.popover_foreground)
269            .shadow(popover_shadow(popover_ring(cx), 1.))
270            .rounded(theme.radius)
271    }
272}