BlueGit

ict rusty-teams

feat(app): message hover bar with reactions, edit and delete

- Hover a message: 4 quick reactions, emoji picker with search, reply, and a More menu (reply with quote, copy text, edit, delete).
- Reaction chips toggle your own reaction on click.
- Edit your own message from the menu or with Up arrow in an empty composer. Esc cancels. Chat mentions are kept.
- Delete your own message directly, no confirmation.
- Demo mode applies reactions, edits and deletes locally.
- Selection: highlight and copy stop at the last character, not the padding reserved for the timestamp. Dragging into the bubble padding no longer selects the next messages.

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-07 · 7 weeks ago

Hash
dc16b78486818b39a6b79ccf1eaf4eb9467b0c65
Parent
4a4c85f3
11 files changed +1000 −58
Cargo.lock +1 −0
@@ -266,6 +266,7 @@ dependencies = [
266 266 "image",
267 267 "raw-window-handle",
268 268 "rodio",
269 "serde_json",
269 270 "session",
270 271 "store",
271 272 "teams-core",
@@ -266,6 +266,7 @@ dependencies = [
266 "image",
266 "image",
267 "raw-window-handle",
267 "raw-window-handle",
268 "rodio",
268 "rodio",
269 "serde_json",
269 "session",
270 "session",
270 "store",
271 "store",
271 "teams-core",
272 "teams-core",
ROADMAP.md +15 −16
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 52 %** (39 done, 7 partial, 35 missing of 81). Partial counts half.
5 **Parity: 55 %** (42 done, 5 partial, 34 missing of 81). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11 11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12 12 | [Chat list](#chat-list) | 55 % | 5 | 1 | 4 |
13 13 | [Reading](#reading) | 70 % | 10 | 1 | 4 |
14 | [Writing](#writing) | 46 % | 5 | 3 | 6 |
14 | [Writing](#writing) | 61 % | 8 | 1 | 5 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
17 17 | [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
@@ -24,16 +24,15 @@ Feature parity with the Microsoft Teams desktop client.
24 24
25 25 | # | Feature | Note |
26 26 |---|---|---|
27 | 1 | Message toolbar: react, edit, delete, Up-arrow edits the last own message | Backend is done |
28 | 2 | New chat: 1:1 and group with title | Backend is done |
29 | 3 | Attach a file, paste or drag an image | |
30 | 4 | Channel: new post with subject, post cards | |
31 | 5 | Sign in on Linux without Chrome on a debug port | |
32 | 6 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
33 | 7 | Emoji picker for reactions and the composer | |
34 | 8 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
35 | 9 | Typing indicator | |
36 | 10 | Unsent messages survive a restart | |
27 | 1 | New chat: 1:1 and group with title | Backend is done |
28 | 2 | Attach a file, paste or drag an image | |
29 | 3 | Channel: new post with subject, post cards | |
30 | 4 | Sign in on Linux without Chrome on a debug port | |
31 | 5 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
32 | 6 | Emoji picker in the composer | Reaction picker exists |
33 | 7 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
34 | 8 | Typing indicator | |
35 | 9 | Unsent messages survive a restart | |
37 36
38 37 ## Sign-in and app
39 38
@@ -90,10 +89,10 @@ Feature parity with the Microsoft Teams desktop client.
90 89 | Quote-reply (Alt+R) | Done | |
91 90 | @mentions with people search | Done | |
92 91 | Emoji by colon code, English and German aliases | Done | |
93 | Edit own message | Partial | Backend done, no UI |
94 | Delete own message | Partial | Backend done, no UI |
95 | React to a message | Partial | Backend done, no UI |
96 | Emoji picker | Missing | |
92 | Edit own message | Done | From the menu or Up arrow in an empty composer |
93 | Delete own message | Done | |
94 | React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
95 | Emoji picker | Partial | For reactions; composer still uses colon codes |
97 96 | Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
98 97 | Attach a file, paste or drag an image | Missing | |
99 98 | GIFs and stickers | Missing | |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 52 %** (39 done, 7 partial, 35 missing of 81). Partial counts half.
5**Parity: 55 %** (42 done, 5 partial, 34 missing of 81). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12| [Chat list](#chat-list) | 55 % | 5 | 1 | 4 |
12| [Chat list](#chat-list) | 55 % | 5 | 1 | 4 |
13| [Reading](#reading) | 70 % | 10 | 1 | 4 |
13| [Reading](#reading) | 70 % | 10 | 1 | 4 |
14| [Writing](#writing) | 46 % | 5 | 3 | 6 |
14| [Writing](#writing) | 61 % | 8 | 1 | 5 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
17| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
17| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
@@ -24,16 +24,15 @@ Feature parity with the Microsoft Teams desktop client.
24
24
25| # | Feature | Note |
25| # | Feature | Note |
26|---|---|---|
26|---|---|---|
27| 1 | Message toolbar: react, edit, delete, Up-arrow edits the last own message | Backend is done |
27| 1 | New chat: 1:1 and group with title | Backend is done |
28| 2 | New chat: 1:1 and group with title | Backend is done |
28| 2 | Attach a file, paste or drag an image | |
29| 3 | Attach a file, paste or drag an image | |
29| 3 | Channel: new post with subject, post cards | |
30| 4 | Channel: new post with subject, post cards | |
30| 4 | Sign in on Linux without Chrome on a debug port | |
31| 5 | Sign in on Linux without Chrome on a debug port | |
31| 5 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
32| 6 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
32| 6 | Emoji picker in the composer | Reaction picker exists |
33| 7 | Emoji picker for reactions and the composer | |
33| 7 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
34| 8 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
34| 8 | Typing indicator | |
35| 9 | Typing indicator | |
35| 9 | Unsent messages survive a restart | |
36| 10 | Unsent messages survive a restart | |
37
36
38## Sign-in and app
37## Sign-in and app
39
38
@@ -90,10 +89,10 @@ Feature parity with the Microsoft Teams desktop client.
90| Quote-reply (Alt+R) | Done | |
89| Quote-reply (Alt+R) | Done | |
91| @mentions with people search | Done | |
90| @mentions with people search | Done | |
92| Emoji by colon code, English and German aliases | Done | |
91| Emoji by colon code, English and German aliases | Done | |
93| Edit own message | Partial | Backend done, no UI |
92| Edit own message | Done | From the menu or Up arrow in an empty composer |
94| Delete own message | Partial | Backend done, no UI |
93| Delete own message | Done | |
95| React to a message | Partial | Backend done, no UI |
94| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
96| Emoji picker | Missing | |
95| Emoji picker | Partial | For reactions; composer still uses colon codes |
97| Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
96| Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
98| Attach a file, paste or drag an image | Missing | |
97| Attach a file, paste or drag an image | Missing | |
99| GIFs and stickers | Missing | |
98| GIFs and stickers | Missing | |
crates/app/Cargo.toml +1 −0
@@ -23,6 +23,7 @@ chrono.workspace = true
23 23 directories.workspace = true
24 24 gpui-kit.workspace = true
25 25 graph.workspace = true
26 serde_json.workspace = true
26 27 session.workspace = true
27 28 store.workspace = true
28 29 teams-core.workspace = true
@@ -23,6 +23,7 @@ chrono.workspace = true
23directories.workspace = true
23directories.workspace = true
24gpui-kit.workspace = true
24gpui-kit.workspace = true
25graph.workspace = true
25graph.workspace = true
26serde_json.workspace = true
26session.workspace = true
27session.workspace = true
27store.workspace = true
28store.workspace = true
28teams-core.workspace = true
29teams-core.workspace = true
crates/app/src/render/selectable.rs +42 −12
@@ -1,10 +1,21 @@
1 use std::cell::RefCell;
1 2 use std::ops::Range;
3 use std::rc::Rc;
2 4
3 5 use gpui_kit::base::{
4 6 TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, Theme,
5 7 };
6 8 use gpui_kit::*;
7 9
10 const TIME_ROOM: char = '\u{2007}';
11 const HIT_SLOP: f32 = 12.;
12
13 #[derive(Clone)]
14 pub struct Participant {
15 handle: TextSelectionHandle,
16 copied: Rc<RefCell<String>>,
17 }
18
8 19 /// Styled text that takes part in the window text selection, with clickable link ranges.
9 20 pub struct SelectableRichText {
10 21 id: ElementId,
@@ -84,7 +95,7 @@ impl IntoElement for SelectableRichText {
84 95 }
85 96
86 97 impl Element for SelectableRichText {
87 type RequestLayoutState = TextSelectionHandle;
98 type RequestLayoutState = Participant;
88 99 type PrepaintState = Hitbox;
89 100
90 101 fn id(&self) -> Option<ElementId> {
@@ -102,18 +113,23 @@ impl Element for SelectableRichText {
102 113 window: &mut Window,
103 114 cx: &mut App,
104 115 ) -> (LayoutId, Self::RequestLayoutState) {
105 let handle = window.with_element_state(
116 let participant = window.with_element_state(
106 117 global_id.expect("SelectableRichText has an element id"),
107 |retained: Option<TextSelectionHandle>, _| {
108 let handle =
109 retained.unwrap_or_else(|| TextSelectionHandle::new(self.text.clone(), cx));
110 (handle.clone(), handle)
118 |retained: Option<Participant>, _| {
119 let participant = retained.unwrap_or_else(|| {
120 let handle = TextSelectionHandle::new(self.text.clone(), cx);
121 let copied = Rc::new(RefCell::new(String::new()));
122 let source = copied.clone();
123 handle.copy_with(move |_| source.borrow().clone(), cx);
124 Participant { handle, copied }
125 });
126 (participant.clone(), participant)
111 127 },
112 128 );
113 129 let (layout_id, ()) = self
114 130 .styled_text
115 131 .request_layout(global_id, inspector_id, window, cx);
116 (layout_id, handle)
132 (layout_id, participant)
117 133 }
118 134
119 135 fn prepaint(
@@ -121,13 +137,19 @@ impl Element for SelectableRichText {
121 137 global_id: Option<&GlobalElementId>,
122 138 inspector_id: Option<&InspectorElementId>,
123 139 bounds: Bounds<Pixels>,
124 handle: &mut Self::RequestLayoutState,
140 participant: &mut Self::RequestLayoutState,
125 141 window: &mut Window,
126 142 cx: &mut App,
127 143 ) -> Self::PrepaintState {
144 let handle = &participant.handle;
128 145 self.styled_text
129 146 .prepaint(global_id, inspector_id, bounds, &mut (), window, cx);
130 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
147 let slop = Edges {
148 left: px(HIT_SLOP),
149 right: px(HIT_SLOP),
150 ..Default::default()
151 };
152 let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal);
131 153 let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)
132 154 .with_text_bounds(vec![bounds])
133 155 .with_rendered_element(handle, window, cx);
@@ -140,14 +162,14 @@ impl Element for SelectableRichText {
140 162 global_id: Option<&GlobalElementId>,
141 163 inspector_id: Option<&InspectorElementId>,
142 164 bounds: Bounds<Pixels>,
143 handle: &mut Self::RequestLayoutState,
165 participant: &mut Self::RequestLayoutState,
144 166 hitbox: &mut Self::PrepaintState,
145 167 window: &mut Window,
146 168 cx: &mut App,
147 169 ) {
148 170 let layout = self.styled_text.layout().clone();
149 171 let selected_before = TextSelection::selected_text(window, cx);
150 let projection = handle.update_runs(
172 let projection = participant.handle.update_runs(
151 173 &[TextSelectionRun::new(
152 174 self.text.clone(),
153 175 layout.clone(),
@@ -159,10 +181,17 @@ impl Element for SelectableRichText {
159 181 window.refresh();
160 182 }
161 183 let color = Theme::global(cx).tokens.colors.selection;
184 let content_end = self.text.trim_end_matches(TIME_ROOM).len();
185 let mut copied = String::new();
162 186 for range in projection.ranges().iter().flatten() {
187 let end_index = range.end.min(content_end);
188 if end_index <= range.start {
189 continue;
190 }
191 copied.push_str(&self.text[range.start..end_index]);
163 192 let (Some(start), Some(end)) = (
164 193 layout.position_for_index(range.start),
165 layout.position_for_index(range.end),
194 layout.position_for_index(end_index),
166 195 ) else {
167 196 continue;
168 197 };
@@ -170,6 +199,7 @@ impl Element for SelectableRichText {
170 199 window.paint_quad(fill(quad, color));
171 200 }
172 201 }
202 *participant.copied.borrow_mut() = copied;
173 203 self.styled_text.paint(
174 204 global_id,
175 205 inspector_id,
@@ -1,10 +1,21 @@
1use std::cell::RefCell;
1use std::ops::Range;
2use std::ops::Range;
3use std::rc::Rc;
2
4
3use gpui_kit::base::{
5use gpui_kit::base::{
4 TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, Theme,
6 TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, Theme,
5};
7};
6use gpui_kit::*;
8use gpui_kit::*;
7
9
10const TIME_ROOM: char = '\u{2007}';
11const HIT_SLOP: f32 = 12.;
12
13#[derive(Clone)]
14pub struct Participant {
15 handle: TextSelectionHandle,
16 copied: Rc<RefCell<String>>,
17}
18
8/// Styled text that takes part in the window text selection, with clickable link ranges.
19/// Styled text that takes part in the window text selection, with clickable link ranges.
9pub struct SelectableRichText {
20pub struct SelectableRichText {
10 id: ElementId,
21 id: ElementId,
@@ -84,7 +95,7 @@ impl IntoElement for SelectableRichText {
84}
95}
85
96
86impl Element for SelectableRichText {
97impl Element for SelectableRichText {
87 type RequestLayoutState = TextSelectionHandle;
98 type RequestLayoutState = Participant;
88 type PrepaintState = Hitbox;
99 type PrepaintState = Hitbox;
89
100
90 fn id(&self) -> Option<ElementId> {
101 fn id(&self) -> Option<ElementId> {
@@ -102,18 +113,23 @@ impl Element for SelectableRichText {
102 window: &mut Window,
113 window: &mut Window,
103 cx: &mut App,
114 cx: &mut App,
104 ) -> (LayoutId, Self::RequestLayoutState) {
115 ) -> (LayoutId, Self::RequestLayoutState) {
105 let handle = window.with_element_state(
116 let participant = window.with_element_state(
106 global_id.expect("SelectableRichText has an element id"),
117 global_id.expect("SelectableRichText has an element id"),
107 |retained: Option<TextSelectionHandle>, _| {
118 |retained: Option<Participant>, _| {
108 let handle =
119 let participant = retained.unwrap_or_else(|| {
109 retained.unwrap_or_else(|| TextSelectionHandle::new(self.text.clone(), cx));
120 let handle = TextSelectionHandle::new(self.text.clone(), cx);
110 (handle.clone(), handle)
121 let copied = Rc::new(RefCell::new(String::new()));
122 let source = copied.clone();
123 handle.copy_with(move |_| source.borrow().clone(), cx);
124 Participant { handle, copied }
125 });
126 (participant.clone(), participant)
111 },
127 },
112 );
128 );
113 let (layout_id, ()) = self
129 let (layout_id, ()) = self
114 .styled_text
130 .styled_text
115 .request_layout(global_id, inspector_id, window, cx);
131 .request_layout(global_id, inspector_id, window, cx);
116 (layout_id, handle)
132 (layout_id, participant)
117 }
133 }
118
134
119 fn prepaint(
135 fn prepaint(
@@ -121,13 +137,19 @@ impl Element for SelectableRichText {
121 global_id: Option<&GlobalElementId>,
137 global_id: Option<&GlobalElementId>,
122 inspector_id: Option<&InspectorElementId>,
138 inspector_id: Option<&InspectorElementId>,
123 bounds: Bounds<Pixels>,
139 bounds: Bounds<Pixels>,
124 handle: &mut Self::RequestLayoutState,
140 participant: &mut Self::RequestLayoutState,
125 window: &mut Window,
141 window: &mut Window,
126 cx: &mut App,
142 cx: &mut App,
127 ) -> Self::PrepaintState {
143 ) -> Self::PrepaintState {
144 let handle = &participant.handle;
128 self.styled_text
145 self.styled_text
129 .prepaint(global_id, inspector_id, bounds, &mut (), window, cx);
146 .prepaint(global_id, inspector_id, bounds, &mut (), window, cx);
130 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
147 let slop = Edges {
148 left: px(HIT_SLOP),
149 right: px(HIT_SLOP),
150 ..Default::default()
151 };
152 let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal);
131 let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)
153 let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)
132 .with_text_bounds(vec![bounds])
154 .with_text_bounds(vec![bounds])
133 .with_rendered_element(handle, window, cx);
155 .with_rendered_element(handle, window, cx);
@@ -140,14 +162,14 @@ impl Element for SelectableRichText {
140 global_id: Option<&GlobalElementId>,
162 global_id: Option<&GlobalElementId>,
141 inspector_id: Option<&InspectorElementId>,
163 inspector_id: Option<&InspectorElementId>,
142 bounds: Bounds<Pixels>,
164 bounds: Bounds<Pixels>,
143 handle: &mut Self::RequestLayoutState,
165 participant: &mut Self::RequestLayoutState,
144 hitbox: &mut Self::PrepaintState,
166 hitbox: &mut Self::PrepaintState,
145 window: &mut Window,
167 window: &mut Window,
146 cx: &mut App,
168 cx: &mut App,
147 ) {
169 ) {
148 let layout = self.styled_text.layout().clone();
170 let layout = self.styled_text.layout().clone();
149 let selected_before = TextSelection::selected_text(window, cx);
171 let selected_before = TextSelection::selected_text(window, cx);
150 let projection = handle.update_runs(
172 let projection = participant.handle.update_runs(
151 &[TextSelectionRun::new(
173 &[TextSelectionRun::new(
152 self.text.clone(),
174 self.text.clone(),
153 layout.clone(),
175 layout.clone(),
@@ -159,10 +181,17 @@ impl Element for SelectableRichText {
159 window.refresh();
181 window.refresh();
160 }
182 }
161 let color = Theme::global(cx).tokens.colors.selection;
183 let color = Theme::global(cx).tokens.colors.selection;
184 let content_end = self.text.trim_end_matches(TIME_ROOM).len();
185 let mut copied = String::new();
162 for range in projection.ranges().iter().flatten() {
186 for range in projection.ranges().iter().flatten() {
187 let end_index = range.end.min(content_end);
188 if end_index <= range.start {
189 continue;
190 }
191 copied.push_str(&self.text[range.start..end_index]);
163 let (Some(start), Some(end)) = (
192 let (Some(start), Some(end)) = (
164 layout.position_for_index(range.start),
193 layout.position_for_index(range.start),
165 layout.position_for_index(range.end),
194 layout.position_for_index(end_index),
166 ) else {
195 ) else {
167 continue;
196 continue;
168 };
197 };
@@ -170,6 +199,7 @@ impl Element for SelectableRichText {
170 window.paint_quad(fill(quad, color));
199 window.paint_quad(fill(quad, color));
171 }
200 }
172 }
201 }
202 *participant.copied.borrow_mut() = copied;
173 self.styled_text.paint(
203 self.styled_text.paint(
174 global_id,
204 global_id,
175 inspector_id,
205 inspector_id,
crates/app/src/rows.rs +35 −0
@@ -21,6 +21,7 @@ const CORNER_SERIES: f32 = 4.;
21 21
22 22 #[derive(Debug, Clone, PartialEq, Eq)]
23 23 pub struct ReactionChip {
24 pub reaction_type: String,
24 25 pub label: String,
25 26 pub count: usize,
26 27 pub mine: bool,
@@ -256,6 +257,15 @@ pub fn reaction_label(reaction_type: &str) -> String {
256 257 }
257 258 }
258 259
260 /// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
261 pub fn reaction_type_for(glyph: &str) -> String {
262 let bare = glyph.trim_end_matches('\u{FE0F}');
263 ["like", "heart", "laugh", "surprised", "sad", "angry"]
264 .into_iter()
265 .find(|name| reaction_label(name) == bare)
266 .map_or_else(|| bare.to_owned(), str::to_owned)
267 }
268
259 269 pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> Vec<ReactionChip> {
260 270 let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
261 271 let mut mine: BTreeMap<&str, bool> = BTreeMap::new();
@@ -273,6 +283,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> V
273 283 order
274 284 .into_iter()
275 285 .map(|reaction_type| ReactionChip {
286 reaction_type: reaction_type.to_owned(),
276 287 label: reaction_label(reaction_type),
277 288 count: counts[reaction_type],
278 289 mine: mine.contains_key(reaction_type),
@@ -282,6 +293,23 @@ pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> V
282 293
283 294 const REPLY_EXCERPT_CHARS: usize = 90;
284 295
296 pub fn message_text(record: &MessageRecord) -> String {
297 let own_spans: Vec<Span> = message_spans(record)
298 .into_iter()
299 .filter(|span| !matches!(span, Span::Quote(_)))
300 .collect();
301 strip_image_placeholders(layout_blocks(&own_spans))
302 .into_iter()
303 .filter_map(|block| match block {
304 Block::Paragraph(inline) => Some(inline.text),
305 Block::ListItem(inline) => Some(format!("- {}", inline.text)),
306 Block::Code(code) => Some(format!("```\n{code}\n```")),
307 Block::Quote(_) => None,
308 })
309 .collect::<Vec<_>>()
310 .join("\n")
311 }
312
285 313 pub fn reply_excerpt(record: &MessageRecord) -> String {
286 314 let own_spans: Vec<Span> = message_spans(record)
287 315 .into_iter()
@@ -563,6 +591,13 @@ mod tests {
563 591 }
564 592 }
565 593
594 #[test]
595 fn reaction_type_maps_classic_glyphs_to_names() {
596 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
597 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
598 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
599 }
600
566 601 #[test]
567 602 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
568 603 let mut text = record("a", None, 8, 6);
@@ -21,6 +21,7 @@ const CORNER_SERIES: f32 = 4.;
21
21
22#[derive(Debug, Clone, PartialEq, Eq)]
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ReactionChip {
23pub struct ReactionChip {
24 pub reaction_type: String,
24 pub label: String,
25 pub label: String,
25 pub count: usize,
26 pub count: usize,
26 pub mine: bool,
27 pub mine: bool,
@@ -256,6 +257,15 @@ pub fn reaction_label(reaction_type: &str) -> String {
256 }
257 }
257}
258}
258
259
260/// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
261pub fn reaction_type_for(glyph: &str) -> String {
262 let bare = glyph.trim_end_matches('\u{FE0F}');
263 ["like", "heart", "laugh", "surprised", "sad", "angry"]
264 .into_iter()
265 .find(|name| reaction_label(name) == bare)
266 .map_or_else(|| bare.to_owned(), str::to_owned)
267}
268
259pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> Vec<ReactionChip> {
269pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> Vec<ReactionChip> {
260 let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
270 let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
261 let mut mine: BTreeMap<&str, bool> = BTreeMap::new();
271 let mut mine: BTreeMap<&str, bool> = BTreeMap::new();
@@ -273,6 +283,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> V
273 order
283 order
274 .into_iter()
284 .into_iter()
275 .map(|reaction_type| ReactionChip {
285 .map(|reaction_type| ReactionChip {
286 reaction_type: reaction_type.to_owned(),
276 label: reaction_label(reaction_type),
287 label: reaction_label(reaction_type),
277 count: counts[reaction_type],
288 count: counts[reaction_type],
278 mine: mine.contains_key(reaction_type),
289 mine: mine.contains_key(reaction_type),
@@ -282,6 +293,23 @@ pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> V
282
293
283const REPLY_EXCERPT_CHARS: usize = 90;
294const REPLY_EXCERPT_CHARS: usize = 90;
284
295
296pub fn message_text(record: &MessageRecord) -> String {
297 let own_spans: Vec<Span> = message_spans(record)
298 .into_iter()
299 .filter(|span| !matches!(span, Span::Quote(_)))
300 .collect();
301 strip_image_placeholders(layout_blocks(&own_spans))
302 .into_iter()
303 .filter_map(|block| match block {
304 Block::Paragraph(inline) => Some(inline.text),
305 Block::ListItem(inline) => Some(format!("- {}", inline.text)),
306 Block::Code(code) => Some(format!("```\n{code}\n```")),
307 Block::Quote(_) => None,
308 })
309 .collect::<Vec<_>>()
310 .join("\n")
311}
312
285pub fn reply_excerpt(record: &MessageRecord) -> String {
313pub fn reply_excerpt(record: &MessageRecord) -> String {
286 let own_spans: Vec<Span> = message_spans(record)
314 let own_spans: Vec<Span> = message_spans(record)
287 .into_iter()
315 .into_iter()
@@ -563,6 +591,13 @@ mod tests {
563 }
591 }
564 }
592 }
565
593
594 #[test]
595 fn reaction_type_maps_classic_glyphs_to_names() {
596 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
597 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
598 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
599 }
600
566 #[test]
601 #[test]
567 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
602 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
568 let mut text = record("a", None, 8, 6);
603 let mut text = record("a", None, 8, 6);
crates/app/src/views/composer.rs +90 −1
@@ -39,15 +39,23 @@ pub struct ReplyPreview {
39 39 pub excerpt: String,
40 40 }
41 41
42 #[derive(Debug, Clone, PartialEq, Eq)]
43 pub struct EditPreview {
44 pub message_id: String,
45 pub excerpt: String,
46 }
47
42 48 #[derive(Debug, Clone, PartialEq, Eq)]
43 49 pub struct Outgoing {
44 50 pub text: String,
45 51 pub mentions: Vec<MentionInput>,
46 52 pub reply: Option<ReplyPreview>,
53 pub edit: Option<EditPreview>,
47 54 }
48 55
49 56 pub enum ComposerEvent {
50 57 Submit(Outgoing),
58 EditLast,
51 59 }
52 60
53 61 struct MentionPopup {
@@ -69,6 +77,7 @@ pub struct Composer {
69 77 input: Entity<TextareaState>,
70 78 conversation_id: Option<String>,
71 79 reply: Option<ReplyPreview>,
80 editing: Option<EditPreview>,
72 81 mention_inputs: HashMap<String, MentionInput>,
73 82 mention_counter: usize,
74 83 popup: Option<MentionPopup>,
@@ -160,6 +169,7 @@ impl Composer {
160 169 input,
161 170 conversation_id: None,
162 171 reply: None,
172 editing: None,
163 173 mention_inputs: HashMap::new(),
164 174 mention_counter: 0,
165 175 popup: None,
@@ -447,6 +457,10 @@ impl Composer {
447 457 if self.conversation_id.as_deref() != Some(conversation_id) {
448 458 self.conversation_id = Some(conversation_id.to_owned());
449 459 self.reply = None;
460 if self.editing.take().is_some() {
461 self.input
462 .update(cx, |state, cx| state.set_value("", window, cx));
463 }
450 464 self.mention_inputs.clear();
451 465 self.close_popup();
452 466 cx.notify();
@@ -455,9 +469,22 @@ impl Composer {
455 469
456 470 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
457 471 self.reply = reply;
472 if self.reply.is_some() {
473 self.editing = None;
474 }
458 475 cx.notify();
459 476 }
460 477
478 pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
479 self.restore(&draft, window, cx);
480 self.focus(window, cx);
481 }
482
483 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
484 self.editing = None;
485 self.set_text("", window, cx);
486 }
487
461 488 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
462 489 let state = self.input.read(cx);
463 490 let mut text = state.value().trim().to_owned();
@@ -479,6 +506,7 @@ impl Composer {
479 506 text,
480 507 mentions,
481 508 reply: self.reply.clone(),
509 edit: self.editing.clone(),
482 510 })
483 511 }
484 512
@@ -490,6 +518,7 @@ impl Composer {
490 518 .update(cx, |state, cx| state.set_value("", window, cx));
491 519 self.mention_inputs.clear();
492 520 self.reply = None;
521 self.editing = None;
493 522 self.close_popup();
494 523 cx.emit(ComposerEvent::Submit(outgoing));
495 524 cx.notify();
@@ -520,6 +549,7 @@ impl Composer {
520 549 state.set_selected_range(end..end, cx);
521 550 });
522 551 self.reply = outgoing.reply.clone();
552 self.editing = outgoing.edit.clone();
523 553 self.close_popup();
524 554 cx.notify();
525 555 }
@@ -658,6 +688,58 @@ impl Composer {
658 688 ))
659 689 }
660 690
691 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
692 let edit = self.editing.as_ref()?;
693 Some(
694 h_flex()
695 .w_full()
696 .mb(px(6.))
697 .gap(px(10.))
698 .items_center()
699 .pl(px(10.))
700 .pr(px(4.))
701 .py(px(6.))
702 .rounded(px(8.))
703 .bg(theme::surface())
704 .border_1()
705 .border_color(theme::border())
706 .child(icon(IconName::Pencil, 14., theme::accent_text()))
707 .child(
708 v_flex()
709 .flex_1()
710 .min_w_0()
711 .child(
712 div()
713 .truncate()
714 .text_size(px(12.))
715 .font_weight(FontWeight::SEMIBOLD)
716 .text_color(theme::accent_text())
717 .child("Editing message"),
718 )
719 .child(
720 div()
721 .truncate()
722 .text_size(px(12.))
723 .text_color(theme::text_muted())
724 .child(edit.excerpt.clone()),
725 ),
726 )
727 .child(
728 div()
729 .id("edit-close")
730 .size(px(24.))
731 .flex()
732 .items_center()
733 .justify_center()
734 .rounded(px(6.))
735 .cursor_pointer()
736 .hover(|button| button.bg(theme::row_hover()))
737 .child(icon(IconName::Close, 14., theme::text_muted()))
738 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
739 ),
740 )
741 }
742
661 743 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
662 744 let reply = self.reply.as_ref()?;
663 745 Some(
@@ -758,6 +840,9 @@ impl Render for Composer {
758 840 if this.popup_is_open() {
759 841 this.move_highlight(-1, cx);
760 842 cx.stop_propagation();
843 } else if this.editing.is_none() && this.is_empty(cx) {
844 cx.emit(ComposerEvent::EditLast);
845 cx.stop_propagation();
761 846 }
762 847 }))
763 848 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
@@ -783,7 +868,7 @@ impl Render for Composer {
783 868 cx.stop_propagation();
784 869 }
785 870 }))
786 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
871 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
787 872 if let Some(popup) = &this.emoji_popup {
788 873 this.emoji_dismissed_at = Some(popup.range.start);
789 874 }
@@ -791,9 +876,13 @@ impl Render for Composer {
791 876 this.close_popup();
792 877 cx.notify();
793 878 cx.stop_propagation();
879 } else if this.editing.is_some() {
880 this.cancel_edit(window, cx);
881 cx.stop_propagation();
794 882 }
795 883 }))
796 884 .children(self.render_reply_strip(cx))
885 .children(self.render_edit_strip(cx))
797 886 .child(
798 887 div()
799 888 .relative()
@@ -39,15 +39,23 @@ pub struct ReplyPreview {
39 pub excerpt: String,
39 pub excerpt: String,
40}
40}
41
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct EditPreview {
44 pub message_id: String,
45 pub excerpt: String,
46}
47
42#[derive(Debug, Clone, PartialEq, Eq)]
48#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Outgoing {
49pub struct Outgoing {
44 pub text: String,
50 pub text: String,
45 pub mentions: Vec<MentionInput>,
51 pub mentions: Vec<MentionInput>,
46 pub reply: Option<ReplyPreview>,
52 pub reply: Option<ReplyPreview>,
53 pub edit: Option<EditPreview>,
47}
54}
48
55
49pub enum ComposerEvent {
56pub enum ComposerEvent {
50 Submit(Outgoing),
57 Submit(Outgoing),
58 EditLast,
51}
59}
52
60
53struct MentionPopup {
61struct MentionPopup {
@@ -69,6 +77,7 @@ pub struct Composer {
69 input: Entity<TextareaState>,
77 input: Entity<TextareaState>,
70 conversation_id: Option<String>,
78 conversation_id: Option<String>,
71 reply: Option<ReplyPreview>,
79 reply: Option<ReplyPreview>,
80 editing: Option<EditPreview>,
72 mention_inputs: HashMap<String, MentionInput>,
81 mention_inputs: HashMap<String, MentionInput>,
73 mention_counter: usize,
82 mention_counter: usize,
74 popup: Option<MentionPopup>,
83 popup: Option<MentionPopup>,
@@ -160,6 +169,7 @@ impl Composer {
160 input,
169 input,
161 conversation_id: None,
170 conversation_id: None,
162 reply: None,
171 reply: None,
172 editing: None,
163 mention_inputs: HashMap::new(),
173 mention_inputs: HashMap::new(),
164 mention_counter: 0,
174 mention_counter: 0,
165 popup: None,
175 popup: None,
@@ -447,6 +457,10 @@ impl Composer {
447 if self.conversation_id.as_deref() != Some(conversation_id) {
457 if self.conversation_id.as_deref() != Some(conversation_id) {
448 self.conversation_id = Some(conversation_id.to_owned());
458 self.conversation_id = Some(conversation_id.to_owned());
449 self.reply = None;
459 self.reply = None;
460 if self.editing.take().is_some() {
461 self.input
462 .update(cx, |state, cx| state.set_value("", window, cx));
463 }
450 self.mention_inputs.clear();
464 self.mention_inputs.clear();
451 self.close_popup();
465 self.close_popup();
452 cx.notify();
466 cx.notify();
@@ -455,9 +469,22 @@ impl Composer {
455
469
456 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
470 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
457 self.reply = reply;
471 self.reply = reply;
472 if self.reply.is_some() {
473 self.editing = None;
474 }
458 cx.notify();
475 cx.notify();
459 }
476 }
460
477
478 pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
479 self.restore(&draft, window, cx);
480 self.focus(window, cx);
481 }
482
483 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
484 self.editing = None;
485 self.set_text("", window, cx);
486 }
487
461 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
488 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
462 let state = self.input.read(cx);
489 let state = self.input.read(cx);
463 let mut text = state.value().trim().to_owned();
490 let mut text = state.value().trim().to_owned();
@@ -479,6 +506,7 @@ impl Composer {
479 text,
506 text,
480 mentions,
507 mentions,
481 reply: self.reply.clone(),
508 reply: self.reply.clone(),
509 edit: self.editing.clone(),
482 })
510 })
483 }
511 }
484
512
@@ -490,6 +518,7 @@ impl Composer {
490 .update(cx, |state, cx| state.set_value("", window, cx));
518 .update(cx, |state, cx| state.set_value("", window, cx));
491 self.mention_inputs.clear();
519 self.mention_inputs.clear();
492 self.reply = None;
520 self.reply = None;
521 self.editing = None;
493 self.close_popup();
522 self.close_popup();
494 cx.emit(ComposerEvent::Submit(outgoing));
523 cx.emit(ComposerEvent::Submit(outgoing));
495 cx.notify();
524 cx.notify();
@@ -520,6 +549,7 @@ impl Composer {
520 state.set_selected_range(end..end, cx);
549 state.set_selected_range(end..end, cx);
521 });
550 });
522 self.reply = outgoing.reply.clone();
551 self.reply = outgoing.reply.clone();
552 self.editing = outgoing.edit.clone();
523 self.close_popup();
553 self.close_popup();
524 cx.notify();
554 cx.notify();
525 }
555 }
@@ -658,6 +688,58 @@ impl Composer {
658 ))
688 ))
659 }
689 }
660
690
691 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
692 let edit = self.editing.as_ref()?;
693 Some(
694 h_flex()
695 .w_full()
696 .mb(px(6.))
697 .gap(px(10.))
698 .items_center()
699 .pl(px(10.))
700 .pr(px(4.))
701 .py(px(6.))
702 .rounded(px(8.))
703 .bg(theme::surface())
704 .border_1()
705 .border_color(theme::border())
706 .child(icon(IconName::Pencil, 14., theme::accent_text()))
707 .child(
708 v_flex()
709 .flex_1()
710 .min_w_0()
711 .child(
712 div()
713 .truncate()
714 .text_size(px(12.))
715 .font_weight(FontWeight::SEMIBOLD)
716 .text_color(theme::accent_text())
717 .child("Editing message"),
718 )
719 .child(
720 div()
721 .truncate()
722 .text_size(px(12.))
723 .text_color(theme::text_muted())
724 .child(edit.excerpt.clone()),
725 ),
726 )
727 .child(
728 div()
729 .id("edit-close")
730 .size(px(24.))
731 .flex()
732 .items_center()
733 .justify_center()
734 .rounded(px(6.))
735 .cursor_pointer()
736 .hover(|button| button.bg(theme::row_hover()))
737 .child(icon(IconName::Close, 14., theme::text_muted()))
738 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
739 ),
740 )
741 }
742
661 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
743 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
662 let reply = self.reply.as_ref()?;
744 let reply = self.reply.as_ref()?;
663 Some(
745 Some(
@@ -758,6 +840,9 @@ impl Render for Composer {
758 if this.popup_is_open() {
840 if this.popup_is_open() {
759 this.move_highlight(-1, cx);
841 this.move_highlight(-1, cx);
760 cx.stop_propagation();
842 cx.stop_propagation();
843 } else if this.editing.is_none() && this.is_empty(cx) {
844 cx.emit(ComposerEvent::EditLast);
845 cx.stop_propagation();
761 }
846 }
762 }))
847 }))
763 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
848 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
@@ -783,7 +868,7 @@ impl Render for Composer {
783 cx.stop_propagation();
868 cx.stop_propagation();
784 }
869 }
785 }))
870 }))
786 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
871 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
787 if let Some(popup) = &this.emoji_popup {
872 if let Some(popup) = &this.emoji_popup {
788 this.emoji_dismissed_at = Some(popup.range.start);
873 this.emoji_dismissed_at = Some(popup.range.start);
789 }
874 }
@@ -791,9 +876,13 @@ impl Render for Composer {
791 this.close_popup();
876 this.close_popup();
792 cx.notify();
877 cx.notify();
793 cx.stop_propagation();
878 cx.stop_propagation();
879 } else if this.editing.is_some() {
880 this.cancel_edit(window, cx);
881 cx.stop_propagation();
794 }
882 }
795 }))
883 }))
796 .children(self.render_reply_strip(cx))
884 .children(self.render_reply_strip(cx))
885 .children(self.render_edit_strip(cx))
797 .child(
886 .child(
798 div()
887 div()
799 .relative()
888 .relative()
crates/app/src/views/conversation.rs +366 −11
@@ -14,22 +14,24 @@ use gpui_kit::component::{
14 14 use gpui_kit::prelude::FluentBuilder as _;
15 15 use gpui_kit::*;
16 16 use store::MessageRecord;
17 use teams_core::ImageRef;
17 use teams_core::{ImageRef, MentionInput};
18 18
19 19 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
20 use super::composer::{Composer, ComposerEvent, Outgoing, ReplyPreview};
20 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
21 use super::message_actions::{Action, MessageMenu};
21 22 use super::message_row::{RowActions, render_message_row, render_skeleton_row};
23 use super::reaction_picker::{PickHandler, ReactionPicker};
22 24 use super::widgets::icon;
23 25 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
24 26 use crate::data::{is_one_on_one, others};
27 use crate::read_state::{ReadTrigger, plan_read};
25 28 use crate::render::Block;
26 29 use crate::render::blocks::Inline;
27 30 use crate::rows::{
28 31 Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
29 changed_indices, diff_keys, flat_rows, placeholder_rows, reply_excerpt, thread_list_rows,
30 thread_rows, trailing_skeleton,
32 changed_indices, diff_keys, flat_rows, message_text, placeholder_rows, reaction_type_for,
33 reply_excerpt, thread_list_rows, thread_rows, trailing_skeleton,
31 34 };
32 use crate::read_state::{ReadTrigger, plan_read};
33 35 use crate::runtime;
34 36 use crate::sidebar_model::{AvatarSpec, Face};
35 37 use crate::theme;
@@ -52,6 +54,12 @@ const PROGRESS_BAR_WIDTH: f32 = 0.35;
52 54
53 55 actions!(teams, [ReplyToHovered]);
54 56
57 #[derive(Clone, Copy)]
58 enum HoverSlot {
59 Row,
60 Toolbar,
61 }
62
55 63 #[derive(Debug, Clone, PartialEq, Eq)]
56 64 enum ViewMode {
57 65 Flat,
@@ -101,6 +109,9 @@ pub struct ConversationView {
101 109 pending_counter: usize,
102 110 pending_outgoing: HashMap<String, Outgoing>,
103 111 hovered_message: Option<String>,
112 toolbar_hovered: Option<String>,
113 toolbar_pinned: Option<String>,
114 picker: Entity<ReactionPicker>,
104 115 highlighted_message: Option<String>,
105 116 notice: Option<String>,
106 117 sync_generation: u64,
@@ -123,6 +134,7 @@ impl ConversationView {
123 134 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
124 135 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
125 136 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
137 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
126 138 let subscriptions = vec![
127 139 cx.subscribe_in(&app, window, Self::on_app_event),
128 140 cx.subscribe_in(&composer, window, Self::on_composer_event),
@@ -138,6 +150,9 @@ impl ConversationView {
138 150 pending_counter: 0,
139 151 pending_outgoing: HashMap::new(),
140 152 hovered_message: None,
153 toolbar_hovered: None,
154 toolbar_pinned: None,
155 picker,
141 156 highlighted_message: None,
142 157 notice: None,
143 158 sync_generation: 0,
@@ -225,11 +240,18 @@ impl ConversationView {
225 240 window: &mut Window,
226 241 cx: &mut Context<Self>,
227 242 ) {
228 let ComposerEvent::Submit(outgoing) = event;
229 self.send(outgoing.clone(), window, cx);
243 match event {
244 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
245 self.send_edit(outgoing.clone(), window, cx)
246 }
247 ComposerEvent::Submit(outgoing) => self.send(outgoing.clone(), window, cx),
248 ComposerEvent::EditLast => self.edit_last_own(window, cx),
249 }
230 250 }
231 251
232 252 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
253 self.toolbar_hovered = None;
254 self.toolbar_pinned = None;
233 255 let title = selection_title(&self.app.read(cx).sidebar, &selection);
234 256 let mode = match selection {
235 257 Selection::Chat(_) => ViewMode::Flat,
@@ -1054,6 +1076,7 @@ impl ConversationView {
1054 1076 text,
1055 1077 mentions,
1056 1078 reply,
1079 ..
1057 1080 } = &sent;
1058 1081 match (&view_mode, reply) {
1059 1082 (_, Some(reply)) => {
@@ -1089,6 +1112,323 @@ impl ConversationView {
1089 1112 .detach();
1090 1113 }
1091 1114
1115 fn conversation_id(&self) -> Option<String> {
1116 self.current
1117 .as_ref()
1118 .map(|current| current.selection.conversation_id().to_owned())
1119 }
1120
1121 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
1122 let conversation_id = self.conversation_id()?;
1123 let my_user_id = self.row_context(cx).my_user_id?;
1124 self.app
1125 .read(cx)
1126 .store
1127 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1128 .ok()?
1129 .remove(message_id)
1130 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
1131 }
1132
1133 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
1134 let target = match slot {
1135 HoverSlot::Row => &mut self.hovered_message,
1136 HoverSlot::Toolbar => &mut self.toolbar_hovered,
1137 };
1138 if hovered {
1139 *target = Some(key.to_owned());
1140 } else if target.as_deref() == Some(key) {
1141 *target = None;
1142 }
1143 cx.notify();
1144 }
1145
1146 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
1147 if open {
1148 self.toolbar_pinned = Some(key.to_owned());
1149 } else if self.toolbar_pinned.as_deref() == Some(key) {
1150 self.toolbar_pinned = None;
1151 }
1152 cx.notify();
1153 }
1154
1155 fn toolbar_visible(&self, key: &str) -> bool {
1156 [
1157 &self.hovered_message,
1158 &self.toolbar_hovered,
1159 &self.toolbar_pinned,
1160 ]
1161 .iter()
1162 .any(|slot| slot.as_deref() == Some(key))
1163 }
1164
1165 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
1166 let Some(conversation_id) = self.conversation_id() else {
1167 return;
1168 };
1169 let reaction_type = reaction_type_for(glyph);
1170 let state = self.app.read(cx);
1171 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1172 let my_user_id = self.row_context(cx).my_user_id;
1173 let Some(mut record) = store
1174 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1175 .ok()
1176 .and_then(|mut found| found.remove(message_id))
1177 else {
1178 return;
1179 };
1180 let mut reactions = teams_core::reactions(&record);
1181 let mine = |reaction: &teams_core::ReactionInfo| {
1182 reaction.reaction_type == reaction_type
1183 && my_user_id.is_some()
1184 && reaction.user_id == my_user_id
1185 };
1186 let remove = reactions.iter().any(mine);
1187 if mode.demo {
1188 if remove {
1189 reactions.retain(|reaction| !mine(reaction));
1190 } else {
1191 reactions.push(teams_core::ReactionInfo {
1192 reaction_type: reaction_type.clone(),
1193 user_id: my_user_id.clone(),
1194 user_name: Some("You".to_owned()),
1195 });
1196 }
1197 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1198 let _ = store.upsert_messages(std::slice::from_ref(&record));
1199 self.rebuild(false, cx);
1200 return;
1201 }
1202 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1203 self.show_notice("Read-only mode: reaction not sent", cx);
1204 return;
1205 };
1206 let message_id = message_id.to_owned();
1207 let receiver = runtime::spawn(async move {
1208 if remove {
1209 engine
1210 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1211 .await
1212 } else {
1213 engine
1214 .set_reaction(&conversation_id, &message_id, &reaction_type)
1215 .await
1216 }
1217 });
1218 self.report_failure(receiver, "Reaction failed", cx);
1219 }
1220
1221 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1222 let Some(record) = self.own_record(message_id, cx) else {
1223 return;
1224 };
1225 let edit = EditPreview {
1226 message_id: record.message_id.clone(),
1227 excerpt: reply_excerpt(&record),
1228 };
1229 let in_chat = matches!(
1230 self.current.as_ref().map(|current| &current.selection),
1231 Some(Selection::Chat(_))
1232 );
1233 let mentions = if in_chat {
1234 teams_core::mentions(&record)
1235 .into_iter()
1236 .filter_map(|mention| {
1237 let user_id = mention.user_id?;
1238 Some(MentionInput::user(&user_id, &mention.name))
1239 })
1240 .collect()
1241 } else {
1242 Vec::new()
1243 };
1244 let draft = Outgoing {
1245 text: message_text(&record),
1246 mentions,
1247 reply: None,
1248 edit: Some(edit),
1249 };
1250 self.composer
1251 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
1252 }
1253
1254 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1255 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
1256 Row::Message(message)
1257 if message.own
1258 && !message.deleted
1259 && !message.key.starts_with(PENDING_KEY_PREFIX) =>
1260 {
1261 Some(message.key.clone())
1262 }
1263 _ => None,
1264 });
1265 if let Some(key) = key {
1266 self.begin_edit(&key, window, cx);
1267 }
1268 }
1269
1270 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1271 let Some(edit) = outgoing.edit.clone() else {
1272 return;
1273 };
1274 let Some(conversation_id) = self.conversation_id() else {
1275 return;
1276 };
1277 let state = self.app.read(cx);
1278 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1279 if mode.demo {
1280 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
1281 record.body_html = teams_core::markdown_to_html(&outgoing.text);
1282 record.edited_at = Some(Utc::now());
1283 let _ = store.upsert_messages(std::slice::from_ref(&record));
1284 self.rebuild(false, cx);
1285 }
1286 return;
1287 }
1288 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1289 self.notice = Some("Read-only mode: edit not saved".to_owned());
1290 self.composer
1291 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1292 cx.notify();
1293 return;
1294 };
1295 let sent = outgoing.clone();
1296 let receiver = runtime::spawn(async move {
1297 engine
1298 .edit_message_with_mentions(
1299 &conversation_id,
1300 &edit.message_id,
1301 &sent.text,
1302 &sent.mentions,
1303 )
1304 .await
1305 });
1306 cx.spawn_in(window, async move |this, cx| {
1307 let failed = !matches!(receiver.await, Ok(Ok(())));
1308 this.update_in(cx, |this, window, cx| {
1309 if failed {
1310 this.notice = Some("Edit failed: your text is back in the composer".to_owned());
1311 this.composer
1312 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1313 cx.notify();
1314 }
1315 })
1316 .ok();
1317 })
1318 .detach();
1319 }
1320
1321 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
1322 let Some(mut record) = self.own_record(message_id, cx) else {
1323 return;
1324 };
1325 let state = self.app.read(cx);
1326 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1327 if mode.demo {
1328 record.deleted = true;
1329 let _ = store.upsert_messages(std::slice::from_ref(&record));
1330 self.rebuild(false, cx);
1331 return;
1332 }
1333 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1334 self.show_notice("Read-only mode: message not deleted", cx);
1335 return;
1336 };
1337 let conversation_id = record.conversation_id.clone();
1338 let receiver = runtime::spawn(async move {
1339 engine
1340 .soft_delete_message(&conversation_id, &record.message_id)
1341 .await
1342 });
1343 self.report_failure(receiver, "Delete failed", cx);
1344 }
1345
1346 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
1347 let Some(conversation_id) = self.conversation_id() else {
1348 return;
1349 };
1350 let record = self
1351 .app
1352 .read(cx)
1353 .store
1354 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1355 .ok()
1356 .and_then(|mut found| found.remove(message_id));
1357 if let Some(record) = record {
1358 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
1359 }
1360 }
1361
1362 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
1363 self.notice = Some(message.to_owned());
1364 cx.notify();
1365 }
1366
1367 fn report_failure(
1368 &mut self,
1369 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
1370 label: &'static str,
1371 cx: &mut Context<Self>,
1372 ) {
1373 cx.spawn(async move |this, cx| {
1374 let error = match receiver.await {
1375 Ok(Ok(())) => return,
1376 Ok(Err(error)) => short_error(&error),
1377 Err(_) => "cancelled".to_owned(),
1378 };
1379 this.update(cx, |this, cx| {
1380 this.show_notice(&format!("{label}: {error}"), cx)
1381 })
1382 .ok();
1383 })
1384 .detach();
1385 }
1386
1387 fn message_menu(&self, key: &str, own: bool, view: WeakEntity<Self>) -> MessageMenu {
1388 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
1389 let (view, key) = (view.clone(), key.to_owned());
1390 Rc::new(move |window, cx| {
1391 view.update(cx, |this, cx| run(this, &key, window, cx)).ok();
1392 })
1393 };
1394 let react: PickHandler = {
1395 let (view, key) = (view.clone(), key.to_owned());
1396 Rc::new(move |glyph, _, cx| {
1397 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
1398 .ok();
1399 })
1400 };
1401 let hover = {
1402 let (view, key) = (view.clone(), key.to_owned());
1403 Rc::new(move |hovered: bool, cx: &mut App| {
1404 view.update(cx, |this, cx| {
1405 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
1406 })
1407 .ok();
1408 })
1409 };
1410 let pin = {
1411 let (view, key) = (view.clone(), key.to_owned());
1412 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
1413 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
1414 .ok();
1415 })
1416 };
1417 MessageMenu {
1418 key: key.to_owned(),
1419 react,
1420 reply: Some(action(|this, key, window, cx| {
1421 this.begin_reply(key, window, cx)
1422 })),
1423 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
1424 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
1425 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
1426 pin,
1427 hover,
1428 picker: self.picker.clone(),
1429 }
1430 }
1431
1092 1432 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
1093 1433 let Some(outgoing) = self.pending_outgoing.remove(key) else {
1094 1434 return;
@@ -1324,13 +1664,26 @@ impl Render for ConversationView {
1324 1664 let is_real = !message.key.starts_with(PENDING_KEY_PREFIX);
1325 1665 let hovered = is_real.then(|| {
1326 1666 let (view, key) = (view.clone(), message.key.clone());
1327 Box::new(move |cx: &mut App| {
1328 view.update(cx, |this, _| {
1329 this.hovered_message = Some(key.clone());
1667 Rc::new(move |hovered: bool, cx: &mut App| {
1668 view.update(cx, |this, cx| {
1669 this.set_hover(HoverSlot::Row, &key, hovered, cx)
1330 1670 })
1331 1671 .ok();
1332 }) as Box<dyn Fn(&mut App)>
1672 }) as Rc<dyn Fn(bool, &mut App)>
1333 1673 });
1674 let actionable = is_real && !message.deleted && !message.card;
1675 let (menu, react) = view
1676 .upgrade()
1677 .filter(|_| actionable)
1678 .map(|entity| {
1679 let this = entity.read(cx);
1680 let menu =
1681 this.message_menu(&message.key, message.own, view.clone());
1682 let react = menu.react.clone();
1683 let visible = this.toolbar_visible(&message.key);
1684 (visible.then_some(menu), Some(react))
1685 })
1686 .unwrap_or((None, None));
1334 1687 let reply = (is_real && !message.deleted).then(|| {
1335 1688 let (view, key, handle) =
1336 1689 (view.clone(), message.key.clone(), window.window_handle());
@@ -1355,6 +1708,8 @@ impl Render for ConversationView {
1355 1708 retry,
1356 1709 reply,
1357 1710 hovered,
1711 menu,
1712 react,
1358 1713 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
1359 1714 },
1360 1715 &state.directory,
@@ -14,22 +14,24 @@ use gpui_kit::component::{
14use gpui_kit::prelude::FluentBuilder as _;
14use gpui_kit::prelude::FluentBuilder as _;
15use gpui_kit::*;
15use gpui_kit::*;
16use store::MessageRecord;
16use store::MessageRecord;
17use teams_core::ImageRef;
17use teams_core::{ImageRef, MentionInput};
18
18
19use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
19use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
20use super::composer::{Composer, ComposerEvent, Outgoing, ReplyPreview};
20use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
21use super::message_actions::{Action, MessageMenu};
21use super::message_row::{RowActions, render_message_row, render_skeleton_row};
22use super::message_row::{RowActions, render_message_row, render_skeleton_row};
23use super::reaction_picker::{PickHandler, ReactionPicker};
22use super::widgets::icon;
24use super::widgets::icon;
23use crate::app_state::{AppEvent, AppState, Selection, selection_title};
25use crate::app_state::{AppEvent, AppState, Selection, selection_title};
24use crate::data::{is_one_on_one, others};
26use crate::data::{is_one_on_one, others};
27use crate::read_state::{ReadTrigger, plan_read};
25use crate::render::Block;
28use crate::render::Block;
26use crate::render::blocks::Inline;
29use crate::render::blocks::Inline;
27use crate::rows::{
30use crate::rows::{
28 Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
31 Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
29 changed_indices, diff_keys, flat_rows, placeholder_rows, reply_excerpt, thread_list_rows,
32 changed_indices, diff_keys, flat_rows, message_text, placeholder_rows, reaction_type_for,
30 thread_rows, trailing_skeleton,
33 reply_excerpt, thread_list_rows, thread_rows, trailing_skeleton,
31};
34};
32use crate::read_state::{ReadTrigger, plan_read};
33use crate::runtime;
35use crate::runtime;
34use crate::sidebar_model::{AvatarSpec, Face};
36use crate::sidebar_model::{AvatarSpec, Face};
35use crate::theme;
37use crate::theme;
@@ -52,6 +54,12 @@ const PROGRESS_BAR_WIDTH: f32 = 0.35;
52
54
53actions!(teams, [ReplyToHovered]);
55actions!(teams, [ReplyToHovered]);
54
56
57#[derive(Clone, Copy)]
58enum HoverSlot {
59 Row,
60 Toolbar,
61}
62
55#[derive(Debug, Clone, PartialEq, Eq)]
63#[derive(Debug, Clone, PartialEq, Eq)]
56enum ViewMode {
64enum ViewMode {
57 Flat,
65 Flat,
@@ -101,6 +109,9 @@ pub struct ConversationView {
101 pending_counter: usize,
109 pending_counter: usize,
102 pending_outgoing: HashMap<String, Outgoing>,
110 pending_outgoing: HashMap<String, Outgoing>,
103 hovered_message: Option<String>,
111 hovered_message: Option<String>,
112 toolbar_hovered: Option<String>,
113 toolbar_pinned: Option<String>,
114 picker: Entity<ReactionPicker>,
104 highlighted_message: Option<String>,
115 highlighted_message: Option<String>,
105 notice: Option<String>,
116 notice: Option<String>,
106 sync_generation: u64,
117 sync_generation: u64,
@@ -123,6 +134,7 @@ impl ConversationView {
123 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
134 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
124 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
135 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
125 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
136 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
137 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
126 let subscriptions = vec![
138 let subscriptions = vec![
127 cx.subscribe_in(&app, window, Self::on_app_event),
139 cx.subscribe_in(&app, window, Self::on_app_event),
128 cx.subscribe_in(&composer, window, Self::on_composer_event),
140 cx.subscribe_in(&composer, window, Self::on_composer_event),
@@ -138,6 +150,9 @@ impl ConversationView {
138 pending_counter: 0,
150 pending_counter: 0,
139 pending_outgoing: HashMap::new(),
151 pending_outgoing: HashMap::new(),
140 hovered_message: None,
152 hovered_message: None,
153 toolbar_hovered: None,
154 toolbar_pinned: None,
155 picker,
141 highlighted_message: None,
156 highlighted_message: None,
142 notice: None,
157 notice: None,
143 sync_generation: 0,
158 sync_generation: 0,
@@ -225,11 +240,18 @@ impl ConversationView {
225 window: &mut Window,
240 window: &mut Window,
226 cx: &mut Context<Self>,
241 cx: &mut Context<Self>,
227 ) {
242 ) {
228 let ComposerEvent::Submit(outgoing) = event;
243 match event {
229 self.send(outgoing.clone(), window, cx);
244 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
245 self.send_edit(outgoing.clone(), window, cx)
246 }
247 ComposerEvent::Submit(outgoing) => self.send(outgoing.clone(), window, cx),
248 ComposerEvent::EditLast => self.edit_last_own(window, cx),
249 }
230 }
250 }
231
251
232 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
252 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
253 self.toolbar_hovered = None;
254 self.toolbar_pinned = None;
233 let title = selection_title(&self.app.read(cx).sidebar, &selection);
255 let title = selection_title(&self.app.read(cx).sidebar, &selection);
234 let mode = match selection {
256 let mode = match selection {
235 Selection::Chat(_) => ViewMode::Flat,
257 Selection::Chat(_) => ViewMode::Flat,
@@ -1054,6 +1076,7 @@ impl ConversationView {
1054 text,
1076 text,
1055 mentions,
1077 mentions,
1056 reply,
1078 reply,
1079 ..
1057 } = &sent;
1080 } = &sent;
1058 match (&view_mode, reply) {
1081 match (&view_mode, reply) {
1059 (_, Some(reply)) => {
1082 (_, Some(reply)) => {
@@ -1089,6 +1112,323 @@ impl ConversationView {
1089 .detach();
1112 .detach();
1090 }
1113 }
1091
1114
1115 fn conversation_id(&self) -> Option<String> {
1116 self.current
1117 .as_ref()
1118 .map(|current| current.selection.conversation_id().to_owned())
1119 }
1120
1121 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
1122 let conversation_id = self.conversation_id()?;
1123 let my_user_id = self.row_context(cx).my_user_id?;
1124 self.app
1125 .read(cx)
1126 .store
1127 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1128 .ok()?
1129 .remove(message_id)
1130 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
1131 }
1132
1133 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
1134 let target = match slot {
1135 HoverSlot::Row => &mut self.hovered_message,
1136 HoverSlot::Toolbar => &mut self.toolbar_hovered,
1137 };
1138 if hovered {
1139 *target = Some(key.to_owned());
1140 } else if target.as_deref() == Some(key) {
1141 *target = None;
1142 }
1143 cx.notify();
1144 }
1145
1146 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
1147 if open {
1148 self.toolbar_pinned = Some(key.to_owned());
1149 } else if self.toolbar_pinned.as_deref() == Some(key) {
1150 self.toolbar_pinned = None;
1151 }
1152 cx.notify();
1153 }
1154
1155 fn toolbar_visible(&self, key: &str) -> bool {
1156 [
1157 &self.hovered_message,
1158 &self.toolbar_hovered,
1159 &self.toolbar_pinned,
1160 ]
1161 .iter()
1162 .any(|slot| slot.as_deref() == Some(key))
1163 }
1164
1165 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
1166 let Some(conversation_id) = self.conversation_id() else {
1167 return;
1168 };
1169 let reaction_type = reaction_type_for(glyph);
1170 let state = self.app.read(cx);
1171 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1172 let my_user_id = self.row_context(cx).my_user_id;
1173 let Some(mut record) = store
1174 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1175 .ok()
1176 .and_then(|mut found| found.remove(message_id))
1177 else {
1178 return;
1179 };
1180 let mut reactions = teams_core::reactions(&record);
1181 let mine = |reaction: &teams_core::ReactionInfo| {
1182 reaction.reaction_type == reaction_type
1183 && my_user_id.is_some()
1184 && reaction.user_id == my_user_id
1185 };
1186 let remove = reactions.iter().any(mine);
1187 if mode.demo {
1188 if remove {
1189 reactions.retain(|reaction| !mine(reaction));
1190 } else {
1191 reactions.push(teams_core::ReactionInfo {
1192 reaction_type: reaction_type.clone(),
1193 user_id: my_user_id.clone(),
1194 user_name: Some("You".to_owned()),
1195 });
1196 }
1197 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1198 let _ = store.upsert_messages(std::slice::from_ref(&record));
1199 self.rebuild(false, cx);
1200 return;
1201 }
1202 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1203 self.show_notice("Read-only mode: reaction not sent", cx);
1204 return;
1205 };
1206 let message_id = message_id.to_owned();
1207 let receiver = runtime::spawn(async move {
1208 if remove {
1209 engine
1210 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1211 .await
1212 } else {
1213 engine
1214 .set_reaction(&conversation_id, &message_id, &reaction_type)
1215 .await
1216 }
1217 });
1218 self.report_failure(receiver, "Reaction failed", cx);
1219 }
1220
1221 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1222 let Some(record) = self.own_record(message_id, cx) else {
1223 return;
1224 };
1225 let edit = EditPreview {
1226 message_id: record.message_id.clone(),
1227 excerpt: reply_excerpt(&record),
1228 };
1229 let in_chat = matches!(
1230 self.current.as_ref().map(|current| &current.selection),
1231 Some(Selection::Chat(_))
1232 );
1233 let mentions = if in_chat {
1234 teams_core::mentions(&record)
1235 .into_iter()
1236 .filter_map(|mention| {
1237 let user_id = mention.user_id?;
1238 Some(MentionInput::user(&user_id, &mention.name))
1239 })
1240 .collect()
1241 } else {
1242 Vec::new()
1243 };
1244 let draft = Outgoing {
1245 text: message_text(&record),
1246 mentions,
1247 reply: None,
1248 edit: Some(edit),
1249 };
1250 self.composer
1251 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
1252 }
1253
1254 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1255 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
1256 Row::Message(message)
1257 if message.own
1258 && !message.deleted
1259 && !message.key.starts_with(PENDING_KEY_PREFIX) =>
1260 {
1261 Some(message.key.clone())
1262 }
1263 _ => None,
1264 });
1265 if let Some(key) = key {
1266 self.begin_edit(&key, window, cx);
1267 }
1268 }
1269
1270 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1271 let Some(edit) = outgoing.edit.clone() else {
1272 return;
1273 };
1274 let Some(conversation_id) = self.conversation_id() else {
1275 return;
1276 };
1277 let state = self.app.read(cx);
1278 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1279 if mode.demo {
1280 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
1281 record.body_html = teams_core::markdown_to_html(&outgoing.text);
1282 record.edited_at = Some(Utc::now());
1283 let _ = store.upsert_messages(std::slice::from_ref(&record));
1284 self.rebuild(false, cx);
1285 }
1286 return;
1287 }
1288 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1289 self.notice = Some("Read-only mode: edit not saved".to_owned());
1290 self.composer
1291 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1292 cx.notify();
1293 return;
1294 };
1295 let sent = outgoing.clone();
1296 let receiver = runtime::spawn(async move {
1297 engine
1298 .edit_message_with_mentions(
1299 &conversation_id,
1300 &edit.message_id,
1301 &sent.text,
1302 &sent.mentions,
1303 )
1304 .await
1305 });
1306 cx.spawn_in(window, async move |this, cx| {
1307 let failed = !matches!(receiver.await, Ok(Ok(())));
1308 this.update_in(cx, |this, window, cx| {
1309 if failed {
1310 this.notice = Some("Edit failed: your text is back in the composer".to_owned());
1311 this.composer
1312 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1313 cx.notify();
1314 }
1315 })
1316 .ok();
1317 })
1318 .detach();
1319 }
1320
1321 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
1322 let Some(mut record) = self.own_record(message_id, cx) else {
1323 return;
1324 };
1325 let state = self.app.read(cx);
1326 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1327 if mode.demo {
1328 record.deleted = true;
1329 let _ = store.upsert_messages(std::slice::from_ref(&record));
1330 self.rebuild(false, cx);
1331 return;
1332 }
1333 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1334 self.show_notice("Read-only mode: message not deleted", cx);
1335 return;
1336 };
1337 let conversation_id = record.conversation_id.clone();
1338 let receiver = runtime::spawn(async move {
1339 engine
1340 .soft_delete_message(&conversation_id, &record.message_id)
1341 .await
1342 });
1343 self.report_failure(receiver, "Delete failed", cx);
1344 }
1345
1346 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
1347 let Some(conversation_id) = self.conversation_id() else {
1348 return;
1349 };
1350 let record = self
1351 .app
1352 .read(cx)
1353 .store
1354 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1355 .ok()
1356 .and_then(|mut found| found.remove(message_id));
1357 if let Some(record) = record {
1358 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
1359 }
1360 }
1361
1362 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
1363 self.notice = Some(message.to_owned());
1364 cx.notify();
1365 }
1366
1367 fn report_failure(
1368 &mut self,
1369 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
1370 label: &'static str,
1371 cx: &mut Context<Self>,
1372 ) {
1373 cx.spawn(async move |this, cx| {
1374 let error = match receiver.await {
1375 Ok(Ok(())) => return,
1376 Ok(Err(error)) => short_error(&error),
1377 Err(_) => "cancelled".to_owned(),
1378 };
1379 this.update(cx, |this, cx| {
1380 this.show_notice(&format!("{label}: {error}"), cx)
1381 })
1382 .ok();
1383 })
1384 .detach();
1385 }
1386
1387 fn message_menu(&self, key: &str, own: bool, view: WeakEntity<Self>) -> MessageMenu {
1388 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
1389 let (view, key) = (view.clone(), key.to_owned());
1390 Rc::new(move |window, cx| {
1391 view.update(cx, |this, cx| run(this, &key, window, cx)).ok();
1392 })
1393 };
1394 let react: PickHandler = {
1395 let (view, key) = (view.clone(), key.to_owned());
1396 Rc::new(move |glyph, _, cx| {
1397 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
1398 .ok();
1399 })
1400 };
1401 let hover = {
1402 let (view, key) = (view.clone(), key.to_owned());
1403 Rc::new(move |hovered: bool, cx: &mut App| {
1404 view.update(cx, |this, cx| {
1405 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
1406 })
1407 .ok();
1408 })
1409 };
1410 let pin = {
1411 let (view, key) = (view.clone(), key.to_owned());
1412 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
1413 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
1414 .ok();
1415 })
1416 };
1417 MessageMenu {
1418 key: key.to_owned(),
1419 react,
1420 reply: Some(action(|this, key, window, cx| {
1421 this.begin_reply(key, window, cx)
1422 })),
1423 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
1424 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
1425 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
1426 pin,
1427 hover,
1428 picker: self.picker.clone(),
1429 }
1430 }
1431
1092 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
1432 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
1093 let Some(outgoing) = self.pending_outgoing.remove(key) else {
1433 let Some(outgoing) = self.pending_outgoing.remove(key) else {
1094 return;
1434 return;
@@ -1324,13 +1664,26 @@ impl Render for ConversationView {
1324 let is_real = !message.key.starts_with(PENDING_KEY_PREFIX);
1664 let is_real = !message.key.starts_with(PENDING_KEY_PREFIX);
1325 let hovered = is_real.then(|| {
1665 let hovered = is_real.then(|| {
1326 let (view, key) = (view.clone(), message.key.clone());
1666 let (view, key) = (view.clone(), message.key.clone());
1327 Box::new(move |cx: &mut App| {
1667 Rc::new(move |hovered: bool, cx: &mut App| {
1328 view.update(cx, |this, _| {
1668 view.update(cx, |this, cx| {
1329 this.hovered_message = Some(key.clone());
1669 this.set_hover(HoverSlot::Row, &key, hovered, cx)
1330 })
1670 })
1331 .ok();
1671 .ok();
1332 }) as Box<dyn Fn(&mut App)>
1672 }) as Rc<dyn Fn(bool, &mut App)>
1333 });
1673 });
1674 let actionable = is_real && !message.deleted && !message.card;
1675 let (menu, react) = view
1676 .upgrade()
1677 .filter(|_| actionable)
1678 .map(|entity| {
1679 let this = entity.read(cx);
1680 let menu =
1681 this.message_menu(&message.key, message.own, view.clone());
1682 let react = menu.react.clone();
1683 let visible = this.toolbar_visible(&message.key);
1684 (visible.then_some(menu), Some(react))
1685 })
1686 .unwrap_or((None, None));
1334 let reply = (is_real && !message.deleted).then(|| {
1687 let reply = (is_real && !message.deleted).then(|| {
1335 let (view, key, handle) =
1688 let (view, key, handle) =
1336 (view.clone(), message.key.clone(), window.window_handle());
1689 (view.clone(), message.key.clone(), window.window_handle());
@@ -1355,6 +1708,8 @@ impl Render for ConversationView {
1355 retry,
1708 retry,
1356 reply,
1709 reply,
1357 hovered,
1710 hovered,
1711 menu,
1712 react,
1358 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
1713 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
1359 },
1714 },
1360 &state.directory,
1715 &state.directory,
crates/app/src/views/message_actions.rs added +175 −0
@@ -0,0 +1,175 @@
1 use std::rc::Rc;
2
3 use gpui_kit::assets::IconName;
4 use gpui_kit::base::GlobalState;
5 use gpui_kit::component::{
6 Sizable as _,
7 button::{Button, ButtonVariants as _},
8 h_flex,
9 menu::{DropdownMenu as _, PopupMenuItem},
10 popover::Popover,
11 };
12 use gpui_kit::*;
13
14 use super::reaction_picker::{PickHandler, QUICK_REACTIONS, ReactionPicker};
15 use super::widgets::icon;
16 use crate::theme;
17
18 const BAR_BUTTON: f32 = 28.;
19
20 pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
21 pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
22 pub type HoverChange = Rc<dyn Fn(bool, &mut App)>;
23
24 pub struct MessageMenu {
25 pub key: String,
26 pub react: PickHandler,
27 pub reply: Option<Action>,
28 pub copy: Action,
29 pub edit: Option<Action>,
30 pub delete: Option<Action>,
31 pub pin: OpenChange,
32 pub hover: HoverChange,
33 pub picker: Entity<ReactionPicker>,
34 }
35
36 fn element_id(prefix: &str, key: &str) -> ElementId {
37 ElementId::Name(format!("{prefix}-{key}").into())
38 }
39
40 fn bar_button(id: ElementId) -> Stateful<Div> {
41 div()
42 .id(id)
43 .size(px(BAR_BUTTON))
44 .flex()
45 .items_center()
46 .justify_center()
47 .rounded(px(6.))
48 .cursor_pointer()
49 .hover(|button| button.bg(theme::border_strong()))
50 }
51
52 fn reaction_button(menu: &MessageMenu, glyph: &'static str, index: usize) -> AnyElement {
53 let react = menu.react.clone();
54 bar_button(element_id(&format!("quick-reaction-{index}"), &menu.key))
55 .text_size(px(17.))
56 .child(glyph)
57 .on_click(move |_, window, cx| {
58 cx.stop_propagation();
59 react(glyph, window, cx);
60 })
61 .into_any_element()
62 }
63
64 fn picker_button(menu: &MessageMenu) -> AnyElement {
65 let (picker, picker_reset, react, pin) = (
66 menu.picker.clone(),
67 menu.picker.clone(),
68 menu.react.clone(),
69 menu.pin.clone(),
70 );
71 Popover::new(element_id("reaction-picker", &menu.key))
72 .anchor(Anchor::TopRight)
73 .trigger(
74 Button::new(element_id("add-reaction", &menu.key))
75 .icon(IconName::Plus)
76 .ghost()
77 .xsmall()
78 .size(px(BAR_BUTTON)),
79 )
80 .on_open_change(move |open, window, cx| {
81 pin(*open, window, cx);
82 if *open {
83 picker_reset.update(cx, |picker, cx| picker.reset(window, cx));
84 }
85 })
86 .content(move |_, _, cx| {
87 let popover = cx.entity().downgrade();
88 picker.update(cx, |picker, _| picker.set_target(react.clone(), popover));
89 picker.clone()
90 })
91 .into_any_element()
92 }
93
94 fn more_button(menu: &MessageMenu) -> AnyElement {
95 let (reply, copy, edit, delete, pin) = (
96 menu.reply.clone(),
97 menu.copy.clone(),
98 menu.edit.clone(),
99 menu.delete.clone(),
100 menu.pin.clone(),
101 );
102 Button::new(element_id("message-more", &menu.key))
103 .icon(IconName::Ellipsis)
104 .ghost()
105 .xsmall()
106 .size(px(BAR_BUTTON))
107 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
108 let item = |label: &'static str, glyph: IconName, action: Action| {
109 PopupMenuItem::new(label)
110 .icon(glyph)
111 .on_click(move |_, window, cx| action(window, cx))
112 };
113 let mut popup = popup;
114 if let Some(reply) = reply.clone() {
115 popup = popup.item(item("Reply with quote", IconName::Reply, reply));
116 }
117 popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));
118 if let Some(edit) = edit.clone() {
119 popup = popup.item(item("Edit", IconName::Pencil, edit));
120 }
121 if let Some(delete) = delete.clone() {
122 popup = popup
123 .separator()
124 .item(item("Delete", IconName::Trash, delete));
125 }
126 popup
127 })
128 .on_open_change(move |open, window, cx| pin(*open, window, cx))
129 .into_any_element()
130 }
131
132 pub fn message_toolbar(menu: MessageMenu) -> AnyElement {
133 let hover = menu.hover.clone();
134 let mut children: Vec<AnyElement> = QUICK_REACTIONS
135 .iter()
136 .enumerate()
137 .map(|(index, glyph)| reaction_button(&menu, glyph, index))
138 .collect();
139 children.push(picker_button(&menu));
140 children.push(
141 div()
142 .w(px(1.))
143 .h(px(18.))
144 .mx(px(2.))
145 .bg(theme::border_strong())
146 .into_any_element(),
147 );
148 if let Some(reply) = menu.reply.clone() {
149 children.push(
150 bar_button(element_id("toolbar-reply", &menu.key))
151 .child(icon(IconName::Reply, 16., theme::text_soft()))
152 .on_click(move |_, window, cx| {
153 cx.stop_propagation();
154 reply(window, cx);
155 })
156 .into_any_element(),
157 );
158 }
159 children.push(more_button(&menu));
160 h_flex()
161 .id(element_id("message-toolbar", &menu.key))
162 .p(px(2.))
163 .gap(px(2.))
164 .items_center()
165 .rounded(px(8.))
166 .bg(theme::surface())
167 .border_1()
168 .border_color(theme::border_strong())
169 .on_hover(move |hovered, _, cx| hover(*hovered, cx))
170 .on_mouse_down(MouseButton::Left, |_, _, cx| {
171 GlobalState::suppress_text_selection(cx)
172 })
173 .children(children)
174 .into_any_element()
175 }
@@ -0,0 +1,175 @@
1use std::rc::Rc;
2
3use gpui_kit::assets::IconName;
4use gpui_kit::base::GlobalState;
5use gpui_kit::component::{
6 Sizable as _,
7 button::{Button, ButtonVariants as _},
8 h_flex,
9 menu::{DropdownMenu as _, PopupMenuItem},
10 popover::Popover,
11};
12use gpui_kit::*;
13
14use super::reaction_picker::{PickHandler, QUICK_REACTIONS, ReactionPicker};
15use super::widgets::icon;
16use crate::theme;
17
18const BAR_BUTTON: f32 = 28.;
19
20pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
21pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
22pub type HoverChange = Rc<dyn Fn(bool, &mut App)>;
23
24pub struct MessageMenu {
25 pub key: String,
26 pub react: PickHandler,
27 pub reply: Option<Action>,
28 pub copy: Action,
29 pub edit: Option<Action>,
30 pub delete: Option<Action>,
31 pub pin: OpenChange,
32 pub hover: HoverChange,
33 pub picker: Entity<ReactionPicker>,
34}
35
36fn element_id(prefix: &str, key: &str) -> ElementId {
37 ElementId::Name(format!("{prefix}-{key}").into())
38}
39
40fn bar_button(id: ElementId) -> Stateful<Div> {
41 div()
42 .id(id)
43 .size(px(BAR_BUTTON))
44 .flex()
45 .items_center()
46 .justify_center()
47 .rounded(px(6.))
48 .cursor_pointer()
49 .hover(|button| button.bg(theme::border_strong()))
50}
51
52fn reaction_button(menu: &MessageMenu, glyph: &'static str, index: usize) -> AnyElement {
53 let react = menu.react.clone();
54 bar_button(element_id(&format!("quick-reaction-{index}"), &menu.key))
55 .text_size(px(17.))
56 .child(glyph)
57 .on_click(move |_, window, cx| {
58 cx.stop_propagation();
59 react(glyph, window, cx);
60 })
61 .into_any_element()
62}
63
64fn picker_button(menu: &MessageMenu) -> AnyElement {
65 let (picker, picker_reset, react, pin) = (
66 menu.picker.clone(),
67 menu.picker.clone(),
68 menu.react.clone(),
69 menu.pin.clone(),
70 );
71 Popover::new(element_id("reaction-picker", &menu.key))
72 .anchor(Anchor::TopRight)
73 .trigger(
74 Button::new(element_id("add-reaction", &menu.key))
75 .icon(IconName::Plus)
76 .ghost()
77 .xsmall()
78 .size(px(BAR_BUTTON)),
79 )
80 .on_open_change(move |open, window, cx| {
81 pin(*open, window, cx);
82 if *open {
83 picker_reset.update(cx, |picker, cx| picker.reset(window, cx));
84 }
85 })
86 .content(move |_, _, cx| {
87 let popover = cx.entity().downgrade();
88 picker.update(cx, |picker, _| picker.set_target(react.clone(), popover));
89 picker.clone()
90 })
91 .into_any_element()
92}
93
94fn more_button(menu: &MessageMenu) -> AnyElement {
95 let (reply, copy, edit, delete, pin) = (
96 menu.reply.clone(),
97 menu.copy.clone(),
98 menu.edit.clone(),
99 menu.delete.clone(),
100 menu.pin.clone(),
101 );
102 Button::new(element_id("message-more", &menu.key))
103 .icon(IconName::Ellipsis)
104 .ghost()
105 .xsmall()
106 .size(px(BAR_BUTTON))
107 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
108 let item = |label: &'static str, glyph: IconName, action: Action| {
109 PopupMenuItem::new(label)
110 .icon(glyph)
111 .on_click(move |_, window, cx| action(window, cx))
112 };
113 let mut popup = popup;
114 if let Some(reply) = reply.clone() {
115 popup = popup.item(item("Reply with quote", IconName::Reply, reply));
116 }
117 popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));
118 if let Some(edit) = edit.clone() {
119 popup = popup.item(item("Edit", IconName::Pencil, edit));
120 }
121 if let Some(delete) = delete.clone() {
122 popup = popup
123 .separator()
124 .item(item("Delete", IconName::Trash, delete));
125 }
126 popup
127 })
128 .on_open_change(move |open, window, cx| pin(*open, window, cx))
129 .into_any_element()
130}
131
132pub fn message_toolbar(menu: MessageMenu) -> AnyElement {
133 let hover = menu.hover.clone();
134 let mut children: Vec<AnyElement> = QUICK_REACTIONS
135 .iter()
136 .enumerate()
137 .map(|(index, glyph)| reaction_button(&menu, glyph, index))
138 .collect();
139 children.push(picker_button(&menu));
140 children.push(
141 div()
142 .w(px(1.))
143 .h(px(18.))
144 .mx(px(2.))
145 .bg(theme::border_strong())
146 .into_any_element(),
147 );
148 if let Some(reply) = menu.reply.clone() {
149 children.push(
150 bar_button(element_id("toolbar-reply", &menu.key))
151 .child(icon(IconName::Reply, 16., theme::text_soft()))
152 .on_click(move |_, window, cx| {
153 cx.stop_propagation();
154 reply(window, cx);
155 })
156 .into_any_element(),
157 );
158 }
159 children.push(more_button(&menu));
160 h_flex()
161 .id(element_id("message-toolbar", &menu.key))
162 .p(px(2.))
163 .gap(px(2.))
164 .items_center()
165 .rounded(px(8.))
166 .bg(theme::surface())
167 .border_1()
168 .border_color(theme::border_strong())
169 .on_hover(move |hovered, _, cx| hover(*hovered, cx))
170 .on_mouse_down(MouseButton::Left, |_, _, cx| {
171 GlobalState::suppress_text_selection(cx)
172 })
173 .children(children)
174 .into_any_element()
175}
crates/app/src/views/message_row.rs +67 −18
@@ -1,5 +1,5 @@
1 1 use gpui_kit::assets::IconName;
2 use gpui_kit::base::TextSelection;
2 use gpui_kit::base::{GlobalState, TextSelection};
3 3 use gpui_kit::component::{h_flex, v_flex};
4 4 use gpui_kit::prelude::FluentBuilder as _;
5 5 use gpui_kit::*;
@@ -7,6 +7,8 @@ use std::time::Duration;
7 7
8 8 use super::attachments::attachments_view;
9 9 use super::avatar::{member_stack, person_avatar};
10 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11 use super::reaction_picker::PickHandler;
10 12 use super::widgets::{icon, symbol};
11 13 use crate::data::Directory;
12 14 use crate::render::{Block, render_blocks};
@@ -35,17 +37,25 @@ pub struct RowActions {
35 37 pub open_thread: RowAction,
36 38 pub retry: RowAction,
37 39 pub reply: RowAction,
38 pub hovered: RowAction,
40 pub hovered: Option<HoverChange>,
41 pub menu: Option<MessageMenu>,
42 pub react: Option<PickHandler>,
39 43 pub highlighted: bool,
40 44 }
41 45
42 fn reaction_chip(chip: &ReactionChip) -> Div {
46 const TOOLBAR_LIFT: f32 = 22.;
47
48 fn reaction_chip(chip: &ReactionChip, index: usize, react: Option<PickHandler>) -> Stateful<Div> {
43 49 let (background, border, foreground) = if chip.mine {
44 50 (theme::bubble_own(), theme::accent(), theme::accent_tint())
45 51 } else {
46 52 (theme::surface(), theme::border_strong(), theme::text_soft())
47 53 };
54 let glyph = chip.label.clone();
48 55 h_flex()
56 .id(ElementId::Name(
57 format!("reaction-{index}-{}", chip.reaction_type).into(),
58 ))
49 59 .h(px(22.))
50 60 .px(px(8.))
51 61 .gap(px(4.))
@@ -58,6 +68,17 @@ fn reaction_chip(chip: &ReactionChip) -> Div {
58 68 .text_color(foreground)
59 69 .child(chip.label.clone())
60 70 .child(chip.count.to_string())
71 .when_some(react, |chip, react| {
72 chip.cursor_pointer()
73 .hover(|chip| chip.border_color(theme::accent()))
74 .on_mouse_down(MouseButton::Left, |_, _, cx| {
75 GlobalState::suppress_text_selection(cx)
76 })
77 .on_click(move |_, window, cx| {
78 cx.stop_propagation();
79 react(&glyph, window, cx);
80 })
81 })
61 82 }
62 83
63 84 fn labeled_divider(label: &str, line_color: Hsla, text_color: Hsla) -> Div {
@@ -85,7 +106,14 @@ fn new_marker() -> Div {
85 106 labeled_divider("New", theme::accent(), theme::accent_text())
86 107 }
87 108
88 fn bubble(row: &MessageRow, index: usize, own: bool, directory: &Directory, cx: &App) -> Div {
109 fn bubble(
110 row: &MessageRow,
111 index: usize,
112 own: bool,
113 directory: &Directory,
114 extras: BubbleExtras,
115 cx: &App,
116 ) -> Div {
89 117 let corners = bubble_corners(own, row.series);
90 118 let mut element = div()
91 119 .relative()
@@ -162,12 +190,31 @@ fn bubble(row: &MessageRow, index: usize, own: bool, directory: &Directory, cx:
162 190 .when(!own, |chips| chips.left(px(11.)))
163 191 .bottom(px(-14.))
164 192 .gap(px(4.))
165 .children(row.reactions.iter().map(reaction_chip)),
193 .children(
194 row.reactions
195 .iter()
196 .map(|chip| reaction_chip(chip, index, extras.react.clone())),
197 ),
198 );
199 }
200 if let Some(menu) = extras.menu {
201 element = element.child(
202 div()
203 .absolute()
204 .top(px(-TOOLBAR_LIFT))
205 .right(px(8.))
206 .child(deferred(message_toolbar(menu)).with_priority(1)),
166 207 );
167 208 }
168 209 element
169 210 }
170 211
212 #[derive(Default)]
213 struct BubbleExtras {
214 menu: Option<MessageMenu>,
215 react: Option<PickHandler>,
216 }
217
171 218 fn bubble_meta(row: &MessageRow, own: bool) -> Div {
172 219 let tint = if own {
173 220 theme::own_meta()
@@ -432,10 +479,11 @@ fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) ->
432 479 ));
433 480 if !row.reactions.is_empty() {
434 481 body = body.child(
435 h_flex()
436 .gap(px(4.))
437 .flex_wrap()
438 .children(row.reactions.iter().map(reaction_chip)),
482 h_flex().gap(px(4.)).flex_wrap().children(
483 row.reactions
484 .iter()
485 .map(|chip| reaction_chip(chip, index, None)),
486 ),
439 487 );
440 488 }
441 489 }
@@ -460,6 +508,7 @@ fn others_row(
460 508 index: usize,
461 509 directory: &Directory,
462 510 retry: RowAction,
511 extras: BubbleExtras,
463 512 cx: &App,
464 513 ) -> Div {
465 514 let first = !row.series.has_prev;
@@ -478,7 +527,7 @@ fn others_row(
478 527 ),
479 528 );
480 529 }
481 column = column.child(bubble(row, index, false, directory, cx));
530 column = column.child(bubble(row, index, false, directory, extras, cx));
482 531 if let Some(note) = delivery_note(row, retry, index) {
483 532 column = column.child(note);
484 533 }
@@ -505,13 +554,14 @@ fn own_row(
505 554 index: usize,
506 555 directory: &Directory,
507 556 retry: RowAction,
557 extras: BubbleExtras,
508 558 cx: &App,
509 559 ) -> Div {
510 560 let mut column = v_flex().w_full().items_end().gap(px(2.));
511 561 column = column.child(
512 562 div()
513 563 .max_w(relative(MAX_WIDTH_RATIO))
514 .child(bubble(row, index, true, directory, cx)),
564 .child(bubble(row, index, true, directory, extras, cx)),
515 565 );
516 566 if let Some(note) = delivery_note(row, retry, index) {
517 567 column = column.child(note);
@@ -531,8 +581,11 @@ pub fn render_message_row(
531 581 retry,
532 582 reply,
533 583 hovered,
584 menu,
585 react,
534 586 highlighted,
535 587 } = actions;
588 let extras = BubbleExtras { menu, react };
536 589 let own = row.own && !row.card;
537 590 let spacing = if row.card {
538 591 px(CARD_GAP)
@@ -551,9 +604,9 @@ pub fn render_message_row(
551 604 let body = if row.card {
552 605 post_card(row, index, directory, cx)
553 606 } else if own {
554 own_row(row, index, directory, retry, cx)
607 own_row(row, index, directory, retry, extras, cx)
555 608 } else {
556 others_row(row, index, directory, retry, cx)
609 others_row(row, index, directory, retry, extras, cx)
557 610 };
558 611 container
559 612 .child(
@@ -569,11 +622,7 @@ pub fn render_message_row(
569 622 })
570 623 })
571 624 .when_some(hovered, |element, hovered| {
572 element.on_hover(move |is_hovered, _, cx| {
573 if *is_hovered {
574 hovered(cx);
575 }
576 })
625 element.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
577 626 })
578 627 .when_some(reply, |element, reply| {
579 628 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
@@ -1,5 +1,5 @@
1use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::base::TextSelection;
2use gpui_kit::base::{GlobalState, TextSelection};
3use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
5use gpui_kit::*;
@@ -7,6 +7,8 @@ use std::time::Duration;
7
7
8use super::attachments::attachments_view;
8use super::attachments::attachments_view;
9use super::avatar::{member_stack, person_avatar};
9use super::avatar::{member_stack, person_avatar};
10use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11use super::reaction_picker::PickHandler;
10use super::widgets::{icon, symbol};
12use super::widgets::{icon, symbol};
11use crate::data::Directory;
13use crate::data::Directory;
12use crate::render::{Block, render_blocks};
14use crate::render::{Block, render_blocks};
@@ -35,17 +37,25 @@ pub struct RowActions {
35 pub open_thread: RowAction,
37 pub open_thread: RowAction,
36 pub retry: RowAction,
38 pub retry: RowAction,
37 pub reply: RowAction,
39 pub reply: RowAction,
38 pub hovered: RowAction,
40 pub hovered: Option<HoverChange>,
41 pub menu: Option<MessageMenu>,
42 pub react: Option<PickHandler>,
39 pub highlighted: bool,
43 pub highlighted: bool,
40}
44}
41
45
42fn reaction_chip(chip: &ReactionChip) -> Div {
46const TOOLBAR_LIFT: f32 = 22.;
47
48fn reaction_chip(chip: &ReactionChip, index: usize, react: Option<PickHandler>) -> Stateful<Div> {
43 let (background, border, foreground) = if chip.mine {
49 let (background, border, foreground) = if chip.mine {
44 (theme::bubble_own(), theme::accent(), theme::accent_tint())
50 (theme::bubble_own(), theme::accent(), theme::accent_tint())
45 } else {
51 } else {
46 (theme::surface(), theme::border_strong(), theme::text_soft())
52 (theme::surface(), theme::border_strong(), theme::text_soft())
47 };
53 };
54 let glyph = chip.label.clone();
48 h_flex()
55 h_flex()
56 .id(ElementId::Name(
57 format!("reaction-{index}-{}", chip.reaction_type).into(),
58 ))
49 .h(px(22.))
59 .h(px(22.))
50 .px(px(8.))
60 .px(px(8.))
51 .gap(px(4.))
61 .gap(px(4.))
@@ -58,6 +68,17 @@ fn reaction_chip(chip: &ReactionChip) -> Div {
58 .text_color(foreground)
68 .text_color(foreground)
59 .child(chip.label.clone())
69 .child(chip.label.clone())
60 .child(chip.count.to_string())
70 .child(chip.count.to_string())
71 .when_some(react, |chip, react| {
72 chip.cursor_pointer()
73 .hover(|chip| chip.border_color(theme::accent()))
74 .on_mouse_down(MouseButton::Left, |_, _, cx| {
75 GlobalState::suppress_text_selection(cx)
76 })
77 .on_click(move |_, window, cx| {
78 cx.stop_propagation();
79 react(&glyph, window, cx);
80 })
81 })
61}
82}
62
83
63fn labeled_divider(label: &str, line_color: Hsla, text_color: Hsla) -> Div {
84fn labeled_divider(label: &str, line_color: Hsla, text_color: Hsla) -> Div {
@@ -85,7 +106,14 @@ fn new_marker() -> Div {
85 labeled_divider("New", theme::accent(), theme::accent_text())
106 labeled_divider("New", theme::accent(), theme::accent_text())
86}
107}
87
108
88fn bubble(row: &MessageRow, index: usize, own: bool, directory: &Directory, cx: &App) -> Div {
109fn bubble(
110 row: &MessageRow,
111 index: usize,
112 own: bool,
113 directory: &Directory,
114 extras: BubbleExtras,
115 cx: &App,
116) -> Div {
89 let corners = bubble_corners(own, row.series);
117 let corners = bubble_corners(own, row.series);
90 let mut element = div()
118 let mut element = div()
91 .relative()
119 .relative()
@@ -162,12 +190,31 @@ fn bubble(row: &MessageRow, index: usize, own: bool, directory: &Directory, cx:
162 .when(!own, |chips| chips.left(px(11.)))
190 .when(!own, |chips| chips.left(px(11.)))
163 .bottom(px(-14.))
191 .bottom(px(-14.))
164 .gap(px(4.))
192 .gap(px(4.))
165 .children(row.reactions.iter().map(reaction_chip)),
193 .children(
194 row.reactions
195 .iter()
196 .map(|chip| reaction_chip(chip, index, extras.react.clone())),
197 ),
198 );
199 }
200 if let Some(menu) = extras.menu {
201 element = element.child(
202 div()
203 .absolute()
204 .top(px(-TOOLBAR_LIFT))
205 .right(px(8.))
206 .child(deferred(message_toolbar(menu)).with_priority(1)),
166 );
207 );
167 }
208 }
168 element
209 element
169}
210}
170
211
212#[derive(Default)]
213struct BubbleExtras {
214 menu: Option<MessageMenu>,
215 react: Option<PickHandler>,
216}
217
171fn bubble_meta(row: &MessageRow, own: bool) -> Div {
218fn bubble_meta(row: &MessageRow, own: bool) -> Div {
172 let tint = if own {
219 let tint = if own {
173 theme::own_meta()
220 theme::own_meta()
@@ -432,10 +479,11 @@ fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) ->
432 ));
479 ));
433 if !row.reactions.is_empty() {
480 if !row.reactions.is_empty() {
434 body = body.child(
481 body = body.child(
435 h_flex()
482 h_flex().gap(px(4.)).flex_wrap().children(
436 .gap(px(4.))
483 row.reactions
437 .flex_wrap()
484 .iter()
438 .children(row.reactions.iter().map(reaction_chip)),
485 .map(|chip| reaction_chip(chip, index, None)),
486 ),
439 );
487 );
440 }
488 }
441 }
489 }
@@ -460,6 +508,7 @@ fn others_row(
460 index: usize,
508 index: usize,
461 directory: &Directory,
509 directory: &Directory,
462 retry: RowAction,
510 retry: RowAction,
511 extras: BubbleExtras,
463 cx: &App,
512 cx: &App,
464) -> Div {
513) -> Div {
465 let first = !row.series.has_prev;
514 let first = !row.series.has_prev;
@@ -478,7 +527,7 @@ fn others_row(
478 ),
527 ),
479 );
528 );
480 }
529 }
481 column = column.child(bubble(row, index, false, directory, cx));
530 column = column.child(bubble(row, index, false, directory, extras, cx));
482 if let Some(note) = delivery_note(row, retry, index) {
531 if let Some(note) = delivery_note(row, retry, index) {
483 column = column.child(note);
532 column = column.child(note);
484 }
533 }
@@ -505,13 +554,14 @@ fn own_row(
505 index: usize,
554 index: usize,
506 directory: &Directory,
555 directory: &Directory,
507 retry: RowAction,
556 retry: RowAction,
557 extras: BubbleExtras,
508 cx: &App,
558 cx: &App,
509) -> Div {
559) -> Div {
510 let mut column = v_flex().w_full().items_end().gap(px(2.));
560 let mut column = v_flex().w_full().items_end().gap(px(2.));
511 column = column.child(
561 column = column.child(
512 div()
562 div()
513 .max_w(relative(MAX_WIDTH_RATIO))
563 .max_w(relative(MAX_WIDTH_RATIO))
514 .child(bubble(row, index, true, directory, cx)),
564 .child(bubble(row, index, true, directory, extras, cx)),
515 );
565 );
516 if let Some(note) = delivery_note(row, retry, index) {
566 if let Some(note) = delivery_note(row, retry, index) {
517 column = column.child(note);
567 column = column.child(note);
@@ -531,8 +581,11 @@ pub fn render_message_row(
531 retry,
581 retry,
532 reply,
582 reply,
533 hovered,
583 hovered,
584 menu,
585 react,
534 highlighted,
586 highlighted,
535 } = actions;
587 } = actions;
588 let extras = BubbleExtras { menu, react };
536 let own = row.own && !row.card;
589 let own = row.own && !row.card;
537 let spacing = if row.card {
590 let spacing = if row.card {
538 px(CARD_GAP)
591 px(CARD_GAP)
@@ -551,9 +604,9 @@ pub fn render_message_row(
551 let body = if row.card {
604 let body = if row.card {
552 post_card(row, index, directory, cx)
605 post_card(row, index, directory, cx)
553 } else if own {
606 } else if own {
554 own_row(row, index, directory, retry, cx)
607 own_row(row, index, directory, retry, extras, cx)
555 } else {
608 } else {
556 others_row(row, index, directory, retry, cx)
609 others_row(row, index, directory, retry, extras, cx)
557 };
610 };
558 container
611 container
559 .child(
612 .child(
@@ -569,11 +622,7 @@ pub fn render_message_row(
569 })
622 })
570 })
623 })
571 .when_some(hovered, |element, hovered| {
624 .when_some(hovered, |element, hovered| {
572 element.on_hover(move |is_hovered, _, cx| {
625 element.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
573 if *is_hovered {
574 hovered(cx);
575 }
576 })
577 })
626 })
578 .when_some(reply, |element, reply| {
627 .when_some(reply, |element, reply| {
579 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
628 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
crates/app/src/views/mod.rs +2 −0
@@ -3,7 +3,9 @@ pub mod avatar;
3 3 pub mod composer;
4 4 pub mod conversation;
5 5 pub mod emoji_popup;
6 pub mod message_actions;
6 7 pub mod message_row;
8 pub mod reaction_picker;
7 9 pub mod shell;
8 10 pub mod sidebar;
9 11 pub mod status_bar;
@@ -3,7 +3,9 @@ pub mod avatar;
3pub mod composer;
3pub mod composer;
4pub mod conversation;
4pub mod conversation;
5pub mod emoji_popup;
5pub mod emoji_popup;
6pub mod message_actions;
6pub mod message_row;
7pub mod message_row;
8pub mod reaction_picker;
7pub mod shell;
9pub mod shell;
8pub mod sidebar;
10pub mod sidebar;
9pub mod status_bar;
11pub mod status_bar;
crates/app/src/views/reaction_picker.rs added +206 −0
@@ -0,0 +1,206 @@
1 use std::rc::Rc;
2
3 use gpui_kit::base::PopoverState;
4 use gpui_kit::component::{
5 h_flex,
6 input::{Input, InputEvent, InputState},
7 v_flex,
8 };
9 use gpui_kit::*;
10
11 use crate::app_state::AppState;
12 use crate::emoji;
13 use crate::theme;
14
15 pub const QUICK_REACTIONS: [&str; 4] = ["\u{1F44D}", "\u{2764}", "\u{1F602}", "\u{1F62E}"];
16 const PICKER_QUICK: [&str; 6] = [
17 "\u{1F44D}",
18 "\u{2764}",
19 "\u{1F602}",
20 "\u{1F62E}",
21 "\u{1F622}",
22 "\u{1F64F}",
23 ];
24 const FALLBACK_RECENT: [&str; 16] = [
25 "\u{1F389}",
26 "\u{1F525}",
27 "\u{1F440}",
28 "\u{2705}",
29 "\u{1F4AF}",
30 "\u{1F680}",
31 "\u{1F605}",
32 "\u{1F914}",
33 "\u{1F44F}",
34 "\u{1F64C}",
35 "\u{1F60A}",
36 "\u{1F4A1}",
37 "\u{1F4CC}",
38 "\u{1F41E}",
39 "\u{1F9EA}",
40 "\u{2615}",
41 ];
42 const PICKER_WIDTH: f32 = 296.;
43 const CELL_SIZE: f32 = 32.;
44 const GRID_COLUMNS: usize = 8;
45 const GRID_LIMIT: usize = 32;
46
47 pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
48
49 pub struct ReactionPicker {
50 app: Entity<AppState>,
51 input: Entity<InputState>,
52 query: String,
53 recent: emoji::Recent,
54 target: Option<(PickHandler, WeakEntity<PopoverState>)>,
55 _subscription: Subscription,
56 }
57
58 impl ReactionPicker {
59 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
60 let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search emoji"));
61 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 let recent = emoji::Recent::load(&app.read(cx).store);
63 ReactionPicker {
64 app,
65 input,
66 query: String::new(),
67 recent,
68 target: None,
69 _subscription: subscription,
70 }
71 }
72
73 pub fn set_target(&mut self, on_pick: PickHandler, popover: WeakEntity<PopoverState>) {
74 self.target = Some((on_pick, popover));
75 }
76
77 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
78 self.query.clear();
79 self.input.update(cx, |state, cx| {
80 state.set_value("", window, cx);
81 state.focus(window, cx);
82 });
83 cx.notify();
84 }
85
86 fn on_input_event(
87 &mut self,
88 input: &Entity<InputState>,
89 event: &InputEvent,
90 window: &mut Window,
91 cx: &mut Context<Self>,
92 ) {
93 match event {
94 InputEvent::Change => {
95 self.query = input.read(cx).value().trim().to_owned();
96 cx.notify();
97 }
98 InputEvent::PressEnter { .. } => {
99 if let Some(first) = self.results().first().cloned() {
100 self.pick(&first, window, cx);
101 }
102 }
103 _ => {}
104 }
105 }
106
107 fn results(&self) -> Vec<String> {
108 if self.query.is_empty() {
109 let recent = self.recent.glyphs();
110 let fill = FALLBACK_RECENT
111 .iter()
112 .map(|glyph| (*glyph).to_owned())
113 .filter(|glyph| !recent.contains(glyph));
114 return recent
115 .iter()
116 .cloned()
117 .chain(fill)
118 .take(GRID_LIMIT)
119 .collect();
120 }
121 emoji::search(&self.query, self.recent.glyphs(), GRID_LIMIT)
122 .into_iter()
123 .map(|found| found.glyph.to_owned())
124 .collect()
125 }
126
127 fn pick(&mut self, glyph: &str, window: &mut Window, cx: &mut Context<Self>) {
128 self.recent.push(glyph);
129 self.recent.save(&self.app.read(cx).store);
130 if let Some((on_pick, popover)) = self.target.take() {
131 on_pick(glyph, window, cx);
132 popover
133 .update(cx, |state, cx| state.dismiss(window, cx))
134 .ok();
135 }
136 }
137
138 fn cell(&self, glyph: String, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
139 let picked = glyph.clone();
140 div()
141 .id(("reaction-picker-cell", index))
142 .size(px(CELL_SIZE))
143 .flex()
144 .items_center()
145 .justify_center()
146 .rounded(px(6.))
147 .text_size(px(20.))
148 .cursor_pointer()
149 .hover(|cell| cell.bg(theme::border_strong()))
150 .child(glyph)
151 .on_click(cx.listener(move |this, _, window, cx| this.pick(&picked, window, cx)))
152 }
153 }
154
155 impl Render for ReactionPicker {
156 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
157 let results = self.results();
158 let label = if self.query.is_empty() {
159 "Recently used"
160 } else if results.is_empty() {
161 "No emoji found"
162 } else {
163 "Results"
164 };
165 let quick = PICKER_QUICK
166 .iter()
167 .enumerate()
168 .map(|(index, glyph)| self.cell((*glyph).to_owned(), 1000 + index, cx))
169 .collect::<Vec<_>>();
170 let mut rows = Vec::new();
171 let mut row = Vec::new();
172 for (index, glyph) in results.into_iter().enumerate() {
173 row.push(self.cell(glyph, index, cx));
174 if row.len() == GRID_COLUMNS {
175 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
176 }
177 }
178 if !row.is_empty() {
179 rows.push(h_flex().gap(px(2.)).children(row));
180 }
181 v_flex()
182 .w(px(PICKER_WIDTH))
183 .gap(px(8.))
184 .p(px(8.))
185 .child(h_flex().gap(px(2.)).children(quick))
186 .child(
187 div()
188 .h(px(32.))
189 .px(px(8.))
190 .flex()
191 .items_center()
192 .rounded(px(8.))
193 .bg(theme::surface())
194 .border_1()
195 .border_color(theme::border_strong())
196 .child(Input::new(&self.input).appearance(false).bordered(false)),
197 )
198 .child(
199 div()
200 .text_size(px(11.))
201 .text_color(theme::text_muted())
202 .child(label),
203 )
204 .child(v_flex().gap(px(2.)).children(rows))
205 }
206 }
@@ -0,0 +1,206 @@
1use std::rc::Rc;
2
3use gpui_kit::base::PopoverState;
4use gpui_kit::component::{
5 h_flex,
6 input::{Input, InputEvent, InputState},
7 v_flex,
8};
9use gpui_kit::*;
10
11use crate::app_state::AppState;
12use crate::emoji;
13use crate::theme;
14
15pub const QUICK_REACTIONS: [&str; 4] = ["\u{1F44D}", "\u{2764}", "\u{1F602}", "\u{1F62E}"];
16const PICKER_QUICK: [&str; 6] = [
17 "\u{1F44D}",
18 "\u{2764}",
19 "\u{1F602}",
20 "\u{1F62E}",
21 "\u{1F622}",
22 "\u{1F64F}",
23];
24const FALLBACK_RECENT: [&str; 16] = [
25 "\u{1F389}",
26 "\u{1F525}",
27 "\u{1F440}",
28 "\u{2705}",
29 "\u{1F4AF}",
30 "\u{1F680}",
31 "\u{1F605}",
32 "\u{1F914}",
33 "\u{1F44F}",
34 "\u{1F64C}",
35 "\u{1F60A}",
36 "\u{1F4A1}",
37 "\u{1F4CC}",
38 "\u{1F41E}",
39 "\u{1F9EA}",
40 "\u{2615}",
41];
42const PICKER_WIDTH: f32 = 296.;
43const CELL_SIZE: f32 = 32.;
44const GRID_COLUMNS: usize = 8;
45const GRID_LIMIT: usize = 32;
46
47pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
48
49pub struct ReactionPicker {
50 app: Entity<AppState>,
51 input: Entity<InputState>,
52 query: String,
53 recent: emoji::Recent,
54 target: Option<(PickHandler, WeakEntity<PopoverState>)>,
55 _subscription: Subscription,
56}
57
58impl ReactionPicker {
59 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
60 let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search emoji"));
61 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 let recent = emoji::Recent::load(&app.read(cx).store);
63 ReactionPicker {
64 app,
65 input,
66 query: String::new(),
67 recent,
68 target: None,
69 _subscription: subscription,
70 }
71 }
72
73 pub fn set_target(&mut self, on_pick: PickHandler, popover: WeakEntity<PopoverState>) {
74 self.target = Some((on_pick, popover));
75 }
76
77 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
78 self.query.clear();
79 self.input.update(cx, |state, cx| {
80 state.set_value("", window, cx);
81 state.focus(window, cx);
82 });
83 cx.notify();
84 }
85
86 fn on_input_event(
87 &mut self,
88 input: &Entity<InputState>,
89 event: &InputEvent,
90 window: &mut Window,
91 cx: &mut Context<Self>,
92 ) {
93 match event {
94 InputEvent::Change => {
95 self.query = input.read(cx).value().trim().to_owned();
96 cx.notify();
97 }
98 InputEvent::PressEnter { .. } => {
99 if let Some(first) = self.results().first().cloned() {
100 self.pick(&first, window, cx);
101 }
102 }
103 _ => {}
104 }
105 }
106
107 fn results(&self) -> Vec<String> {
108 if self.query.is_empty() {
109 let recent = self.recent.glyphs();
110 let fill = FALLBACK_RECENT
111 .iter()
112 .map(|glyph| (*glyph).to_owned())
113 .filter(|glyph| !recent.contains(glyph));
114 return recent
115 .iter()
116 .cloned()
117 .chain(fill)
118 .take(GRID_LIMIT)
119 .collect();
120 }
121 emoji::search(&self.query, self.recent.glyphs(), GRID_LIMIT)
122 .into_iter()
123 .map(|found| found.glyph.to_owned())
124 .collect()
125 }
126
127 fn pick(&mut self, glyph: &str, window: &mut Window, cx: &mut Context<Self>) {
128 self.recent.push(glyph);
129 self.recent.save(&self.app.read(cx).store);
130 if let Some((on_pick, popover)) = self.target.take() {
131 on_pick(glyph, window, cx);
132 popover
133 .update(cx, |state, cx| state.dismiss(window, cx))
134 .ok();
135 }
136 }
137
138 fn cell(&self, glyph: String, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
139 let picked = glyph.clone();
140 div()
141 .id(("reaction-picker-cell", index))
142 .size(px(CELL_SIZE))
143 .flex()
144 .items_center()
145 .justify_center()
146 .rounded(px(6.))
147 .text_size(px(20.))
148 .cursor_pointer()
149 .hover(|cell| cell.bg(theme::border_strong()))
150 .child(glyph)
151 .on_click(cx.listener(move |this, _, window, cx| this.pick(&picked, window, cx)))
152 }
153}
154
155impl Render for ReactionPicker {
156 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
157 let results = self.results();
158 let label = if self.query.is_empty() {
159 "Recently used"
160 } else if results.is_empty() {
161 "No emoji found"
162 } else {
163 "Results"
164 };
165 let quick = PICKER_QUICK
166 .iter()
167 .enumerate()
168 .map(|(index, glyph)| self.cell((*glyph).to_owned(), 1000 + index, cx))
169 .collect::<Vec<_>>();
170 let mut rows = Vec::new();
171 let mut row = Vec::new();
172 for (index, glyph) in results.into_iter().enumerate() {
173 row.push(self.cell(glyph, index, cx));
174 if row.len() == GRID_COLUMNS {
175 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
176 }
177 }
178 if !row.is_empty() {
179 rows.push(h_flex().gap(px(2.)).children(row));
180 }
181 v_flex()
182 .w(px(PICKER_WIDTH))
183 .gap(px(8.))
184 .p(px(8.))
185 .child(h_flex().gap(px(2.)).children(quick))
186 .child(
187 div()
188 .h(px(32.))
189 .px(px(8.))
190 .flex()
191 .items_center()
192 .rounded(px(8.))
193 .bg(theme::surface())
194 .border_1()
195 .border_color(theme::border_strong())
196 .child(Input::new(&self.input).appearance(false).bordered(false)),
197 )
198 .child(
199 div()
200 .text_size(px(11.))
201 .text_color(theme::text_muted())
202 .child(label),
203 )
204 .child(v_flex().gap(px(2.)).children(rows))
205 }
206}