BlueGit

ict rusty-teams

Files

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

tooltip.rs

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