BlueGit

ict rusty-teams

feat(chat): make reactions instant and show own picks

- Show a reaction at once as a pending overlay, write it to the store on success, drop it on failure
- Highlight own reactions in the hover bar and the picker
- Hide the hover bar after a quick reaction until the pointer leaves the message
- Picker: click closes, Shift+click keeps it open for more
- Hover bar offers the four most used reactions

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
656a19d76ffc815d6d0f830dc4ae5407d73f5caa
Parent
2bc60c13
7 files changed +524 −98
crates/app/src/emoji/mod.rs +1 −1
@@ -245,7 +245,7 @@ mod tests {
245 245
246 246 #[test]
247 247 fn quick_reactions_lead_with_a_case_insensitive_query() {
248 let found = search("Herz", Recent::default().glyphs(), 7);
248 let found = search("Herz", &Recent::default().glyphs(), 7);
249 249 assert_eq!(found[0].glyph, "❤️");
250 250 assert_eq!(found[0].alias, Some("herz"));
251 251 }
@@ -245,7 +245,7 @@ mod tests {
245
245
246 #[test]
246 #[test]
247 fn quick_reactions_lead_with_a_case_insensitive_query() {
247 fn quick_reactions_lead_with_a_case_insensitive_query() {
248 let found = search("Herz", Recent::default().glyphs(), 7);
248 let found = search("Herz", &Recent::default().glyphs(), 7);
249 assert_eq!(found[0].glyph, "❤️");
249 assert_eq!(found[0].glyph, "❤️");
250 assert_eq!(found[0].alias, Some("herz"));
250 assert_eq!(found[0].alias, Some("herz"));
251 }
251 }
crates/app/src/emoji/recent.rs +125 −14
@@ -1,13 +1,29 @@
1 use crate::rows::reaction_glyph;
2
1 3 const LIMIT: usize = 24;
2 4 const META_KEY: &str = "emoji_recent";
3 5 const TEAMS_QUICK_REACTIONS: [&str; 6] = ["👍", "❤️", "😆", "😮", "😢", "😡"];
6 const COUNT_SEPARATOR: char = '\t';
4 7
5 8 #[derive(Debug, Clone, PartialEq, Eq)]
6 pub struct Recent(Vec<String>);
9 struct Entry {
10 glyph: String,
11 uses: u32,
12 }
13
14 #[derive(Debug, Clone, PartialEq, Eq)]
15 pub struct Recent(Vec<Entry>);
7 16
8 17 impl Default for Recent {
9 18 fn default() -> Self {
10 Recent(TEAMS_QUICK_REACTIONS.map(str::to_owned).to_vec())
19 Recent(
20 TEAMS_QUICK_REACTIONS
21 .map(|glyph| Entry {
22 glyph: glyph.to_owned(),
23 uses: 0,
24 })
25 .to_vec(),
26 )
11 27 }
12 28 }
13 29
@@ -19,28 +35,77 @@ impl Recent {
19 35 }
20 36 }
21 37
38 pub fn reload(&mut self, store: &store::Store) {
39 *self = Self::load(store);
40 }
41
22 42 pub fn save(&self, store: &store::Store) {
23 store.set_meta(META_KEY, &self.0.join("\n")).ok();
43 store.set_meta(META_KEY, &self.serialize()).ok();
44 }
45
46 fn serialize(&self) -> String {
47 self.0
48 .iter()
49 .map(|entry| format!("{}{COUNT_SEPARATOR}{}", entry.glyph, entry.uses))
50 .collect::<Vec<_>>()
51 .join("\n")
24 52 }
25 53
26 54 fn parse(stored: &str) -> Self {
27 55 Recent(
28 56 stored
29 57 .lines()
30 .filter(|glyph| !glyph.is_empty())
58 .filter(|line| !line.is_empty())
31 59 .take(LIMIT)
32 .map(str::to_owned)
60 .map(|line| match line.split_once(COUNT_SEPARATOR) {
61 Some((glyph, uses)) => Entry {
62 glyph: glyph.to_owned(),
63 uses: uses.parse().unwrap_or(0),
64 },
65 None => Entry {
66 glyph: line.to_owned(),
67 uses: 0,
68 },
69 })
33 70 .collect(),
34 71 )
35 72 }
36 73
37 pub fn glyphs(&self) -> &[String] {
38 &self.0
74 pub fn glyphs(&self) -> Vec<String> {
75 self.0.iter().map(|entry| entry.glyph.clone()).collect()
76 }
77
78 pub fn most_used(&self, count: usize) -> Vec<String> {
79 let mut ranked: Vec<&Entry> = self.0.iter().collect();
80 ranked.sort_by_key(|entry| std::cmp::Reverse(entry.uses));
81 ranked
82 .into_iter()
83 .take(count)
84 .map(|entry| entry.glyph.clone())
85 .collect()
39 86 }
40 87
41 88 pub fn push(&mut self, glyph: &str) {
42 self.0.retain(|known| known != glyph);
43 self.0.insert(0, glyph.to_owned());
89 self.bump(glyph, 0);
90 }
91
92 pub fn record_use(&mut self, glyph: &str) {
93 self.bump(glyph, 1);
94 }
95
96 fn bump(&mut self, glyph: &str, uses: u32) {
97 let previous_uses = self
98 .0
99 .iter()
100 .position(|entry| reaction_glyph(&entry.glyph) == reaction_glyph(glyph))
101 .map_or(0, |position| self.0.remove(position).uses);
102 self.0.insert(
103 0,
104 Entry {
105 glyph: glyph.to_owned(),
106 uses: previous_uses + uses,
107 },
108 );
44 109 self.0.truncate(LIMIT);
45 110 }
46 111 }
@@ -52,14 +117,15 @@ mod tests {
52 117 #[test]
53 118 fn starts_with_the_teams_quick_reactions() {
54 119 assert_eq!(Recent::default().glyphs()[..2], ["👍", "❤️"]);
120 assert_eq!(Recent::default().most_used(4), ["👍", "❤️", "😆", "😮"]);
55 121 }
56 122
57 123 #[test]
58 124 fn newest_first_without_duplicates() {
59 125 let mut recent = Recent::parse("");
60 recent.push("👍");
61 recent.push("❤️");
62 recent.push("👍");
126 recent.record_use("👍");
127 recent.record_use("❤️");
128 recent.record_use("👍");
63 129 assert_eq!(recent.glyphs(), ["👍", "❤️"]);
64 130 }
65 131
@@ -67,9 +133,54 @@ mod tests {
67 133 fn keeps_at_most_the_limit() {
68 134 let mut recent = Recent::parse("");
69 135 for index in 0..LIMIT + 5 {
70 recent.push(&index.to_string());
136 recent.record_use(&index.to_string());
71 137 }
72 138 assert_eq!(recent.glyphs().len(), LIMIT);
73 assert_eq!(Recent::parse(&recent.glyphs().join("\n")), recent);
139 assert_eq!(Recent::parse(&recent.serialize()), recent);
140 }
141
142 #[test]
143 fn ranks_by_count_then_recency() {
144 let mut recent = Recent::parse("");
145 for glyph in ["🎉", "🎉", "🔥", "👀", "👀", "✅", "🚀"] {
146 recent.record_use(glyph);
147 }
148 assert_eq!(recent.most_used(4), ["👀", "🎉", "🚀", "✅"]);
149 }
150
151 #[test]
152 fn matches_glyphs_with_and_without_variation_selector() {
153 let mut recent = Recent::parse("");
154 recent.record_use("\u{2764}\u{FE0F}");
155 recent.record_use("\u{2764}");
156 assert_eq!(recent.glyphs().len(), 1);
157 assert_eq!(recent.most_used(1), ["\u{2764}"]);
158 }
159
160 #[test]
161 fn push_moves_to_front_without_counting() {
162 let mut recent = Recent::default();
163 recent.push("😮");
164 assert_eq!(recent.glyphs()[0], "😮");
165 assert_eq!(recent.most_used(1), ["😮"]);
166 recent.record_use("👍");
167 assert_eq!(recent.most_used(1), ["👍"]);
168 }
169
170 #[test]
171 fn legacy_values_without_counts_still_load() {
172 let recent = Recent::parse("🎉\n👍\n");
173 assert_eq!(recent.glyphs(), ["🎉", "👍"]);
174 assert_eq!(recent.most_used(2), ["🎉", "👍"]);
175 }
176
177 #[test]
178 fn counts_survive_a_round_trip() {
179 let mut recent = Recent::parse("");
180 recent.record_use("👍");
181 recent.record_use("👍");
182 recent.record_use("🔥");
183 assert_eq!(Recent::parse(&recent.serialize()), recent);
184 assert_eq!(recent.most_used(1), ["👍"]);
74 185 }
75 186 }
@@ -1,13 +1,29 @@
1use crate::rows::reaction_glyph;
2
1const LIMIT: usize = 24;
3const LIMIT: usize = 24;
2const META_KEY: &str = "emoji_recent";
4const META_KEY: &str = "emoji_recent";
3const TEAMS_QUICK_REACTIONS: [&str; 6] = ["👍", "❤️", "😆", "😮", "😢", "😡"];
5const TEAMS_QUICK_REACTIONS: [&str; 6] = ["👍", "❤️", "😆", "😮", "😢", "😡"];
6const COUNT_SEPARATOR: char = '\t';
4
7
5#[derive(Debug, Clone, PartialEq, Eq)]
8#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Recent(Vec<String>);
9struct Entry {
10 glyph: String,
11 uses: u32,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct Recent(Vec<Entry>);
7
16
8impl Default for Recent {
17impl Default for Recent {
9 fn default() -> Self {
18 fn default() -> Self {
10 Recent(TEAMS_QUICK_REACTIONS.map(str::to_owned).to_vec())
19 Recent(
20 TEAMS_QUICK_REACTIONS
21 .map(|glyph| Entry {
22 glyph: glyph.to_owned(),
23 uses: 0,
24 })
25 .to_vec(),
26 )
11 }
27 }
12}
28}
13
29
@@ -19,28 +35,77 @@ impl Recent {
19 }
35 }
20 }
36 }
21
37
38 pub fn reload(&mut self, store: &store::Store) {
39 *self = Self::load(store);
40 }
41
22 pub fn save(&self, store: &store::Store) {
42 pub fn save(&self, store: &store::Store) {
23 store.set_meta(META_KEY, &self.0.join("\n")).ok();
43 store.set_meta(META_KEY, &self.serialize()).ok();
44 }
45
46 fn serialize(&self) -> String {
47 self.0
48 .iter()
49 .map(|entry| format!("{}{COUNT_SEPARATOR}{}", entry.glyph, entry.uses))
50 .collect::<Vec<_>>()
51 .join("\n")
24 }
52 }
25
53
26 fn parse(stored: &str) -> Self {
54 fn parse(stored: &str) -> Self {
27 Recent(
55 Recent(
28 stored
56 stored
29 .lines()
57 .lines()
30 .filter(|glyph| !glyph.is_empty())
58 .filter(|line| !line.is_empty())
31 .take(LIMIT)
59 .take(LIMIT)
32 .map(str::to_owned)
60 .map(|line| match line.split_once(COUNT_SEPARATOR) {
61 Some((glyph, uses)) => Entry {
62 glyph: glyph.to_owned(),
63 uses: uses.parse().unwrap_or(0),
64 },
65 None => Entry {
66 glyph: line.to_owned(),
67 uses: 0,
68 },
69 })
33 .collect(),
70 .collect(),
34 )
71 )
35 }
72 }
36
73
37 pub fn glyphs(&self) -> &[String] {
74 pub fn glyphs(&self) -> Vec<String> {
38 &self.0
75 self.0.iter().map(|entry| entry.glyph.clone()).collect()
76 }
77
78 pub fn most_used(&self, count: usize) -> Vec<String> {
79 let mut ranked: Vec<&Entry> = self.0.iter().collect();
80 ranked.sort_by_key(|entry| std::cmp::Reverse(entry.uses));
81 ranked
82 .into_iter()
83 .take(count)
84 .map(|entry| entry.glyph.clone())
85 .collect()
39 }
86 }
40
87
41 pub fn push(&mut self, glyph: &str) {
88 pub fn push(&mut self, glyph: &str) {
42 self.0.retain(|known| known != glyph);
89 self.bump(glyph, 0);
43 self.0.insert(0, glyph.to_owned());
90 }
91
92 pub fn record_use(&mut self, glyph: &str) {
93 self.bump(glyph, 1);
94 }
95
96 fn bump(&mut self, glyph: &str, uses: u32) {
97 let previous_uses = self
98 .0
99 .iter()
100 .position(|entry| reaction_glyph(&entry.glyph) == reaction_glyph(glyph))
101 .map_or(0, |position| self.0.remove(position).uses);
102 self.0.insert(
103 0,
104 Entry {
105 glyph: glyph.to_owned(),
106 uses: previous_uses + uses,
107 },
108 );
44 self.0.truncate(LIMIT);
109 self.0.truncate(LIMIT);
45 }
110 }
46}
111}
@@ -52,14 +117,15 @@ mod tests {
52 #[test]
117 #[test]
53 fn starts_with_the_teams_quick_reactions() {
118 fn starts_with_the_teams_quick_reactions() {
54 assert_eq!(Recent::default().glyphs()[..2], ["👍", "❤️"]);
119 assert_eq!(Recent::default().glyphs()[..2], ["👍", "❤️"]);
120 assert_eq!(Recent::default().most_used(4), ["👍", "❤️", "😆", "😮"]);
55 }
121 }
56
122
57 #[test]
123 #[test]
58 fn newest_first_without_duplicates() {
124 fn newest_first_without_duplicates() {
59 let mut recent = Recent::parse("");
125 let mut recent = Recent::parse("");
60 recent.push("👍");
126 recent.record_use("👍");
61 recent.push("❤️");
127 recent.record_use("❤️");
62 recent.push("👍");
128 recent.record_use("👍");
63 assert_eq!(recent.glyphs(), ["👍", "❤️"]);
129 assert_eq!(recent.glyphs(), ["👍", "❤️"]);
64 }
130 }
65
131
@@ -67,9 +133,54 @@ mod tests {
67 fn keeps_at_most_the_limit() {
133 fn keeps_at_most_the_limit() {
68 let mut recent = Recent::parse("");
134 let mut recent = Recent::parse("");
69 for index in 0..LIMIT + 5 {
135 for index in 0..LIMIT + 5 {
70 recent.push(&index.to_string());
136 recent.record_use(&index.to_string());
71 }
137 }
72 assert_eq!(recent.glyphs().len(), LIMIT);
138 assert_eq!(recent.glyphs().len(), LIMIT);
73 assert_eq!(Recent::parse(&recent.glyphs().join("\n")), recent);
139 assert_eq!(Recent::parse(&recent.serialize()), recent);
140 }
141
142 #[test]
143 fn ranks_by_count_then_recency() {
144 let mut recent = Recent::parse("");
145 for glyph in ["🎉", "🎉", "🔥", "👀", "👀", "✅", "🚀"] {
146 recent.record_use(glyph);
147 }
148 assert_eq!(recent.most_used(4), ["👀", "🎉", "🚀", "✅"]);
149 }
150
151 #[test]
152 fn matches_glyphs_with_and_without_variation_selector() {
153 let mut recent = Recent::parse("");
154 recent.record_use("\u{2764}\u{FE0F}");
155 recent.record_use("\u{2764}");
156 assert_eq!(recent.glyphs().len(), 1);
157 assert_eq!(recent.most_used(1), ["\u{2764}"]);
158 }
159
160 #[test]
161 fn push_moves_to_front_without_counting() {
162 let mut recent = Recent::default();
163 recent.push("😮");
164 assert_eq!(recent.glyphs()[0], "😮");
165 assert_eq!(recent.most_used(1), ["😮"]);
166 recent.record_use("👍");
167 assert_eq!(recent.most_used(1), ["👍"]);
168 }
169
170 #[test]
171 fn legacy_values_without_counts_still_load() {
172 let recent = Recent::parse("🎉\n👍\n");
173 assert_eq!(recent.glyphs(), ["🎉", "👍"]);
174 assert_eq!(recent.most_used(2), ["🎉", "👍"]);
175 }
176
177 #[test]
178 fn counts_survive_a_round_trip() {
179 let mut recent = Recent::parse("");
180 recent.record_use("👍");
181 recent.record_use("👍");
182 recent.record_use("🔥");
183 assert_eq!(Recent::parse(&recent.serialize()), recent);
184 assert_eq!(recent.most_used(1), ["👍"]);
74 }
185 }
75}
186}
crates/app/src/rows.rs +123 −1
@@ -302,6 +302,52 @@ pub fn reaction_type_for(glyph: &str) -> String {
302 302 .map_or_else(|| bare.to_owned(), str::to_owned)
303 303 }
304 304
305 pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
306
307 fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool {
308 my_user_id.is_some()
309 && reaction.user_id.as_deref() == my_user_id
310 && reaction_glyph(&reaction.reaction_type) == wanted
311 }
312
313 pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool {
314 let wanted = reaction_glyph(glyph);
315 reactions
316 .iter()
317 .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
318 }
319
320 pub fn set_own_reaction(
321 reactions: &mut Vec<ReactionInfo>,
322 glyph: &str,
323 my_user_id: Option<&str>,
324 present: bool,
325 now: DateTime<Utc>,
326 ) {
327 let wanted = reaction_glyph(glyph);
328 if !present {
329 reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id));
330 } else if !has_own_reaction(reactions, glyph, my_user_id) {
331 reactions.push(ReactionInfo {
332 reaction_type: reaction_type_for(glyph),
333 user_id: my_user_id.map(str::to_owned),
334 user_name: Some("You".to_owned()),
335 created_at: Some(now),
336 });
337 }
338 }
339
340 pub fn apply_pending_reactions(
341 reactions: &mut Vec<ReactionInfo>,
342 pending: Option<&Vec<(String, bool)>>,
343 my_user_id: Option<&str>,
344 now: DateTime<Utc>,
345 ) {
346 for (glyph, present) in pending.into_iter().flatten() {
347 set_own_reaction(reactions, glyph, my_user_id, *present, now);
348 }
349 }
350
305 351 pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
306 352 let my_user_id = context.my_user_id.as_deref();
307 353 let mut chips: Vec<ReactionChip> = Vec::new();
@@ -406,6 +452,18 @@ pub struct RowContext {
406 452 pub today: NaiveDate,
407 453 pub my_user_id: Option<String>,
408 454 pub names: HashMap<String, String>,
455 pub pending_reactions: PendingReactions,
456 }
457
458 fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
459 let mut visible = reactions(record);
460 apply_pending_reactions(
461 &mut visible,
462 context.pending_reactions.get(&record.message_id),
463 context.my_user_id.as_deref(),
464 Utc::now(),
465 );
466 visible
409 467 }
410 468
411 469 pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
@@ -436,7 +494,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
436 494 blocks,
437 495 edited: record.edited_at.is_some() && !record.deleted,
438 496 deleted: record.deleted,
439 reactions: reaction_chips(&reactions(record), context),
497 reactions: reaction_chips(&visible_reactions(record, context), context),
440 498 images,
441 499 local_images: Vec::new(),
442 500 files: files(record),
@@ -655,6 +713,69 @@ mod tests {
655 713 }
656 714 }
657 715
716 fn own_reaction(reaction_type: &str) -> ReactionInfo {
717 ReactionInfo {
718 reaction_type: reaction_type.into(),
719 user_id: Some("me".into()),
720 user_name: None,
721 created_at: None,
722 }
723 }
724
725 #[test]
726 fn setting_a_reaction_is_idempotent_and_only_touches_mine() {
727 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
728 let other = ReactionInfo {
729 user_id: Some("them".into()),
730 ..own_reaction("like")
731 };
732 let mut reactions = vec![other.clone()];
733 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
734 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
735 assert_eq!(reactions.len(), 2);
736 assert_eq!(reactions[1].reaction_type, "like");
737 assert_eq!(reactions[1].user_id.as_deref(), Some("me"));
738 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
739 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
740 assert_eq!(reactions, vec![other]);
741 }
742
743 #[test]
744 fn setting_matches_legacy_names_and_variation_selectors() {
745 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
746 let mut reactions = vec![own_reaction("heart")];
747 assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me")));
748 set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now);
749 assert!(reactions.is_empty());
750 set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now);
751 assert_eq!(reactions[0].reaction_type, "\u{1F389}");
752 }
753
754 #[test]
755 fn setting_without_a_known_user_never_matches() {
756 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
757 let mut reactions = Vec::new();
758 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
759 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
760 assert_eq!(reactions.len(), 2);
761 }
762
763 #[test]
764 fn pending_reactions_overlay_the_stored_ones() {
765 let mut stored = record("a", None, 8, 6);
766 stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap();
767 let mut context = context();
768 context.my_user_id = Some("me".into());
769 context.pending_reactions.insert(
770 "a".into(),
771 vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)],
772 );
773 let chips = message_row(&stored, &context).reactions;
774 assert_eq!(chips.len(), 1);
775 assert_eq!(chips[0].reaction_type, "\u{1F389}");
776 assert!(chips[0].mine);
777 }
778
658 779 #[test]
659 780 fn reaction_type_maps_classic_glyphs_to_names() {
660 781 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
@@ -708,6 +829,7 @@ mod tests {
708 829 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
709 830 my_user_id: None,
710 831 names: HashMap::new(),
832 pending_reactions: HashMap::new(),
711 833 }
712 834 }
713 835
@@ -302,6 +302,52 @@ pub fn reaction_type_for(glyph: &str) -> String {
302 .map_or_else(|| bare.to_owned(), str::to_owned)
302 .map_or_else(|| bare.to_owned(), str::to_owned)
303}
303}
304
304
305pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
306
307fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool {
308 my_user_id.is_some()
309 && reaction.user_id.as_deref() == my_user_id
310 && reaction_glyph(&reaction.reaction_type) == wanted
311}
312
313pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool {
314 let wanted = reaction_glyph(glyph);
315 reactions
316 .iter()
317 .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
318}
319
320pub fn set_own_reaction(
321 reactions: &mut Vec<ReactionInfo>,
322 glyph: &str,
323 my_user_id: Option<&str>,
324 present: bool,
325 now: DateTime<Utc>,
326) {
327 let wanted = reaction_glyph(glyph);
328 if !present {
329 reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id));
330 } else if !has_own_reaction(reactions, glyph, my_user_id) {
331 reactions.push(ReactionInfo {
332 reaction_type: reaction_type_for(glyph),
333 user_id: my_user_id.map(str::to_owned),
334 user_name: Some("You".to_owned()),
335 created_at: Some(now),
336 });
337 }
338}
339
340pub fn apply_pending_reactions(
341 reactions: &mut Vec<ReactionInfo>,
342 pending: Option<&Vec<(String, bool)>>,
343 my_user_id: Option<&str>,
344 now: DateTime<Utc>,
345) {
346 for (glyph, present) in pending.into_iter().flatten() {
347 set_own_reaction(reactions, glyph, my_user_id, *present, now);
348 }
349}
350
305pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
351pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
306 let my_user_id = context.my_user_id.as_deref();
352 let my_user_id = context.my_user_id.as_deref();
307 let mut chips: Vec<ReactionChip> = Vec::new();
353 let mut chips: Vec<ReactionChip> = Vec::new();
@@ -406,6 +452,18 @@ pub struct RowContext {
406 pub today: NaiveDate,
452 pub today: NaiveDate,
407 pub my_user_id: Option<String>,
453 pub my_user_id: Option<String>,
408 pub names: HashMap<String, String>,
454 pub names: HashMap<String, String>,
455 pub pending_reactions: PendingReactions,
456}
457
458fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
459 let mut visible = reactions(record);
460 apply_pending_reactions(
461 &mut visible,
462 context.pending_reactions.get(&record.message_id),
463 context.my_user_id.as_deref(),
464 Utc::now(),
465 );
466 visible
409}
467}
410
468
411pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
469pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
@@ -436,7 +494,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
436 blocks,
494 blocks,
437 edited: record.edited_at.is_some() && !record.deleted,
495 edited: record.edited_at.is_some() && !record.deleted,
438 deleted: record.deleted,
496 deleted: record.deleted,
439 reactions: reaction_chips(&reactions(record), context),
497 reactions: reaction_chips(&visible_reactions(record, context), context),
440 images,
498 images,
441 local_images: Vec::new(),
499 local_images: Vec::new(),
442 files: files(record),
500 files: files(record),
@@ -655,6 +713,69 @@ mod tests {
655 }
713 }
656 }
714 }
657
715
716 fn own_reaction(reaction_type: &str) -> ReactionInfo {
717 ReactionInfo {
718 reaction_type: reaction_type.into(),
719 user_id: Some("me".into()),
720 user_name: None,
721 created_at: None,
722 }
723 }
724
725 #[test]
726 fn setting_a_reaction_is_idempotent_and_only_touches_mine() {
727 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
728 let other = ReactionInfo {
729 user_id: Some("them".into()),
730 ..own_reaction("like")
731 };
732 let mut reactions = vec![other.clone()];
733 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
734 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
735 assert_eq!(reactions.len(), 2);
736 assert_eq!(reactions[1].reaction_type, "like");
737 assert_eq!(reactions[1].user_id.as_deref(), Some("me"));
738 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
739 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
740 assert_eq!(reactions, vec![other]);
741 }
742
743 #[test]
744 fn setting_matches_legacy_names_and_variation_selectors() {
745 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
746 let mut reactions = vec![own_reaction("heart")];
747 assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me")));
748 set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now);
749 assert!(reactions.is_empty());
750 set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now);
751 assert_eq!(reactions[0].reaction_type, "\u{1F389}");
752 }
753
754 #[test]
755 fn setting_without_a_known_user_never_matches() {
756 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
757 let mut reactions = Vec::new();
758 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
759 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
760 assert_eq!(reactions.len(), 2);
761 }
762
763 #[test]
764 fn pending_reactions_overlay_the_stored_ones() {
765 let mut stored = record("a", None, 8, 6);
766 stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap();
767 let mut context = context();
768 context.my_user_id = Some("me".into());
769 context.pending_reactions.insert(
770 "a".into(),
771 vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)],
772 );
773 let chips = message_row(&stored, &context).reactions;
774 assert_eq!(chips.len(), 1);
775 assert_eq!(chips[0].reaction_type, "\u{1F389}");
776 assert!(chips[0].mine);
777 }
778
658 #[test]
779 #[test]
659 fn reaction_type_maps_classic_glyphs_to_names() {
780 fn reaction_type_maps_classic_glyphs_to_names() {
660 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
781 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
@@ -708,6 +829,7 @@ mod tests {
708 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
829 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
709 my_user_id: None,
830 my_user_id: None,
710 names: HashMap::new(),
831 names: HashMap::new(),
832 pending_reactions: HashMap::new(),
711 }
833 }
712 }
834 }
713
835
crates/app/src/views/composer.rs +4 −2
@@ -1109,8 +1109,10 @@ impl Composer {
1109 1109 }
1110 1110
1111 1111 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
1112 let store = &self.app.read(cx).store;
1113 self.recent_emoji.reload(store);
1112 1114 self.recent_emoji.push(glyph);
1113 self.recent_emoji.save(&self.app.read(cx).store);
1115 self.recent_emoji.save(store);
1114 1116 }
1115 1117
1116 1118 fn update_emoji(&mut self, cx: &mut Context<Self>) {
@@ -1132,7 +1134,7 @@ impl Composer {
1132 1134 if unchanged {
1133 1135 return;
1134 1136 }
1135 let matches = emoji::search(&query, self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1137 let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1136 1138 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
1137 1139 }
1138 1140
@@ -1109,8 +1109,10 @@ impl Composer {
1109 }
1109 }
1110
1110
1111 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
1111 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
1112 let store = &self.app.read(cx).store;
1113 self.recent_emoji.reload(store);
1112 self.recent_emoji.push(glyph);
1114 self.recent_emoji.push(glyph);
1113 self.recent_emoji.save(&self.app.read(cx).store);
1115 self.recent_emoji.save(store);
1114 }
1116 }
1115
1117
1116 fn update_emoji(&mut self, cx: &mut Context<Self>) {
1118 fn update_emoji(&mut self, cx: &mut Context<Self>) {
@@ -1132,7 +1134,7 @@ impl Composer {
1132 if unchanged {
1134 if unchanged {
1133 return;
1135 return;
1134 }
1136 }
1135 let matches = emoji::search(&query, self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1137 let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1136 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
1138 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
1137 }
1139 }
1138
1140
crates/app/src/views/conversation.rs +176 −50
@@ -1,5 +1,5 @@
1 1 use std::cell::RefCell;
2 use std::collections::HashMap;
2 use std::collections::{HashMap, HashSet};
3 3 use std::path::{Path, PathBuf};
4 4 use std::rc::Rc;
5 5 use std::time::{Duration, Instant};
@@ -21,7 +21,7 @@ use teams_core::{FileCard, ImageRef};
21 21 use super::attachments::FileActions;
22 22 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23 23 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24 use super::message_actions::{Action, MessageMenu};
24 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
25 25 use super::message_row::{RowActions, render_message_row, render_skeleton_row};
26 26 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
27 27 use super::reaction_picker::{PickHandler, ReactionPicker};
@@ -31,14 +31,15 @@ use crate::app_state::{AppEvent, AppState, Selection, selection_title};
31 31 use crate::backend::Engine;
32 32 use crate::data::{is_one_on_one, others};
33 33 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
34 use crate::emoji;
34 35 use crate::reaction_model::UNKNOWN_REACTOR;
35 36 use crate::read_state::{ReadTrigger, plan_read};
36 37 use crate::render::layout_blocks;
37 38 use crate::rows::{
38 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, api_reaction,
39 assign_series, changed_indices, diff_keys, flat_rows, message_draft, message_text,
40 placeholder_rows, reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows,
41 thread_rows, trailing_skeleton,
39 Delivery, LocalImage, MessageRow, PendingReactions, Receipt, Row, RowContext, Series,
40 StartInfo, api_reaction, apply_pending_reactions, assign_series, changed_indices, diff_keys,
41 flat_rows, has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph,
42 reply_excerpt, set_own_reaction, thread_list_rows, thread_rows, trailing_skeleton,
42 43 };
43 44 use crate::runtime;
44 45 use crate::sidebar_model::{AvatarSpec, Face};
@@ -128,10 +129,13 @@ pub struct ConversationView {
128 129 pending: Vec<MessageRow>,
129 130 pending_counter: usize,
130 131 pending_outgoing: HashMap<String, Outgoing>,
132 pending_reactions: PendingReactions,
131 133 downloads: Downloads,
132 134 hovered_message: Option<String>,
133 135 toolbar_hovered: Option<String>,
134 136 toolbar_pinned: Option<String>,
137 toolbar_suppressed: Option<String>,
138 recent: Entity<emoji::Recent>,
135 139 picker: Entity<ReactionPicker>,
136 140 reaction_details: Option<ReactionDetails>,
137 141 highlighted_message: Option<String>,
@@ -323,7 +327,8 @@ impl ConversationView {
323 327 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
324 328 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
325 329 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
326 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
330 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
331 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
327 332 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
328 333 let subscriptions = vec![
329 334 cx.subscribe_in(&app, window, Self::on_app_event),
@@ -349,10 +354,13 @@ impl ConversationView {
349 354 pending: Vec::new(),
350 355 pending_counter: 0,
351 356 pending_outgoing: HashMap::new(),
357 pending_reactions: HashMap::new(),
352 358 downloads: Downloads::default(),
353 359 hovered_message: None,
354 360 toolbar_hovered: None,
355 361 toolbar_pinned: None,
362 toolbar_suppressed: None,
363 recent,
356 364 picker,
357 365 reaction_details: None,
358 366 highlighted_message: None,
@@ -488,6 +496,7 @@ impl ConversationView {
488 496 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
489 497 self.toolbar_hovered = None;
490 498 self.toolbar_pinned = None;
499 self.toolbar_suppressed = None;
491 500 let title = selection_title(&self.app.read(cx).sidebar, &selection);
492 501 let mode = match selection {
493 502 Selection::Chat(_) => ViewMode::Flat,
@@ -544,6 +553,7 @@ impl ConversationView {
544 553 self.draft_error = None;
545 554 self.toolbar_hovered = None;
546 555 self.toolbar_pinned = None;
556 self.toolbar_suppressed = None;
547 557 self.hovered_message = None;
548 558 self.sync_generation += 1;
549 559 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
@@ -836,6 +846,7 @@ impl ConversationView {
836 846 today: now.date_naive(),
837 847 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
838 848 names,
849 pending_reactions: self.pending_reactions.clone(),
839 850 }
840 851 }
841 852
@@ -1833,6 +1844,20 @@ impl ConversationView {
1833 1844 } else if target.as_deref() == Some(key) {
1834 1845 *target = None;
1835 1846 }
1847 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
1848 && self.hovered_message.as_deref() != Some(suppressed)
1849 && self.toolbar_hovered.as_deref() != Some(suppressed)
1850 {
1851 self.toolbar_suppressed = None;
1852 }
1853 cx.notify();
1854 }
1855
1856 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
1857 if self.toolbar_hovered.as_deref() == Some(key) {
1858 self.toolbar_hovered = None;
1859 }
1860 self.toolbar_suppressed = Some(key.to_owned());
1836 1861 cx.notify();
1837 1862 }
1838 1863
@@ -1846,21 +1871,26 @@ impl ConversationView {
1846 1871 }
1847 1872
1848 1873 fn toolbar_visible(&self, key: &str) -> bool {
1849 self.toolbar_pinned
1850 .as_deref()
1851 .or(self.toolbar_hovered.as_deref())
1852 .or(self.hovered_message.as_deref())
1853 == Some(key)
1874 self.toolbar_suppressed.as_deref() != Some(key)
1875 && self
1876 .toolbar_pinned
1877 .as_deref()
1878 .or(self.toolbar_hovered.as_deref())
1879 .or(self.hovered_message.as_deref())
1880 == Some(key)
1854 1881 }
1855 1882
1856 1883 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
1857 1884 let Some(conversation_id) = self.conversation_id() else {
1858 1885 return;
1859 1886 };
1860 let reaction_type = reaction_type_for(glyph);
1861 let wanted = reaction_glyph(glyph);
1862 1887 let state = self.app.read(cx);
1863 1888 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1889 let engine = engine.filter(|_| !mode.read_only);
1890 if !mode.demo && engine.is_none() {
1891 self.show_notice("Read-only mode: reaction not sent", cx);
1892 return;
1893 }
1864 1894 let my_user_id = self.row_context(cx).my_user_id;
1865 1895 let Some(mut record) = store
1866 1896 .messages_by_id(&conversation_id, &[message_id.to_owned()])
@@ -1869,47 +1899,122 @@ impl ConversationView {
1869 1899 else {
1870 1900 return;
1871 1901 };
1872 let mut reactions = teams_core::reactions(&record);
1873 let mine = |reaction: &teams_core::ReactionInfo| {
1874 reaction_glyph(&reaction.reaction_type) == wanted
1875 && my_user_id.is_some()
1876 && reaction.user_id == my_user_id
1877 };
1878 let remove = reactions.iter().any(mine);
1879 if mode.demo {
1880 if remove {
1881 reactions.retain(|reaction| !mine(reaction));
1882 } else {
1883 reactions.push(teams_core::ReactionInfo {
1884 reaction_type: reaction_type.clone(),
1885 user_id: my_user_id.clone(),
1886 user_name: Some("You".to_owned()),
1887 created_at: Some(Utc::now()),
1888 });
1889 }
1902 let wanted = reaction_glyph(glyph);
1903 let mut visible = teams_core::reactions(&record);
1904 apply_pending_reactions(
1905 &mut visible,
1906 self.pending_reactions.get(message_id),
1907 my_user_id.as_deref(),
1908 Utc::now(),
1909 );
1910 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
1911 let Some(engine) = engine.filter(|_| !mode.demo) else {
1912 let mut reactions = teams_core::reactions(&record);
1913 set_own_reaction(
1914 &mut reactions,
1915 glyph,
1916 my_user_id.as_deref(),
1917 added,
1918 Utc::now(),
1919 );
1890 1920 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1891 1921 let _ = store.upsert_messages(std::slice::from_ref(&record));
1922 if added {
1923 self.record_reaction_use(glyph, cx);
1924 }
1892 1925 self.rebuild(false, cx);
1893 1926 return;
1894 }
1895 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1896 self.show_notice("Read-only mode: reaction not sent", cx);
1897 return;
1898 1927 };
1899 let message_id = message_id.to_owned();
1928 let entries = self
1929 .pending_reactions
1930 .entry(message_id.to_owned())
1931 .or_default();
1932 entries.retain(|(pending, _)| *pending != wanted);
1933 entries.push((wanted.clone(), added));
1934 self.rebuild(false, cx);
1935 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
1900 1936 let reaction_type = api_reaction(&wanted);
1901 let receiver = runtime::spawn(async move {
1902 if remove {
1903 engine
1904 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1905 .await
1906 } else {
1907 engine
1908 .set_reaction(&conversation_id, &message_id, &reaction_type)
1909 .await
1937 let receiver = runtime::spawn({
1938 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
1939 async move {
1940 if added {
1941 engine
1942 .set_reaction(&conversation_id, &message_id, &reaction_type)
1943 .await
1944 } else {
1945 engine
1946 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1947 .await
1948 }
1910 1949 }
1911 1950 });
1912 self.report_failure(receiver, "Reaction failed", cx);
1951 cx.spawn(async move |this, cx| {
1952 let outcome = match receiver.await {
1953 Ok(Ok(())) => Ok(()),
1954 Ok(Err(error)) => Err(short_error(&error)),
1955 Err(_) => Err("cancelled".to_owned()),
1956 };
1957 this.update(cx, |this, cx| {
1958 this.finish_reaction(&conversation_id, &message_id, &glyph, added, outcome, cx)
1959 })
1960 .ok();
1961 })
1962 .detach();
1963 }
1964
1965 fn finish_reaction(
1966 &mut self,
1967 conversation_id: &str,
1968 message_id: &str,
1969 glyph: &str,
1970 added: bool,
1971 outcome: Result<(), String>,
1972 cx: &mut Context<Self>,
1973 ) {
1974 let wanted = reaction_glyph(glyph);
1975 let store = self.app.read(cx).store.clone();
1976 if outcome.is_ok() {
1977 let my_user_id = self.row_context(cx).my_user_id;
1978 if let Some(mut record) = store
1979 .messages_by_id(conversation_id, &[message_id.to_owned()])
1980 .ok()
1981 .and_then(|mut found| found.remove(message_id))
1982 {
1983 let mut reactions = teams_core::reactions(&record);
1984 set_own_reaction(
1985 &mut reactions,
1986 glyph,
1987 my_user_id.as_deref(),
1988 added,
1989 Utc::now(),
1990 );
1991 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1992 let _ = store.upsert_messages(std::slice::from_ref(&record));
1993 }
1994 if added {
1995 self.record_reaction_use(glyph, cx);
1996 }
1997 }
1998 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
1999 entries.retain(|entry| *entry != (wanted.clone(), added));
2000 if entries.is_empty() {
2001 self.pending_reactions.remove(message_id);
2002 }
2003 }
2004 self.rebuild(false, cx);
2005 if let Err(error) = outcome {
2006 self.show_notice(&format!("Reaction failed: {error}"), cx);
2007 }
2008 }
2009
2010 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
2011 let store = self.app.read(cx).store.clone();
2012 self.recent.update(cx, |recent, cx| {
2013 recent.reload(&store);
2014 recent.record_use(glyph);
2015 recent.save(&store);
2016 cx.notify();
2017 });
1913 2018 }
1914 2019
1915 2020 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
@@ -2082,7 +2187,14 @@ impl ConversationView {
2082 2187 .detach();
2083 2188 }
2084 2189
2085 fn message_menu(&self, key: &str, own: bool, view: WeakEntity<Self>) -> MessageMenu {
2190 fn message_menu(
2191 &self,
2192 key: &str,
2193 own: bool,
2194 mine: HashSet<String>,
2195 view: WeakEntity<Self>,
2196 cx: &App,
2197 ) -> MessageMenu {
2086 2198 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
2087 2199 let (view, key) = (view.clone(), key.to_owned());
2088 2200 Rc::new(move |window, cx| {
@@ -2124,6 +2236,9 @@ impl ConversationView {
2124 2236 pin,
2125 2237 hover,
2126 2238 picker: self.picker.clone(),
2239 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
2240 mine,
2241 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
2127 2242 }
2128 2243 }
2129 2244
@@ -2491,8 +2606,19 @@ impl Render for ConversationView {
2491 2606 .filter(|_| actionable)
2492 2607 .map(|entity| {
2493 2608 let this = entity.read(cx);
2494 let menu =
2495 this.message_menu(&message.key, message.own, view.clone());
2609 let mine = message
2610 .reactions
2611 .iter()
2612 .filter(|chip| chip.mine)
2613 .map(|chip| chip.glyph())
2614 .collect();
2615 let menu = this.message_menu(
2616 &message.key,
2617 message.own,
2618 mine,
2619 view.clone(),
2620 cx,
2621 );
2496 2622 let react = menu.react.clone();
2497 2623 let visible = this.toolbar_visible(&message.key);
2498 2624 let controls = (!message.reactions.is_empty())
@@ -1,5 +1,5 @@
1use std::cell::RefCell;
1use std::cell::RefCell;
2use std::collections::HashMap;
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
4use std::rc::Rc;
5use std::time::{Duration, Instant};
5use std::time::{Duration, Instant};
@@ -21,7 +21,7 @@ use teams_core::{FileCard, ImageRef};
21use super::attachments::FileActions;
21use super::attachments::FileActions;
22use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
22use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
23use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24use super::message_actions::{Action, MessageMenu};
24use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
25use super::message_row::{RowActions, render_message_row, render_skeleton_row};
25use super::message_row::{RowActions, render_message_row, render_skeleton_row};
26use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
26use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
27use super::reaction_picker::{PickHandler, ReactionPicker};
27use super::reaction_picker::{PickHandler, ReactionPicker};
@@ -31,14 +31,15 @@ use crate::app_state::{AppEvent, AppState, Selection, selection_title};
31use crate::backend::Engine;
31use crate::backend::Engine;
32use crate::data::{is_one_on_one, others};
32use crate::data::{is_one_on_one, others};
33use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
33use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
34use crate::emoji;
34use crate::reaction_model::UNKNOWN_REACTOR;
35use crate::reaction_model::UNKNOWN_REACTOR;
35use crate::read_state::{ReadTrigger, plan_read};
36use crate::read_state::{ReadTrigger, plan_read};
36use crate::render::layout_blocks;
37use crate::render::layout_blocks;
37use crate::rows::{
38use crate::rows::{
38 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, api_reaction,
39 Delivery, LocalImage, MessageRow, PendingReactions, Receipt, Row, RowContext, Series,
39 assign_series, changed_indices, diff_keys, flat_rows, message_draft, message_text,
40 StartInfo, api_reaction, apply_pending_reactions, assign_series, changed_indices, diff_keys,
40 placeholder_rows, reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows,
41 flat_rows, has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph,
41 thread_rows, trailing_skeleton,
42 reply_excerpt, set_own_reaction, thread_list_rows, thread_rows, trailing_skeleton,
42};
43};
43use crate::runtime;
44use crate::runtime;
44use crate::sidebar_model::{AvatarSpec, Face};
45use crate::sidebar_model::{AvatarSpec, Face};
@@ -128,10 +129,13 @@ pub struct ConversationView {
128 pending: Vec<MessageRow>,
129 pending: Vec<MessageRow>,
129 pending_counter: usize,
130 pending_counter: usize,
130 pending_outgoing: HashMap<String, Outgoing>,
131 pending_outgoing: HashMap<String, Outgoing>,
132 pending_reactions: PendingReactions,
131 downloads: Downloads,
133 downloads: Downloads,
132 hovered_message: Option<String>,
134 hovered_message: Option<String>,
133 toolbar_hovered: Option<String>,
135 toolbar_hovered: Option<String>,
134 toolbar_pinned: Option<String>,
136 toolbar_pinned: Option<String>,
137 toolbar_suppressed: Option<String>,
138 recent: Entity<emoji::Recent>,
135 picker: Entity<ReactionPicker>,
139 picker: Entity<ReactionPicker>,
136 reaction_details: Option<ReactionDetails>,
140 reaction_details: Option<ReactionDetails>,
137 highlighted_message: Option<String>,
141 highlighted_message: Option<String>,
@@ -323,7 +327,8 @@ impl ConversationView {
323 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
327 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
324 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
328 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
325 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
329 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
326 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
330 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
331 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
327 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
332 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
328 let subscriptions = vec![
333 let subscriptions = vec![
329 cx.subscribe_in(&app, window, Self::on_app_event),
334 cx.subscribe_in(&app, window, Self::on_app_event),
@@ -349,10 +354,13 @@ impl ConversationView {
349 pending: Vec::new(),
354 pending: Vec::new(),
350 pending_counter: 0,
355 pending_counter: 0,
351 pending_outgoing: HashMap::new(),
356 pending_outgoing: HashMap::new(),
357 pending_reactions: HashMap::new(),
352 downloads: Downloads::default(),
358 downloads: Downloads::default(),
353 hovered_message: None,
359 hovered_message: None,
354 toolbar_hovered: None,
360 toolbar_hovered: None,
355 toolbar_pinned: None,
361 toolbar_pinned: None,
362 toolbar_suppressed: None,
363 recent,
356 picker,
364 picker,
357 reaction_details: None,
365 reaction_details: None,
358 highlighted_message: None,
366 highlighted_message: None,
@@ -488,6 +496,7 @@ impl ConversationView {
488 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
496 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
489 self.toolbar_hovered = None;
497 self.toolbar_hovered = None;
490 self.toolbar_pinned = None;
498 self.toolbar_pinned = None;
499 self.toolbar_suppressed = None;
491 let title = selection_title(&self.app.read(cx).sidebar, &selection);
500 let title = selection_title(&self.app.read(cx).sidebar, &selection);
492 let mode = match selection {
501 let mode = match selection {
493 Selection::Chat(_) => ViewMode::Flat,
502 Selection::Chat(_) => ViewMode::Flat,
@@ -544,6 +553,7 @@ impl ConversationView {
544 self.draft_error = None;
553 self.draft_error = None;
545 self.toolbar_hovered = None;
554 self.toolbar_hovered = None;
546 self.toolbar_pinned = None;
555 self.toolbar_pinned = None;
556 self.toolbar_suppressed = None;
547 self.hovered_message = None;
557 self.hovered_message = None;
548 self.sync_generation += 1;
558 self.sync_generation += 1;
549 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
559 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
@@ -836,6 +846,7 @@ impl ConversationView {
836 today: now.date_naive(),
846 today: now.date_naive(),
837 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
847 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
838 names,
848 names,
849 pending_reactions: self.pending_reactions.clone(),
839 }
850 }
840 }
851 }
841
852
@@ -1833,6 +1844,20 @@ impl ConversationView {
1833 } else if target.as_deref() == Some(key) {
1844 } else if target.as_deref() == Some(key) {
1834 *target = None;
1845 *target = None;
1835 }
1846 }
1847 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
1848 && self.hovered_message.as_deref() != Some(suppressed)
1849 && self.toolbar_hovered.as_deref() != Some(suppressed)
1850 {
1851 self.toolbar_suppressed = None;
1852 }
1853 cx.notify();
1854 }
1855
1856 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
1857 if self.toolbar_hovered.as_deref() == Some(key) {
1858 self.toolbar_hovered = None;
1859 }
1860 self.toolbar_suppressed = Some(key.to_owned());
1836 cx.notify();
1861 cx.notify();
1837 }
1862 }
1838
1863
@@ -1846,21 +1871,26 @@ impl ConversationView {
1846 }
1871 }
1847
1872
1848 fn toolbar_visible(&self, key: &str) -> bool {
1873 fn toolbar_visible(&self, key: &str) -> bool {
1849 self.toolbar_pinned
1874 self.toolbar_suppressed.as_deref() != Some(key)
1850 .as_deref()
1875 && self
1851 .or(self.toolbar_hovered.as_deref())
1876 .toolbar_pinned
1852 .or(self.hovered_message.as_deref())
1877 .as_deref()
1853 == Some(key)
1878 .or(self.toolbar_hovered.as_deref())
1879 .or(self.hovered_message.as_deref())
1880 == Some(key)
1854 }
1881 }
1855
1882
1856 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
1883 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
1857 let Some(conversation_id) = self.conversation_id() else {
1884 let Some(conversation_id) = self.conversation_id() else {
1858 return;
1885 return;
1859 };
1886 };
1860 let reaction_type = reaction_type_for(glyph);
1861 let wanted = reaction_glyph(glyph);
1862 let state = self.app.read(cx);
1887 let state = self.app.read(cx);
1863 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1888 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1889 let engine = engine.filter(|_| !mode.read_only);
1890 if !mode.demo && engine.is_none() {
1891 self.show_notice("Read-only mode: reaction not sent", cx);
1892 return;
1893 }
1864 let my_user_id = self.row_context(cx).my_user_id;
1894 let my_user_id = self.row_context(cx).my_user_id;
1865 let Some(mut record) = store
1895 let Some(mut record) = store
1866 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1896 .messages_by_id(&conversation_id, &[message_id.to_owned()])
@@ -1869,47 +1899,122 @@ impl ConversationView {
1869 else {
1899 else {
1870 return;
1900 return;
1871 };
1901 };
1872 let mut reactions = teams_core::reactions(&record);
1902 let wanted = reaction_glyph(glyph);
1873 let mine = |reaction: &teams_core::ReactionInfo| {
1903 let mut visible = teams_core::reactions(&record);
1874 reaction_glyph(&reaction.reaction_type) == wanted
1904 apply_pending_reactions(
1875 && my_user_id.is_some()
1905 &mut visible,
1876 && reaction.user_id == my_user_id
1906 self.pending_reactions.get(message_id),
1877 };
1907 my_user_id.as_deref(),
1878 let remove = reactions.iter().any(mine);
1908 Utc::now(),
1879 if mode.demo {
1909 );
1880 if remove {
1910 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
1881 reactions.retain(|reaction| !mine(reaction));
1911 let Some(engine) = engine.filter(|_| !mode.demo) else {
1882 } else {
1912 let mut reactions = teams_core::reactions(&record);
1883 reactions.push(teams_core::ReactionInfo {
1913 set_own_reaction(
1884 reaction_type: reaction_type.clone(),
1914 &mut reactions,
1885 user_id: my_user_id.clone(),
1915 glyph,
1886 user_name: Some("You".to_owned()),
1916 my_user_id.as_deref(),
1887 created_at: Some(Utc::now()),
1917 added,
1888 });
1918 Utc::now(),
1889 }
1919 );
1890 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1920 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1891 let _ = store.upsert_messages(std::slice::from_ref(&record));
1921 let _ = store.upsert_messages(std::slice::from_ref(&record));
1922 if added {
1923 self.record_reaction_use(glyph, cx);
1924 }
1892 self.rebuild(false, cx);
1925 self.rebuild(false, cx);
1893 return;
1926 return;
1894 }
1895 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1896 self.show_notice("Read-only mode: reaction not sent", cx);
1897 return;
1898 };
1927 };
1899 let message_id = message_id.to_owned();
1928 let entries = self
1929 .pending_reactions
1930 .entry(message_id.to_owned())
1931 .or_default();
1932 entries.retain(|(pending, _)| *pending != wanted);
1933 entries.push((wanted.clone(), added));
1934 self.rebuild(false, cx);
1935 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
1900 let reaction_type = api_reaction(&wanted);
1936 let reaction_type = api_reaction(&wanted);
1901 let receiver = runtime::spawn(async move {
1937 let receiver = runtime::spawn({
1902 if remove {
1938 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
1903 engine
1939 async move {
1904 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1940 if added {
1905 .await
1941 engine
1906 } else {
1942 .set_reaction(&conversation_id, &message_id, &reaction_type)
1907 engine
1943 .await
1908 .set_reaction(&conversation_id, &message_id, &reaction_type)
1944 } else {
1909 .await
1945 engine
1946 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1947 .await
1948 }
1910 }
1949 }
1911 });
1950 });
1912 self.report_failure(receiver, "Reaction failed", cx);
1951 cx.spawn(async move |this, cx| {
1952 let outcome = match receiver.await {
1953 Ok(Ok(())) => Ok(()),
1954 Ok(Err(error)) => Err(short_error(&error)),
1955 Err(_) => Err("cancelled".to_owned()),
1956 };
1957 this.update(cx, |this, cx| {
1958 this.finish_reaction(&conversation_id, &message_id, &glyph, added, outcome, cx)
1959 })
1960 .ok();
1961 })
1962 .detach();
1963 }
1964
1965 fn finish_reaction(
1966 &mut self,
1967 conversation_id: &str,
1968 message_id: &str,
1969 glyph: &str,
1970 added: bool,
1971 outcome: Result<(), String>,
1972 cx: &mut Context<Self>,
1973 ) {
1974 let wanted = reaction_glyph(glyph);
1975 let store = self.app.read(cx).store.clone();
1976 if outcome.is_ok() {
1977 let my_user_id = self.row_context(cx).my_user_id;
1978 if let Some(mut record) = store
1979 .messages_by_id(conversation_id, &[message_id.to_owned()])
1980 .ok()
1981 .and_then(|mut found| found.remove(message_id))
1982 {
1983 let mut reactions = teams_core::reactions(&record);
1984 set_own_reaction(
1985 &mut reactions,
1986 glyph,
1987 my_user_id.as_deref(),
1988 added,
1989 Utc::now(),
1990 );
1991 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1992 let _ = store.upsert_messages(std::slice::from_ref(&record));
1993 }
1994 if added {
1995 self.record_reaction_use(glyph, cx);
1996 }
1997 }
1998 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
1999 entries.retain(|entry| *entry != (wanted.clone(), added));
2000 if entries.is_empty() {
2001 self.pending_reactions.remove(message_id);
2002 }
2003 }
2004 self.rebuild(false, cx);
2005 if let Err(error) = outcome {
2006 self.show_notice(&format!("Reaction failed: {error}"), cx);
2007 }
2008 }
2009
2010 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
2011 let store = self.app.read(cx).store.clone();
2012 self.recent.update(cx, |recent, cx| {
2013 recent.reload(&store);
2014 recent.record_use(glyph);
2015 recent.save(&store);
2016 cx.notify();
2017 });
1913 }
2018 }
1914
2019
1915 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
2020 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
@@ -2082,7 +2187,14 @@ impl ConversationView {
2082 .detach();
2187 .detach();
2083 }
2188 }
2084
2189
2085 fn message_menu(&self, key: &str, own: bool, view: WeakEntity<Self>) -> MessageMenu {
2190 fn message_menu(
2191 &self,
2192 key: &str,
2193 own: bool,
2194 mine: HashSet<String>,
2195 view: WeakEntity<Self>,
2196 cx: &App,
2197 ) -> MessageMenu {
2086 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
2198 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
2087 let (view, key) = (view.clone(), key.to_owned());
2199 let (view, key) = (view.clone(), key.to_owned());
2088 Rc::new(move |window, cx| {
2200 Rc::new(move |window, cx| {
@@ -2124,6 +2236,9 @@ impl ConversationView {
2124 pin,
2236 pin,
2125 hover,
2237 hover,
2126 picker: self.picker.clone(),
2238 picker: self.picker.clone(),
2239 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
2240 mine,
2241 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
2127 }
2242 }
2128 }
2243 }
2129
2244
@@ -2491,8 +2606,19 @@ impl Render for ConversationView {
2491 .filter(|_| actionable)
2606 .filter(|_| actionable)
2492 .map(|entity| {
2607 .map(|entity| {
2493 let this = entity.read(cx);
2608 let this = entity.read(cx);
2494 let menu =
2609 let mine = message
2495 this.message_menu(&message.key, message.own, view.clone());
2610 .reactions
2611 .iter()
2612 .filter(|chip| chip.mine)
2613 .map(|chip| chip.glyph())
2614 .collect();
2615 let menu = this.message_menu(
2616 &message.key,
2617 message.own,
2618 mine,
2619 view.clone(),
2620 cx,
2621 );
2496 let react = menu.react.clone();
2622 let react = menu.react.clone();
2497 let visible = this.toolbar_visible(&message.key);
2623 let visible = this.toolbar_visible(&message.key);
2498 let controls = (!message.reactions.is_empty())
2624 let controls = (!message.reactions.is_empty())
crates/app/src/views/message_actions.rs +23 −8
@@ -1,3 +1,4 @@
1 use std::collections::HashSet;
1 2 use std::rc::Rc;
2 3
3 4 use gpui_kit::assets::IconName;
@@ -9,13 +10,16 @@ use gpui_kit::component::{
9 10 menu::{DropdownMenu as _, PopupMenuItem},
10 11 popover::Popover,
11 12 };
13 use gpui_kit::prelude::FluentBuilder as _;
12 14 use gpui_kit::*;
13 15
14 use super::reaction_picker::{PickHandler, QUICK_REACTIONS, ReactionPicker};
16 use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
15 17 use super::widgets::icon;
18 use crate::rows::reaction_glyph;
16 19 use crate::theme;
17 20
18 21 const BAR_BUTTON: f32 = 28.;
22 pub const QUICK_REACTION_COUNT: usize = 4;
19 23
20 24 pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
21 25 pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
@@ -31,6 +35,9 @@ pub struct MessageMenu {
31 35 pub pin: OpenChange,
32 36 pub hover: HoverChange,
33 37 pub picker: Entity<ReactionPicker>,
38 pub quick: Vec<String>,
39 pub mine: HashSet<String>,
40 pub done: DoneHandler,
34 41 }
35 42
36 43 fn element_id(prefix: &str, key: &str) -> ElementId {
@@ -49,23 +56,28 @@ fn bar_button(id: ElementId) -> Stateful<Div> {
49 56 .hover(|button| button.bg(theme::border_strong()))
50 57 }
51 58
52 fn reaction_button(menu: &MessageMenu, glyph: &'static str, index: usize) -> AnyElement {
53 let react = menu.react.clone();
59 fn reaction_button(menu: &MessageMenu, glyph: &str, index: usize) -> AnyElement {
60 let (react, done, picked) = (menu.react.clone(), menu.done.clone(), glyph.to_owned());
61 let selected = menu.mine.contains(&reaction_glyph(glyph));
54 62 bar_button(element_id(&format!("quick-reaction-{index}"), &menu.key))
55 63 .text_size(px(17.))
56 .child(glyph)
64 .when(selected, |button| button.bg(theme::reaction_on_own()))
65 .child(glyph.to_owned())
57 66 .on_click(move |_, window, cx| {
58 67 cx.stop_propagation();
59 react(glyph, window, cx);
68 react(&picked, window, cx);
69 done(window, cx);
60 70 })
61 71 .into_any_element()
62 72 }
63 73
64 74 fn picker_button(menu: &MessageMenu) -> AnyElement {
65 let (picker, picker_reset, react, pin) = (
75 let (picker, picker_reset, react, done, mine, pin) = (
66 76 menu.picker.clone(),
67 77 menu.picker.clone(),
68 78 menu.react.clone(),
79 menu.done.clone(),
80 menu.mine.clone(),
69 81 menu.pin.clone(),
70 82 );
71 83 Popover::new(element_id("reaction-picker", &menu.key))
@@ -85,7 +97,9 @@ fn picker_button(menu: &MessageMenu) -> AnyElement {
85 97 })
86 98 .content(move |_, _, cx| {
87 99 let popover = cx.entity().downgrade();
88 picker.update(cx, |picker, _| picker.set_target(react.clone(), popover));
100 picker.update(cx, |picker, _| {
101 picker.set_target(react.clone(), done.clone(), popover, mine.clone())
102 });
89 103 picker.clone()
90 104 })
91 105 .into_any_element()
@@ -131,7 +145,8 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
131 145
132 146 pub fn message_toolbar(menu: MessageMenu) -> AnyElement {
133 147 let hover = menu.hover.clone();
134 let mut children: Vec<AnyElement> = QUICK_REACTIONS
148 let mut children: Vec<AnyElement> = menu
149 .quick
135 150 .iter()
136 151 .enumerate()
137 152 .map(|(index, glyph)| reaction_button(&menu, glyph, index))
@@ -1,3 +1,4 @@
1use std::collections::HashSet;
1use std::rc::Rc;
2use std::rc::Rc;
2
3
3use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
@@ -9,13 +10,16 @@ use gpui_kit::component::{
9 menu::{DropdownMenu as _, PopupMenuItem},
10 menu::{DropdownMenu as _, PopupMenuItem},
10 popover::Popover,
11 popover::Popover,
11};
12};
13use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
14use gpui_kit::*;
13
15
14use super::reaction_picker::{PickHandler, QUICK_REACTIONS, ReactionPicker};
16use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
15use super::widgets::icon;
17use super::widgets::icon;
18use crate::rows::reaction_glyph;
16use crate::theme;
19use crate::theme;
17
20
18const BAR_BUTTON: f32 = 28.;
21const BAR_BUTTON: f32 = 28.;
22pub const QUICK_REACTION_COUNT: usize = 4;
19
23
20pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
24pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
21pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
25pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
@@ -31,6 +35,9 @@ pub struct MessageMenu {
31 pub pin: OpenChange,
35 pub pin: OpenChange,
32 pub hover: HoverChange,
36 pub hover: HoverChange,
33 pub picker: Entity<ReactionPicker>,
37 pub picker: Entity<ReactionPicker>,
38 pub quick: Vec<String>,
39 pub mine: HashSet<String>,
40 pub done: DoneHandler,
34}
41}
35
42
36fn element_id(prefix: &str, key: &str) -> ElementId {
43fn element_id(prefix: &str, key: &str) -> ElementId {
@@ -49,23 +56,28 @@ fn bar_button(id: ElementId) -> Stateful<Div> {
49 .hover(|button| button.bg(theme::border_strong()))
56 .hover(|button| button.bg(theme::border_strong()))
50}
57}
51
58
52fn reaction_button(menu: &MessageMenu, glyph: &'static str, index: usize) -> AnyElement {
59fn reaction_button(menu: &MessageMenu, glyph: &str, index: usize) -> AnyElement {
53 let react = menu.react.clone();
60 let (react, done, picked) = (menu.react.clone(), menu.done.clone(), glyph.to_owned());
61 let selected = menu.mine.contains(&reaction_glyph(glyph));
54 bar_button(element_id(&format!("quick-reaction-{index}"), &menu.key))
62 bar_button(element_id(&format!("quick-reaction-{index}"), &menu.key))
55 .text_size(px(17.))
63 .text_size(px(17.))
56 .child(glyph)
64 .when(selected, |button| button.bg(theme::reaction_on_own()))
65 .child(glyph.to_owned())
57 .on_click(move |_, window, cx| {
66 .on_click(move |_, window, cx| {
58 cx.stop_propagation();
67 cx.stop_propagation();
59 react(glyph, window, cx);
68 react(&picked, window, cx);
69 done(window, cx);
60 })
70 })
61 .into_any_element()
71 .into_any_element()
62}
72}
63
73
64fn picker_button(menu: &MessageMenu) -> AnyElement {
74fn picker_button(menu: &MessageMenu) -> AnyElement {
65 let (picker, picker_reset, react, pin) = (
75 let (picker, picker_reset, react, done, mine, pin) = (
66 menu.picker.clone(),
76 menu.picker.clone(),
67 menu.picker.clone(),
77 menu.picker.clone(),
68 menu.react.clone(),
78 menu.react.clone(),
79 menu.done.clone(),
80 menu.mine.clone(),
69 menu.pin.clone(),
81 menu.pin.clone(),
70 );
82 );
71 Popover::new(element_id("reaction-picker", &menu.key))
83 Popover::new(element_id("reaction-picker", &menu.key))
@@ -85,7 +97,9 @@ fn picker_button(menu: &MessageMenu) -> AnyElement {
85 })
97 })
86 .content(move |_, _, cx| {
98 .content(move |_, _, cx| {
87 let popover = cx.entity().downgrade();
99 let popover = cx.entity().downgrade();
88 picker.update(cx, |picker, _| picker.set_target(react.clone(), popover));
100 picker.update(cx, |picker, _| {
101 picker.set_target(react.clone(), done.clone(), popover, mine.clone())
102 });
89 picker.clone()
103 picker.clone()
90 })
104 })
91 .into_any_element()
105 .into_any_element()
@@ -131,7 +145,8 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
131
145
132pub fn message_toolbar(menu: MessageMenu) -> AnyElement {
146pub fn message_toolbar(menu: MessageMenu) -> AnyElement {
133 let hover = menu.hover.clone();
147 let hover = menu.hover.clone();
134 let mut children: Vec<AnyElement> = QUICK_REACTIONS
148 let mut children: Vec<AnyElement> = menu
149 .quick
135 .iter()
150 .iter()
136 .enumerate()
151 .enumerate()
137 .map(|(index, glyph)| reaction_button(&menu, glyph, index))
152 .map(|(index, glyph)| reaction_button(&menu, glyph, index))
crates/app/src/views/reaction_picker.rs +72 −22
@@ -1,3 +1,4 @@
1 use std::collections::HashSet;
1 2 use std::rc::Rc;
2 3
3 4 use gpui_kit::base::PopoverState;
@@ -6,13 +7,14 @@ use gpui_kit::component::{
6 7 input::{Input, InputEvent, InputState},
7 8 v_flex,
8 9 };
10 use gpui_kit::prelude::FluentBuilder as _;
9 11 use gpui_kit::*;
10 12
11 13 use crate::app_state::AppState;
12 14 use crate::emoji;
15 use crate::rows::reaction_glyph;
13 16 use crate::theme;
14 17
15 pub const QUICK_REACTIONS: [&str; 4] = ["\u{1F44D}", "\u{2764}", "\u{1F602}", "\u{1F62E}"];
16 18 const PICKER_QUICK: [&str; 6] = [
17 19 "\u{1F44D}",
18 20 "\u{2764}",
@@ -45,36 +47,66 @@ const GRID_COLUMNS: usize = 8;
45 47 const GRID_LIMIT: usize = 32;
46 48
47 49 pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
50 pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
51
52 #[derive(Clone)]
53 struct PickTarget {
54 on_pick: PickHandler,
55 on_done: DoneHandler,
56 popover: WeakEntity<PopoverState>,
57 }
48 58
49 59 pub struct ReactionPicker {
50 60 app: Entity<AppState>,
51 61 input: Entity<InputState>,
52 62 query: String,
53 recent: emoji::Recent,
54 target: Option<(PickHandler, WeakEntity<PopoverState>)>,
63 recent: Entity<emoji::Recent>,
64 selected: HashSet<String>,
65 target: Option<PickTarget>,
55 66 _subscription: Subscription,
56 67 }
57 68
58 69 impl ReactionPicker {
59 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
70 pub fn new(
71 app: Entity<AppState>,
72 recent: Entity<emoji::Recent>,
73 window: &mut Window,
74 cx: &mut Context<Self>,
75 ) -> Self {
60 76 let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search emoji"));
61 77 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 let recent = emoji::Recent::load(&app.read(cx).store);
63 78 ReactionPicker {
64 79 app,
65 80 input,
66 81 query: String::new(),
67 82 recent,
83 selected: HashSet::new(),
68 84 target: None,
69 85 _subscription: subscription,
70 86 }
71 87 }
72 88
73 pub fn set_target(&mut self, on_pick: PickHandler, popover: WeakEntity<PopoverState>) {
74 self.target = Some((on_pick, popover));
89 pub fn set_target(
90 &mut self,
91 on_pick: PickHandler,
92 on_done: DoneHandler,
93 popover: WeakEntity<PopoverState>,
94 selected: HashSet<String>,
95 ) {
96 self.target = Some(PickTarget {
97 on_pick,
98 on_done,
99 popover,
100 });
101 self.selected = selected;
75 102 }
76 103
77 104 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
105 let store = self.app.read(cx).store.clone();
106 self.recent.update(cx, |recent, cx| {
107 recent.reload(&store);
108 cx.notify();
109 });
78 110 self.query.clear();
79 111 self.input.update(cx, |state, cx| {
80 112 state.set_value("", window, cx);
@@ -96,17 +128,17 @@ impl ReactionPicker {
96 128 cx.notify();
97 129 }
98 130 InputEvent::PressEnter { .. } => {
99 if let Some(first) = self.results().first().cloned() {
100 self.pick(&first, window, cx);
131 if let Some(first) = self.results(cx).first().cloned() {
132 self.pick(&first, false, window, cx);
101 133 }
102 134 }
103 135 _ => {}
104 136 }
105 137 }
106 138
107 fn results(&self) -> Vec<String> {
139 fn results(&self, cx: &App) -> Vec<String> {
140 let recent = self.recent.read(cx).glyphs();
108 141 if self.query.is_empty() {
109 let recent = self.recent.glyphs();
110 142 let fill = FALLBACK_RECENT
111 143 .iter()
112 144 .map(|glyph| (*glyph).to_owned())
@@ -118,25 +150,40 @@ impl ReactionPicker {
118 150 .take(GRID_LIMIT)
119 151 .collect();
120 152 }
121 emoji::search(&self.query, self.recent.glyphs(), GRID_LIMIT)
153 emoji::search(&self.query, &recent, GRID_LIMIT)
122 154 .into_iter()
123 155 .map(|found| found.glyph.to_owned())
124 156 .collect()
125 157 }
126 158
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();
159 fn pick(&mut self, glyph: &str, keep_open: bool, window: &mut Window, cx: &mut Context<Self>) {
160 let target = if keep_open {
161 self.target.clone()
162 } else {
163 self.target.take()
164 };
165 let Some(target) = target else {
166 return;
167 };
168 let normalized = reaction_glyph(glyph);
169 if !self.selected.remove(&normalized) {
170 self.selected.insert(normalized);
171 }
172 (target.on_pick)(glyph, window, cx);
173 if keep_open {
174 cx.notify();
175 return;
135 176 }
177 target
178 .popover
179 .update(cx, |state, cx| state.dismiss(window, cx))
180 .ok();
181 (target.on_done)(window, cx);
136 182 }
137 183
138 184 fn cell(&self, glyph: String, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
139 185 let picked = glyph.clone();
186 let selected = self.selected.contains(&reaction_glyph(&glyph));
140 187 div()
141 188 .id(("reaction-picker-cell", index))
142 189 .size(px(CELL_SIZE))
@@ -146,15 +193,18 @@ impl ReactionPicker {
146 193 .rounded(px(6.))
147 194 .text_size(px(20.))
148 195 .cursor_pointer()
196 .when(selected, |cell| cell.bg(theme::reaction_on_own()))
149 197 .hover(|cell| cell.bg(theme::border_strong()))
150 198 .child(glyph)
151 .on_click(cx.listener(move |this, _, window, cx| this.pick(&picked, window, cx)))
199 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
200 this.pick(&picked, event.modifiers().shift, window, cx)
201 }))
152 202 }
153 203 }
154 204
155 205 impl Render for ReactionPicker {
156 206 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
157 let results = self.results();
207 let results = self.results(cx);
158 208 let label = if self.query.is_empty() {
159 209 "Recently used"
160 210 } else if results.is_empty() {
@@ -1,3 +1,4 @@
1use std::collections::HashSet;
1use std::rc::Rc;
2use std::rc::Rc;
2
3
3use gpui_kit::base::PopoverState;
4use gpui_kit::base::PopoverState;
@@ -6,13 +7,14 @@ use gpui_kit::component::{
6 input::{Input, InputEvent, InputState},
7 input::{Input, InputEvent, InputState},
7 v_flex,
8 v_flex,
8};
9};
10use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
11use gpui_kit::*;
10
12
11use crate::app_state::AppState;
13use crate::app_state::AppState;
12use crate::emoji;
14use crate::emoji;
15use crate::rows::reaction_glyph;
13use crate::theme;
16use crate::theme;
14
17
15pub const QUICK_REACTIONS: [&str; 4] = ["\u{1F44D}", "\u{2764}", "\u{1F602}", "\u{1F62E}"];
16const PICKER_QUICK: [&str; 6] = [
18const PICKER_QUICK: [&str; 6] = [
17 "\u{1F44D}",
19 "\u{1F44D}",
18 "\u{2764}",
20 "\u{2764}",
@@ -45,36 +47,66 @@ const GRID_COLUMNS: usize = 8;
45const GRID_LIMIT: usize = 32;
47const GRID_LIMIT: usize = 32;
46
48
47pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
49pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
50pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
51
52#[derive(Clone)]
53struct PickTarget {
54 on_pick: PickHandler,
55 on_done: DoneHandler,
56 popover: WeakEntity<PopoverState>,
57}
48
58
49pub struct ReactionPicker {
59pub struct ReactionPicker {
50 app: Entity<AppState>,
60 app: Entity<AppState>,
51 input: Entity<InputState>,
61 input: Entity<InputState>,
52 query: String,
62 query: String,
53 recent: emoji::Recent,
63 recent: Entity<emoji::Recent>,
54 target: Option<(PickHandler, WeakEntity<PopoverState>)>,
64 selected: HashSet<String>,
65 target: Option<PickTarget>,
55 _subscription: Subscription,
66 _subscription: Subscription,
56}
67}
57
68
58impl ReactionPicker {
69impl ReactionPicker {
59 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
70 pub fn new(
71 app: Entity<AppState>,
72 recent: Entity<emoji::Recent>,
73 window: &mut Window,
74 cx: &mut Context<Self>,
75 ) -> Self {
60 let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search emoji"));
76 let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search emoji"));
61 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
77 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 let recent = emoji::Recent::load(&app.read(cx).store);
63 ReactionPicker {
78 ReactionPicker {
64 app,
79 app,
65 input,
80 input,
66 query: String::new(),
81 query: String::new(),
67 recent,
82 recent,
83 selected: HashSet::new(),
68 target: None,
84 target: None,
69 _subscription: subscription,
85 _subscription: subscription,
70 }
86 }
71 }
87 }
72
88
73 pub fn set_target(&mut self, on_pick: PickHandler, popover: WeakEntity<PopoverState>) {
89 pub fn set_target(
74 self.target = Some((on_pick, popover));
90 &mut self,
91 on_pick: PickHandler,
92 on_done: DoneHandler,
93 popover: WeakEntity<PopoverState>,
94 selected: HashSet<String>,
95 ) {
96 self.target = Some(PickTarget {
97 on_pick,
98 on_done,
99 popover,
100 });
101 self.selected = selected;
75 }
102 }
76
103
77 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
104 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
105 let store = self.app.read(cx).store.clone();
106 self.recent.update(cx, |recent, cx| {
107 recent.reload(&store);
108 cx.notify();
109 });
78 self.query.clear();
110 self.query.clear();
79 self.input.update(cx, |state, cx| {
111 self.input.update(cx, |state, cx| {
80 state.set_value("", window, cx);
112 state.set_value("", window, cx);
@@ -96,17 +128,17 @@ impl ReactionPicker {
96 cx.notify();
128 cx.notify();
97 }
129 }
98 InputEvent::PressEnter { .. } => {
130 InputEvent::PressEnter { .. } => {
99 if let Some(first) = self.results().first().cloned() {
131 if let Some(first) = self.results(cx).first().cloned() {
100 self.pick(&first, window, cx);
132 self.pick(&first, false, window, cx);
101 }
133 }
102 }
134 }
103 _ => {}
135 _ => {}
104 }
136 }
105 }
137 }
106
138
107 fn results(&self) -> Vec<String> {
139 fn results(&self, cx: &App) -> Vec<String> {
140 let recent = self.recent.read(cx).glyphs();
108 if self.query.is_empty() {
141 if self.query.is_empty() {
109 let recent = self.recent.glyphs();
110 let fill = FALLBACK_RECENT
142 let fill = FALLBACK_RECENT
111 .iter()
143 .iter()
112 .map(|glyph| (*glyph).to_owned())
144 .map(|glyph| (*glyph).to_owned())
@@ -118,25 +150,40 @@ impl ReactionPicker {
118 .take(GRID_LIMIT)
150 .take(GRID_LIMIT)
119 .collect();
151 .collect();
120 }
152 }
121 emoji::search(&self.query, self.recent.glyphs(), GRID_LIMIT)
153 emoji::search(&self.query, &recent, GRID_LIMIT)
122 .into_iter()
154 .into_iter()
123 .map(|found| found.glyph.to_owned())
155 .map(|found| found.glyph.to_owned())
124 .collect()
156 .collect()
125 }
157 }
126
158
127 fn pick(&mut self, glyph: &str, window: &mut Window, cx: &mut Context<Self>) {
159 fn pick(&mut self, glyph: &str, keep_open: bool, window: &mut Window, cx: &mut Context<Self>) {
128 self.recent.push(glyph);
160 let target = if keep_open {
129 self.recent.save(&self.app.read(cx).store);
161 self.target.clone()
130 if let Some((on_pick, popover)) = self.target.take() {
162 } else {
131 on_pick(glyph, window, cx);
163 self.target.take()
132 popover
164 };
133 .update(cx, |state, cx| state.dismiss(window, cx))
165 let Some(target) = target else {
134 .ok();
166 return;
167 };
168 let normalized = reaction_glyph(glyph);
169 if !self.selected.remove(&normalized) {
170 self.selected.insert(normalized);
171 }
172 (target.on_pick)(glyph, window, cx);
173 if keep_open {
174 cx.notify();
175 return;
135 }
176 }
177 target
178 .popover
179 .update(cx, |state, cx| state.dismiss(window, cx))
180 .ok();
181 (target.on_done)(window, cx);
136 }
182 }
137
183
138 fn cell(&self, glyph: String, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
184 fn cell(&self, glyph: String, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
139 let picked = glyph.clone();
185 let picked = glyph.clone();
186 let selected = self.selected.contains(&reaction_glyph(&glyph));
140 div()
187 div()
141 .id(("reaction-picker-cell", index))
188 .id(("reaction-picker-cell", index))
142 .size(px(CELL_SIZE))
189 .size(px(CELL_SIZE))
@@ -146,15 +193,18 @@ impl ReactionPicker {
146 .rounded(px(6.))
193 .rounded(px(6.))
147 .text_size(px(20.))
194 .text_size(px(20.))
148 .cursor_pointer()
195 .cursor_pointer()
196 .when(selected, |cell| cell.bg(theme::reaction_on_own()))
149 .hover(|cell| cell.bg(theme::border_strong()))
197 .hover(|cell| cell.bg(theme::border_strong()))
150 .child(glyph)
198 .child(glyph)
151 .on_click(cx.listener(move |this, _, window, cx| this.pick(&picked, window, cx)))
199 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
200 this.pick(&picked, event.modifiers().shift, window, cx)
201 }))
152 }
202 }
153}
203}
154
204
155impl Render for ReactionPicker {
205impl Render for ReactionPicker {
156 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
206 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
157 let results = self.results();
207 let results = self.results(cx);
158 let label = if self.query.is_empty() {
208 let label = if self.query.is_empty() {
159 "Recently used"
209 "Recently used"
160 } else if results.is_empty() {
210 } else if results.is_empty() {