gpui_material_components/overlay/tooltip/
label.rs1use gpui::{
2 App, ElementId, Entity, EntityId, IntoElement, Pixels, RenderOnce, SharedString, Subscription,
3 Window,
4};
5use gpui_material_foundation::InteractionSource;
6
7use super::{Tooltip, TooltipCaret, TooltipPlacement};
8
9#[derive(IntoElement)]
11pub struct Label {
12 tooltip: Tooltip,
13 source: Option<(Entity<InteractionSource>, ElementId)>,
14 persistent: bool,
15}
16
17impl Label {
18 pub fn new(
19 id: impl Into<ElementId>,
20 anchor: impl IntoElement,
21 description: impl Into<SharedString>,
22 ) -> Self {
23 Self {
24 tooltip: Tooltip::plain(id, anchor, description),
25 source: None,
26 persistent: false,
27 }
28 }
29
30 pub fn content(mut self, content: impl IntoElement) -> Self {
32 self.tooltip = self.tooltip.body_content(content);
33 self
34 }
35
36 pub fn interaction_source(
38 mut self,
39 source: &Entity<InteractionSource>,
40 control_id: impl Into<ElementId>,
41 ) -> Self {
42 self.source = Some((source.clone(), control_id.into()));
43 self
44 }
45
46 pub fn persistent(mut self, persistent: bool) -> Self {
48 self.persistent = persistent;
49 self
50 }
51
52 pub fn placement(mut self, placement: TooltipPlacement) -> Self {
53 self.tooltip = self.tooltip.placement(placement);
54 self
55 }
56
57 pub fn offset(mut self, offset: Pixels) -> Self {
58 self.tooltip = self.tooltip.offset(offset);
59 self
60 }
61
62 pub fn max_width(mut self, width: Pixels) -> Self {
63 self.tooltip = self.tooltip.max_width(width);
64 self
65 }
66
67 pub fn caret(mut self, caret: TooltipCaret) -> Self {
68 self.tooltip = self.tooltip.caret(caret);
69 self
70 }
71}
72
73impl RenderOnce for Label {
74 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
75 let observed = self.source.as_ref().filter(|_| !self.persistent);
76 let observation = window.use_keyed_state(
77 (self.tooltip.id.clone(), "label-interaction-source"),
78 cx,
79 |_, _| None::<(EntityId, Subscription)>,
80 );
81 let source_id = observed.map(|(source, _)| source.entity_id());
82 observation.update(cx, |observation, cx| {
83 if observation.as_ref().map(|(id, _)| *id) != source_id {
84 *observation = observed.map(|(source, _)| {
85 (
86 source.entity_id(),
87 window.observe(source, cx, |_, window, _| window.refresh()),
88 )
89 });
90 }
91 });
92 let window_id = window.window_handle().window_id();
93 let active = observed
94 .and_then(|(source, control)| source.read(cx).state(window_id, control))
95 .is_some_and(|state| {
96 !state.disabled
97 && (state.hovered || state.pressed || state.dragged || state.focus_visible)
98 });
99 self.tooltip.label_visible = Some(self.persistent || active);
100 self.tooltip.render(window, cx)
101 }
102}