BlueGit

ict rusty-teams

Files

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

tooltip.rs

tooltip.rs 10.6 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 key_binding = if let Some(key_binding) = &self.key_binding {
95 Some(key_binding.clone())
96 } else {
97 if let Some((action, context)) = &self.action {
98 Kbd::binding_for_action(
99 action.as_ref(),
100 context.as_ref().map(|s| s.as_ref()),
101 window,
102 )
103 } else {
104 None
105 }
106 };
107
108 div().child(
109 // Wrap in a child, to ensure the left margin is applied to the tooltip
110 BaseTooltip::new("tooltip-popup")
111 .h_flex()
112 .font_family(cx.theme().font_family.clone())
113 .m_3()
114 .bg(cx.theme().tokens.popover)
115 .text_color(cx.theme().popover_foreground)
116 .bg(cx.theme().tokens.popover)
117 .rounded(cx.theme().radius)
118 .justify_between()
119 .py_0p5()
120 .px_2()
121 .text_sm()
122 .gap_3()
123 .refine_style(&self.style)
124 .map(|this| {
125 this.child(div().map(|this| match self.content {
126 TooltipContext::Text(ref text) => this.child(text.clone()),
127 TooltipContext::Element(ref builder) => this.child(builder(window, cx)),
128 }))
129 })
130 .when_some(key_binding, |this, kbd| {
131 this.child(
132 div()
133 .text_xs()
134 .flex_shrink_0()
135 .text_color(cx.theme().muted_foreground)
136 .child(kbd.appearance(false)),
137 )
138 }),
139 )
140 }
141}
142
143// ── Managed tooltip system ──────────────────────────────────────────────────
144
145/// Duration of the slide-down enter animation.
146const ENTER_DURATION: Duration = Duration::from_millis(150);
147/// Duration of the position-slide animation when switching tooltips.
148const SLIDE_DURATION: Duration = Duration::from_millis(200);
149pub(crate) fn render_tooltip(
150 content_view: AnyView,
151 transition: BaseTooltipTransition,
152 _: &mut Window,
153 _: &mut App,
154) -> AnyElement {
155 div().child(content_view).map(|element| match transition {
156 BaseTooltipTransition::Switch {
157 epoch,
158 previous,
159 current,
160 } => {
161 let same_row = (current.origin.y - previous.origin.y).abs() < px(10.);
162 if !same_row {
163 return element.into_any_element();
164 }
165 let dx = current.center().x - previous.center().x;
166 EffectTransition::new(SLIDE_DURATION)
167 .ease(ease_in_out_cubic)
168 .slide_x(-dx, px(0.))
169 .apply(
170 element,
171 ElementId::NamedInteger("tooltip-slide".into(), epoch as u64),
172 )
173 .into_any_element()
174 }
175 BaseTooltipTransition::Enter { epoch } => EffectTransition::new(ENTER_DURATION)
176 .ease(ease_out_cubic)
177 .slide_y(px(4.), px(0.))
178 .fade(0.0, 1.0)
179 .apply(
180 element,
181 ElementId::NamedInteger("tooltip-enter".into(), epoch as u64),
182 )
183 .into_any_element(),
184 })
185}
186
187// ── Extension trait for managed tooltips ─────────────────────────────────────
188
189// ── Shared tooltip state for components ─────────────────────────────────────
190
191/// Shared tooltip state that components (Button, Switch, Checkbox, Radio, etc.)
192/// can embed to get `.tooltip()` support with minimal boilerplate.
193#[derive(Default)]
194pub(crate) struct ComponentTooltip {
195 pub text: Option<(
196 SharedString,
197 Option<(Rc<Box<dyn Action>>, Option<SharedString>)>,
198 )>,
199 pub builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyView>>,
200}
201
202impl ComponentTooltip {
203 /// Apply this tooltip to a `Stateful<Div>` (or any `ManagedTooltipExt` element).
204 pub fn apply<E: ManagedTooltipExt>(self, el: E) -> E {
205 if let Some(builder) = self.builder {
206 el.managed_tooltip(move |window, cx| builder(window, cx))
207 } else if let Some((text, action)) = self.text {
208 el.managed_tooltip(move |window, cx| {
209 Tooltip::new(text.clone())
210 .when_some(action.clone(), |this, (action, context)| {
211 this.action(
212 action.boxed_clone().as_ref(),
213 context.as_ref().map(|c| c.as_ref()),
214 )
215 })
216 .build(window, cx)
217 })
218 } else {
219 el
220 }
221 }
222}
223
224// ── Internal managed tooltip trait ──────────────────────────────────────────
225
226pub(crate) trait ManagedTooltipExt:
227 StatefulInteractiveElement + crate::ElementExt + Sized
228{
229 fn managed_tooltip(
230 self,
231 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
232 ) -> Self {
233 self.managed_tooltip_with_placement(None, build_tooltip)
234 }
235
236 fn managed_tooltip_at(
237 self,
238 placement: Placement,
239 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
240 ) -> Self {
241 self.managed_tooltip_with_placement(Some(placement), build_tooltip)
242 }
243
244 fn managed_tooltip_with_placement(
245 self,
246 preferred_placement: Option<Placement>,
247 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
248 ) -> Self {
249 let build_tooltip = Rc::new(build_tooltip);
250 let trigger_bounds_cell: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
251 let bounds_writer = trigger_bounds_cell.clone();
252
253 self.on_prepaint(move |bounds, _, _| {
254 bounds_writer.set(bounds);
255 })
256 .on_hover({
257 let trigger_bounds_cell = trigger_bounds_cell.clone();
258 let build_tooltip = build_tooltip.clone();
259 move |hovered, window, cx| {
260 if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
261 if *hovered {
262 let bounds = trigger_bounds_cell.get();
263 overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
264 let build = build_tooltip.clone();
265 let request = BaseTooltipRequest::new(bounds, move |window, cx| {
266 build(window, cx)
267 });
268 let request = match preferred_placement {
269 Some(placement) => request.placement(placement),
270 None => request,
271 };
272 o.request_show(request, window, cx);
273 });
274 } else {
275 overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
276 o.request_hide(window, cx);
277 });
278 }
279 }
280 }
281 })
282 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
283 if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
284 overlay.update(cx, |overlay, cx| {
285 overlay.hide(cx);
286 });
287 }
288 })
289 }
290}
291
292impl<E: StatefulInteractiveElement + crate::ElementExt> ManagedTooltipExt for E {}