Skip to main content

gpui_material_components/overlay/tooltip/
appearance.rs

1use gpui::{
2    Bounds, Div, Hsla, Path, PathBuilder, Pixels, Point, Size, Styled, Window, point, px, size,
3};
4use gpui_base::Placement;
5use gpui_material_foundation::{color, elevation_shadows};
6use gpui_material_theme::{
7    ColorRole, CornerRole, CornerShape, Direction, Elevation, MaterialTheme,
8};
9
10use crate::control_style::finite_length;
11use gpui_material_foundation::OverlayMotion;
12
13/// Preferred tooltip side. Start and End resolve against the window's direction.
14#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
15pub enum TooltipPlacement {
16    /// Place the tooltip above the trigger.
17    #[default]
18    Above,
19    /// Place the tooltip below the trigger.
20    Below,
21    /// Place the tooltip to the physical left of the trigger.
22    Left,
23    /// Place the tooltip to the physical right of the trigger.
24    Right,
25    /// Place the tooltip on the logical start side (left in LTR, right in RTL).
26    Start,
27    /// Place the tooltip on the logical end side (right in LTR, left in RTL).
28    End,
29}
30
31impl TooltipPlacement {
32    pub(super) fn physical(self, direction: Direction) -> Placement {
33        match (self, direction) {
34            (Self::Above, _) => Placement::Top,
35            (Self::Below, _) => Placement::Bottom,
36            (Self::Left, _) | (Self::Start, Direction::Ltr) | (Self::End, Direction::Rtl) => {
37                Placement::Left
38            }
39            (Self::Right, _) | (Self::End, Direction::Ltr) | (Self::Start, Direction::Rtl) => {
40                Placement::Right
41            }
42        }
43    }
44}
45
46/// Window-theme color overrides for a tooltip's individual slots.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct TooltipColors {
49    /// Background color override for the tooltip container.
50    pub container: Option<Hsla>,
51    /// Foreground color override for the tooltip body text.
52    pub content: Option<Hsla>,
53    /// Foreground color override for the rich tooltip title.
54    pub title_content: Option<Hsla>,
55    /// Foreground color override for rich tooltip action buttons and links.
56    pub action_content: Option<Hsla>,
57}
58
59type CaretPath = Box<dyn Fn(Bounds<Pixels>, TooltipPlacement) -> Option<Path>>;
60
61/// Tooltip caret geometry. The default triangle is 16 px wide and 8 px deep.
62pub struct TooltipCaret {
63    size: Size<Pixels>,
64    path: Option<CaretPath>,
65}
66
67impl Default for TooltipCaret {
68    fn default() -> Self {
69        Self::new(size(px(16.), px(8.)))
70    }
71}
72
73impl TooltipCaret {
74    /// Width along the tooltip edge and depth toward the trigger.
75    pub fn new(size: Size<Pixels>) -> Self {
76        Self {
77            size: size.map(finite_length),
78            path: None,
79        }
80    }
81
82    /// Supplies a path in window coordinates. The side is the tooltip's resolved
83    /// physical side relative to the trigger.
84    pub fn path(
85        mut self,
86        path: impl Fn(Bounds<Pixels>, TooltipPlacement) -> Option<Path> + 'static,
87    ) -> Self {
88        self.path = Some(Box::new(path));
89        self
90    }
91
92    pub(super) fn depth(&self, viewport: Size<Pixels>) -> Pixels {
93        self.size
94            .height
95            .min(viewport.width.min(viewport.height) * 0.125)
96    }
97
98    pub(super) fn paint(
99        &self,
100        surface: Bounds<Pixels>,
101        trigger: Bounds<Pixels>,
102        side: Option<Placement>,
103        style: SurfaceStyle,
104        window: &mut Window,
105    ) {
106        let Some(side) = side.or_else(|| infer_side(surface, trigger)) else {
107            return;
108        };
109        let [tl, tr, br, bl] = style
110            .shape
111            .radii(
112                (surface.size.width / style.motion.scale).into(),
113                (surface.size.height / style.motion.scale).into(),
114                style.direction,
115            )
116            .map(|radius| style.motion.px(radius));
117        let anchor = trigger.center();
118        let (lower, upper, center) = match side {
119            Placement::Top => (surface.left() + bl, surface.right() - br, anchor.x),
120            Placement::Bottom => (surface.left() + tl, surface.right() - tr, anchor.x),
121            Placement::Left => (surface.top() + tr, surface.bottom() - br, anchor.y),
122            Placement::Right => (surface.top() + tl, surface.bottom() - bl, anchor.y),
123        };
124        let span = (self.size.width * style.motion.scale).min(upper - lower);
125        let depth = self.depth(window.viewport_size()) * style.motion.scale;
126        if span <= px(0.) || depth <= px(0.) {
127            return;
128        }
129        let half = span * 0.5;
130        let center = center.max(lower + half).min(upper - half);
131        let (origin, dimensions, base_start, tip, base_end, side) = match side {
132            Placement::Top => (
133                point(center - half, surface.bottom()),
134                size(span, depth),
135                point(center - half, surface.bottom()),
136                point(center, surface.bottom() + depth),
137                point(center + half, surface.bottom()),
138                TooltipPlacement::Above,
139            ),
140            Placement::Bottom => (
141                point(center - half, surface.top() - depth),
142                size(span, depth),
143                point(center - half, surface.top()),
144                point(center, surface.top() - depth),
145                point(center + half, surface.top()),
146                TooltipPlacement::Below,
147            ),
148            Placement::Left => (
149                point(surface.right(), center - half),
150                size(depth, span),
151                point(surface.right(), center - half),
152                point(surface.right() + depth, center),
153                point(surface.right(), center + half),
154                TooltipPlacement::Left,
155            ),
156            Placement::Right => (
157                point(surface.left() - depth, center - half),
158                size(depth, span),
159                point(surface.left(), center - half),
160                point(surface.left() - depth, center),
161                point(surface.left(), center + half),
162                TooltipPlacement::Right,
163            ),
164        };
165        let path = self.path.as_ref().map_or_else(
166            || triangle(base_start, tip, base_end),
167            |path| path(Bounds::new(origin, dimensions), side),
168        );
169        if let Some(path) = path {
170            window.paint_path(path, style.container);
171        }
172    }
173}
174
175fn infer_side(surface: Bounds<Pixels>, trigger: Bounds<Pixels>) -> Option<Placement> {
176    if surface.bottom() <= trigger.top() {
177        Some(Placement::Top)
178    } else if surface.top() >= trigger.bottom() {
179        Some(Placement::Bottom)
180    } else if surface.right() <= trigger.left() {
181        Some(Placement::Left)
182    } else if surface.left() >= trigger.right() {
183        Some(Placement::Right)
184    } else {
185        None
186    }
187}
188
189fn triangle(a: Point<Pixels>, tip: Point<Pixels>, b: Point<Pixels>) -> Option<Path> {
190    let mut path = PathBuilder::fill();
191    path.move_to(a);
192    path.line_to(tip);
193    path.line_to(b);
194    path.close();
195    path.build().ok()
196}
197
198#[derive(Default)]
199pub(super) struct Appearance {
200    pub(super) colors: TooltipColors,
201    pub(super) shape: Option<CornerShape>,
202    pub(super) max_width: Option<Pixels>,
203    pub(super) tonal_elevation: Elevation,
204    pub(super) shadow_elevation: Option<Elevation>,
205    pub(super) caret: Option<TooltipCaret>,
206}
207
208#[derive(Clone, Copy)]
209pub(super) struct SurfaceStyle {
210    rich: bool,
211    shape: CornerShape,
212    direction: Direction,
213    motion: OverlayMotion,
214    container: Hsla,
215    pub(super) content: Hsla,
216    pub(super) title: Hsla,
217    pub(super) action: Hsla,
218    pub(super) action_override: Option<Hsla>,
219    width: Pixels,
220    height: Pixels,
221    shadow: Hsla,
222    elevation: Elevation,
223}
224
225impl Appearance {
226    pub(super) fn margin(&self, viewport: Size<Pixels>) -> Pixels {
227        let depth = self
228            .caret
229            .as_ref()
230            .map_or(px(0.), |caret| caret.depth(viewport));
231        (px(8.) + depth).min(viewport.width.min(viewport.height) * 0.25)
232    }
233
234    pub(super) fn resolve(
235        &self,
236        rich: bool,
237        viewport: Size<Pixels>,
238        motion: OverlayMotion,
239        theme: &MaterialTheme,
240    ) -> SurfaceStyle {
241        let tint = |role| color(theme.colors.color(role));
242        let default_container = if rich {
243            ColorRole::SurfaceContainer
244        } else {
245            ColorRole::InverseSurface
246        };
247        let default_content = if rich {
248            ColorRole::OnSurfaceVariant
249        } else {
250            ColorRole::InverseOnSurface
251        };
252        let corner = if rich {
253            CornerRole::Medium
254        } else {
255            CornerRole::ExtraSmall
256        };
257        let margin = self.margin(viewport);
258        let width = self
259            .max_width
260            .unwrap_or_else(|| viewport.width * 0.75)
261            .min(viewport.width - margin * 2.)
262            .min(self.max_width.unwrap_or(px(if rich { 320. } else { 200. })));
263        SurfaceStyle {
264            rich,
265            shape: self.shape.unwrap_or_else(|| corner.shape()),
266            direction: theme.layout.direction,
267            motion,
268            container: self.colors.container.unwrap_or_else(|| {
269                if self.tonal_elevation == Elevation::Level0 {
270                    tint(default_container)
271                } else {
272                    color(theme.colors.surface_at_elevation(self.tonal_elevation))
273                }
274            }),
275            content: self.colors.content.unwrap_or_else(|| tint(default_content)),
276            title: self
277                .colors
278                .title_content
279                .unwrap_or_else(|| tint(default_content)),
280            action: self
281                .colors
282                .action_content
283                .unwrap_or_else(|| tint(ColorRole::Primary)),
284            action_override: self.colors.action_content,
285            width,
286            height: viewport.height - margin * 2.,
287            shadow: tint(ColorRole::Shadow),
288            elevation: self.shadow_elevation.unwrap_or(if rich {
289                Elevation::Level2
290            } else {
291                Elevation::Level0
292            }),
293        }
294    }
295}
296
297impl SurfaceStyle {
298    pub(super) fn apply(self, div: Div) -> Div {
299        let scale = self.motion.scale;
300        let surface = div
301            .flex()
302            .flex_col()
303            .bg(self.container)
304            .text_color(self.content)
305            .min_w(self.width.min(px(40.)) * scale)
306            .min_h(self.height.min(px(24.)) * scale)
307            .max_w(self.width * scale)
308            .max_h(self.height * scale)
309            .overflow_hidden()
310            .shadow(elevation_shadows(self.elevation.dp(), scale, self.shadow));
311        let surface = if self.shape == CornerShape::Full {
312            surface.rounded_full()
313        } else {
314            let [tl, tr, br, bl] = self.shape.radii(f32::MAX, f32::MAX, self.direction);
315            surface
316                .rounded_tl(self.motion.px(tl))
317                .rounded_tr(self.motion.px(tr))
318                .rounded_br(self.motion.px(br))
319                .rounded_bl(self.motion.px(bl))
320        };
321        if self.rich {
322            surface.gap(self.motion.px(8.)).p(self.motion.px(16.))
323        } else {
324            surface
325                .px(self.motion.px(8.))
326                .py(self.motion.px(4.))
327                .justify_center()
328        }
329    }
330}