BlueGit

ict rusty-teams

Files

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

tooltip.rs

tooltip.rs 10.7 KiB Download Raw
1use crate::root::WindowState;
2use std::{cell::Cell, rc::Rc, time::Duration};
3
4use gpui::{
5 Action, AnyElement, AnyView, App, AppContext, Bounds, Context, ElementId, IntoElement,
6 MouseButton, ParentElement, Pixels, Render, SharedString, StatefulInteractiveElement,
7 StyleRefinement, Styled, Window, div, prelude::FluentBuilder, px,
8};
9use gpui_base::{
10 Tooltip as BaseTooltip, TooltipOverlay as BaseTooltipOverlay,
11 TooltipRequest as BaseTooltipRequest, TooltipTransition as BaseTooltipTransition,
12};
13
14use crate::{
15 ActiveTheme, Placement, StyledExt,
16 animation::{EffectTransition, ease_in_out_cubic, ease_out_cubic},
17 kbd::Kbd,
18 text::Text,
19};
20
21pub(crate) fn init(_cx: &mut App) {
22 // No app-level init needed — TooltipOverlay is per-window via Root.
23}
24
25// ── Tooltip view (unchanged API) ────────────────────────────────────────────
26
27enum TooltipContext {
28 Text(Text),
29 Element(Box<dyn Fn(&mut Window, &mut App) -> AnyElement>),
30}
31
32/// A Tooltip element that can display text or custom content,
33/// with optional key binding information.
34pub struct Tooltip {
35 style: StyleRefinement,
36 content: TooltipContext,
37 key_binding: Option<Kbd>,
38 action: Option<(Box<dyn Action>, Option<SharedString>)>,
39}
40
41impl Tooltip {
42 /// Create a Tooltip with a text content.
43 pub fn new(text: impl Into<Text>) -> Self {
44 Self {
45 style: StyleRefinement::default(),
46 content: TooltipContext::Text(text.into()),
47 key_binding: None,
48 action: None,
49 }
50 }
51
52 /// Create a Tooltip with a custom element.
53 pub fn element<E, F>(builder: F) -> Self
54 where
55 E: IntoElement,
56 F: Fn(&mut Window, &mut App) -> E + 'static,
57 {
58 Self {
59 style: StyleRefinement::default(),
60 key_binding: None,
61 action: None,
62 content: TooltipContext::Element(Box::new(move |window, cx| {
63 builder(window, cx).into_any_element()
64 })),
65 }
66 }
67
68 /// Set Action to display key binding information for the tooltip if it exists.
69 pub fn action(mut self, action: &dyn Action, context: Option<&str>) -> Self {
70 self.action = Some((action.boxed_clone(), context.map(SharedString::new)));
71 self
72 }
73
74 /// Set KeyBinding information for the tooltip.
75 pub fn key_binding(mut self, key_binding: Option<Kbd>) -> Self {
76 self.key_binding = key_binding;
77 self
78 }
79
80 /// Build the tooltip and return it as an `AnyView`.
81 pub fn build(self, _: &mut Window, cx: &mut App) -> AnyView {
82 cx.new(|_| self).into()
83 }
84}
85
86impl FluentBuilder for Tooltip {}
87impl Styled for Tooltip {
88 fn style(&mut self) -> &mut StyleRefinement {
89 &mut self.style
90 }
91}
92impl Render for Tooltip {
93 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
94 let flyout_fill = crate::elevation::flyout(window, cx).fill;
95 let key_binding = if let Some(key_binding) = &self.key_binding {
96 Some(key_binding.clone())
97 } else {
98 if let Some((action, context)) = &self.action {
99 Kbd::binding_for_action(
100 action.as_ref(),
101 context.as_ref().map(|s| s.as_ref()),
102 window,
103 )
104 } else {
105 None
106 }
107 };
108
109 div().child(
110 // Wrap in a child, to ensure the left margin is applied to the tooltip
111 BaseTooltip::new("tooltip-popup")
112 .h_flex()
113 .font_family(cx.theme().font_family.clone())
114 .m_3()
115 .bg(flyout_fill)
116 .shadow(crate::elevation::shadow8())
117 .text_color(cx.theme().popover_foreground)
118 .rounded(cx.theme().radius)
119 .justify_between()
120 .py_0p5()
121 .px_2()
122 .text_sm()
123 .gap_3()
124 .refine_style(&self.style)
125 .map(|this| {
126 this.child(div().map(|this| match self.content {
127 TooltipContext::Text(ref text) => this.child(text.clone()),
128 TooltipContext::Element(ref builder) => this.child(builder(window, cx)),
129 }))
130 })
131 .when_some(key_binding, |this, kbd| {
132 this.child(
133 div()
134 .text_xs()
135 .flex_shrink_0()
136 .text_color(cx.theme().muted_foreground)
137 .child(kbd.appearance(false)),
138 )
139 }),
140 )
141 }
142}
143
144// ── Managed tooltip system ──────────────────────────────────────────────────
145
146/// Duration of the slide-down enter animation.
147const ENTER_DURATION: Duration = Duration::from_millis(150);
148/// Duration of the position-slide animation when switching tooltips.
149const SLIDE_DURATION: Duration = Duration::from_millis(200);
150pub(crate) fn render_tooltip(
151 content_view: AnyView,
152 transition: BaseTooltipTransition,
153 _: &mut Window,
154 _: &mut App,
155) -> AnyElement {
156 div().child(content_view).map(|element| match transition {
157 BaseTooltipTransition::Switch {
158 epoch,
159 previous,
160 current,
161 } => {
162 let same_row = (current.origin.y - previous.origin.y).abs() < px(10.);
163 if !same_row {
164 return element.into_any_element();
165 }
166 let dx = current.center().x - previous.center().x;
167 EffectTransition::new(SLIDE_DURATION)
168 .ease(ease_in_out_cubic)
169 .slide_x(-dx, px(0.))
170 .apply(
171 element,
172 ElementId::NamedInteger("tooltip-slide".into(), epoch as u64),
173 )
174 .into_any_element()
175 }
176 BaseTooltipTransition::Enter { epoch } => EffectTransition::new(ENTER_DURATION)
177 .ease(ease_out_cubic)
178 .slide_y(px(4.), px(0.))
179 .fade(0.0, 1.0)
180 .apply(
181 element,
182 ElementId::NamedInteger("tooltip-enter".into(), epoch as u64),
183 )
184 .into_any_element(),
185 })
186}
187
188// ── Extension trait for managed tooltips ─────────────────────────────────────
189
190// ── Shared tooltip state for components ─────────────────────────────────────
191
192/// Shared tooltip state that components (Button, Switch, Checkbox, Radio, etc.)
193/// can embed to get `.tooltip()` support with minimal boilerplate.
194#[derive(Default)]
195pub(crate) struct ComponentTooltip {
196 pub text: Option<(
197 SharedString,
198 Option<(Rc<Box<dyn Action>>, Option<SharedString>)>,
199 )>,
200 pub builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyView>>,
201}
202
203impl ComponentTooltip {
204 /// Apply this tooltip to a `Stateful<Div>` (or any `ManagedTooltipExt` element).
205 pub fn apply<E: ManagedTooltipExt>(self, el: E) -> E {
206 if let Some(builder) = self.builder {
207 el.managed_tooltip(move |window, cx| builder(window, cx))
208 } else if let Some((text, action)) = self.text {
209 el.managed_tooltip(move |window, cx| {
210 Tooltip::new(text.clone())
211 .when_some(action.clone(), |this, (action, context)| {
212 this.action(
213 action.boxed_clone().as_ref(),
214 context.as_ref().map(|c| c.as_ref()),
215 )
216 })
217 .build(window, cx)
218 })
219 } else {
220 el
221 }
222 }
223}
224
225// ── Internal managed tooltip trait ──────────────────────────────────────────
226
227pub(crate) trait ManagedTooltipExt:
228 StatefulInteractiveElement + crate::ElementExt + Sized
229{
230 fn managed_tooltip(
231 self,
232 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
233 ) -> Self {
234 self.managed_tooltip_with_placement(None, build_tooltip)
235 }
236
237 fn managed_tooltip_at(
238 self,
239 placement: Placement,
240 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
241 ) -> Self {
242 self.managed_tooltip_with_placement(Some(placement), build_tooltip)
243 }
244
245 fn managed_tooltip_with_placement(
246 self,
247 preferred_placement: Option<Placement>,
248 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
249 ) -> Self {
250 let build_tooltip = Rc::new(build_tooltip);
251 let trigger_bounds_cell: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
252 let bounds_writer = trigger_bounds_cell.clone();
253
254 self.on_prepaint(move |bounds, _, _| {
255 bounds_writer.set(bounds);
256 })
257 .on_hover({
258 let trigger_bounds_cell = trigger_bounds_cell.clone();
259 let build_tooltip = build_tooltip.clone();
260 move |hovered, window, cx| {
261 if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
262 if *hovered {
263 let bounds = trigger_bounds_cell.get();
264 overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
265 let build = build_tooltip.clone();
266 let request = BaseTooltipRequest::new(bounds, move |window, cx| {
267 build(window, cx)
268 });
269 let request = match preferred_placement {
270 Some(placement) => request.placement(placement),
271 None => request,
272 };
273 o.request_show(request, window, cx);
274 });
275 } else {
276 overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
277 o.request_hide(window, cx);
278 });
279 }
280 }
281 }
282 })
283 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
284 if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
285 overlay.update(cx, |overlay, cx| {
286 overlay.hide(cx);
287 });
288 }
289 })
290 }
291}
292
293impl<E: StatefulInteractiveElement + crate::ElementExt> ManagedTooltipExt for E {}