1mod appearance;
2mod interaction;
3mod label;
4
5use std::{cell::Cell, rc::Rc, time::Duration};
6
7use gpui::{
8 AccessibleAction, Anchor, AnyElement, App, Bounds, ElementId, Entity, FocusHandle,
9 InteractiveElement, IntoElement, KeyBinding, MouseButton, ParentElement, Pixels, RenderOnce,
10 Role, SharedString, Size, StatefulInteractiveElement, Styled, Window, canvas, deferred, div,
11 point, prelude::FluentBuilder, px,
12};
13use gpui_base::{Link, Placement, TestSupportExt};
14use gpui_material_foundation::{ThemeScope, current_material_theme};
15use gpui_material_theme::{CornerShape, Direction, Elevation, TypeRole};
16
17use appearance::{Appearance, SurfaceStyle};
18use interaction::{Dismiss, Interaction};
19
20pub use appearance::{TooltipCaret, TooltipColors, TooltipPlacement};
21pub use gpui_base::Positioner as TooltipPositioner;
22pub use interaction::TooltipState;
23pub use label::Label;
24
25use crate::{
26 Button, ButtonColors, ButtonVariant,
27 button_style::finite_length,
28 motion::{OverlayMotion, ScaledOverlay},
29};
30
31gpui::actions!(
32 material_tooltip,
33 [
34 FocusTooltipAction,
35 FocusTooltipTrigger,
36 DismissTooltip,
37 ActivateTooltipAction
38 ]
39);
40
41pub(crate) fn init(cx: &mut App) {
42 cx.bind_keys([
43 KeyBinding::new("tab", FocusTooltipAction, Some("MaterialTooltipTrigger")),
44 KeyBinding::new(
45 "shift-tab",
46 FocusTooltipTrigger,
47 Some("MaterialTooltipContent"),
48 ),
49 KeyBinding::new("escape", DismissTooltip, Some("MaterialTooltip")),
50 KeyBinding::new(
51 "enter",
52 ActivateTooltipAction,
53 Some("MaterialTooltipAction"),
54 ),
55 KeyBinding::new(
56 "space",
57 ActivateTooltipAction,
58 Some("MaterialTooltipAction"),
59 ),
60 ]);
61}
62
63type TooltipCallback = Rc<dyn Fn(&mut Window, &mut App)>;
64type PositionProvider = Box<dyn Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner>;
65
66struct TooltipAction {
67 label: SharedString,
68 focus: FocusHandle,
69 callback: TooltipCallback,
70}
71
72#[derive(IntoElement)]
75pub struct Tooltip {
76 id: ElementId,
77 trigger: Option<AnyElement>,
78 text: SharedString,
79 title: Option<SharedString>,
80 shortcut: Option<SharedString>,
81 action: Option<TooltipAction>,
82 title_content: Option<AnyElement>,
83 body_content: Option<AnyElement>,
84 action_content: Option<AnyElement>,
85 link: Option<(SharedString, TooltipCallback)>,
86 rich: bool,
87 trigger_focus: Option<FocusHandle>,
88 focus_target: Option<FocusHandle>,
89 focusable: bool,
90 enable_user_input: bool,
91 persistent: Option<Entity<TooltipState>>,
92 label_visible: Option<bool>,
93 on_dismiss_request: Option<TooltipCallback>,
94 placement: TooltipPlacement,
95 offset: Pixels,
96 positioner: Option<PositionProvider>,
97 appearance: Appearance,
98 show_delay: Duration,
99 hide_delay: Duration,
100}
101
102impl Tooltip {
103 pub fn plain(
105 id: impl Into<ElementId>,
106 trigger: impl IntoElement,
107 text: impl Into<SharedString>,
108 ) -> Self {
109 Self {
110 id: id.into(),
111 trigger: Some(trigger.into_any_element()),
112 text: text.into(),
113 title: None,
114 shortcut: None,
115 action: None,
116 title_content: None,
117 body_content: None,
118 action_content: None,
119 link: None,
120 rich: false,
121 trigger_focus: None,
122 focus_target: None,
123 focusable: false,
124 enable_user_input: true,
125 persistent: None,
126 label_visible: None,
127 on_dismiss_request: None,
128 placement: TooltipPlacement::Above,
129 offset: px(4.),
130 positioner: None,
131 appearance: Appearance::default(),
132 show_delay: Duration::from_millis(500),
133 hide_delay: Duration::from_millis(200),
134 }
135 }
136
137 pub fn rich(
139 id: impl Into<ElementId>,
140 trigger: impl IntoElement,
141 title: impl Into<SharedString>,
142 text: impl Into<SharedString>,
143 ) -> Self {
144 Self {
145 title: Some(title.into()),
146 rich: true,
147 ..Self::plain(id, trigger, text)
148 }
149 }
150
151 pub fn shortcut(mut self, text: impl Into<SharedString>) -> Self {
155 self.shortcut = Some(text.into());
156 self
157 }
158
159 pub fn action(
161 mut self,
162 label: impl Into<SharedString>,
163 focus: &FocusHandle,
164 callback: impl Fn(&mut Window, &mut App) + 'static,
165 ) -> Self {
166 self.rich = true;
167 self.action = Some(TooltipAction {
168 label: label.into(),
169 focus: focus.clone(),
170 callback: Rc::new(callback),
171 });
172 self
173 }
174
175 pub fn title_content(mut self, content: impl IntoElement) -> Self {
177 self.rich = true;
178 self.title_content = Some(content.into_any_element());
179 self
180 }
181
182 pub fn body_content(mut self, content: impl IntoElement) -> Self {
184 self.body_content = Some(content.into_any_element());
185 self
186 }
187
188 pub fn action_content(mut self, content: impl IntoElement) -> Self {
190 self.rich = true;
191 self.action_content = Some(content.into_any_element());
192 self
193 }
194
195 pub fn link(
197 mut self,
198 label: impl Into<SharedString>,
199 callback: impl Fn(&mut Window, &mut App) + 'static,
200 ) -> Self {
201 self.rich = true;
202 self.link = Some((label.into(), Rc::new(callback)));
203 self
204 }
205
206 pub fn show_delay(mut self, delay: Duration) -> Self {
208 self.show_delay = delay;
209 self
210 }
211
212 pub fn hide_delay(mut self, delay: Duration) -> Self {
214 self.hide_delay = delay;
215 self
216 }
217
218 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
220 self.trigger_focus = Some(focus.clone());
221 self
222 }
223
224 pub fn focus_target(mut self, focus: &FocusHandle) -> Self {
226 self.focus_target = Some(focus.clone());
227 self
228 }
229
230 pub fn focusable(mut self, focusable: bool) -> Self {
232 self.focusable = focusable;
233 self
234 }
235
236 pub fn enable_user_input(mut self, enable: bool) -> Self {
238 self.enable_user_input = enable;
239 self
240 }
241
242 pub fn persistent(mut self, state: &Entity<TooltipState>) -> Self {
244 self.rich = true;
245 self.persistent = Some(state.clone());
246 self
247 }
248
249 pub fn on_dismiss_request(
252 mut self,
253 callback: impl Fn(&mut Window, &mut App) + 'static,
254 ) -> Self {
255 self.on_dismiss_request = Some(Rc::new(callback));
256 self
257 }
258
259 pub fn placement(mut self, placement: TooltipPlacement) -> Self {
261 self.placement = placement;
262 self
263 }
264
265 pub fn offset(mut self, offset: Pixels) -> Self {
267 self.offset = finite_length(offset);
268 self
269 }
270
271 pub fn positioner(
274 mut self,
275 positioner: impl Fn(Bounds<Pixels>, Size<Pixels>, Direction) -> TooltipPositioner + 'static,
276 ) -> Self {
277 self.positioner = Some(Box::new(positioner));
278 self
279 }
280
281 pub fn caret(mut self, caret: TooltipCaret) -> Self {
283 self.appearance.caret = Some(caret);
284 self
285 }
286
287 pub fn max_width(mut self, width: Pixels) -> Self {
289 self.appearance.max_width = Some(finite_length(width));
290 self
291 }
292
293 pub fn shape(mut self, shape: CornerShape) -> Self {
295 self.appearance.shape = Some(shape);
296 self
297 }
298
299 pub fn colors(mut self, colors: TooltipColors) -> Self {
301 self.appearance.colors = colors;
302 self
303 }
304
305 pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
307 self.appearance.tonal_elevation = elevation;
308 self
309 }
310
311 pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
313 self.appearance.shadow_elevation = Some(elevation);
314 self
315 }
316}
317
318#[derive(Clone, Default)]
319struct Geometry {
320 anchor: Rc<Cell<Option<Bounds<Pixels>>>>,
321 placed: Rc<Cell<Bounds<Pixels>>>,
322 side: Rc<Cell<Option<Placement>>>,
323}
324
325impl RenderOnce for Tooltip {
326 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
327 let label = self.label_visible.is_some();
328 let state = window.use_keyed_state(
329 (self.id.clone(), "tooltip-interaction"),
330 cx,
331 Interaction::new,
332 );
333 let geometry = window
334 .use_keyed_state((self.id.clone(), "tooltip-geometry"), cx, |_, _| {
335 Geometry::default()
336 })
337 .read(cx)
338 .clone();
339 let transient = !label && self.enable_user_input && self.persistent.is_none();
340 state.update(cx, |state, cx| {
341 state.configure(
342 transient,
343 (self.show_delay, self.hide_delay),
344 self.trigger_focus.as_ref(),
345 self.persistent.as_ref(),
346 window,
347 cx,
348 )
349 });
350 let open = self.label_visible.unwrap_or_else(|| {
351 self.persistent.as_ref().map_or_else(
352 || state.read(cx).is_open(window, cx),
353 |state| state.read(cx).is_visible(),
354 )
355 });
356 let surface = state.read(cx).surface.clone();
357 let first = self.focus_target.clone().or_else(|| {
358 self.action
359 .as_ref()
360 .filter(|_| self.action_content.is_none())
361 .map(|action| action.focus.clone())
362 });
363 let anchor = geometry.anchor.get();
364 state.update(cx, |state, cx| {
365 state.present(
366 !label && open && anchor.is_some(),
367 self.trigger_focus.as_ref(),
368 self.focusable
369 .then(|| first.clone().unwrap_or_else(|| surface.clone())),
370 window,
371 cx,
372 )
373 });
374
375 let dismiss = Dismiss {
376 transient: state.clone(),
377 persistent: self.persistent.clone(),
378 request: self.on_dismiss_request.clone(),
379 };
380 let on_escape = dismiss.clone();
381 let hover = state.clone();
382 let measured = geometry.anchor.clone();
383 let trigger = div()
384 .id(if label {
385 "label-anchor"
386 } else {
387 "tooltip-trigger"
388 })
389 .role(Role::Group)
390 .aria_description(self.text.clone())
391 .when(self.persistent.is_some(), |trigger| {
392 trigger.aria_expanded(open)
393 })
394 .when(open && !label, |trigger| {
395 trigger.when_some(first.clone(), |trigger, first| {
396 trigger.key_context("MaterialTooltipTrigger").on_action(
397 move |_: &FocusTooltipAction, window, cx| first.focus(window, cx),
398 )
399 })
400 })
401 .when(transient, |trigger| {
402 trigger.on_hover(move |hovering, window, cx| {
403 hover.update(cx, |state, cx| state.hover(false, *hovering, window, cx));
404 })
405 })
406 .when_some(
407 self.persistent
408 .clone()
409 .filter(|_| self.enable_user_input && !label),
410 |trigger, visibility| {
411 let press = state.clone();
412 let release = state.clone();
413 let release_outside = state.clone();
414 let key = visibility.clone();
415 let accessible = visibility.clone();
416 trigger
417 .capture_any_mouse_down(move |event, _, cx| {
418 if event.button == MouseButton::Left {
419 press.update(cx, |state, _| state.pressed = true);
420 }
421 })
422 .capture_any_mouse_up(move |event, _, cx| {
423 if event.button == MouseButton::Left
424 && release.update(cx, |state, _| std::mem::take(&mut state.pressed))
425 {
426 visibility.update(cx, |state, cx| state.show(cx));
427 }
428 })
429 .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
430 release_outside.update(cx, |state, _| state.pressed = false);
431 })
432 .capture_key_down(move |event, _, cx| {
433 if !event.is_held
434 && matches!(event.keystroke.key.as_str(), "enter" | "space")
435 {
436 key.update(cx, |state, cx| state.show(cx));
437 }
438 })
439 .on_a11y_action(AccessibleAction::Click, move |_, _, cx| {
440 accessible.update(cx, |state, cx| state.show(cx));
441 })
442 },
443 )
444 .relative()
445 .children(self.trigger.take())
446 .child(
447 canvas(
448 move |bounds, window, _| {
449 let anchor = (!label
450 || !bounds.intersect(&window.content_mask().bounds).is_empty())
451 .then_some(bounds);
452 if measured.replace(anchor) != anchor && open {
453 window.refresh();
454 }
455 },
456 |_, _, _, _| {},
457 )
458 .absolute()
459 .inset_0(),
460 );
461 let mut root =
462 div()
463 .id(self.id.clone())
464 .relative()
465 .child(trigger)
466 .when(open && !label, |root| {
467 root.key_context("MaterialTooltip").on_action(
468 move |_: &DismissTooltip, window, cx| {
469 on_escape.request(window, cx);
470 },
471 )
472 });
473 let Some(anchor) = anchor else {
474 return root;
475 };
476 let Some(motion) = OverlayMotion::sample(&self.id, open, window, cx) else {
477 return root;
478 };
479 let last = geometry.placed.get();
480 if !open && last.size.width <= px(0.) {
481 return root;
482 }
483
484 let viewport = window.viewport_size();
485 let theme = current_material_theme(window, cx);
486 let direction = theme.layout.direction;
487 let style = self.appearance.resolve(self.rich, viewport, motion, &theme);
488 let view = tooltip_surface(&mut self, open || label, style, motion, window, cx);
489 let margin = self.appearance.margin(viewport);
490 let view = if label {
491 div()
493 .id("label-content")
494 .role(Role::Group)
495 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
496 .child(
497 view.max_h((viewport.height - margin * 2.) * motion.scale)
498 .overflow_hidden(),
499 )
500 .into_any_element()
501 } else {
502 view.into_any_element()
503 };
504 let caret = self.appearance.caret.take();
505 let resolved_side = geometry.side.clone();
506 let shift_tab = first.clone();
507 let return_focus = self.trigger_focus;
508 let anchor_bounds = geometry.anchor.clone();
509 let tip = div()
510 .id(match (label, open) {
511 (true, true) => "label",
512 (true, false) => "label-exit",
513 (false, true) => "tooltip",
514 (false, false) => "tooltip-exit",
515 })
516 .relative()
517 .test_support()
518 .opacity(motion.alpha)
519 .when(open, |tip| {
520 tip.role(Role::Tooltip)
521 .aria_label(self.text)
522 .when(!label, |tip| {
523 tip.track_focus(&surface)
524 .key_context("MaterialTooltipContent")
525 .on_action(move |_: &FocusTooltipTrigger, window, cx| {
526 if let Some(trigger) = &return_focus
527 && shift_tab
528 .as_ref()
529 .is_some_and(|first| first.is_focused(window))
530 {
531 trigger.focus(window, cx);
532 } else {
533 cx.propagate();
534 }
535 })
536 })
537 .when(transient, |tip| {
538 tip.on_hover(move |hovering, window, cx| {
539 state.update(cx, |state, cx| state.hover(true, *hovering, window, cx));
540 })
541 })
542 .when(!label && dismiss.persistent.is_some(), |tip| {
543 tip.on_mouse_down_out(move |event, window, cx| {
544 if !anchor_bounds
545 .get()
546 .is_some_and(|anchor| anchor.contains(&event.position))
547 {
548 dismiss.request(window, cx);
549 }
550 })
551 })
552 })
553 .child(view)
554 .children(caret.map(|caret| {
555 canvas(
556 |_, _, _| (),
557 move |bounds, _, window, _| {
558 caret.paint(bounds, anchor, resolved_side.get(), style, window);
559 },
560 )
561 .absolute()
562 .inset_0()
563 }));
564 let scaled = ScaledOverlay::new(
565 motion
566 .text(tip, window)
567 .when(!open, |tip| tip.w(last.size.width * motion.scale)),
568 motion,
569 |_| point(0.5, 0.5),
570 );
571 let positioner = if open {
572 let positioner = self.positioner.map_or_else(
573 || {
574 TooltipPositioner::side(anchor)
575 .placement(self.placement.physical(direction))
576 .offset(self.offset)
577 },
578 |positioner| positioner(anchor, viewport, direction),
579 );
580 positioner
581 .margin(margin)
582 .when(!label, TooltipPositioner::occlude)
583 .on_position(move |resolved| {
584 geometry.placed.set(resolved.bounds);
585 geometry.side.set(resolved.placement);
586 })
587 .child(scaled)
588 } else {
589 TooltipPositioner::corner(Anchor::TopLeft, last.origin)
590 .margin(margin)
591 .child(scaled.width(last.size.width))
592 };
593 root = root.child(deferred(ThemeScope::inherit(positioner, window, cx)).with_priority(100));
594 root
595 }
596}
597
598fn tooltip_surface(
599 tooltip: &mut Tooltip,
600 open: bool,
601 style: SurfaceStyle,
602 motion: OverlayMotion,
603 window: &Window,
604 cx: &App,
605) -> gpui::Div {
606 let title = tooltip.title.take().map(IntoElement::into_any_element);
607 let title = if open {
608 tooltip.title_content.take().or(title)
609 } else {
610 title
611 };
612 let body = if open {
613 tooltip.body_content.take()
614 } else {
615 None
616 }
617 .unwrap_or_else(|| tooltip.text.clone().into_any_element());
618 let action = if open {
619 tooltip.action_content.take()
620 } else {
621 None
622 }
623 .or_else(|| {
624 tooltip
625 .action
626 .take()
627 .map(|action| render_action(action, open, style, motion, window, cx))
628 });
629 let link = tooltip.link.take().map(|(label, callback)| {
630 if open {
631 let activate = callback.clone();
632 Link::new("tooltip-link")
633 .accessibility_label(label.clone())
634 .text_color(style.action)
635 .underline()
636 .on_activate(move |_, window, cx| callback(window, cx))
637 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
638 activate(window, cx)
639 })
640 .child(label)
641 .into_any_element()
642 } else {
643 div()
644 .text_color(style.action)
645 .child(label)
646 .into_any_element()
647 }
648 });
649 let text_role = if tooltip.rich {
650 TypeRole::BodyMedium
651 } else {
652 TypeRole::BodySmall
653 };
654 let direction = current_material_theme(window, cx).layout.direction;
655 let shortcut = tooltip.shortcut.take().filter(|text| !text.is_empty());
656 let shortcut_pill = |text: SharedString| {
657 super::text_style(
658 div()
659 .id("tooltip-shortcut")
660 .test_support()
661 .flex_none()
662 .px(motion.px(4.))
663 .rounded(motion.px(4.))
664 .bg(style.content.opacity(0.12))
665 .text_color(style.content.opacity(0.78))
666 .child(text),
667 TypeRole::LabelSmall,
668 motion.scale,
669 window,
670 cx,
671 )
672 };
673 let (title_row, body_shortcut) = match (title, shortcut) {
674 (Some(title), Some(shortcut)) => (
675 Some(
676 div()
677 .flex()
678 .items_center()
679 .justify_between()
680 .gap(motion.px(8.))
681 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
682 .child(super::text_style(
683 div().min_w_0().text_color(style.title).child(title),
684 TypeRole::TitleSmall,
685 motion.scale,
686 window,
687 cx,
688 ))
689 .child(shortcut_pill(shortcut)),
690 ),
691 None,
692 ),
693 (Some(title), None) => (
694 Some(super::text_style(
695 div().text_color(style.title).child(title),
696 TypeRole::TitleSmall,
697 motion.scale,
698 window,
699 cx,
700 )),
701 None,
702 ),
703 (None, shortcut) => (None, shortcut),
704 };
705 let body_row = if let Some(shortcut) = body_shortcut {
706 div()
707 .flex()
708 .items_center()
709 .gap(motion.px(6.))
710 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
711 .child(super::text_style(
712 div().min_w_0().text_color(style.content).child(body),
713 text_role,
714 motion.scale,
715 window,
716 cx,
717 ))
718 .child(shortcut_pill(shortcut))
719 } else {
720 super::text_style(
721 div().text_color(style.content).child(body),
722 text_role,
723 motion.scale,
724 window,
725 cx,
726 )
727 };
728 style
729 .apply(div())
730 .children(title_row)
731 .child(body_row)
732 .children(action.map(|action| div().text_color(style.action).child(action)))
733 .children(link)
734}
735
736fn render_action(
737 action: TooltipAction,
738 open: bool,
739 style: SurfaceStyle,
740 motion: OverlayMotion,
741 window: &Window,
742 cx: &App,
743) -> AnyElement {
744 if open {
745 let activate = action.callback.clone();
746 return div()
747 .id("tooltip-action-keys")
748 .key_context("MaterialTooltipAction")
749 .on_action(move |_: &ActivateTooltipAction, window, cx| activate(window, cx))
750 .child(
751 Button::new("tooltip-action", action.label)
752 .track_focus(&action.focus)
753 .variant(ButtonVariant::Text)
754 .scale(motion.scale)
755 .colors(ButtonColors {
756 content: style.action_override,
757 ..Default::default()
758 })
759 .on_activate(move |window, cx| (action.callback)(window, cx)),
760 )
761 .into_any_element();
762 }
763 let density = current_material_theme(window, cx).layout.density;
764 div()
765 .min_h(motion.px(density.interactive_size(40.)))
766 .flex()
767 .items_center()
768 .justify_center()
769 .child(
770 super::text_style(
771 div().px(motion.px(16.)).min_w_0().truncate(),
772 TypeRole::LabelLarge,
773 motion.scale,
774 window,
775 cx,
776 )
777 .text_color(style.action)
778 .child(action.label),
779 )
780 .into_any_element()
781}