Merge remote-tracking branch 'origin/main' into feat/channel-menu
@@ -1,8 +1,8 @@
1
1
use std::future::Future;
2
2
3
use chatsvc::HistoryShare;
3
4
use chrono::{DateTime, Duration, Local, Offset, Utc};
4
5
use gpui_kit::*;
5
use chatsvc::HistoryShare;
6
6
use store::{ChannelNotifications, ChatRecord, MemberRecord};
7
7
use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
8
8
@@ -255,9 +255,7 @@ impl AppState {
255
255
};
256
256
let mut with_members = chat.clone();
257
257
merge_members(&mut with_members.members, &people);
258
let _ = self
259
.store
260
.upsert_chats(std::slice::from_ref(&with_members));
258
let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));
261
259
self.reload_sidebar(cx);
262
260
let Some(engine) = engine_or_demo else {
263
261
self.add_demo_roster_line(chat_id, &people, share, cx);
@@ -302,19 +300,90 @@ impl AppState {
302
300
HistoryShare::Days(days) => SharedHistory::Days(days),
303
301
HistoryShare::All => SharedHistory::All,
304
302
},
303
topic: None,
305
304
};
305
self.store_demo_roster_line(chat_id, &event, cx);
306
}
307
308
fn store_demo_roster_line(
309
&mut self,
310
chat_id: &str,
311
event: &RosterEvent,
312
cx: &mut Context<Self>,
313
) {
306
314
let now = Utc::now();
307
315
let record = crate::demo::roster_record(
308
316
chat_id,
309
317
&format!("demo-roster-{}", now.timestamp_millis()),
310
318
now,
311
&event,
319
event,
312
320
);
313
321
let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314
322
cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315
323
cx.notify();
316
324
}
317
325
326
/// Teams' "Remove chat history": hidden for me only until a newer message arrives.
327
pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
328
let Some(chat) = self.chat_record(chat_id) else {
329
return;
330
};
331
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
332
return;
333
};
334
self.remove_chat_locally(chat_id, cx);
335
let Some(engine) = engine_or_demo else {
336
return;
337
};
338
let owned_id = chat_id.to_owned();
339
self.run_chat_action(
340
"Remove chat history",
341
async move { engine.remove_chat_history(&owned_id).await },
342
move |state, cx| state.restore_chat_locally(&chat, cx),
343
|_, _| {},
344
cx,
345
);
346
}
347
348
pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
349
let Some(chat) = self.chat_record(chat_id) else {
350
return;
351
};
352
let topic = topic.trim().to_owned();
353
if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
354
return;
355
}
356
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
357
return;
358
};
359
let mut renamed = chat.clone();
360
renamed.title = topic.clone();
361
let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
362
self.reload_sidebar(cx);
363
let Some(engine) = engine_or_demo else {
364
let me = self.directory.me.as_ref();
365
let event = RosterEvent {
366
change: RosterChange::Renamed,
367
initiator_id: me.map(|person| person.user_id.clone()),
368
initiator_name: me.map(|person| person.display_name.clone()),
369
member_ids: Vec::new(),
370
member_names: Vec::new(),
371
history: SharedHistory::None,
372
topic: (!topic.is_empty()).then(|| topic.clone()),
373
};
374
self.store_demo_roster_line(chat_id, &event, cx);
375
return;
376
};
377
let owned_id = chat_id.to_owned();
378
self.run_chat_action(
379
"Rename group chat",
380
async move { engine.rename_chat(&owned_id, &topic).await },
381
move |state, cx| state.restore_chat_locally(&chat, cx),
382
|_, _| {},
383
cx,
384
);
385
}
386
318
387
/// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319
388
pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320
389
self.new_chat_people = people;
@@ -1,8 +1,8 @@1
use std::future::Future;1
use std::future::Future;2
2
3
use chatsvc::HistoryShare;3
use chrono::{DateTime, Duration, Local, Offset, Utc};4
use chrono::{DateTime, Duration, Local, Offset, Utc};4
use gpui_kit::*;5
use gpui_kit::*;5
use chatsvc::HistoryShare;6
use store::{ChannelNotifications, ChatRecord, MemberRecord};6
use store::{ChannelNotifications, ChatRecord, MemberRecord};7
use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};7
use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};8
8
@@ -255,9 +255,7 @@ impl AppState {255
};255
};256
let mut with_members = chat.clone();256
let mut with_members = chat.clone();257
merge_members(&mut with_members.members, &people);257
merge_members(&mut with_members.members, &people);258
let _ = self258
let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));259
.store260
.upsert_chats(std::slice::from_ref(&with_members));261
self.reload_sidebar(cx);259
self.reload_sidebar(cx);262
let Some(engine) = engine_or_demo else {260
let Some(engine) = engine_or_demo else {263
self.add_demo_roster_line(chat_id, &people, share, cx);261
self.add_demo_roster_line(chat_id, &people, share, cx);@@ -302,19 +300,90 @@ impl AppState {302
HistoryShare::Days(days) => SharedHistory::Days(days),300
HistoryShare::Days(days) => SharedHistory::Days(days),303
HistoryShare::All => SharedHistory::All,301
HistoryShare::All => SharedHistory::All,304
},302
},303
topic: None,305
};304
};305
self.store_demo_roster_line(chat_id, &event, cx);306
}307
308
fn store_demo_roster_line(309
&mut self,310
chat_id: &str,311
event: &RosterEvent,312
cx: &mut Context<Self>,313
) {306
let now = Utc::now();314
let now = Utc::now();307
let record = crate::demo::roster_record(315
let record = crate::demo::roster_record(308
chat_id,316
chat_id,309
&format!("demo-roster-{}", now.timestamp_millis()),317
&format!("demo-roster-{}", now.timestamp_millis()),310
now,318
now,311
&event,319
event,312
);320
);313
let _ = self.store.upsert_messages(std::slice::from_ref(&record));321
let _ = self.store.upsert_messages(std::slice::from_ref(&record));314
cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));322
cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));315
cx.notify();323
cx.notify();316
}324
}317
325
326
/// Teams' "Remove chat history": hidden for me only until a newer message arrives.327
pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {328
let Some(chat) = self.chat_record(chat_id) else {329
return;330
};331
let Some(engine_or_demo) = self.chat_action_engine(cx) else {332
return;333
};334
self.remove_chat_locally(chat_id, cx);335
let Some(engine) = engine_or_demo else {336
return;337
};338
let owned_id = chat_id.to_owned();339
self.run_chat_action(340
"Remove chat history",341
async move { engine.remove_chat_history(&owned_id).await },342
move |state, cx| state.restore_chat_locally(&chat, cx),343
|_, _| {},344
cx,345
);346
}347
348
pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {349
let Some(chat) = self.chat_record(chat_id) else {350
return;351
};352
let topic = topic.trim().to_owned();353
if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {354
return;355
}356
let Some(engine_or_demo) = self.chat_action_engine(cx) else {357
return;358
};359
let mut renamed = chat.clone();360
renamed.title = topic.clone();361
let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));362
self.reload_sidebar(cx);363
let Some(engine) = engine_or_demo else {364
let me = self.directory.me.as_ref();365
let event = RosterEvent {366
change: RosterChange::Renamed,367
initiator_id: me.map(|person| person.user_id.clone()),368
initiator_name: me.map(|person| person.display_name.clone()),369
member_ids: Vec::new(),370
member_names: Vec::new(),371
history: SharedHistory::None,372
topic: (!topic.is_empty()).then(|| topic.clone()),373
};374
self.store_demo_roster_line(chat_id, &event, cx);375
return;376
};377
let owned_id = chat_id.to_owned();378
self.run_chat_action(379
"Rename group chat",380
async move { engine.rename_chat(&owned_id, &topic).await },381
move |state, cx| state.restore_chat_locally(&chat, cx),382
|_, _| {},383
cx,384
);385
}386
318
/// Teams turns adding people to a 1:1 into a new group chat draft with everyone.387
/// Teams turns adding people to a 1:1 into a new group chat draft with everyone.319
pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {388
pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {320
self.new_chat_people = people;389
self.new_chat_people = people;@@ -0,0 +1,127 @@
1
use gpui_kit::Context;
2
3
use crate::app_state::AppState;
4
use crate::emoticons;
5
6
pub fn quick_reaction_glyphs(reaction_ids: &[String], skin_tone: u8) -> Vec<String> {
7
reaction_ids
8
.iter()
9
.filter_map(|reaction_id| chatsvc::reaction_glyph_for_key(reaction_id))
10
.map(|glyph| emoticons::with_tone(&glyph, skin_tone))
11
.collect()
12
}
13
14
pub fn reaction_id_for_glyph(glyph: &str) -> Option<String> {
15
chatsvc::reaction_key(&emoticons::without_tone(glyph))
16
}
17
18
pub fn slots_for(reaction_ids: &[String]) -> Vec<Option<String>> {
19
let length = reaction_ids.len().max(teams_core::DEFAULT_REACTION_SLOTS);
20
(0..length)
21
.map(|index| reaction_ids.get(index).cloned())
22
.collect()
23
}
24
25
/// Teams' replace rule: an id already in another slot leaves that slot empty.
26
pub fn place_in_slot(slots: &mut [Option<String>], index: usize, reaction_id: String) {
27
for slot in slots.iter_mut() {
28
if slot.as_deref() == Some(reaction_id.as_str()) {
29
*slot = None;
30
}
31
}
32
if let Some(slot) = slots.get_mut(index) {
33
*slot = Some(reaction_id);
34
}
35
}
36
37
pub fn filled(slots: &[Option<String>]) -> Vec<String> {
38
slots.iter().flatten().cloned().collect()
39
}
40
41
impl AppState {
42
pub fn default_reactions(&self) -> Vec<String> {
43
teams_core::default_reactions(&self.store)
44
}
45
46
pub fn quick_reactions(&self) -> Vec<String> {
47
quick_reaction_glyphs(
48
&self.default_reactions(),
49
teams_core::skin_tone(&self.store),
50
)
51
}
52
53
pub fn set_default_reactions(&mut self, reaction_ids: Vec<String>, cx: &mut Context<Self>) {
54
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
55
return;
56
};
57
let previous = self.default_reactions();
58
let _ = teams_core::store_account_default_reactions(&self.store, Some(&reaction_ids));
59
cx.notify();
60
let Some(engine) = engine_or_demo else {
61
return;
62
};
63
self.run_chat_action(
64
"Customising default reactions",
65
async move { engine.set_default_reactions(&reaction_ids).await },
66
move |state, cx| {
67
let _ = teams_core::store_account_default_reactions(&state.store, Some(&previous));
68
cx.notify();
69
},
70
|_, _| {},
71
cx,
72
);
73
}
74
}
75
76
#[cfg(test)]
77
mod tests {
78
use super::*;
79
80
fn ids(values: &[&str]) -> Vec<String> {
81
values.iter().map(|value| (*value).to_owned()).collect()
82
}
83
84
#[test]
85
fn teams_defaults_show_as_glyphs_and_like_takes_the_tone() {
86
let defaults = ids(&teams_core::TEAMS_DEFAULT_REACTIONS);
87
assert_eq!(
88
quick_reaction_glyphs(&defaults, 0),
89
["\u{1F44D}", "\u{2764}", "\u{1F606}", "\u{1F62E}"]
90
);
91
assert_eq!(quick_reaction_glyphs(&defaults, 2)[0], "\u{1F44D}\u{1F3FC}");
92
assert_eq!(
93
chatsvc::reaction_key(&quick_reaction_glyphs(&defaults, 2)[0]).as_deref(),
94
Some("yes-tone2")
95
);
96
}
97
98
#[test]
99
fn unknown_ids_are_left_out() {
100
assert_eq!(
101
quick_reaction_glyphs(&ids(&["heart", "custom-gone"]), 0),
102
["\u{2764}"]
103
);
104
}
105
106
#[test]
107
fn picked_glyphs_store_the_untoned_id() {
108
assert_eq!(
109
reaction_id_for_glyph("\u{1F44D}\u{1F3FC}").as_deref(),
110
Some("like")
111
);
112
assert_eq!(
113
reaction_id_for_glyph("\u{2764}\u{FE0F}").as_deref(),
114
Some("heart")
115
);
116
}
117
118
#[test]
119
fn there_are_always_five_slots_and_a_repeat_moves() {
120
let mut slots = slots_for(&ids(&["like", "heart"]));
121
assert_eq!(slots.len(), 5);
122
place_in_slot(&mut slots, 3, "like".to_owned());
123
assert_eq!(filled(&slots), ["heart", "like"]);
124
assert_eq!(slots[0], None);
125
assert_eq!(slots_for(&ids(&["a", "b", "c", "d", "e", "f"])).len(), 6);
126
}
127
}
@@ -0,0 +1,127 @@1
use gpui_kit::Context;2
3
use crate::app_state::AppState;4
use crate::emoticons;5
6
pub fn quick_reaction_glyphs(reaction_ids: &[String], skin_tone: u8) -> Vec<String> {7
reaction_ids8
.iter()9
.filter_map(|reaction_id| chatsvc::reaction_glyph_for_key(reaction_id))10
.map(|glyph| emoticons::with_tone(&glyph, skin_tone))11
.collect()12
}13
14
pub fn reaction_id_for_glyph(glyph: &str) -> Option<String> {15
chatsvc::reaction_key(&emoticons::without_tone(glyph))16
}17
18
pub fn slots_for(reaction_ids: &[String]) -> Vec<Option<String>> {19
let length = reaction_ids.len().max(teams_core::DEFAULT_REACTION_SLOTS);20
(0..length)21
.map(|index| reaction_ids.get(index).cloned())22
.collect()23
}24
25
/// Teams' replace rule: an id already in another slot leaves that slot empty.26
pub fn place_in_slot(slots: &mut [Option<String>], index: usize, reaction_id: String) {27
for slot in slots.iter_mut() {28
if slot.as_deref() == Some(reaction_id.as_str()) {29
*slot = None;30
}31
}32
if let Some(slot) = slots.get_mut(index) {33
*slot = Some(reaction_id);34
}35
}36
37
pub fn filled(slots: &[Option<String>]) -> Vec<String> {38
slots.iter().flatten().cloned().collect()39
}40
41
impl AppState {42
pub fn default_reactions(&self) -> Vec<String> {43
teams_core::default_reactions(&self.store)44
}45
46
pub fn quick_reactions(&self) -> Vec<String> {47
quick_reaction_glyphs(48
&self.default_reactions(),49
teams_core::skin_tone(&self.store),50
)51
}52
53
pub fn set_default_reactions(&mut self, reaction_ids: Vec<String>, cx: &mut Context<Self>) {54
let Some(engine_or_demo) = self.chat_action_engine(cx) else {55
return;56
};57
let previous = self.default_reactions();58
let _ = teams_core::store_account_default_reactions(&self.store, Some(&reaction_ids));59
cx.notify();60
let Some(engine) = engine_or_demo else {61
return;62
};63
self.run_chat_action(64
"Customising default reactions",65
async move { engine.set_default_reactions(&reaction_ids).await },66
move |state, cx| {67
let _ = teams_core::store_account_default_reactions(&state.store, Some(&previous));68
cx.notify();69
},70
|_, _| {},71
cx,72
);73
}74
}75
76
#[cfg(test)]77
mod tests {78
use super::*;79
80
fn ids(values: &[&str]) -> Vec<String> {81
values.iter().map(|value| (*value).to_owned()).collect()82
}83
84
#[test]85
fn teams_defaults_show_as_glyphs_and_like_takes_the_tone() {86
let defaults = ids(&teams_core::TEAMS_DEFAULT_REACTIONS);87
assert_eq!(88
quick_reaction_glyphs(&defaults, 0),89
["\u{1F44D}", "\u{2764}", "\u{1F606}", "\u{1F62E}"]90
);91
assert_eq!(quick_reaction_glyphs(&defaults, 2)[0], "\u{1F44D}\u{1F3FC}");92
assert_eq!(93
chatsvc::reaction_key(&quick_reaction_glyphs(&defaults, 2)[0]).as_deref(),94
Some("yes-tone2")95
);96
}97
98
#[test]99
fn unknown_ids_are_left_out() {100
assert_eq!(101
quick_reaction_glyphs(&ids(&["heart", "custom-gone"]), 0),102
["\u{2764}"]103
);104
}105
106
#[test]107
fn picked_glyphs_store_the_untoned_id() {108
assert_eq!(109
reaction_id_for_glyph("\u{1F44D}\u{1F3FC}").as_deref(),110
Some("like")111
);112
assert_eq!(113
reaction_id_for_glyph("\u{2764}\u{FE0F}").as_deref(),114
Some("heart")115
);116
}117
118
#[test]119
fn there_are_always_five_slots_and_a_repeat_moves() {120
let mut slots = slots_for(&ids(&["like", "heart"]));121
assert_eq!(slots.len(), 5);122
place_in_slot(&mut slots, 3, "like".to_owned());123
assert_eq!(filled(&slots), ["heart", "like"]);124
assert_eq!(slots[0], None);125
assert_eq!(slots_for(&ids(&["a", "b", "c", "d", "e", "f"])).len(), 6);126
}127
}@@ -14,6 +14,7 @@ pub mod chat_actions;
14
14
pub mod chat_members;
15
15
pub mod connection_banner;
16
16
pub mod data;
17
pub mod default_reactions;
17
18
pub mod demo;
18
19
pub mod demo_meetings;
19
20
pub mod demo_profiles;
@@ -14,6 +14,7 @@ pub mod chat_actions;14
pub mod chat_members;14
pub mod chat_members;15
pub mod connection_banner;15
pub mod connection_banner;16
pub mod data;16
pub mod data;17
pub mod default_reactions;17
pub mod demo;18
pub mod demo;18
pub mod demo_meetings;19
pub mod demo_meetings;19
pub mod demo_profiles;20
pub mod demo_profiles;@@ -120,11 +120,33 @@ impl AppState {
120
120
}
121
121
122
122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {
123
self.with_one_on_one(user_id, cx, |state, chat_id, cx| {
124
state.select(Selection::Chat(chat_id.to_owned()), cx)
125
});
126
}
127
128
/// Teams starts a 1:1 call from the profile card; the 1:1 chat is the call thread.
129
pub fn call_person(&mut self, user_id: &str, with_video: bool, cx: &mut Context<Self>) {
130
self.with_one_on_one(user_id, cx, move |state, chat_id, cx| {
131
if with_video {
132
state.start_chat_video_call(chat_id, cx);
133
} else {
134
state.start_chat_call(chat_id, cx);
135
}
136
});
137
}
138
139
fn with_one_on_one(
140
&mut self,
141
user_id: &str,
142
cx: &mut Context<Self>,
143
then: impl FnOnce(&mut Self, &str, &mut Context<Self>) + 'static,
144
) {
123
145
let existing =
124
146
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)
125
147
.map(|chat| chat.id.clone());
126
148
if let Some(chat_id) = existing {
127
self.select(Selection::Chat(chat_id), cx);
149
then(self, &chat_id, cx);
128
150
return;
129
151
}
130
152
if self.mode.read_only {
@@ -149,7 +171,7 @@ impl AppState {
149
171
this.update(cx, |state, cx| match outcome {
150
172
Ok(chat_id) => {
151
173
state.reload_sidebar(cx);
152
state.select(Selection::Chat(chat_id), cx);
174
then(state, &chat_id, cx);
153
175
}
154
176
Err(reason) => {
155
177
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)
@@ -120,11 +120,33 @@ impl AppState {120
}120
}121
121
122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {123
self.with_one_on_one(user_id, cx, |state, chat_id, cx| {124
state.select(Selection::Chat(chat_id.to_owned()), cx)125
});126
}127
128
/// Teams starts a 1:1 call from the profile card; the 1:1 chat is the call thread.129
pub fn call_person(&mut self, user_id: &str, with_video: bool, cx: &mut Context<Self>) {130
self.with_one_on_one(user_id, cx, move |state, chat_id, cx| {131
if with_video {132
state.start_chat_video_call(chat_id, cx);133
} else {134
state.start_chat_call(chat_id, cx);135
}136
});137
}138
139
fn with_one_on_one(140
&mut self,141
user_id: &str,142
cx: &mut Context<Self>,143
then: impl FnOnce(&mut Self, &str, &mut Context<Self>) + 'static,144
) {123
let existing =145
let existing =124
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)146
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)125
.map(|chat| chat.id.clone());147
.map(|chat| chat.id.clone());126
if let Some(chat_id) = existing {148
if let Some(chat_id) = existing {127
self.select(Selection::Chat(chat_id), cx);149
then(self, &chat_id, cx);128
return;150
return;129
}151
}130
if self.mode.read_only {152
if self.mode.read_only {@@ -149,7 +171,7 @@ impl AppState {149
this.update(cx, |state, cx| match outcome {171
this.update(cx, |state, cx| match outcome {150
Ok(chat_id) => {172
Ok(chat_id) => {151
state.reload_sidebar(cx);173
state.reload_sidebar(cx);152
state.select(Selection::Chat(chat_id), cx);174
then(state, &chat_id, cx);153
}175
}154
Err(reason) => {176
Err(reason) => {155
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)177
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)@@ -38,16 +38,17 @@ mod render_env;
38
38
mod scheduled;
39
39
mod shared;
40
40
41
use super::add_people_dialog::open_add_people;
41
42
use super::attachments::FileActions;
42
43
use super::avatar::{
43
44
bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
44
45
};
45
46
use super::call_controls::header_call_controls;
46
47
use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
47
use super::add_people_dialog::open_add_people;
48
48
use super::chat_members::members_popover;
49
49
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
50
use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
50
use super::group_name::group_name_button;
51
use super::message_actions::{Action, DelegateEntry, MessageMenu};
51
52
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
52
53
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
53
54
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
@@ -3025,6 +3026,7 @@ impl ConversationView {
3025
3026
let saved = self
3026
3027
.conversation_id()
3027
3028
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3029
let quick = state.quick_reactions();
3028
3030
let in_chat = chat_id.is_some();
3029
3031
let pin_conversation_id = self.pin_conversation_id();
3030
3032
let pinned = pin_conversation_id
@@ -3063,7 +3065,7 @@ impl ConversationView {
3063
3065
pin,
3064
3066
hover,
3065
3067
picker: self.picker.clone(),
3066
quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
3068
quick,
3067
3069
mine,
3068
3070
done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3069
3071
}
@@ -3258,6 +3260,7 @@ impl ConversationView {
3258
3260
let mut lead: Option<AnyElement> = None;
3259
3261
let mut subline = String::new();
3260
3262
let mut stack: Option<AnyElement> = None;
3263
let mut rename: Option<AnyElement> = None;
3261
3264
match ¤t.selection {
3262
3265
Selection::Chat(chat_id) => {
3263
3266
if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3293,6 +3296,15 @@ impl ConversationView {
3293
3296
stack = Some(add_people_button(&self.app, chat_id));
3294
3297
}
3295
3298
} else {
3299
if chat.kind == GROUP_KIND
3300
&& me.is_some_and(|me| {
3301
chat.members
3302
.iter()
3303
.any(|member| member.user_id.as_deref() == Some(&me.user_id))
3304
})
3305
{
3306
rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3307
}
3296
3308
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3297
3309
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3298
3310
subline = format!("{} participants", chat.members.len());
@@ -3395,12 +3407,19 @@ impl ConversationView {
3395
3407
.overflow_hidden()
3396
3408
.gap(px(1.))
3397
3409
.child(
3398
div()
3399
.truncate()
3400
.text_size(px(15.))
3401
.font_weight(FontWeight::SEMIBOLD)
3402
.text_color(theme::text())
3403
.child(current.title.clone()),
3410
h_flex()
3411
.min_w_0()
3412
.gap(px(2.))
3413
.items_center()
3414
.child(
3415
div()
3416
.truncate()
3417
.text_size(px(15.))
3418
.font_weight(FontWeight::SEMIBOLD)
3419
.text_color(theme::text())
3420
.child(current.title.clone()),
3421
)
3422
.children(rename),
3404
3423
)
3405
3424
.when(!subline.is_empty(), |column| {
3406
3425
column.child(
@@ -3418,6 +3437,8 @@ impl ConversationView {
3418
3437
}
3419
3438
}
3420
3439
3440
const GROUP_KIND: &str = "group";
3441
3421
3442
impl Render for ConversationView {
3422
3443
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3423
3444
let background = theme::surface();
@@ -38,16 +38,17 @@ mod render_env;38
mod scheduled;38
mod scheduled;39
mod shared;39
mod shared;40
40
41
use super::add_people_dialog::open_add_people;41
use super::attachments::FileActions;42
use super::attachments::FileActions;42
use super::avatar::{43
use super::avatar::{43
bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,44
bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,44
};45
};45
use super::call_controls::header_call_controls;46
use super::call_controls::header_call_controls;46
use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};47
use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};47
use super::add_people_dialog::open_add_people;48
use super::chat_members::members_popover;48
use super::chat_members::members_popover;49
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};49
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};50
use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};50
use super::group_name::group_name_button;51
use super::message_actions::{Action, DelegateEntry, MessageMenu};51
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};52
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};52
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};53
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};53
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};54
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};@@ -3025,6 +3026,7 @@ impl ConversationView {3025
let saved = self3026
let saved = self3026
.conversation_id()3027
.conversation_id()3027
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));3028
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));3029
let quick = state.quick_reactions();3028
let in_chat = chat_id.is_some();3030
let in_chat = chat_id.is_some();3029
let pin_conversation_id = self.pin_conversation_id();3031
let pin_conversation_id = self.pin_conversation_id();3030
let pinned = pin_conversation_id3032
let pinned = pin_conversation_id@@ -3063,7 +3065,7 @@ impl ConversationView {3063
pin,3065
pin,3064
hover,3066
hover,3065
picker: self.picker.clone(),3067
picker: self.picker.clone(),3066
quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),3068
quick,3067
mine,3069
mine,3068
done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),3070
done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),3069
}3071
}@@ -3258,6 +3260,7 @@ impl ConversationView {3258
let mut lead: Option<AnyElement> = None;3260
let mut lead: Option<AnyElement> = None;3259
let mut subline = String::new();3261
let mut subline = String::new();3260
let mut stack: Option<AnyElement> = None;3262
let mut stack: Option<AnyElement> = None;3263
let mut rename: Option<AnyElement> = None;3261
match ¤t.selection {3264
match ¤t.selection {3262
Selection::Chat(chat_id) => {3265
Selection::Chat(chat_id) => {3263
if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {3266
if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {@@ -3293,6 +3296,15 @@ impl ConversationView {3293
stack = Some(add_people_button(&self.app, chat_id));3296
stack = Some(add_people_button(&self.app, chat_id));3294
}3297
}3295
} else {3298
} else {3299
if chat.kind == GROUP_KIND3300
&& me.is_some_and(|me| {3301
chat.members3302
.iter()3303
.any(|member| member.user_id.as_deref() == Some(&me.user_id))3304
})3305
{3306
rename = Some(group_name_button(&self.app, chat_id, &chat.title));3307
}3296
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));3308
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));3297
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));3309
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));3298
subline = format!("{} participants", chat.members.len());3310
subline = format!("{} participants", chat.members.len());@@ -3395,12 +3407,19 @@ impl ConversationView {3395
.overflow_hidden()3407
.overflow_hidden()3396
.gap(px(1.))3408
.gap(px(1.))3397
.child(3409
.child(3398
div()3410
h_flex()3399
.truncate()3411
.min_w_0()3400
.text_size(px(15.))3412
.gap(px(2.))3401
.font_weight(FontWeight::SEMIBOLD)3413
.items_center()3402
.text_color(theme::text())3414
.child(3403
.child(current.title.clone()),3415
div()3416
.truncate()3417
.text_size(px(15.))3418
.font_weight(FontWeight::SEMIBOLD)3419
.text_color(theme::text())3420
.child(current.title.clone()),3421
)3422
.children(rename),3404
)3423
)3405
.when(!subline.is_empty(), |column| {3424
.when(!subline.is_empty(), |column| {3406
column.child(3425
column.child(@@ -3418,6 +3437,8 @@ impl ConversationView {3418
}3437
}3419
}3438
}3420
3439
3440
const GROUP_KIND: &str = "group";3441
3421
impl Render for ConversationView {3442
impl Render for ConversationView {3422
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {3443
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {3423
let background = theme::surface();3444
let background = theme::surface();@@ -0,0 +1,263 @@
1
use std::collections::HashSet;
2
use std::rc::Rc;
3
4
use gpui_kit::assets::IconName;
5
use gpui_kit::component::button::{Button, ButtonVariants as _};
6
use gpui_kit::component::dialog::{Dialog, DialogFooter};
7
use gpui_kit::component::popover::Popover;
8
use gpui_kit::component::tooltip::Tooltip;
9
use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};
10
use gpui_kit::prelude::FluentBuilder as _;
11
use gpui_kit::*;
12
13
use super::reaction_picker::ReactionPicker;
14
use super::widgets::{Corner, corner_badge, icon};
15
use crate::app_state::AppState;
16
use crate::default_reactions::{
17
filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,
18
};
19
use crate::emoji;
20
use crate::emoticons::{SKIN_TONE_COUNT, with_tone};
21
use crate::theme;
22
23
pub const CUSTOMIZE_TOOLTIP: &str = "Customise default reactions";
24
const TITLE: &str = "Customise your reactions and appearance in Teams";
25
const DESCRIPTION: &str = "Click on a reaction below, then choose an emoji to replace it with.";
26
const SKIN_TONE_TEXT: &str =
27
"Choose a skin tone. After selection, reactions and emoji will appear with this skin tone.";
28
const CHOOSE_EMOJI: &str = "Choose an emoji";
29
const REMOVE_REACTION: &str = "Remove reaction";
30
const TONE_SAMPLE: &str = "\u{1F44D}";
31
const DIALOG_WIDTH: f32 = 440.;
32
const SLOT_SIZE: f32 = 48.;
33
const SLOT_GLYPH_SIZE: f32 = 26.;
34
const TONE_SIZE: f32 = 36.;
35
const TONE_GLYPH_SIZE: f32 = 20.;
36
const REMOVE_SIZE: f32 = 18.;
37
const REMOVE_OVERHANG: f32 = 5.;
38
const SECTION_GAP: f32 = 16.;
39
const TEXT_SIZE: f32 = 13.;
40
41
struct CustomizeForm {
42
state: Entity<AppState>,
43
picker: Entity<ReactionPicker>,
44
saved_ids: Vec<String>,
45
saved_tone: u8,
46
slots: Vec<Option<String>>,
47
skin_tone: u8,
48
}
49
50
impl CustomizeForm {
51
fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
52
let (saved_ids, saved_tone, store) = {
53
let app = state.read(cx);
54
(
55
app.default_reactions(),
56
teams_core::skin_tone(&app.store),
57
app.store.clone(),
58
)
59
};
60
let recent = cx.new(|_| emoji::Recent::load(&store));
61
let picker_state = state.clone();
62
let picker =
63
cx.new(|cx| ReactionPicker::new(picker_state, recent, window, cx).for_customizing());
64
CustomizeForm {
65
state,
66
picker,
67
slots: slots_for(&saved_ids),
68
saved_ids,
69
saved_tone,
70
skin_tone: saved_tone,
71
}
72
}
73
74
fn unchanged(&self) -> bool {
75
filled(&self.slots) == self.saved_ids && self.skin_tone == self.saved_tone
76
}
77
78
fn place(&mut self, index: usize, glyph: &str, cx: &mut Context<Self>) {
79
if let Some(reaction_id) = reaction_id_for_glyph(glyph) {
80
place_in_slot(&mut self.slots, index, reaction_id);
81
cx.notify();
82
}
83
}
84
85
fn remove(&mut self, index: usize, cx: &mut Context<Self>) {
86
if let Some(slot) = self.slots.get_mut(index) {
87
*slot = None;
88
cx.notify();
89
}
90
}
91
92
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
93
let reaction_ids = filled(&self.slots);
94
let (tone_changed, tone) = (self.skin_tone != self.saved_tone, self.skin_tone);
95
self.state.update(cx, |state, cx| {
96
if tone_changed {
97
state.set_skin_tone(tone, cx);
98
}
99
state.set_default_reactions(reaction_ids, cx);
100
});
101
window.close_dialog(cx);
102
}
103
104
fn slot_glyph(&self, reaction_id: &str) -> Option<String> {
105
quick_reaction_glyphs(&[reaction_id.to_owned()], self.skin_tone)
106
.into_iter()
107
.next()
108
}
109
110
fn slot(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
111
let glyph = self
112
.slots
113
.get(index)
114
.cloned()
115
.flatten()
116
.and_then(|reaction_id| self.slot_glyph(&reaction_id));
117
let label = if glyph.is_some() {
118
REMOVE_REACTION
119
} else {
120
CHOOSE_EMOJI
121
};
122
let trigger = Button::new(("customize-reaction-slot", index))
123
.size(px(SLOT_SIZE))
124
.rounded(px(10.))
125
.tooltip(label)
126
.map(|button| match &glyph {
127
Some(glyph) => {
128
button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))
129
}
130
None => button.child(icon(IconName::Plus, 18., theme::text_muted())),
131
});
132
let (picker, view) = (self.picker.clone(), cx.entity().downgrade());
133
let selected: HashSet<String> = glyph.iter().cloned().collect();
134
let popover = Popover::new(("customize-reaction-picker", index))
135
.anchor(Anchor::TopLeft)
136
.trigger(trigger)
137
.on_open_change({
138
let picker = self.picker.clone();
139
move |open, window, cx| {
140
if *open {
141
picker.update(cx, |picker, cx| picker.reset(window, cx));
142
}
143
}
144
})
145
.content(move |_, _, cx| {
146
let popover = cx.entity().downgrade();
147
let view = view.clone();
148
picker.update(cx, |picker, _| {
149
picker.set_target(
150
Rc::new(move |glyph, _, cx| {
151
view.update(cx, |form, cx| form.place(index, glyph, cx))
152
.ok();
153
}),
154
Rc::new(|_, _| {}),
155
popover,
156
selected.clone(),
157
)
158
});
159
picker.clone()
160
});
161
let remove = glyph.is_some().then(|| {
162
corner_badge(Corner::TopRight, REMOVE_OVERHANG).child(
163
div()
164
.id(("customize-reaction-remove", index))
165
.size(px(REMOVE_SIZE))
166
.flex()
167
.items_center()
168
.justify_center()
169
.rounded_full()
170
.cursor_pointer()
171
.bg(theme::popup_hover())
172
.hover(|button| button.bg(theme::row_hover()))
173
.child(icon(IconName::X, 10., theme::text_soft()))
174
.tooltip(|window, cx| Tooltip::new(REMOVE_REACTION).build(window, cx))
175
.on_click(cx.listener(move |form, _, _, cx| {
176
cx.stop_propagation();
177
form.remove(index, cx);
178
})),
179
)
180
});
181
div()
182
.relative()
183
.child(popover)
184
.children(remove)
185
.into_any_element()
186
}
187
188
fn tone_choice(&self, tone: u8, cx: &mut Context<Self>) -> AnyElement {
189
let selected = tone == self.skin_tone;
190
div()
191
.id(("customize-skin-tone", usize::from(tone)))
192
.size(px(TONE_SIZE))
193
.flex()
194
.items_center()
195
.justify_center()
196
.rounded_full()
197
.cursor_pointer()
198
.text_size(px(TONE_GLYPH_SIZE))
199
.when(selected, |choice| choice.bg(theme::reaction_on_own()))
200
.when(!selected, |choice| {
201
choice.hover(|choice| choice.bg(theme::popup_hover()))
202
})
203
.child(with_tone(TONE_SAMPLE, tone))
204
.on_click(cx.listener(move |form, _, _, cx| {
205
form.skin_tone = tone;
206
cx.notify();
207
}))
208
.into_any_element()
209
}
210
}
211
212
impl Render for CustomizeForm {
213
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
214
let slots: Vec<AnyElement> = (0..self.slots.len())
215
.map(|index| self.slot(index, cx))
216
.collect();
217
let tones: Vec<AnyElement> = (0..=SKIN_TONE_COUNT)
218
.map(|tone| self.tone_choice(tone, cx))
219
.collect();
220
v_flex()
221
.gap(px(SECTION_GAP))
222
.text_size(px(TEXT_SIZE))
223
.text_color(theme::text())
224
.child(div().text_color(theme::text_soft()).child(DESCRIPTION))
225
.child(
226
h_flex()
227
.justify_center()
228
.gap(px(10.))
229
.py(px(4.))
230
.children(slots),
231
)
232
.child(div().text_color(theme::text_soft()).child(SKIN_TONE_TEXT))
233
.child(h_flex().gap(px(6.)).children(tones))
234
}
235
}
236
237
pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
238
let form = cx.new(|cx| CustomizeForm::new(state, window, cx));
239
window.open_dialog(cx, move |dialog: Dialog, _, cx| {
240
let submit_form = form.clone();
241
let unchanged = form.read(cx).unchanged();
242
let footer = DialogFooter::new()
243
.child(
244
Button::new("customize-reactions-cancel")
245
.label("Cancel")
246
.on_click(|_, window, cx| window.close_dialog(cx)),
247
)
248
.child(
249
Button::new("customize-reactions-save")
250
.primary()
251
.label("Save")
252
.disabled(unchanged)
253
.on_click(move |_, window, cx| {
254
submit_form.update(cx, |form, cx| form.save(window, cx));
255
}),
256
);
257
dialog
258
.title(TITLE)
259
.w(px(DIALOG_WIDTH))
260
.child(form.clone())
261
.footer(footer)
262
});
263
}
@@ -0,0 +1,263 @@1
use std::collections::HashSet;2
use std::rc::Rc;3
4
use gpui_kit::assets::IconName;5
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::dialog::{Dialog, DialogFooter};7
use gpui_kit::component::popover::Popover;8
use gpui_kit::component::tooltip::Tooltip;9
use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;12
13
use super::reaction_picker::ReactionPicker;14
use super::widgets::{Corner, corner_badge, icon};15
use crate::app_state::AppState;16
use crate::default_reactions::{17
filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,18
};19
use crate::emoji;20
use crate::emoticons::{SKIN_TONE_COUNT, with_tone};21
use crate::theme;22
23
pub const CUSTOMIZE_TOOLTIP: &str = "Customise default reactions";24
const TITLE: &str = "Customise your reactions and appearance in Teams";25
const DESCRIPTION: &str = "Click on a reaction below, then choose an emoji to replace it with.";26
const SKIN_TONE_TEXT: &str =27
"Choose a skin tone. After selection, reactions and emoji will appear with this skin tone.";28
const CHOOSE_EMOJI: &str = "Choose an emoji";29
const REMOVE_REACTION: &str = "Remove reaction";30
const TONE_SAMPLE: &str = "\u{1F44D}";31
const DIALOG_WIDTH: f32 = 440.;32
const SLOT_SIZE: f32 = 48.;33
const SLOT_GLYPH_SIZE: f32 = 26.;34
const TONE_SIZE: f32 = 36.;35
const TONE_GLYPH_SIZE: f32 = 20.;36
const REMOVE_SIZE: f32 = 18.;37
const REMOVE_OVERHANG: f32 = 5.;38
const SECTION_GAP: f32 = 16.;39
const TEXT_SIZE: f32 = 13.;40
41
struct CustomizeForm {42
state: Entity<AppState>,43
picker: Entity<ReactionPicker>,44
saved_ids: Vec<String>,45
saved_tone: u8,46
slots: Vec<Option<String>>,47
skin_tone: u8,48
}49
50
impl CustomizeForm {51
fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {52
let (saved_ids, saved_tone, store) = {53
let app = state.read(cx);54
(55
app.default_reactions(),56
teams_core::skin_tone(&app.store),57
app.store.clone(),58
)59
};60
let recent = cx.new(|_| emoji::Recent::load(&store));61
let picker_state = state.clone();62
let picker =63
cx.new(|cx| ReactionPicker::new(picker_state, recent, window, cx).for_customizing());64
CustomizeForm {65
state,66
picker,67
slots: slots_for(&saved_ids),68
saved_ids,69
saved_tone,70
skin_tone: saved_tone,71
}72
}73
74
fn unchanged(&self) -> bool {75
filled(&self.slots) == self.saved_ids && self.skin_tone == self.saved_tone76
}77
78
fn place(&mut self, index: usize, glyph: &str, cx: &mut Context<Self>) {79
if let Some(reaction_id) = reaction_id_for_glyph(glyph) {80
place_in_slot(&mut self.slots, index, reaction_id);81
cx.notify();82
}83
}84
85
fn remove(&mut self, index: usize, cx: &mut Context<Self>) {86
if let Some(slot) = self.slots.get_mut(index) {87
*slot = None;88
cx.notify();89
}90
}91
92
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {93
let reaction_ids = filled(&self.slots);94
let (tone_changed, tone) = (self.skin_tone != self.saved_tone, self.skin_tone);95
self.state.update(cx, |state, cx| {96
if tone_changed {97
state.set_skin_tone(tone, cx);98
}99
state.set_default_reactions(reaction_ids, cx);100
});101
window.close_dialog(cx);102
}103
104
fn slot_glyph(&self, reaction_id: &str) -> Option<String> {105
quick_reaction_glyphs(&[reaction_id.to_owned()], self.skin_tone)106
.into_iter()107
.next()108
}109
110
fn slot(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {111
let glyph = self112
.slots113
.get(index)114
.cloned()115
.flatten()116
.and_then(|reaction_id| self.slot_glyph(&reaction_id));117
let label = if glyph.is_some() {118
REMOVE_REACTION119
} else {120
CHOOSE_EMOJI121
};122
let trigger = Button::new(("customize-reaction-slot", index))123
.size(px(SLOT_SIZE))124
.rounded(px(10.))125
.tooltip(label)126
.map(|button| match &glyph {127
Some(glyph) => {128
button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))129
}130
None => button.child(icon(IconName::Plus, 18., theme::text_muted())),131
});132
let (picker, view) = (self.picker.clone(), cx.entity().downgrade());133
let selected: HashSet<String> = glyph.iter().cloned().collect();134
let popover = Popover::new(("customize-reaction-picker", index))135
.anchor(Anchor::TopLeft)136
.trigger(trigger)137
.on_open_change({138
let picker = self.picker.clone();139
move |open, window, cx| {140
if *open {141
picker.update(cx, |picker, cx| picker.reset(window, cx));142
}143
}144
})145
.content(move |_, _, cx| {146
let popover = cx.entity().downgrade();147
let view = view.clone();148
picker.update(cx, |picker, _| {149
picker.set_target(150
Rc::new(move |glyph, _, cx| {151
view.update(cx, |form, cx| form.place(index, glyph, cx))152
.ok();153
}),154
Rc::new(|_, _| {}),155
popover,156
selected.clone(),157
)158
});159
picker.clone()160
});161
let remove = glyph.is_some().then(|| {162
corner_badge(Corner::TopRight, REMOVE_OVERHANG).child(163
div()164
.id(("customize-reaction-remove", index))165
.size(px(REMOVE_SIZE))166
.flex()167
.items_center()168
.justify_center()169
.rounded_full()170
.cursor_pointer()171
.bg(theme::popup_hover())172
.hover(|button| button.bg(theme::row_hover()))173
.child(icon(IconName::X, 10., theme::text_soft()))174
.tooltip(|window, cx| Tooltip::new(REMOVE_REACTION).build(window, cx))175
.on_click(cx.listener(move |form, _, _, cx| {176
cx.stop_propagation();177
form.remove(index, cx);178
})),179
)180
});181
div()182
.relative()183
.child(popover)184
.children(remove)185
.into_any_element()186
}187
188
fn tone_choice(&self, tone: u8, cx: &mut Context<Self>) -> AnyElement {189
let selected = tone == self.skin_tone;190
div()191
.id(("customize-skin-tone", usize::from(tone)))192
.size(px(TONE_SIZE))193
.flex()194
.items_center()195
.justify_center()196
.rounded_full()197
.cursor_pointer()198
.text_size(px(TONE_GLYPH_SIZE))199
.when(selected, |choice| choice.bg(theme::reaction_on_own()))200
.when(!selected, |choice| {201
choice.hover(|choice| choice.bg(theme::popup_hover()))202
})203
.child(with_tone(TONE_SAMPLE, tone))204
.on_click(cx.listener(move |form, _, _, cx| {205
form.skin_tone = tone;206
cx.notify();207
}))208
.into_any_element()209
}210
}211
212
impl Render for CustomizeForm {213
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {214
let slots: Vec<AnyElement> = (0..self.slots.len())215
.map(|index| self.slot(index, cx))216
.collect();217
let tones: Vec<AnyElement> = (0..=SKIN_TONE_COUNT)218
.map(|tone| self.tone_choice(tone, cx))219
.collect();220
v_flex()221
.gap(px(SECTION_GAP))222
.text_size(px(TEXT_SIZE))223
.text_color(theme::text())224
.child(div().text_color(theme::text_soft()).child(DESCRIPTION))225
.child(226
h_flex()227
.justify_center()228
.gap(px(10.))229
.py(px(4.))230
.children(slots),231
)232
.child(div().text_color(theme::text_soft()).child(SKIN_TONE_TEXT))233
.child(h_flex().gap(px(6.)).children(tones))234
}235
}236
237
pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx: &mut App) {238
let form = cx.new(|cx| CustomizeForm::new(state, window, cx));239
window.open_dialog(cx, move |dialog: Dialog, _, cx| {240
let submit_form = form.clone();241
let unchanged = form.read(cx).unchanged();242
let footer = DialogFooter::new()243
.child(244
Button::new("customize-reactions-cancel")245
.label("Cancel")246
.on_click(|_, window, cx| window.close_dialog(cx)),247
)248
.child(249
Button::new("customize-reactions-save")250
.primary()251
.label("Save")252
.disabled(unchanged)253
.on_click(move |_, window, cx| {254
submit_form.update(cx, |form, cx| form.save(window, cx));255
}),256
);257
dialog258
.title(TITLE)259
.w(px(DIALOG_WIDTH))260
.child(form.clone())261
.footer(footer)262
});263
}@@ -0,0 +1,196 @@
1
use std::cell::RefCell;
2
use std::rc::Rc;
3
4
use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};
5
use gpui_kit::assets::IconName;
6
use gpui_kit::base::PopoverState;
7
use gpui_kit::component::button::{Button, ButtonVariants as _};
8
use gpui_kit::component::input::{Input, InputEvent, InputState};
9
use gpui_kit::component::popover::Popover;
10
use gpui_kit::component::{Disableable as _, h_flex, v_flex};
11
use gpui_kit::prelude::FluentBuilder as _;
12
use gpui_kit::*;
13
14
use super::widgets::icon;
15
use crate::app_state::AppState;
16
use crate::theme;
17
18
const BUTTON_TOOLTIP: &str = "Name group chat";
19
const FIELD_LABEL: &str = "Group name";
20
const PLACEHOLDER: &str = "Type a group name";
21
const FORM_WIDTH: f32 = 300.;
22
const FORM_PADDING: f32 = 12.;
23
const FORM_GAP: f32 = 8.;
24
const LABEL_SIZE: f32 = 12.;
25
const ICON_SIZE: f32 = 16.;
26
27
pub fn problem_text(problem: TopicProblem) -> String {
28
match problem {
29
TopicProblem::TooLong => {
30
format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")
31
}
32
TopicProblem::InvalidCharacter => {
33
format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")
34
}
35
}
36
}
37
38
struct GroupNameForm {
39
app: Entity<AppState>,
40
chat_id: String,
41
input: Entity<InputState>,
42
popover: WeakEntity<PopoverState>,
43
_subscription: Subscription,
44
}
45
46
impl GroupNameForm {
47
fn new(
48
app: Entity<AppState>,
49
chat_id: String,
50
title: String,
51
popover: WeakEntity<PopoverState>,
52
window: &mut Window,
53
cx: &mut Context<Self>,
54
) -> Self {
55
let input = cx.new(|cx| {
56
let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);
57
state.set_value(title, window, cx);
58
state
59
});
60
input.update(cx, |state, cx| state.focus(window, cx));
61
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62
GroupNameForm {
63
app,
64
chat_id,
65
input,
66
popover,
67
_subscription: subscription,
68
}
69
}
70
71
fn on_input_event(
72
&mut self,
73
_: &Entity<InputState>,
74
event: &InputEvent,
75
window: &mut Window,
76
cx: &mut Context<Self>,
77
) {
78
match event {
79
InputEvent::Change => cx.notify(),
80
InputEvent::PressEnter { .. } => self.save(window, cx),
81
_ => {}
82
}
83
}
84
85
fn problem(&self, cx: &App) -> Option<TopicProblem> {
86
topic_problem(self.input.read(cx).value().trim())
87
}
88
89
fn close(&self, window: &mut Window, cx: &mut App) {
90
self.popover
91
.update(cx, |state, cx| state.dismiss(window, cx))
92
.ok();
93
}
94
95
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
96
if self.problem(cx).is_some() {
97
return;
98
}
99
let topic = self.input.read(cx).value().trim().to_owned();
100
let chat_id = self.chat_id.clone();
101
self.app
102
.update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));
103
self.close(window, cx);
104
}
105
}
106
107
impl Render for GroupNameForm {
108
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
109
let problem = self.problem(cx);
110
v_flex()
111
.w(px(FORM_WIDTH))
112
.p(px(FORM_PADDING))
113
.gap(px(FORM_GAP))
114
.child(
115
div()
116
.text_size(px(LABEL_SIZE))
117
.text_color(theme::text_soft())
118
.child(FIELD_LABEL),
119
)
120
.child(Input::new(&self.input))
121
.when_some(problem, |form, problem| {
122
form.child(
123
div()
124
.text_size(px(LABEL_SIZE))
125
.text_color(theme::red_soft())
126
.child(problem_text(problem)),
127
)
128
})
129
.child(
130
h_flex()
131
.justify_end()
132
.gap(px(FORM_GAP))
133
.child(
134
Button::new("group-name-cancel")
135
.label("Cancel")
136
.on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
137
)
138
.child(
139
Button::new("group-name-save")
140
.primary()
141
.label("Save")
142
.disabled(problem.is_some())
143
.on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
144
),
145
)
146
}
147
}
148
149
pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {
150
let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
151
let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();
152
let reset = form.clone();
153
Popover::new("group-name")
154
.anchor(Anchor::TopLeft)
155
.p(px(0.))
156
.trigger(
157
Button::new("group-name-button")
158
.ghost()
159
.compact()
160
.tooltip(BUTTON_TOOLTIP)
161
.child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),
162
)
163
.on_open_change(move |open, _, _| {
164
if !*open {
165
reset.borrow_mut().take();
166
}
167
})
168
.content(move |_, window, cx| {
169
if let Some(existing) = form.borrow().clone() {
170
return existing;
171
}
172
let popover = cx.entity().downgrade();
173
let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());
174
let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));
175
*form.borrow_mut() = Some(created.clone());
176
created
177
})
178
.into_any_element()
179
}
180
181
#[cfg(test)]
182
mod tests {
183
use super::{TopicProblem, problem_text};
184
185
#[test]
186
fn problems_use_the_teams_wording() {
187
assert_eq!(
188
problem_text(TopicProblem::TooLong),
189
"Your group name can't be longer than 250 characters."
190
);
191
assert_eq!(
192
problem_text(TopicProblem::InvalidCharacter),
193
"':' is not a valid character in group names."
194
);
195
}
196
}
@@ -0,0 +1,196 @@1
use std::cell::RefCell;2
use std::rc::Rc;3
4
use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};5
use gpui_kit::assets::IconName;6
use gpui_kit::base::PopoverState;7
use gpui_kit::component::button::{Button, ButtonVariants as _};8
use gpui_kit::component::input::{Input, InputEvent, InputState};9
use gpui_kit::component::popover::Popover;10
use gpui_kit::component::{Disableable as _, h_flex, v_flex};11
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;13
14
use super::widgets::icon;15
use crate::app_state::AppState;16
use crate::theme;17
18
const BUTTON_TOOLTIP: &str = "Name group chat";19
const FIELD_LABEL: &str = "Group name";20
const PLACEHOLDER: &str = "Type a group name";21
const FORM_WIDTH: f32 = 300.;22
const FORM_PADDING: f32 = 12.;23
const FORM_GAP: f32 = 8.;24
const LABEL_SIZE: f32 = 12.;25
const ICON_SIZE: f32 = 16.;26
27
pub fn problem_text(problem: TopicProblem) -> String {28
match problem {29
TopicProblem::TooLong => {30
format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")31
}32
TopicProblem::InvalidCharacter => {33
format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")34
}35
}36
}37
38
struct GroupNameForm {39
app: Entity<AppState>,40
chat_id: String,41
input: Entity<InputState>,42
popover: WeakEntity<PopoverState>,43
_subscription: Subscription,44
}45
46
impl GroupNameForm {47
fn new(48
app: Entity<AppState>,49
chat_id: String,50
title: String,51
popover: WeakEntity<PopoverState>,52
window: &mut Window,53
cx: &mut Context<Self>,54
) -> Self {55
let input = cx.new(|cx| {56
let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);57
state.set_value(title, window, cx);58
state59
});60
input.update(cx, |state, cx| state.focus(window, cx));61
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);62
GroupNameForm {63
app,64
chat_id,65
input,66
popover,67
_subscription: subscription,68
}69
}70
71
fn on_input_event(72
&mut self,73
_: &Entity<InputState>,74
event: &InputEvent,75
window: &mut Window,76
cx: &mut Context<Self>,77
) {78
match event {79
InputEvent::Change => cx.notify(),80
InputEvent::PressEnter { .. } => self.save(window, cx),81
_ => {}82
}83
}84
85
fn problem(&self, cx: &App) -> Option<TopicProblem> {86
topic_problem(self.input.read(cx).value().trim())87
}88
89
fn close(&self, window: &mut Window, cx: &mut App) {90
self.popover91
.update(cx, |state, cx| state.dismiss(window, cx))92
.ok();93
}94
95
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {96
if self.problem(cx).is_some() {97
return;98
}99
let topic = self.input.read(cx).value().trim().to_owned();100
let chat_id = self.chat_id.clone();101
self.app102
.update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));103
self.close(window, cx);104
}105
}106
107
impl Render for GroupNameForm {108
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {109
let problem = self.problem(cx);110
v_flex()111
.w(px(FORM_WIDTH))112
.p(px(FORM_PADDING))113
.gap(px(FORM_GAP))114
.child(115
div()116
.text_size(px(LABEL_SIZE))117
.text_color(theme::text_soft())118
.child(FIELD_LABEL),119
)120
.child(Input::new(&self.input))121
.when_some(problem, |form, problem| {122
form.child(123
div()124
.text_size(px(LABEL_SIZE))125
.text_color(theme::red_soft())126
.child(problem_text(problem)),127
)128
})129
.child(130
h_flex()131
.justify_end()132
.gap(px(FORM_GAP))133
.child(134
Button::new("group-name-cancel")135
.label("Cancel")136
.on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),137
)138
.child(139
Button::new("group-name-save")140
.primary()141
.label("Save")142
.disabled(problem.is_some())143
.on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),144
),145
)146
}147
}148
149
pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {150
let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());151
let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();152
let reset = form.clone();153
Popover::new("group-name")154
.anchor(Anchor::TopLeft)155
.p(px(0.))156
.trigger(157
Button::new("group-name-button")158
.ghost()159
.compact()160
.tooltip(BUTTON_TOOLTIP)161
.child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),162
)163
.on_open_change(move |open, _, _| {164
if !*open {165
reset.borrow_mut().take();166
}167
})168
.content(move |_, window, cx| {169
if let Some(existing) = form.borrow().clone() {170
return existing;171
}172
let popover = cx.entity().downgrade();173
let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());174
let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));175
*form.borrow_mut() = Some(created.clone());176
created177
})178
.into_any_element()179
}180
181
#[cfg(test)]182
mod tests {183
use super::{TopicProblem, problem_text};184
185
#[test]186
fn problems_use_the_teams_wording() {187
assert_eq!(188
problem_text(TopicProblem::TooLong),189
"Your group name can't be longer than 250 characters."190
);191
assert_eq!(192
problem_text(TopicProblem::InvalidCharacter),193
"':' is not a valid character in group names."194
);195
}196
}@@ -23,7 +23,6 @@ const BAR_PADDING: f32 = 3.;
23
23
const BAR_ICON: f32 = 16.;
24
24
const DELEGATE_ITEM_WIDTH: f32 = 188.;
25
25
const DELEGATE_AGENT_SIZE: f32 = 11.;
26
pub const QUICK_REACTION_COUNT: usize = 4;
27
26
28
27
pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
29
28
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
@@ -23,7 +23,6 @@ const BAR_PADDING: f32 = 3.;23
const BAR_ICON: f32 = 16.;23
const BAR_ICON: f32 = 16.;24
const DELEGATE_ITEM_WIDTH: f32 = 188.;24
const DELEGATE_ITEM_WIDTH: f32 = 188.;25
const DELEGATE_AGENT_SIZE: f32 = 11.;25
const DELEGATE_AGENT_SIZE: f32 = 11.;26
pub const QUICK_REACTION_COUNT: usize = 4;27
26
28
pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;27
pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;29
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;28
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;@@ -38,11 +38,13 @@ pub mod chat_members;
38
38
pub mod composer;
39
39
pub mod connection_banner;
40
40
pub mod conversation;
41
pub mod customize_reactions;
41
42
pub mod dialog_overlay;
42
43
pub mod emoji_popup;
43
44
pub mod format_toolbar;
44
45
pub mod forward_dialog;
45
46
pub mod fun_picker;
47
pub mod group_name;
46
48
pub mod image_menu;
47
49
pub mod image_viewer;
48
50
pub mod join_dialog;
@@ -38,11 +38,13 @@ pub mod chat_members;38
pub mod composer;38
pub mod composer;39
pub mod connection_banner;39
pub mod connection_banner;40
pub mod conversation;40
pub mod conversation;41
pub mod customize_reactions;41
pub mod dialog_overlay;42
pub mod dialog_overlay;42
pub mod emoji_popup;43
pub mod emoji_popup;43
pub mod format_toolbar;44
pub mod format_toolbar;44
pub mod forward_dialog;45
pub mod forward_dialog;45
pub mod fun_picker;46
pub mod fun_picker;47
pub mod group_name;46
pub mod image_menu;48
pub mod image_menu;47
pub mod image_viewer;49
pub mod image_viewer;48
pub mod join_dialog;50
pub mod join_dialog;@@ -12,7 +12,7 @@ use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
12
12
use gpui_kit::prelude::FluentBuilder as _;
13
13
use gpui_kit::*;
14
14
15
use super::new_chat::NewChatDraft;
15
use super::new_chat::{NewChatDraft, Pick};
16
16
use super::widgets::icon;
17
17
use crate::app_state::AppState;
18
18
use crate::call::{FormValues, Invitee, default_window, draft_from_form};
@@ -233,7 +233,20 @@ impl Render for MeetingForm {
233
233
}
234
234
235
235
pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
236
open_new_meeting_with(state, Vec::new(), window, cx);
237
}
238
239
pub fn open_new_meeting_with(
240
state: Entity<AppState>,
241
people: Vec<Pick>,
242
window: &mut Window,
243
cx: &mut App,
244
) {
236
245
let form = cx.new(|cx| MeetingForm::new(state, window, cx));
246
if !people.is_empty() {
247
let draft = form.read(cx).people.clone();
248
draft.update(cx, |draft, cx| draft.set_chips(people, cx));
249
}
237
250
let first_field = form.read(cx).title.clone();
238
251
window.open_dialog(cx, move |dialog: Dialog, _, cx| {
239
252
let submit_form = form.clone();
@@ -12,7 +12,7 @@ use gpui_kit::component::{WindowExt as _, h_flex, v_flex};12
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::prelude::FluentBuilder as _;13
use gpui_kit::*;13
use gpui_kit::*;14
14
15
use super::new_chat::NewChatDraft;15
use super::new_chat::{NewChatDraft, Pick};16
use super::widgets::icon;16
use super::widgets::icon;17
use crate::app_state::AppState;17
use crate::app_state::AppState;18
use crate::call::{FormValues, Invitee, default_window, draft_from_form};18
use crate::call::{FormValues, Invitee, default_window, draft_from_form};@@ -233,7 +233,20 @@ impl Render for MeetingForm {233
}233
}234
234
235
pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {235
pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {236
open_new_meeting_with(state, Vec::new(), window, cx);237
}238
239
pub fn open_new_meeting_with(240
state: Entity<AppState>,241
people: Vec<Pick>,242
window: &mut Window,243
cx: &mut App,244
) {236
let form = cx.new(|cx| MeetingForm::new(state, window, cx));245
let form = cx.new(|cx| MeetingForm::new(state, window, cx));246
if !people.is_empty() {247
let draft = form.read(cx).people.clone();248
draft.update(cx, |draft, cx| draft.set_chips(people, cx));249
}237
let first_field = form.read(cx).title.clone();250
let first_field = form.read(cx).title.clone();238
window.open_dialog(cx, move |dialog: Dialog, _, cx| {251
window.open_dialog(cx, move |dialog: Dialog, _, cx| {239
let submit_form = form.clone();252
let submit_form = form.clone();@@ -9,6 +9,8 @@ use gpui_kit::*;
9
9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};
10
10
11
11
use super::avatar::{person_avatar, with_presence};
12
use super::new_chat::Pick;
13
use super::new_meeting_dialog::open_new_meeting_with;
12
14
use super::widgets::icon;
13
15
use crate::app_state::{AppHandle, AppState};
14
16
use crate::data::{Presence, PresenceKind, presence_kind_of};
@@ -31,6 +33,9 @@ const STATUS_LINES: usize = 3;
31
33
const REPORTS_MAX_HEIGHT: f32 = 168.;
32
34
const ACTION_HEIGHT: f32 = 30.;
33
35
const SKELETON_HEIGHT: f32 = 10.;
36
const SCHEDULE_MEETING: &str = "Schedule meeting";
37
const EMAIL: &str = "Email";
38
const COPY_EMAIL: &str = "Copy email";
34
39
35
40
pub enum ProfileCardEvent {
36
41
Close,
@@ -255,25 +260,76 @@ impl ProfileCard {
255
260
.me
256
261
.as_ref()
257
262
.is_some_and(|me| me.user_id == self.user_id);
263
let profile = self
264
.app
265
.read(cx)
266
.profiles
267
.get(&self.user_id)
268
.and_then(|entry| entry.profile.clone());
269
let name = self.display_name(profile.as_deref(), cx);
258
270
let user_id = self.user_id.clone();
259
271
let (mail_email, copy_email) = (email.clone(), email.clone());
272
let invitee = Pick {
273
user_id: user_id.clone(),
274
name: name.clone(),
275
mail: email,
276
};
277
let chat_id = user_id.clone();
278
let (video_id, audio_id) = (user_id.clone(), user_id.clone());
260
279
h_flex()
261
280
.gap(px(8.))
262
281
.when(!is_me, |row| {
263
282
row.child(
264
283
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(
265
284
cx.listener(move |this, _, _, cx| {
266
let user_id = user_id.clone();
285
let user_id = chat_id.clone();
267
286
this.app
268
287
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));
269
288
cx.emit(ProfileCardEvent::Close);
270
289
}),
271
290
),
272
291
)
292
.child(
293
icon_action(
294
"profile-video-call",
295
IconName::Video,
296
video_call_tooltip(&name),
297
)
298
.on_click(cx.listener(move |this, _, _, cx| {
299
let user_id = video_id.clone();
300
this.app
301
.update(cx, |state, cx| state.call_person(&user_id, true, cx));
302
cx.emit(ProfileCardEvent::Close);
303
})),
304
)
305
.child(
306
icon_action(
307
"profile-audio-call",
308
IconName::Phone,
309
audio_call_tooltip(&name),
310
)
311
.on_click(cx.listener(move |this, _, _, cx| {
312
let user_id = audio_id.clone();
313
this.app
314
.update(cx, |state, cx| state.call_person(&user_id, false, cx));
315
cx.emit(ProfileCardEvent::Close);
316
})),
317
)
318
.child(
319
icon_action(
320
"profile-schedule-meeting",
321
IconName::Calendar,
322
SCHEDULE_MEETING.to_owned(),
323
)
324
.on_click(cx.listener(move |this, _, window, cx| {
325
open_new_meeting_with(this.app.clone(), vec![invitee.clone()], window, cx);
326
cx.emit(ProfileCardEvent::Close);
327
})),
328
)
273
329
})
274
330
.when_some(mail_email, |row, address| {
275
331
row.child(
276
action_button("profile-email", "Email", IconName::Mail, false).on_click(
332
icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
277
333
cx.listener(move |_, _, _, cx| {
278
334
cx.open_url(&mailto_url(&address));
279
335
cx.emit(ProfileCardEvent::Close);
@@ -283,7 +339,7 @@ impl ProfileCard {
283
339
})
284
340
.when_some(copy_email, |row, address| {
285
341
row.child(
286
action_button("profile-copy-email", "Copy email", IconName::Copy, false)
342
icon_action("profile-copy-email", IconName::Copy, COPY_EMAIL.to_owned())
287
343
.on_click(cx.listener(move |this, _, _, cx| {
288
344
this.app
289
345
.update(cx, |state, cx| state.copy_profile_email(&address, cx));
@@ -557,6 +613,30 @@ fn contact_row(row: ContactRow) -> Div {
557
613
)
558
614
}
559
615
616
pub fn video_call_tooltip(name: &str) -> String {
617
format!("Start a video call with {name}")
618
}
619
620
pub fn audio_call_tooltip(name: &str) -> String {
621
format!("Start an audio call with {name}")
622
}
623
624
fn icon_action(id: &'static str, glyph: IconName, tooltip: String) -> Stateful<Div> {
625
div()
626
.id(id)
627
.size(px(ACTION_HEIGHT))
628
.flex()
629
.flex_none()
630
.items_center()
631
.justify_center()
632
.rounded(px(6.))
633
.cursor_pointer()
634
.bg(theme::popup_hover())
635
.hover(|button| button.opacity(0.9))
636
.child(icon(glyph, 14., theme::text_soft()))
637
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
638
}
639
560
640
fn action_button(
561
641
id: &'static str,
562
642
label: &'static str,
@@ -664,3 +744,14 @@ impl Render for ProfileCard {
664
744
)
665
745
}
666
746
}
747
748
#[cfg(test)]
749
mod tests {
750
use super::{audio_call_tooltip, video_call_tooltip};
751
752
#[test]
753
fn call_tooltips_use_the_teams_wording() {
754
assert_eq!(video_call_tooltip("Ann"), "Start a video call with Ann");
755
assert_eq!(audio_call_tooltip("Ann"), "Start an audio call with Ann");
756
}
757
}
@@ -9,6 +9,8 @@ use gpui_kit::*;9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};10
10
11
use super::avatar::{person_avatar, with_presence};11
use super::avatar::{person_avatar, with_presence};12
use super::new_chat::Pick;13
use super::new_meeting_dialog::open_new_meeting_with;12
use super::widgets::icon;14
use super::widgets::icon;13
use crate::app_state::{AppHandle, AppState};15
use crate::app_state::{AppHandle, AppState};14
use crate::data::{Presence, PresenceKind, presence_kind_of};16
use crate::data::{Presence, PresenceKind, presence_kind_of};@@ -31,6 +33,9 @@ const STATUS_LINES: usize = 3;31
const REPORTS_MAX_HEIGHT: f32 = 168.;33
const REPORTS_MAX_HEIGHT: f32 = 168.;32
const ACTION_HEIGHT: f32 = 30.;34
const ACTION_HEIGHT: f32 = 30.;33
const SKELETON_HEIGHT: f32 = 10.;35
const SKELETON_HEIGHT: f32 = 10.;36
const SCHEDULE_MEETING: &str = "Schedule meeting";37
const EMAIL: &str = "Email";38
const COPY_EMAIL: &str = "Copy email";34
39
35
pub enum ProfileCardEvent {40
pub enum ProfileCardEvent {36
Close,41
Close,@@ -255,25 +260,76 @@ impl ProfileCard {255
.me260
.me256
.as_ref()261
.as_ref()257
.is_some_and(|me| me.user_id == self.user_id);262
.is_some_and(|me| me.user_id == self.user_id);263
let profile = self264
.app265
.read(cx)266
.profiles267
.get(&self.user_id)268
.and_then(|entry| entry.profile.clone());269
let name = self.display_name(profile.as_deref(), cx);258
let user_id = self.user_id.clone();270
let user_id = self.user_id.clone();259
let (mail_email, copy_email) = (email.clone(), email.clone());271
let (mail_email, copy_email) = (email.clone(), email.clone());272
let invitee = Pick {273
user_id: user_id.clone(),274
name: name.clone(),275
mail: email,276
};277
let chat_id = user_id.clone();278
let (video_id, audio_id) = (user_id.clone(), user_id.clone());260
h_flex()279
h_flex()261
.gap(px(8.))280
.gap(px(8.))262
.when(!is_me, |row| {281
.when(!is_me, |row| {263
row.child(282
row.child(264
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(283
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(265
cx.listener(move |this, _, _, cx| {284
cx.listener(move |this, _, _, cx| {266
let user_id = user_id.clone();285
let user_id = chat_id.clone();267
this.app286
this.app268
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));287
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));269
cx.emit(ProfileCardEvent::Close);288
cx.emit(ProfileCardEvent::Close);270
}),289
}),271
),290
),272
)291
)292
.child(293
icon_action(294
"profile-video-call",295
IconName::Video,296
video_call_tooltip(&name),297
)298
.on_click(cx.listener(move |this, _, _, cx| {299
let user_id = video_id.clone();300
this.app301
.update(cx, |state, cx| state.call_person(&user_id, true, cx));302
cx.emit(ProfileCardEvent::Close);303
})),304
)305
.child(306
icon_action(307
"profile-audio-call",308
IconName::Phone,309
audio_call_tooltip(&name),310
)311
.on_click(cx.listener(move |this, _, _, cx| {312
let user_id = audio_id.clone();313
this.app314
.update(cx, |state, cx| state.call_person(&user_id, false, cx));315
cx.emit(ProfileCardEvent::Close);316
})),317
)318
.child(319
icon_action(320
"profile-schedule-meeting",321
IconName::Calendar,322
SCHEDULE_MEETING.to_owned(),323
)324
.on_click(cx.listener(move |this, _, window, cx| {325
open_new_meeting_with(this.app.clone(), vec![invitee.clone()], window, cx);326
cx.emit(ProfileCardEvent::Close);327
})),328
)273
})329
})274
.when_some(mail_email, |row, address| {330
.when_some(mail_email, |row, address| {275
row.child(331
row.child(276
action_button("profile-email", "Email", IconName::Mail, false).on_click(332
icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(277
cx.listener(move |_, _, _, cx| {333
cx.listener(move |_, _, _, cx| {278
cx.open_url(&mailto_url(&address));334
cx.open_url(&mailto_url(&address));279
cx.emit(ProfileCardEvent::Close);335
cx.emit(ProfileCardEvent::Close);@@ -283,7 +339,7 @@ impl ProfileCard {283
})339
})284
.when_some(copy_email, |row, address| {340
.when_some(copy_email, |row, address| {285
row.child(341
row.child(286
action_button("profile-copy-email", "Copy email", IconName::Copy, false)342
icon_action("profile-copy-email", IconName::Copy, COPY_EMAIL.to_owned())287
.on_click(cx.listener(move |this, _, _, cx| {343
.on_click(cx.listener(move |this, _, _, cx| {288
this.app344
this.app289
.update(cx, |state, cx| state.copy_profile_email(&address, cx));345
.update(cx, |state, cx| state.copy_profile_email(&address, cx));@@ -557,6 +613,30 @@ fn contact_row(row: ContactRow) -> Div {557
)613
)558
}614
}559
615
616
pub fn video_call_tooltip(name: &str) -> String {617
format!("Start a video call with {name}")618
}619
620
pub fn audio_call_tooltip(name: &str) -> String {621
format!("Start an audio call with {name}")622
}623
624
fn icon_action(id: &'static str, glyph: IconName, tooltip: String) -> Stateful<Div> {625
div()626
.id(id)627
.size(px(ACTION_HEIGHT))628
.flex()629
.flex_none()630
.items_center()631
.justify_center()632
.rounded(px(6.))633
.cursor_pointer()634
.bg(theme::popup_hover())635
.hover(|button| button.opacity(0.9))636
.child(icon(glyph, 14., theme::text_soft()))637
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))638
}639
560
fn action_button(640
fn action_button(561
id: &'static str,641
id: &'static str,562
label: &'static str,642
label: &'static str,@@ -664,3 +744,14 @@ impl Render for ProfileCard {664
)744
)665
}745
}666
}746
}747
748
#[cfg(test)]749
mod tests {750
use super::{audio_call_tooltip, video_call_tooltip};751
752
#[test]753
fn call_tooltips_use_the_teams_wording() {754
assert_eq!(video_call_tooltip("Ann"), "Start a video call with Ann");755
assert_eq!(audio_call_tooltip("Ann"), "Start an audio call with Ann");756
}757
}@@ -10,7 +10,12 @@ use gpui_kit::component::{
10
10
use gpui_kit::prelude::FluentBuilder as _;
11
11
use gpui_kit::*;
12
12
13
use gpui_kit::assets::IconName;
14
use gpui_kit::component::tooltip::Tooltip;
15
16
use super::customize_reactions::{CUSTOMIZE_TOOLTIP, open_customize_reactions};
13
17
use super::skin_tone_choices::{tone_badge, tone_choices};
18
use super::widgets::icon;
14
19
use crate::app_state::AppState;
15
20
use crate::emoji;
16
21
use crate::emoticons;
@@ -67,6 +72,7 @@ pub struct ReactionPicker {
67
72
target: Option<PickTarget>,
68
73
skin_tone: u8,
69
74
tone_menu: Option<(String, Point<Pixels>)>,
75
customizing: bool,
70
76
_subscription: Subscription,
71
77
}
72
78
@@ -88,10 +94,16 @@ impl ReactionPicker {
88
94
target: None,
89
95
skin_tone: 0,
90
96
tone_menu: None,
97
customizing: false,
91
98
_subscription: subscription,
92
99
}
93
100
}
94
101
102
pub fn for_customizing(mut self) -> Self {
103
self.customizing = true;
104
self
105
}
106
95
107
pub fn set_target(
96
108
&mut self,
97
109
on_pick: PickHandler,
@@ -195,10 +207,43 @@ impl ReactionPicker {
195
207
196
208
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {
197
209
self.skin_tone = tone;
198
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
210
if !self.customizing {
211
self.app
212
.update(cx, |state, cx| state.set_skin_tone(tone, cx));
213
}
199
214
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);
200
215
}
201
216
217
fn open_customize(&mut self, window: &mut Window, cx: &mut Context<Self>) {
218
if let Some(target) = self.target.take() {
219
target
220
.popover
221
.update(cx, |state, cx| state.dismiss(window, cx))
222
.ok();
223
(target.on_done)(window, cx);
224
}
225
open_customize_reactions(self.app.clone(), window, cx);
226
}
227
228
fn customize_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
229
(!self.customizing).then(|| {
230
div()
231
.id("customize-reactions-trigger")
232
.size(px(CELL_SIZE))
233
.flex_none()
234
.flex()
235
.items_center()
236
.justify_center()
237
.rounded(px(8.))
238
.cursor_pointer()
239
.hover(|button| button.bg(theme::popup_hover()))
240
.child(icon(IconName::Settings, 16., theme::text_soft()))
241
.tooltip(|window, cx| Tooltip::new(CUSTOMIZE_TOOLTIP).build(window, cx))
242
.on_click(cx.listener(|this, _, window, cx| this.open_customize(window, cx)))
243
.into_any_element()
244
})
245
}
246
202
247
fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
203
248
let (base, position) = self.tone_menu.clone()?;
204
249
let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());
@@ -303,14 +348,21 @@ impl Render for ReactionPicker {
303
348
.p(px(8.))
304
349
.child(h_flex().gap(px(2.)).children(quick))
305
350
.child(
306
div()
307
.h(px(32.))
308
.px(px(8.))
309
.flex()
351
h_flex()
352
.gap(px(4.))
310
353
.items_center()
311
.rounded(px(8.))
312
.bg(theme::popup_hover())
313
.child(Input::new(&self.input).appearance(false).bordered(false)),
354
.child(
355
div()
356
.flex_1()
357
.h(px(32.))
358
.px(px(8.))
359
.flex()
360
.items_center()
361
.rounded(px(8.))
362
.bg(theme::popup_hover())
363
.child(Input::new(&self.input).appearance(false).bordered(false)),
364
)
365
.children(self.customize_button(cx)),
314
366
)
315
367
.child(
316
368
div()
@@ -10,7 +10,12 @@ use gpui_kit::component::{10
use gpui_kit::prelude::FluentBuilder as _;10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;11
use gpui_kit::*;12
12
13
use gpui_kit::assets::IconName;14
use gpui_kit::component::tooltip::Tooltip;15
16
use super::customize_reactions::{CUSTOMIZE_TOOLTIP, open_customize_reactions};13
use super::skin_tone_choices::{tone_badge, tone_choices};17
use super::skin_tone_choices::{tone_badge, tone_choices};18
use super::widgets::icon;14
use crate::app_state::AppState;19
use crate::app_state::AppState;15
use crate::emoji;20
use crate::emoji;16
use crate::emoticons;21
use crate::emoticons;@@ -67,6 +72,7 @@ pub struct ReactionPicker {67
target: Option<PickTarget>,72
target: Option<PickTarget>,68
skin_tone: u8,73
skin_tone: u8,69
tone_menu: Option<(String, Point<Pixels>)>,74
tone_menu: Option<(String, Point<Pixels>)>,75
customizing: bool,70
_subscription: Subscription,76
_subscription: Subscription,71
}77
}72
78
@@ -88,10 +94,16 @@ impl ReactionPicker {88
target: None,94
target: None,89
skin_tone: 0,95
skin_tone: 0,90
tone_menu: None,96
tone_menu: None,97
customizing: false,91
_subscription: subscription,98
_subscription: subscription,92
}99
}93
}100
}94
101
102
pub fn for_customizing(mut self) -> Self {103
self.customizing = true;104
self105
}106
95
pub fn set_target(107
pub fn set_target(96
&mut self,108
&mut self,97
on_pick: PickHandler,109
on_pick: PickHandler,@@ -195,10 +207,43 @@ impl ReactionPicker {195
207
196
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {208
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {197
self.skin_tone = tone;209
self.skin_tone = tone;198
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));210
if !self.customizing {211
self.app212
.update(cx, |state, cx| state.set_skin_tone(tone, cx));213
}199
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);214
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);200
}215
}201
216
217
fn open_customize(&mut self, window: &mut Window, cx: &mut Context<Self>) {218
if let Some(target) = self.target.take() {219
target220
.popover221
.update(cx, |state, cx| state.dismiss(window, cx))222
.ok();223
(target.on_done)(window, cx);224
}225
open_customize_reactions(self.app.clone(), window, cx);226
}227
228
fn customize_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {229
(!self.customizing).then(|| {230
div()231
.id("customize-reactions-trigger")232
.size(px(CELL_SIZE))233
.flex_none()234
.flex()235
.items_center()236
.justify_center()237
.rounded(px(8.))238
.cursor_pointer()239
.hover(|button| button.bg(theme::popup_hover()))240
.child(icon(IconName::Settings, 16., theme::text_soft()))241
.tooltip(|window, cx| Tooltip::new(CUSTOMIZE_TOOLTIP).build(window, cx))242
.on_click(cx.listener(|this, _, window, cx| this.open_customize(window, cx)))243
.into_any_element()244
})245
}246
202
fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {247
fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {203
let (base, position) = self.tone_menu.clone()?;248
let (base, position) = self.tone_menu.clone()?;204
let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());249
let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());@@ -303,14 +348,21 @@ impl Render for ReactionPicker {303
.p(px(8.))348
.p(px(8.))304
.child(h_flex().gap(px(2.)).children(quick))349
.child(h_flex().gap(px(2.)).children(quick))305
.child(350
.child(306
div()351
h_flex()307
.h(px(32.))352
.gap(px(4.))308
.px(px(8.))309
.flex()310
.items_center()353
.items_center()311
.rounded(px(8.))354
.child(312
.bg(theme::popup_hover())355
div()313
.child(Input::new(&self.input).appearance(false).bordered(false)),356
.flex_1()357
.h(px(32.))358
.px(px(8.))359
.flex()360
.items_center()361
.rounded(px(8.))362
.bg(theme::popup_hover())363
.child(Input::new(&self.input).appearance(false).bordered(false)),364
)365
.children(self.customize_button(cx)),314
)366
)315
.child(367
.child(316
div()368
div()@@ -235,6 +235,17 @@ fn chat_menu(
235
235
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
236
236
}),
237
237
);
238
if !target.is_group {
239
let remove_state = context.state.clone();
240
let remove_id = target.id.clone();
241
popup = popup.item(
242
PopupMenuItem::new(REMOVE_HISTORY_LABEL)
243
.icon(menu_icon(IconName::Trash))
244
.on_click(move |_, window, cx| {
245
confirm_remove_history(&remove_state, &remove_id, window, cx);
246
}),
247
);
248
}
238
249
if target.is_group {
239
250
let leave_state = context.state.clone();
240
251
let leave_id = target.id.clone();
@@ -446,6 +457,40 @@ fn leave_description(member_count: usize) -> String {
446
457
format!("{who} {verb} that you left. You can only come back if someone adds you.")
447
458
}
448
459
460
const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
461
const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
462
const REMOVE_HISTORY_TEXT: &str =
463
"This will remove the chat from your list and search. It affects you only.";
464
465
fn confirm_remove_history(
466
state: &Entity<AppState>,
467
chat_id: &str,
468
window: &mut Window,
469
cx: &mut App,
470
) {
471
let state = state.clone();
472
let chat_id = chat_id.to_owned();
473
window.open_alert_dialog(cx, move |alert, _, _| {
474
let state = state.clone();
475
let chat_id = chat_id.clone();
476
let cancel = Button::new("remove-history-cancel")
477
.label("Cancel")
478
.on_click(|_, window, cx| window.close_dialog(cx));
479
let remove = Button::new("remove-history-confirm")
480
.label("Remove")
481
.primary()
482
.on_click(move |_, window, cx| {
483
state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
484
window.close_dialog(cx);
485
});
486
alert
487
.title(REMOVE_HISTORY_TITLE)
488
.description(REMOVE_HISTORY_TEXT)
489
.footer(DialogFooter::new().child(cancel).child(remove))
490
.on_ok(|_, _, _| false)
491
});
492
}
493
449
494
pub(crate) fn confirm_leave(
450
495
state: &Entity<AppState>,
451
496
chat_id: &str,
@@ -235,6 +235,17 @@ fn chat_menu(235
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));235
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));236
}),236
}),237
);237
);238
if !target.is_group {239
let remove_state = context.state.clone();240
let remove_id = target.id.clone();241
popup = popup.item(242
PopupMenuItem::new(REMOVE_HISTORY_LABEL)243
.icon(menu_icon(IconName::Trash))244
.on_click(move |_, window, cx| {245
confirm_remove_history(&remove_state, &remove_id, window, cx);246
}),247
);248
}238
if target.is_group {249
if target.is_group {239
let leave_state = context.state.clone();250
let leave_state = context.state.clone();240
let leave_id = target.id.clone();251
let leave_id = target.id.clone();@@ -446,6 +457,40 @@ fn leave_description(member_count: usize) -> String {446
format!("{who} {verb} that you left. You can only come back if someone adds you.")457
format!("{who} {verb} that you left. You can only come back if someone adds you.")447
}458
}448
459
460
const REMOVE_HISTORY_LABEL: &str = "Remove chat history";461
const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";462
const REMOVE_HISTORY_TEXT: &str =463
"This will remove the chat from your list and search. It affects you only.";464
465
fn confirm_remove_history(466
state: &Entity<AppState>,467
chat_id: &str,468
window: &mut Window,469
cx: &mut App,470
) {471
let state = state.clone();472
let chat_id = chat_id.to_owned();473
window.open_alert_dialog(cx, move |alert, _, _| {474
let state = state.clone();475
let chat_id = chat_id.clone();476
let cancel = Button::new("remove-history-cancel")477
.label("Cancel")478
.on_click(|_, window, cx| window.close_dialog(cx));479
let remove = Button::new("remove-history-confirm")480
.label("Remove")481
.primary()482
.on_click(move |_, window, cx| {483
state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));484
window.close_dialog(cx);485
});486
alert487
.title(REMOVE_HISTORY_TITLE)488
.description(REMOVE_HISTORY_TEXT)489
.footer(DialogFooter::new().child(cancel).child(remove))490
.on_ok(|_, _, _| false)491
});492
}493
449
pub(crate) fn confirm_leave(494
pub(crate) fn confirm_leave(450
state: &Entity<AppState>,495
state: &Entity<AppState>,451
chat_id: &str,496
chat_id: &str,@@ -10,6 +10,7 @@ use crate::read_horizon::{self, ReadHorizon};
10
10
const PAGE_SIZE: usize = 200;
11
11
const MAX_PAGES: usize = 100;
12
12
const ALERTS_OFF: &str = "false";
13
const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
13
14
14
15
#[derive(Debug, Clone, PartialEq, Eq)]
15
16
pub struct ConversationState {
@@ -17,6 +18,7 @@ pub struct ConversationState {
17
18
pub muted: bool,
18
19
pub hidden: Option<bool>,
19
20
pub read: ReadHorizon,
21
pub history_cleared_ms: Option<i64>,
20
22
}
21
23
22
24
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -84,6 +86,19 @@ impl<T: MessageTransport> Conversations<T> {
84
86
ensure_success(&answer)
85
87
}
86
88
89
/// Teams' "Remove chat history": everything up to this time disappears for the current user only.
90
pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {
91
let answer = self
92
.transport
93
.send(clear_history_request(
94
&self.base_url,
95
conversation_id,
96
cleared_until_ms,
97
))
98
.await?;
99
ensure_success(&answer)
100
}
101
87
102
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88
103
let url = format!(
89
104
"{}/{}/properties?name={}",
@@ -118,6 +133,29 @@ impl<T: MessageTransport> Conversations<T> {
118
133
}
119
134
}
120
135
136
pub fn clear_history_request(
137
base_url: &str,
138
conversation_id: &str,
139
cleared_until_ms: i64,
140
) -> Request {
141
Request::with_body(
142
Method::Put,
143
format!(
144
"{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",
145
encode(conversation_id)
146
),
147
json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),
148
)
149
}
150
151
fn history_cleared_ms(conversation: &Value) -> Option<i64> {
152
let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
153
value
154
.as_i64()
155
.or_else(|| value.as_str()?.parse().ok())
156
.filter(|millis| *millis > 0)
157
}
158
121
159
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122
160
pub fn thread_url(region: &str, thread_id: &str) -> String {
123
161
format!(
@@ -167,6 +205,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
167
205
muted,
168
206
hidden: hidden_flag(conversation),
169
207
read: ReadHorizon::from_conversation(conversation),
208
history_cleared_ms: history_cleared_ms(conversation),
170
209
})
171
210
})
172
211
.collect())
@@ -211,6 +250,7 @@ mod tests {
211
250
muted,
212
251
hidden: None,
213
252
read: ReadHorizon::default(),
253
history_cleared_ms: None,
214
254
}
215
255
}
216
256
@@ -383,6 +423,52 @@ mod tests {
383
423
assert!(states[0].read.is_unread("8:orgid:me"));
384
424
}
385
425
426
#[tokio::test]
427
async fn clear_history_puts_the_time_as_a_number() {
428
let transport = canned(vec![(200, Value::Null)]);
429
Conversations::with_transport(&transport, "emea")
430
.clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)
431
.await
432
.unwrap();
433
let requests = transport.requests.lock().unwrap();
434
assert_eq!(requests[0].method, Method::Put);
435
assert_eq!(
436
requests[0].url,
437
format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")
438
);
439
assert_eq!(
440
requests[0].body,
441
Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))
442
);
443
}
444
445
#[tokio::test]
446
async fn states_carry_the_clear_history_time_as_text_or_number() {
447
let transport = canned(vec![(
448
200,
449
json!({
450
"conversations": [
451
{"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},
452
{"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},
453
{"id": "19:c", "properties": {"clearHistoryTime": "0"}},
454
{"id": "19:d"},
455
],
456
}),
457
)]);
458
let states = Conversations::with_transport(&transport, "emea")
459
.conversation_states()
460
.await
461
.unwrap();
462
let cleared: Vec<Option<i64>> = states
463
.iter()
464
.map(|state| state.history_cleared_ms)
465
.collect();
466
assert_eq!(
467
cleared,
468
[Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]
469
);
470
}
471
386
472
#[tokio::test]
387
473
async fn set_read_horizon_puts_the_consumption_horizon_property() {
388
474
let transport = canned(vec![(200, Value::Null)]);
@@ -10,6 +10,7 @@ use crate::read_horizon::{self, ReadHorizon};10
const PAGE_SIZE: usize = 200;10
const PAGE_SIZE: usize = 200;11
const MAX_PAGES: usize = 100;11
const MAX_PAGES: usize = 100;12
const ALERTS_OFF: &str = "false";12
const ALERTS_OFF: &str = "false";13
const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";13
14
14
#[derive(Debug, Clone, PartialEq, Eq)]15
#[derive(Debug, Clone, PartialEq, Eq)]15
pub struct ConversationState {16
pub struct ConversationState {@@ -17,6 +18,7 @@ pub struct ConversationState {17
pub muted: bool,18
pub muted: bool,18
pub hidden: Option<bool>,19
pub hidden: Option<bool>,19
pub read: ReadHorizon,20
pub read: ReadHorizon,21
pub history_cleared_ms: Option<i64>,20
}22
}21
23
22
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {24
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {@@ -84,6 +86,19 @@ impl<T: MessageTransport> Conversations<T> {84
ensure_success(&answer)86
ensure_success(&answer)85
}87
}86
88
89
/// Teams' "Remove chat history": everything up to this time disappears for the current user only.90
pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {91
let answer = self92
.transport93
.send(clear_history_request(94
&self.base_url,95
conversation_id,96
cleared_until_ms,97
))98
.await?;99
ensure_success(&answer)100
}101
87
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {102
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {88
let url = format!(103
let url = format!(89
"{}/{}/properties?name={}",104
"{}/{}/properties?name={}",@@ -118,6 +133,29 @@ impl<T: MessageTransport> Conversations<T> {118
}133
}119
}134
}120
135
136
pub fn clear_history_request(137
base_url: &str,138
conversation_id: &str,139
cleared_until_ms: i64,140
) -> Request {141
Request::with_body(142
Method::Put,143
format!(144
"{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",145
encode(conversation_id)146
),147
json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),148
)149
}150
151
fn history_cleared_ms(conversation: &Value) -> Option<i64> {152
let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];153
value154
.as_i64()155
.or_else(|| value.as_str()?.parse().ok())156
.filter(|millis| *millis > 0)157
}158
121
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.159
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.122
pub fn thread_url(region: &str, thread_id: &str) -> String {160
pub fn thread_url(region: &str, thread_id: &str) -> String {123
format!(161
format!(@@ -167,6 +205,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {167
muted,205
muted,168
hidden: hidden_flag(conversation),206
hidden: hidden_flag(conversation),169
read: ReadHorizon::from_conversation(conversation),207
read: ReadHorizon::from_conversation(conversation),208
history_cleared_ms: history_cleared_ms(conversation),170
})209
})171
})210
})172
.collect())211
.collect())@@ -211,6 +250,7 @@ mod tests {211
muted,250
muted,212
hidden: None,251
hidden: None,213
read: ReadHorizon::default(),252
read: ReadHorizon::default(),253
history_cleared_ms: None,214
}254
}215
}255
}216
256
@@ -383,6 +423,52 @@ mod tests {383
assert!(states[0].read.is_unread("8:orgid:me"));423
assert!(states[0].read.is_unread("8:orgid:me"));384
}424
}385
425
426
#[tokio::test]427
async fn clear_history_puts_the_time_as_a_number() {428
let transport = canned(vec![(200, Value::Null)]);429
Conversations::with_transport(&transport, "emea")430
.clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)431
.await432
.unwrap();433
let requests = transport.requests.lock().unwrap();434
assert_eq!(requests[0].method, Method::Put);435
assert_eq!(436
requests[0].url,437
format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")438
);439
assert_eq!(440
requests[0].body,441
Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))442
);443
}444
445
#[tokio::test]446
async fn states_carry_the_clear_history_time_as_text_or_number() {447
let transport = canned(vec![(448
200,449
json!({450
"conversations": [451
{"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},452
{"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},453
{"id": "19:c", "properties": {"clearHistoryTime": "0"}},454
{"id": "19:d"},455
],456
}),457
)]);458
let states = Conversations::with_transport(&transport, "emea")459
.conversation_states()460
.await461
.unwrap();462
let cleared: Vec<Option<i64>> = states463
.iter()464
.map(|state| state.history_cleared_ms)465
.collect();466
assert_eq!(467
cleared,468
[Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]469
);470
}471
386
#[tokio::test]472
#[tokio::test]387
async fn set_read_horizon_puts_the_consumption_horizon_property() {473
async fn set_read_horizon_puts_the_consumption_horizon_property() {388
let transport = canned(vec![(200, Value::Null)]);474
let transport = canned(vec![(200, Value::Null)]);@@ -59,7 +59,10 @@ pub use language_settings::{
59
59
};
60
60
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
61
61
pub use mask::mask_conversation_id;
62
pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
62
pub use members::{
63
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
64
TopicProblem, topic_problem,
65
};
63
66
pub use messages::{ConversationRef, Messages};
64
67
pub use pins::{
65
68
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
@@ -59,7 +59,10 @@ pub use language_settings::{59
};59
};60
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};60
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};61
pub use mask::mask_conversation_id;61
pub use mask::mask_conversation_id;62
pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};62
pub use members::{63
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,64
TopicProblem, topic_problem,65
};63
pub use messages::{ConversationRef, Messages};66
pub use messages::{ConversationRef, Messages};64
pub use pins::{67
pub use pins::{65
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,68
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;
8
8
const ORGID_PREFIX: &str = "8:orgid:";
9
9
const MEMBER_ROLE: &str = "Admin";
10
10
const DAY_MS: i64 = 86_400_000;
11
const TOPIC_PROPERTY: &str = "topic";
12
pub const MAX_TOPIC_LENGTH: usize = 250;
13
pub const INVALID_TOPIC_CHARACTER: char = ':';
11
14
pub const MAX_HISTORY_DAYS: u32 = 999;
12
15
13
16
/// How much chat history new members see, as the Teams add-people dialog offers it.
@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
80
83
))
81
84
}
82
85
86
/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87
pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88
Request::with_body(
89
Method::Put,
90
format!(
91
"{}/{}/properties?name={TOPIC_PROPERTY}",
92
threads_url(region),
93
encode(thread_id)
94
),
95
json!({ TOPIC_PROPERTY: topic }),
96
)
97
}
98
99
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100
pub enum TopicProblem {
101
TooLong,
102
InvalidCharacter,
103
}
104
105
pub fn topic_problem(topic: &str) -> Option<TopicProblem> {
106
if topic.chars().count() > MAX_TOPIC_LENGTH {
107
Some(TopicProblem::TooLong)
108
} else if topic.contains(INVALID_TOPIC_CHARACTER) {
109
Some(TopicProblem::InvalidCharacter)
110
} else {
111
None
112
}
113
}
114
83
115
pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84
116
transport: T,
85
117
region: String,
@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {
114
146
let request = remove_member_request(&self.region, thread_id, user_id);
115
147
ensure_success(&self.transport.send(request).await?)
116
148
}
149
150
pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151
let request = topic_request(&self.region, thread_id, topic);
152
ensure_success(&self.transport.send(request).await?)
153
}
117
154
}
118
155
119
156
#[cfg(test)]
@@ -124,6 +161,35 @@ mod tests {
124
161
125
162
use super::*;
126
163
164
#[test]
165
fn topic_is_put_as_the_thread_property() {
166
let request = topic_request("emea", THREAD, "Release crew");
167
assert_eq!(request.method, Method::Put);
168
assert_eq!(
169
request.url,
170
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"
171
);
172
assert_eq!(request.body, Some(json!({"topic": "Release crew"})));
173
assert_eq!(
174
topic_request("emea", THREAD, "").body,
175
Some(json!({"topic": ""}))
176
);
177
}
178
179
#[test]
180
fn topic_rules_follow_teams() {
181
assert_eq!(topic_problem("Release crew"), None);
182
assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);
183
assert_eq!(
184
topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),
185
Some(TopicProblem::TooLong)
186
);
187
assert_eq!(
188
topic_problem("Team: ops"),
189
Some(TopicProblem::InvalidCharacter)
190
);
191
}
192
127
193
const NOW: i64 = 1_792_200_000_000;
128
194
const THREAD: &str = "19:abc@thread.v2";
129
195
@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;8
const ORGID_PREFIX: &str = "8:orgid:";8
const ORGID_PREFIX: &str = "8:orgid:";9
const MEMBER_ROLE: &str = "Admin";9
const MEMBER_ROLE: &str = "Admin";10
const DAY_MS: i64 = 86_400_000;10
const DAY_MS: i64 = 86_400_000;11
const TOPIC_PROPERTY: &str = "topic";12
pub const MAX_TOPIC_LENGTH: usize = 250;13
pub const INVALID_TOPIC_CHARACTER: char = ':';11
pub const MAX_HISTORY_DAYS: u32 = 999;14
pub const MAX_HISTORY_DAYS: u32 = 999;12
15
13
/// How much chat history new members see, as the Teams add-people dialog offers it.16
/// How much chat history new members see, as the Teams add-people dialog offers it.@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re80
))83
))81
}84
}82
85
86
/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.87
pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {88
Request::with_body(89
Method::Put,90
format!(91
"{}/{}/properties?name={TOPIC_PROPERTY}",92
threads_url(region),93
encode(thread_id)94
),95
json!({ TOPIC_PROPERTY: topic }),96
)97
}98
99
#[derive(Debug, Clone, Copy, PartialEq, Eq)]100
pub enum TopicProblem {101
TooLong,102
InvalidCharacter,103
}104
105
pub fn topic_problem(topic: &str) -> Option<TopicProblem> {106
if topic.chars().count() > MAX_TOPIC_LENGTH {107
Some(TopicProblem::TooLong)108
} else if topic.contains(INVALID_TOPIC_CHARACTER) {109
Some(TopicProblem::InvalidCharacter)110
} else {111
None112
}113
}114
83
pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {115
pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {84
transport: T,116
transport: T,85
region: String,117
region: String,@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {114
let request = remove_member_request(&self.region, thread_id, user_id);146
let request = remove_member_request(&self.region, thread_id, user_id);115
ensure_success(&self.transport.send(request).await?)147
ensure_success(&self.transport.send(request).await?)116
}148
}149
150
pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {151
let request = topic_request(&self.region, thread_id, topic);152
ensure_success(&self.transport.send(request).await?)153
}117
}154
}118
155
119
#[cfg(test)]156
#[cfg(test)]@@ -124,6 +161,35 @@ mod tests {124
161
125
use super::*;162
use super::*;126
163
164
#[test]165
fn topic_is_put_as_the_thread_property() {166
let request = topic_request("emea", THREAD, "Release crew");167
assert_eq!(request.method, Method::Put);168
assert_eq!(169
request.url,170
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"171
);172
assert_eq!(request.body, Some(json!({"topic": "Release crew"})));173
assert_eq!(174
topic_request("emea", THREAD, "").body,175
Some(json!({"topic": ""}))176
);177
}178
179
#[test]180
fn topic_rules_follow_teams() {181
assert_eq!(topic_problem("Release crew"), None);182
assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);183
assert_eq!(184
topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),185
Some(TopicProblem::TooLong)186
);187
assert_eq!(188
topic_problem("Team: ops"),189
Some(TopicProblem::InvalidCharacter)190
);191
}192
127
const NOW: i64 = 1_792_200_000_000;193
const NOW: i64 = 1_792_200_000_000;128
const THREAD: &str = "19:abc@thread.v2";194
const THREAD: &str = "19:abc@thread.v2";129
195
@@ -9,6 +9,7 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9
9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10
10
const TEAMS_ORDER_KEY: &str = "teamsOrder";
11
11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12
const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
12
13
const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
13
14
const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
14
15
const MAX_SKIN_TONE: u8 = 5;
@@ -100,6 +101,11 @@ impl<T: MessageTransport> UserSettings<T> {
100
101
.await
101
102
}
102
103
104
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
105
self.set_property(DEFAULT_REACTIONS_KEY, default_reactions_value(reaction_ids))
106
.await
107
}
108
103
109
/// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
104
110
pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
105
111
let properties = self.properties().await?;
@@ -161,6 +167,25 @@ pub fn parse_skin_tone(properties: &Value) -> Option<u8> {
161
167
(tone <= MAX_SKIN_TONE).then_some(tone)
162
168
}
163
169
170
pub fn parse_default_reactions(properties: &Value) -> Option<Vec<String>> {
171
let entries = match properties.get(DEFAULT_REACTIONS_KEY)? {
172
Value::String(text) => serde_json::from_str::<Value>(text).ok()?,
173
other => other.clone(),
174
};
175
entries.as_array().map(|entries| {
176
entries
177
.iter()
178
.filter_map(Value::as_str)
179
.filter(|reaction_id| !reaction_id.is_empty())
180
.map(str::to_owned)
181
.collect()
182
})
183
}
184
185
pub fn default_reactions_value(reaction_ids: &[String]) -> Value {
186
Value::String(Value::from(reaction_ids.to_vec()).to_string())
187
}
188
164
189
pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
165
190
let entries = match properties.get(TEAMS_ORDER_KEY) {
166
191
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
@@ -290,6 +315,53 @@ mod tests {
290
315
assert_eq!(parse_skin_tone(&json!({})), None);
291
316
}
292
317
318
#[test]
319
fn default_reactions_are_read_from_the_json_string_or_an_array() {
320
assert_eq!(
321
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: r#"["like","heart","fire"]"#})),
322
Some(vec![
323
"like".to_owned(),
324
"heart".to_owned(),
325
"fire".to_owned()
326
])
327
);
328
assert_eq!(
329
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: ["yes", "", 3]})),
330
Some(vec!["yes".to_owned()])
331
);
332
assert_eq!(
333
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "[]"})),
334
Some(Vec::new())
335
);
336
assert_eq!(parse_default_reactions(&json!({})), None);
337
assert_eq!(
338
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "not json"})),
339
None
340
);
341
}
342
343
#[tokio::test]
344
async fn default_reactions_are_put_as_a_json_string() {
345
let transport = Canned {
346
answers: Mutex::new(vec![(200, Value::Null)].into()),
347
requests: Mutex::new(Vec::new()),
348
};
349
UserSettings::with_transport(&transport, "emea")
350
.set_default_reactions(&["like".to_owned(), "fire".to_owned()])
351
.await
352
.unwrap();
353
let requests = transport.requests.lock().unwrap();
354
assert_eq!(requests[0].method, Method::Put);
355
assert_eq!(
356
requests[0].url,
357
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=defaultMessageReactions"
358
);
359
assert_eq!(
360
requests[0].body,
361
Some(json!({"defaultMessageReactions": r#"["like","fire"]"#}))
362
);
363
}
364
293
365
#[test]
294
366
fn unset_fields_use_the_teams_defaults() {
295
367
let parsed = parse_chat_sections(&json!({}));
@@ -9,6 +9,7 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";10
const TEAMS_ORDER_KEY: &str = "teamsOrder";10
const TEAMS_ORDER_KEY: &str = "teamsOrder";11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";12
const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";12
const APP_HORIZON_KEY: &str = "appConsumptionHorizon";13
const APP_HORIZON_KEY: &str = "appConsumptionHorizon";13
const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];14
const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];14
const MAX_SKIN_TONE: u8 = 5;15
const MAX_SKIN_TONE: u8 = 5;@@ -100,6 +101,11 @@ impl<T: MessageTransport> UserSettings<T> {100
.await101
.await101
}102
}102
103
104
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {105
self.set_property(DEFAULT_REACTIONS_KEY, default_reactions_value(reaction_ids))106
.await107
}108
103
/// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.109
/// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.104
pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {110
pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {105
let properties = self.properties().await?;111
let properties = self.properties().await?;@@ -161,6 +167,25 @@ pub fn parse_skin_tone(properties: &Value) -> Option<u8> {161
(tone <= MAX_SKIN_TONE).then_some(tone)167
(tone <= MAX_SKIN_TONE).then_some(tone)162
}168
}163
169
170
pub fn parse_default_reactions(properties: &Value) -> Option<Vec<String>> {171
let entries = match properties.get(DEFAULT_REACTIONS_KEY)? {172
Value::String(text) => serde_json::from_str::<Value>(text).ok()?,173
other => other.clone(),174
};175
entries.as_array().map(|entries| {176
entries177
.iter()178
.filter_map(Value::as_str)179
.filter(|reaction_id| !reaction_id.is_empty())180
.map(str::to_owned)181
.collect()182
})183
}184
185
pub fn default_reactions_value(reaction_ids: &[String]) -> Value {186
Value::String(Value::from(reaction_ids.to_vec()).to_string())187
}188
164
pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {189
pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {165
let entries = match properties.get(TEAMS_ORDER_KEY) {190
let entries = match properties.get(TEAMS_ORDER_KEY) {166
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),191
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),@@ -290,6 +315,53 @@ mod tests {290
assert_eq!(parse_skin_tone(&json!({})), None);315
assert_eq!(parse_skin_tone(&json!({})), None);291
}316
}292
317
318
#[test]319
fn default_reactions_are_read_from_the_json_string_or_an_array() {320
assert_eq!(321
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: r#"["like","heart","fire"]"#})),322
Some(vec![323
"like".to_owned(),324
"heart".to_owned(),325
"fire".to_owned()326
])327
);328
assert_eq!(329
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: ["yes", "", 3]})),330
Some(vec!["yes".to_owned()])331
);332
assert_eq!(333
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "[]"})),334
Some(Vec::new())335
);336
assert_eq!(parse_default_reactions(&json!({})), None);337
assert_eq!(338
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "not json"})),339
None340
);341
}342
343
#[tokio::test]344
async fn default_reactions_are_put_as_a_json_string() {345
let transport = Canned {346
answers: Mutex::new(vec![(200, Value::Null)].into()),347
requests: Mutex::new(Vec::new()),348
};349
UserSettings::with_transport(&transport, "emea")350
.set_default_reactions(&["like".to_owned(), "fire".to_owned()])351
.await352
.unwrap();353
let requests = transport.requests.lock().unwrap();354
assert_eq!(requests[0].method, Method::Put);355
assert_eq!(356
requests[0].url,357
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=defaultMessageReactions"358
);359
assert_eq!(360
requests[0].body,361
Some(json!({"defaultMessageReactions": r#"["like","fire"]"#}))362
);363
}364
293
#[test]365
#[test]294
fn unset_fields_use_the_teams_defaults() {366
fn unset_fields_use_the_teams_defaults() {295
let parsed = parse_chat_sections(&json!({}));367
let parsed = parse_chat_sections(&json!({}));@@ -9,6 +9,7 @@ use store::MessageRecord;
9
9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10
10
use crate::error::{Error, Result};
11
11
use crate::external_image::external_image_url;
12
use crate::hidden_chats::cleared_until_ms;
12
13
use crate::links::LinkPreview;
13
14
use crate::mapping::message_record;
14
15
use crate::markdown::markdown_to_html;
@@ -482,6 +483,34 @@ impl<R: Remote> SyncEngine<R> {
482
483
Ok(())
483
484
}
484
485
486
/// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
487
pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
488
let last_message_at = self
489
.store
490
.chat(chat_id)?
491
.and_then(|chat| chat.last_message_at);
492
let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
493
self.remote
494
.clear_chat_history(chat_id, cleared_until_ms)
495
.await?;
496
self.with_locally_hidden(|locally| {
497
locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
498
})?;
499
self.store.remove_chats(&[chat_id.to_owned()])?;
500
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
501
Ok(())
502
}
503
504
pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
505
self.remote.set_chat_topic(chat_id, topic).await?;
506
if let Some(mut chat) = self.store.chat(chat_id)? {
507
chat.title = topic.to_owned();
508
self.store.upsert_chats(std::slice::from_ref(&chat))?;
509
}
510
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
511
Ok(())
512
}
513
485
514
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
486
515
let user_id = self.my_user_id().await?;
487
516
self.remote.remove_chat_member(chat_id, &user_id).await?;
@@ -9,6 +9,7 @@ use store::MessageRecord;9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};10
use crate::error::{Error, Result};10
use crate::error::{Error, Result};11
use crate::external_image::external_image_url;11
use crate::external_image::external_image_url;12
use crate::hidden_chats::cleared_until_ms;12
use crate::links::LinkPreview;13
use crate::links::LinkPreview;13
use crate::mapping::message_record;14
use crate::mapping::message_record;14
use crate::markdown::markdown_to_html;15
use crate::markdown::markdown_to_html;@@ -482,6 +483,34 @@ impl<R: Remote> SyncEngine<R> {482
Ok(())483
Ok(())483
}484
}484
485
486
/// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.487
pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {488
let last_message_at = self489
.store490
.chat(chat_id)?491
.and_then(|chat| chat.last_message_at);492
let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());493
self.remote494
.clear_chat_history(chat_id, cleared_until_ms)495
.await?;496
self.with_locally_hidden(|locally| {497
locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))498
})?;499
self.store.remove_chats(&[chat_id.to_owned()])?;500
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);501
Ok(())502
}503
504
pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {505
self.remote.set_chat_topic(chat_id, topic).await?;506
if let Some(mut chat) = self.store.chat(chat_id)? {507
chat.title = topic.to_owned();508
self.store.upsert_chats(std::slice::from_ref(&chat))?;509
}510
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);511
Ok(())512
}513
485
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {514
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {486
let user_id = self.my_user_id().await?;515
let user_id = self.my_user_id().await?;487
self.remote.remove_chat_member(chat_id, &user_id).await?;516
self.remote.remove_chat_member(chat_id, &user_id).await?;@@ -0,0 +1,51 @@
1
use store::Store;
2
3
use crate::error::Result;
4
5
const META_ACCOUNT_DEFAULT_REACTIONS: &str = "default_reactions_account";
6
pub const TEAMS_DEFAULT_REACTIONS: [&str; 4] = ["like", "heart", "laugh", "surprised"];
7
pub const DEFAULT_REACTION_SLOTS: usize = 5;
8
9
pub fn store_account_default_reactions(
10
store: &Store,
11
reaction_ids: Option<&[String]>,
12
) -> Result<()> {
13
let value = reaction_ids
14
.map(|reaction_ids| serde_json::Value::from(reaction_ids.to_vec()).to_string())
15
.unwrap_or_default();
16
Ok(store.set_meta(META_ACCOUNT_DEFAULT_REACTIONS, &value)?)
17
}
18
19
/// The account setting `defaultMessageReactions`, Teams' own default set when it was never saved.
20
pub fn default_reactions(store: &Store) -> Vec<String> {
21
store
22
.meta(META_ACCOUNT_DEFAULT_REACTIONS)
23
.ok()
24
.flatten()
25
.filter(|stored| !stored.is_empty())
26
.and_then(|stored| serde_json::from_str::<Vec<String>>(&stored).ok())
27
.unwrap_or_else(|| {
28
TEAMS_DEFAULT_REACTIONS
29
.iter()
30
.map(|reaction_id| (*reaction_id).to_owned())
31
.collect()
32
})
33
}
34
35
#[cfg(test)]
36
mod tests {
37
use super::*;
38
39
#[test]
40
fn falls_back_to_the_teams_set_until_the_account_has_one() {
41
let store = Store::open_in_memory().unwrap();
42
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
43
let saved = vec!["fire".to_owned(), "like".to_owned()];
44
store_account_default_reactions(&store, Some(&saved)).unwrap();
45
assert_eq!(default_reactions(&store), saved);
46
store_account_default_reactions(&store, Some(&[])).unwrap();
47
assert!(default_reactions(&store).is_empty());
48
store_account_default_reactions(&store, None).unwrap();
49
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
50
}
51
}
@@ -0,0 +1,51 @@1
use store::Store;2
3
use crate::error::Result;4
5
const META_ACCOUNT_DEFAULT_REACTIONS: &str = "default_reactions_account";6
pub const TEAMS_DEFAULT_REACTIONS: [&str; 4] = ["like", "heart", "laugh", "surprised"];7
pub const DEFAULT_REACTION_SLOTS: usize = 5;8
9
pub fn store_account_default_reactions(10
store: &Store,11
reaction_ids: Option<&[String]>,12
) -> Result<()> {13
let value = reaction_ids14
.map(|reaction_ids| serde_json::Value::from(reaction_ids.to_vec()).to_string())15
.unwrap_or_default();16
Ok(store.set_meta(META_ACCOUNT_DEFAULT_REACTIONS, &value)?)17
}18
19
/// The account setting `defaultMessageReactions`, Teams' own default set when it was never saved.20
pub fn default_reactions(store: &Store) -> Vec<String> {21
store22
.meta(META_ACCOUNT_DEFAULT_REACTIONS)23
.ok()24
.flatten()25
.filter(|stored| !stored.is_empty())26
.and_then(|stored| serde_json::from_str::<Vec<String>>(&stored).ok())27
.unwrap_or_else(|| {28
TEAMS_DEFAULT_REACTIONS29
.iter()30
.map(|reaction_id| (*reaction_id).to_owned())31
.collect()32
})33
}34
35
#[cfg(test)]36
mod tests {37
use super::*;38
39
#[test]40
fn falls_back_to_the_teams_set_until_the_account_has_one() {41
let store = Store::open_in_memory().unwrap();42
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);43
let saved = vec!["fire".to_owned(), "like".to_owned()];44
store_account_default_reactions(&store, Some(&saved)).unwrap();45
assert_eq!(default_reactions(&store), saved);46
store_account_default_reactions(&store, Some(&[])).unwrap();47
assert!(default_reactions(&store).is_empty());48
store_account_default_reactions(&store, None).unwrap();49
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);50
}51
}@@ -3,7 +3,9 @@ use std::future::Future;
3
3
use std::pin::Pin;
4
4
use std::sync::{Arc, Mutex};
5
5
6
use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};
6
use chatsvc::settings::{
7
parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,
8
};
7
9
use chatsvc::{
8
10
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
9
11
ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,
@@ -71,6 +73,15 @@ pub trait FolderSource: Send + Sync {
71
73
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {
72
74
Box::pin(async { Ok(()) })
73
75
}
76
fn default_reactions(&self) -> Option<Vec<String>> {
77
None
78
}
79
fn set_default_reactions<'a>(
80
&'a self,
81
_reaction_ids: &'a [String],
82
) -> BoxFuture<'a, Result<()>> {
83
Box::pin(async { Ok(()) })
84
}
74
85
fn set_section_enabled(&self, section: ChatSection, enabled: bool)
75
86
-> BoxFuture<'_, Result<()>>;
76
87
fn set_folder_expanded<'a>(
@@ -122,6 +133,7 @@ pub struct ChatsvcFolderSource {
122
133
channel_settings: ChannelSettings,
123
134
properties: Mutex<Option<Value>>,
124
135
skin_tone: Mutex<Option<u8>>,
136
default_reactions: Mutex<Option<Vec<String>>>,
125
137
group_ids: Mutex<HashMap<String, String>>,
126
138
}
127
139
@@ -134,6 +146,7 @@ impl ChatsvcFolderSource {
134
146
channel_settings: ChannelSettings::new(session),
135
147
properties: Mutex::new(None),
136
148
skin_tone: Mutex::new(None),
149
default_reactions: Mutex::new(None),
137
150
group_ids: Mutex::new(HashMap::new()),
138
151
}
139
152
}
@@ -221,6 +234,7 @@ impl FolderSource for ChatsvcFolderSource {
221
234
let properties = self.settings.properties().await?;
222
235
let sections = parse_chat_sections(&properties);
223
236
*self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);
237
*self.default_reactions.lock().unwrap() = parse_default_reactions(&properties);
224
238
*self.properties.lock().unwrap() = Some(properties);
225
239
Ok(sections)
226
240
})
@@ -234,6 +248,17 @@ impl FolderSource for ChatsvcFolderSource {
234
248
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })
235
249
}
236
250
251
fn default_reactions(&self) -> Option<Vec<String>> {
252
self.default_reactions.lock().unwrap().clone()
253
}
254
255
fn set_default_reactions<'a>(
256
&'a self,
257
reaction_ids: &'a [String],
258
) -> BoxFuture<'a, Result<()>> {
259
Box::pin(async move { Ok(self.settings.set_default_reactions(reaction_ids).await?) })
260
}
261
237
262
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
238
263
Box::pin(async {
239
264
let cached = self.properties.lock().unwrap().take();
@@ -549,12 +574,18 @@ impl<R: Remote> SyncEngine<R> {
549
574
550
575
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
551
576
let outcome = match source.section_settings().await {
552
Ok(settings) => self.apply_section_settings(&settings).and_then(|()| {
553
match source.preferred_skin_tone() {
577
Ok(settings) => self
578
.apply_section_settings(&settings)
579
.and_then(|()| match source.preferred_skin_tone() {
554
580
Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),
555
581
None => Ok(()),
556
}
557
}),
582
})
583
.and_then(|()| {
584
crate::default_reactions::store_account_default_reactions(
585
&self.store,
586
source.default_reactions().as_deref(),
587
)
588
}),
558
589
Err(error) => Err(error),
559
590
};
560
591
if let Err(error) = outcome {
@@ -581,6 +612,13 @@ impl<R: Remote> SyncEngine<R> {
581
612
crate::skin_tone::store_account_skin_tone(&self.store, tone)
582
613
}
583
614
615
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
616
self.folder_source()?
617
.set_default_reactions(reaction_ids)
618
.await?;
619
crate::default_reactions::store_account_default_reactions(&self.store, Some(reaction_ids))
620
}
621
584
622
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
585
623
self.folder_source()?
586
624
.set_folder_expanded(folder_id, expanded)
@@ -3,7 +3,9 @@ use std::future::Future;3
use std::pin::Pin;3
use std::pin::Pin;4
use std::sync::{Arc, Mutex};4
use std::sync::{Arc, Mutex};5
5
6
use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};6
use chatsvc::settings::{7
parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,8
};7
use chatsvc::{9
use chatsvc::{8
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,10
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,9
ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,11
ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,@@ -71,6 +73,15 @@ pub trait FolderSource: Send + Sync {71
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {73
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {72
Box::pin(async { Ok(()) })74
Box::pin(async { Ok(()) })73
}75
}76
fn default_reactions(&self) -> Option<Vec<String>> {77
None78
}79
fn set_default_reactions<'a>(80
&'a self,81
_reaction_ids: &'a [String],82
) -> BoxFuture<'a, Result<()>> {83
Box::pin(async { Ok(()) })84
}74
fn set_section_enabled(&self, section: ChatSection, enabled: bool)85
fn set_section_enabled(&self, section: ChatSection, enabled: bool)75
-> BoxFuture<'_, Result<()>>;86
-> BoxFuture<'_, Result<()>>;76
fn set_folder_expanded<'a>(87
fn set_folder_expanded<'a>(@@ -122,6 +133,7 @@ pub struct ChatsvcFolderSource {122
channel_settings: ChannelSettings,133
channel_settings: ChannelSettings,123
properties: Mutex<Option<Value>>,134
properties: Mutex<Option<Value>>,124
skin_tone: Mutex<Option<u8>>,135
skin_tone: Mutex<Option<u8>>,136
default_reactions: Mutex<Option<Vec<String>>>,125
group_ids: Mutex<HashMap<String, String>>,137
group_ids: Mutex<HashMap<String, String>>,126
}138
}127
139
@@ -134,6 +146,7 @@ impl ChatsvcFolderSource {134
channel_settings: ChannelSettings::new(session),146
channel_settings: ChannelSettings::new(session),135
properties: Mutex::new(None),147
properties: Mutex::new(None),136
skin_tone: Mutex::new(None),148
skin_tone: Mutex::new(None),149
default_reactions: Mutex::new(None),137
group_ids: Mutex::new(HashMap::new()),150
group_ids: Mutex::new(HashMap::new()),138
}151
}139
}152
}@@ -221,6 +234,7 @@ impl FolderSource for ChatsvcFolderSource {221
let properties = self.settings.properties().await?;234
let properties = self.settings.properties().await?;222
let sections = parse_chat_sections(&properties);235
let sections = parse_chat_sections(&properties);223
*self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);236
*self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);237
*self.default_reactions.lock().unwrap() = parse_default_reactions(&properties);224
*self.properties.lock().unwrap() = Some(properties);238
*self.properties.lock().unwrap() = Some(properties);225
Ok(sections)239
Ok(sections)226
})240
})@@ -234,6 +248,17 @@ impl FolderSource for ChatsvcFolderSource {234
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })248
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })235
}249
}236
250
251
fn default_reactions(&self) -> Option<Vec<String>> {252
self.default_reactions.lock().unwrap().clone()253
}254
255
fn set_default_reactions<'a>(256
&'a self,257
reaction_ids: &'a [String],258
) -> BoxFuture<'a, Result<()>> {259
Box::pin(async move { Ok(self.settings.set_default_reactions(reaction_ids).await?) })260
}261
237
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {262
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {238
Box::pin(async {263
Box::pin(async {239
let cached = self.properties.lock().unwrap().take();264
let cached = self.properties.lock().unwrap().take();@@ -549,12 +574,18 @@ impl<R: Remote> SyncEngine<R> {549
574
550
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {575
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {551
let outcome = match source.section_settings().await {576
let outcome = match source.section_settings().await {552
Ok(settings) => self.apply_section_settings(&settings).and_then(|()| {577
Ok(settings) => self553
match source.preferred_skin_tone() {578
.apply_section_settings(&settings)579
.and_then(|()| match source.preferred_skin_tone() {554
Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),580
Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),555
None => Ok(()),581
None => Ok(()),556
}582
})557
}),583
.and_then(|()| {584
crate::default_reactions::store_account_default_reactions(585
&self.store,586
source.default_reactions().as_deref(),587
)588
}),558
Err(error) => Err(error),589
Err(error) => Err(error),559
};590
};560
if let Err(error) = outcome {591
if let Err(error) = outcome {@@ -581,6 +612,13 @@ impl<R: Remote> SyncEngine<R> {581
crate::skin_tone::store_account_skin_tone(&self.store, tone)612
crate::skin_tone::store_account_skin_tone(&self.store, tone)582
}613
}583
614
615
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {616
self.folder_source()?617
.set_default_reactions(reaction_ids)618
.await?;619
crate::default_reactions::store_account_default_reactions(&self.store, Some(reaction_ids))620
}621
584
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {622
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {585
self.folder_source()?623
self.folder_source()?586
.set_folder_expanded(folder_id, expanded)624
.set_folder_expanded(folder_id, expanded)@@ -15,6 +15,7 @@ mod channel_mentions;
15
15
mod channel_sync;
16
16
mod channel_visibility;
17
17
mod chat_paging;
18
mod default_reactions;
18
19
mod download;
19
20
mod draft;
20
21
mod emoticon_tags;
@@ -108,6 +109,10 @@ pub use chatsvc::{
108
109
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
109
110
parse_language_settings, target_patch,
110
111
};
112
pub use default_reactions::{
113
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
114
store_account_default_reactions,
115
};
111
116
pub use download::LibraryFile;
112
117
pub use draft::{
113
118
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
@@ -15,6 +15,7 @@ mod channel_mentions;15
mod channel_sync;15
mod channel_sync;16
mod channel_visibility;16
mod channel_visibility;17
mod chat_paging;17
mod chat_paging;18
mod default_reactions;18
mod download;19
mod download;19
mod draft;20
mod draft;20
mod emoticon_tags;21
mod emoticon_tags;@@ -108,6 +109,10 @@ pub use chatsvc::{108
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,109
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,109
parse_language_settings, target_patch,110
parse_language_settings, target_patch,110
};111
};112
pub use default_reactions::{113
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,114
store_account_default_reactions,115
};111
pub use download::LibraryFile;116
pub use download::LibraryFile;112
pub use draft::{117
pub use draft::{113
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,118
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,@@ -116,6 +116,7 @@ mod tests {
116
116
last_message_from: Some(format!("8:orgid:{from}")),
117
117
..ReadHorizon::default()
118
118
},
119
history_cleared_ms: None,
119
120
}
120
121
}
121
122
@@ -116,6 +116,7 @@ mod tests {116
last_message_from: Some(format!("8:orgid:{from}")),116
last_message_from: Some(format!("8:orgid:{from}")),117
..ReadHorizon::default()117
..ReadHorizon::default()118
},118
},119
history_cleared_ms: None,119
}120
}120
}121
}121
122
@@ -138,6 +138,12 @@ pub trait Remote {
138
138
share: HistoryShare,
139
139
) -> Result<()>;
140
140
async fn chat_states(&self) -> Result<Vec<ConversationState>>;
141
async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
142
Err(Error::Unsupported("removing chat history"))
143
}
144
async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
145
Err(Error::Unsupported("renaming a chat"))
146
}
141
147
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
142
148
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
143
149
async fn set_channel_notifications(
@@ -734,6 +740,18 @@ impl Remote for Graph {
734
740
.await?)
735
741
}
736
742
743
async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
744
Ok(Conversations::new(self.session())
745
.clear_history(chat_id, cleared_until_ms)
746
.await?)
747
}
748
749
async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
750
Ok(ThreadMembers::new(self.session())
751
.set_topic(chat_id, topic)
752
.await?)
753
}
754
737
755
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
738
756
Ok(Conversations::new(self.session())
739
757
.set_alerts(chat_id, !muted)
@@ -138,6 +138,12 @@ pub trait Remote {138
share: HistoryShare,138
share: HistoryShare,139
) -> Result<()>;139
) -> Result<()>;140
async fn chat_states(&self) -> Result<Vec<ConversationState>>;140
async fn chat_states(&self) -> Result<Vec<ConversationState>>;141
async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {142
Err(Error::Unsupported("removing chat history"))143
}144
async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {145
Err(Error::Unsupported("renaming a chat"))146
}141
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;147
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;142
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;148
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;143
async fn set_channel_notifications(149
async fn set_channel_notifications(@@ -734,6 +740,18 @@ impl Remote for Graph {734
.await?)740
.await?)735
}741
}736
742
743
async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {744
Ok(Conversations::new(self.session())745
.clear_history(chat_id, cleared_until_ms)746
.await?)747
}748
749
async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {750
Ok(ThreadMembers::new(self.session())751
.set_topic(chat_id, topic)752
.await?)753
}754
737
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {755
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {738
Ok(Conversations::new(self.session())756
Ok(Conversations::new(self.session())739
.set_alerts(chat_id, !muted)757
.set_alerts(chat_id, !muted)@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};
6
6
const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7
7
const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8
8
const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9
const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
9
10
const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10
11
const DAY_SECONDS: i64 = 86_400;
11
12
@@ -14,6 +15,7 @@ pub enum RosterChange {
14
15
Added,
15
16
Removed,
16
17
Left,
18
Renamed,
17
19
}
18
20
19
21
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -33,6 +35,8 @@ pub struct RosterEvent {
33
35
pub member_names: Vec<Option<String>>,
34
36
#[serde(default)]
35
37
pub history: SharedHistory,
38
#[serde(default)]
39
pub topic: Option<String>,
36
40
}
37
41
38
42
#[derive(Serialize, Deserialize)]
@@ -67,6 +71,7 @@ impl RosterEvent {
67
71
MEMBERS_LEFT_TYPE => RosterChange::Left,
68
72
MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69
73
MEMBERS_DELETED_TYPE => RosterChange::Removed,
74
CHAT_RENAMED_TYPE => RosterChange::Renamed,
70
75
_ => return None,
71
76
};
72
77
let history = match change {
@@ -86,6 +91,12 @@ impl RosterEvent {
86
91
member_ids,
87
92
member_names,
88
93
history,
94
topic: (change == RosterChange::Renamed)
95
.then(|| detail.get("chatDisplayName").and_then(Value::as_str))
96
.flatten()
97
.map(str::trim)
98
.filter(|topic| !topic.is_empty())
99
.map(str::to_owned),
89
100
})
90
101
}
91
102
@@ -114,6 +125,10 @@ impl RosterEvent {
114
125
let targets = join_targets(&targets);
115
126
match self.change {
116
127
RosterChange::Left => format!("{initiator} left the chat."),
128
RosterChange::Renamed => match &self.topic {
129
Some(topic) => format!("{initiator} changed the group name to {topic}."),
130
None => format!("{initiator} removed the group name for this conversation."),
131
},
117
132
RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118
133
RosterChange::Added => match self.history {
119
134
SharedHistory::None => format!("{initiator} added {targets} to the chat."),
@@ -210,6 +225,32 @@ mod tests {
210
225
name.or(user_id).unwrap_or("Unknown").to_owned()
211
226
}
212
227
228
#[test]
229
fn a_rename_reads_like_teams() {
230
let renamed = |name: Value| {
231
RosterEvent::from_graph(
232
&json!({
233
"@odata.type": CHAT_RENAMED_TYPE,
234
"chatDisplayName": name,
235
"initiator": {"user": {"id": "me", "displayName": "Daniel"}},
236
}),
237
created(),
238
)
239
.unwrap()
240
};
241
let event = renamed(json!("Release crew"));
242
assert_eq!(event.change, RosterChange::Renamed);
243
assert_eq!(
244
event.text(plain_names),
245
"Daniel changed the group name to Release crew."
246
);
247
assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);
248
assert_eq!(
249
renamed(json!(null)).text(plain_names),
250
"Daniel removed the group name for this conversation."
251
);
252
}
253
213
254
#[test]
214
255
fn added_without_history_reads_like_teams() {
215
256
let event = added(
@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};6
const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";6
const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";7
const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";7
const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";8
const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";8
const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";9
const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";9
const UNRESOLVED_NAME_PREFIX: &str = "orgid:";10
const UNRESOLVED_NAME_PREFIX: &str = "orgid:";10
const DAY_SECONDS: i64 = 86_400;11
const DAY_SECONDS: i64 = 86_400;11
12
@@ -14,6 +15,7 @@ pub enum RosterChange {14
Added,15
Added,15
Removed,16
Removed,16
Left,17
Left,18
Renamed,17
}19
}18
20
19
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]21
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]@@ -33,6 +35,8 @@ pub struct RosterEvent {33
pub member_names: Vec<Option<String>>,35
pub member_names: Vec<Option<String>>,34
#[serde(default)]36
#[serde(default)]35
pub history: SharedHistory,37
pub history: SharedHistory,38
#[serde(default)]39
pub topic: Option<String>,36
}40
}37
41
38
#[derive(Serialize, Deserialize)]42
#[derive(Serialize, Deserialize)]@@ -67,6 +71,7 @@ impl RosterEvent {67
MEMBERS_LEFT_TYPE => RosterChange::Left,71
MEMBERS_LEFT_TYPE => RosterChange::Left,68
MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,72
MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,69
MEMBERS_DELETED_TYPE => RosterChange::Removed,73
MEMBERS_DELETED_TYPE => RosterChange::Removed,74
CHAT_RENAMED_TYPE => RosterChange::Renamed,70
_ => return None,75
_ => return None,71
};76
};72
let history = match change {77
let history = match change {@@ -86,6 +91,12 @@ impl RosterEvent {86
member_ids,91
member_ids,87
member_names,92
member_names,88
history,93
history,94
topic: (change == RosterChange::Renamed)95
.then(|| detail.get("chatDisplayName").and_then(Value::as_str))96
.flatten()97
.map(str::trim)98
.filter(|topic| !topic.is_empty())99
.map(str::to_owned),89
})100
})90
}101
}91
102
@@ -114,6 +125,10 @@ impl RosterEvent {114
let targets = join_targets(&targets);125
let targets = join_targets(&targets);115
match self.change {126
match self.change {116
RosterChange::Left => format!("{initiator} left the chat."),127
RosterChange::Left => format!("{initiator} left the chat."),128
RosterChange::Renamed => match &self.topic {129
Some(topic) => format!("{initiator} changed the group name to {topic}."),130
None => format!("{initiator} removed the group name for this conversation."),131
},117
RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),132
RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),118
RosterChange::Added => match self.history {133
RosterChange::Added => match self.history {119
SharedHistory::None => format!("{initiator} added {targets} to the chat."),134
SharedHistory::None => format!("{initiator} added {targets} to the chat."),@@ -210,6 +225,32 @@ mod tests {210
name.or(user_id).unwrap_or("Unknown").to_owned()225
name.or(user_id).unwrap_or("Unknown").to_owned()211
}226
}212
227
228
#[test]229
fn a_rename_reads_like_teams() {230
let renamed = |name: Value| {231
RosterEvent::from_graph(232
&json!({233
"@odata.type": CHAT_RENAMED_TYPE,234
"chatDisplayName": name,235
"initiator": {"user": {"id": "me", "displayName": "Daniel"}},236
}),237
created(),238
)239
.unwrap()240
};241
let event = renamed(json!("Release crew"));242
assert_eq!(event.change, RosterChange::Renamed);243
assert_eq!(244
event.text(plain_names),245
"Daniel changed the group name to Release crew."246
);247
assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);248
assert_eq!(249
renamed(json!(null)).text(plain_names),250
"Daniel removed the group name for this conversation."251
);252
}253
213
#[test]254
#[test]214
fn added_without_history_reads_like_teams() {255
fn added_without_history_reads_like_teams() {215
let event = added(256
let event = added(@@ -584,6 +584,7 @@ impl Remote for Handle {
584
584
muted,
585
585
hidden: None,
586
586
read: chatsvc::ReadHorizon::default(),
587
history_cleared_ms: None,
587
588
})
588
589
.collect();
589
590
states.extend(
@@ -594,6 +595,7 @@ impl Remote for Handle {
594
595
muted: false,
595
596
hidden: Some(hidden),
596
597
read: chatsvc::ReadHorizon::default(),
598
history_cleared_ms: None,
597
599
}),
598
600
);
599
601
let read = self.read_states.lock().unwrap().clone();
@@ -604,6 +606,7 @@ impl Remote for Handle {
604
606
muted: false,
605
607
hidden: None,
606
608
read,
609
history_cleared_ms: None,
607
610
}),
608
611
);
609
612
Ok(states)
@@ -584,6 +584,7 @@ impl Remote for Handle {584
muted,584
muted,585
hidden: None,585
hidden: None,586
read: chatsvc::ReadHorizon::default(),586
read: chatsvc::ReadHorizon::default(),587
history_cleared_ms: None,587
})588
})588
.collect();589
.collect();589
states.extend(590
states.extend(@@ -594,6 +595,7 @@ impl Remote for Handle {594
muted: false,595
muted: false,595
hidden: Some(hidden),596
hidden: Some(hidden),596
read: chatsvc::ReadHorizon::default(),597
read: chatsvc::ReadHorizon::default(),598
history_cleared_ms: None,597
}),599
}),598
);600
);599
let read = self.read_states.lock().unwrap().clone();601
let read = self.read_states.lock().unwrap().clone();@@ -604,6 +606,7 @@ impl Remote for Handle {604
muted: false,606
muted: false,605
hidden: None,607
hidden: None,606
read,608
read,609
history_cleared_ms: None,607
}),610
}),608
);611
);609
Ok(states)612
Ok(states)