feat(sidebar): Muted and Meeting chats sections like Teams
| Before | After | |---|---| | Muted and meeting chats mixed into Other chats | Own sections: Meeting chats above Other chats, Muted below, in Teams' folder order | | - | 5 chats per section, then See more / See less | | Muted unread shows a badge | Muted unread is bold only, not counted | | Collapse stored only locally | Collapse synced to Teams (conversationFolders isExpanded) | | - | Avatar menu > Chat list: "Show muted chats in own section" (default on), "Show meeting chats in own section" (default off), saved in Teams' simpleCollabUserSettings | - System folders RecentChats, MeetingChats, MutedChats are kept instead of dropped (id, order, isExpanded). - Fix: mute state was read from the first 200 chats only; now pages through all. - Settings write verified live as a no-op round trip (same shape as Teams, 200, value unchanged). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -33,7 +33,7 @@
33
33
## Features
34
34
35
35
**Chats and channels**
36
- Teams pin order, chat folders, hidden teams
36
- Teams pin order, chat folders, hidden teams, Muted and Meeting chats sections
37
37
- Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view
38
38
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
39
39
- Read receipts, typing indicator with faces, presence, unread jump
@@ -33,7 +33,7 @@33
## Features33
## Features34
34
35
**Chats and channels**35
**Chats and channels**36
- Teams pin order, chat folders, hidden teams36
- Teams pin order, chat folders, hidden teams, Muted and Meeting chats sections37
- Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view37
- Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view38
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave38
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave39
- Read receipts, typing indicator with faces, presence, unread jump39
- Read receipts, typing indicator with faces, presence, unread jump@@ -2,14 +2,14 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 82 %** (71 done, 1 partial, 15 missing of 87). Partial counts half.
5
**Parity: 83 %** (72 done, 1 partial, 14 missing of 87). Partial counts half.
6
6
7
7
## By area
8
8
9
9
| Area | Parity | Done | Partial | Missing |
10
10
|---|---|---|---|---|
11
11
| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12
| [Chat list](#chat-list) | 100 % | 10 | 0 | 0 |
13
13
| [Reading](#reading) | 89 % | 17 | 0 | 2 |
14
14
| [Writing](#writing) | 100 % | 14 | 0 | 0 |
15
15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
@@ -51,7 +51,7 @@ Feature parity with the Microsoft Teams desktop client.
51
51
| Mark as unread | Done | Keeps the open chat unread until you switch |
52
52
| Mute chat | Done | Synced with Teams, muted rows stay in place with a bell |
53
53
| Hide chat, leave chat | Done | Hide has Undo; leave only for group chats, with a confirmation |
54
| Muted and Meeting chat sections | Missing | Teams rollout Aug-Sep 2026 |
54
| Muted and Meeting chat sections | Done | Own sections like Teams, 5 chats plus See more, switches in the avatar menu under Chat list (synced with Teams settings), collapse synced with Teams |
55
55
56
56
## Reading
57
57
@@ -2,14 +2,14 @@2
2
3
Feature parity with the Microsoft Teams desktop client.3
Feature parity with the Microsoft Teams desktop client.4
4
5
**Parity: 82 %** (71 done, 1 partial, 15 missing of 87). Partial counts half.5
**Parity: 83 %** (72 done, 1 partial, 14 missing of 87). Partial counts half.6
6
7
## By area7
## By area8
8
9
| Area | Parity | Done | Partial | Missing |9
| Area | Parity | Done | Partial | Missing |10
|---|---|---|---|---|10
|---|---|---|---|---|11
| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |11
| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |12
| [Chat list](#chat-list) | 100 % | 10 | 0 | 0 |13
| [Reading](#reading) | 89 % | 17 | 0 | 2 |13
| [Reading](#reading) | 89 % | 17 | 0 | 2 |14
| [Writing](#writing) | 100 % | 14 | 0 | 0 |14
| [Writing](#writing) | 100 % | 14 | 0 | 0 |15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |@@ -51,7 +51,7 @@ Feature parity with the Microsoft Teams desktop client.51
| Mark as unread | Done | Keeps the open chat unread until you switch |51
| Mark as unread | Done | Keeps the open chat unread until you switch |52
| Mute chat | Done | Synced with Teams, muted rows stay in place with a bell |52
| Mute chat | Done | Synced with Teams, muted rows stay in place with a bell |53
| Hide chat, leave chat | Done | Hide has Undo; leave only for group chats, with a confirmation |53
| Hide chat, leave chat | Done | Hide has Undo; leave only for group chats, with a confirmation |54
| Muted and Meeting chat sections | Missing | Teams rollout Aug-Sep 2026 |54
| Muted and Meeting chat sections | Done | Own sections like Teams, 5 chats plus See more, switches in the avatar menu under Chat list (synced with Teams settings), collapse synced with Teams |55
55
56
## Reading56
## Reading57
57
@@ -6,7 +6,10 @@ use chatsvc::TypingEvent;
6
6
use chrono::{DateTime, Utc};
7
7
use gpui_kit::*;
8
8
use store::{ChatRecord, Sidebar, Store};
9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, PresenceStatus, ScheduledDraft};
9
use teams_core::{
10
ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus,
11
ScheduledDraft,
12
};
10
13
11
14
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
12
15
use crate::card_state::{CardState, TaskDialogState};
@@ -77,6 +80,7 @@ pub struct AppState {
77
80
pub mode: Mode,
78
81
pub directory: Directory,
79
82
pub collapsed: HashSet<String>,
83
pub expanded_lists: HashSet<String>,
80
84
pub followed_channels: HashSet<String>,
81
85
pub start_on_channels: bool,
82
86
pub pending_jump: Option<(String, String)>,
@@ -160,6 +164,7 @@ impl AppState {
160
164
mode,
161
165
directory: Directory::default(),
162
166
collapsed: HashSet::new(),
167
expanded_lists: HashSet::new(),
163
168
followed_channels: HashSet::new(),
164
169
start_on_channels: false,
165
170
pending_jump: None,
@@ -219,12 +224,95 @@ impl AppState {
219
224
}
220
225
221
226
pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
222
if !self.collapsed.remove(section_id) {
223
self.collapsed.insert(section_id.to_owned());
227
let now_collapsed = self.collapsed.insert(section_id.to_owned());
228
if !now_collapsed {
229
self.collapsed.remove(section_id);
224
230
}
231
self.save_collapsed();
232
self.sync_folder_expanded(section_id, !now_collapsed);
233
cx.emit(AppEvent::Sidebar);
234
cx.notify();
235
}
236
237
pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
238
if !self.expanded_lists.remove(section_id) {
239
self.expanded_lists.insert(section_id.to_owned());
240
}
241
cx.emit(AppEvent::Sidebar);
242
cx.notify();
243
}
244
245
fn save_collapsed(&self) {
225
246
let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
226
247
ids.sort_unstable();
227
248
let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
249
}
250
251
fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {
252
let Some(folder) = self
253
.directory
254
.folders
255
.iter_mut()
256
.find(|folder| folder.id == folder_id && folder.expanded.is_some())
257
else {
258
return;
259
};
260
folder.expanded = Some(expanded);
261
let _ = self.store.set_folder_expanded(folder_id, expanded);
262
if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {
263
let folder_id = folder_id.to_owned();
264
drop(crate::runtime::spawn(async move {
265
engine.set_folder_expanded(&folder_id, expanded).await
266
}));
267
}
268
}
269
270
fn adopt_folder_expanded(&mut self) {
271
let snapshot = self.collapsed.clone();
272
for folder in &self.directory.folders {
273
match folder.expanded {
274
Some(true) => {
275
self.collapsed.remove(&folder.id);
276
}
277
Some(false) => {
278
self.collapsed.insert(folder.id.clone());
279
}
280
None => {}
281
}
282
}
283
if self.collapsed != snapshot {
284
self.save_collapsed();
285
}
286
}
287
288
pub fn set_chat_section(
289
&mut self,
290
section: ChatSection,
291
enabled: bool,
292
cx: &mut Context<Self>,
293
) {
294
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
295
return;
296
};
297
let previous = self.directory.section_settings;
298
let mut updated = previous;
299
updated.set(section, enabled);
300
self.apply_section_settings(updated, cx);
301
let Some(engine) = engine_or_demo else {
302
return;
303
};
304
self.run_chat_action(
305
"Chat list setting",
306
async move { engine.set_section_enabled(section, enabled).await },
307
move |state, cx| state.apply_section_settings(previous, cx),
308
|_, _| {},
309
cx,
310
);
311
}
312
313
fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
314
self.directory.section_settings = settings;
315
let _ = teams_core::store_section_settings(&self.store, &settings);
228
316
cx.emit(AppEvent::Sidebar);
229
317
cx.notify();
230
318
}
@@ -238,6 +326,8 @@ impl AppState {
238
326
.flatten()
239
327
.unwrap_or_default();
240
328
self.directory.folders = data::folders(&self.store, &self.favorite_ids);
329
self.directory.section_settings = teams_core::stored_section_settings(&self.store);
330
self.adopt_folder_expanded();
241
331
self.directory.pinned_channels = data::pinned_channels(&self.store);
242
332
if self.directory.pinned_channels.is_empty() {
243
333
let known: HashSet<&str> = self
@@ -6,7 +6,10 @@ use chatsvc::TypingEvent;6
use chrono::{DateTime, Utc};6
use chrono::{DateTime, Utc};7
use gpui_kit::*;7
use gpui_kit::*;8
use store::{ChatRecord, Sidebar, Store};8
use store::{ChatRecord, Sidebar, Store};9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, PresenceStatus, ScheduledDraft};9
use teams_core::{10
ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus,11
ScheduledDraft,12
};10
13
11
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};14
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};12
use crate::card_state::{CardState, TaskDialogState};15
use crate::card_state::{CardState, TaskDialogState};@@ -77,6 +80,7 @@ pub struct AppState {77
pub mode: Mode,80
pub mode: Mode,78
pub directory: Directory,81
pub directory: Directory,79
pub collapsed: HashSet<String>,82
pub collapsed: HashSet<String>,83
pub expanded_lists: HashSet<String>,80
pub followed_channels: HashSet<String>,84
pub followed_channels: HashSet<String>,81
pub start_on_channels: bool,85
pub start_on_channels: bool,82
pub pending_jump: Option<(String, String)>,86
pub pending_jump: Option<(String, String)>,@@ -160,6 +164,7 @@ impl AppState {160
mode,164
mode,161
directory: Directory::default(),165
directory: Directory::default(),162
collapsed: HashSet::new(),166
collapsed: HashSet::new(),167
expanded_lists: HashSet::new(),163
followed_channels: HashSet::new(),168
followed_channels: HashSet::new(),164
start_on_channels: false,169
start_on_channels: false,165
pending_jump: None,170
pending_jump: None,@@ -219,12 +224,95 @@ impl AppState {219
}224
}220
225
221
pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {226
pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {222
if !self.collapsed.remove(section_id) {227
let now_collapsed = self.collapsed.insert(section_id.to_owned());223
self.collapsed.insert(section_id.to_owned());228
if !now_collapsed {229
self.collapsed.remove(section_id);224
}230
}231
self.save_collapsed();232
self.sync_folder_expanded(section_id, !now_collapsed);233
cx.emit(AppEvent::Sidebar);234
cx.notify();235
}236
237
pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {238
if !self.expanded_lists.remove(section_id) {239
self.expanded_lists.insert(section_id.to_owned());240
}241
cx.emit(AppEvent::Sidebar);242
cx.notify();243
}244
245
fn save_collapsed(&self) {225
let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();246
let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();226
ids.sort_unstable();247
ids.sort_unstable();227
let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));248
let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));249
}250
251
fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {252
let Some(folder) = self253
.directory254
.folders255
.iter_mut()256
.find(|folder| folder.id == folder_id && folder.expanded.is_some())257
else {258
return;259
};260
folder.expanded = Some(expanded);261
let _ = self.store.set_folder_expanded(folder_id, expanded);262
if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {263
let folder_id = folder_id.to_owned();264
drop(crate::runtime::spawn(async move {265
engine.set_folder_expanded(&folder_id, expanded).await266
}));267
}268
}269
270
fn adopt_folder_expanded(&mut self) {271
let snapshot = self.collapsed.clone();272
for folder in &self.directory.folders {273
match folder.expanded {274
Some(true) => {275
self.collapsed.remove(&folder.id);276
}277
Some(false) => {278
self.collapsed.insert(folder.id.clone());279
}280
None => {}281
}282
}283
if self.collapsed != snapshot {284
self.save_collapsed();285
}286
}287
288
pub fn set_chat_section(289
&mut self,290
section: ChatSection,291
enabled: bool,292
cx: &mut Context<Self>,293
) {294
let Some(engine_or_demo) = self.chat_action_engine(cx) else {295
return;296
};297
let previous = self.directory.section_settings;298
let mut updated = previous;299
updated.set(section, enabled);300
self.apply_section_settings(updated, cx);301
let Some(engine) = engine_or_demo else {302
return;303
};304
self.run_chat_action(305
"Chat list setting",306
async move { engine.set_section_enabled(section, enabled).await },307
move |state, cx| state.apply_section_settings(previous, cx),308
|_, _| {},309
cx,310
);311
}312
313
fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {314
self.directory.section_settings = settings;315
let _ = teams_core::store_section_settings(&self.store, &settings);228
cx.emit(AppEvent::Sidebar);316
cx.emit(AppEvent::Sidebar);229
cx.notify();317
cx.notify();230
}318
}@@ -238,6 +326,8 @@ impl AppState {238
.flatten()326
.flatten()239
.unwrap_or_default();327
.unwrap_or_default();240
self.directory.folders = data::folders(&self.store, &self.favorite_ids);328
self.directory.folders = data::folders(&self.store, &self.favorite_ids);329
self.directory.section_settings = teams_core::stored_section_settings(&self.store);330
self.adopt_folder_expanded();241
self.directory.pinned_channels = data::pinned_channels(&self.store);331
self.directory.pinned_channels = data::pinned_channels(&self.store);242
if self.directory.pinned_channels.is_empty() {332
if self.directory.pinned_channels.is_empty() {243
let known: HashSet<&str> = self333
let known: HashSet<&str> = self@@ -210,6 +210,7 @@ impl AppState {
210
210
chats: &self.sidebar.chats,
211
211
directory: &self.directory,
212
212
collapsed: &self.collapsed,
213
expanded_lists: &self.expanded_lists,
213
214
typing: &self.typing,
214
215
now: Utc::now(),
215
216
offset: Local::now().offset().fix(),
@@ -210,6 +210,7 @@ impl AppState {210
chats: &self.sidebar.chats,210
chats: &self.sidebar.chats,211
directory: &self.directory,211
directory: &self.directory,212
collapsed: &self.collapsed,212
collapsed: &self.collapsed,213
expanded_lists: &self.expanded_lists,213
typing: &self.typing,214
typing: &self.typing,214
now: Utc::now(),215
now: Utc::now(),215
offset: Local::now().offset().fix(),216
offset: Local::now().offset().fix(),@@ -6,13 +6,16 @@ use std::time::{Duration, Instant};
6
6
use gpui_kit::{Image, ImageFormat};
7
7
use store::{ChatRecord, Store};
8
8
9
use teams_core::Availability;
9
use teams_core::{Availability, ChatSectionSettings};
10
10
use tokio::sync::oneshot;
11
11
12
12
use crate::backend::Engine;
13
13
use crate::runtime;
14
14
15
15
const FAVORITES_KIND_MARKER: &str = "favorite";
16
const RECENT_KIND_MARKER: &str = "recent";
17
const MEETING_KIND_MARKER: &str = "meeting";
18
const MUTED_KIND_MARKER: &str = "muted";
16
19
const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);
17
20
const PUSHED_PRESENCE_MAX_AGE: Duration = Duration::from_secs(5 * 60);
18
21
const MEMBER_FACE_LIMIT: usize = 2;
@@ -27,6 +30,9 @@ pub struct Person {
27
30
pub enum FolderKind {
28
31
Favorites,
29
32
UserCreated,
33
Recent,
34
Meeting,
35
Muted,
30
36
}
31
37
32
38
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -34,6 +40,7 @@ pub struct FolderInfo {
34
40
pub id: String,
35
41
pub name: String,
36
42
pub kind: FolderKind,
43
pub expanded: Option<bool>,
37
44
pub conversation_ids: Vec<String>,
38
45
}
39
46
@@ -115,6 +122,7 @@ pub struct ImageEntry {
115
122
pub struct Directory {
116
123
pub me: Option<Person>,
117
124
pub folders: Vec<FolderInfo>,
125
pub section_settings: ChatSectionSettings,
118
126
pub pinned_channels: Vec<String>,
119
127
pub unread_counts: HashMap<String, u32>,
120
128
pub(crate) avatars: HashMap<String, AvatarState>,
@@ -346,21 +354,29 @@ pub fn me(store: &Store) -> Option<Person> {
346
354
})
347
355
}
348
356
357
fn folder_kind(kind: &str) -> FolderKind {
358
let lowered = kind.to_ascii_lowercase();
359
if lowered.contains(FAVORITES_KIND_MARKER) {
360
FolderKind::Favorites
361
} else if lowered.contains(RECENT_KIND_MARKER) {
362
FolderKind::Recent
363
} else if lowered.contains(MEETING_KIND_MARKER) {
364
FolderKind::Meeting
365
} else if lowered.contains(MUTED_KIND_MARKER) {
366
FolderKind::Muted
367
} else {
368
FolderKind::UserCreated
369
}
370
}
371
349
372
pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {
350
373
let stored: Vec<FolderInfo> = store
351
374
.folders()
352
375
.unwrap_or_default()
353
376
.into_iter()
354
377
.map(|record| FolderInfo {
355
kind: if record
356
.kind
357
.to_ascii_lowercase()
358
.contains(FAVORITES_KIND_MARKER)
359
{
360
FolderKind::Favorites
361
} else {
362
FolderKind::UserCreated
363
},
378
kind: folder_kind(&record.kind),
379
expanded: Some(record.expanded),
364
380
id: record.id,
365
381
name: record.name,
366
382
conversation_ids: record.conversation_ids,
@@ -373,6 +389,7 @@ pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {
373
389
id: "favorites".to_owned(),
374
390
name: String::new(),
375
391
kind: FolderKind::Favorites,
392
expanded: None,
376
393
conversation_ids: pinned_ids.to_vec(),
377
394
}]
378
395
}
@@ -492,6 +509,7 @@ mod tests {
492
509
id: id.into(),
493
510
name: id.into(),
494
511
kind,
512
expanded: None,
495
513
conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
496
514
}
497
515
}
@@ -6,13 +6,16 @@ use std::time::{Duration, Instant};6
use gpui_kit::{Image, ImageFormat};6
use gpui_kit::{Image, ImageFormat};7
use store::{ChatRecord, Store};7
use store::{ChatRecord, Store};8
8
9
use teams_core::Availability;9
use teams_core::{Availability, ChatSectionSettings};10
use tokio::sync::oneshot;10
use tokio::sync::oneshot;11
11
12
use crate::backend::Engine;12
use crate::backend::Engine;13
use crate::runtime;13
use crate::runtime;14
14
15
const FAVORITES_KIND_MARKER: &str = "favorite";15
const FAVORITES_KIND_MARKER: &str = "favorite";16
const RECENT_KIND_MARKER: &str = "recent";17
const MEETING_KIND_MARKER: &str = "meeting";18
const MUTED_KIND_MARKER: &str = "muted";16
const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);19
const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);17
const PUSHED_PRESENCE_MAX_AGE: Duration = Duration::from_secs(5 * 60);20
const PUSHED_PRESENCE_MAX_AGE: Duration = Duration::from_secs(5 * 60);18
const MEMBER_FACE_LIMIT: usize = 2;21
const MEMBER_FACE_LIMIT: usize = 2;@@ -27,6 +30,9 @@ pub struct Person {27
pub enum FolderKind {30
pub enum FolderKind {28
Favorites,31
Favorites,29
UserCreated,32
UserCreated,33
Recent,34
Meeting,35
Muted,30
}36
}31
37
32
#[derive(Debug, Clone, PartialEq, Eq)]38
#[derive(Debug, Clone, PartialEq, Eq)]@@ -34,6 +40,7 @@ pub struct FolderInfo {34
pub id: String,40
pub id: String,35
pub name: String,41
pub name: String,36
pub kind: FolderKind,42
pub kind: FolderKind,43
pub expanded: Option<bool>,37
pub conversation_ids: Vec<String>,44
pub conversation_ids: Vec<String>,38
}45
}39
46
@@ -115,6 +122,7 @@ pub struct ImageEntry {115
pub struct Directory {122
pub struct Directory {116
pub me: Option<Person>,123
pub me: Option<Person>,117
pub folders: Vec<FolderInfo>,124
pub folders: Vec<FolderInfo>,125
pub section_settings: ChatSectionSettings,118
pub pinned_channels: Vec<String>,126
pub pinned_channels: Vec<String>,119
pub unread_counts: HashMap<String, u32>,127
pub unread_counts: HashMap<String, u32>,120
pub(crate) avatars: HashMap<String, AvatarState>,128
pub(crate) avatars: HashMap<String, AvatarState>,@@ -346,21 +354,29 @@ pub fn me(store: &Store) -> Option<Person> {346
})354
})347
}355
}348
356
357
fn folder_kind(kind: &str) -> FolderKind {358
let lowered = kind.to_ascii_lowercase();359
if lowered.contains(FAVORITES_KIND_MARKER) {360
FolderKind::Favorites361
} else if lowered.contains(RECENT_KIND_MARKER) {362
FolderKind::Recent363
} else if lowered.contains(MEETING_KIND_MARKER) {364
FolderKind::Meeting365
} else if lowered.contains(MUTED_KIND_MARKER) {366
FolderKind::Muted367
} else {368
FolderKind::UserCreated369
}370
}371
349
pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {372
pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {350
let stored: Vec<FolderInfo> = store373
let stored: Vec<FolderInfo> = store351
.folders()374
.folders()352
.unwrap_or_default()375
.unwrap_or_default()353
.into_iter()376
.into_iter()354
.map(|record| FolderInfo {377
.map(|record| FolderInfo {355
kind: if record378
kind: folder_kind(&record.kind),356
.kind379
expanded: Some(record.expanded),357
.to_ascii_lowercase()358
.contains(FAVORITES_KIND_MARKER)359
{360
FolderKind::Favorites361
} else {362
FolderKind::UserCreated363
},364
id: record.id,380
id: record.id,365
name: record.name,381
name: record.name,366
conversation_ids: record.conversation_ids,382
conversation_ids: record.conversation_ids,@@ -373,6 +389,7 @@ pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {373
id: "favorites".to_owned(),389
id: "favorites".to_owned(),374
name: String::new(),390
name: String::new(),375
kind: FolderKind::Favorites,391
kind: FolderKind::Favorites,392
expanded: None,376
conversation_ids: pinned_ids.to_vec(),393
conversation_ids: pinned_ids.to_vec(),377
}]394
}]378
}395
}@@ -492,6 +509,7 @@ mod tests {492
id: id.into(),509
id: id.into(),493
name: id.into(),510
name: id.into(),494
kind,511
kind,512
expanded: None,495
conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),513
conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),496
}514
}497
}515
}@@ -9,8 +9,8 @@ use store::{
9
9
TeamLayoutRecord, TeamRecord,
10
10
};
11
11
use teams_core::{
12
CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13
PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind,
12
CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,
13
PersonSource, PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind,
14
14
};
15
15
16
16
use crate::activity::{Actor, Entry, Kind};
@@ -137,6 +137,14 @@ const FAVORITES_ID: &str = "demo-folder-favorites";
137
137
const CUSTOMERS_FOLDER: &str = "demo-folder-customers";
138
138
const ATLAS_FOLDER: &str = "demo-folder-atlas";
139
139
const TODO_FOLDER: &str = "demo-folder-todo";
140
const MUTED_CHATS: [&str; 6] = [
141
"demo-chat-muted-lunch",
142
"demo-chat-muted-offsite",
143
"demo-chat-muted-kudos",
144
"demo-chat-muted-bikes",
145
"demo-chat-muted-book",
146
"demo-chat-muted-games",
147
];
140
148
141
149
fn member(user_id: &str, name: &str) -> MemberRecord {
142
150
MemberRecord {
@@ -327,6 +335,86 @@ fn demo_chats() -> Vec<DemoChat> {
327
335
preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),
328
336
deleted: false,
329
337
},
338
DemoChat {
339
id: "demo-chat-meeting-standup",
340
kind: "meeting",
341
title: "Daily standup",
342
members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
343
time: at(0, 9, 45),
344
unread: true,
345
preview: Some((JONAS_ID, "Jonas Ortega", "Recording is available")),
346
deleted: false,
347
},
348
DemoChat {
349
id: "demo-chat-meeting-retro",
350
kind: "meeting",
351
title: "Sprint retrospective",
352
members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
353
time: at(3, 15, 30),
354
unread: false,
355
preview: Some((MARA_ID, "Mara Lindqvist", "Notes are in the wiki")),
356
deleted: false,
357
},
358
DemoChat {
359
id: "demo-chat-muted-lunch",
360
kind: "group",
361
title: "Lunch crew",
362
members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
363
time: at(0, 12, 5),
364
unread: true,
365
preview: Some((JONAS_ID, "Jonas Ortega", "Pizza on Friday?")),
366
deleted: false,
367
},
368
DemoChat {
369
id: "demo-chat-muted-offsite",
370
kind: "group",
371
title: "Team offsite 2027",
372
members: group(&[(LEA_ID, "Lea Schneider"), (LEA_ID, "Lea Schneider")]),
373
time: at(1, 16, 20),
374
unread: false,
375
preview: Some((LEA_ID, "Lea Schneider", "Voting closes tomorrow")),
376
deleted: false,
377
},
378
DemoChat {
379
id: "demo-chat-muted-kudos",
380
kind: "group",
381
title: "Kudos corner",
382
members: group(&[(MARA_ID, "Mara Lindqvist"), (LEA_ID, "Lea Schneider")]),
383
time: at(2, 10, 0),
384
unread: false,
385
preview: Some((MARA_ID, "Mara Lindqvist", "Thanks for the release!")),
386
deleted: false,
387
},
388
DemoChat {
389
id: "demo-chat-muted-bikes",
390
kind: "group",
391
title: "Bike to work",
392
members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
393
time: at(4, 8, 15),
394
unread: false,
395
preview: Some((TOBIAS_ID, "Tobias Klein", "Route map attached")),
396
deleted: false,
397
},
398
DemoChat {
399
id: "demo-chat-muted-book",
400
kind: "group",
401
title: "Book club",
402
members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]),
403
time: at(6, 19, 40),
404
unread: false,
405
preview: Some((PRIYA_ID, "Priya Nair", "Next pick: Dune")),
406
deleted: false,
407
},
408
DemoChat {
409
id: "demo-chat-muted-games",
410
kind: "group",
411
title: "Board game night",
412
members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
413
time: at(9, 18, 0),
414
unread: false,
415
preview: Some((JONAS_ID, "Jonas Ortega", "Who brings the snacks?")),
416
deleted: false,
417
},
330
418
]
331
419
}
332
420
@@ -562,6 +650,9 @@ pub fn seed(store: &Store) {
562
650
})
563
651
.collect();
564
652
let _ = store.upsert_chats(&chats);
653
for chat_id in MUTED_CHATS {
654
let _ = store.set_chat_muted(chat_id, true);
655
}
565
656
let teams: Vec<TeamRecord> = DEMO_TEAMS
566
657
.iter()
567
658
.map(|(id, name, _)| TeamRecord {
@@ -613,12 +704,14 @@ pub fn seed_directory(state: &mut AppState) {
613
704
id: FAVORITES_ID.to_owned(),
614
705
name: String::new(),
615
706
kind: FolderKind::Favorites,
707
expanded: None,
616
708
conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
617
709
},
618
710
FolderInfo {
619
711
id: CUSTOMERS_FOLDER.to_owned(),
620
712
name: "Customers".to_owned(),
621
713
kind: FolderKind::UserCreated,
714
expanded: None,
622
715
conversation_ids: ids(&[
623
716
"demo-chat-customer-1",
624
717
"demo-chat-customer-2",
@@ -630,12 +723,14 @@ pub fn seed_directory(state: &mut AppState) {
630
723
id: ATLAS_FOLDER.to_owned(),
631
724
name: "Project Atlas".to_owned(),
632
725
kind: FolderKind::UserCreated,
726
expanded: None,
633
727
conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
634
728
},
635
729
FolderInfo {
636
730
id: TODO_FOLDER.to_owned(),
637
731
name: "To do".to_owned(),
638
732
kind: FolderKind::UserCreated,
733
expanded: None,
639
734
conversation_ids: Vec::new(),
640
735
},
641
736
];
@@ -688,6 +783,10 @@ pub fn seed_directory(state: &mut AppState) {
688
783
Instant::now(),
689
784
Utc::now(),
690
785
);
786
state
787
.directory
788
.section_settings
789
.set(ChatSection::Meeting, true);
691
790
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
692
791
state.last_sync = Some(Utc::now());
693
792
state.apply_bot_titles();
@@ -845,7 +944,11 @@ fn bot_messages() -> Vec<MessageRecord> {
845
944
let mut messages = vec![
846
945
bot_card_message("b1", at(0, 13, 45), &card),
847
946
bot_card_message("b2", at(0, 13, 52), &input_card()),
848
bot_card_message("b3", at(0, 13, 58), &crate::demo_input_cards::all_inputs_card()),
947
bot_card_message(
948
"b3",
949
at(0, 13, 58),
950
&crate::demo_input_cards::all_inputs_card(),
951
),
849
952
];
850
953
messages.extend(
851
954
crate::demo_cards::behaviour_cards()
@@ -853,14 +956,11 @@ fn bot_messages() -> Vec<MessageRecord> {
853
956
.zip(0u32..)
854
957
.map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),
855
958
);
856
messages.extend(
857
crate::demo_chart_cards::cards()
858
.iter()
859
.zip(0..)
860
.map(|(chart_card, minute)| {
861
bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
862
}),
863
);
959
messages.extend(crate::demo_chart_cards::cards().iter().zip(0..).map(
960
|(chart_card, minute)| {
961
bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
962
},
963
));
864
964
messages
865
965
}
866
966
@@ -9,8 +9,8 @@ use store::{9
TeamLayoutRecord, TeamRecord,9
TeamLayoutRecord, TeamRecord,10
};10
};11
use teams_core::{11
use teams_core::{12
CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,12
CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,13
PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind,13
PersonSource, PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind,14
};14
};15
15
16
use crate::activity::{Actor, Entry, Kind};16
use crate::activity::{Actor, Entry, Kind};@@ -137,6 +137,14 @@ const FAVORITES_ID: &str = "demo-folder-favorites";137
const CUSTOMERS_FOLDER: &str = "demo-folder-customers";137
const CUSTOMERS_FOLDER: &str = "demo-folder-customers";138
const ATLAS_FOLDER: &str = "demo-folder-atlas";138
const ATLAS_FOLDER: &str = "demo-folder-atlas";139
const TODO_FOLDER: &str = "demo-folder-todo";139
const TODO_FOLDER: &str = "demo-folder-todo";140
const MUTED_CHATS: [&str; 6] = [141
"demo-chat-muted-lunch",142
"demo-chat-muted-offsite",143
"demo-chat-muted-kudos",144
"demo-chat-muted-bikes",145
"demo-chat-muted-book",146
"demo-chat-muted-games",147
];140
148
141
fn member(user_id: &str, name: &str) -> MemberRecord {149
fn member(user_id: &str, name: &str) -> MemberRecord {142
MemberRecord {150
MemberRecord {@@ -327,6 +335,86 @@ fn demo_chats() -> Vec<DemoChat> {327
preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),335
preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),328
deleted: false,336
deleted: false,329
},337
},338
DemoChat {339
id: "demo-chat-meeting-standup",340
kind: "meeting",341
title: "Daily standup",342
members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),343
time: at(0, 9, 45),344
unread: true,345
preview: Some((JONAS_ID, "Jonas Ortega", "Recording is available")),346
deleted: false,347
},348
DemoChat {349
id: "demo-chat-meeting-retro",350
kind: "meeting",351
title: "Sprint retrospective",352
members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),353
time: at(3, 15, 30),354
unread: false,355
preview: Some((MARA_ID, "Mara Lindqvist", "Notes are in the wiki")),356
deleted: false,357
},358
DemoChat {359
id: "demo-chat-muted-lunch",360
kind: "group",361
title: "Lunch crew",362
members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),363
time: at(0, 12, 5),364
unread: true,365
preview: Some((JONAS_ID, "Jonas Ortega", "Pizza on Friday?")),366
deleted: false,367
},368
DemoChat {369
id: "demo-chat-muted-offsite",370
kind: "group",371
title: "Team offsite 2027",372
members: group(&[(LEA_ID, "Lea Schneider"), (LEA_ID, "Lea Schneider")]),373
time: at(1, 16, 20),374
unread: false,375
preview: Some((LEA_ID, "Lea Schneider", "Voting closes tomorrow")),376
deleted: false,377
},378
DemoChat {379
id: "demo-chat-muted-kudos",380
kind: "group",381
title: "Kudos corner",382
members: group(&[(MARA_ID, "Mara Lindqvist"), (LEA_ID, "Lea Schneider")]),383
time: at(2, 10, 0),384
unread: false,385
preview: Some((MARA_ID, "Mara Lindqvist", "Thanks for the release!")),386
deleted: false,387
},388
DemoChat {389
id: "demo-chat-muted-bikes",390
kind: "group",391
title: "Bike to work",392
members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),393
time: at(4, 8, 15),394
unread: false,395
preview: Some((TOBIAS_ID, "Tobias Klein", "Route map attached")),396
deleted: false,397
},398
DemoChat {399
id: "demo-chat-muted-book",400
kind: "group",401
title: "Book club",402
members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]),403
time: at(6, 19, 40),404
unread: false,405
preview: Some((PRIYA_ID, "Priya Nair", "Next pick: Dune")),406
deleted: false,407
},408
DemoChat {409
id: "demo-chat-muted-games",410
kind: "group",411
title: "Board game night",412
members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),413
time: at(9, 18, 0),414
unread: false,415
preview: Some((JONAS_ID, "Jonas Ortega", "Who brings the snacks?")),416
deleted: false,417
},330
]418
]331
}419
}332
420
@@ -562,6 +650,9 @@ pub fn seed(store: &Store) {562
})650
})563
.collect();651
.collect();564
let _ = store.upsert_chats(&chats);652
let _ = store.upsert_chats(&chats);653
for chat_id in MUTED_CHATS {654
let _ = store.set_chat_muted(chat_id, true);655
}565
let teams: Vec<TeamRecord> = DEMO_TEAMS656
let teams: Vec<TeamRecord> = DEMO_TEAMS566
.iter()657
.iter()567
.map(|(id, name, _)| TeamRecord {658
.map(|(id, name, _)| TeamRecord {@@ -613,12 +704,14 @@ pub fn seed_directory(state: &mut AppState) {613
id: FAVORITES_ID.to_owned(),704
id: FAVORITES_ID.to_owned(),614
name: String::new(),705
name: String::new(),615
kind: FolderKind::Favorites,706
kind: FolderKind::Favorites,707
expanded: None,616
conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),708
conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),617
},709
},618
FolderInfo {710
FolderInfo {619
id: CUSTOMERS_FOLDER.to_owned(),711
id: CUSTOMERS_FOLDER.to_owned(),620
name: "Customers".to_owned(),712
name: "Customers".to_owned(),621
kind: FolderKind::UserCreated,713
kind: FolderKind::UserCreated,714
expanded: None,622
conversation_ids: ids(&[715
conversation_ids: ids(&[623
"demo-chat-customer-1",716
"demo-chat-customer-1",624
"demo-chat-customer-2",717
"demo-chat-customer-2",@@ -630,12 +723,14 @@ pub fn seed_directory(state: &mut AppState) {630
id: ATLAS_FOLDER.to_owned(),723
id: ATLAS_FOLDER.to_owned(),631
name: "Project Atlas".to_owned(),724
name: "Project Atlas".to_owned(),632
kind: FolderKind::UserCreated,725
kind: FolderKind::UserCreated,726
expanded: None,633
conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),727
conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),634
},728
},635
FolderInfo {729
FolderInfo {636
id: TODO_FOLDER.to_owned(),730
id: TODO_FOLDER.to_owned(),637
name: "To do".to_owned(),731
name: "To do".to_owned(),638
kind: FolderKind::UserCreated,732
kind: FolderKind::UserCreated,733
expanded: None,639
conversation_ids: Vec::new(),734
conversation_ids: Vec::new(),640
},735
},641
];736
];@@ -688,6 +783,10 @@ pub fn seed_directory(state: &mut AppState) {688
Instant::now(),783
Instant::now(),689
Utc::now(),784
Utc::now(),690
);785
);786
state787
.directory788
.section_settings789
.set(ChatSection::Meeting, true);691
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());790
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());692
state.last_sync = Some(Utc::now());791
state.last_sync = Some(Utc::now());693
state.apply_bot_titles();792
state.apply_bot_titles();@@ -845,7 +944,11 @@ fn bot_messages() -> Vec<MessageRecord> {845
let mut messages = vec![944
let mut messages = vec![846
bot_card_message("b1", at(0, 13, 45), &card),945
bot_card_message("b1", at(0, 13, 45), &card),847
bot_card_message("b2", at(0, 13, 52), &input_card()),946
bot_card_message("b2", at(0, 13, 52), &input_card()),848
bot_card_message("b3", at(0, 13, 58), &crate::demo_input_cards::all_inputs_card()),947
bot_card_message(948
"b3",949
at(0, 13, 58),950
&crate::demo_input_cards::all_inputs_card(),951
),849
];952
];850
messages.extend(953
messages.extend(851
crate::demo_cards::behaviour_cards()954
crate::demo_cards::behaviour_cards()@@ -853,14 +956,11 @@ fn bot_messages() -> Vec<MessageRecord> {853
.zip(0u32..)956
.zip(0u32..)854
.map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),957
.map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),855
);958
);856
messages.extend(959
messages.extend(crate::demo_chart_cards::cards().iter().zip(0..).map(857
crate::demo_chart_cards::cards()960
|(chart_card, minute)| {858
.iter()961
bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)859
.zip(0..)962
},860
.map(|(chart_card, minute)| {963
));861
bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)862
}),863
);864
messages964
messages865
}965
}866
966
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
2
2
3
3
use chrono::{DateTime, FixedOffset, Utc};
4
4
use store::{ChatRecord, Sidebar};
5
use teams_core::ChatSection;
5
6
6
7
use crate::app_state::chat_title;
7
8
use crate::data::{
@@ -13,10 +14,16 @@ use crate::typing::{TypingState, preview_label};
13
14
pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
14
15
pub const OTHERS_NAME: &str = "Other chats";
15
16
pub const OTHERS_ID: &str = "others";
17
pub const MEETING_NAME: &str = "Meeting chats";
18
pub const MEETING_ID: &str = "meeting_chats";
19
pub const MUTED_NAME: &str = "Muted";
20
pub const MUTED_ID: &str = "muted_chats";
21
pub const SECTION_PAGE_SIZE: usize = 5;
16
22
pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
17
23
pub const DELETED_PREVIEW: &str = "Message deleted";
18
24
const OWN_PREFIX: &str = "You";
19
25
const GROUP_KIND: &str = "group";
26
const MEETING_KIND: &str = "meeting";
20
27
21
28
#[derive(Debug, Clone, PartialEq, Eq)]
22
29
pub enum Preview {
@@ -32,6 +39,7 @@ pub enum Preview {
32
39
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33
40
pub enum Unread {
34
41
None,
42
Silent,
35
43
Dot,
36
44
Count(u32),
37
45
}
@@ -74,6 +82,8 @@ pub enum SectionKind {
74
82
Favorites,
75
83
Folder,
76
84
Others,
85
Meeting,
86
Muted,
77
87
}
78
88
79
89
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -85,6 +95,8 @@ pub struct Section {
85
95
pub count: usize,
86
96
pub unread_chats: u32,
87
97
pub items: Vec<ChatItem>,
98
pub hidden_count: usize,
99
pub list_expanded: bool,
88
100
pub show_empty_hint: bool,
89
101
}
90
102
@@ -92,6 +104,7 @@ pub struct SectionInput<'a> {
92
104
pub chats: &'a [ChatRecord],
93
105
pub directory: &'a Directory,
94
106
pub collapsed: &'a HashSet<String>,
107
pub expanded_lists: &'a HashSet<String>,
95
108
pub typing: &'a TypingState,
96
109
pub now: DateTime<Utc>,
97
110
pub offset: FixedOffset,
@@ -219,41 +232,97 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
219
232
.map(|chat| (chat.id.as_str(), chat))
220
233
.collect();
221
234
let mut placed: HashSet<&str> = HashSet::new();
222
let mut sections = Vec::new();
223
for folder in &input.directory.folders {
224
let items: Vec<ChatItem> = folder
225
.conversation_ids
226
.iter()
227
.filter_map(|id| by_id.get(id.as_str()).copied())
228
.filter(|chat| placed.insert(chat.id.as_str()))
229
.map(|chat| chat_item(chat, input, Some(&folder.id)))
230
.collect();
231
let (kind, name) = match folder.kind {
232
FolderKind::Favorites => (
233
SectionKind::Favorites,
234
if folder.name.trim().is_empty() {
235
FAVORITES_FALLBACK_NAME.to_owned()
236
} else {
237
folder.name.clone()
238
},
239
),
240
FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),
241
};
242
sections.push(section(folder.id.clone(), name, kind, items, input));
243
}
244
let rest: Vec<ChatItem> = input
235
let mut built: Vec<Option<Section>> = input
236
.directory
237
.folders
238
.iter()
239
.map(|folder| {
240
let (kind, name) = match folder.kind {
241
FolderKind::Favorites => (
242
SectionKind::Favorites,
243
if folder.name.trim().is_empty() {
244
FAVORITES_FALLBACK_NAME.to_owned()
245
} else {
246
folder.name.clone()
247
},
248
),
249
FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),
250
FolderKind::Recent | FolderKind::Meeting | FolderKind::Muted => return None,
251
};
252
let items: Vec<ChatItem> = folder
253
.conversation_ids
254
.iter()
255
.filter_map(|id| by_id.get(id.as_str()).copied())
256
.filter(|chat| placed.insert(chat.id.as_str()))
257
.map(|chat| chat_item(chat, input, Some(&folder.id)))
258
.collect();
259
Some(section(folder.id.clone(), name, kind, items, input))
260
})
261
.collect();
262
let settings = &input.directory.section_settings;
263
let mut muted = Vec::new();
264
let mut meeting = Vec::new();
265
let mut rest = Vec::new();
266
for chat in input
245
267
.chats
246
268
.iter()
247
269
.filter(|chat| !placed.contains(chat.id.as_str()))
248
.map(|chat| chat_item(chat, input, None))
249
.collect();
250
sections.push(section(
251
OTHERS_ID.to_owned(),
270
{
271
let item = chat_item(chat, input, None);
272
if chat.muted && settings.enabled(ChatSection::Muted) {
273
muted.push(item);
274
} else if !chat.muted && chat.kind == MEETING_KIND && settings.enabled(ChatSection::Meeting)
275
{
276
meeting.push(item);
277
} else {
278
rest.push(item);
279
}
280
}
281
let folder_id = |kind: FolderKind, fallback: &str| {
282
input
283
.directory
284
.folders
285
.iter()
286
.find(|folder| folder.kind == kind)
287
.map_or_else(|| fallback.to_owned(), |folder| folder.id.clone())
288
};
289
let mut others = Some(section(
290
folder_id(FolderKind::Recent, OTHERS_ID),
252
291
OTHERS_NAME.to_owned(),
253
292
SectionKind::Others,
254
293
rest,
255
294
input,
256
295
));
296
let mut meeting = (!meeting.is_empty()).then(|| {
297
section(
298
folder_id(FolderKind::Meeting, MEETING_ID),
299
MEETING_NAME.to_owned(),
300
SectionKind::Meeting,
301
meeting,
302
input,
303
)
304
});
305
let mut muted = (!muted.is_empty()).then(|| {
306
section(
307
folder_id(FolderKind::Muted, MUTED_ID),
308
MUTED_NAME.to_owned(),
309
SectionKind::Muted,
310
muted,
311
input,
312
)
313
});
314
let mut sections = Vec::new();
315
for (folder, section) in input.directory.folders.iter().zip(&mut built) {
316
match folder.kind {
317
FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
318
FolderKind::Recent => sections.extend(others.take()),
319
FolderKind::Meeting => sections.extend(meeting.take()),
320
FolderKind::Muted => sections.extend(muted.take()),
321
}
322
}
323
sections.extend(meeting);
324
sections.extend(others);
325
sections.extend(muted);
257
326
sections
258
327
}
259
328
@@ -278,19 +347,39 @@ fn section(
278
347
id: String,
279
348
name: String,
280
349
kind: SectionKind,
281
items: Vec<ChatItem>,
350
mut items: Vec<ChatItem>,
282
351
input: &SectionInput<'_>,
283
352
) -> Section {
284
353
let collapsed = input.collapsed.contains(&id);
354
let count = items.len();
285
355
let unread_chats = items
286
356
.iter()
287
357
.filter(|item| item.unread.is_unread() && !item.muted)
288
358
.count() as u32;
359
let paged = matches!(kind, SectionKind::Meeting | SectionKind::Muted);
360
let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
361
let hidden_count = if paged && !list_expanded {
362
count.saturating_sub(SECTION_PAGE_SIZE)
363
} else {
364
0
365
};
366
items.truncate(count - hidden_count);
367
if kind == SectionKind::Muted {
368
for item in &mut items {
369
if item.unread.is_unread() {
370
item.unread = Unread::Silent;
371
}
372
}
373
}
289
374
Section {
290
375
collapsed,
291
count: items.len(),
376
count,
292
377
unread_chats,
293
show_empty_hint: items.is_empty() && !collapsed && kind != SectionKind::Others,
378
hidden_count,
379
list_expanded,
380
show_empty_hint: items.is_empty()
381
&& !collapsed
382
&& matches!(kind, SectionKind::Favorites | SectionKind::Folder),
294
383
id,
295
384
name,
296
385
kind,
@@ -343,10 +432,42 @@ mod tests {
343
432
id: id.into(),
344
433
name: format!("name-{id}"),
345
434
kind,
435
expanded: None,
346
436
conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
347
437
}
348
438
}
349
439
440
fn muted_chat(id: &str) -> ChatRecord {
441
ChatRecord {
442
muted: true,
443
..chat(id, "group", false)
444
}
445
}
446
447
fn meeting_chat(id: &str) -> ChatRecord {
448
chat(id, "meeting", false)
449
}
450
451
fn sectioned_directory(muted: bool, meeting: bool, folders: Vec<FolderInfo>) -> Directory {
452
let mut directory = Directory {
453
folders,
454
..Default::default()
455
};
456
directory.section_settings.set(ChatSection::Muted, muted);
457
directory
458
.section_settings
459
.set(ChatSection::Meeting, meeting);
460
directory
461
}
462
463
fn section_ids(sections: &[Section]) -> Vec<&str> {
464
sections.iter().map(|section| section.id.as_str()).collect()
465
}
466
467
fn item_ids(section: &Section) -> Vec<&str> {
468
section.items.iter().map(|item| item.id.as_str()).collect()
469
}
470
350
471
fn input<'a>(
351
472
chats: &'a [ChatRecord],
352
473
directory: &'a Directory,
@@ -355,6 +476,9 @@ mod tests {
355
476
typing_input(chats, directory, collapsed, &NO_TYPING)
356
477
}
357
478
479
static NO_EXPANDED: std::sync::LazyLock<HashSet<String>> =
480
std::sync::LazyLock::new(HashSet::new);
481
358
482
static NO_TYPING: std::sync::LazyLock<TypingState> =
359
483
std::sync::LazyLock::new(TypingState::default);
360
484
@@ -368,6 +492,7 @@ mod tests {
368
492
chats,
369
493
directory,
370
494
collapsed,
495
expanded_lists: &NO_EXPANDED,
371
496
typing,
372
497
now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
373
498
offset: FixedOffset::east_opt(0).unwrap(),
@@ -402,8 +527,9 @@ mod tests {
402
527
let collapsed = HashSet::new();
403
528
let sections = build_sections(&input(&chats, &directory, &collapsed));
404
529
assert_eq!(sections[0].unread_chats, 1);
405
assert!(sections[0].items[0].muted);
406
assert!(sections[0].items[0].unread.is_unread());
530
assert_eq!(sections[1].kind, SectionKind::Muted);
531
assert!(sections[1].items[0].muted);
532
assert!(sections[1].items[0].unread.is_unread());
407
533
}
408
534
409
535
#[test]
@@ -613,4 +739,166 @@ mod tests {
613
739
let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
614
740
assert_eq!(item.time_label, "09:30");
615
741
}
742
743
#[test]
744
fn muted_and_meeting_chats_leave_others_unless_pinned_or_in_a_custom_section() {
745
let chats = vec![
746
chat("plain", "group", false),
747
muted_chat("quiet"),
748
muted_chat("pinned-quiet"),
749
meeting_chat("sync"),
750
meeting_chat("custom-sync"),
751
ChatRecord {
752
muted: true,
753
..meeting_chat("quiet-sync")
754
},
755
];
756
let directory = sectioned_directory(
757
true,
758
true,
759
vec![
760
folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
761
folder("work", FolderKind::UserCreated, &["custom-sync"]),
762
],
763
);
764
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
765
assert_eq!(
766
section_ids(§ions),
767
vec!["fav", "work", MEETING_ID, OTHERS_ID, MUTED_ID]
768
);
769
assert_eq!(item_ids(§ions[0]), vec!["pinned-quiet"]);
770
assert_eq!(item_ids(§ions[1]), vec!["custom-sync"]);
771
assert_eq!(item_ids(§ions[2]), vec!["sync"]);
772
assert_eq!(item_ids(§ions[3]), vec!["plain"]);
773
assert_eq!(item_ids(§ions[4]), vec!["quiet", "quiet-sync"]);
774
assert_eq!(sections[4].kind, SectionKind::Muted);
775
assert_eq!(sections[4].count, 2);
776
}
777
778
#[test]
779
fn turning_a_section_off_puts_its_chats_back_in_others() {
780
let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
781
let directory = sectioned_directory(false, false, Vec::new());
782
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
783
assert_eq!(section_ids(§ions), vec![OTHERS_ID]);
784
assert_eq!(item_ids(§ions[0]), vec!["quiet", "sync"]);
785
}
786
787
#[test]
788
fn muted_is_on_and_meeting_is_off_until_the_user_chooses() {
789
let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
790
let directory = Directory::default();
791
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
792
assert_eq!(section_ids(§ions), vec![OTHERS_ID, MUTED_ID]);
793
assert_eq!(item_ids(§ions[0]), vec!["sync"]);
794
}
795
796
#[test]
797
fn empty_system_sections_are_hidden() {
798
let chats = vec![chat("a", "group", false)];
799
let directory = sectioned_directory(true, true, Vec::new());
800
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
801
assert_eq!(section_ids(§ions), vec![OTHERS_ID]);
802
}
803
804
#[test]
805
fn sections_follow_the_server_folder_order_with_system_folders() {
806
let chats = vec![
807
chat("a", "group", false),
808
muted_chat("quiet"),
809
meeting_chat("sync"),
810
];
811
let directory = sectioned_directory(
812
true,
813
true,
814
vec![
815
folder("muted-id", FolderKind::Muted, &[]),
816
folder("fav", FolderKind::Favorites, &[]),
817
folder("recent-id", FolderKind::Recent, &[]),
818
folder("meeting-id", FolderKind::Meeting, &[]),
819
],
820
);
821
let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
822
let sections = build_sections(&input(&chats, &directory, &collapsed));
823
assert_eq!(
824
section_ids(§ions),
825
vec!["muted-id", "fav", "recent-id", "meeting-id"]
826
);
827
assert!(sections[0].collapsed);
828
assert_eq!(sections[0].name, MUTED_NAME);
829
assert_eq!(sections[3].name, MEETING_NAME);
830
}
831
832
#[test]
833
fn newest_five_show_then_see_more_expands_and_see_less_collapses() {
834
let chats: Vec<ChatRecord> = (0..8)
835
.map(|index| muted_chat(&format!("m{index}")))
836
.collect();
837
let directory = Directory::default();
838
let collapsed = HashSet::new();
839
let sections = build_sections(&input(&chats, &directory, &collapsed));
840
let muted = §ions[1];
841
assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);
842
assert_eq!(muted.count, 8);
843
assert_eq!(muted.hidden_count, 3);
844
assert!(!muted.list_expanded);
845
846
let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
847
let mut context = input(&chats, &directory, &collapsed);
848
context.expanded_lists = &expanded;
849
let sections = build_sections(&context);
850
let muted = §ions[1];
851
assert_eq!(muted.items.len(), 8);
852
assert_eq!(muted.hidden_count, 0);
853
assert!(muted.list_expanded);
854
}
855
856
#[test]
857
fn five_chats_need_no_see_more_even_when_marked_expanded() {
858
let chats: Vec<ChatRecord> = (0..5)
859
.map(|index| muted_chat(&format!("m{index}")))
860
.collect();
861
let directory = Directory::default();
862
let collapsed = HashSet::new();
863
let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
864
let mut context = input(&chats, &directory, &collapsed);
865
context.expanded_lists = &expanded;
866
let muted = &build_sections(&context)[1];
867
assert_eq!(muted.hidden_count, 0);
868
assert!(!muted.list_expanded);
869
}
870
871
#[test]
872
fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {
873
let mut quiet = muted_chat("quiet");
874
quiet.unread = true;
875
let chats = vec![
876
quiet,
877
ChatRecord {
878
muted: true,
879
..meeting_chat("x")
880
},
881
];
882
let mut directory = Directory::default();
883
directory.unread_counts.insert("quiet".into(), 4);
884
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
885
let muted = §ions[1];
886
assert_eq!(muted.items[0].unread, Unread::Silent);
887
assert!(muted.items[0].unread.is_unread());
888
assert_eq!(muted.unread_chats, 0);
889
assert_eq!(unread_chat_count(&chats), 0);
890
}
891
892
#[test]
893
fn meeting_chats_keep_their_unread_count() {
894
let mut sync = meeting_chat("sync");
895
sync.unread = true;
896
let chats = vec![sync];
897
let mut directory = sectioned_directory(true, true, Vec::new());
898
directory.unread_counts.insert("sync".into(), 3);
899
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
900
assert_eq!(sections[0].id, MEETING_ID);
901
assert_eq!(sections[0].items[0].unread, Unread::Count(3));
902
assert_eq!(sections[0].unread_chats, 1);
903
}
616
904
}
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};2
2
3
use chrono::{DateTime, FixedOffset, Utc};3
use chrono::{DateTime, FixedOffset, Utc};4
use store::{ChatRecord, Sidebar};4
use store::{ChatRecord, Sidebar};5
use teams_core::ChatSection;5
6
6
use crate::app_state::chat_title;7
use crate::app_state::chat_title;7
use crate::data::{8
use crate::data::{@@ -13,10 +14,16 @@ use crate::typing::{TypingState, preview_label};13
pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";14
pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";14
pub const OTHERS_NAME: &str = "Other chats";15
pub const OTHERS_NAME: &str = "Other chats";15
pub const OTHERS_ID: &str = "others";16
pub const OTHERS_ID: &str = "others";17
pub const MEETING_NAME: &str = "Meeting chats";18
pub const MEETING_ID: &str = "meeting_chats";19
pub const MUTED_NAME: &str = "Muted";20
pub const MUTED_ID: &str = "muted_chats";21
pub const SECTION_PAGE_SIZE: usize = 5;16
pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";22
pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";17
pub const DELETED_PREVIEW: &str = "Message deleted";23
pub const DELETED_PREVIEW: &str = "Message deleted";18
const OWN_PREFIX: &str = "You";24
const OWN_PREFIX: &str = "You";19
const GROUP_KIND: &str = "group";25
const GROUP_KIND: &str = "group";26
const MEETING_KIND: &str = "meeting";20
27
21
#[derive(Debug, Clone, PartialEq, Eq)]28
#[derive(Debug, Clone, PartialEq, Eq)]22
pub enum Preview {29
pub enum Preview {@@ -32,6 +39,7 @@ pub enum Preview {32
#[derive(Debug, Clone, Copy, PartialEq, Eq)]39
#[derive(Debug, Clone, Copy, PartialEq, Eq)]33
pub enum Unread {40
pub enum Unread {34
None,41
None,42
Silent,35
Dot,43
Dot,36
Count(u32),44
Count(u32),37
}45
}@@ -74,6 +82,8 @@ pub enum SectionKind {74
Favorites,82
Favorites,75
Folder,83
Folder,76
Others,84
Others,85
Meeting,86
Muted,77
}87
}78
88
79
#[derive(Debug, Clone, PartialEq, Eq)]89
#[derive(Debug, Clone, PartialEq, Eq)]@@ -85,6 +95,8 @@ pub struct Section {85
pub count: usize,95
pub count: usize,86
pub unread_chats: u32,96
pub unread_chats: u32,87
pub items: Vec<ChatItem>,97
pub items: Vec<ChatItem>,98
pub hidden_count: usize,99
pub list_expanded: bool,88
pub show_empty_hint: bool,100
pub show_empty_hint: bool,89
}101
}90
102
@@ -92,6 +104,7 @@ pub struct SectionInput<'a> {92
pub chats: &'a [ChatRecord],104
pub chats: &'a [ChatRecord],93
pub directory: &'a Directory,105
pub directory: &'a Directory,94
pub collapsed: &'a HashSet<String>,106
pub collapsed: &'a HashSet<String>,107
pub expanded_lists: &'a HashSet<String>,95
pub typing: &'a TypingState,108
pub typing: &'a TypingState,96
pub now: DateTime<Utc>,109
pub now: DateTime<Utc>,97
pub offset: FixedOffset,110
pub offset: FixedOffset,@@ -219,41 +232,97 @@ pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {219
.map(|chat| (chat.id.as_str(), chat))232
.map(|chat| (chat.id.as_str(), chat))220
.collect();233
.collect();221
let mut placed: HashSet<&str> = HashSet::new();234
let mut placed: HashSet<&str> = HashSet::new();222
let mut sections = Vec::new();235
let mut built: Vec<Option<Section>> = input223
for folder in &input.directory.folders {236
.directory224
let items: Vec<ChatItem> = folder237
.folders225
.conversation_ids238
.iter()226
.iter()239
.map(|folder| {227
.filter_map(|id| by_id.get(id.as_str()).copied())240
let (kind, name) = match folder.kind {228
.filter(|chat| placed.insert(chat.id.as_str()))241
FolderKind::Favorites => (229
.map(|chat| chat_item(chat, input, Some(&folder.id)))242
SectionKind::Favorites,230
.collect();243
if folder.name.trim().is_empty() {231
let (kind, name) = match folder.kind {244
FAVORITES_FALLBACK_NAME.to_owned()232
FolderKind::Favorites => (245
} else {233
SectionKind::Favorites,246
folder.name.clone()234
if folder.name.trim().is_empty() {247
},235
FAVORITES_FALLBACK_NAME.to_owned()248
),236
} else {249
FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),237
folder.name.clone()250
FolderKind::Recent | FolderKind::Meeting | FolderKind::Muted => return None,238
},251
};239
),252
let items: Vec<ChatItem> = folder240
FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),253
.conversation_ids241
};254
.iter()242
sections.push(section(folder.id.clone(), name, kind, items, input));255
.filter_map(|id| by_id.get(id.as_str()).copied())243
}256
.filter(|chat| placed.insert(chat.id.as_str()))244
let rest: Vec<ChatItem> = input257
.map(|chat| chat_item(chat, input, Some(&folder.id)))258
.collect();259
Some(section(folder.id.clone(), name, kind, items, input))260
})261
.collect();262
let settings = &input.directory.section_settings;263
let mut muted = Vec::new();264
let mut meeting = Vec::new();265
let mut rest = Vec::new();266
for chat in input245
.chats267
.chats246
.iter()268
.iter()247
.filter(|chat| !placed.contains(chat.id.as_str()))269
.filter(|chat| !placed.contains(chat.id.as_str()))248
.map(|chat| chat_item(chat, input, None))270
{249
.collect();271
let item = chat_item(chat, input, None);250
sections.push(section(272
if chat.muted && settings.enabled(ChatSection::Muted) {251
OTHERS_ID.to_owned(),273
muted.push(item);274
} else if !chat.muted && chat.kind == MEETING_KIND && settings.enabled(ChatSection::Meeting)275
{276
meeting.push(item);277
} else {278
rest.push(item);279
}280
}281
let folder_id = |kind: FolderKind, fallback: &str| {282
input283
.directory284
.folders285
.iter()286
.find(|folder| folder.kind == kind)287
.map_or_else(|| fallback.to_owned(), |folder| folder.id.clone())288
};289
let mut others = Some(section(290
folder_id(FolderKind::Recent, OTHERS_ID),252
OTHERS_NAME.to_owned(),291
OTHERS_NAME.to_owned(),253
SectionKind::Others,292
SectionKind::Others,254
rest,293
rest,255
input,294
input,256
));295
));296
let mut meeting = (!meeting.is_empty()).then(|| {297
section(298
folder_id(FolderKind::Meeting, MEETING_ID),299
MEETING_NAME.to_owned(),300
SectionKind::Meeting,301
meeting,302
input,303
)304
});305
let mut muted = (!muted.is_empty()).then(|| {306
section(307
folder_id(FolderKind::Muted, MUTED_ID),308
MUTED_NAME.to_owned(),309
SectionKind::Muted,310
muted,311
input,312
)313
});314
let mut sections = Vec::new();315
for (folder, section) in input.directory.folders.iter().zip(&mut built) {316
match folder.kind {317
FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),318
FolderKind::Recent => sections.extend(others.take()),319
FolderKind::Meeting => sections.extend(meeting.take()),320
FolderKind::Muted => sections.extend(muted.take()),321
}322
}323
sections.extend(meeting);324
sections.extend(others);325
sections.extend(muted);257
sections326
sections258
}327
}259
328
@@ -278,19 +347,39 @@ fn section(278
id: String,347
id: String,279
name: String,348
name: String,280
kind: SectionKind,349
kind: SectionKind,281
items: Vec<ChatItem>,350
mut items: Vec<ChatItem>,282
input: &SectionInput<'_>,351
input: &SectionInput<'_>,283
) -> Section {352
) -> Section {284
let collapsed = input.collapsed.contains(&id);353
let collapsed = input.collapsed.contains(&id);354
let count = items.len();285
let unread_chats = items355
let unread_chats = items286
.iter()356
.iter()287
.filter(|item| item.unread.is_unread() && !item.muted)357
.filter(|item| item.unread.is_unread() && !item.muted)288
.count() as u32;358
.count() as u32;359
let paged = matches!(kind, SectionKind::Meeting | SectionKind::Muted);360
let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);361
let hidden_count = if paged && !list_expanded {362
count.saturating_sub(SECTION_PAGE_SIZE)363
} else {364
0365
};366
items.truncate(count - hidden_count);367
if kind == SectionKind::Muted {368
for item in &mut items {369
if item.unread.is_unread() {370
item.unread = Unread::Silent;371
}372
}373
}289
Section {374
Section {290
collapsed,375
collapsed,291
count: items.len(),376
count,292
unread_chats,377
unread_chats,293
show_empty_hint: items.is_empty() && !collapsed && kind != SectionKind::Others,378
hidden_count,379
list_expanded,380
show_empty_hint: items.is_empty()381
&& !collapsed382
&& matches!(kind, SectionKind::Favorites | SectionKind::Folder),294
id,383
id,295
name,384
name,296
kind,385
kind,@@ -343,10 +432,42 @@ mod tests {343
id: id.into(),432
id: id.into(),344
name: format!("name-{id}"),433
name: format!("name-{id}"),345
kind,434
kind,435
expanded: None,346
conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),436
conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),347
}437
}348
}438
}349
439
440
fn muted_chat(id: &str) -> ChatRecord {441
ChatRecord {442
muted: true,443
..chat(id, "group", false)444
}445
}446
447
fn meeting_chat(id: &str) -> ChatRecord {448
chat(id, "meeting", false)449
}450
451
fn sectioned_directory(muted: bool, meeting: bool, folders: Vec<FolderInfo>) -> Directory {452
let mut directory = Directory {453
folders,454
..Default::default()455
};456
directory.section_settings.set(ChatSection::Muted, muted);457
directory458
.section_settings459
.set(ChatSection::Meeting, meeting);460
directory461
}462
463
fn section_ids(sections: &[Section]) -> Vec<&str> {464
sections.iter().map(|section| section.id.as_str()).collect()465
}466
467
fn item_ids(section: &Section) -> Vec<&str> {468
section.items.iter().map(|item| item.id.as_str()).collect()469
}470
350
fn input<'a>(471
fn input<'a>(351
chats: &'a [ChatRecord],472
chats: &'a [ChatRecord],352
directory: &'a Directory,473
directory: &'a Directory,@@ -355,6 +476,9 @@ mod tests {355
typing_input(chats, directory, collapsed, &NO_TYPING)476
typing_input(chats, directory, collapsed, &NO_TYPING)356
}477
}357
478
479
static NO_EXPANDED: std::sync::LazyLock<HashSet<String>> =480
std::sync::LazyLock::new(HashSet::new);481
358
static NO_TYPING: std::sync::LazyLock<TypingState> =482
static NO_TYPING: std::sync::LazyLock<TypingState> =359
std::sync::LazyLock::new(TypingState::default);483
std::sync::LazyLock::new(TypingState::default);360
484
@@ -368,6 +492,7 @@ mod tests {368
chats,492
chats,369
directory,493
directory,370
collapsed,494
collapsed,495
expanded_lists: &NO_EXPANDED,371
typing,496
typing,372
now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),497
now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),373
offset: FixedOffset::east_opt(0).unwrap(),498
offset: FixedOffset::east_opt(0).unwrap(),@@ -402,8 +527,9 @@ mod tests {402
let collapsed = HashSet::new();527
let collapsed = HashSet::new();403
let sections = build_sections(&input(&chats, &directory, &collapsed));528
let sections = build_sections(&input(&chats, &directory, &collapsed));404
assert_eq!(sections[0].unread_chats, 1);529
assert_eq!(sections[0].unread_chats, 1);405
assert!(sections[0].items[0].muted);530
assert_eq!(sections[1].kind, SectionKind::Muted);406
assert!(sections[0].items[0].unread.is_unread());531
assert!(sections[1].items[0].muted);532
assert!(sections[1].items[0].unread.is_unread());407
}533
}408
534
409
#[test]535
#[test]@@ -613,4 +739,166 @@ mod tests {613
let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);739
let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);614
assert_eq!(item.time_label, "09:30");740
assert_eq!(item.time_label, "09:30");615
}741
}742
743
#[test]744
fn muted_and_meeting_chats_leave_others_unless_pinned_or_in_a_custom_section() {745
let chats = vec![746
chat("plain", "group", false),747
muted_chat("quiet"),748
muted_chat("pinned-quiet"),749
meeting_chat("sync"),750
meeting_chat("custom-sync"),751
ChatRecord {752
muted: true,753
..meeting_chat("quiet-sync")754
},755
];756
let directory = sectioned_directory(757
true,758
true,759
vec![760
folder("fav", FolderKind::Favorites, &["pinned-quiet"]),761
folder("work", FolderKind::UserCreated, &["custom-sync"]),762
],763
);764
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));765
assert_eq!(766
section_ids(§ions),767
vec!["fav", "work", MEETING_ID, OTHERS_ID, MUTED_ID]768
);769
assert_eq!(item_ids(§ions[0]), vec!["pinned-quiet"]);770
assert_eq!(item_ids(§ions[1]), vec!["custom-sync"]);771
assert_eq!(item_ids(§ions[2]), vec!["sync"]);772
assert_eq!(item_ids(§ions[3]), vec!["plain"]);773
assert_eq!(item_ids(§ions[4]), vec!["quiet", "quiet-sync"]);774
assert_eq!(sections[4].kind, SectionKind::Muted);775
assert_eq!(sections[4].count, 2);776
}777
778
#[test]779
fn turning_a_section_off_puts_its_chats_back_in_others() {780
let chats = vec![muted_chat("quiet"), meeting_chat("sync")];781
let directory = sectioned_directory(false, false, Vec::new());782
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));783
assert_eq!(section_ids(§ions), vec![OTHERS_ID]);784
assert_eq!(item_ids(§ions[0]), vec!["quiet", "sync"]);785
}786
787
#[test]788
fn muted_is_on_and_meeting_is_off_until_the_user_chooses() {789
let chats = vec![muted_chat("quiet"), meeting_chat("sync")];790
let directory = Directory::default();791
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));792
assert_eq!(section_ids(§ions), vec![OTHERS_ID, MUTED_ID]);793
assert_eq!(item_ids(§ions[0]), vec!["sync"]);794
}795
796
#[test]797
fn empty_system_sections_are_hidden() {798
let chats = vec![chat("a", "group", false)];799
let directory = sectioned_directory(true, true, Vec::new());800
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));801
assert_eq!(section_ids(§ions), vec![OTHERS_ID]);802
}803
804
#[test]805
fn sections_follow_the_server_folder_order_with_system_folders() {806
let chats = vec![807
chat("a", "group", false),808
muted_chat("quiet"),809
meeting_chat("sync"),810
];811
let directory = sectioned_directory(812
true,813
true,814
vec![815
folder("muted-id", FolderKind::Muted, &[]),816
folder("fav", FolderKind::Favorites, &[]),817
folder("recent-id", FolderKind::Recent, &[]),818
folder("meeting-id", FolderKind::Meeting, &[]),819
],820
);821
let collapsed: HashSet<String> = ["muted-id".to_owned()].into();822
let sections = build_sections(&input(&chats, &directory, &collapsed));823
assert_eq!(824
section_ids(§ions),825
vec!["muted-id", "fav", "recent-id", "meeting-id"]826
);827
assert!(sections[0].collapsed);828
assert_eq!(sections[0].name, MUTED_NAME);829
assert_eq!(sections[3].name, MEETING_NAME);830
}831
832
#[test]833
fn newest_five_show_then_see_more_expands_and_see_less_collapses() {834
let chats: Vec<ChatRecord> = (0..8)835
.map(|index| muted_chat(&format!("m{index}")))836
.collect();837
let directory = Directory::default();838
let collapsed = HashSet::new();839
let sections = build_sections(&input(&chats, &directory, &collapsed));840
let muted = §ions[1];841
assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);842
assert_eq!(muted.count, 8);843
assert_eq!(muted.hidden_count, 3);844
assert!(!muted.list_expanded);845
846
let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();847
let mut context = input(&chats, &directory, &collapsed);848
context.expanded_lists = &expanded;849
let sections = build_sections(&context);850
let muted = §ions[1];851
assert_eq!(muted.items.len(), 8);852
assert_eq!(muted.hidden_count, 0);853
assert!(muted.list_expanded);854
}855
856
#[test]857
fn five_chats_need_no_see_more_even_when_marked_expanded() {858
let chats: Vec<ChatRecord> = (0..5)859
.map(|index| muted_chat(&format!("m{index}")))860
.collect();861
let directory = Directory::default();862
let collapsed = HashSet::new();863
let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();864
let mut context = input(&chats, &directory, &collapsed);865
context.expanded_lists = &expanded;866
let muted = &build_sections(&context)[1];867
assert_eq!(muted.hidden_count, 0);868
assert!(!muted.list_expanded);869
}870
871
#[test]872
fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {873
let mut quiet = muted_chat("quiet");874
quiet.unread = true;875
let chats = vec![876
quiet,877
ChatRecord {878
muted: true,879
..meeting_chat("x")880
},881
];882
let mut directory = Directory::default();883
directory.unread_counts.insert("quiet".into(), 4);884
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));885
let muted = §ions[1];886
assert_eq!(muted.items[0].unread, Unread::Silent);887
assert!(muted.items[0].unread.is_unread());888
assert_eq!(muted.unread_chats, 0);889
assert_eq!(unread_chat_count(&chats), 0);890
}891
892
#[test]893
fn meeting_chats_keep_their_unread_count() {894
let mut sync = meeting_chat("sync");895
sync.unread = true;896
let chats = vec![sync];897
let mut directory = sectioned_directory(true, true, Vec::new());898
directory.unread_counts.insert("sync".into(), 3);899
let sections = build_sections(&input(&chats, &directory, &HashSet::new()));900
assert_eq!(sections[0].id, MEETING_ID);901
assert_eq!(sections[0].items[0].unread, Unread::Count(3));902
assert_eq!(sections[0].unread_chats, 1);903
}616
}904
}@@ -31,6 +31,7 @@ const PINNED_CHANNEL_HEIGHT: f32 = 48.;
31
31
const SECTION_HEIGHT: f32 = 30.;
32
32
const SECTION_GAP: f32 = 4.;
33
33
const HINT_HEIGHT: f32 = 26.;
34
const SEE_MORE_HEIGHT: f32 = 28.;
34
35
const FALLBACK_VIEWPORT: f32 = 900.;
35
36
const VIEWPORT_MARGIN: f32 = 300.;
36
37
const AVATAR_SIZE: f32 = 36.;
@@ -507,7 +508,8 @@ impl SidebarView {
507
508
}
508
509
509
510
fn section_header(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
510
let drop_target = (section.kind != SectionKind::Others).then(|| section.id.clone());
511
let drop_target = matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)
512
.then(|| section.id.clone());
511
513
let toggle_id = section.id.clone();
512
514
h_flex()
513
515
.id(SharedString::from(format!("section-{}", section.id)))
@@ -569,6 +571,33 @@ impl SidebarView {
569
571
}))
570
572
}
571
573
574
fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
575
let toggle_id = section.id.clone();
576
let label = if section.hidden_count > 0 {
577
format!("See more ({})", section.hidden_count)
578
} else {
579
"See less".to_owned()
580
};
581
div()
582
.id(SharedString::from(format!("see-more-{}", section.id)))
583
.mx(px(8.))
584
.pl(px(54.))
585
.h(px(SEE_MORE_HEIGHT))
586
.flex()
587
.items_center()
588
.rounded(px(6.))
589
.cursor_pointer()
590
.text_size(px(12.5))
591
.text_color(theme::accent_text())
592
.hover(|row| row.bg(theme::row_hover()))
593
.child(label)
594
.on_click(cx.listener(move |this, _, _, cx| {
595
let id = toggle_id.clone();
596
this.state
597
.update(cx, |state, cx| state.toggle_list_expanded(&id, cx));
598
}))
599
}
600
572
601
fn chat_row(
573
602
&self,
574
603
item: &ChatItem,
@@ -720,6 +749,7 @@ impl SidebarView {
720
749
chats: &state.sidebar.chats,
721
750
directory: &state.directory,
722
751
collapsed: &state.collapsed,
752
expanded_lists: &state.expanded_lists,
723
753
typing: &state.typing,
724
754
now,
725
755
offset,
@@ -795,6 +825,11 @@ impl SidebarView {
795
825
}
796
826
y += ROW_HEIGHT;
797
827
}
828
if section.hidden_count > 0 || section.list_expanded {
829
list = with_spacer(list, &mut skipped_height);
830
list = list.child(self.see_more_row(section, cx));
831
y += SEE_MORE_HEIGHT;
832
}
798
833
if section.show_empty_hint {
799
834
list = with_spacer(list, &mut skipped_height);
800
835
list = list.child(
@@ -31,6 +31,7 @@ const PINNED_CHANNEL_HEIGHT: f32 = 48.;31
const SECTION_HEIGHT: f32 = 30.;31
const SECTION_HEIGHT: f32 = 30.;32
const SECTION_GAP: f32 = 4.;32
const SECTION_GAP: f32 = 4.;33
const HINT_HEIGHT: f32 = 26.;33
const HINT_HEIGHT: f32 = 26.;34
const SEE_MORE_HEIGHT: f32 = 28.;34
const FALLBACK_VIEWPORT: f32 = 900.;35
const FALLBACK_VIEWPORT: f32 = 900.;35
const VIEWPORT_MARGIN: f32 = 300.;36
const VIEWPORT_MARGIN: f32 = 300.;36
const AVATAR_SIZE: f32 = 36.;37
const AVATAR_SIZE: f32 = 36.;@@ -507,7 +508,8 @@ impl SidebarView {507
}508
}508
509
509
fn section_header(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {510
fn section_header(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {510
let drop_target = (section.kind != SectionKind::Others).then(|| section.id.clone());511
let drop_target = matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)512
.then(|| section.id.clone());511
let toggle_id = section.id.clone();513
let toggle_id = section.id.clone();512
h_flex()514
h_flex()513
.id(SharedString::from(format!("section-{}", section.id)))515
.id(SharedString::from(format!("section-{}", section.id)))@@ -569,6 +571,33 @@ impl SidebarView {569
}))571
}))570
}572
}571
573
574
fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {575
let toggle_id = section.id.clone();576
let label = if section.hidden_count > 0 {577
format!("See more ({})", section.hidden_count)578
} else {579
"See less".to_owned()580
};581
div()582
.id(SharedString::from(format!("see-more-{}", section.id)))583
.mx(px(8.))584
.pl(px(54.))585
.h(px(SEE_MORE_HEIGHT))586
.flex()587
.items_center()588
.rounded(px(6.))589
.cursor_pointer()590
.text_size(px(12.5))591
.text_color(theme::accent_text())592
.hover(|row| row.bg(theme::row_hover()))593
.child(label)594
.on_click(cx.listener(move |this, _, _, cx| {595
let id = toggle_id.clone();596
this.state597
.update(cx, |state, cx| state.toggle_list_expanded(&id, cx));598
}))599
}600
572
fn chat_row(601
fn chat_row(573
&self,602
&self,574
item: &ChatItem,603
item: &ChatItem,@@ -720,6 +749,7 @@ impl SidebarView {720
chats: &state.sidebar.chats,749
chats: &state.sidebar.chats,721
directory: &state.directory,750
directory: &state.directory,722
collapsed: &state.collapsed,751
collapsed: &state.collapsed,752
expanded_lists: &state.expanded_lists,723
typing: &state.typing,753
typing: &state.typing,724
now,754
now,725
offset,755
offset,@@ -795,6 +825,11 @@ impl SidebarView {795
}825
}796
y += ROW_HEIGHT;826
y += ROW_HEIGHT;797
}827
}828
if section.hidden_count > 0 || section.list_expanded {829
list = with_spacer(list, &mut skipped_height);830
list = list.child(self.see_more_row(section, cx));831
y += SEE_MORE_HEIGHT;832
}798
if section.show_empty_hint {833
if section.show_empty_hint {799
list = with_spacer(list, &mut skipped_height);834
list = with_spacer(list, &mut skipped_height);800
list = list.child(835
list = list.child(@@ -50,7 +50,7 @@ pub fn dot(size: f32) -> Div {
50
50
51
51
pub fn unread_marker(unread: Unread, muted: bool) -> Option<Div> {
52
52
match unread {
53
Unread::None => None,
53
Unread::None | Unread::Silent => None,
54
54
Unread::Dot if muted => Some(dot(8.).bg(theme::badge_muted())),
55
55
Unread::Dot => Some(dot(8.)),
56
56
Unread::Count(count) => Some(count_badge(count, muted)),
@@ -50,7 +50,7 @@ pub fn dot(size: f32) -> Div {50
50
51
pub fn unread_marker(unread: Unread, muted: bool) -> Option<Div> {51
pub fn unread_marker(unread: Unread, muted: bool) -> Option<Div> {52
match unread {52
match unread {53
Unread::None => None,53
Unread::None | Unread::Silent => None,54
Unread::Dot if muted => Some(dot(8.).bg(theme::badge_muted())),54
Unread::Dot if muted => Some(dot(8.).bg(theme::badge_muted())),55
Unread::Dot => Some(dot(8.)),55
Unread::Dot => Some(dot(8.)),56
Unread::Count(count) => Some(count_badge(count, muted)),56
Unread::Count(count) => Some(count_badge(count, muted)),@@ -6,6 +6,7 @@ use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_
6
6
use crate::pins::DEFAULT_REGION;
7
7
8
8
const PAGE_SIZE: usize = 200;
9
const MAX_PAGES: usize = 100;
9
10
const ALERTS_OFF: &str = "false";
10
11
11
12
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -46,9 +47,18 @@ impl<T: MessageTransport> Conversations<T> {
46
47
"{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",
47
48
self.base_url
48
49
);
49
let answer = self.transport.send(Request::get(&url)).await?;
50
ensure_success(&answer)?;
51
mute_states_in_page(&answer.body)
50
let mut states = Vec::new();
51
let mut next_url = Some(url);
52
for _ in 0..MAX_PAGES {
53
let Some(url) = next_url.take() else {
54
break;
55
};
56
let answer = self.transport.send(Request::get(&url)).await?;
57
ensure_success(&answer)?;
58
states.extend(mute_states_in_page(&answer.body)?);
59
next_url = backward_link(&answer.body).filter(|link| *link != url);
60
}
61
Ok(states)
52
62
}
53
63
54
64
pub async fn set_alerts(&self, conversation_id: &str, enabled: bool) -> Result<()> {
@@ -65,6 +75,13 @@ impl<T: MessageTransport> Conversations<T> {
65
75
}
66
76
}
67
77
78
fn backward_link(body: &Value) -> Option<String> {
79
body.pointer("/_metadata/backwardLink")
80
.and_then(Value::as_str)
81
.filter(|link| !link.is_empty())
82
.map(str::to_owned)
83
}
84
68
85
fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {
69
86
let conversations = body
70
87
.get("conversations")
@@ -126,7 +143,6 @@ mod tests {
126
143
{"id": "19:c", "properties": {}},
127
144
{"id": "19:d"},
128
145
],
129
"_metadata": {"backwardLink": "https://example.test/next"},
130
146
}),
131
147
)]);
132
148
let states = Conversations::with_transport(&transport, "emea")
@@ -150,6 +166,46 @@ mod tests {
150
166
);
151
167
}
152
168
169
#[tokio::test]
170
async fn mute_states_follow_the_backward_link_through_every_page() {
171
let transport = canned(vec![
172
(
173
200,
174
json!({
175
"conversations": [{"id": "19:a", "properties": {"alerts": "true"}}],
176
"_metadata": {"backwardLink": "https://example.test/page2"},
177
}),
178
),
179
(
180
200,
181
json!({
182
"conversations": [{"id": "19:old", "properties": {"alerts": "false"}}],
183
"_metadata": {"backwardLink": "https://example.test/page3"},
184
}),
185
),
186
(200, json!({"conversations": [{"id": "19:oldest"}]})),
187
]);
188
let states = Conversations::with_transport(&transport, "emea")
189
.conversation_mute_states()
190
.await
191
.unwrap();
192
assert_eq!(
193
states,
194
vec![
195
("19:a".to_owned(), false),
196
("19:old".to_owned(), true),
197
("19:oldest".to_owned(), false),
198
]
199
);
200
let requests = transport.requests.lock().unwrap();
201
let urls: Vec<&str> = requests
202
.iter()
203
.map(|request| request.url.as_str())
204
.collect();
205
assert_eq!(urls[1], "https://example.test/page2");
206
assert_eq!(urls[2], "https://example.test/page3");
207
}
208
153
209
#[tokio::test]
154
210
async fn mute_states_fail_on_an_error_status() {
155
211
let transport = canned(vec![(500, Value::Null)]);
@@ -6,6 +6,7 @@ use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_6
use crate::pins::DEFAULT_REGION;6
use crate::pins::DEFAULT_REGION;7
7
8
const PAGE_SIZE: usize = 200;8
const PAGE_SIZE: usize = 200;9
const MAX_PAGES: usize = 100;9
const ALERTS_OFF: &str = "false";10
const ALERTS_OFF: &str = "false";10
11
11
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {12
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {@@ -46,9 +47,18 @@ impl<T: MessageTransport> Conversations<T> {46
"{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",47
"{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}",47
self.base_url48
self.base_url48
);49
);49
let answer = self.transport.send(Request::get(&url)).await?;50
let mut states = Vec::new();50
ensure_success(&answer)?;51
let mut next_url = Some(url);51
mute_states_in_page(&answer.body)52
for _ in 0..MAX_PAGES {53
let Some(url) = next_url.take() else {54
break;55
};56
let answer = self.transport.send(Request::get(&url)).await?;57
ensure_success(&answer)?;58
states.extend(mute_states_in_page(&answer.body)?);59
next_url = backward_link(&answer.body).filter(|link| *link != url);60
}61
Ok(states)52
}62
}53
63
54
pub async fn set_alerts(&self, conversation_id: &str, enabled: bool) -> Result<()> {64
pub async fn set_alerts(&self, conversation_id: &str, enabled: bool) -> Result<()> {@@ -65,6 +75,13 @@ impl<T: MessageTransport> Conversations<T> {65
}75
}66
}76
}67
77
78
fn backward_link(body: &Value) -> Option<String> {79
body.pointer("/_metadata/backwardLink")80
.and_then(Value::as_str)81
.filter(|link| !link.is_empty())82
.map(str::to_owned)83
}84
68
fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {85
fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> {69
let conversations = body86
let conversations = body70
.get("conversations")87
.get("conversations")@@ -126,7 +143,6 @@ mod tests {126
{"id": "19:c", "properties": {}},143
{"id": "19:c", "properties": {}},127
{"id": "19:d"},144
{"id": "19:d"},128
],145
],129
"_metadata": {"backwardLink": "https://example.test/next"},130
}),146
}),131
)]);147
)]);132
let states = Conversations::with_transport(&transport, "emea")148
let states = Conversations::with_transport(&transport, "emea")@@ -150,6 +166,46 @@ mod tests {150
);166
);151
}167
}152
168
169
#[tokio::test]170
async fn mute_states_follow_the_backward_link_through_every_page() {171
let transport = canned(vec![172
(173
200,174
json!({175
"conversations": [{"id": "19:a", "properties": {"alerts": "true"}}],176
"_metadata": {"backwardLink": "https://example.test/page2"},177
}),178
),179
(180
200,181
json!({182
"conversations": [{"id": "19:old", "properties": {"alerts": "false"}}],183
"_metadata": {"backwardLink": "https://example.test/page3"},184
}),185
),186
(200, json!({"conversations": [{"id": "19:oldest"}]})),187
]);188
let states = Conversations::with_transport(&transport, "emea")189
.conversation_mute_states()190
.await191
.unwrap();192
assert_eq!(193
states,194
vec![195
("19:a".to_owned(), false),196
("19:old".to_owned(), true),197
("19:oldest".to_owned(), false),198
]199
);200
let requests = transport.requests.lock().unwrap();201
let urls: Vec<&str> = requests202
.iter()203
.map(|request| request.url.as_str())204
.collect();205
assert_eq!(urls[1], "https://example.test/page2");206
assert_eq!(urls[2], "https://example.test/page3");207
}208
153
#[tokio::test]209
#[tokio::test]154
async fn mute_states_fail_on_an_error_status() {210
async fn mute_states_fail_on_an_error_status() {155
let transport = canned(vec![(500, Value::Null)]);211
let transport = canned(vec![(500, Value::Null)]);@@ -13,6 +13,7 @@ pub mod reactions;
13
13
pub mod realtime;
14
14
pub mod receipts;
15
15
pub mod saved;
16
pub mod settings;
16
17
17
18
pub use cards::{
18
19
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
@@ -40,3 +41,4 @@ pub use realtime::{
40
41
};
41
42
pub use receipts::{MemberHorizon, Receipts};
42
43
pub use saved::SavedMessage;
44
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
@@ -13,6 +13,7 @@ pub mod reactions;13
pub mod realtime;13
pub mod realtime;14
pub mod receipts;14
pub mod receipts;15
pub mod saved;15
pub mod saved;16
pub mod settings;16
17
17
pub use cards::{18
pub use cards::{18
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,19
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,@@ -40,3 +41,4 @@ pub use realtime::{40
};41
};41
pub use receipts::{MemberHorizon, Receipts};42
pub use receipts::{MemberHorizon, Receipts};42
pub use saved::SavedMessage;43
pub use saved::SavedMessage;44
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};@@ -6,11 +6,15 @@ use super::chats::{FOLDER_QUERY, NO_OP_CODES, api_error, ensure_success};
6
6
use super::state::error_code;
7
7
use super::transport::CsaTransport;
8
8
use crate::error::{Error, Result};
9
use crate::messages::encode;
9
10
10
11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11
12
pub enum FolderKind {
12
13
Favorites,
13
14
UserCreated,
15
Recent,
16
Meeting,
17
Muted,
14
18
}
15
19
16
20
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -18,6 +22,7 @@ pub struct Folder {
18
22
pub id: String,
19
23
pub name: String,
20
24
pub kind: FolderKind,
25
pub expanded: bool,
21
26
pub conversation_ids: Vec<String>,
22
27
}
23
28
@@ -74,6 +79,9 @@ fn parse_folder(folder: &Value) -> Option<Folder> {
74
79
let kind = match folder.get("folderType").and_then(Value::as_str)? {
75
80
"Favorites" => FolderKind::Favorites,
76
81
"UserCreated" => FolderKind::UserCreated,
82
"RecentChats" => FolderKind::Recent,
83
"MeetingChats" => FolderKind::Meeting,
84
"MutedChats" => FolderKind::Muted,
77
85
_ => return None,
78
86
};
79
87
Some(Folder {
@@ -84,6 +92,10 @@ fn parse_folder(folder: &Value) -> Option<Folder> {
84
92
.unwrap_or_default()
85
93
.to_owned(),
86
94
kind,
95
expanded: folder
96
.get("isExpanded")
97
.and_then(Value::as_bool)
98
.unwrap_or(true),
87
99
conversation_ids: folder
88
100
.get("conversationFolderItems")
89
101
.and_then(Value::as_array)
@@ -98,6 +110,15 @@ fn parse_folder(folder: &Value) -> Option<Folder> {
98
110
})
99
111
}
100
112
113
fn expanded_body(hierarchy_version: i64, expanded: bool) -> Value {
114
json!({
115
"folderHierarchyVersion": hierarchy_version,
116
"supportsAdditionalSystemGeneratedFolders": true,
117
"supportsSliceItems": true,
118
"isExpanded": expanded,
119
})
120
}
121
101
122
fn add_item(folder_id: &str, conversation_id: &str) -> Value {
102
123
json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id})
103
124
}
@@ -165,6 +186,34 @@ impl<T: CsaTransport> Pins<T> {
165
186
.await
166
187
}
167
188
189
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
190
let mut hierarchy_version = self.folders().await?.hierarchy_version;
191
for attempt in 0..2 {
192
let url = format!(
193
"{}/conversationFolders/{}?{FOLDER_QUERY}",
194
self.base_url,
195
encode(folder_id)
196
);
197
let body = expanded_body(hierarchy_version, expanded);
198
let answer = self
199
.transport
200
.send(Request::with_body(Method::Put, url, body))
201
.await?;
202
match answer.status {
203
200..=299 => return Ok(()),
204
412 if attempt == 0 => {
205
hierarchy_version = match parse_folders(&answer.body) {
206
Ok(current) => current.hierarchy_version,
207
Err(_) => self.folders().await?.hierarchy_version,
208
};
209
}
210
412 => return Err(Error::VersionConflict),
211
_ => return Err(api_error(&answer)),
212
}
213
}
214
Err(Error::VersionConflict)
215
}
216
168
217
async fn write_folders(
169
218
&self,
170
219
plan: impl Fn(&Folders) -> Result<Vec<Value>>,
@@ -210,7 +259,7 @@ mod tests {
210
259
use super::*;
211
260
212
261
#[test]
213
fn keeps_favorites_and_user_folders_in_server_order() {
262
fn keeps_folders_in_server_order() {
214
263
let body = json!({
215
264
"folderHierarchyVersion": 5,
216
265
"conversationFolderOrder": ["b", "a", "r"],
@@ -227,8 +276,51 @@ mod tests {
227
276
.iter()
228
277
.map(|folder| folder.id.as_str())
229
278
.collect();
230
assert_eq!(ids, ["b", "a"]);
279
assert_eq!(ids, ["b", "a", "r"]);
231
280
assert_eq!(parsed.folders[1].conversation_ids, ["c1", "c2"]);
232
281
assert_eq!(parsed.folders[0].kind, FolderKind::Favorites);
233
282
}
283
284
#[test]
285
fn keeps_system_folders_with_id_order_and_expanded_state() {
286
let body = json!({
287
"folderHierarchyVersion": 5,
288
"conversationFolderOrder": ["m", "f", "r", "u"],
289
"conversationFolders": [
290
{"id": "r", "folderType": "RecentChats", "isExpanded": true, "conversationFolderItems": []},
291
{"id": "u", "folderType": "MutedChats", "isExpanded": false, "conversationFolderItems": []},
292
{"id": "m", "folderType": "MeetingChats", "conversationFolderItems": []},
293
{"id": "f", "name": "Pins", "folderType": "Favorites", "conversationFolderItems": []},
294
{"id": "q", "folderType": "QuickViews", "conversationFolderItems": []}
295
]
296
});
297
let parsed = parse_folders(&body).unwrap();
298
let summary: Vec<(&str, FolderKind, bool)> = parsed
299
.folders
300
.iter()
301
.map(|folder| (folder.id.as_str(), folder.kind, folder.expanded))
302
.collect();
303
assert_eq!(
304
summary,
305
[
306
("m", FolderKind::Meeting, true),
307
("f", FolderKind::Favorites, true),
308
("r", FolderKind::Recent, true),
309
("u", FolderKind::Muted, false),
310
]
311
);
312
}
313
314
#[test]
315
fn expanded_body_carries_only_the_flag_and_the_lock() {
316
assert_eq!(
317
expanded_body(7, false),
318
json!({
319
"folderHierarchyVersion": 7,
320
"supportsAdditionalSystemGeneratedFolders": true,
321
"supportsSliceItems": true,
322
"isExpanded": false,
323
})
324
);
325
}
234
326
}
@@ -6,11 +6,15 @@ use super::chats::{FOLDER_QUERY, NO_OP_CODES, api_error, ensure_success};6
use super::state::error_code;6
use super::state::error_code;7
use super::transport::CsaTransport;7
use super::transport::CsaTransport;8
use crate::error::{Error, Result};8
use crate::error::{Error, Result};9
use crate::messages::encode;9
10
10
#[derive(Debug, Clone, Copy, PartialEq, Eq)]11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]11
pub enum FolderKind {12
pub enum FolderKind {12
Favorites,13
Favorites,13
UserCreated,14
UserCreated,15
Recent,16
Meeting,17
Muted,14
}18
}15
19
16
#[derive(Debug, Clone, PartialEq, Eq)]20
#[derive(Debug, Clone, PartialEq, Eq)]@@ -18,6 +22,7 @@ pub struct Folder {18
pub id: String,22
pub id: String,19
pub name: String,23
pub name: String,20
pub kind: FolderKind,24
pub kind: FolderKind,25
pub expanded: bool,21
pub conversation_ids: Vec<String>,26
pub conversation_ids: Vec<String>,22
}27
}23
28
@@ -74,6 +79,9 @@ fn parse_folder(folder: &Value) -> Option<Folder> {74
let kind = match folder.get("folderType").and_then(Value::as_str)? {79
let kind = match folder.get("folderType").and_then(Value::as_str)? {75
"Favorites" => FolderKind::Favorites,80
"Favorites" => FolderKind::Favorites,76
"UserCreated" => FolderKind::UserCreated,81
"UserCreated" => FolderKind::UserCreated,82
"RecentChats" => FolderKind::Recent,83
"MeetingChats" => FolderKind::Meeting,84
"MutedChats" => FolderKind::Muted,77
_ => return None,85
_ => return None,78
};86
};79
Some(Folder {87
Some(Folder {@@ -84,6 +92,10 @@ fn parse_folder(folder: &Value) -> Option<Folder> {84
.unwrap_or_default()92
.unwrap_or_default()85
.to_owned(),93
.to_owned(),86
kind,94
kind,95
expanded: folder96
.get("isExpanded")97
.and_then(Value::as_bool)98
.unwrap_or(true),87
conversation_ids: folder99
conversation_ids: folder88
.get("conversationFolderItems")100
.get("conversationFolderItems")89
.and_then(Value::as_array)101
.and_then(Value::as_array)@@ -98,6 +110,15 @@ fn parse_folder(folder: &Value) -> Option<Folder> {98
})110
})99
}111
}100
112
113
fn expanded_body(hierarchy_version: i64, expanded: bool) -> Value {114
json!({115
"folderHierarchyVersion": hierarchy_version,116
"supportsAdditionalSystemGeneratedFolders": true,117
"supportsSliceItems": true,118
"isExpanded": expanded,119
})120
}121
101
fn add_item(folder_id: &str, conversation_id: &str) -> Value {122
fn add_item(folder_id: &str, conversation_id: &str) -> Value {102
json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id})123
json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id})103
}124
}@@ -165,6 +186,34 @@ impl<T: CsaTransport> Pins<T> {165
.await186
.await166
}187
}167
188
189
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {190
let mut hierarchy_version = self.folders().await?.hierarchy_version;191
for attempt in 0..2 {192
let url = format!(193
"{}/conversationFolders/{}?{FOLDER_QUERY}",194
self.base_url,195
encode(folder_id)196
);197
let body = expanded_body(hierarchy_version, expanded);198
let answer = self199
.transport200
.send(Request::with_body(Method::Put, url, body))201
.await?;202
match answer.status {203
200..=299 => return Ok(()),204
412 if attempt == 0 => {205
hierarchy_version = match parse_folders(&answer.body) {206
Ok(current) => current.hierarchy_version,207
Err(_) => self.folders().await?.hierarchy_version,208
};209
}210
412 => return Err(Error::VersionConflict),211
_ => return Err(api_error(&answer)),212
}213
}214
Err(Error::VersionConflict)215
}216
168
async fn write_folders(217
async fn write_folders(169
&self,218
&self,170
plan: impl Fn(&Folders) -> Result<Vec<Value>>,219
plan: impl Fn(&Folders) -> Result<Vec<Value>>,@@ -210,7 +259,7 @@ mod tests {210
use super::*;259
use super::*;211
260
212
#[test]261
#[test]213
fn keeps_favorites_and_user_folders_in_server_order() {262
fn keeps_folders_in_server_order() {214
let body = json!({263
let body = json!({215
"folderHierarchyVersion": 5,264
"folderHierarchyVersion": 5,216
"conversationFolderOrder": ["b", "a", "r"],265
"conversationFolderOrder": ["b", "a", "r"],@@ -227,8 +276,51 @@ mod tests {227
.iter()276
.iter()228
.map(|folder| folder.id.as_str())277
.map(|folder| folder.id.as_str())229
.collect();278
.collect();230
assert_eq!(ids, ["b", "a"]);279
assert_eq!(ids, ["b", "a", "r"]);231
assert_eq!(parsed.folders[1].conversation_ids, ["c1", "c2"]);280
assert_eq!(parsed.folders[1].conversation_ids, ["c1", "c2"]);232
assert_eq!(parsed.folders[0].kind, FolderKind::Favorites);281
assert_eq!(parsed.folders[0].kind, FolderKind::Favorites);233
}282
}283
284
#[test]285
fn keeps_system_folders_with_id_order_and_expanded_state() {286
let body = json!({287
"folderHierarchyVersion": 5,288
"conversationFolderOrder": ["m", "f", "r", "u"],289
"conversationFolders": [290
{"id": "r", "folderType": "RecentChats", "isExpanded": true, "conversationFolderItems": []},291
{"id": "u", "folderType": "MutedChats", "isExpanded": false, "conversationFolderItems": []},292
{"id": "m", "folderType": "MeetingChats", "conversationFolderItems": []},293
{"id": "f", "name": "Pins", "folderType": "Favorites", "conversationFolderItems": []},294
{"id": "q", "folderType": "QuickViews", "conversationFolderItems": []}295
]296
});297
let parsed = parse_folders(&body).unwrap();298
let summary: Vec<(&str, FolderKind, bool)> = parsed299
.folders300
.iter()301
.map(|folder| (folder.id.as_str(), folder.kind, folder.expanded))302
.collect();303
assert_eq!(304
summary,305
[306
("m", FolderKind::Meeting, true),307
("f", FolderKind::Favorites, true),308
("r", FolderKind::Recent, true),309
("u", FolderKind::Muted, false),310
]311
);312
}313
314
#[test]315
fn expanded_body_carries_only_the_flag_and_the_lock() {316
assert_eq!(317
expanded_body(7, false),318
json!({319
"folderHierarchyVersion": 7,320
"supportsAdditionalSystemGeneratedFolders": true,321
"supportsSliceItems": true,322
"isExpanded": false,323
})324
);325
}234
}326
}@@ -0,0 +1,241 @@
1
use serde_json::{Map, Value, json};
2
use session::{Method, Request, Session};
3
4
use crate::error::{Error, Result};
5
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
6
use crate::pins::DEFAULT_REGION;
7
8
const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
11
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
12
const MUTED_DEFAULT: bool = true;
13
const MEETING_DEFAULT: bool = false;
14
15
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
pub enum ChatSection {
17
Muted,
18
Meeting,
19
}
20
21
impl ChatSection {
22
fn field(self) -> &'static str {
23
match self {
24
ChatSection::Muted => MUTED_FIELD,
25
ChatSection::Meeting => MEETING_FIELD,
26
}
27
}
28
}
29
30
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
31
pub struct ChatSectionSettings {
32
pub muted: Option<bool>,
33
pub meeting: Option<bool>,
34
}
35
36
impl ChatSectionSettings {
37
pub fn enabled(&self, section: ChatSection) -> bool {
38
match section {
39
ChatSection::Muted => self.muted.unwrap_or(MUTED_DEFAULT),
40
ChatSection::Meeting => self.meeting.unwrap_or(MEETING_DEFAULT),
41
}
42
}
43
44
pub fn set(&mut self, section: ChatSection, enabled: bool) {
45
match section {
46
ChatSection::Muted => self.muted = Some(enabled),
47
ChatSection::Meeting => self.meeting = Some(enabled),
48
}
49
}
50
}
51
52
pub struct UserSettings<T: MessageTransport = SessionMessageTransport> {
53
transport: T,
54
base_url: String,
55
}
56
57
impl UserSettings<SessionMessageTransport> {
58
pub fn new(session: &Session) -> Self {
59
Self::with_region(session, DEFAULT_REGION)
60
}
61
62
pub fn with_region(session: &Session, region: &str) -> Self {
63
UserSettings::with_transport(SessionMessageTransport::new(session), region)
64
}
65
}
66
67
impl<T: MessageTransport> UserSettings<T> {
68
pub fn with_transport(transport: T, region: &str) -> Self {
69
UserSettings {
70
transport,
71
base_url: format!(
72
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/properties"
73
),
74
}
75
}
76
77
pub async fn chat_sections(&self) -> Result<ChatSectionSettings> {
78
Ok(parse_chat_sections(&self.properties().await?))
79
}
80
81
pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {
82
let properties = self.properties().await?;
83
let merged = merge_chat_section(&properties, section, enabled);
84
let url = format!("{}?name={SETTINGS_KEY}", self.base_url);
85
let body = json!({ SETTINGS_KEY: merged });
86
let answer = self
87
.transport
88
.send(Request::with_body(Method::Put, url, body))
89
.await?;
90
ensure_success(&answer)
91
}
92
93
async fn properties(&self) -> Result<Value> {
94
let answer = self.transport.send(Request::get(&self.base_url)).await?;
95
ensure_success(&answer)?;
96
if answer.body.is_object() {
97
Ok(answer.body)
98
} else {
99
Err(Error::UnexpectedAnswer("no user properties".into()))
100
}
101
}
102
}
103
104
fn stored_settings(properties: &Value) -> Map<String, Value> {
105
properties
106
.get(SETTINGS_KEY)
107
.and_then(Value::as_str)
108
.and_then(|text| serde_json::from_str::<Value>(text).ok())
109
.and_then(|value| value.as_object().cloned())
110
.unwrap_or_default()
111
}
112
113
pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
114
let settings = stored_settings(properties);
115
ChatSectionSettings {
116
muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
117
meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
118
}
119
}
120
121
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
122
let mut settings = stored_settings(properties);
123
settings
124
.entry("id")
125
.or_insert_with(|| Value::String(SETTINGS_ID.to_owned()));
126
settings.insert(section.field().to_owned(), Value::Bool(enabled));
127
Value::Object(settings).to_string()
128
}
129
130
#[cfg(test)]
131
mod tests {
132
use std::collections::VecDeque;
133
use std::sync::Mutex;
134
135
use session::ApiResponse;
136
137
use super::*;
138
139
struct Canned {
140
answers: Mutex<VecDeque<(u16, Value)>>,
141
requests: Mutex<Vec<Request>>,
142
}
143
144
impl MessageTransport for &Canned {
145
async fn send(&self, request: Request) -> Result<ApiResponse> {
146
self.requests.lock().unwrap().push(request);
147
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
148
Ok(ApiResponse {
149
status,
150
body,
151
retry_after: None,
152
})
153
}
154
}
155
156
fn properties(settings: &str) -> Value {
157
json!({"other": "kept", SETTINGS_KEY: settings})
158
}
159
160
#[test]
161
fn unset_fields_use_the_teams_defaults() {
162
let parsed = parse_chat_sections(&json!({}));
163
assert_eq!(parsed, ChatSectionSettings::default());
164
assert!(parsed.enabled(ChatSection::Muted));
165
assert!(!parsed.enabled(ChatSection::Meeting));
166
}
167
168
#[test]
169
fn reads_both_flags_from_the_json_string() {
170
let parsed = parse_chat_sections(&properties(
171
r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true}"#,
172
));
173
assert!(!parsed.enabled(ChatSection::Muted));
174
assert!(parsed.enabled(ChatSection::Meeting));
175
}
176
177
#[test]
178
fn merge_keeps_every_unknown_field_and_the_other_flag() {
179
let existing = properties(
180
r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMeetingChatSection":true,"futureSetting":{"nested":[1,2]},"count":3}"#,
181
);
182
let merged = merge_chat_section(&existing, ChatSection::Muted, false);
183
let value: Value = serde_json::from_str(&merged).unwrap();
184
assert_eq!(
185
value,
186
json!({
187
"id": "simpleCollabUserSettingsId",
188
"hasUserEnabledMeetingChatSection": true,
189
"hasUserEnabledMutedChatSection": false,
190
"futureSetting": {"nested": [1, 2]},
191
"count": 3,
192
})
193
);
194
assert_eq!(
195
parse_chat_sections(&json!({SETTINGS_KEY: merged})),
196
ChatSectionSettings {
197
muted: Some(false),
198
meeting: Some(true)
199
}
200
);
201
}
202
203
#[test]
204
fn merge_without_stored_settings_creates_the_object_with_its_id() {
205
let merged = merge_chat_section(&json!({}), ChatSection::Meeting, true);
206
let value: Value = serde_json::from_str(&merged).unwrap();
207
assert_eq!(
208
value,
209
json!({"id": SETTINGS_ID, "hasUserEnabledMeetingChatSection": true})
210
);
211
}
212
213
#[tokio::test]
214
async fn setting_a_section_reads_then_puts_the_merged_object_as_text() {
215
let transport = Canned {
216
answers: Mutex::new(
217
vec![(200, properties(r#"{"keep":1}"#)), (200, Value::Null)].into(),
218
),
219
requests: Mutex::new(Vec::new()),
220
};
221
UserSettings::with_transport(&transport, "emea")
222
.set_chat_section(ChatSection::Muted, false)
223
.await
224
.unwrap();
225
let requests = transport.requests.lock().unwrap();
226
let base = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties";
227
assert_eq!(requests[0].method, Method::Get);
228
assert_eq!(requests[0].url, base);
229
assert_eq!(requests[1].method, Method::Put);
230
assert_eq!(
231
requests[1].url,
232
format!("{base}?name=simpleCollabUserSettings")
233
);
234
let sent = requests[1].body.as_ref().unwrap()["simpleCollabUserSettings"]
235
.as_str()
236
.unwrap();
237
let value: Value = serde_json::from_str(sent).unwrap();
238
assert_eq!(value["keep"], json!(1));
239
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
240
}
241
}
@@ -0,0 +1,241 @@1
use serde_json::{Map, Value, json};2
use session::{Method, Request, Session};3
4
use crate::error::{Error, Result};5
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};6
use crate::pins::DEFAULT_REGION;7
8
const SETTINGS_KEY: &str = "simpleCollabUserSettings";9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";10
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";11
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";12
const MUTED_DEFAULT: bool = true;13
const MEETING_DEFAULT: bool = false;14
15
#[derive(Debug, Clone, Copy, PartialEq, Eq)]16
pub enum ChatSection {17
Muted,18
Meeting,19
}20
21
impl ChatSection {22
fn field(self) -> &'static str {23
match self {24
ChatSection::Muted => MUTED_FIELD,25
ChatSection::Meeting => MEETING_FIELD,26
}27
}28
}29
30
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]31
pub struct ChatSectionSettings {32
pub muted: Option<bool>,33
pub meeting: Option<bool>,34
}35
36
impl ChatSectionSettings {37
pub fn enabled(&self, section: ChatSection) -> bool {38
match section {39
ChatSection::Muted => self.muted.unwrap_or(MUTED_DEFAULT),40
ChatSection::Meeting => self.meeting.unwrap_or(MEETING_DEFAULT),41
}42
}43
44
pub fn set(&mut self, section: ChatSection, enabled: bool) {45
match section {46
ChatSection::Muted => self.muted = Some(enabled),47
ChatSection::Meeting => self.meeting = Some(enabled),48
}49
}50
}51
52
pub struct UserSettings<T: MessageTransport = SessionMessageTransport> {53
transport: T,54
base_url: String,55
}56
57
impl UserSettings<SessionMessageTransport> {58
pub fn new(session: &Session) -> Self {59
Self::with_region(session, DEFAULT_REGION)60
}61
62
pub fn with_region(session: &Session, region: &str) -> Self {63
UserSettings::with_transport(SessionMessageTransport::new(session), region)64
}65
}66
67
impl<T: MessageTransport> UserSettings<T> {68
pub fn with_transport(transport: T, region: &str) -> Self {69
UserSettings {70
transport,71
base_url: format!(72
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/properties"73
),74
}75
}76
77
pub async fn chat_sections(&self) -> Result<ChatSectionSettings> {78
Ok(parse_chat_sections(&self.properties().await?))79
}80
81
pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {82
let properties = self.properties().await?;83
let merged = merge_chat_section(&properties, section, enabled);84
let url = format!("{}?name={SETTINGS_KEY}", self.base_url);85
let body = json!({ SETTINGS_KEY: merged });86
let answer = self87
.transport88
.send(Request::with_body(Method::Put, url, body))89
.await?;90
ensure_success(&answer)91
}92
93
async fn properties(&self) -> Result<Value> {94
let answer = self.transport.send(Request::get(&self.base_url)).await?;95
ensure_success(&answer)?;96
if answer.body.is_object() {97
Ok(answer.body)98
} else {99
Err(Error::UnexpectedAnswer("no user properties".into()))100
}101
}102
}103
104
fn stored_settings(properties: &Value) -> Map<String, Value> {105
properties106
.get(SETTINGS_KEY)107
.and_then(Value::as_str)108
.and_then(|text| serde_json::from_str::<Value>(text).ok())109
.and_then(|value| value.as_object().cloned())110
.unwrap_or_default()111
}112
113
pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {114
let settings = stored_settings(properties);115
ChatSectionSettings {116
muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),117
meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),118
}119
}120
121
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {122
let mut settings = stored_settings(properties);123
settings124
.entry("id")125
.or_insert_with(|| Value::String(SETTINGS_ID.to_owned()));126
settings.insert(section.field().to_owned(), Value::Bool(enabled));127
Value::Object(settings).to_string()128
}129
130
#[cfg(test)]131
mod tests {132
use std::collections::VecDeque;133
use std::sync::Mutex;134
135
use session::ApiResponse;136
137
use super::*;138
139
struct Canned {140
answers: Mutex<VecDeque<(u16, Value)>>,141
requests: Mutex<Vec<Request>>,142
}143
144
impl MessageTransport for &Canned {145
async fn send(&self, request: Request) -> Result<ApiResponse> {146
self.requests.lock().unwrap().push(request);147
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");148
Ok(ApiResponse {149
status,150
body,151
retry_after: None,152
})153
}154
}155
156
fn properties(settings: &str) -> Value {157
json!({"other": "kept", SETTINGS_KEY: settings})158
}159
160
#[test]161
fn unset_fields_use_the_teams_defaults() {162
let parsed = parse_chat_sections(&json!({}));163
assert_eq!(parsed, ChatSectionSettings::default());164
assert!(parsed.enabled(ChatSection::Muted));165
assert!(!parsed.enabled(ChatSection::Meeting));166
}167
168
#[test]169
fn reads_both_flags_from_the_json_string() {170
let parsed = parse_chat_sections(&properties(171
r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true}"#,172
));173
assert!(!parsed.enabled(ChatSection::Muted));174
assert!(parsed.enabled(ChatSection::Meeting));175
}176
177
#[test]178
fn merge_keeps_every_unknown_field_and_the_other_flag() {179
let existing = properties(180
r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMeetingChatSection":true,"futureSetting":{"nested":[1,2]},"count":3}"#,181
);182
let merged = merge_chat_section(&existing, ChatSection::Muted, false);183
let value: Value = serde_json::from_str(&merged).unwrap();184
assert_eq!(185
value,186
json!({187
"id": "simpleCollabUserSettingsId",188
"hasUserEnabledMeetingChatSection": true,189
"hasUserEnabledMutedChatSection": false,190
"futureSetting": {"nested": [1, 2]},191
"count": 3,192
})193
);194
assert_eq!(195
parse_chat_sections(&json!({SETTINGS_KEY: merged})),196
ChatSectionSettings {197
muted: Some(false),198
meeting: Some(true)199
}200
);201
}202
203
#[test]204
fn merge_without_stored_settings_creates_the_object_with_its_id() {205
let merged = merge_chat_section(&json!({}), ChatSection::Meeting, true);206
let value: Value = serde_json::from_str(&merged).unwrap();207
assert_eq!(208
value,209
json!({"id": SETTINGS_ID, "hasUserEnabledMeetingChatSection": true})210
);211
}212
213
#[tokio::test]214
async fn setting_a_section_reads_then_puts_the_merged_object_as_text() {215
let transport = Canned {216
answers: Mutex::new(217
vec![(200, properties(r#"{"keep":1}"#)), (200, Value::Null)].into(),218
),219
requests: Mutex::new(Vec::new()),220
};221
UserSettings::with_transport(&transport, "emea")222
.set_chat_section(ChatSection::Muted, false)223
.await224
.unwrap();225
let requests = transport.requests.lock().unwrap();226
let base = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties";227
assert_eq!(requests[0].method, Method::Get);228
assert_eq!(requests[0].url, base);229
assert_eq!(requests[1].method, Method::Put);230
assert_eq!(231
requests[1].url,232
format!("{base}?name=simpleCollabUserSettings")233
);234
let sent = requests[1].body.as_ref().unwrap()["simpleCollabUserSettings"]235
.as_str()236
.unwrap();237
let value: Value = serde_json::from_str(sent).unwrap();238
assert_eq!(value["keep"], json!(1));239
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));240
}241
}@@ -460,3 +460,60 @@ async fn remove_from_folder_sends_remove_item_and_skips_when_absent() {
460
460
pins(&idle).remove_from_folder("c", "t~u~A").await.unwrap();
461
461
assert_eq!(sent(&idle).len(), 1);
462
462
}
463
464
#[tokio::test]
465
async fn collapse_puts_only_the_flag_and_the_lock_on_the_folder_url() {
466
let mock = Mock::new(vec![(200, folders(10, &[])), (200, json!({}))]);
467
pins(&mock)
468
.set_folder_expanded("t~u~MutedChats", false)
469
.await
470
.unwrap();
471
let requests = sent(&mock);
472
assert_eq!(requests[1].0, "PUT");
473
assert_eq!(
474
requests[1].1,
475
"https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me/conversationFolders/t~u~MutedChats?supportsAdditionalSystemGeneratedFolders=true&supportsSliceItems=true"
476
);
477
assert_eq!(
478
requests[1].2,
479
Some(json!({
480
"folderHierarchyVersion": 10,
481
"supportsAdditionalSystemGeneratedFolders": true,
482
"supportsSliceItems": true,
483
"isExpanded": false,
484
}))
485
);
486
}
487
488
#[tokio::test]
489
async fn collapse_retries_once_with_the_version_from_the_412_body() {
490
let mock = Mock::new(vec![
491
(200, folders(10, &[])),
492
(412, folders(15, &[])),
493
(200, json!({})),
494
]);
495
pins(&mock)
496
.set_folder_expanded("t~u~MutedChats", true)
497
.await
498
.unwrap();
499
let requests = sent(&mock);
500
assert_eq!(requests.len(), 3);
501
assert_eq!(
502
requests[2].2.as_ref().unwrap()["folderHierarchyVersion"],
503
15
504
);
505
assert_eq!(requests[2].2.as_ref().unwrap()["isExpanded"], true);
506
}
507
508
#[tokio::test]
509
async fn collapse_gives_up_after_a_second_version_mismatch() {
510
let mock = Mock::new(vec![
511
(200, folders(10, &[])),
512
(412, folders(11, &[])),
513
(412, folders(12, &[])),
514
]);
515
let outcome = pins(&mock)
516
.set_folder_expanded("t~u~MutedChats", true)
517
.await;
518
assert!(matches!(outcome, Err(Error::VersionConflict)));
519
}
@@ -460,3 +460,60 @@ async fn remove_from_folder_sends_remove_item_and_skips_when_absent() {460
pins(&idle).remove_from_folder("c", "t~u~A").await.unwrap();460
pins(&idle).remove_from_folder("c", "t~u~A").await.unwrap();461
assert_eq!(sent(&idle).len(), 1);461
assert_eq!(sent(&idle).len(), 1);462
}462
}463
464
#[tokio::test]465
async fn collapse_puts_only_the_flag_and_the_lock_on_the_folder_url() {466
let mock = Mock::new(vec![(200, folders(10, &[])), (200, json!({}))]);467
pins(&mock)468
.set_folder_expanded("t~u~MutedChats", false)469
.await470
.unwrap();471
let requests = sent(&mock);472
assert_eq!(requests[1].0, "PUT");473
assert_eq!(474
requests[1].1,475
"https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me/conversationFolders/t~u~MutedChats?supportsAdditionalSystemGeneratedFolders=true&supportsSliceItems=true"476
);477
assert_eq!(478
requests[1].2,479
Some(json!({480
"folderHierarchyVersion": 10,481
"supportsAdditionalSystemGeneratedFolders": true,482
"supportsSliceItems": true,483
"isExpanded": false,484
}))485
);486
}487
488
#[tokio::test]489
async fn collapse_retries_once_with_the_version_from_the_412_body() {490
let mock = Mock::new(vec![491
(200, folders(10, &[])),492
(412, folders(15, &[])),493
(200, json!({})),494
]);495
pins(&mock)496
.set_folder_expanded("t~u~MutedChats", true)497
.await498
.unwrap();499
let requests = sent(&mock);500
assert_eq!(requests.len(), 3);501
assert_eq!(502
requests[2].2.as_ref().unwrap()["folderHierarchyVersion"],503
15504
);505
assert_eq!(requests[2].2.as_ref().unwrap()["isExpanded"], true);506
}507
508
#[tokio::test]509
async fn collapse_gives_up_after_a_second_version_mismatch() {510
let mock = Mock::new(vec![511
(200, folders(10, &[])),512
(412, folders(11, &[])),513
(412, folders(12, &[])),514
]);515
let outcome = pins(&mock)516
.set_folder_expanded("t~u~MutedChats", true)517
.await;518
assert!(matches!(outcome, Err(Error::VersionConflict)));519
}@@ -2,10 +2,10 @@ use std::future::Future;
2
2
use std::pin::Pin;
3
3
use std::sync::Arc;
4
4
5
use chatsvc::{Pins, pins::SessionTransport};
6
use session::Session;
5
use chatsvc::{ChatSection, ChatSectionSettings, Pins, UserSettings, pins::SessionTransport};
7
6
use chrono::Utc;
8
use store::{ChannelLayoutRecord, FolderRecord, TeamLayoutRecord};
7
use session::Session;
8
use store::{ChannelLayoutRecord, FolderRecord, Store, TeamLayoutRecord};
9
9
10
10
use crate::engine::SyncEngine;
11
11
use crate::error::{Error, Result};
@@ -18,6 +18,9 @@ pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
18
18
pub enum FolderKind {
19
19
Favorites,
20
20
UserCreated,
21
Recent,
22
Meeting,
23
Muted,
21
24
}
22
25
23
26
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -25,6 +28,7 @@ pub struct ChatFolder {
25
28
pub id: String,
26
29
pub name: String,
27
30
pub kind: FolderKind,
31
pub expanded: bool,
28
32
pub conversation_ids: Vec<String>,
29
33
}
30
34
@@ -32,6 +36,14 @@ pub trait FolderSource: Send + Sync {
32
36
fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
33
37
fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>>;
34
38
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>>;
39
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>>;
40
fn set_section_enabled(&self, section: ChatSection, enabled: bool)
41
-> BoxFuture<'_, Result<()>>;
42
fn set_folder_expanded<'a>(
43
&'a self,
44
folder_id: &'a str,
45
expanded: bool,
46
) -> BoxFuture<'a, Result<()>>;
35
47
fn move_to_folder<'a>(
36
48
&'a self,
37
49
conversation_id: &'a str,
@@ -46,12 +58,14 @@ pub trait FolderSource: Send + Sync {
46
58
47
59
pub struct ChatsvcFolderSource {
48
60
pins: Pins<SessionTransport>,
61
settings: UserSettings,
49
62
}
50
63
51
64
impl ChatsvcFolderSource {
52
65
pub fn new(session: &Session) -> Self {
53
66
ChatsvcFolderSource {
54
67
pins: Pins::new(session),
68
settings: UserSettings::new(session),
55
69
}
56
70
}
57
71
}
@@ -77,6 +91,26 @@ impl FolderSource for ChatsvcFolderSource {
77
91
})
78
92
}
79
93
94
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {
95
Box::pin(async { Ok(self.settings.chat_sections().await?) })
96
}
97
98
fn set_section_enabled(
99
&self,
100
section: ChatSection,
101
enabled: bool,
102
) -> BoxFuture<'_, Result<()>> {
103
Box::pin(async move { Ok(self.settings.set_chat_section(section, enabled).await?) })
104
}
105
106
fn set_folder_expanded<'a>(
107
&'a self,
108
folder_id: &'a str,
109
expanded: bool,
110
) -> BoxFuture<'a, Result<()>> {
111
Box::pin(async move { Ok(self.pins.set_folder_expanded(folder_id, expanded).await?) })
112
}
113
80
114
fn move_to_folder<'a>(
81
115
&'a self,
82
116
conversation_id: &'a str,
@@ -116,7 +150,11 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
116
150
kind: match folder.kind {
117
151
chatsvc::FolderKind::Favorites => FolderKind::Favorites,
118
152
chatsvc::FolderKind::UserCreated => FolderKind::UserCreated,
153
chatsvc::FolderKind::Recent => FolderKind::Recent,
154
chatsvc::FolderKind::Meeting => FolderKind::Meeting,
155
chatsvc::FolderKind::Muted => FolderKind::Muted,
119
156
},
157
expanded: folder.expanded,
120
158
conversation_ids: folder.conversation_ids,
121
159
})
122
160
.collect()
@@ -141,6 +179,11 @@ fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {
141
179
const META_TEAM_LAYOUT_AT: &str = "team_layout_refreshed_at";
142
180
const KIND_FAVORITES: &str = "Favorites";
143
181
const KIND_USER_CREATED: &str = "UserCreated";
182
const KIND_RECENT: &str = "RecentChats";
183
const KIND_MEETING: &str = "MeetingChats";
184
const KIND_MUTED: &str = "MutedChats";
185
const META_MUTED_SECTION: &str = "chat_section_muted";
186
const META_MEETING_SECTION: &str = "chat_section_meeting";
144
187
145
188
fn to_record(folder: &ChatFolder) -> FolderRecord {
146
189
FolderRecord {
@@ -149,8 +192,12 @@ fn to_record(folder: &ChatFolder) -> FolderRecord {
149
192
kind: match folder.kind {
150
193
FolderKind::Favorites => KIND_FAVORITES,
151
194
FolderKind::UserCreated => KIND_USER_CREATED,
195
FolderKind::Recent => KIND_RECENT,
196
FolderKind::Meeting => KIND_MEETING,
197
FolderKind::Muted => KIND_MUTED,
152
198
}
153
199
.to_owned(),
200
expanded: folder.expanded,
154
201
conversation_ids: folder.conversation_ids.clone(),
155
202
}
156
203
}
@@ -159,15 +206,43 @@ fn from_record(record: FolderRecord) -> ChatFolder {
159
206
ChatFolder {
160
207
id: record.id,
161
208
name: record.name,
162
kind: if record.kind == KIND_FAVORITES {
163
FolderKind::Favorites
164
} else {
165
FolderKind::UserCreated
209
kind: match record.kind.as_str() {
210
KIND_FAVORITES => FolderKind::Favorites,
211
KIND_RECENT => FolderKind::Recent,
212
KIND_MEETING => FolderKind::Meeting,
213
KIND_MUTED => FolderKind::Muted,
214
_ => FolderKind::UserCreated,
166
215
},
216
expanded: record.expanded,
167
217
conversation_ids: record.conversation_ids,
168
218
}
169
219
}
170
220
221
pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {
222
let read = |key: &str| {
223
store
224
.meta(key)
225
.ok()
226
.flatten()
227
.and_then(|value| value.parse().ok())
228
};
229
ChatSectionSettings {
230
muted: read(META_MUTED_SECTION),
231
meeting: read(META_MEETING_SECTION),
232
}
233
}
234
235
pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) -> Result<()> {
236
for (key, value) in [
237
(META_MUTED_SECTION, settings.muted),
238
(META_MEETING_SECTION, settings.meeting),
239
] {
240
let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
241
store.set_meta(key, &text)?;
242
}
243
Ok(())
244
}
245
171
246
impl<R: Remote> SyncEngine<R> {
172
247
pub fn with_folder_source(mut self, source: Arc<dyn FolderSource>) -> Self {
173
248
self.folder_source = Some(source);
@@ -186,9 +261,40 @@ impl<R: Remote> SyncEngine<R> {
186
261
let source = self.folder_source()?;
187
262
let (folders, channels) = tokio::try_join!(source.folders(), source.pinned_channels())?;
188
263
self.store_folders(&folders, &channels)?;
264
self.refresh_section_settings(source).await;
189
265
self.refresh_team_layout(source).await
190
266
}
191
267
268
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
269
let outcome = match source.section_settings().await {
270
Ok(settings) => self.apply_section_settings(&settings),
271
Err(error) => Err(error),
272
};
273
if let Err(error) = outcome {
274
self.report(format!("cannot refresh chat list settings: {error}"));
275
}
276
}
277
278
fn apply_section_settings(&self, settings: &ChatSectionSettings) -> Result<()> {
279
if stored_section_settings(&self.store) != *settings {
280
store_section_settings(&self.store, settings)?;
281
let _ = self.events.send(CoreEvent::FoldersChanged);
282
}
283
Ok(())
284
}
285
286
pub async fn set_section_enabled(&self, section: ChatSection, enabled: bool) -> Result<()> {
287
self.folder_source()?
288
.set_section_enabled(section, enabled)
289
.await
290
}
291
292
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
293
self.folder_source()?
294
.set_folder_expanded(folder_id, expanded)
295
.await
296
}
297
192
298
async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> {
193
299
let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;
194
300
if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) {
@@ -2,10 +2,10 @@ use std::future::Future;2
use std::pin::Pin;2
use std::pin::Pin;3
use std::sync::Arc;3
use std::sync::Arc;4
4
5
use chatsvc::{Pins, pins::SessionTransport};5
use chatsvc::{ChatSection, ChatSectionSettings, Pins, UserSettings, pins::SessionTransport};6
use session::Session;7
use chrono::Utc;6
use chrono::Utc;8
use store::{ChannelLayoutRecord, FolderRecord, TeamLayoutRecord};7
use session::Session;8
use store::{ChannelLayoutRecord, FolderRecord, Store, TeamLayoutRecord};9
9
10
use crate::engine::SyncEngine;10
use crate::engine::SyncEngine;11
use crate::error::{Error, Result};11
use crate::error::{Error, Result};@@ -18,6 +18,9 @@ pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;18
pub enum FolderKind {18
pub enum FolderKind {19
Favorites,19
Favorites,20
UserCreated,20
UserCreated,21
Recent,22
Meeting,23
Muted,21
}24
}22
25
23
#[derive(Debug, Clone, PartialEq, Eq)]26
#[derive(Debug, Clone, PartialEq, Eq)]@@ -25,6 +28,7 @@ pub struct ChatFolder {25
pub id: String,28
pub id: String,26
pub name: String,29
pub name: String,27
pub kind: FolderKind,30
pub kind: FolderKind,31
pub expanded: bool,28
pub conversation_ids: Vec<String>,32
pub conversation_ids: Vec<String>,29
}33
}30
34
@@ -32,6 +36,14 @@ pub trait FolderSource: Send + Sync {32
fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;36
fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;33
fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>>;37
fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>>;34
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>>;38
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>>;39
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>>;40
fn set_section_enabled(&self, section: ChatSection, enabled: bool)41
-> BoxFuture<'_, Result<()>>;42
fn set_folder_expanded<'a>(43
&'a self,44
folder_id: &'a str,45
expanded: bool,46
) -> BoxFuture<'a, Result<()>>;35
fn move_to_folder<'a>(47
fn move_to_folder<'a>(36
&'a self,48
&'a self,37
conversation_id: &'a str,49
conversation_id: &'a str,@@ -46,12 +58,14 @@ pub trait FolderSource: Send + Sync {46
58
47
pub struct ChatsvcFolderSource {59
pub struct ChatsvcFolderSource {48
pins: Pins<SessionTransport>,60
pins: Pins<SessionTransport>,61
settings: UserSettings,49
}62
}50
63
51
impl ChatsvcFolderSource {64
impl ChatsvcFolderSource {52
pub fn new(session: &Session) -> Self {65
pub fn new(session: &Session) -> Self {53
ChatsvcFolderSource {66
ChatsvcFolderSource {54
pins: Pins::new(session),67
pins: Pins::new(session),68
settings: UserSettings::new(session),55
}69
}56
}70
}57
}71
}@@ -77,6 +91,26 @@ impl FolderSource for ChatsvcFolderSource {77
})91
})78
}92
}79
93
94
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {95
Box::pin(async { Ok(self.settings.chat_sections().await?) })96
}97
98
fn set_section_enabled(99
&self,100
section: ChatSection,101
enabled: bool,102
) -> BoxFuture<'_, Result<()>> {103
Box::pin(async move { Ok(self.settings.set_chat_section(section, enabled).await?) })104
}105
106
fn set_folder_expanded<'a>(107
&'a self,108
folder_id: &'a str,109
expanded: bool,110
) -> BoxFuture<'a, Result<()>> {111
Box::pin(async move { Ok(self.pins.set_folder_expanded(folder_id, expanded).await?) })112
}113
80
fn move_to_folder<'a>(114
fn move_to_folder<'a>(81
&'a self,115
&'a self,82
conversation_id: &'a str,116
conversation_id: &'a str,@@ -116,7 +150,11 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {116
kind: match folder.kind {150
kind: match folder.kind {117
chatsvc::FolderKind::Favorites => FolderKind::Favorites,151
chatsvc::FolderKind::Favorites => FolderKind::Favorites,118
chatsvc::FolderKind::UserCreated => FolderKind::UserCreated,152
chatsvc::FolderKind::UserCreated => FolderKind::UserCreated,153
chatsvc::FolderKind::Recent => FolderKind::Recent,154
chatsvc::FolderKind::Meeting => FolderKind::Meeting,155
chatsvc::FolderKind::Muted => FolderKind::Muted,119
},156
},157
expanded: folder.expanded,120
conversation_ids: folder.conversation_ids,158
conversation_ids: folder.conversation_ids,121
})159
})122
.collect()160
.collect()@@ -141,6 +179,11 @@ fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {141
const META_TEAM_LAYOUT_AT: &str = "team_layout_refreshed_at";179
const META_TEAM_LAYOUT_AT: &str = "team_layout_refreshed_at";142
const KIND_FAVORITES: &str = "Favorites";180
const KIND_FAVORITES: &str = "Favorites";143
const KIND_USER_CREATED: &str = "UserCreated";181
const KIND_USER_CREATED: &str = "UserCreated";182
const KIND_RECENT: &str = "RecentChats";183
const KIND_MEETING: &str = "MeetingChats";184
const KIND_MUTED: &str = "MutedChats";185
const META_MUTED_SECTION: &str = "chat_section_muted";186
const META_MEETING_SECTION: &str = "chat_section_meeting";144
187
145
fn to_record(folder: &ChatFolder) -> FolderRecord {188
fn to_record(folder: &ChatFolder) -> FolderRecord {146
FolderRecord {189
FolderRecord {@@ -149,8 +192,12 @@ fn to_record(folder: &ChatFolder) -> FolderRecord {149
kind: match folder.kind {192
kind: match folder.kind {150
FolderKind::Favorites => KIND_FAVORITES,193
FolderKind::Favorites => KIND_FAVORITES,151
FolderKind::UserCreated => KIND_USER_CREATED,194
FolderKind::UserCreated => KIND_USER_CREATED,195
FolderKind::Recent => KIND_RECENT,196
FolderKind::Meeting => KIND_MEETING,197
FolderKind::Muted => KIND_MUTED,152
}198
}153
.to_owned(),199
.to_owned(),200
expanded: folder.expanded,154
conversation_ids: folder.conversation_ids.clone(),201
conversation_ids: folder.conversation_ids.clone(),155
}202
}156
}203
}@@ -159,15 +206,43 @@ fn from_record(record: FolderRecord) -> ChatFolder {159
ChatFolder {206
ChatFolder {160
id: record.id,207
id: record.id,161
name: record.name,208
name: record.name,162
kind: if record.kind == KIND_FAVORITES {209
kind: match record.kind.as_str() {163
FolderKind::Favorites210
KIND_FAVORITES => FolderKind::Favorites,164
} else {211
KIND_RECENT => FolderKind::Recent,165
FolderKind::UserCreated212
KIND_MEETING => FolderKind::Meeting,213
KIND_MUTED => FolderKind::Muted,214
_ => FolderKind::UserCreated,166
},215
},216
expanded: record.expanded,167
conversation_ids: record.conversation_ids,217
conversation_ids: record.conversation_ids,168
}218
}169
}219
}170
220
221
pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {222
let read = |key: &str| {223
store224
.meta(key)225
.ok()226
.flatten()227
.and_then(|value| value.parse().ok())228
};229
ChatSectionSettings {230
muted: read(META_MUTED_SECTION),231
meeting: read(META_MEETING_SECTION),232
}233
}234
235
pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) -> Result<()> {236
for (key, value) in [237
(META_MUTED_SECTION, settings.muted),238
(META_MEETING_SECTION, settings.meeting),239
] {240
let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();241
store.set_meta(key, &text)?;242
}243
Ok(())244
}245
171
impl<R: Remote> SyncEngine<R> {246
impl<R: Remote> SyncEngine<R> {172
pub fn with_folder_source(mut self, source: Arc<dyn FolderSource>) -> Self {247
pub fn with_folder_source(mut self, source: Arc<dyn FolderSource>) -> Self {173
self.folder_source = Some(source);248
self.folder_source = Some(source);@@ -186,9 +261,40 @@ impl<R: Remote> SyncEngine<R> {186
let source = self.folder_source()?;261
let source = self.folder_source()?;187
let (folders, channels) = tokio::try_join!(source.folders(), source.pinned_channels())?;262
let (folders, channels) = tokio::try_join!(source.folders(), source.pinned_channels())?;188
self.store_folders(&folders, &channels)?;263
self.store_folders(&folders, &channels)?;264
self.refresh_section_settings(source).await;189
self.refresh_team_layout(source).await265
self.refresh_team_layout(source).await190
}266
}191
267
268
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {269
let outcome = match source.section_settings().await {270
Ok(settings) => self.apply_section_settings(&settings),271
Err(error) => Err(error),272
};273
if let Err(error) = outcome {274
self.report(format!("cannot refresh chat list settings: {error}"));275
}276
}277
278
fn apply_section_settings(&self, settings: &ChatSectionSettings) -> Result<()> {279
if stored_section_settings(&self.store) != *settings {280
store_section_settings(&self.store, settings)?;281
let _ = self.events.send(CoreEvent::FoldersChanged);282
}283
Ok(())284
}285
286
pub async fn set_section_enabled(&self, section: ChatSection, enabled: bool) -> Result<()> {287
self.folder_source()?288
.set_section_enabled(section, enabled)289
.await290
}291
292
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {293
self.folder_source()?294
.set_folder_expanded(folder_id, expanded)295
.await296
}297
192
async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> {298
async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> {193
let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;299
let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;194
if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) {300
if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) {@@ -75,6 +75,7 @@ pub use chatsvc::{
75
75
ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,
76
76
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,
77
77
};
78
pub use chatsvc::{ChatSection, ChatSectionSettings};
78
79
pub use draft::{
79
80
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
80
81
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -83,7 +84,10 @@ pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
83
84
pub use error::{Error, Result};
84
85
pub use events::CoreEvent;
85
86
pub use external_image::external_image_url;
86
pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
87
pub use folders::{
88
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource, store_section_settings,
89
stored_section_settings,
90
};
87
91
pub use graph::{
88
92
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
89
93
UploadedFile,
@@ -75,6 +75,7 @@ pub use chatsvc::{75
ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,75
ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,76
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,76
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,77
};77
};78
pub use chatsvc::{ChatSection, ChatSectionSettings};78
pub use draft::{79
pub use draft::{79
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,80
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,80
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,81
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,@@ -83,7 +84,10 @@ pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};83
pub use error::{Error, Result};84
pub use error::{Error, Result};84
pub use events::CoreEvent;85
pub use events::CoreEvent;85
pub use external_image::external_image_url;86
pub use external_image::external_image_url;86
pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};87
pub use folders::{88
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource, store_section_settings,89
stored_section_settings,90
};87
pub use graph::{91
pub use graph::{88
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,92
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,89
UploadedFile,93
UploadedFile,@@ -10,9 +10,9 @@ use graph::{
10
10
use serde_json::json;
11
11
use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
12
12
use teams_core::{
13
Availability, BoxFuture, ChatFolder, ChatsPage, CoreEvent, DeltaPage, Error, FolderKind,
14
FolderSource, MentionCandidate, MentionInput, MentionTarget, PersonSource, Remote, RemotePage,
15
Result, SyncConfig, SyncEngine,
13
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,
14
DeltaPage, Error, FolderKind, FolderSource, MentionCandidate, MentionInput, MentionTarget,
15
PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,
16
16
};
17
17
18
18
const ME: &str = "user-me";
@@ -2142,6 +2142,7 @@ struct FakeFolders {
2142
2142
state: Mutex<Vec<ChatFolder>>,
2143
2143
channels: Vec<String>,
2144
2144
layout: Vec<TeamLayoutRecord>,
2145
settings: ChatSectionSettings,
2145
2146
calls: Mutex<Vec<String>>,
2146
2147
}
2147
2148
@@ -2151,6 +2152,7 @@ impl FakeFolders {
2151
2152
id: id.to_owned(),
2152
2153
name: id.to_owned(),
2153
2154
kind,
2155
expanded: true,
2154
2156
conversation_ids: ids(items),
2155
2157
};
2156
2158
Arc::new(FakeFolders {
@@ -2160,6 +2162,7 @@ impl FakeFolders {
2160
2162
]),
2161
2163
channels: ids(&["ch1", "ch2"]),
2162
2164
layout: Vec::new(),
2165
settings: ChatSectionSettings::default(),
2163
2166
calls: Mutex::new(Vec::new()),
2164
2167
})
2165
2168
}
@@ -2178,6 +2181,38 @@ impl FolderSource for FakeFolders {
2178
2181
Box::pin(async { Ok(self.layout.clone()) })
2179
2182
}
2180
2183
2184
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {
2185
Box::pin(async { Ok(self.settings) })
2186
}
2187
2188
fn set_section_enabled(
2189
&self,
2190
section: ChatSection,
2191
enabled: bool,
2192
) -> BoxFuture<'_, Result<()>> {
2193
Box::pin(async move {
2194
self.calls
2195
.lock()
2196
.unwrap()
2197
.push(format!("section {section:?} {enabled}"));
2198
Ok(())
2199
})
2200
}
2201
2202
fn set_folder_expanded<'a>(
2203
&'a self,
2204
folder_id: &'a str,
2205
expanded: bool,
2206
) -> BoxFuture<'a, Result<()>> {
2207
Box::pin(async move {
2208
self.calls
2209
.lock()
2210
.unwrap()
2211
.push(format!("expanded {folder_id} {expanded}"));
2212
Ok(())
2213
})
2214
}
2215
2181
2216
fn move_to_folder<'a>(
2182
2217
&'a self,
2183
2218
conversation_id: &'a str,
@@ -2265,6 +2300,38 @@ async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() {
2265
2300
);
2266
2301
}
2267
2302
2303
#[tokio::test]
2304
async fn collapse_and_section_settings_go_through_the_source() {
2305
let fake = Arc::new(Fake::default());
2306
let mut source = FakeFolders::new();
2307
Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {
2308
muted: Some(false),
2309
meeting: Some(true),
2310
};
2311
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
2312
let mut events = engine.subscribe();
2313
engine.refresh_folders().await.unwrap();
2314
assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
2315
assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
2316
assert_eq!(
2317
teams_core::stored_section_settings(engine.store()),
2318
ChatSectionSettings {
2319
muted: Some(false),
2320
meeting: Some(true),
2321
}
2322
);
2323
2324
engine.set_folder_expanded("work", false).await.unwrap();
2325
engine
2326
.set_section_enabled(ChatSection::Meeting, false)
2327
.await
2328
.unwrap();
2329
assert_eq!(
2330
*source.calls.lock().unwrap(),
2331
["expanded work false", "section Meeting false"]
2332
);
2333
}
2334
2268
2335
#[tokio::test]
2269
2336
async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2270
2337
let fake = Arc::new(Fake::default());
@@ -10,9 +10,9 @@ use graph::{10
use serde_json::json;10
use serde_json::json;11
use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};11
use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};12
use teams_core::{12
use teams_core::{13
Availability, BoxFuture, ChatFolder, ChatsPage, CoreEvent, DeltaPage, Error, FolderKind,13
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,14
FolderSource, MentionCandidate, MentionInput, MentionTarget, PersonSource, Remote, RemotePage,14
DeltaPage, Error, FolderKind, FolderSource, MentionCandidate, MentionInput, MentionTarget,15
Result, SyncConfig, SyncEngine,15
PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,16
};16
};17
17
18
const ME: &str = "user-me";18
const ME: &str = "user-me";@@ -2142,6 +2142,7 @@ struct FakeFolders {2142
state: Mutex<Vec<ChatFolder>>,2142
state: Mutex<Vec<ChatFolder>>,2143
channels: Vec<String>,2143
channels: Vec<String>,2144
layout: Vec<TeamLayoutRecord>,2144
layout: Vec<TeamLayoutRecord>,2145
settings: ChatSectionSettings,2145
calls: Mutex<Vec<String>>,2146
calls: Mutex<Vec<String>>,2146
}2147
}2147
2148
@@ -2151,6 +2152,7 @@ impl FakeFolders {2151
id: id.to_owned(),2152
id: id.to_owned(),2152
name: id.to_owned(),2153
name: id.to_owned(),2153
kind,2154
kind,2155
expanded: true,2154
conversation_ids: ids(items),2156
conversation_ids: ids(items),2155
};2157
};2156
Arc::new(FakeFolders {2158
Arc::new(FakeFolders {@@ -2160,6 +2162,7 @@ impl FakeFolders {2160
]),2162
]),2161
channels: ids(&["ch1", "ch2"]),2163
channels: ids(&["ch1", "ch2"]),2162
layout: Vec::new(),2164
layout: Vec::new(),2165
settings: ChatSectionSettings::default(),2163
calls: Mutex::new(Vec::new()),2166
calls: Mutex::new(Vec::new()),2164
})2167
})2165
}2168
}@@ -2178,6 +2181,38 @@ impl FolderSource for FakeFolders {2178
Box::pin(async { Ok(self.layout.clone()) })2181
Box::pin(async { Ok(self.layout.clone()) })2179
}2182
}2180
2183
2184
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {2185
Box::pin(async { Ok(self.settings) })2186
}2187
2188
fn set_section_enabled(2189
&self,2190
section: ChatSection,2191
enabled: bool,2192
) -> BoxFuture<'_, Result<()>> {2193
Box::pin(async move {2194
self.calls2195
.lock()2196
.unwrap()2197
.push(format!("section {section:?} {enabled}"));2198
Ok(())2199
})2200
}2201
2202
fn set_folder_expanded<'a>(2203
&'a self,2204
folder_id: &'a str,2205
expanded: bool,2206
) -> BoxFuture<'a, Result<()>> {2207
Box::pin(async move {2208
self.calls2209
.lock()2210
.unwrap()2211
.push(format!("expanded {folder_id} {expanded}"));2212
Ok(())2213
})2214
}2215
2181
fn move_to_folder<'a>(2216
fn move_to_folder<'a>(2182
&'a self,2217
&'a self,2183
conversation_id: &'a str,2218
conversation_id: &'a str,@@ -2265,6 +2300,38 @@ async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() {2265
);2300
);2266
}2301
}2267
2302
2303
#[tokio::test]2304
async fn collapse_and_section_settings_go_through_the_source() {2305
let fake = Arc::new(Fake::default());2306
let mut source = FakeFolders::new();2307
Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {2308
muted: Some(false),2309
meeting: Some(true),2310
};2311
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());2312
let mut events = engine.subscribe();2313
engine.refresh_folders().await.unwrap();2314
assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);2315
assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);2316
assert_eq!(2317
teams_core::stored_section_settings(engine.store()),2318
ChatSectionSettings {2319
muted: Some(false),2320
meeting: Some(true),2321
}2322
);2323
2324
engine.set_folder_expanded("work", false).await.unwrap();2325
engine2326
.set_section_enabled(ChatSection::Meeting, false)2327
.await2328
.unwrap();2329
assert_eq!(2330
*source.calls.lock().unwrap(),2331
["expanded work false", "section Meeting false"]2332
);2333
}2334
2268
#[tokio::test]2335
#[tokio::test]2269
async fn team_layout_from_teams_orders_and_hides_the_sidebar() {2336
async fn team_layout_from_teams_orders_and_hides_the_sidebar() {2270
let fake = Arc::new(Fake::default());2337
let fake = Arc::new(Fake::default());@@ -16,7 +16,7 @@ impl Store {
16
16
transaction.execute("DELETE FROM pinned_channels", [])?;
17
17
{
18
18
let mut insert_folder = transaction.prepare_cached(
19
"INSERT INTO folders (id, position, name, kind) VALUES (?1, ?2, ?3, ?4)",
19
"INSERT INTO folders (id, position, name, kind, expanded) VALUES (?1, ?2, ?3, ?4, ?5)",
20
20
)?;
21
21
let mut insert_item = transaction.prepare_cached(
22
22
"INSERT INTO folder_items (folder_id, position, conversation_id) VALUES (?1, ?2, ?3)",
@@ -26,7 +26,8 @@ impl Store {
26
26
folder.id,
27
27
position as i64,
28
28
folder.name,
29
folder.kind
29
folder.kind,
30
folder.expanded
30
31
])?;
31
32
for (item_position, conversation_id) in folder.conversation_ids.iter().enumerate() {
32
33
insert_item.execute(params![
@@ -48,14 +49,15 @@ impl Store {
48
49
49
50
pub fn folders(&self) -> Result<Vec<FolderRecord>> {
50
51
let connection = self.lock()?;
51
let mut statement =
52
connection.prepare_cached("SELECT id, name, kind FROM folders ORDER BY position")?;
52
let mut statement = connection
53
.prepare_cached("SELECT id, name, kind, expanded FROM folders ORDER BY position")?;
53
54
let mut folders = statement
54
55
.query_map([], |row| {
55
56
Ok(FolderRecord {
56
57
id: row.get(0)?,
57
58
name: row.get(1)?,
58
59
kind: row.get(2)?,
60
expanded: row.get(3)?,
59
61
conversation_ids: Vec::new(),
60
62
})
61
63
})?
@@ -71,6 +73,15 @@ impl Store {
71
73
Ok(folders)
72
74
}
73
75
76
pub fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
77
let connection = self.lock()?;
78
connection.execute(
79
"UPDATE folders SET expanded = ?2 WHERE id = ?1",
80
params![folder_id, expanded],
81
)?;
82
Ok(())
83
}
84
74
85
pub fn pinned_channel_ids(&self) -> Result<Vec<String>> {
75
86
let connection = self.lock()?;
76
87
let mut statement = connection
@@ -16,7 +16,7 @@ impl Store {16
transaction.execute("DELETE FROM pinned_channels", [])?;16
transaction.execute("DELETE FROM pinned_channels", [])?;17
{17
{18
let mut insert_folder = transaction.prepare_cached(18
let mut insert_folder = transaction.prepare_cached(19
"INSERT INTO folders (id, position, name, kind) VALUES (?1, ?2, ?3, ?4)",19
"INSERT INTO folders (id, position, name, kind, expanded) VALUES (?1, ?2, ?3, ?4, ?5)",20
)?;20
)?;21
let mut insert_item = transaction.prepare_cached(21
let mut insert_item = transaction.prepare_cached(22
"INSERT INTO folder_items (folder_id, position, conversation_id) VALUES (?1, ?2, ?3)",22
"INSERT INTO folder_items (folder_id, position, conversation_id) VALUES (?1, ?2, ?3)",@@ -26,7 +26,8 @@ impl Store {26
folder.id,26
folder.id,27
position as i64,27
position as i64,28
folder.name,28
folder.name,29
folder.kind29
folder.kind,30
folder.expanded30
])?;31
])?;31
for (item_position, conversation_id) in folder.conversation_ids.iter().enumerate() {32
for (item_position, conversation_id) in folder.conversation_ids.iter().enumerate() {32
insert_item.execute(params![33
insert_item.execute(params![@@ -48,14 +49,15 @@ impl Store {48
49
49
pub fn folders(&self) -> Result<Vec<FolderRecord>> {50
pub fn folders(&self) -> Result<Vec<FolderRecord>> {50
let connection = self.lock()?;51
let connection = self.lock()?;51
let mut statement =52
let mut statement = connection52
connection.prepare_cached("SELECT id, name, kind FROM folders ORDER BY position")?;53
.prepare_cached("SELECT id, name, kind, expanded FROM folders ORDER BY position")?;53
let mut folders = statement54
let mut folders = statement54
.query_map([], |row| {55
.query_map([], |row| {55
Ok(FolderRecord {56
Ok(FolderRecord {56
id: row.get(0)?,57
id: row.get(0)?,57
name: row.get(1)?,58
name: row.get(1)?,58
kind: row.get(2)?,59
kind: row.get(2)?,60
expanded: row.get(3)?,59
conversation_ids: Vec::new(),61
conversation_ids: Vec::new(),60
})62
})61
})?63
})?@@ -71,6 +73,15 @@ impl Store {71
Ok(folders)73
Ok(folders)72
}74
}73
75
76
pub fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {77
let connection = self.lock()?;78
connection.execute(79
"UPDATE folders SET expanded = ?2 WHERE id = ?1",80
params![folder_id, expanded],81
)?;82
Ok(())83
}84
74
pub fn pinned_channel_ids(&self) -> Result<Vec<String>> {85
pub fn pinned_channel_ids(&self) -> Result<Vec<String>> {75
let connection = self.lock()?;86
let connection = self.lock()?;76
let mut statement = connection87
let mut statement = connection@@ -61,6 +61,10 @@ const MIGRATIONS: &[Migration] = &[
61
61
script: include_str!("migrations/0013_message_subject.sql"),
62
62
after: None,
63
63
},
64
Migration {
65
script: include_str!("migrations/0014_folder_expanded.sql"),
66
after: None,
67
},
64
68
];
65
69
66
70
pub fn latest_version() -> i64 {
@@ -61,6 +61,10 @@ const MIGRATIONS: &[Migration] = &[61
script: include_str!("migrations/0013_message_subject.sql"),61
script: include_str!("migrations/0013_message_subject.sql"),62
after: None,62
after: None,63
},63
},64
Migration {65
script: include_str!("migrations/0014_folder_expanded.sql"),66
after: None,67
},64
];68
];65
69
66
pub fn latest_version() -> i64 {70
pub fn latest_version() -> i64 {@@ -0,0 +1 @@
1
ALTER TABLE folders ADD COLUMN expanded INTEGER NOT NULL DEFAULT 1;
@@ -0,0 +1 @@1
ALTER TABLE folders ADD COLUMN expanded INTEGER NOT NULL DEFAULT 1;@@ -37,6 +37,7 @@ pub struct FolderRecord {
37
37
pub id: String,
38
38
pub name: String,
39
39
pub kind: String,
40
pub expanded: bool,
40
41
pub conversation_ids: Vec<String>,
41
42
}
42
43
@@ -37,6 +37,7 @@ pub struct FolderRecord {37
pub id: String,37
pub id: String,38
pub name: String,38
pub name: String,39
pub kind: String,39
pub kind: String,40
pub expanded: bool,40
pub conversation_ids: Vec<String>,41
pub conversation_ids: Vec<String>,41
}42
}42
43
@@ -140,7 +140,9 @@ fn an_upsert_without_links_keeps_the_stored_links() {
140
140
links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),
141
141
..message("c1", "m1", 1)
142
142
};
143
store.upsert_messages(std::slice::from_ref(&replaced)).unwrap();
143
store
144
.upsert_messages(std::slice::from_ref(&replaced))
145
.unwrap();
144
146
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
145
147
assert_eq!(found["m1"].links_json, replaced.links_json);
146
148
}
@@ -467,11 +469,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
467
469
let path = directory.path().join("nested").join("cache.sqlite3");
468
470
{
469
471
let store = Store::open(&path).unwrap();
470
assert_eq!(store.schema_version().unwrap(), 13);
472
assert_eq!(store.schema_version().unwrap(), 14);
471
473
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
472
474
}
473
475
let reopened = Store::open(&path).unwrap();
474
assert_eq!(reopened.schema_version().unwrap(), 13);
476
assert_eq!(reopened.schema_version().unwrap(), 14);
475
477
assert_eq!(reopened.message_count("c").unwrap(), 1);
476
478
drop(reopened);
477
479
let mode: String = rusqlite_open(&path)
@@ -503,7 +505,7 @@ fn old_schema_is_upgraded_in_place() {
503
505
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
504
506
drop(connection);
505
507
let store = Store::open(&path).unwrap();
506
assert_eq!(store.schema_version().unwrap(), 13);
508
assert_eq!(store.schema_version().unwrap(), 14);
507
509
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
508
510
}
509
511
@@ -569,7 +571,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
569
571
let store = Store::open(&path).unwrap();
570
572
let state = store.sync_state("c").unwrap().unwrap();
571
573
assert_eq!(state.delta_link, None);
572
assert_eq!(store.schema_version().unwrap(), 13);
574
assert_eq!(store.schema_version().unwrap(), 14);
573
575
}
574
576
575
577
#[test]
@@ -586,6 +588,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
586
588
INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
587
589
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
588
590
ALTER TABLE messages DROP COLUMN subject;
591
ALTER TABLE folders DROP COLUMN expanded;
589
592
PRAGMA user_version = 12",
590
593
)
591
594
.unwrap();
@@ -593,7 +596,12 @@ fn migration_to_v13_clears_channel_delta_links_only() {
593
596
let store = Store::open(&path).unwrap();
594
597
assert_eq!(store.sync_state("ch").unwrap().unwrap().delta_link, None);
595
598
assert_eq!(
596
store.sync_state("chat").unwrap().unwrap().delta_link.as_deref(),
599
store
600
.sync_state("chat")
601
.unwrap()
602
.unwrap()
603
.delta_link
604
.as_deref(),
597
605
Some("link")
598
606
);
599
607
}
@@ -667,17 +675,21 @@ fn folders_and_pinned_channels_are_replaced_in_order() {
667
675
id: id.into(),
668
676
name: id.into(),
669
677
kind: kind.into(),
678
expanded: kind != "MutedChats",
670
679
conversation_ids: items.iter().map(|item| item.to_string()).collect(),
671
680
};
672
681
let first = [
673
682
folder("f1", "Favorites", &["b", "a"]),
674
683
folder("f2", "UserCreated", &[]),
684
folder("f4", "MutedChats", &[]),
675
685
];
676
686
store
677
687
.replace_folders(&first, &["c2".into(), "c1".into()])
678
688
.unwrap();
679
689
assert_eq!(store.folders().unwrap(), first);
680
690
assert_eq!(store.pinned_channel_ids().unwrap(), ["c2", "c1"]);
691
store.set_folder_expanded("f2", false).unwrap();
692
assert!(!store.folders().unwrap()[1].expanded);
681
693
store
682
694
.replace_folders(&[folder("f3", "UserCreated", &["z"])], &[])
683
695
.unwrap();
@@ -831,6 +843,7 @@ fn migration_indexes_rows_that_predate_search() {
831
843
ALTER TABLE messages DROP COLUMN links_json;
832
844
ALTER TABLE messages DROP COLUMN subject;
833
845
ALTER TABLE chats DROP COLUMN muted;
846
ALTER TABLE folders DROP COLUMN expanded;
834
847
PRAGMA user_version = 3;",
835
848
)
836
849
.unwrap();
@@ -140,7 +140,9 @@ fn an_upsert_without_links_keeps_the_stored_links() {140
links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),140
links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),141
..message("c1", "m1", 1)141
..message("c1", "m1", 1)142
};142
};143
store.upsert_messages(std::slice::from_ref(&replaced)).unwrap();143
store144
.upsert_messages(std::slice::from_ref(&replaced))145
.unwrap();144
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();146
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();145
assert_eq!(found["m1"].links_json, replaced.links_json);147
assert_eq!(found["m1"].links_json, replaced.links_json);146
}148
}@@ -467,11 +469,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {467
let path = directory.path().join("nested").join("cache.sqlite3");469
let path = directory.path().join("nested").join("cache.sqlite3");468
{470
{469
let store = Store::open(&path).unwrap();471
let store = Store::open(&path).unwrap();470
assert_eq!(store.schema_version().unwrap(), 13);472
assert_eq!(store.schema_version().unwrap(), 14);471
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();473
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();472
}474
}473
let reopened = Store::open(&path).unwrap();475
let reopened = Store::open(&path).unwrap();474
assert_eq!(reopened.schema_version().unwrap(), 13);476
assert_eq!(reopened.schema_version().unwrap(), 14);475
assert_eq!(reopened.message_count("c").unwrap(), 1);477
assert_eq!(reopened.message_count("c").unwrap(), 1);476
drop(reopened);478
drop(reopened);477
let mode: String = rusqlite_open(&path)479
let mode: String = rusqlite_open(&path)@@ -503,7 +505,7 @@ fn old_schema_is_upgraded_in_place() {503
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();505
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();504
drop(connection);506
drop(connection);505
let store = Store::open(&path).unwrap();507
let store = Store::open(&path).unwrap();506
assert_eq!(store.schema_version().unwrap(), 13);508
assert_eq!(store.schema_version().unwrap(), 14);507
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();509
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();508
}510
}509
511
@@ -569,7 +571,7 @@ fn migration_to_v2_keeps_existing_sync_state() {569
let store = Store::open(&path).unwrap();571
let store = Store::open(&path).unwrap();570
let state = store.sync_state("c").unwrap().unwrap();572
let state = store.sync_state("c").unwrap().unwrap();571
assert_eq!(state.delta_link, None);573
assert_eq!(state.delta_link, None);572
assert_eq!(store.schema_version().unwrap(), 13);574
assert_eq!(store.schema_version().unwrap(), 14);573
}575
}574
576
575
#[test]577
#[test]@@ -586,6 +588,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {586
INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');588
INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');587
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');589
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');588
ALTER TABLE messages DROP COLUMN subject;590
ALTER TABLE messages DROP COLUMN subject;591
ALTER TABLE folders DROP COLUMN expanded;589
PRAGMA user_version = 12",592
PRAGMA user_version = 12",590
)593
)591
.unwrap();594
.unwrap();@@ -593,7 +596,12 @@ fn migration_to_v13_clears_channel_delta_links_only() {593
let store = Store::open(&path).unwrap();596
let store = Store::open(&path).unwrap();594
assert_eq!(store.sync_state("ch").unwrap().unwrap().delta_link, None);597
assert_eq!(store.sync_state("ch").unwrap().unwrap().delta_link, None);595
assert_eq!(598
assert_eq!(596
store.sync_state("chat").unwrap().unwrap().delta_link.as_deref(),599
store600
.sync_state("chat")601
.unwrap()602
.unwrap()603
.delta_link604
.as_deref(),597
Some("link")605
Some("link")598
);606
);599
}607
}@@ -667,17 +675,21 @@ fn folders_and_pinned_channels_are_replaced_in_order() {667
id: id.into(),675
id: id.into(),668
name: id.into(),676
name: id.into(),669
kind: kind.into(),677
kind: kind.into(),678
expanded: kind != "MutedChats",670
conversation_ids: items.iter().map(|item| item.to_string()).collect(),679
conversation_ids: items.iter().map(|item| item.to_string()).collect(),671
};680
};672
let first = [681
let first = [673
folder("f1", "Favorites", &["b", "a"]),682
folder("f1", "Favorites", &["b", "a"]),674
folder("f2", "UserCreated", &[]),683
folder("f2", "UserCreated", &[]),684
folder("f4", "MutedChats", &[]),675
];685
];676
store686
store677
.replace_folders(&first, &["c2".into(), "c1".into()])687
.replace_folders(&first, &["c2".into(), "c1".into()])678
.unwrap();688
.unwrap();679
assert_eq!(store.folders().unwrap(), first);689
assert_eq!(store.folders().unwrap(), first);680
assert_eq!(store.pinned_channel_ids().unwrap(), ["c2", "c1"]);690
assert_eq!(store.pinned_channel_ids().unwrap(), ["c2", "c1"]);691
store.set_folder_expanded("f2", false).unwrap();692
assert!(!store.folders().unwrap()[1].expanded);681
store693
store682
.replace_folders(&[folder("f3", "UserCreated", &["z"])], &[])694
.replace_folders(&[folder("f3", "UserCreated", &["z"])], &[])683
.unwrap();695
.unwrap();@@ -831,6 +843,7 @@ fn migration_indexes_rows_that_predate_search() {831
ALTER TABLE messages DROP COLUMN links_json;843
ALTER TABLE messages DROP COLUMN links_json;832
ALTER TABLE messages DROP COLUMN subject;844
ALTER TABLE messages DROP COLUMN subject;833
ALTER TABLE chats DROP COLUMN muted;845
ALTER TABLE chats DROP COLUMN muted;846
ALTER TABLE folders DROP COLUMN expanded;834
PRAGMA user_version = 3;",847
PRAGMA user_version = 3;",835
)848
)836
.unwrap();849
.unwrap();