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