BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / styled.rs

styled.rs

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