BlueGit

ict rusty-teams

feat(forward): forward up to 5 messages at once, tooltips never cover their popup

- Message menu "Forward" submenu in chats: "This message" / "Multiple messages"
- Selection mode: checkbox per row, Teams validators (limit 5, images, undelivered, scheduled), footer "{n} selected" with Cancel / Next instead of the composer, Escape cancels
- Forward dialog: Teams header and subheader, stacked previews, one chatsvc forward call with 1-5 message ids oldest first; demo builds one quote per message
- Tooltips: PopupTriggerTooltip drops the tooltip while its popup is open (delivery options, card overflow); gpui-component Button skips its managed tooltip while its popover or menu is open
- Managed tooltips close when their trigger is no longer rendered (e.g. "Jump to newest"): liveness token in the trigger's element state, checked by the gpui-base overlay
- layout_guard: footer, checkbox and dialog insets
- Deviations from Teams: split "Forward" item is a submenu (one more click for a single message); leaving the chat drops the selection without the "Discard and leave" confirmation; character, size and quote-only validators not built

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-04 · 3 weeks ago

Hash
a598903d4dcf158708e7aa64b995d366a24bd429
Parent
26c3c417
22 files changed +1284 −99
crates/app-state/src/app_state.rs +5 −0
@@ -15,6 +15,7 @@ use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15 15 use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16 16 use crate::card_state::{CardState, TaskDialogState};
17 17 use crate::data::{self, Directory};
18 use crate::forward_selection::ForwardSelection;
18 19 use crate::image_view_gallery::ViewerRequest;
19 20 use crate::local_previews::{LocalPreview, load_local_previews};
20 21 use crate::message_actions::{ForwardSource, SavedSet};
@@ -61,6 +62,7 @@ pub enum AppEvent {
61 62 CallHistory,
62 63 Translation,
63 64 Forward,
65 ForwardSelection,
64 66 ImageViewer,
65 67 StatusMessage,
66 68 Settings(crate::settings_section::SettingsSection),
@@ -124,6 +126,7 @@ pub struct AppState {
124 126 pub calls_list: crate::call::CallsList,
125 127 pub pins: HashMap<String, Vec<PinnedMessage>>,
126 128 pub forward_request: Option<ForwardSource>,
129 pub forward_selection: Option<ForwardSelection>,
127 130 pub image_viewer_request: Option<ViewerRequest>,
128 131 pub own_status: PresenceStatus,
129 132 pub own_email: String,
@@ -284,6 +287,7 @@ impl AppState {
284 287 calls_list: crate::call::CallsList::default(),
285 288 pins: HashMap::new(),
286 289 forward_request: None,
290 forward_selection: None,
287 291 image_viewer_request: None,
288 292 own_status: PresenceStatus::default(),
289 293 own_email: String::new(),
@@ -878,6 +882,7 @@ impl AppState {
878 882 let conversation_id = selection.conversation_id().to_owned();
879 883 self.selection = Some(selection);
880 884 self.keep_unread = None;
885 self.forward_selection = None;
881 886 cx.emit(AppEvent::Selection);
882 887 cx.notify();
883 888 self.refresh_live_meeting(&conversation_id, cx);
@@ -15,6 +15,7 @@ use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
15use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16use crate::card_state::{CardState, TaskDialogState};
16use crate::card_state::{CardState, TaskDialogState};
17use crate::data::{self, Directory};
17use crate::data::{self, Directory};
18use crate::forward_selection::ForwardSelection;
18use crate::image_view_gallery::ViewerRequest;
19use crate::image_view_gallery::ViewerRequest;
19use crate::local_previews::{LocalPreview, load_local_previews};
20use crate::local_previews::{LocalPreview, load_local_previews};
20use crate::message_actions::{ForwardSource, SavedSet};
21use crate::message_actions::{ForwardSource, SavedSet};
@@ -61,6 +62,7 @@ pub enum AppEvent {
61 CallHistory,
62 CallHistory,
62 Translation,
63 Translation,
63 Forward,
64 Forward,
65 ForwardSelection,
64 ImageViewer,
66 ImageViewer,
65 StatusMessage,
67 StatusMessage,
66 Settings(crate::settings_section::SettingsSection),
68 Settings(crate::settings_section::SettingsSection),
@@ -124,6 +126,7 @@ pub struct AppState {
124 pub calls_list: crate::call::CallsList,
126 pub calls_list: crate::call::CallsList,
125 pub pins: HashMap<String, Vec<PinnedMessage>>,
127 pub pins: HashMap<String, Vec<PinnedMessage>>,
126 pub forward_request: Option<ForwardSource>,
128 pub forward_request: Option<ForwardSource>,
129 pub forward_selection: Option<ForwardSelection>,
127 pub image_viewer_request: Option<ViewerRequest>,
130 pub image_viewer_request: Option<ViewerRequest>,
128 pub own_status: PresenceStatus,
131 pub own_status: PresenceStatus,
129 pub own_email: String,
132 pub own_email: String,
@@ -284,6 +287,7 @@ impl AppState {
284 calls_list: crate::call::CallsList::default(),
287 calls_list: crate::call::CallsList::default(),
285 pins: HashMap::new(),
288 pins: HashMap::new(),
286 forward_request: None,
289 forward_request: None,
290 forward_selection: None,
287 image_viewer_request: None,
291 image_viewer_request: None,
288 own_status: PresenceStatus::default(),
292 own_status: PresenceStatus::default(),
289 own_email: String::new(),
293 own_email: String::new(),
@@ -878,6 +882,7 @@ impl AppState {
878 let conversation_id = selection.conversation_id().to_owned();
882 let conversation_id = selection.conversation_id().to_owned();
879 self.selection = Some(selection);
883 self.selection = Some(selection);
880 self.keep_unread = None;
884 self.keep_unread = None;
885 self.forward_selection = None;
881 cx.emit(AppEvent::Selection);
886 cx.emit(AppEvent::Selection);
882 cx.notify();
887 cx.notify();
883 self.refresh_live_meeting(&conversation_id, cx);
888 self.refresh_live_meeting(&conversation_id, cx);
crates/app-state/src/demo.rs +45 −7
@@ -1075,13 +1075,24 @@ pub fn forwarded_message(
1075 1075 } else {
1076 1076 format!("<p>{}</p>", teams_core::escape_html(comment))
1077 1077 };
1078 let html = format!(
1079 "{comment_html}<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
1080 teams_core::escape_html(&source.message_id),
1081 teams_core::escape_html(&source.author),
1082 teams_core::escape_html(&source.text),
1083 );
1084 send_in_chat(chat, &source.text, &html, now)
1078 let quotes: String = source
1079 .messages
1080 .iter()
1081 .map(|item| {
1082 format!(
1083 "<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
1084 teams_core::escape_html(&item.message_id),
1085 teams_core::escape_html(&item.author),
1086 teams_core::escape_html(&item.text),
1087 )
1088 })
1089 .collect();
1090 let preview = source
1091 .messages
1092 .first()
1093 .map(|item| item.text.as_str())
1094 .unwrap_or_default();
1095 send_in_chat(chat, preview, &format!("{comment_html}{quotes}"), now)
1085 1096 }
1086 1097
1087 1098 #[allow(clippy::too_many_arguments)]
@@ -2351,6 +2362,33 @@ mod tests {
2351 2362 );
2352 2363 }
2353 2364
2365 #[test]
2366 fn a_multi_forward_quotes_each_message_in_order_after_the_comment() {
2367 let store = Store::open_in_memory().unwrap();
2368 seed(&store);
2369 let chat = store
2370 .recent_chats(100)
2371 .unwrap()
2372 .into_iter()
2373 .find(|chat| chat.id == PRIORITY_CHAT)
2374 .unwrap();
2375 let item = |message_id: &str, text: &str| crate::message_actions::ForwardItem {
2376 message_id: message_id.to_owned(),
2377 author: "Synthetic Sender".to_owned(),
2378 time: "09:00".to_owned(),
2379 text: text.to_owned(),
2380 };
2381 let source = ForwardSource {
2382 conversation_id: PRIORITY_CHAT.to_owned(),
2383 messages: vec![item("m1", "first"), item("m2", "second")],
2384 };
2385 let (_, record) = forwarded_message(&chat, &source, "fyi", Utc::now());
2386 let html = &record.body_html;
2387 assert!(html.starts_with("<p>fyi</p>"));
2388 assert_eq!(html.matches(FORWARD_ITEMTYPE).count(), 2);
2389 assert!(html.find("first").unwrap() < html.find("second").unwrap());
2390 }
2391
2354 2392 #[test]
2355 2393 fn png_has_signature_and_ends_with_iend() {
2356 2394 let png = encode_png(&MARA);
@@ -1075,13 +1075,24 @@ pub fn forwarded_message(
1075 } else {
1075 } else {
1076 format!("<p>{}</p>", teams_core::escape_html(comment))
1076 format!("<p>{}</p>", teams_core::escape_html(comment))
1077 };
1077 };
1078 let html = format!(
1078 let quotes: String = source
1079 "{comment_html}<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
1079 .messages
1080 teams_core::escape_html(&source.message_id),
1080 .iter()
1081 teams_core::escape_html(&source.author),
1081 .map(|item| {
1082 teams_core::escape_html(&source.text),
1082 format!(
1083 );
1083 "<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
1084 send_in_chat(chat, &source.text, &html, now)
1084 teams_core::escape_html(&item.message_id),
1085 teams_core::escape_html(&item.author),
1086 teams_core::escape_html(&item.text),
1087 )
1088 })
1089 .collect();
1090 let preview = source
1091 .messages
1092 .first()
1093 .map(|item| item.text.as_str())
1094 .unwrap_or_default();
1095 send_in_chat(chat, preview, &format!("{comment_html}{quotes}"), now)
1085}
1096}
1086
1097
1087#[allow(clippy::too_many_arguments)]
1098#[allow(clippy::too_many_arguments)]
@@ -2351,6 +2362,33 @@ mod tests {
2351 );
2362 );
2352 }
2363 }
2353
2364
2365 #[test]
2366 fn a_multi_forward_quotes_each_message_in_order_after_the_comment() {
2367 let store = Store::open_in_memory().unwrap();
2368 seed(&store);
2369 let chat = store
2370 .recent_chats(100)
2371 .unwrap()
2372 .into_iter()
2373 .find(|chat| chat.id == PRIORITY_CHAT)
2374 .unwrap();
2375 let item = |message_id: &str, text: &str| crate::message_actions::ForwardItem {
2376 message_id: message_id.to_owned(),
2377 author: "Synthetic Sender".to_owned(),
2378 time: "09:00".to_owned(),
2379 text: text.to_owned(),
2380 };
2381 let source = ForwardSource {
2382 conversation_id: PRIORITY_CHAT.to_owned(),
2383 messages: vec![item("m1", "first"), item("m2", "second")],
2384 };
2385 let (_, record) = forwarded_message(&chat, &source, "fyi", Utc::now());
2386 let html = &record.body_html;
2387 assert!(html.starts_with("<p>fyi</p>"));
2388 assert_eq!(html.matches(FORWARD_ITEMTYPE).count(), 2);
2389 assert!(html.find("first").unwrap() < html.find("second").unwrap());
2390 }
2391
2354 #[test]
2392 #[test]
2355 fn png_has_signature_and_ends_with_iend() {
2393 fn png_has_signature_and_ends_with_iend() {
2356 let png = encode_png(&MARA);
2394 let png = encode_png(&MARA);
crates/app-state/src/forward_selection.rs added +269 −0
@@ -0,0 +1,269 @@
1 use gpui_kit::*;
2
3 use crate::app_state::{AppEvent, AppState};
4 use crate::rows::{Delivery, MessageRow};
5
6 pub const FORWARD_SELECTION_LIMIT: usize = 5;
7 pub const FORWARD_IMAGE_LIMIT: usize = 5;
8 pub const FORWARD_LABEL: &str = "Forward";
9 pub const THIS_MESSAGE_LABEL: &str = "This message";
10 pub const MULTIPLE_MESSAGES_LABEL: &str = "Multiple messages";
11 pub const SELECT_MESSAGE_LABEL: &str = "Select message";
12 pub const NEXT_LABEL: &str = "Next";
13 pub const CANCEL_LABEL: &str = "Cancel";
14 pub const LIMIT_REASON: &str = "You can only forward up to 5 messages at a time.";
15 pub const IMAGE_LIMIT_REASON: &str = "Messages with more than 5 images can't be forwarded.";
16 pub const UNDELIVERED_REASON: &str = "Undelivered messages can't be forwarded.";
17 pub const SCHEDULED_REASON: &str = "Scheduled messages can't be forwarded until they're sent.";
18 pub const DEFAULT_REASON: &str = "This message can't be forwarded.";
19
20 pub fn selected_count_label(count: usize) -> String {
21 format!("{count} selected")
22 }
23
24 #[derive(Debug, Clone, PartialEq, Eq)]
25 pub struct ForwardSelection {
26 conversation_id: String,
27 message_ids: Vec<String>,
28 }
29
30 impl ForwardSelection {
31 pub fn starting_with(conversation_id: &str, message_id: &str) -> Self {
32 ForwardSelection {
33 conversation_id: conversation_id.to_owned(),
34 message_ids: vec![message_id.to_owned()],
35 }
36 }
37
38 pub fn conversation_id(&self) -> &str {
39 &self.conversation_id
40 }
41
42 pub fn message_ids(&self) -> &[String] {
43 &self.message_ids
44 }
45
46 pub fn contains(&self, message_id: &str) -> bool {
47 self.message_ids
48 .iter()
49 .any(|selected| selected == message_id)
50 }
51
52 pub fn len(&self) -> usize {
53 self.message_ids.len()
54 }
55
56 pub fn is_empty(&self) -> bool {
57 self.message_ids.is_empty()
58 }
59
60 pub fn is_full(&self) -> bool {
61 self.message_ids.len() >= FORWARD_SELECTION_LIMIT
62 }
63
64 /// Removes a selected message or adds a new one; returns false when the limit refuses it.
65 pub fn toggle(&mut self, message_id: &str) -> bool {
66 if let Some(position) = self
67 .message_ids
68 .iter()
69 .position(|selected| selected == message_id)
70 {
71 self.message_ids.remove(position);
72 return true;
73 }
74 if self.is_full() {
75 return false;
76 }
77 self.message_ids.push(message_id.to_owned());
78 true
79 }
80
81 /// `rows` in timeline order; the result keeps only the selected rows, oldest first.
82 pub fn ordered_ids<'a>(&self, rows: impl IntoIterator<Item = &'a MessageRow>) -> Vec<String> {
83 rows.into_iter()
84 .filter(|row| self.contains(&row.key))
85 .map(|row| row.key.clone())
86 .collect()
87 }
88 }
89
90 /// Why `row` cannot be checked now, in Teams' words; `None` when it can.
91 pub fn block_reason(
92 row: &MessageRow,
93 selection: &ForwardSelection,
94 selected_image_count: usize,
95 ) -> Option<&'static str> {
96 if selection.contains(&row.key) {
97 return None;
98 }
99 match row.delivery {
100 Delivery::Sending | Delivery::Failed(_) => return Some(UNDELIVERED_REASON),
101 Delivery::Scheduled(_) => return Some(SCHEDULED_REASON),
102 Delivery::Delivered => {}
103 }
104 if row.deleted || row.call.is_some() {
105 return Some(DEFAULT_REASON);
106 }
107 if !row.images.is_empty() && selected_image_count + row.images.len() > FORWARD_IMAGE_LIMIT {
108 return Some(IMAGE_LIMIT_REASON);
109 }
110 if selection.is_full() {
111 return Some(LIMIT_REASON);
112 }
113 None
114 }
115
116 impl AppState {
117 pub fn start_forward_selection(
118 &mut self,
119 conversation_id: &str,
120 message_id: &str,
121 cx: &mut Context<Self>,
122 ) {
123 if self.mode.read_only {
124 self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx);
125 return;
126 }
127 self.forward_selection = Some(ForwardSelection::starting_with(conversation_id, message_id));
128 cx.emit(AppEvent::ForwardSelection);
129 cx.notify();
130 }
131
132 pub fn toggle_forward_selected(&mut self, message_id: &str, cx: &mut Context<Self>) {
133 let Some(selection) = self.forward_selection.as_mut() else {
134 return;
135 };
136 if selection.toggle(message_id) {
137 cx.notify();
138 }
139 }
140
141 pub fn cancel_forward_selection(&mut self, cx: &mut Context<Self>) {
142 if self.forward_selection.take().is_some() {
143 cx.emit(AppEvent::ForwardSelection);
144 cx.notify();
145 }
146 }
147
148 /// `ordered_ids` are the selected messages, oldest first. The selection stays until the forward is sent.
149 pub fn forward_selected(&mut self, ordered_ids: &[String], cx: &mut Context<Self>) {
150 let Some(conversation_id) = self
151 .forward_selection
152 .as_ref()
153 .map(|selection| selection.conversation_id().to_owned())
154 else {
155 return;
156 };
157 if !ordered_ids.is_empty() {
158 self.request_forward_messages(&conversation_id, ordered_ids, cx);
159 }
160 }
161 }
162
163 #[cfg(test)]
164 mod tests {
165 use super::{
166 DEFAULT_REASON, Delivery, FORWARD_SELECTION_LIMIT, ForwardSelection, IMAGE_LIMIT_REASON,
167 LIMIT_REASON, MessageRow, SCHEDULED_REASON, UNDELIVERED_REASON, block_reason,
168 selected_count_label,
169 };
170 use crate::rows::ScheduledState;
171 use teams_core::ImageRef;
172
173 fn row(key: &str) -> MessageRow {
174 crate::pending_rows::pending_row(
175 key.to_owned(),
176 "chat".to_owned(),
177 None,
178 chrono::Utc::now(),
179 &crate::scheduled_rows::scheduled_outgoing("<p>hello</p>"),
180 Delivery::Delivered,
181 )
182 }
183
184 fn image() -> ImageRef {
185 ImageRef {
186 id: "image".into(),
187 url: "https://example.invalid/image.png".into(),
188 width: None,
189 height: None,
190 alt: None,
191 }
192 }
193
194 #[test]
195 fn the_first_message_is_selected_and_toggling_adds_or_removes() {
196 let mut selection = ForwardSelection::starting_with("chat", "m1");
197 assert_eq!(selection.message_ids(), ["m1"]);
198 assert!(selection.toggle("m2"));
199 assert!(selection.contains("m2"));
200 assert!(selection.toggle("m1"));
201 assert_eq!(selection.message_ids(), ["m2"]);
202 assert!(selection.toggle("m2"));
203 assert!(selection.is_empty());
204 }
205
206 #[test]
207 fn a_sixth_message_is_refused() {
208 let mut selection = ForwardSelection::starting_with("chat", "m1");
209 for id in ["m2", "m3", "m4", "m5"] {
210 assert!(selection.toggle(id));
211 }
212 assert!(selection.is_full());
213 assert!(!selection.toggle("m6"));
214 assert_eq!(selection.len(), FORWARD_SELECTION_LIMIT);
215 assert_eq!(block_reason(&row("m6"), &selection, 0), Some(LIMIT_REASON));
216 assert_eq!(block_reason(&row("m3"), &selection, 0), None);
217 }
218
219 #[test]
220 fn the_order_follows_the_timeline_not_the_clicks() {
221 let mut selection = ForwardSelection::starting_with("chat", "m3");
222 selection.toggle("m1");
223 let rows = [row("m1"), row("m2"), row("m3")];
224 assert_eq!(selection.ordered_ids(rows.iter()), ["m1", "m3"]);
225 }
226
227 #[test]
228 fn unsent_scheduled_deleted_and_call_rows_cannot_be_checked() {
229 let selection = ForwardSelection::starting_with("chat", "m1");
230 let mut sending = row("a");
231 sending.delivery = Delivery::Sending;
232 assert_eq!(
233 block_reason(&sending, &selection, 0),
234 Some(UNDELIVERED_REASON)
235 );
236 let mut failed = row("b");
237 failed.delivery = Delivery::Failed("offline".into());
238 assert_eq!(
239 block_reason(&failed, &selection, 0),
240 Some(UNDELIVERED_REASON)
241 );
242 let mut scheduled = row("c");
243 scheduled.delivery = Delivery::Scheduled(ScheduledState::Waiting);
244 assert_eq!(
245 block_reason(&scheduled, &selection, 0),
246 Some(SCHEDULED_REASON)
247 );
248 let mut deleted = row("d");
249 deleted.deleted = true;
250 assert_eq!(block_reason(&deleted, &selection, 0), Some(DEFAULT_REASON));
251 }
252
253 #[test]
254 fn images_over_the_combined_limit_block_the_row() {
255 let selection = ForwardSelection::starting_with("chat", "m1");
256 let mut pictures = row("p");
257 pictures.images = vec![image(), image()];
258 assert_eq!(block_reason(&pictures, &selection, 3), None);
259 assert_eq!(
260 block_reason(&pictures, &selection, 4),
261 Some(IMAGE_LIMIT_REASON)
262 );
263 }
264
265 #[test]
266 fn the_footer_counts_the_selection() {
267 assert_eq!(selected_count_label(3), "3 selected");
268 }
269 }
@@ -0,0 +1,269 @@
1use gpui_kit::*;
2
3use crate::app_state::{AppEvent, AppState};
4use crate::rows::{Delivery, MessageRow};
5
6pub const FORWARD_SELECTION_LIMIT: usize = 5;
7pub const FORWARD_IMAGE_LIMIT: usize = 5;
8pub const FORWARD_LABEL: &str = "Forward";
9pub const THIS_MESSAGE_LABEL: &str = "This message";
10pub const MULTIPLE_MESSAGES_LABEL: &str = "Multiple messages";
11pub const SELECT_MESSAGE_LABEL: &str = "Select message";
12pub const NEXT_LABEL: &str = "Next";
13pub const CANCEL_LABEL: &str = "Cancel";
14pub const LIMIT_REASON: &str = "You can only forward up to 5 messages at a time.";
15pub const IMAGE_LIMIT_REASON: &str = "Messages with more than 5 images can't be forwarded.";
16pub const UNDELIVERED_REASON: &str = "Undelivered messages can't be forwarded.";
17pub const SCHEDULED_REASON: &str = "Scheduled messages can't be forwarded until they're sent.";
18pub const DEFAULT_REASON: &str = "This message can't be forwarded.";
19
20pub fn selected_count_label(count: usize) -> String {
21 format!("{count} selected")
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ForwardSelection {
26 conversation_id: String,
27 message_ids: Vec<String>,
28}
29
30impl ForwardSelection {
31 pub fn starting_with(conversation_id: &str, message_id: &str) -> Self {
32 ForwardSelection {
33 conversation_id: conversation_id.to_owned(),
34 message_ids: vec![message_id.to_owned()],
35 }
36 }
37
38 pub fn conversation_id(&self) -> &str {
39 &self.conversation_id
40 }
41
42 pub fn message_ids(&self) -> &[String] {
43 &self.message_ids
44 }
45
46 pub fn contains(&self, message_id: &str) -> bool {
47 self.message_ids
48 .iter()
49 .any(|selected| selected == message_id)
50 }
51
52 pub fn len(&self) -> usize {
53 self.message_ids.len()
54 }
55
56 pub fn is_empty(&self) -> bool {
57 self.message_ids.is_empty()
58 }
59
60 pub fn is_full(&self) -> bool {
61 self.message_ids.len() >= FORWARD_SELECTION_LIMIT
62 }
63
64 /// Removes a selected message or adds a new one; returns false when the limit refuses it.
65 pub fn toggle(&mut self, message_id: &str) -> bool {
66 if let Some(position) = self
67 .message_ids
68 .iter()
69 .position(|selected| selected == message_id)
70 {
71 self.message_ids.remove(position);
72 return true;
73 }
74 if self.is_full() {
75 return false;
76 }
77 self.message_ids.push(message_id.to_owned());
78 true
79 }
80
81 /// `rows` in timeline order; the result keeps only the selected rows, oldest first.
82 pub fn ordered_ids<'a>(&self, rows: impl IntoIterator<Item = &'a MessageRow>) -> Vec<String> {
83 rows.into_iter()
84 .filter(|row| self.contains(&row.key))
85 .map(|row| row.key.clone())
86 .collect()
87 }
88}
89
90/// Why `row` cannot be checked now, in Teams' words; `None` when it can.
91pub fn block_reason(
92 row: &MessageRow,
93 selection: &ForwardSelection,
94 selected_image_count: usize,
95) -> Option<&'static str> {
96 if selection.contains(&row.key) {
97 return None;
98 }
99 match row.delivery {
100 Delivery::Sending | Delivery::Failed(_) => return Some(UNDELIVERED_REASON),
101 Delivery::Scheduled(_) => return Some(SCHEDULED_REASON),
102 Delivery::Delivered => {}
103 }
104 if row.deleted || row.call.is_some() {
105 return Some(DEFAULT_REASON);
106 }
107 if !row.images.is_empty() && selected_image_count + row.images.len() > FORWARD_IMAGE_LIMIT {
108 return Some(IMAGE_LIMIT_REASON);
109 }
110 if selection.is_full() {
111 return Some(LIMIT_REASON);
112 }
113 None
114}
115
116impl AppState {
117 pub fn start_forward_selection(
118 &mut self,
119 conversation_id: &str,
120 message_id: &str,
121 cx: &mut Context<Self>,
122 ) {
123 if self.mode.read_only {
124 self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx);
125 return;
126 }
127 self.forward_selection = Some(ForwardSelection::starting_with(conversation_id, message_id));
128 cx.emit(AppEvent::ForwardSelection);
129 cx.notify();
130 }
131
132 pub fn toggle_forward_selected(&mut self, message_id: &str, cx: &mut Context<Self>) {
133 let Some(selection) = self.forward_selection.as_mut() else {
134 return;
135 };
136 if selection.toggle(message_id) {
137 cx.notify();
138 }
139 }
140
141 pub fn cancel_forward_selection(&mut self, cx: &mut Context<Self>) {
142 if self.forward_selection.take().is_some() {
143 cx.emit(AppEvent::ForwardSelection);
144 cx.notify();
145 }
146 }
147
148 /// `ordered_ids` are the selected messages, oldest first. The selection stays until the forward is sent.
149 pub fn forward_selected(&mut self, ordered_ids: &[String], cx: &mut Context<Self>) {
150 let Some(conversation_id) = self
151 .forward_selection
152 .as_ref()
153 .map(|selection| selection.conversation_id().to_owned())
154 else {
155 return;
156 };
157 if !ordered_ids.is_empty() {
158 self.request_forward_messages(&conversation_id, ordered_ids, cx);
159 }
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::{
166 DEFAULT_REASON, Delivery, FORWARD_SELECTION_LIMIT, ForwardSelection, IMAGE_LIMIT_REASON,
167 LIMIT_REASON, MessageRow, SCHEDULED_REASON, UNDELIVERED_REASON, block_reason,
168 selected_count_label,
169 };
170 use crate::rows::ScheduledState;
171 use teams_core::ImageRef;
172
173 fn row(key: &str) -> MessageRow {
174 crate::pending_rows::pending_row(
175 key.to_owned(),
176 "chat".to_owned(),
177 None,
178 chrono::Utc::now(),
179 &crate::scheduled_rows::scheduled_outgoing("<p>hello</p>"),
180 Delivery::Delivered,
181 )
182 }
183
184 fn image() -> ImageRef {
185 ImageRef {
186 id: "image".into(),
187 url: "https://example.invalid/image.png".into(),
188 width: None,
189 height: None,
190 alt: None,
191 }
192 }
193
194 #[test]
195 fn the_first_message_is_selected_and_toggling_adds_or_removes() {
196 let mut selection = ForwardSelection::starting_with("chat", "m1");
197 assert_eq!(selection.message_ids(), ["m1"]);
198 assert!(selection.toggle("m2"));
199 assert!(selection.contains("m2"));
200 assert!(selection.toggle("m1"));
201 assert_eq!(selection.message_ids(), ["m2"]);
202 assert!(selection.toggle("m2"));
203 assert!(selection.is_empty());
204 }
205
206 #[test]
207 fn a_sixth_message_is_refused() {
208 let mut selection = ForwardSelection::starting_with("chat", "m1");
209 for id in ["m2", "m3", "m4", "m5"] {
210 assert!(selection.toggle(id));
211 }
212 assert!(selection.is_full());
213 assert!(!selection.toggle("m6"));
214 assert_eq!(selection.len(), FORWARD_SELECTION_LIMIT);
215 assert_eq!(block_reason(&row("m6"), &selection, 0), Some(LIMIT_REASON));
216 assert_eq!(block_reason(&row("m3"), &selection, 0), None);
217 }
218
219 #[test]
220 fn the_order_follows_the_timeline_not_the_clicks() {
221 let mut selection = ForwardSelection::starting_with("chat", "m3");
222 selection.toggle("m1");
223 let rows = [row("m1"), row("m2"), row("m3")];
224 assert_eq!(selection.ordered_ids(rows.iter()), ["m1", "m3"]);
225 }
226
227 #[test]
228 fn unsent_scheduled_deleted_and_call_rows_cannot_be_checked() {
229 let selection = ForwardSelection::starting_with("chat", "m1");
230 let mut sending = row("a");
231 sending.delivery = Delivery::Sending;
232 assert_eq!(
233 block_reason(&sending, &selection, 0),
234 Some(UNDELIVERED_REASON)
235 );
236 let mut failed = row("b");
237 failed.delivery = Delivery::Failed("offline".into());
238 assert_eq!(
239 block_reason(&failed, &selection, 0),
240 Some(UNDELIVERED_REASON)
241 );
242 let mut scheduled = row("c");
243 scheduled.delivery = Delivery::Scheduled(ScheduledState::Waiting);
244 assert_eq!(
245 block_reason(&scheduled, &selection, 0),
246 Some(SCHEDULED_REASON)
247 );
248 let mut deleted = row("d");
249 deleted.deleted = true;
250 assert_eq!(block_reason(&deleted, &selection, 0), Some(DEFAULT_REASON));
251 }
252
253 #[test]
254 fn images_over_the_combined_limit_block_the_row() {
255 let selection = ForwardSelection::starting_with("chat", "m1");
256 let mut pictures = row("p");
257 pictures.images = vec![image(), image()];
258 assert_eq!(block_reason(&pictures, &selection, 3), None);
259 assert_eq!(
260 block_reason(&pictures, &selection, 4),
261 Some(IMAGE_LIMIT_REASON)
262 );
263 }
264
265 #[test]
266 fn the_footer_counts_the_selection() {
267 assert_eq!(selected_count_label(3), "3 selected");
268 }
269}
crates/app-state/src/lib.rs +1 −0
@@ -13,6 +13,7 @@ pub mod channel_menu;
13 13 pub mod chat_actions;
14 14 pub mod chat_filter;
15 15 pub mod find_in_chat;
16 pub mod forward_selection;
16 17 pub mod chat_members;
17 18 pub mod chat_settings_actions;
18 19 pub mod connection_banner;
@@ -13,6 +13,7 @@ pub mod channel_menu;
13pub mod chat_actions;
13pub mod chat_actions;
14pub mod chat_filter;
14pub mod chat_filter;
15pub mod find_in_chat;
15pub mod find_in_chat;
16pub mod forward_selection;
16pub mod chat_members;
17pub mod chat_members;
17pub mod chat_settings_actions;
18pub mod chat_settings_actions;
18pub mod connection_banner;
19pub mod connection_banner;
crates/app-state/src/message_actions.rs +46 −10
@@ -8,6 +8,7 @@ use teams_core::{PinnedMessage, SavedMessage};
8 8 use crate::app_state::{AppEvent, AppState, Selection, selection_for};
9 9 use crate::channel_menu::{post_pin_failure, post_pin_notice};
10 10 use crate::format;
11 use crate::forward_selection::FORWARD_SELECTION_LIMIT;
11 12 use crate::image_view_gallery::ViewerRequest;
12 13 use crate::notice::short_error;
13 14 use crate::rows::{message_text, reply_excerpt};
@@ -57,12 +58,27 @@ fn saved_key(item: &SavedMessage) -> (String, String) {
57 58 #[derive(Debug, Clone, PartialEq, Eq)]
58 59 pub struct ForwardSource {
59 60 pub conversation_id: String,
61 /// 1 to 5 messages, oldest first.
62 pub messages: Vec<ForwardItem>,
63 }
64
65 #[derive(Debug, Clone, PartialEq, Eq)]
66 pub struct ForwardItem {
60 67 pub message_id: String,
61 68 pub author: String,
62 69 pub time: String,
63 70 pub text: String,
64 71 }
65 72
73 impl ForwardSource {
74 pub fn message_ids(&self) -> Vec<String> {
75 self.messages
76 .iter()
77 .map(|item| item.message_id.clone())
78 .collect()
79 }
80 }
81
66 82 fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
67 83 SavedMessage {
68 84 conversation_id: record.conversation_id.clone(),
@@ -335,24 +351,44 @@ impl AppState {
335 351 conversation_id: &str,
336 352 message_id: &str,
337 353 cx: &mut Context<Self>,
354 ) {
355 self.request_forward_messages(conversation_id, &[message_id.to_owned()], cx);
356 }
357
358 pub fn request_forward_messages(
359 &mut self,
360 conversation_id: &str,
361 message_ids: &[String],
362 cx: &mut Context<Self>,
338 363 ) {
339 364 if self.mode.read_only {
340 365 self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx);
341 366 return;
342 367 }
343 let Some(record) = self.message_record(conversation_id, message_id) else {
368 let mut records: Vec<MessageRecord> = message_ids
369 .iter()
370 .filter_map(|message_id| self.message_record(conversation_id, message_id))
371 .collect();
372 if records.is_empty() {
344 373 return;
345 };
374 }
375 records.sort_by_key(|record| record.created_at);
376 records.truncate(FORWARD_SELECTION_LIMIT);
346 377 let now = Local::now();
347 378 self.forward_request = Some(ForwardSource {
348 conversation_id: record.conversation_id.clone(),
349 message_id: record.message_id.clone(),
350 author: record
351 .sender_name
352 .clone()
353 .unwrap_or_else(|| "Unknown".to_owned()),
354 time: forward_time(record.created_at, now),
355 text: message_text(&record),
379 conversation_id: records[0].conversation_id.clone(),
380 messages: records
381 .iter()
382 .map(|record| ForwardItem {
383 message_id: record.message_id.clone(),
384 author: record
385 .sender_name
386 .clone()
387 .unwrap_or_else(|| "Unknown".to_owned()),
388 time: forward_time(record.created_at, now),
389 text: message_text(record),
390 })
391 .collect(),
356 392 });
357 393 cx.emit(AppEvent::Forward);
358 394 cx.notify();
@@ -8,6 +8,7 @@ use teams_core::{PinnedMessage, SavedMessage};
8use crate::app_state::{AppEvent, AppState, Selection, selection_for};
8use crate::app_state::{AppEvent, AppState, Selection, selection_for};
9use crate::channel_menu::{post_pin_failure, post_pin_notice};
9use crate::channel_menu::{post_pin_failure, post_pin_notice};
10use crate::format;
10use crate::format;
11use crate::forward_selection::FORWARD_SELECTION_LIMIT;
11use crate::image_view_gallery::ViewerRequest;
12use crate::image_view_gallery::ViewerRequest;
12use crate::notice::short_error;
13use crate::notice::short_error;
13use crate::rows::{message_text, reply_excerpt};
14use crate::rows::{message_text, reply_excerpt};
@@ -57,12 +58,27 @@ fn saved_key(item: &SavedMessage) -> (String, String) {
57#[derive(Debug, Clone, PartialEq, Eq)]
58#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct ForwardSource {
59pub struct ForwardSource {
59 pub conversation_id: String,
60 pub conversation_id: String,
61 /// 1 to 5 messages, oldest first.
62 pub messages: Vec<ForwardItem>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct ForwardItem {
60 pub message_id: String,
67 pub message_id: String,
61 pub author: String,
68 pub author: String,
62 pub time: String,
69 pub time: String,
63 pub text: String,
70 pub text: String,
64}
71}
65
72
73impl ForwardSource {
74 pub fn message_ids(&self) -> Vec<String> {
75 self.messages
76 .iter()
77 .map(|item| item.message_id.clone())
78 .collect()
79 }
80}
81
66fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
82fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
67 SavedMessage {
83 SavedMessage {
68 conversation_id: record.conversation_id.clone(),
84 conversation_id: record.conversation_id.clone(),
@@ -335,24 +351,44 @@ impl AppState {
335 conversation_id: &str,
351 conversation_id: &str,
336 message_id: &str,
352 message_id: &str,
337 cx: &mut Context<Self>,
353 cx: &mut Context<Self>,
354 ) {
355 self.request_forward_messages(conversation_id, &[message_id.to_owned()], cx);
356 }
357
358 pub fn request_forward_messages(
359 &mut self,
360 conversation_id: &str,
361 message_ids: &[String],
362 cx: &mut Context<Self>,
338 ) {
363 ) {
339 if self.mode.read_only {
364 if self.mode.read_only {
340 self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx);
365 self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx);
341 return;
366 return;
342 }
367 }
343 let Some(record) = self.message_record(conversation_id, message_id) else {
368 let mut records: Vec<MessageRecord> = message_ids
369 .iter()
370 .filter_map(|message_id| self.message_record(conversation_id, message_id))
371 .collect();
372 if records.is_empty() {
344 return;
373 return;
345 };
374 }
375 records.sort_by_key(|record| record.created_at);
376 records.truncate(FORWARD_SELECTION_LIMIT);
346 let now = Local::now();
377 let now = Local::now();
347 self.forward_request = Some(ForwardSource {
378 self.forward_request = Some(ForwardSource {
348 conversation_id: record.conversation_id.clone(),
379 conversation_id: records[0].conversation_id.clone(),
349 message_id: record.message_id.clone(),
380 messages: records
350 author: record
381 .iter()
351 .sender_name
382 .map(|record| ForwardItem {
352 .clone()
383 message_id: record.message_id.clone(),
353 .unwrap_or_else(|| "Unknown".to_owned()),
384 author: record
354 time: forward_time(record.created_at, now),
385 .sender_name
355 text: message_text(&record),
386 .clone()
387 .unwrap_or_else(|| "Unknown".to_owned()),
388 time: forward_time(record.created_at, now),
389 text: message_text(record),
390 })
391 .collect(),
356 });
392 });
357 cx.emit(AppEvent::Forward);
393 cx.emit(AppEvent::Forward);
358 cx.notify();
394 cx.notify();
crates/app/src/layout_guard.rs +152 −2
@@ -156,6 +156,7 @@ mod frames {
156 156 use std::sync::Arc;
157 157 use std::time::Duration;
158 158
159 use app_ui_kit::layout::ROW_PADDING;
159 160 use gpui_kit::test::TestWindowExt as _;
160 161 use gpui_kit::{
161 162 AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,
@@ -190,14 +191,20 @@ mod frames {
190 191 CHANNEL_DETAILS_TAG,
191 192 };
192 193 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
193 use crate::views::conversation::{FEED_EDGE_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
194 use crate::views::conversation::{
195 FEED_EDGE_TAG, FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG,
196 FORWARD_FOOTER_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG,
197 };
194 198 use crate::views::post_card::{
195 199 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
196 200 };
197 201 use crate::views::find_panel::{
198 202 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
199 203 };
200 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};
204 use crate::views::forward_dialog::{FORWARD_CARD_TAG, FORWARD_PREVIEW_TAG};
205 use crate::views::message_row::{
206 BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y, select_box_selector,
207 };
201 208 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
202 209 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
203 210 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -1508,6 +1515,149 @@ mod frames {
1508 1515 }
1509 1516 }
1510 1517
1518 const FORWARD_CHAT: &str = "demo-chat-release";
1519 const FORWARD_FOOTER_TAGS: [&str; 4] = [
1520 FORWARD_FOOTER_TAG,
1521 FORWARD_FOOTER_BAR_TAG,
1522 FORWARD_FOOTER_COUNT_TAG,
1523 FORWARD_FOOTER_NEXT_TAG,
1524 ];
1525 const FORWARD_DIALOG_PADDING: f32 = 16.;
1526 const FORWARD_BAR_PADDING: f32 = 8.;
1527 const FORWARD_ROWS_SCANNED: usize = 80;
1528
1529 fn forward_message_ids(
1530 state: &Entity<AppState>,
1531 visual: &mut VisualTestContext,
1532 ) -> Vec<String> {
1533 visual.update(|_, cx| {
1534 let mut records = state
1535 .read(cx)
1536 .store
1537 .messages(FORWARD_CHAT, None, 50)
1538 .expect("demo messages");
1539 records.retain(|record| !record.deleted);
1540 records.sort_by_key(|record| record.created_at);
1541 records
1542 .iter()
1543 .rev()
1544 .take(2)
1545 .map(|record| record.message_id.clone())
1546 .collect()
1547 })
1548 }
1549
1550 #[gpui_kit::test]
1551 fn forward_selection_footer_checks_and_dialog_keep_their_insets(cx: &mut TestAppContext) {
1552 let (handle, state) = mount(cx);
1553 let mut visual = VisualTestContext::from_window(handle, cx);
1554 for (width, height) in SIZES {
1555 visual.simulate_resize(size(px(width), px(height)));
1556 let window = Bounds {
1557 origin: point(px(0.), px(0.)),
1558 size: size(px(width), px(height)),
1559 };
1560 visual.update(|_, cx| {
1561 state.update(cx, |state, cx| {
1562 state.select(Selection::Chat(FORWARD_CHAT.to_owned()), cx)
1563 })
1564 });
1565 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1566 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
1567 let ids = forward_message_ids(&state, &mut visual);
1568 visual.update(|_, cx| {
1569 state.update(cx, |state, cx| {
1570 state.start_forward_selection(FORWARD_CHAT, &ids[0], cx);
1571 state.toggle_forward_selected(&ids[1], cx);
1572 })
1573 });
1574 collect(&mut visual, Some(FORWARD_FOOTER_NEXT_TAG));
1575 assert!(
1576 visual.debug_bounds(COMPOSER_BOX_TAG).is_none(),
1577 "the footer replaces the composer"
1578 );
1579 let tags: Vec<Tag> = FORWARD_FOOTER_TAGS
1580 .iter()
1581 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1582 .collect();
1583 let mut found: Vec<String> = violations(&tags, window, &FORWARD_FOOTER_TAGS)
1584 .into_iter()
1585 .map(|(key, message)| format!("forward@{width}x{height}:{key}: {message}"))
1586 .collect();
1587 let main = visual.debug_bounds(MAIN).expect("main island");
1588 let bar = visual.debug_bounds(FORWARD_FOOTER_BAR_TAG).expect("bar");
1589 let next = visual.debug_bounds(FORWARD_FOOTER_NEXT_TAG).expect("next");
1590 if (f32::from(bar.left() - composer.left())).abs() > TOLERANCE
1591 || (f32::from(bar.right() - composer.right())).abs() > TOLERANCE
1592 {
1593 found.push(format!(
1594 "forward@{width}x{height}: bar {} not on the composer edges {}",
1595 describe(bar),
1596 describe(composer)
1597 ));
1598 }
1599 for edge in [Edge::Top, Edge::Right, Edge::Bottom] {
1600 let gap = inset(bar, next, edge);
1601 if (gap - FORWARD_BAR_PADDING).abs() > TOLERANCE {
1602 found.push(format!(
1603 "forward@{width}x{height}: next button {edge:?} inset {gap} != {FORWARD_BAR_PADDING}"
1604 ));
1605 }
1606 }
1607 let checks: Vec<Bounds<Pixels>> = (0..FORWARD_ROWS_SCANNED)
1608 .filter_map(|index| {
1609 visual.debug_bounds(Box::leak(select_box_selector(index).into_boxed_str()))
1610 })
1611 .filter(|check| contains(main, *check))
1612 .collect();
1613 if checks.is_empty() {
1614 found.push(format!("forward@{width}x{height}: no checkbox rendered"));
1615 }
1616 for check in &checks {
1617 let left = inset(main, *check, Edge::Left);
1618 if (left - ROW_PADDING).abs() > TOLERANCE {
1619 found.push(format!(
1620 "forward@{width}x{height}: checkbox {} starts {left} from the island, not {ROW_PADDING}",
1621 describe(*check)
1622 ));
1623 }
1624 }
1625 visual.simulate_click(next.center(), Default::default());
1626 collect(&mut visual, Some(FORWARD_PREVIEW_TAG));
1627 let card = visual.debug_bounds(FORWARD_CARD_TAG).expect("dialog card");
1628 let preview = visual.debug_bounds(FORWARD_PREVIEW_TAG).expect("preview");
1629 if !contains(window, card) || !contains(card, preview) {
1630 found.push(format!(
1631 "forward@{width}x{height}: dialog {} or preview {} clipped",
1632 describe(card),
1633 describe(preview)
1634 ));
1635 }
1636 let (left, right) = (
1637 inset(card, preview, Edge::Left),
1638 inset(card, preview, Edge::Right),
1639 );
1640 if (left - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1641 || (right - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1642 {
1643 found.push(format!(
1644 "forward@{width}x{height}: preview insets {left}/{right} != {FORWARD_DIALOG_PADDING}"
1645 ));
1646 }
1647 visual.simulate_keystrokes("escape");
1648 collect(&mut visual, None);
1649 assert!(visual.debug_bounds(FORWARD_CARD_TAG).is_none());
1650 assert!(
1651 visual.debug_bounds(FORWARD_FOOTER_TAG).is_some(),
1652 "closing the dialog keeps the selection"
1653 );
1654 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_forward_selection(cx)));
1655 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1656 assert!(visual.debug_bounds(FORWARD_FOOTER_TAG).is_none());
1657 assert!(found.is_empty(), "{}", found.join("\n"));
1658 }
1659 }
1660
1511 1661 const MENU_ITEMS_SCANNED: usize = 40;
1512 1662 const MENU_CHAT: &str = "demo-chat-release";
1513 1663 const THEME_SELECT: &str = "settings-theme";
@@ -156,6 +156,7 @@ mod frames {
156 use std::sync::Arc;
156 use std::sync::Arc;
157 use std::time::Duration;
157 use std::time::Duration;
158
158
159 use app_ui_kit::layout::ROW_PADDING;
159 use gpui_kit::test::TestWindowExt as _;
160 use gpui_kit::test::TestWindowExt as _;
160 use gpui_kit::{
161 use gpui_kit::{
161 AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,
162 AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,
@@ -190,14 +191,20 @@ mod frames {
190 CHANNEL_DETAILS_TAG,
191 CHANNEL_DETAILS_TAG,
191 };
192 };
192 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
193 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
193 use crate::views::conversation::{FEED_EDGE_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
194 use crate::views::conversation::{
195 FEED_EDGE_TAG, FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG,
196 FORWARD_FOOTER_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG,
197 };
194 use crate::views::post_card::{
198 use crate::views::post_card::{
195 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
199 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
196 };
200 };
197 use crate::views::find_panel::{
201 use crate::views::find_panel::{
198 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
202 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
199 };
203 };
200 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};
204 use crate::views::forward_dialog::{FORWARD_CARD_TAG, FORWARD_PREVIEW_TAG};
205 use crate::views::message_row::{
206 BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y, select_box_selector,
207 };
201 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
208 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
202 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
209 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
203 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
210 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -1508,6 +1515,149 @@ mod frames {
1508 }
1515 }
1509 }
1516 }
1510
1517
1518 const FORWARD_CHAT: &str = "demo-chat-release";
1519 const FORWARD_FOOTER_TAGS: [&str; 4] = [
1520 FORWARD_FOOTER_TAG,
1521 FORWARD_FOOTER_BAR_TAG,
1522 FORWARD_FOOTER_COUNT_TAG,
1523 FORWARD_FOOTER_NEXT_TAG,
1524 ];
1525 const FORWARD_DIALOG_PADDING: f32 = 16.;
1526 const FORWARD_BAR_PADDING: f32 = 8.;
1527 const FORWARD_ROWS_SCANNED: usize = 80;
1528
1529 fn forward_message_ids(
1530 state: &Entity<AppState>,
1531 visual: &mut VisualTestContext,
1532 ) -> Vec<String> {
1533 visual.update(|_, cx| {
1534 let mut records = state
1535 .read(cx)
1536 .store
1537 .messages(FORWARD_CHAT, None, 50)
1538 .expect("demo messages");
1539 records.retain(|record| !record.deleted);
1540 records.sort_by_key(|record| record.created_at);
1541 records
1542 .iter()
1543 .rev()
1544 .take(2)
1545 .map(|record| record.message_id.clone())
1546 .collect()
1547 })
1548 }
1549
1550 #[gpui_kit::test]
1551 fn forward_selection_footer_checks_and_dialog_keep_their_insets(cx: &mut TestAppContext) {
1552 let (handle, state) = mount(cx);
1553 let mut visual = VisualTestContext::from_window(handle, cx);
1554 for (width, height) in SIZES {
1555 visual.simulate_resize(size(px(width), px(height)));
1556 let window = Bounds {
1557 origin: point(px(0.), px(0.)),
1558 size: size(px(width), px(height)),
1559 };
1560 visual.update(|_, cx| {
1561 state.update(cx, |state, cx| {
1562 state.select(Selection::Chat(FORWARD_CHAT.to_owned()), cx)
1563 })
1564 });
1565 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1566 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
1567 let ids = forward_message_ids(&state, &mut visual);
1568 visual.update(|_, cx| {
1569 state.update(cx, |state, cx| {
1570 state.start_forward_selection(FORWARD_CHAT, &ids[0], cx);
1571 state.toggle_forward_selected(&ids[1], cx);
1572 })
1573 });
1574 collect(&mut visual, Some(FORWARD_FOOTER_NEXT_TAG));
1575 assert!(
1576 visual.debug_bounds(COMPOSER_BOX_TAG).is_none(),
1577 "the footer replaces the composer"
1578 );
1579 let tags: Vec<Tag> = FORWARD_FOOTER_TAGS
1580 .iter()
1581 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1582 .collect();
1583 let mut found: Vec<String> = violations(&tags, window, &FORWARD_FOOTER_TAGS)
1584 .into_iter()
1585 .map(|(key, message)| format!("forward@{width}x{height}:{key}: {message}"))
1586 .collect();
1587 let main = visual.debug_bounds(MAIN).expect("main island");
1588 let bar = visual.debug_bounds(FORWARD_FOOTER_BAR_TAG).expect("bar");
1589 let next = visual.debug_bounds(FORWARD_FOOTER_NEXT_TAG).expect("next");
1590 if (f32::from(bar.left() - composer.left())).abs() > TOLERANCE
1591 || (f32::from(bar.right() - composer.right())).abs() > TOLERANCE
1592 {
1593 found.push(format!(
1594 "forward@{width}x{height}: bar {} not on the composer edges {}",
1595 describe(bar),
1596 describe(composer)
1597 ));
1598 }
1599 for edge in [Edge::Top, Edge::Right, Edge::Bottom] {
1600 let gap = inset(bar, next, edge);
1601 if (gap - FORWARD_BAR_PADDING).abs() > TOLERANCE {
1602 found.push(format!(
1603 "forward@{width}x{height}: next button {edge:?} inset {gap} != {FORWARD_BAR_PADDING}"
1604 ));
1605 }
1606 }
1607 let checks: Vec<Bounds<Pixels>> = (0..FORWARD_ROWS_SCANNED)
1608 .filter_map(|index| {
1609 visual.debug_bounds(Box::leak(select_box_selector(index).into_boxed_str()))
1610 })
1611 .filter(|check| contains(main, *check))
1612 .collect();
1613 if checks.is_empty() {
1614 found.push(format!("forward@{width}x{height}: no checkbox rendered"));
1615 }
1616 for check in &checks {
1617 let left = inset(main, *check, Edge::Left);
1618 if (left - ROW_PADDING).abs() > TOLERANCE {
1619 found.push(format!(
1620 "forward@{width}x{height}: checkbox {} starts {left} from the island, not {ROW_PADDING}",
1621 describe(*check)
1622 ));
1623 }
1624 }
1625 visual.simulate_click(next.center(), Default::default());
1626 collect(&mut visual, Some(FORWARD_PREVIEW_TAG));
1627 let card = visual.debug_bounds(FORWARD_CARD_TAG).expect("dialog card");
1628 let preview = visual.debug_bounds(FORWARD_PREVIEW_TAG).expect("preview");
1629 if !contains(window, card) || !contains(card, preview) {
1630 found.push(format!(
1631 "forward@{width}x{height}: dialog {} or preview {} clipped",
1632 describe(card),
1633 describe(preview)
1634 ));
1635 }
1636 let (left, right) = (
1637 inset(card, preview, Edge::Left),
1638 inset(card, preview, Edge::Right),
1639 );
1640 if (left - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1641 || (right - FORWARD_DIALOG_PADDING).abs() > TOLERANCE
1642 {
1643 found.push(format!(
1644 "forward@{width}x{height}: preview insets {left}/{right} != {FORWARD_DIALOG_PADDING}"
1645 ));
1646 }
1647 visual.simulate_keystrokes("escape");
1648 collect(&mut visual, None);
1649 assert!(visual.debug_bounds(FORWARD_CARD_TAG).is_none());
1650 assert!(
1651 visual.debug_bounds(FORWARD_FOOTER_TAG).is_some(),
1652 "closing the dialog keeps the selection"
1653 );
1654 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_forward_selection(cx)));
1655 collect(&mut visual, Some(COMPOSER_BOX_TAG));
1656 assert!(visual.debug_bounds(FORWARD_FOOTER_TAG).is_none());
1657 assert!(found.is_empty(), "{}", found.join("\n"));
1658 }
1659 }
1660
1511 const MENU_ITEMS_SCANNED: usize = 40;
1661 const MENU_ITEMS_SCANNED: usize = 40;
1512 const MENU_CHAT: &str = "demo-chat-release";
1662 const MENU_CHAT: &str = "demo-chat-release";
1513 const THEME_SELECT: &str = "settings-theme";
1663 const THEME_SELECT: &str = "settings-theme";
crates/app/src/views/adaptive_card.rs +3 −2
@@ -1,7 +1,8 @@
1 1 use std::collections::HashMap;
2 2 use std::rc::Rc;
3 3
4 use gpui_kit::component::{ActiveTheme as _, h_flex, tooltip::Tooltip, v_flex};
4 use gpui_kit::component::tooltip::{PopupTriggerTooltip as _, Tooltip};
5 use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
5 6 use gpui_kit::prelude::FluentBuilder as _;
6 7 use gpui_kit::*;
7 8 use teams_core::{
@@ -804,7 +805,7 @@ fn overflow_button(overflow_key: &str, open: bool, context: &CardContext) -> Sta
804 805 .cursor_pointer()
805 806 .hover(|button| button.bg(theme::row_hover()))
806 807 .when(open, |button| button.bg(theme::row_hover()))
807 .tooltip(|window, cx| Tooltip::new(ACTION_OVERFLOW_TOOLTIP).build(window, cx))
808 .popup_trigger_tooltip_text(open, ACTION_OVERFLOW_TOOLTIP)
808 809 .child(ACTION_OVERFLOW_LABEL)
809 810 .on_click(move |_, _, cx| {
810 811 cx.stop_propagation();
@@ -1,7 +1,8 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use gpui_kit::component::{ActiveTheme as _, h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::component::tooltip::{PopupTriggerTooltip as _, Tooltip};
5use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use gpui_kit::*;
7use teams_core::{
8use teams_core::{
@@ -804,7 +805,7 @@ fn overflow_button(overflow_key: &str, open: bool, context: &CardContext) -> Sta
804 .cursor_pointer()
805 .cursor_pointer()
805 .hover(|button| button.bg(theme::row_hover()))
806 .hover(|button| button.bg(theme::row_hover()))
806 .when(open, |button| button.bg(theme::row_hover()))
807 .when(open, |button| button.bg(theme::row_hover()))
807 .tooltip(|window, cx| Tooltip::new(ACTION_OVERFLOW_TOOLTIP).build(window, cx))
808 .popup_trigger_tooltip_text(open, ACTION_OVERFLOW_TOOLTIP)
808 .child(ACTION_OVERFLOW_LABEL)
809 .child(ACTION_OVERFLOW_LABEL)
809 .on_click(move |_, _, cx| {
810 .on_click(move |_, _, cx| {
810 cx.stop_propagation();
811 cx.stop_propagation();
crates/app/src/views/composer/delivery.rs +3 −2
@@ -2,7 +2,8 @@ use gpui_kit::component::fluent::{
2 2 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
3 3 MENU_LIST_PADDING, OPTION_CHECK_SIZE,
4 4 };
5 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5 use gpui_kit::component::tooltip::{PopupTriggerTooltip as _, Tooltip};
6 use gpui_kit::component::{h_flex, v_flex};
6 7 use gpui_kit::prelude::FluentBuilder as _;
7 8 use gpui_kit::*;
8 9 use store::MessageImportance;
@@ -84,7 +85,7 @@ impl Composer {
84 85 .cursor_pointer()
85 86 .when(open, |button| button.bg(theme::popup_hover()))
86 87 .hover(|button| button.bg(theme::popup_hover()))
87 .tooltip(|window, cx| Tooltip::new(DELIVERY_BUTTON_TITLE).build(window, cx))
88 .popup_trigger_tooltip_text(open, DELIVERY_BUTTON_TITLE)
88 89 .child(symbol(
89 90 "fluent_important",
90 91 COMPOSER_ICON_SIZE,
@@ -2,7 +2,8 @@ use gpui_kit::component::fluent::{
2 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
2 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
3 MENU_LIST_PADDING, OPTION_CHECK_SIZE,
3 MENU_LIST_PADDING, OPTION_CHECK_SIZE,
4};
4};
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::component::tooltip::{PopupTriggerTooltip as _, Tooltip};
6use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use gpui_kit::*;
8use store::MessageImportance;
9use store::MessageImportance;
@@ -84,7 +85,7 @@ impl Composer {
84 .cursor_pointer()
85 .cursor_pointer()
85 .when(open, |button| button.bg(theme::popup_hover()))
86 .when(open, |button| button.bg(theme::popup_hover()))
86 .hover(|button| button.bg(theme::popup_hover()))
87 .hover(|button| button.bg(theme::popup_hover()))
87 .tooltip(|window, cx| Tooltip::new(DELIVERY_BUTTON_TITLE).build(window, cx))
88 .popup_trigger_tooltip_text(open, DELIVERY_BUTTON_TITLE)
88 .child(symbol(
89 .child(symbol(
89 "fluent_important",
90 "fluent_important",
90 COMPOSER_ICON_SIZE,
91 COMPOSER_ICON_SIZE,
crates/app/src/views/conversation.rs +21 −6
@@ -29,6 +29,11 @@ pub use channel_details::{
29 29 mod deletes;
30 30 mod detached;
31 31 mod feed;
32 mod forward_select;
33 #[cfg(test)]
34 pub use forward_select::{
35 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
36 };
32 37 mod jump;
33 38 mod pins;
34 39 mod proposal;
@@ -678,6 +683,7 @@ impl ConversationView {
678 683 self.refresh_reactor_names(cx);
679 684 cx.notify();
680 685 }
686 AppEvent::ForwardSelection => self.on_forward_selection_changed(window, cx),
681 687 AppEvent::TaskDialog
682 688 | AppEvent::LocalPreviews
683 689 | AppEvent::Forward
@@ -3099,6 +3105,8 @@ impl ConversationView {
3099 3105 this.begin_reply(key, window, cx)
3100 3106 })),
3101 3107 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
3108 forward_multiple: in_chat
3109 .then(|| action(|this, key, _, cx| this.start_forward_selection(key, cx))),
3102 3110 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
3103 3111 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3104 3112 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
@@ -3566,6 +3574,7 @@ impl Render for ConversationView {
3566 3574 if in_feed && rows_seen != usize::MAX {
3567 3575 self.feed_at_top = rows_seen == 0;
3568 3576 }
3577 let forward_selection = self.active_forward_selection(cx);
3569 3578 let rows = self.rows.clone();
3570 3579 let rows_seen = self.feed_rows_seen.clone();
3571 3580 let env = RenderEnv {
@@ -3577,6 +3586,7 @@ impl Render for ConversationView {
3577 3586 timeline: self.timeline_bounds.clone(),
3578 3587 agent_runs: self.agent_runs.clone(),
3579 3588 reaction_proposals: self.reaction_proposals.clone(),
3589 forward_selection: forward_selection.clone(),
3580 3590 };
3581 3591 let pin_banner = self
3582 3592 .render_pin_banner(cx)
@@ -3800,12 +3810,16 @@ impl Render for ConversationView {
3800 3810 .children(pin_banner.map(pin_banner_overlay)),
3801 3811 )
3802 3812 .children(self.render_draft_error(cx))
3803 .when(!in_feed && !recap_active, |column| {
3804 column
3805 .child(self.render_typing_line(cx))
3806 .children(self.render_proposal_card(cx))
3807 .child(self.composer.clone())
3808 })
3813 .when(
3814 !in_feed && !recap_active,
3815 |column| match &forward_selection {
3816 Some(snapshot) => column.child(self.render_forward_footer(snapshot, cx)),
3817 None => column
3818 .child(self.render_typing_line(cx))
3819 .children(self.render_proposal_card(cx))
3820 .child(self.composer.clone()),
3821 },
3822 )
3809 3823 .child(self.render_drop_overlay(cx));
3810 3824 root.child(
3811 3825 h_flex()
@@ -3839,6 +3853,7 @@ impl Render for ConversationView {
3839 3853 if this.draft.read(cx).has_focus(window, cx) {
3840 3854 this.draft.update(cx, |draft, cx| draft.escape(cx));
3841 3855 }
3856 } else if this.cancel_forward_selection(cx) {
3842 3857 } else if !this.on_escape(window, cx) {
3843 3858 cx.propagate();
3844 3859 }
@@ -29,6 +29,11 @@ pub use channel_details::{
29mod deletes;
29mod deletes;
30mod detached;
30mod detached;
31mod feed;
31mod feed;
32mod forward_select;
33#[cfg(test)]
34pub use forward_select::{
35 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
36};
32mod jump;
37mod jump;
33mod pins;
38mod pins;
34mod proposal;
39mod proposal;
@@ -678,6 +683,7 @@ impl ConversationView {
678 self.refresh_reactor_names(cx);
683 self.refresh_reactor_names(cx);
679 cx.notify();
684 cx.notify();
680 }
685 }
686 AppEvent::ForwardSelection => self.on_forward_selection_changed(window, cx),
681 AppEvent::TaskDialog
687 AppEvent::TaskDialog
682 | AppEvent::LocalPreviews
688 | AppEvent::LocalPreviews
683 | AppEvent::Forward
689 | AppEvent::Forward
@@ -3099,6 +3105,8 @@ impl ConversationView {
3099 this.begin_reply(key, window, cx)
3105 this.begin_reply(key, window, cx)
3100 })),
3106 })),
3101 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
3107 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
3108 forward_multiple: in_chat
3109 .then(|| action(|this, key, _, cx| this.start_forward_selection(key, cx))),
3102 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
3110 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
3103 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3111 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3104 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
3112 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
@@ -3566,6 +3574,7 @@ impl Render for ConversationView {
3566 if in_feed && rows_seen != usize::MAX {
3574 if in_feed && rows_seen != usize::MAX {
3567 self.feed_at_top = rows_seen == 0;
3575 self.feed_at_top = rows_seen == 0;
3568 }
3576 }
3577 let forward_selection = self.active_forward_selection(cx);
3569 let rows = self.rows.clone();
3578 let rows = self.rows.clone();
3570 let rows_seen = self.feed_rows_seen.clone();
3579 let rows_seen = self.feed_rows_seen.clone();
3571 let env = RenderEnv {
3580 let env = RenderEnv {
@@ -3577,6 +3586,7 @@ impl Render for ConversationView {
3577 timeline: self.timeline_bounds.clone(),
3586 timeline: self.timeline_bounds.clone(),
3578 agent_runs: self.agent_runs.clone(),
3587 agent_runs: self.agent_runs.clone(),
3579 reaction_proposals: self.reaction_proposals.clone(),
3588 reaction_proposals: self.reaction_proposals.clone(),
3589 forward_selection: forward_selection.clone(),
3580 };
3590 };
3581 let pin_banner = self
3591 let pin_banner = self
3582 .render_pin_banner(cx)
3592 .render_pin_banner(cx)
@@ -3800,12 +3810,16 @@ impl Render for ConversationView {
3800 .children(pin_banner.map(pin_banner_overlay)),
3810 .children(pin_banner.map(pin_banner_overlay)),
3801 )
3811 )
3802 .children(self.render_draft_error(cx))
3812 .children(self.render_draft_error(cx))
3803 .when(!in_feed && !recap_active, |column| {
3813 .when(
3804 column
3814 !in_feed && !recap_active,
3805 .child(self.render_typing_line(cx))
3815 |column| match &forward_selection {
3806 .children(self.render_proposal_card(cx))
3816 Some(snapshot) => column.child(self.render_forward_footer(snapshot, cx)),
3807 .child(self.composer.clone())
3817 None => column
3808 })
3818 .child(self.render_typing_line(cx))
3819 .children(self.render_proposal_card(cx))
3820 .child(self.composer.clone()),
3821 },
3822 )
3809 .child(self.render_drop_overlay(cx));
3823 .child(self.render_drop_overlay(cx));
3810 root.child(
3824 root.child(
3811 h_flex()
3825 h_flex()
@@ -3839,6 +3853,7 @@ impl Render for ConversationView {
3839 if this.draft.read(cx).has_focus(window, cx) {
3853 if this.draft.read(cx).has_focus(window, cx) {
3840 this.draft.update(cx, |draft, cx| draft.escape(cx));
3854 this.draft.update(cx, |draft, cx| draft.escape(cx));
3841 }
3855 }
3856 } else if this.cancel_forward_selection(cx) {
3842 } else if !this.on_escape(window, cx) {
3857 } else if !this.on_escape(window, cx) {
3843 cx.propagate();
3858 cx.propagate();
3844 }
3859 }
crates/app/src/views/conversation/forward_select.rs added +180 −0
@@ -0,0 +1,180 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::button::{Button, ButtonVariants as _};
3 use gpui_kit::component::h_flex;
4 use gpui_kit::*;
5
6 use super::ConversationView;
7 use crate::forward_selection::{CANCEL_LABEL, ForwardSelection, NEXT_LABEL, selected_count_label};
8 use crate::rows::MessageRow;
9 use crate::theme;
10 use crate::views::widgets::icon;
11 use app_ui_kit::layout::ROW_PADDING;
12
13 pub const FORWARD_FOOTER_TAG: &str = "forward-footer";
14 pub const FORWARD_FOOTER_BAR_TAG: &str = "forward-footer/bar";
15 pub const FORWARD_FOOTER_COUNT_TAG: &str = "forward-footer/bar/count";
16 pub const FORWARD_FOOTER_NEXT_TAG: &str = "forward-footer/bar/next";
17 const FOOTER_TOP: f32 = 8.;
18 const FOOTER_BOTTOM: f32 = 16.;
19 const BAR_PADDING: f32 = 8.;
20 const BAR_RADIUS: f32 = 12.;
21 const COUNT_INSET: f32 = 4.;
22 const ICON_SIZE: f32 = 16.;
23 const BUTTON_HEIGHT: f32 = 32.;
24 const BUTTON_RADIUS: f32 = 6.;
25 const DISABLED_OPACITY: f32 = 0.4;
26
27 #[derive(Debug, Clone, PartialEq, Eq)]
28 pub(super) struct SelectionSnapshot {
29 pub selection: ForwardSelection,
30 pub image_count: usize,
31 }
32
33 impl ConversationView {
34 pub(super) fn active_forward_selection(&self, cx: &App) -> Option<SelectionSnapshot> {
35 let chat_id = self
36 .chat_id()
37 .filter(|_| !self.draft_active && !self.in_feed())?;
38 let selection = self
39 .app
40 .read(cx)
41 .forward_selection
42 .clone()
43 .filter(|selection| selection.conversation_id() == chat_id)?;
44 let image_count = self
45 .rows
46 .borrow()
47 .iter()
48 .flat_map(|row| row.messages())
49 .filter(|message| selection.contains(&message.key))
50 .map(|message| message.images.len())
51 .sum();
52 Some(SelectionSnapshot {
53 selection,
54 image_count,
55 })
56 }
57
58 pub(super) fn start_forward_selection(&mut self, message_id: &str, cx: &mut Context<Self>) {
59 if let Some(chat_id) = self.chat_id() {
60 self.app.update(cx, |state, cx| {
61 state.start_forward_selection(&chat_id, message_id, cx)
62 });
63 }
64 }
65
66 pub(super) fn on_forward_selection_changed(
67 &mut self,
68 window: &mut Window,
69 cx: &mut Context<Self>,
70 ) {
71 let row_count = self.rows.borrow().len();
72 self.scroller.update(cx, |scroller, cx| {
73 scroller.remeasure_items(0..row_count, cx)
74 });
75 if self.active_forward_selection(cx).is_some() {
76 window.focus(&self.focus_handle, cx);
77 } else if !self.draft_active && !self.in_feed() {
78 self.composer
79 .update(cx, |composer, cx| composer.focus(window, cx));
80 }
81 cx.notify();
82 }
83
84 pub(super) fn cancel_forward_selection(&mut self, cx: &mut Context<Self>) -> bool {
85 if self.active_forward_selection(cx).is_none() {
86 return false;
87 }
88 self.app
89 .update(cx, |state, cx| state.cancel_forward_selection(cx));
90 true
91 }
92
93 fn forward_next(&mut self, cx: &mut Context<Self>) {
94 let Some(snapshot) = self.active_forward_selection(cx) else {
95 return;
96 };
97 let ordered_ids = {
98 let rows = self.rows.borrow();
99 let messages: Vec<&MessageRow> = rows.iter().flat_map(|row| row.messages()).collect();
100 snapshot.selection.ordered_ids(messages)
101 };
102 self.app
103 .update(cx, |state, cx| state.forward_selected(&ordered_ids, cx));
104 }
105
106 pub(super) fn render_forward_footer(
107 &self,
108 snapshot: &SelectionSnapshot,
109 cx: &mut Context<Self>,
110 ) -> Div {
111 let count = snapshot.selection.len();
112 div()
113 .debug_selector(|| FORWARD_FOOTER_TAG.into())
114 .w_full()
115 .flex_none()
116 .px(px(ROW_PADDING))
117 .pt(px(FOOTER_TOP))
118 .pb(px(FOOTER_BOTTOM))
119 .child(
120 h_flex()
121 .debug_selector(|| FORWARD_FOOTER_BAR_TAG.into())
122 .w_full()
123 .p(px(BAR_PADDING))
124 .gap(px(BAR_PADDING))
125 .items_center()
126 .rounded(px(BAR_RADIUS))
127 .bg(theme::surface_raised())
128 .child(
129 h_flex()
130 .debug_selector(|| FORWARD_FOOTER_COUNT_TAG.into())
131 .flex_1()
132 .min_w_0()
133 .pl(px(COUNT_INSET))
134 .gap(px(BAR_PADDING))
135 .items_center()
136 .child(icon(IconName::Forward, ICON_SIZE, theme::text_soft()))
137 .child(
138 div()
139 .truncate()
140 .text_size(px(13.))
141 .text_color(theme::text())
142 .child(selected_count_label(count)),
143 ),
144 )
145 .child(
146 Button::new("forward-footer-cancel")
147 .ghost()
148 .label(CANCEL_LABEL)
149 .on_click(cx.listener(|this, _, _, cx| {
150 this.cancel_forward_selection(cx);
151 })),
152 )
153 .child(next_button(count > 0, cx)),
154 )
155 }
156 }
157
158 fn next_button(enabled: bool, cx: &mut Context<ConversationView>) -> Stateful<Div> {
159 let button = h_flex()
160 .id("forward-footer-next")
161 .debug_selector(|| FORWARD_FOOTER_NEXT_TAG.into())
162 .h(px(BUTTON_HEIGHT))
163 .flex_none()
164 .px(px(16.))
165 .items_center()
166 .rounded(px(BUTTON_RADIUS))
167 .bg(theme::accent())
168 .text_color(theme::on_accent())
169 .text_size(px(13.))
170 .font_weight(FontWeight::SEMIBOLD)
171 .child(NEXT_LABEL);
172 if enabled {
173 button
174 .cursor_pointer()
175 .hover(|button| button.bg(theme::accent_text()))
176 .on_click(cx.listener(|this, _, _, cx| this.forward_next(cx)))
177 } else {
178 button.opacity(DISABLED_OPACITY)
179 }
180 }
@@ -0,0 +1,180 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::h_flex;
4use gpui_kit::*;
5
6use super::ConversationView;
7use crate::forward_selection::{CANCEL_LABEL, ForwardSelection, NEXT_LABEL, selected_count_label};
8use crate::rows::MessageRow;
9use crate::theme;
10use crate::views::widgets::icon;
11use app_ui_kit::layout::ROW_PADDING;
12
13pub const FORWARD_FOOTER_TAG: &str = "forward-footer";
14pub const FORWARD_FOOTER_BAR_TAG: &str = "forward-footer/bar";
15pub const FORWARD_FOOTER_COUNT_TAG: &str = "forward-footer/bar/count";
16pub const FORWARD_FOOTER_NEXT_TAG: &str = "forward-footer/bar/next";
17const FOOTER_TOP: f32 = 8.;
18const FOOTER_BOTTOM: f32 = 16.;
19const BAR_PADDING: f32 = 8.;
20const BAR_RADIUS: f32 = 12.;
21const COUNT_INSET: f32 = 4.;
22const ICON_SIZE: f32 = 16.;
23const BUTTON_HEIGHT: f32 = 32.;
24const BUTTON_RADIUS: f32 = 6.;
25const DISABLED_OPACITY: f32 = 0.4;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub(super) struct SelectionSnapshot {
29 pub selection: ForwardSelection,
30 pub image_count: usize,
31}
32
33impl ConversationView {
34 pub(super) fn active_forward_selection(&self, cx: &App) -> Option<SelectionSnapshot> {
35 let chat_id = self
36 .chat_id()
37 .filter(|_| !self.draft_active && !self.in_feed())?;
38 let selection = self
39 .app
40 .read(cx)
41 .forward_selection
42 .clone()
43 .filter(|selection| selection.conversation_id() == chat_id)?;
44 let image_count = self
45 .rows
46 .borrow()
47 .iter()
48 .flat_map(|row| row.messages())
49 .filter(|message| selection.contains(&message.key))
50 .map(|message| message.images.len())
51 .sum();
52 Some(SelectionSnapshot {
53 selection,
54 image_count,
55 })
56 }
57
58 pub(super) fn start_forward_selection(&mut self, message_id: &str, cx: &mut Context<Self>) {
59 if let Some(chat_id) = self.chat_id() {
60 self.app.update(cx, |state, cx| {
61 state.start_forward_selection(&chat_id, message_id, cx)
62 });
63 }
64 }
65
66 pub(super) fn on_forward_selection_changed(
67 &mut self,
68 window: &mut Window,
69 cx: &mut Context<Self>,
70 ) {
71 let row_count = self.rows.borrow().len();
72 self.scroller.update(cx, |scroller, cx| {
73 scroller.remeasure_items(0..row_count, cx)
74 });
75 if self.active_forward_selection(cx).is_some() {
76 window.focus(&self.focus_handle, cx);
77 } else if !self.draft_active && !self.in_feed() {
78 self.composer
79 .update(cx, |composer, cx| composer.focus(window, cx));
80 }
81 cx.notify();
82 }
83
84 pub(super) fn cancel_forward_selection(&mut self, cx: &mut Context<Self>) -> bool {
85 if self.active_forward_selection(cx).is_none() {
86 return false;
87 }
88 self.app
89 .update(cx, |state, cx| state.cancel_forward_selection(cx));
90 true
91 }
92
93 fn forward_next(&mut self, cx: &mut Context<Self>) {
94 let Some(snapshot) = self.active_forward_selection(cx) else {
95 return;
96 };
97 let ordered_ids = {
98 let rows = self.rows.borrow();
99 let messages: Vec<&MessageRow> = rows.iter().flat_map(|row| row.messages()).collect();
100 snapshot.selection.ordered_ids(messages)
101 };
102 self.app
103 .update(cx, |state, cx| state.forward_selected(&ordered_ids, cx));
104 }
105
106 pub(super) fn render_forward_footer(
107 &self,
108 snapshot: &SelectionSnapshot,
109 cx: &mut Context<Self>,
110 ) -> Div {
111 let count = snapshot.selection.len();
112 div()
113 .debug_selector(|| FORWARD_FOOTER_TAG.into())
114 .w_full()
115 .flex_none()
116 .px(px(ROW_PADDING))
117 .pt(px(FOOTER_TOP))
118 .pb(px(FOOTER_BOTTOM))
119 .child(
120 h_flex()
121 .debug_selector(|| FORWARD_FOOTER_BAR_TAG.into())
122 .w_full()
123 .p(px(BAR_PADDING))
124 .gap(px(BAR_PADDING))
125 .items_center()
126 .rounded(px(BAR_RADIUS))
127 .bg(theme::surface_raised())
128 .child(
129 h_flex()
130 .debug_selector(|| FORWARD_FOOTER_COUNT_TAG.into())
131 .flex_1()
132 .min_w_0()
133 .pl(px(COUNT_INSET))
134 .gap(px(BAR_PADDING))
135 .items_center()
136 .child(icon(IconName::Forward, ICON_SIZE, theme::text_soft()))
137 .child(
138 div()
139 .truncate()
140 .text_size(px(13.))
141 .text_color(theme::text())
142 .child(selected_count_label(count)),
143 ),
144 )
145 .child(
146 Button::new("forward-footer-cancel")
147 .ghost()
148 .label(CANCEL_LABEL)
149 .on_click(cx.listener(|this, _, _, cx| {
150 this.cancel_forward_selection(cx);
151 })),
152 )
153 .child(next_button(count > 0, cx)),
154 )
155 }
156}
157
158fn next_button(enabled: bool, cx: &mut Context<ConversationView>) -> Stateful<Div> {
159 let button = h_flex()
160 .id("forward-footer-next")
161 .debug_selector(|| FORWARD_FOOTER_NEXT_TAG.into())
162 .h(px(BUTTON_HEIGHT))
163 .flex_none()
164 .px(px(16.))
165 .items_center()
166 .rounded(px(BUTTON_RADIUS))
167 .bg(theme::accent())
168 .text_color(theme::on_accent())
169 .text_size(px(13.))
170 .font_weight(FontWeight::SEMIBOLD)
171 .child(NEXT_LABEL);
172 if enabled {
173 button
174 .cursor_pointer()
175 .hover(|button| button.bg(theme::accent_text()))
176 .on_click(cx.listener(|this, _, _, cx| this.forward_next(cx)))
177 } else {
178 button.opacity(DISABLED_OPACITY)
179 }
180}
crates/app/src/views/conversation/render_env.rs +28 −8
@@ -10,10 +10,12 @@ use gpui_kit::*;
10 10 use mcp::ReactionProposal;
11 11 use teams_core::{ImageRef, LinkPreview};
12 12
13 use super::forward_select::SelectionSnapshot;
13 14 use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
14 15 use crate::agent_api::agent_label;
15 16 use crate::agents::AgentRun;
16 17 use crate::app_state::AppState;
18 use crate::forward_selection::block_reason;
17 19 use crate::rows::{Delivery, MessageRow, PostRow, ReactionChip, RecordingCard};
18 20 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19 21 use crate::translation::TranslationLine;
@@ -22,7 +24,7 @@ use crate::views::attachments::ImageActions;
22 24 use crate::views::call_card::CallActions;
23 25 use crate::views::call_notice::RecapActions;
24 26 use crate::views::composer::Composer;
25 use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};
27 use crate::views::message_row::{DeliveryActions, RowActions, RowSelect, SharedRowAction};
26 28 use crate::views::post_card::{PostAction, PostActions};
27 29 use crate::views::reaction_proposal_pill::ReactionPill;
28 30 use crate::views::toolbar_placement::TimelineBounds;
@@ -37,6 +39,7 @@ pub(super) struct RenderEnv {
37 39 pub timeline: TimelineBounds,
38 40 pub agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
39 41 pub reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
42 pub forward_selection: Option<SelectionSnapshot>,
40 43 }
41 44
42 45 fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
@@ -295,18 +298,24 @@ impl RenderEnv {
295 298 &message.key,
296 299 cx,
297 300 );
301 let select = self
302 .forward_selection
303 .as_ref()
304 .map(|snapshot| self.row_select(snapshot, message));
305 let selecting = select.is_some();
298 306 RowActions {
307 select,
299 308 bot,
300 309 delivery,
301 reply,
302 hovered,
303 menu,
310 reply: reply.filter(|_| !selecting),
311 hovered: hovered.filter(|_| !selecting),
312 menu: menu.filter(|_| !selecting),
304 313 scheduled_menu,
305 react,
314 react: react.filter(|_| !selecting),
306 315 reaction_controls,
307 add_reaction,
308 files,
309 open_image,
316 add_reaction: add_reaction.filter(|_| !selecting),
317 files: files.filter(|_| !selecting),
318 open_image: open_image.filter(|_| !selecting),
310 319 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
311 320 saved: self
312 321 .app
@@ -327,6 +336,17 @@ impl RenderEnv {
327 336 }
328 337 }
329 338
339 fn row_select(&self, snapshot: &SelectionSnapshot, message: &MessageRow) -> RowSelect {
340 let (app, key) = (self.app.clone(), message.key.clone());
341 RowSelect {
342 checked: snapshot.selection.contains(&message.key),
343 blocked: block_reason(message, &snapshot.selection, snapshot.image_count),
344 toggle: Rc::new(move |cx| {
345 app.update(cx, |state, cx| state.toggle_forward_selected(&key, cx))
346 }),
347 }
348 }
349
330 350 fn undo_delete_action(
331 351 &self,
332 352 message: &MessageRow,
@@ -10,10 +10,12 @@ use gpui_kit::*;
10use mcp::ReactionProposal;
10use mcp::ReactionProposal;
11use teams_core::{ImageRef, LinkPreview};
11use teams_core::{ImageRef, LinkPreview};
12
12
13use super::forward_select::SelectionSnapshot;
13use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
14use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
14use crate::agent_api::agent_label;
15use crate::agent_api::agent_label;
15use crate::agents::AgentRun;
16use crate::agents::AgentRun;
16use crate::app_state::AppState;
17use crate::app_state::AppState;
18use crate::forward_selection::block_reason;
17use crate::rows::{Delivery, MessageRow, PostRow, ReactionChip, RecordingCard};
19use crate::rows::{Delivery, MessageRow, PostRow, ReactionChip, RecordingCard};
18use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
20use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19use crate::translation::TranslationLine;
21use crate::translation::TranslationLine;
@@ -22,7 +24,7 @@ use crate::views::attachments::ImageActions;
22use crate::views::call_card::CallActions;
24use crate::views::call_card::CallActions;
23use crate::views::call_notice::RecapActions;
25use crate::views::call_notice::RecapActions;
24use crate::views::composer::Composer;
26use crate::views::composer::Composer;
25use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};
27use crate::views::message_row::{DeliveryActions, RowActions, RowSelect, SharedRowAction};
26use crate::views::post_card::{PostAction, PostActions};
28use crate::views::post_card::{PostAction, PostActions};
27use crate::views::reaction_proposal_pill::ReactionPill;
29use crate::views::reaction_proposal_pill::ReactionPill;
28use crate::views::toolbar_placement::TimelineBounds;
30use crate::views::toolbar_placement::TimelineBounds;
@@ -37,6 +39,7 @@ pub(super) struct RenderEnv {
37 pub timeline: TimelineBounds,
39 pub timeline: TimelineBounds,
38 pub agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
40 pub agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
39 pub reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
41 pub reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
42 pub forward_selection: Option<SelectionSnapshot>,
40}
43}
41
44
42fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
45fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
@@ -295,18 +298,24 @@ impl RenderEnv {
295 &message.key,
298 &message.key,
296 cx,
299 cx,
297 );
300 );
301 let select = self
302 .forward_selection
303 .as_ref()
304 .map(|snapshot| self.row_select(snapshot, message));
305 let selecting = select.is_some();
298 RowActions {
306 RowActions {
307 select,
299 bot,
308 bot,
300 delivery,
309 delivery,
301 reply,
310 reply: reply.filter(|_| !selecting),
302 hovered,
311 hovered: hovered.filter(|_| !selecting),
303 menu,
312 menu: menu.filter(|_| !selecting),
304 scheduled_menu,
313 scheduled_menu,
305 react,
314 react: react.filter(|_| !selecting),
306 reaction_controls,
315 reaction_controls,
307 add_reaction,
316 add_reaction: add_reaction.filter(|_| !selecting),
308 files,
317 files: files.filter(|_| !selecting),
309 open_image,
318 open_image: open_image.filter(|_| !selecting),
310 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
319 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
311 saved: self
320 saved: self
312 .app
321 .app
@@ -327,6 +336,17 @@ impl RenderEnv {
327 }
336 }
328 }
337 }
329
338
339 fn row_select(&self, snapshot: &SelectionSnapshot, message: &MessageRow) -> RowSelect {
340 let (app, key) = (self.app.clone(), message.key.clone());
341 RowSelect {
342 checked: snapshot.selection.contains(&message.key),
343 blocked: block_reason(message, &snapshot.selection, snapshot.image_count),
344 toggle: Rc::new(move |cx| {
345 app.update(cx, |state, cx| state.toggle_forward_selected(&key, cx))
346 }),
347 }
348 }
349
330 fn undo_delete_action(
350 fn undo_delete_action(
331 &self,
351 &self,
332 message: &MessageRow,
352 message: &MessageRow,
crates/app/src/views/forward_dialog.rs +99 −49
@@ -12,7 +12,7 @@ use super::switcher::{Candidate, candidate_avatar, clamp_highlight};
12 12 use super::widgets::{icon, symbol};
13 13 use crate::app_state::{AppState, Selection};
14 14 use crate::fuzzy;
15 use crate::message_actions::ForwardSource;
15 use crate::message_actions::{ForwardItem, ForwardSource};
16 16 use crate::notice::short_error;
17 17 use crate::runtime;
18 18 use crate::theme::{self, ElevatedSurface as _};
@@ -27,6 +27,13 @@ const BACKDROP_OPACITY: f32 = 0.55;
27 27 const ROW_HEIGHT: f32 = 40.;
28 28 const AVATAR_SIZE: f32 = 28.;
29 29 const PREVIEW_LINES: usize = 4;
30 const MULTI_PREVIEW_LINES: usize = 2;
31 const PREVIEW_GAP: f32 = 6.;
32 const PREVIEW_MAX_HEIGHT: f32 = 240.;
33 pub const FORWARD_CARD_TAG: &str = "forward-dialog";
34 pub const FORWARD_PREVIEW_TAG: &str = "forward-dialog/preview";
35 pub const DIALOG_TITLE: &str = "Forward this message";
36 pub const DIALOG_SUBTITLE: &str = "You can forward to any chat or channel.";
30 37 const CLOSE_SIZE: f32 = 28.;
31 38 const FIELD_HEIGHT: f32 = 36.;
32 39 const BUTTON_HEIGHT: f32 = 32.;
@@ -189,16 +196,12 @@ impl ForwardDialog {
189 196 };
190 197 self.sending = true;
191 198 self.error = None;
192 let source = self.source.clone();
199 let source_id = self.source.conversation_id.clone();
200 let message_ids = self.source.message_ids();
193 201 let target_id = target.selection.conversation_id().to_owned();
194 202 let receiver = runtime::spawn(async move {
195 203 engine
196 .forward_messages(
197 &source.conversation_id,
198 &target_id,
199 &[source.message_id],
200 &comment,
201 )
204 .forward_messages(&source_id, &target_id, &message_ids, &comment)
202 205 .await
203 206 });
204 207 cx.spawn(async move |this, cx| {
@@ -227,11 +230,22 @@ impl ForwardDialog {
227 230 .items_center()
228 231 .gap(px(SECTION_GAP))
229 232 .child(
230 div()
233 v_flex()
231 234 .flex_1()
232 .text_size(px(15.))
233 .font_weight(FontWeight::SEMIBOLD)
234 .child("Forward message"),
235 .min_w_0()
236 .gap(px(2.))
237 .child(
238 div()
239 .text_size(px(15.))
240 .font_weight(FontWeight::SEMIBOLD)
241 .child(DIALOG_TITLE),
242 )
243 .child(
244 div()
245 .text_size(px(12.))
246 .text_color(theme::text_muted())
247 .child(DIALOG_SUBTITLE),
248 ),
235 249 )
236 250 .child(
237 251 div()
@@ -386,48 +400,74 @@ impl ForwardDialog {
386 400 }
387 401 }
388 402
389 fn preview(&self) -> Div {
390 let text = match self.source.text.trim() {
391 "" => EMPTY_PREVIEW.to_owned(),
392 text => text.to_owned(),
393 };
403 fn preview(&self) -> Stateful<Div> {
404 let lines = preview_lines(self.source.messages.len());
394 405 v_flex()
406 .id("forward-preview")
407 .debug_selector(|| FORWARD_PREVIEW_TAG.into())
395 408 .w_full()
396 .px(px(10.))
397 .py(px(6.))
398 .gap(px(2.))
399 .border_l(px(3.))
400 .border_color(theme::accent())
401 .rounded_r(px(4.))
402 .bg(theme::quote_fill())
403 .child(
404 h_flex()
405 .gap(px(8.))
406 .items_baseline()
407 .child(
408 div()
409 .text_size(px(12.))
410 .font_weight(FontWeight::SEMIBOLD)
411 .text_color(theme::text_soft())
412 .child(self.source.author.clone()),
413 )
414 .child(
415 div()
416 .text_size(px(11.))
417 .text_color(theme::text_muted())
418 .child(self.source.time.clone()),
419 ),
420 )
421 .child(
422 div()
423 .line_clamp(PREVIEW_LINES)
424 .text_size(px(12.5))
425 .text_color(theme::text_muted())
426 .child(text),
409 .max_h(px(PREVIEW_MAX_HEIGHT))
410 .overflow_y_scroll()
411 .gap(px(PREVIEW_GAP))
412 .children(
413 self.source
414 .messages
415 .iter()
416 .map(|item| preview_quote(item, lines)),
427 417 )
428 418 }
429 419 }
430 420
421 pub fn preview_lines(message_count: usize) -> usize {
422 if message_count > 1 {
423 MULTI_PREVIEW_LINES
424 } else {
425 PREVIEW_LINES
426 }
427 }
428
429 fn preview_quote(item: &ForwardItem, lines: usize) -> Div {
430 let text = match item.text.trim() {
431 "" => EMPTY_PREVIEW.to_owned(),
432 text => text.to_owned(),
433 };
434 v_flex()
435 .w_full()
436 .flex_none()
437 .px(px(10.))
438 .py(px(6.))
439 .gap(px(2.))
440 .border_l(px(3.))
441 .border_color(theme::accent())
442 .rounded_r(px(4.))
443 .bg(theme::quote_fill())
444 .child(
445 h_flex()
446 .gap(px(8.))
447 .items_baseline()
448 .child(
449 div()
450 .text_size(px(12.))
451 .font_weight(FontWeight::SEMIBOLD)
452 .text_color(theme::text_soft())
453 .child(item.author.clone()),
454 )
455 .child(
456 div()
457 .text_size(px(11.))
458 .text_color(theme::text_muted())
459 .child(item.time.clone()),
460 ),
461 )
462 .child(
463 div()
464 .line_clamp(lines)
465 .text_size(px(12.5))
466 .text_color(theme::text_muted())
467 .child(text),
468 )
469 }
470
431 471 impl Render for ForwardDialog {
432 472 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
433 473 let enabled = can_forward(self.target.as_ref(), self.sending);
@@ -454,6 +494,7 @@ impl Render for ForwardDialog {
454 494 .child(
455 495 v_flex()
456 496 .id("forward-card")
497 .debug_selector(|| FORWARD_CARD_TAG.into())
457 498 .w(px(CARD_WIDTH))
458 499 .max_w(relative(1.))
459 500 .max_h(relative(1.))
@@ -497,7 +538,10 @@ impl Render for ForwardDialog {
497 538
498 539 #[cfg(test)]
499 540 mod tests {
500 use super::{MAX_RESULTS, can_forward, visible_candidates};
541 use super::{
542 MAX_RESULTS, MULTI_PREVIEW_LINES, PREVIEW_LINES, can_forward, preview_lines,
543 visible_candidates,
544 };
501 545 use crate::app_state::Selection;
502 546 use crate::views::switcher::{Candidate, CandidateAvatar};
503 547
@@ -553,4 +597,10 @@ mod tests {
553 597 assert!(can_forward(Some(target), false));
554 598 assert!(!can_forward(Some(target), true));
555 599 }
600
601 #[test]
602 fn several_forwarded_messages_get_shorter_previews() {
603 assert_eq!(preview_lines(1), PREVIEW_LINES);
604 assert_eq!(preview_lines(5), MULTI_PREVIEW_LINES);
605 }
556 606 }
@@ -12,7 +12,7 @@ use super::switcher::{Candidate, candidate_avatar, clamp_highlight};
12use super::widgets::{icon, symbol};
12use super::widgets::{icon, symbol};
13use crate::app_state::{AppState, Selection};
13use crate::app_state::{AppState, Selection};
14use crate::fuzzy;
14use crate::fuzzy;
15use crate::message_actions::ForwardSource;
15use crate::message_actions::{ForwardItem, ForwardSource};
16use crate::notice::short_error;
16use crate::notice::short_error;
17use crate::runtime;
17use crate::runtime;
18use crate::theme::{self, ElevatedSurface as _};
18use crate::theme::{self, ElevatedSurface as _};
@@ -27,6 +27,13 @@ const BACKDROP_OPACITY: f32 = 0.55;
27const ROW_HEIGHT: f32 = 40.;
27const ROW_HEIGHT: f32 = 40.;
28const AVATAR_SIZE: f32 = 28.;
28const AVATAR_SIZE: f32 = 28.;
29const PREVIEW_LINES: usize = 4;
29const PREVIEW_LINES: usize = 4;
30const MULTI_PREVIEW_LINES: usize = 2;
31const PREVIEW_GAP: f32 = 6.;
32const PREVIEW_MAX_HEIGHT: f32 = 240.;
33pub const FORWARD_CARD_TAG: &str = "forward-dialog";
34pub const FORWARD_PREVIEW_TAG: &str = "forward-dialog/preview";
35pub const DIALOG_TITLE: &str = "Forward this message";
36pub const DIALOG_SUBTITLE: &str = "You can forward to any chat or channel.";
30const CLOSE_SIZE: f32 = 28.;
37const CLOSE_SIZE: f32 = 28.;
31const FIELD_HEIGHT: f32 = 36.;
38const FIELD_HEIGHT: f32 = 36.;
32const BUTTON_HEIGHT: f32 = 32.;
39const BUTTON_HEIGHT: f32 = 32.;
@@ -189,16 +196,12 @@ impl ForwardDialog {
189 };
196 };
190 self.sending = true;
197 self.sending = true;
191 self.error = None;
198 self.error = None;
192 let source = self.source.clone();
199 let source_id = self.source.conversation_id.clone();
200 let message_ids = self.source.message_ids();
193 let target_id = target.selection.conversation_id().to_owned();
201 let target_id = target.selection.conversation_id().to_owned();
194 let receiver = runtime::spawn(async move {
202 let receiver = runtime::spawn(async move {
195 engine
203 engine
196 .forward_messages(
204 .forward_messages(&source_id, &target_id, &message_ids, &comment)
197 &source.conversation_id,
198 &target_id,
199 &[source.message_id],
200 &comment,
201 )
202 .await
205 .await
203 });
206 });
204 cx.spawn(async move |this, cx| {
207 cx.spawn(async move |this, cx| {
@@ -227,11 +230,22 @@ impl ForwardDialog {
227 .items_center()
230 .items_center()
228 .gap(px(SECTION_GAP))
231 .gap(px(SECTION_GAP))
229 .child(
232 .child(
230 div()
233 v_flex()
231 .flex_1()
234 .flex_1()
232 .text_size(px(15.))
235 .min_w_0()
233 .font_weight(FontWeight::SEMIBOLD)
236 .gap(px(2.))
234 .child("Forward message"),
237 .child(
238 div()
239 .text_size(px(15.))
240 .font_weight(FontWeight::SEMIBOLD)
241 .child(DIALOG_TITLE),
242 )
243 .child(
244 div()
245 .text_size(px(12.))
246 .text_color(theme::text_muted())
247 .child(DIALOG_SUBTITLE),
248 ),
235 )
249 )
236 .child(
250 .child(
237 div()
251 div()
@@ -386,48 +400,74 @@ impl ForwardDialog {
386 }
400 }
387 }
401 }
388
402
389 fn preview(&self) -> Div {
403 fn preview(&self) -> Stateful<Div> {
390 let text = match self.source.text.trim() {
404 let lines = preview_lines(self.source.messages.len());
391 "" => EMPTY_PREVIEW.to_owned(),
392 text => text.to_owned(),
393 };
394 v_flex()
405 v_flex()
406 .id("forward-preview")
407 .debug_selector(|| FORWARD_PREVIEW_TAG.into())
395 .w_full()
408 .w_full()
396 .px(px(10.))
409 .max_h(px(PREVIEW_MAX_HEIGHT))
397 .py(px(6.))
410 .overflow_y_scroll()
398 .gap(px(2.))
411 .gap(px(PREVIEW_GAP))
399 .border_l(px(3.))
412 .children(
400 .border_color(theme::accent())
413 self.source
401 .rounded_r(px(4.))
414 .messages
402 .bg(theme::quote_fill())
415 .iter()
403 .child(
416 .map(|item| preview_quote(item, lines)),
404 h_flex()
405 .gap(px(8.))
406 .items_baseline()
407 .child(
408 div()
409 .text_size(px(12.))
410 .font_weight(FontWeight::SEMIBOLD)
411 .text_color(theme::text_soft())
412 .child(self.source.author.clone()),
413 )
414 .child(
415 div()
416 .text_size(px(11.))
417 .text_color(theme::text_muted())
418 .child(self.source.time.clone()),
419 ),
420 )
421 .child(
422 div()
423 .line_clamp(PREVIEW_LINES)
424 .text_size(px(12.5))
425 .text_color(theme::text_muted())
426 .child(text),
427 )
417 )
428 }
418 }
429}
419}
430
420
421pub fn preview_lines(message_count: usize) -> usize {
422 if message_count > 1 {
423 MULTI_PREVIEW_LINES
424 } else {
425 PREVIEW_LINES
426 }
427}
428
429fn preview_quote(item: &ForwardItem, lines: usize) -> Div {
430 let text = match item.text.trim() {
431 "" => EMPTY_PREVIEW.to_owned(),
432 text => text.to_owned(),
433 };
434 v_flex()
435 .w_full()
436 .flex_none()
437 .px(px(10.))
438 .py(px(6.))
439 .gap(px(2.))
440 .border_l(px(3.))
441 .border_color(theme::accent())
442 .rounded_r(px(4.))
443 .bg(theme::quote_fill())
444 .child(
445 h_flex()
446 .gap(px(8.))
447 .items_baseline()
448 .child(
449 div()
450 .text_size(px(12.))
451 .font_weight(FontWeight::SEMIBOLD)
452 .text_color(theme::text_soft())
453 .child(item.author.clone()),
454 )
455 .child(
456 div()
457 .text_size(px(11.))
458 .text_color(theme::text_muted())
459 .child(item.time.clone()),
460 ),
461 )
462 .child(
463 div()
464 .line_clamp(lines)
465 .text_size(px(12.5))
466 .text_color(theme::text_muted())
467 .child(text),
468 )
469}
470
431impl Render for ForwardDialog {
471impl Render for ForwardDialog {
432 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
472 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
433 let enabled = can_forward(self.target.as_ref(), self.sending);
473 let enabled = can_forward(self.target.as_ref(), self.sending);
@@ -454,6 +494,7 @@ impl Render for ForwardDialog {
454 .child(
494 .child(
455 v_flex()
495 v_flex()
456 .id("forward-card")
496 .id("forward-card")
497 .debug_selector(|| FORWARD_CARD_TAG.into())
457 .w(px(CARD_WIDTH))
498 .w(px(CARD_WIDTH))
458 .max_w(relative(1.))
499 .max_w(relative(1.))
459 .max_h(relative(1.))
500 .max_h(relative(1.))
@@ -497,7 +538,10 @@ impl Render for ForwardDialog {
497
538
498#[cfg(test)]
539#[cfg(test)]
499mod tests {
540mod tests {
500 use super::{MAX_RESULTS, can_forward, visible_candidates};
541 use super::{
542 MAX_RESULTS, MULTI_PREVIEW_LINES, PREVIEW_LINES, can_forward, preview_lines,
543 visible_candidates,
544 };
501 use crate::app_state::Selection;
545 use crate::app_state::Selection;
502 use crate::views::switcher::{Candidate, CandidateAvatar};
546 use crate::views::switcher::{Candidate, CandidateAvatar};
503
547
@@ -553,4 +597,10 @@ mod tests {
553 assert!(can_forward(Some(target), false));
597 assert!(can_forward(Some(target), false));
554 assert!(!can_forward(Some(target), true));
598 assert!(!can_forward(Some(target), true));
555 }
599 }
600
601 #[test]
602 fn several_forwarded_messages_get_shorter_previews() {
603 assert_eq!(preview_lines(1), PREVIEW_LINES);
604 assert_eq!(preview_lines(5), MULTI_PREVIEW_LINES);
605 }
556}
606}
crates/app/src/views/message_actions.rs +29 −3
@@ -15,6 +15,7 @@ use gpui_kit::*;
15 15 use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
16 16 use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
17 17 use super::widgets::{icon, symbol};
18 use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
18 19 use crate::rows::reaction_glyph;
19 20 use crate::theme::{self, ElevatedSurface as _};
20 21
@@ -41,6 +42,7 @@ pub struct MessageMenu {
41 42 pub react: PickHandler,
42 43 pub reply: Option<Action>,
43 44 pub forward: Option<Action>,
45 pub forward_multiple: Option<Action>,
44 46 pub copy_link: Option<Action>,
45 47 pub copy: Action,
46 48 pub translate: Option<Action>,
@@ -184,6 +186,7 @@ pub fn add_reaction_pill(adder: ReactionAdder, height: f32, cx: &App) -> AnyElem
184 186 }
185 187
186 188 fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
189 let forward_multiple = menu.forward_multiple.clone();
187 190 let (
188 191 reply,
189 192 forward,
@@ -217,7 +220,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
217 220 .custom(bar_variant(cx))
218 221 .rounded(px(7.))
219 222 .size(px(BAR_BUTTON))
220 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
223 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
221 224 let item = |label: &'static str, glyph: IconName, action: Action| {
222 225 PopupMenuItem::new(label)
223 226 .icon(glyph)
@@ -227,8 +230,31 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
227 230 if let Some(reply) = reply.clone() {
228 231 popup = popup.item(item("Reply with quote", IconName::Reply, reply));
229 232 }
230 if let Some(forward) = forward.clone() {
231 popup = popup.item(item("Forward", IconName::Forward, forward));
233 match (forward.clone(), forward_multiple.clone()) {
234 (Some(forward), Some(forward_multiple)) => {
235 popup = popup.submenu_with_icon(
236 Some(IconName::Forward.into()),
237 FORWARD_LABEL,
238 window,
239 cx,
240 move |submenu, _, _| {
241 let (single, multiple) = (forward.clone(), forward_multiple.clone());
242 submenu
243 .item(
244 PopupMenuItem::new(THIS_MESSAGE_LABEL)
245 .on_click(move |_, window, cx| single(window, cx)),
246 )
247 .item(
248 PopupMenuItem::new(MULTIPLE_MESSAGES_LABEL)
249 .on_click(move |_, window, cx| multiple(window, cx)),
250 )
251 },
252 );
253 }
254 (Some(forward), None) => {
255 popup = popup.item(item(FORWARD_LABEL, IconName::Forward, forward));
256 }
257 (None, _) => {}
232 258 }
233 259 if let Some(copy_link) = copy_link.clone() {
234 260 popup = popup.item(item("Copy link", IconName::Link, copy_link));
@@ -15,6 +15,7 @@ use gpui_kit::*;
15use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
15use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
16use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
16use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
17use super::widgets::{icon, symbol};
17use super::widgets::{icon, symbol};
18use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
18use crate::rows::reaction_glyph;
19use crate::rows::reaction_glyph;
19use crate::theme::{self, ElevatedSurface as _};
20use crate::theme::{self, ElevatedSurface as _};
20
21
@@ -41,6 +42,7 @@ pub struct MessageMenu {
41 pub react: PickHandler,
42 pub react: PickHandler,
42 pub reply: Option<Action>,
43 pub reply: Option<Action>,
43 pub forward: Option<Action>,
44 pub forward: Option<Action>,
45 pub forward_multiple: Option<Action>,
44 pub copy_link: Option<Action>,
46 pub copy_link: Option<Action>,
45 pub copy: Action,
47 pub copy: Action,
46 pub translate: Option<Action>,
48 pub translate: Option<Action>,
@@ -184,6 +186,7 @@ pub fn add_reaction_pill(adder: ReactionAdder, height: f32, cx: &App) -> AnyElem
184}
186}
185
187
186fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
188fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
189 let forward_multiple = menu.forward_multiple.clone();
187 let (
190 let (
188 reply,
191 reply,
189 forward,
192 forward,
@@ -217,7 +220,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
217 .custom(bar_variant(cx))
220 .custom(bar_variant(cx))
218 .rounded(px(7.))
221 .rounded(px(7.))
219 .size(px(BAR_BUTTON))
222 .size(px(BAR_BUTTON))
220 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
223 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
221 let item = |label: &'static str, glyph: IconName, action: Action| {
224 let item = |label: &'static str, glyph: IconName, action: Action| {
222 PopupMenuItem::new(label)
225 PopupMenuItem::new(label)
223 .icon(glyph)
226 .icon(glyph)
@@ -227,8 +230,31 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
227 if let Some(reply) = reply.clone() {
230 if let Some(reply) = reply.clone() {
228 popup = popup.item(item("Reply with quote", IconName::Reply, reply));
231 popup = popup.item(item("Reply with quote", IconName::Reply, reply));
229 }
232 }
230 if let Some(forward) = forward.clone() {
233 match (forward.clone(), forward_multiple.clone()) {
231 popup = popup.item(item("Forward", IconName::Forward, forward));
234 (Some(forward), Some(forward_multiple)) => {
235 popup = popup.submenu_with_icon(
236 Some(IconName::Forward.into()),
237 FORWARD_LABEL,
238 window,
239 cx,
240 move |submenu, _, _| {
241 let (single, multiple) = (forward.clone(), forward_multiple.clone());
242 submenu
243 .item(
244 PopupMenuItem::new(THIS_MESSAGE_LABEL)
245 .on_click(move |_, window, cx| single(window, cx)),
246 )
247 .item(
248 PopupMenuItem::new(MULTIPLE_MESSAGES_LABEL)
249 .on_click(move |_, window, cx| multiple(window, cx)),
250 )
251 },
252 );
253 }
254 (Some(forward), None) => {
255 popup = popup.item(item(FORWARD_LABEL, IconName::Forward, forward));
256 }
257 (None, _) => {}
232 }
258 }
233 if let Some(copy_link) = copy_link.clone() {
259 if let Some(copy_link) = copy_link.clone() {
234 popup = popup.item(item("Copy link", IconName::Link, copy_link));
260 popup = popup.item(item("Copy link", IconName::Link, copy_link));
crates/app/src/views/message_row.rs +83 −1
@@ -72,6 +72,15 @@ const FIGURE_SPACE_WIDTH: f32 = 7.4;
72 72 const PULSE_PERIOD: Duration = Duration::from_millis(1600);
73 73 const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
74 74 const SKELETON_LINE_HEIGHT: f32 = 20.;
75 pub const SELECT_BOX_SIZE: f32 = 16.;
76 pub const SELECT_GAP: f32 = 12.;
77 const SELECT_CHECK_SIZE: f32 = 12.;
78 const SELECT_BOX_RADIUS: f32 = 4.;
79 const SELECT_BLOCKED_OPACITY: f32 = 0.4;
80 const SELECTED_TINT: f32 = 0.08;
81 pub fn select_box_selector(index: usize) -> String {
82 format!("forward-check/{index}")
83 }
75 84
76 85 pub struct DeliveryActions {
77 86 pub retry: RowAction,
@@ -79,7 +88,14 @@ pub struct DeliveryActions {
79 88 pub send_now: RowAction,
80 89 }
81 90
91 pub struct RowSelect {
92 pub checked: bool,
93 pub blocked: Option<&'static str>,
94 pub toggle: std::rc::Rc<dyn Fn(&mut App)>,
95 }
96
82 97 pub struct RowActions {
98 pub select: Option<RowSelect>,
83 99 pub bot: Option<BotIdentity>,
84 100 pub delivery: DeliveryActions,
85 101 pub reply: RowAction,
@@ -713,9 +729,20 @@ pub fn render_message_row(
713 729 cx: &App,
714 730 ) -> AnyElement {
715 731 if let Some(call) = &row.call {
716 return call_card_row(row, call, index, directory, actions.call);
732 let selecting = actions.select.is_some();
733 let card = call_card_row(row, call, index, directory, actions.call);
734 return if selecting {
735 div()
736 .w_full()
737 .pl(px(SELECT_BOX_SIZE + SELECT_GAP))
738 .child(card)
739 .into_any_element()
740 } else {
741 card
742 };
717 743 }
718 744 let RowActions {
745 select,
719 746 bot,
720 747 delivery,
721 748 reply,
@@ -768,6 +795,11 @@ pub fn render_message_row(
768 795 } else {
769 796 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
770 797 };
798 let checked = select.as_ref().is_some_and(|select| select.checked);
799 let body = match select {
800 Some(select) => selectable_body(select, index, body).into_any_element(),
801 None => body.into_any_element(),
802 };
771 803 container
772 804 .child(
773 805 div()
@@ -784,12 +816,62 @@ pub fn render_message_row(
784 816 .when(highlighted, |element| {
785 817 element.bg(theme::accent().opacity(0.2))
786 818 })
819 .when(checked && !highlighted, |element| {
820 element.bg(theme::accent().opacity(SELECTED_TINT))
821 })
787 822 .child(body),
788 823 ),
789 824 )
790 825 .into_any_element()
791 826 }
792 827
828 fn selectable_body(select: RowSelect, index: usize, body: impl IntoElement) -> Stateful<Div> {
829 let RowSelect {
830 checked,
831 blocked,
832 toggle,
833 } = select;
834 h_flex()
835 .id(ElementId::Name(format!("forward-select-{index}").into()))
836 .w_full()
837 .items_center()
838 .gap(px(SELECT_GAP))
839 .child(select_box(checked, blocked.is_some(), index))
840 .child(div().flex_1().min_w_0().child(body))
841 .map(|row| match blocked {
842 Some(reason) => row.tooltip(move |window, cx| {
843 gpui_kit::component::tooltip::Tooltip::new(reason).build(window, cx)
844 }),
845 None => row.cursor_pointer().on_click(move |_, _, cx| {
846 cx.stop_propagation();
847 toggle(cx)
848 }),
849 })
850 }
851
852 pub fn select_box(checked: bool, blocked: bool, index: usize) -> Div {
853 div()
854 .debug_selector(|| select_box_selector(index))
855 .size(px(SELECT_BOX_SIZE))
856 .flex_none()
857 .flex()
858 .items_center()
859 .justify_center()
860 .rounded(px(SELECT_BOX_RADIUS))
861 .map(|element| {
862 if checked {
863 element.bg(theme::accent()).child(icon(
864 IconName::Check,
865 SELECT_CHECK_SIZE,
866 theme::on_accent(),
867 ))
868 } else {
869 element.bg(theme::border_strong())
870 }
871 })
872 .when(blocked, |element| element.opacity(SELECT_BLOCKED_OPACITY))
873 }
874
793 875 #[cfg(test)]
794 876 mod density_tests {
795 877 use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
@@ -72,6 +72,15 @@ const FIGURE_SPACE_WIDTH: f32 = 7.4;
72const PULSE_PERIOD: Duration = Duration::from_millis(1600);
72const PULSE_PERIOD: Duration = Duration::from_millis(1600);
73const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
73const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
74const SKELETON_LINE_HEIGHT: f32 = 20.;
74const SKELETON_LINE_HEIGHT: f32 = 20.;
75pub const SELECT_BOX_SIZE: f32 = 16.;
76pub const SELECT_GAP: f32 = 12.;
77const SELECT_CHECK_SIZE: f32 = 12.;
78const SELECT_BOX_RADIUS: f32 = 4.;
79const SELECT_BLOCKED_OPACITY: f32 = 0.4;
80const SELECTED_TINT: f32 = 0.08;
81pub fn select_box_selector(index: usize) -> String {
82 format!("forward-check/{index}")
83}
75
84
76pub struct DeliveryActions {
85pub struct DeliveryActions {
77 pub retry: RowAction,
86 pub retry: RowAction,
@@ -79,7 +88,14 @@ pub struct DeliveryActions {
79 pub send_now: RowAction,
88 pub send_now: RowAction,
80}
89}
81
90
91pub struct RowSelect {
92 pub checked: bool,
93 pub blocked: Option<&'static str>,
94 pub toggle: std::rc::Rc<dyn Fn(&mut App)>,
95}
96
82pub struct RowActions {
97pub struct RowActions {
98 pub select: Option<RowSelect>,
83 pub bot: Option<BotIdentity>,
99 pub bot: Option<BotIdentity>,
84 pub delivery: DeliveryActions,
100 pub delivery: DeliveryActions,
85 pub reply: RowAction,
101 pub reply: RowAction,
@@ -713,9 +729,20 @@ pub fn render_message_row(
713 cx: &App,
729 cx: &App,
714) -> AnyElement {
730) -> AnyElement {
715 if let Some(call) = &row.call {
731 if let Some(call) = &row.call {
716 return call_card_row(row, call, index, directory, actions.call);
732 let selecting = actions.select.is_some();
733 let card = call_card_row(row, call, index, directory, actions.call);
734 return if selecting {
735 div()
736 .w_full()
737 .pl(px(SELECT_BOX_SIZE + SELECT_GAP))
738 .child(card)
739 .into_any_element()
740 } else {
741 card
742 };
717 }
743 }
718 let RowActions {
744 let RowActions {
745 select,
719 bot,
746 bot,
720 delivery,
747 delivery,
721 reply,
748 reply,
@@ -768,6 +795,11 @@ pub fn render_message_row(
768 } else {
795 } else {
769 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
796 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
770 };
797 };
798 let checked = select.as_ref().is_some_and(|select| select.checked);
799 let body = match select {
800 Some(select) => selectable_body(select, index, body).into_any_element(),
801 None => body.into_any_element(),
802 };
771 container
803 container
772 .child(
804 .child(
773 div()
805 div()
@@ -784,12 +816,62 @@ pub fn render_message_row(
784 .when(highlighted, |element| {
816 .when(highlighted, |element| {
785 element.bg(theme::accent().opacity(0.2))
817 element.bg(theme::accent().opacity(0.2))
786 })
818 })
819 .when(checked && !highlighted, |element| {
820 element.bg(theme::accent().opacity(SELECTED_TINT))
821 })
787 .child(body),
822 .child(body),
788 ),
823 ),
789 )
824 )
790 .into_any_element()
825 .into_any_element()
791}
826}
792
827
828fn selectable_body(select: RowSelect, index: usize, body: impl IntoElement) -> Stateful<Div> {
829 let RowSelect {
830 checked,
831 blocked,
832 toggle,
833 } = select;
834 h_flex()
835 .id(ElementId::Name(format!("forward-select-{index}").into()))
836 .w_full()
837 .items_center()
838 .gap(px(SELECT_GAP))
839 .child(select_box(checked, blocked.is_some(), index))
840 .child(div().flex_1().min_w_0().child(body))
841 .map(|row| match blocked {
842 Some(reason) => row.tooltip(move |window, cx| {
843 gpui_kit::component::tooltip::Tooltip::new(reason).build(window, cx)
844 }),
845 None => row.cursor_pointer().on_click(move |_, _, cx| {
846 cx.stop_propagation();
847 toggle(cx)
848 }),
849 })
850}
851
852pub fn select_box(checked: bool, blocked: bool, index: usize) -> Div {
853 div()
854 .debug_selector(|| select_box_selector(index))
855 .size(px(SELECT_BOX_SIZE))
856 .flex_none()
857 .flex()
858 .items_center()
859 .justify_center()
860 .rounded(px(SELECT_BOX_RADIUS))
861 .map(|element| {
862 if checked {
863 element.bg(theme::accent()).child(icon(
864 IconName::Check,
865 SELECT_CHECK_SIZE,
866 theme::on_accent(),
867 ))
868 } else {
869 element.bg(theme::border_strong())
870 }
871 })
872 .when(blocked, |element| element.opacity(SELECT_BLOCKED_OPACITY))
873}
874
793#[cfg(test)]
875#[cfg(test)]
794mod density_tests {
876mod density_tests {
795 use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
877 use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
crates/app/src/views/mod.rs +2 −0
@@ -57,6 +57,8 @@ pub mod new_chat;
57 57 pub mod notice_toast;
58 58 pub mod new_meeting_dialog;
59 59 pub mod pin_banner;
60 #[cfg(test)]
61 mod popup_tooltip_tests;
60 62 pub mod post_card;
61 63 pub mod prejoin_view;
62 64 pub mod profile_card;
@@ -57,6 +57,8 @@ pub mod new_chat;
57pub mod notice_toast;
57pub mod notice_toast;
58pub mod new_meeting_dialog;
58pub mod new_meeting_dialog;
59pub mod pin_banner;
59pub mod pin_banner;
60#[cfg(test)]
61mod popup_tooltip_tests;
60pub mod post_card;
62pub mod post_card;
61pub mod prejoin_view;
63pub mod prejoin_view;
62pub mod profile_card;
64pub mod profile_card;
crates/app/src/views/popup_tooltip_tests.rs added +192 −0
@@ -0,0 +1,192 @@
1 use std::{cell::Cell, rc::Rc, time::Duration};
2
3 use gpui_kit::component::button::Button;
4 use gpui_kit::component::tooltip::{PopupTriggerTooltip as _, TOOLTIP_DEBUG_SELECTOR};
5 use gpui_kit::prelude::FluentBuilder as _;
6 use gpui_kit::{
7 AppContext as _, Context, InteractiveElement as _, IntoElement, Modifiers, ParentElement as _,
8 Render, StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext,
9 Window, div, point, px,
10 };
11
12 const TOOLTIP_TAG: &str = "probe-tooltip";
13 const POPUP_TAG: &str = "probe-popup";
14 const PAST_SHOW_DELAY: Duration = Duration::from_millis(600);
15
16 struct Probe;
17
18 impl Render for Probe {
19 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
20 div()
21 .debug_selector(|| TOOLTIP_TAG.into())
22 .size(px(40.))
23 .child("tip")
24 }
25 }
26
27 struct Trigger {
28 popup_open: bool,
29 builds: Rc<Cell<usize>>,
30 }
31
32 impl Render for Trigger {
33 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
34 let builds = self.builds.clone();
35 div()
36 .size_full()
37 .child(
38 div()
39 .id("trigger")
40 .size(px(40.))
41 .popup_trigger_tooltip(self.popup_open, move |_, cx| {
42 builds.set(builds.get() + 1);
43 cx.new(|_| Probe).into()
44 })
45 .on_click(cx.listener(|this, _, _, cx| {
46 this.popup_open = !this.popup_open;
47 cx.notify();
48 })),
49 )
50 .when(self.popup_open, |root| {
51 root.child(
52 div()
53 .debug_selector(|| POPUP_TAG.into())
54 .mt(px(8.))
55 .size(px(80.))
56 .child("menu"),
57 )
58 })
59 }
60 }
61
62 fn settle(cx: &mut VisualTestContext) {
63 cx.executor().advance_clock(PAST_SHOW_DELAY);
64 cx.run_until_parked();
65 cx.update(|window, cx| window.draw(cx).clear(cx));
66 }
67
68 #[gpui_kit::test]
69 fn the_tooltip_hides_on_click_and_stays_hidden_while_its_popup_is_open(cx: &mut TestAppContext) {
70 let builds = Rc::new(Cell::new(0));
71 let (_, cx) = cx.add_window_view({
72 let builds = builds.clone();
73 move |_, _| Trigger {
74 popup_open: false,
75 builds,
76 }
77 });
78 cx.update(|window, cx| window.draw(cx).clear(cx));
79 cx.simulate_mouse_move(point(px(10.), px(10.)), None, Modifiers::default());
80 settle(cx);
81 assert_eq!(builds.get(), 1);
82 assert!(
83 cx.debug_bounds(TOOLTIP_TAG).is_some(),
84 "hover shows the tooltip"
85 );
86
87 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
88 settle(cx);
89 assert!(
90 cx.debug_bounds(POPUP_TAG).is_some(),
91 "the click opens the popup"
92 );
93 assert!(
94 cx.debug_bounds(TOOLTIP_TAG).is_none(),
95 "the click hides the tooltip"
96 );
97
98 for step in 1..4 {
99 let offset = 10. + step as f32;
100 cx.simulate_mouse_move(point(px(offset), px(offset)), None, Modifiers::default());
101 settle(cx);
102 }
103 assert_eq!(
104 builds.get(),
105 1,
106 "no tooltip is built while the popup is open"
107 );
108 assert!(cx.debug_bounds(TOOLTIP_TAG).is_none());
109
110 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
111 settle(cx);
112 cx.simulate_mouse_move(point(px(11.), px(11.)), None, Modifiers::default());
113 settle(cx);
114 assert!(cx.debug_bounds(POPUP_TAG).is_none());
115 assert!(
116 cx.debug_bounds(TOOLTIP_TAG).is_some(),
117 "after the popup closes the tooltip works again"
118 );
119 }
120
121 struct VanishingTrigger {
122 visible: bool,
123 }
124
125 impl Render for VanishingTrigger {
126 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
127 div().size_full().when(self.visible, |root| {
128 root.child(
129 Button::new("vanishing-trigger")
130 .label("Jump")
131 .tooltip("Jump to newest"),
132 )
133 })
134 }
135 }
136
137 #[gpui_kit::test]
138 fn a_managed_tooltip_closes_when_its_trigger_is_no_longer_rendered(cx: &mut TestAppContext) {
139 cx.update(gpui_kit::init);
140 let trigger = Rc::new(Cell::new(None));
141 let (_, cx) = cx.add_window_view({
142 let trigger = trigger.clone();
143 move |window, cx| {
144 let view = cx.new(|_| VanishingTrigger { visible: true });
145 trigger.set(Some(view.clone()));
146 gpui_kit::base::Root::new(view, window, cx)
147 }
148 });
149 let trigger = trigger.take().expect("trigger view");
150 cx.update(|window, cx| window.draw(cx).clear(cx));
151 cx.simulate_mouse_move(point(px(10.), px(10.)), None, Modifiers::default());
152 settle(cx);
153 assert!(
154 cx.debug_bounds(TOOLTIP_DEBUG_SELECTOR).is_some(),
155 "hover shows the tooltip"
156 );
157
158 cx.update(|_, cx| {
159 trigger.update(cx, |trigger, cx| {
160 trigger.visible = false;
161 cx.notify();
162 })
163 });
164 cx.update(|window, cx| window.draw(cx).clear(cx));
165 cx.update(|window, cx| window.simulate_next_frame(cx));
166 settle(cx);
167 assert!(
168 cx.debug_bounds(TOOLTIP_DEBUG_SELECTOR).is_none(),
169 "the tooltip closes with its trigger"
170 );
171 }
172
173 #[gpui_kit::test]
174 fn a_managed_tooltip_stays_while_its_trigger_is_rendered(cx: &mut TestAppContext) {
175 cx.update(gpui_kit::init);
176 let (_, cx) = cx.add_window_view(|window, cx| {
177 let view = cx.new(|_| VanishingTrigger { visible: true });
178 gpui_kit::base::Root::new(view, window, cx)
179 });
180 cx.update(|window, cx| window.draw(cx).clear(cx));
181 cx.simulate_mouse_move(point(px(10.), px(10.)), None, Modifiers::default());
182 settle(cx);
183 for _ in 0..3 {
184 cx.update(|window, cx| {
185 window.refresh();
186 window.draw(cx).clear(cx);
187 window.simulate_next_frame(cx);
188 });
189 settle(cx);
190 }
191 assert!(cx.debug_bounds(TOOLTIP_DEBUG_SELECTOR).is_some());
192 }
@@ -0,0 +1,192 @@
1use std::{cell::Cell, rc::Rc, time::Duration};
2
3use gpui_kit::component::button::Button;
4use gpui_kit::component::tooltip::{PopupTriggerTooltip as _, TOOLTIP_DEBUG_SELECTOR};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::{
7 AppContext as _, Context, InteractiveElement as _, IntoElement, Modifiers, ParentElement as _,
8 Render, StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext,
9 Window, div, point, px,
10};
11
12const TOOLTIP_TAG: &str = "probe-tooltip";
13const POPUP_TAG: &str = "probe-popup";
14const PAST_SHOW_DELAY: Duration = Duration::from_millis(600);
15
16struct Probe;
17
18impl Render for Probe {
19 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
20 div()
21 .debug_selector(|| TOOLTIP_TAG.into())
22 .size(px(40.))
23 .child("tip")
24 }
25}
26
27struct Trigger {
28 popup_open: bool,
29 builds: Rc<Cell<usize>>,
30}
31
32impl Render for Trigger {
33 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
34 let builds = self.builds.clone();
35 div()
36 .size_full()
37 .child(
38 div()
39 .id("trigger")
40 .size(px(40.))
41 .popup_trigger_tooltip(self.popup_open, move |_, cx| {
42 builds.set(builds.get() + 1);
43 cx.new(|_| Probe).into()
44 })
45 .on_click(cx.listener(|this, _, _, cx| {
46 this.popup_open = !this.popup_open;
47 cx.notify();
48 })),
49 )
50 .when(self.popup_open, |root| {
51 root.child(
52 div()
53 .debug_selector(|| POPUP_TAG.into())
54 .mt(px(8.))
55 .size(px(80.))
56 .child("menu"),
57 )
58 })
59 }
60}
61
62fn settle(cx: &mut VisualTestContext) {
63 cx.executor().advance_clock(PAST_SHOW_DELAY);
64 cx.run_until_parked();
65 cx.update(|window, cx| window.draw(cx).clear(cx));
66}
67
68#[gpui_kit::test]
69fn the_tooltip_hides_on_click_and_stays_hidden_while_its_popup_is_open(cx: &mut TestAppContext) {
70 let builds = Rc::new(Cell::new(0));
71 let (_, cx) = cx.add_window_view({
72 let builds = builds.clone();
73 move |_, _| Trigger {
74 popup_open: false,
75 builds,
76 }
77 });
78 cx.update(|window, cx| window.draw(cx).clear(cx));
79 cx.simulate_mouse_move(point(px(10.), px(10.)), None, Modifiers::default());
80 settle(cx);
81 assert_eq!(builds.get(), 1);
82 assert!(
83 cx.debug_bounds(TOOLTIP_TAG).is_some(),
84 "hover shows the tooltip"
85 );
86
87 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
88 settle(cx);
89 assert!(
90 cx.debug_bounds(POPUP_TAG).is_some(),
91 "the click opens the popup"
92 );
93 assert!(
94 cx.debug_bounds(TOOLTIP_TAG).is_none(),
95 "the click hides the tooltip"
96 );
97
98 for step in 1..4 {
99 let offset = 10. + step as f32;
100 cx.simulate_mouse_move(point(px(offset), px(offset)), None, Modifiers::default());
101 settle(cx);
102 }
103 assert_eq!(
104 builds.get(),
105 1,
106 "no tooltip is built while the popup is open"
107 );
108 assert!(cx.debug_bounds(TOOLTIP_TAG).is_none());
109
110 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
111 settle(cx);
112 cx.simulate_mouse_move(point(px(11.), px(11.)), None, Modifiers::default());
113 settle(cx);
114 assert!(cx.debug_bounds(POPUP_TAG).is_none());
115 assert!(
116 cx.debug_bounds(TOOLTIP_TAG).is_some(),
117 "after the popup closes the tooltip works again"
118 );
119}
120
121struct VanishingTrigger {
122 visible: bool,
123}
124
125impl Render for VanishingTrigger {
126 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
127 div().size_full().when(self.visible, |root| {
128 root.child(
129 Button::new("vanishing-trigger")
130 .label("Jump")
131 .tooltip("Jump to newest"),
132 )
133 })
134 }
135}
136
137#[gpui_kit::test]
138fn a_managed_tooltip_closes_when_its_trigger_is_no_longer_rendered(cx: &mut TestAppContext) {
139 cx.update(gpui_kit::init);
140 let trigger = Rc::new(Cell::new(None));
141 let (_, cx) = cx.add_window_view({
142 let trigger = trigger.clone();
143 move |window, cx| {
144 let view = cx.new(|_| VanishingTrigger { visible: true });
145 trigger.set(Some(view.clone()));
146 gpui_kit::base::Root::new(view, window, cx)
147 }
148 });
149 let trigger = trigger.take().expect("trigger view");
150 cx.update(|window, cx| window.draw(cx).clear(cx));
151 cx.simulate_mouse_move(point(px(10.), px(10.)), None, Modifiers::default());
152 settle(cx);
153 assert!(
154 cx.debug_bounds(TOOLTIP_DEBUG_SELECTOR).is_some(),
155 "hover shows the tooltip"
156 );
157
158 cx.update(|_, cx| {
159 trigger.update(cx, |trigger, cx| {
160 trigger.visible = false;
161 cx.notify();
162 })
163 });
164 cx.update(|window, cx| window.draw(cx).clear(cx));
165 cx.update(|window, cx| window.simulate_next_frame(cx));
166 settle(cx);
167 assert!(
168 cx.debug_bounds(TOOLTIP_DEBUG_SELECTOR).is_none(),
169 "the tooltip closes with its trigger"
170 );
171}
172
173#[gpui_kit::test]
174fn a_managed_tooltip_stays_while_its_trigger_is_rendered(cx: &mut TestAppContext) {
175 cx.update(gpui_kit::init);
176 let (_, cx) = cx.add_window_view(|window, cx| {
177 let view = cx.new(|_| VanishingTrigger { visible: true });
178 gpui_kit::base::Root::new(view, window, cx)
179 });
180 cx.update(|window, cx| window.draw(cx).clear(cx));
181 cx.simulate_mouse_move(point(px(10.), px(10.)), None, Modifiers::default());
182 settle(cx);
183 for _ in 0..3 {
184 cx.update(|window, cx| {
185 window.refresh();
186 window.draw(cx).clear(cx);
187 window.simulate_next_frame(cx);
188 });
189 settle(cx);
190 }
191 assert!(cx.debug_bounds(TOOLTIP_DEBUG_SELECTOR).is_some());
192}
crates/app/src/views/shell.rs +1 −0
@@ -764,6 +764,7 @@ impl AppShell {
764 764 state.select(target.clone(), cx)
765 765 });
766 766 this.state.update(cx, |state, cx| {
767 state.cancel_forward_selection(cx);
767 768 state.raise_notice(format!("Forwarded to {title}"), Some(open), cx)
768 769 });
769 770 }
@@ -764,6 +764,7 @@ impl AppShell {
764 state.select(target.clone(), cx)
764 state.select(target.clone(), cx)
765 });
765 });
766 this.state.update(cx, |state, cx| {
766 this.state.update(cx, |state, cx| {
767 state.cancel_forward_selection(cx);
767 state.raise_notice(format!("Forwarded to {title}"), Some(open), cx)
768 state.raise_notice(format!("Forwarded to {title}"), Some(open), cx)
768 });
769 });
769 }
770 }
vendor/gpui-base/PATCH.md +1 −0
@@ -34,6 +34,7 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
34 34 | `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |
35 35 | `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |
36 36 | `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |
37 | `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |
37 38
38 39 ## Limits
39 40
@@ -34,6 +34,7 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
34| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |
34| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |
35| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |
35| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |
36| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |
36| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |
37| `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |
37
38
38## Limits
39## Limits
39
40
vendor/gpui-base/src/tooltip.rs +60 −1
@@ -1,4 +1,7 @@
1 use std::{rc::Rc, time::Duration};
1 use std::{
2 rc::{Rc, Weak},
3 time::Duration,
4 };
2 5
3 6 use gpui::{
4 7 AnyElement, AnyView, App, Bounds, Context, Div, ElementId, InteractiveElement, IntoElement,
@@ -57,6 +60,7 @@ pub struct TooltipRequest {
57 60 build: TooltipBuilder,
58 61 trigger_bounds: Bounds<Pixels>,
59 62 preferred_placement: Option<Placement>,
63 trigger_alive: Option<Weak<()>>,
60 64 }
61 65
62 66 impl TooltipRequest {
@@ -68,6 +72,7 @@ impl TooltipRequest {
68 72 build: Rc::new(build),
69 73 trigger_bounds,
70 74 preferred_placement: None,
75 trigger_alive: None,
71 76 }
72 77 }
73 78
@@ -75,6 +80,19 @@ impl TooltipRequest {
75 80 self.preferred_placement = Some(placement);
76 81 self
77 82 }
83
84 /// The tooltip closes once `trigger_alive` can no longer be upgraded,
85 /// i.e. when the trigger stopped being rendered.
86 pub fn while_alive(mut self, trigger_alive: Weak<()>) -> Self {
87 self.trigger_alive = Some(trigger_alive);
88 self
89 }
90
91 fn trigger_gone(&self) -> bool {
92 self.trigger_alive
93 .as_ref()
94 .is_some_and(|alive| alive.upgrade().is_none())
95 }
78 96 }
79 97
80 98 /// Presentation transition requested by the Base tooltip lifecycle.
@@ -104,6 +122,7 @@ pub struct TooltipOverlay {
104 122 is_switching: bool,
105 123 show_task: Option<Task<()>>,
106 124 hide_task: Option<Task<()>>,
125 trigger_check_scheduled: bool,
107 126 renderer: TooltipRenderer,
108 127 }
109 128
@@ -119,6 +138,7 @@ impl TooltipOverlay {
119 138 is_switching: false,
120 139 show_task: None,
121 140 hide_task: None,
141 trigger_check_scheduled: false,
122 142 renderer: Rc::new(|view, _, _, _| div().child(view).into_any_element()),
123 143 }
124 144 }
@@ -218,8 +238,47 @@ impl Default for TooltipOverlay {
218 238 }
219 239 }
220 240
241 impl TooltipOverlay {
242 fn schedule_trigger_check(&mut self, window: &mut Window, cx: &mut Context<Self>) {
243 if self.trigger_check_scheduled {
244 return;
245 }
246 self.trigger_check_scheduled = true;
247 let overlay = cx.weak_entity();
248 // Element state of a trigger that was not rendered is dropped only after the frame.
249 window.on_next_frame(move |_, cx| {
250 let _ = overlay.update(cx, |overlay, cx| {
251 overlay.trigger_check_scheduled = false;
252 if overlay
253 .content
254 .as_ref()
255 .is_some_and(TooltipRequest::trigger_gone)
256 {
257 overlay.hide(cx);
258 }
259 });
260 });
261 }
262 }
263
221 264 impl Render for TooltipOverlay {
222 265 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
266 if self
267 .content
268 .as_ref()
269 .is_some_and(TooltipRequest::trigger_gone)
270 {
271 self.content = None;
272 self.previous_bounds = None;
273 self.is_switching = false;
274 }
275 if self
276 .content
277 .as_ref()
278 .is_some_and(|content| content.trigger_alive.is_some())
279 {
280 self.schedule_trigger_check(window, cx);
281 }
223 282 let Some(content) = self.content.as_ref() else {
224 283 return div().into_any_element();
225 284 };
@@ -1,4 +1,7 @@
1use std::{rc::Rc, time::Duration};
1use std::{
2 rc::{Rc, Weak},
3 time::Duration,
4};
2
5
3use gpui::{
6use gpui::{
4 AnyElement, AnyView, App, Bounds, Context, Div, ElementId, InteractiveElement, IntoElement,
7 AnyElement, AnyView, App, Bounds, Context, Div, ElementId, InteractiveElement, IntoElement,
@@ -57,6 +60,7 @@ pub struct TooltipRequest {
57 build: TooltipBuilder,
60 build: TooltipBuilder,
58 trigger_bounds: Bounds<Pixels>,
61 trigger_bounds: Bounds<Pixels>,
59 preferred_placement: Option<Placement>,
62 preferred_placement: Option<Placement>,
63 trigger_alive: Option<Weak<()>>,
60}
64}
61
65
62impl TooltipRequest {
66impl TooltipRequest {
@@ -68,6 +72,7 @@ impl TooltipRequest {
68 build: Rc::new(build),
72 build: Rc::new(build),
69 trigger_bounds,
73 trigger_bounds,
70 preferred_placement: None,
74 preferred_placement: None,
75 trigger_alive: None,
71 }
76 }
72 }
77 }
73
78
@@ -75,6 +80,19 @@ impl TooltipRequest {
75 self.preferred_placement = Some(placement);
80 self.preferred_placement = Some(placement);
76 self
81 self
77 }
82 }
83
84 /// The tooltip closes once `trigger_alive` can no longer be upgraded,
85 /// i.e. when the trigger stopped being rendered.
86 pub fn while_alive(mut self, trigger_alive: Weak<()>) -> Self {
87 self.trigger_alive = Some(trigger_alive);
88 self
89 }
90
91 fn trigger_gone(&self) -> bool {
92 self.trigger_alive
93 .as_ref()
94 .is_some_and(|alive| alive.upgrade().is_none())
95 }
78}
96}
79
97
80/// Presentation transition requested by the Base tooltip lifecycle.
98/// Presentation transition requested by the Base tooltip lifecycle.
@@ -104,6 +122,7 @@ pub struct TooltipOverlay {
104 is_switching: bool,
122 is_switching: bool,
105 show_task: Option<Task<()>>,
123 show_task: Option<Task<()>>,
106 hide_task: Option<Task<()>>,
124 hide_task: Option<Task<()>>,
125 trigger_check_scheduled: bool,
107 renderer: TooltipRenderer,
126 renderer: TooltipRenderer,
108}
127}
109
128
@@ -119,6 +138,7 @@ impl TooltipOverlay {
119 is_switching: false,
138 is_switching: false,
120 show_task: None,
139 show_task: None,
121 hide_task: None,
140 hide_task: None,
141 trigger_check_scheduled: false,
122 renderer: Rc::new(|view, _, _, _| div().child(view).into_any_element()),
142 renderer: Rc::new(|view, _, _, _| div().child(view).into_any_element()),
123 }
143 }
124 }
144 }
@@ -218,8 +238,47 @@ impl Default for TooltipOverlay {
218 }
238 }
219}
239}
220
240
241impl TooltipOverlay {
242 fn schedule_trigger_check(&mut self, window: &mut Window, cx: &mut Context<Self>) {
243 if self.trigger_check_scheduled {
244 return;
245 }
246 self.trigger_check_scheduled = true;
247 let overlay = cx.weak_entity();
248 // Element state of a trigger that was not rendered is dropped only after the frame.
249 window.on_next_frame(move |_, cx| {
250 let _ = overlay.update(cx, |overlay, cx| {
251 overlay.trigger_check_scheduled = false;
252 if overlay
253 .content
254 .as_ref()
255 .is_some_and(TooltipRequest::trigger_gone)
256 {
257 overlay.hide(cx);
258 }
259 });
260 });
261 }
262}
263
221impl Render for TooltipOverlay {
264impl Render for TooltipOverlay {
222 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
265 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
266 if self
267 .content
268 .as_ref()
269 .is_some_and(TooltipRequest::trigger_gone)
270 {
271 self.content = None;
272 self.previous_bounds = None;
273 self.is_switching = false;
274 }
275 if self
276 .content
277 .as_ref()
278 .is_some_and(|content| content.trigger_alive.is_some())
279 {
280 self.schedule_trigger_check(window, cx);
281 }
223 let Some(content) = self.content.as_ref() else {
282 let Some(content) = self.content.as_ref() else {
224 return div().into_any_element();
283 return div().into_any_element();
225 };
284 };
vendor/gpui-component/PATCHES.md +3 −0
@@ -11,3 +11,6 @@ Upstream: crates.io `gpui-component 0.7.1`. Wired in via `[patch.crates-io]` in
11 11 | `src/menu/popup_menu.rs` | separator `border_b(1px)` in `tokens.sidebar_accent` | 1px `POPUP_HOVER` line, full width |
12 12 | `src/tooltip.rs` | no `border_1`, `border_color`, `shadow_md` | tooltips match borderless popups |
13 13 | `src/button/button.rs` | pointer cursor on every interactive button, not only link/text | consistent with the app's own clickable elements |
14 | `src/tooltip.rs` | `PopupTriggerTooltip` (`popup_trigger_tooltip`, `popup_trigger_tooltip_text`): no tooltip while the element's popup is open | a tooltip never covers the menu its trigger opened, and does not come back while it is open |
15 | `src/button/button.rs` | no managed tooltip while the button is held `open` by its popover or dropdown menu | same, for Button triggers |
16 | `src/tooltip.rs` | managed tooltip requests carry a liveness token from the trigger's element state (`while_alive`); `TOOLTIP_DEBUG_SELECTOR` on `Tooltip` | a tooltip closes when its trigger is no longer rendered (e.g. "Jump to newest" after the button vanished); tests find tooltips |
@@ -11,3 +11,6 @@ Upstream: crates.io `gpui-component 0.7.1`. Wired in via `[patch.crates-io]` in
11| `src/menu/popup_menu.rs` | separator `border_b(1px)` in `tokens.sidebar_accent` | 1px `POPUP_HOVER` line, full width |
11| `src/menu/popup_menu.rs` | separator `border_b(1px)` in `tokens.sidebar_accent` | 1px `POPUP_HOVER` line, full width |
12| `src/tooltip.rs` | no `border_1`, `border_color`, `shadow_md` | tooltips match borderless popups |
12| `src/tooltip.rs` | no `border_1`, `border_color`, `shadow_md` | tooltips match borderless popups |
13| `src/button/button.rs` | pointer cursor on every interactive button, not only link/text | consistent with the app's own clickable elements |
13| `src/button/button.rs` | pointer cursor on every interactive button, not only link/text | consistent with the app's own clickable elements |
14| `src/tooltip.rs` | `PopupTriggerTooltip` (`popup_trigger_tooltip`, `popup_trigger_tooltip_text`): no tooltip while the element's popup is open | a tooltip never covers the menu its trigger opened, and does not come back while it is open |
15| `src/button/button.rs` | no managed tooltip while the button is held `open` by its popover or dropdown menu | same, for Button triggers |
16| `src/tooltip.rs` | managed tooltip requests carry a liveness token from the trigger's element state (`while_alive`); `TOOLTIP_DEBUG_SELECTOR` on `Tooltip` | a tooltip closes when its trigger is no longer rendered (e.g. "Jump to newest" after the button vanished); tests find tooltips |
vendor/gpui-component/src/button/button.rs +3 −1
@@ -852,7 +852,9 @@ impl RenderOnce for Button {
852 852 })
853 853 })
854 854 .map(|this| {
855 if let Some(builder) = self.tooltip_builder {
855 if self.open {
856 this
857 } else if let Some(builder) = self.tooltip_builder {
856 858 this.managed_tooltip_with_placement(tooltip_placement, move |window, cx| {
857 859 builder(window, cx)
858 860 })
@@ -852,7 +852,9 @@ impl RenderOnce for Button {
852 })
852 })
853 })
853 })
854 .map(|this| {
854 .map(|this| {
855 if let Some(builder) = self.tooltip_builder {
855 if self.open {
856 this
857 } else if let Some(builder) = self.tooltip_builder {
856 this.managed_tooltip_with_placement(tooltip_placement, move |window, cx| {
858 this.managed_tooltip_with_placement(tooltip_placement, move |window, cx| {
857 builder(window, cx)
859 builder(window, cx)
858 })
860 })
vendor/gpui-component/src/tooltip.rs +58 −7
@@ -1,10 +1,14 @@
1 1 use crate::root::WindowState;
2 use std::{cell::Cell, rc::Rc, time::Duration};
2 use std::{
3 cell::{Cell, RefCell},
4 rc::{Rc, Weak},
5 time::Duration,
6 };
3 7
4 8 use 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,
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,
8 12 };
9 13 use gpui_base::{
10 14 Tooltip as BaseTooltip, TooltipOverlay as BaseTooltipOverlay,
@@ -29,6 +33,8 @@ enum TooltipContext {
29 33 Element(Box<dyn Fn(&mut Window, &mut App) -> AnyElement>),
30 34 }
31 35
36 pub const TOOLTIP_DEBUG_SELECTOR: &str = "tooltip";
37
32 38 /// A Tooltip element that can display text or custom content,
33 39 /// with optional key binding information.
34 40 pub struct Tooltip {
@@ -106,7 +112,8 @@ impl Render for Tooltip {
106 112 }
107 113 };
108 114
109 div().child(
115 let tooltip = div().debug_selector(|| TOOLTIP_DEBUG_SELECTOR.into());
116 tooltip.child(
110 117 // Wrap in a child, to ensure the left margin is applied to the tooltip
111 118 BaseTooltip::new("tooltip-popup")
112 119 .h_flex()
@@ -141,6 +148,32 @@ impl Render for Tooltip {
141 148 }
142 149 }
143 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.
154 pub 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
175 impl<E: StatefulInteractiveElement + Sized> PopupTriggerTooltip for E {}
176
144 177 // ── Managed tooltip system ──────────────────────────────────────────────────
145 178
146 179 /// Duration of the slide-down enter animation.
@@ -250,9 +283,12 @@ pub(crate) trait ManagedTooltipExt:
250 283 let build_tooltip = Rc::new(build_tooltip);
251 284 let trigger_bounds_cell: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
252 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();
253 288
254 self.on_prepaint(move |bounds, _, _| {
289 self.on_prepaint(move |bounds, window, _| {
255 290 bounds_writer.set(bounds);
291 *alive_writer.borrow_mut() = trigger_alive_token(window);
256 292 })
257 293 .on_hover({
258 294 let trigger_bounds_cell = trigger_bounds_cell.clone();
@@ -261,11 +297,13 @@ pub(crate) trait ManagedTooltipExt:
261 297 if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
262 298 if *hovered {
263 299 let bounds = trigger_bounds_cell.get();
300 let trigger_alive = trigger_alive_cell.borrow().clone();
264 301 overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
265 302 let build = build_tooltip.clone();
266 303 let request = BaseTooltipRequest::new(bounds, move |window, cx| {
267 304 build(window, cx)
268 });
305 })
306 .while_alive(trigger_alive);
269 307 let request = match preferred_placement {
270 308 Some(placement) => request.placement(placement),
271 309 None => request,
@@ -291,3 +329,16 @@ pub(crate) trait ManagedTooltipExt:
291 329 }
292 330
293 331 impl<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.
334 fn 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 }
@@ -1,10 +1,14 @@
1use crate::root::WindowState;
1use crate::root::WindowState;
2use std::{cell::Cell, rc::Rc, time::Duration};
2use std::{
3 cell::{Cell, RefCell},
4 rc::{Rc, Weak},
5 time::Duration,
6};
3
7
4use gpui::{
8use gpui::{
5 Action, AnyElement, AnyView, App, AppContext, Bounds, Context, ElementId, IntoElement,
9 Action, AnyElement, AnyView, App, AppContext, Bounds, Context, ElementId, InteractiveElement,
6 MouseButton, ParentElement, Pixels, Render, SharedString, StatefulInteractiveElement,
10 IntoElement, MouseButton, ParentElement, Pixels, Render, SharedString,
7 StyleRefinement, Styled, Window, div, prelude::FluentBuilder, px,
11 StatefulInteractiveElement, StyleRefinement, Styled, Window, div, prelude::FluentBuilder, px,
8};
12};
9use gpui_base::{
13use gpui_base::{
10 Tooltip as BaseTooltip, TooltipOverlay as BaseTooltipOverlay,
14 Tooltip as BaseTooltip, TooltipOverlay as BaseTooltipOverlay,
@@ -29,6 +33,8 @@ enum TooltipContext {
29 Element(Box<dyn Fn(&mut Window, &mut App) -> AnyElement>),
33 Element(Box<dyn Fn(&mut Window, &mut App) -> AnyElement>),
30}
34}
31
35
36pub const TOOLTIP_DEBUG_SELECTOR: &str = "tooltip";
37
32/// A Tooltip element that can display text or custom content,
38/// A Tooltip element that can display text or custom content,
33/// with optional key binding information.
39/// with optional key binding information.
34pub struct Tooltip {
40pub struct Tooltip {
@@ -106,7 +112,8 @@ impl Render for Tooltip {
106 }
112 }
107 };
113 };
108
114
109 div().child(
115 let tooltip = div().debug_selector(|| TOOLTIP_DEBUG_SELECTOR.into());
116 tooltip.child(
110 // Wrap in a child, to ensure the left margin is applied to the tooltip
117 // Wrap in a child, to ensure the left margin is applied to the tooltip
111 BaseTooltip::new("tooltip-popup")
118 BaseTooltip::new("tooltip-popup")
112 .h_flex()
119 .h_flex()
@@ -141,6 +148,32 @@ impl Render for Tooltip {
141 }
148 }
142}
149}
143
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
144// ── Managed tooltip system ──────────────────────────────────────────────────
177// ── Managed tooltip system ──────────────────────────────────────────────────
145
178
146/// Duration of the slide-down enter animation.
179/// Duration of the slide-down enter animation.
@@ -250,9 +283,12 @@ pub(crate) trait ManagedTooltipExt:
250 let build_tooltip = Rc::new(build_tooltip);
283 let build_tooltip = Rc::new(build_tooltip);
251 let trigger_bounds_cell: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
284 let trigger_bounds_cell: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
252 let bounds_writer = trigger_bounds_cell.clone();
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();
253
288
254 self.on_prepaint(move |bounds, _, _| {
289 self.on_prepaint(move |bounds, window, _| {
255 bounds_writer.set(bounds);
290 bounds_writer.set(bounds);
291 *alive_writer.borrow_mut() = trigger_alive_token(window);
256 })
292 })
257 .on_hover({
293 .on_hover({
258 let trigger_bounds_cell = trigger_bounds_cell.clone();
294 let trigger_bounds_cell = trigger_bounds_cell.clone();
@@ -261,11 +297,13 @@ pub(crate) trait ManagedTooltipExt:
261 if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
297 if let Some(overlay) = WindowState::tooltip_overlay(window, cx) {
262 if *hovered {
298 if *hovered {
263 let bounds = trigger_bounds_cell.get();
299 let bounds = trigger_bounds_cell.get();
300 let trigger_alive = trigger_alive_cell.borrow().clone();
264 overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
301 overlay.update(cx, |o: &mut BaseTooltipOverlay, cx| {
265 let build = build_tooltip.clone();
302 let build = build_tooltip.clone();
266 let request = BaseTooltipRequest::new(bounds, move |window, cx| {
303 let request = BaseTooltipRequest::new(bounds, move |window, cx| {
267 build(window, cx)
304 build(window, cx)
268 });
305 })
306 .while_alive(trigger_alive);
269 let request = match preferred_placement {
307 let request = match preferred_placement {
270 Some(placement) => request.placement(placement),
308 Some(placement) => request.placement(placement),
271 None => request,
309 None => request,
@@ -291,3 +329,16 @@ pub(crate) trait ManagedTooltipExt:
291}
329}
292
330
293impl<E: StatefulInteractiveElement + crate::ElementExt> ManagedTooltipExt for E {}
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}