fix(chat): section menu review findings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -133,6 +133,7 @@ pub struct AppState {
133
133
pub live_meetings: HashMap<String, LiveMeeting>,
134
134
pub live_refreshing: HashSet<String>,
135
135
pub translation: TranslationState,
136
pub section_changes: crate::section_actions::SectionChanges,
136
137
}
137
138
138
139
pub struct AppHandle(pub Entity<AppState>);
@@ -233,6 +234,7 @@ impl AppState {
233
234
live_meetings: HashMap::new(),
234
235
live_refreshing: HashSet::new(),
235
236
translation: TranslationState::default(),
237
section_changes: crate::section_actions::SectionChanges::default(),
236
238
};
237
239
state.local_previews = load_local_previews(&state.store);
238
240
state.collapsed = state.load_collapsed();
@@ -366,6 +368,7 @@ impl AppState {
366
368
.flatten()
367
369
.unwrap_or_default();
368
370
self.directory.folders = data::folders(&self.store, &self.favorite_ids);
371
self.reapply_section_changes();
369
372
self.directory.section_settings = teams_core::stored_section_settings(&self.store);
370
373
self.adopt_folder_expanded();
371
374
self.directory.pinned_channels = data::pinned_channels(&self.store);
@@ -133,6 +133,7 @@ pub struct AppState {133
pub live_meetings: HashMap<String, LiveMeeting>,133
pub live_meetings: HashMap<String, LiveMeeting>,134
pub live_refreshing: HashSet<String>,134
pub live_refreshing: HashSet<String>,135
pub translation: TranslationState,135
pub translation: TranslationState,136
pub section_changes: crate::section_actions::SectionChanges,136
}137
}137
138
138
pub struct AppHandle(pub Entity<AppState>);139
pub struct AppHandle(pub Entity<AppState>);@@ -233,6 +234,7 @@ impl AppState {233
live_meetings: HashMap::new(),234
live_meetings: HashMap::new(),234
live_refreshing: HashSet::new(),235
live_refreshing: HashSet::new(),235
translation: TranslationState::default(),236
translation: TranslationState::default(),237
section_changes: crate::section_actions::SectionChanges::default(),236
};238
};237
state.local_previews = load_local_previews(&state.store);239
state.local_previews = load_local_previews(&state.store);238
state.collapsed = state.load_collapsed();240
state.collapsed = state.load_collapsed();@@ -366,6 +368,7 @@ impl AppState {366
.flatten()368
.flatten()367
.unwrap_or_default();369
.unwrap_or_default();368
self.directory.folders = data::folders(&self.store, &self.favorite_ids);370
self.directory.folders = data::folders(&self.store, &self.favorite_ids);371
self.reapply_section_changes();369
self.directory.section_settings = teams_core::stored_section_settings(&self.store);372
self.directory.section_settings = teams_core::stored_section_settings(&self.store);370
self.adopt_folder_expanded();373
self.adopt_folder_expanded();371
self.directory.pinned_channels = data::pinned_channels(&self.store);374
self.directory.pinned_channels = data::pinned_channels(&self.store);@@ -336,17 +336,39 @@ impl Directory {
336
336
}
337
337
}
338
338
339
pub fn apply_folder_change(&mut self, change: &FolderChange) {
339
pub fn move_targets(&self) -> Vec<(String, String)> {
340
self.folders
341
.iter()
342
.filter(|folder| {
343
folder.kind == FolderKind::UserCreated && !is_pending_folder(&folder.id)
344
})
345
.map(|folder| (folder.id.clone(), folder.name.clone()))
346
.collect()
347
}
348
349
pub fn apply_folder_change(&mut self, change: &FolderChange, created_id: &str) {
340
350
let position =
341
351
|folders: &[FolderInfo], id: &str| folders.iter().position(|folder| folder.id == id);
342
352
match change {
343
FolderChange::Create { name } => self.folders.push(FolderInfo {
344
id: format!("{PENDING_FOLDER_PREFIX}{name}"),
345
name: name.clone(),
346
kind: FolderKind::UserCreated,
347
expanded: None,
348
conversation_ids: Vec::new(),
349
}),
353
FolderChange::Create { name } => {
354
let index = position(&self.folders, created_id).unwrap_or_else(|| {
355
self.folders
356
.iter()
357
.position(|folder| folder.kind == FolderKind::Recent)
358
.unwrap_or(0)
359
});
360
self.folders.retain(|folder| folder.id != created_id);
361
self.folders.insert(
362
index.min(self.folders.len()),
363
FolderInfo {
364
id: created_id.to_owned(),
365
name: name.clone(),
366
kind: FolderKind::UserCreated,
367
expanded: None,
368
conversation_ids: Vec::new(),
369
},
370
);
371
}
350
372
FolderChange::Rename { folder_id, name } => {
351
373
if let Some(index) = position(&self.folders, folder_id) {
352
374
self.folders[index].name = name.clone();
@@ -373,6 +395,10 @@ impl Directory {
373
395
374
396
pub const PENDING_FOLDER_PREFIX: &str = "pending-section:";
375
397
398
pub fn is_pending_folder(folder_id: &str) -> bool {
399
folder_id.starts_with(PENDING_FOLDER_PREFIX)
400
}
401
376
402
pub fn image_format(content_type: &str) -> ImageFormat {
377
403
let lowered = content_type.to_ascii_lowercase();
378
404
if lowered.contains("png") {
@@ -645,6 +671,7 @@ mod tests {
645
671
folder("fav", FolderKind::Favorites, &["a"]),
646
672
folder("work", FolderKind::UserCreated, &["b"]),
647
673
folder("todo", FolderKind::UserCreated, &[]),
674
folder("recent", FolderKind::Recent, &[]),
648
675
],
649
676
..Default::default()
650
677
};
@@ -655,28 +682,70 @@ mod tests {
655
682
.map(|folder| folder.id.clone())
656
683
.collect()
657
684
};
658
directory.apply_folder_change(&FolderChange::Move {
659
folder_id: "todo".into(),
660
target_folder_id: "work".into(),
661
});
662
assert_eq!(order(&directory), ["fav", "todo", "work"]);
663
directory.apply_folder_change(&FolderChange::Move {
664
folder_id: "fav".into(),
665
target_folder_id: "todo".into(),
666
});
667
assert_eq!(order(&directory), ["todo", "fav", "work"]);
668
directory.apply_folder_change(&FolderChange::Rename {
685
let move_folder = |folder_id: &str, target_folder_id: &str| FolderChange::Move {
686
folder_id: folder_id.into(),
687
target_folder_id: target_folder_id.into(),
688
};
689
directory.apply_folder_change(&move_folder("todo", "work"), "");
690
assert_eq!(order(&directory), ["fav", "todo", "work", "recent"]);
691
directory.apply_folder_change(&move_folder("fav", "todo"), "");
692
assert_eq!(order(&directory), ["todo", "fav", "work", "recent"]);
693
let rename = FolderChange::Rename {
669
694
folder_id: "work".into(),
670
695
name: "Job".into(),
671
});
696
};
697
directory.apply_folder_change(&rename, "");
672
698
assert_eq!(directory.folders[2].name, "Job");
673
directory.apply_folder_change(&FolderChange::Delete {
699
let delete = FolderChange::Delete {
674
700
folder_id: "work".into(),
675
});
701
};
702
directory.apply_folder_change(&delete, "");
676
703
assert!(directory.folder_of("b").is_none());
677
directory.apply_folder_change(&FolderChange::Create { name: "New".into() });
678
assert_eq!(directory.folders[2].name, "New");
679
assert!(directory.folders[2].id.starts_with(PENDING_FOLDER_PREFIX));
704
}
705
706
#[test]
707
fn created_folder_lands_before_recent_and_keeps_its_place_when_reapplied() {
708
let mut directory = Directory {
709
folders: vec![
710
folder("fav", FolderKind::Favorites, &[]),
711
folder("recent", FolderKind::Recent, &[]),
712
folder("muted", FolderKind::Muted, &[]),
713
],
714
..Default::default()
715
};
716
let create = FolderChange::Create { name: "New".into() };
717
let pending_id = format!("{PENDING_FOLDER_PREFIX}1");
718
directory.apply_folder_change(&create, &pending_id);
719
directory.apply_folder_change(&create, &pending_id);
720
let ids: Vec<&str> = directory
721
.folders
722
.iter()
723
.map(|folder| folder.id.as_str())
724
.collect();
725
assert_eq!(ids, ["fav", pending_id.as_str(), "recent", "muted"]);
726
let mut bare = Directory::default();
727
bare.apply_folder_change(&create, "x");
728
assert_eq!(bare.folders[0].id, "x");
729
}
730
731
#[test]
732
fn pending_folders_are_no_move_targets() {
733
let directory = Directory {
734
folders: vec![
735
folder("fav", FolderKind::Favorites, &[]),
736
folder("work", FolderKind::UserCreated, &[]),
737
folder(
738
&format!("{PENDING_FOLDER_PREFIX}1"),
739
FolderKind::UserCreated,
740
&[],
741
),
742
],
743
..Default::default()
744
};
745
assert_eq!(
746
directory.move_targets(),
747
[("work".to_owned(), "work".to_owned())]
748
);
680
749
}
681
750
682
751
#[test]
@@ -336,17 +336,39 @@ impl Directory {336
}336
}337
}337
}338
338
339
pub fn apply_folder_change(&mut self, change: &FolderChange) {339
pub fn move_targets(&self) -> Vec<(String, String)> {340
self.folders341
.iter()342
.filter(|folder| {343
folder.kind == FolderKind::UserCreated && !is_pending_folder(&folder.id)344
})345
.map(|folder| (folder.id.clone(), folder.name.clone()))346
.collect()347
}348
349
pub fn apply_folder_change(&mut self, change: &FolderChange, created_id: &str) {340
let position =350
let position =341
|folders: &[FolderInfo], id: &str| folders.iter().position(|folder| folder.id == id);351
|folders: &[FolderInfo], id: &str| folders.iter().position(|folder| folder.id == id);342
match change {352
match change {343
FolderChange::Create { name } => self.folders.push(FolderInfo {353
FolderChange::Create { name } => {344
id: format!("{PENDING_FOLDER_PREFIX}{name}"),354
let index = position(&self.folders, created_id).unwrap_or_else(|| {345
name: name.clone(),355
self.folders346
kind: FolderKind::UserCreated,356
.iter()347
expanded: None,357
.position(|folder| folder.kind == FolderKind::Recent)348
conversation_ids: Vec::new(),358
.unwrap_or(0)349
}),359
});360
self.folders.retain(|folder| folder.id != created_id);361
self.folders.insert(362
index.min(self.folders.len()),363
FolderInfo {364
id: created_id.to_owned(),365
name: name.clone(),366
kind: FolderKind::UserCreated,367
expanded: None,368
conversation_ids: Vec::new(),369
},370
);371
}350
FolderChange::Rename { folder_id, name } => {372
FolderChange::Rename { folder_id, name } => {351
if let Some(index) = position(&self.folders, folder_id) {373
if let Some(index) = position(&self.folders, folder_id) {352
self.folders[index].name = name.clone();374
self.folders[index].name = name.clone();@@ -373,6 +395,10 @@ impl Directory {373
395
374
pub const PENDING_FOLDER_PREFIX: &str = "pending-section:";396
pub const PENDING_FOLDER_PREFIX: &str = "pending-section:";375
397
398
pub fn is_pending_folder(folder_id: &str) -> bool {399
folder_id.starts_with(PENDING_FOLDER_PREFIX)400
}401
376
pub fn image_format(content_type: &str) -> ImageFormat {402
pub fn image_format(content_type: &str) -> ImageFormat {377
let lowered = content_type.to_ascii_lowercase();403
let lowered = content_type.to_ascii_lowercase();378
if lowered.contains("png") {404
if lowered.contains("png") {@@ -645,6 +671,7 @@ mod tests {645
folder("fav", FolderKind::Favorites, &["a"]),671
folder("fav", FolderKind::Favorites, &["a"]),646
folder("work", FolderKind::UserCreated, &["b"]),672
folder("work", FolderKind::UserCreated, &["b"]),647
folder("todo", FolderKind::UserCreated, &[]),673
folder("todo", FolderKind::UserCreated, &[]),674
folder("recent", FolderKind::Recent, &[]),648
],675
],649
..Default::default()676
..Default::default()650
};677
};@@ -655,28 +682,70 @@ mod tests {655
.map(|folder| folder.id.clone())682
.map(|folder| folder.id.clone())656
.collect()683
.collect()657
};684
};658
directory.apply_folder_change(&FolderChange::Move {685
let move_folder = |folder_id: &str, target_folder_id: &str| FolderChange::Move {659
folder_id: "todo".into(),686
folder_id: folder_id.into(),660
target_folder_id: "work".into(),687
target_folder_id: target_folder_id.into(),661
});688
};662
assert_eq!(order(&directory), ["fav", "todo", "work"]);689
directory.apply_folder_change(&move_folder("todo", "work"), "");663
directory.apply_folder_change(&FolderChange::Move {690
assert_eq!(order(&directory), ["fav", "todo", "work", "recent"]);664
folder_id: "fav".into(),691
directory.apply_folder_change(&move_folder("fav", "todo"), "");665
target_folder_id: "todo".into(),692
assert_eq!(order(&directory), ["todo", "fav", "work", "recent"]);666
});693
let rename = FolderChange::Rename {667
assert_eq!(order(&directory), ["todo", "fav", "work"]);668
directory.apply_folder_change(&FolderChange::Rename {669
folder_id: "work".into(),694
folder_id: "work".into(),670
name: "Job".into(),695
name: "Job".into(),671
});696
};697
directory.apply_folder_change(&rename, "");672
assert_eq!(directory.folders[2].name, "Job");698
assert_eq!(directory.folders[2].name, "Job");673
directory.apply_folder_change(&FolderChange::Delete {699
let delete = FolderChange::Delete {674
folder_id: "work".into(),700
folder_id: "work".into(),675
});701
};702
directory.apply_folder_change(&delete, "");676
assert!(directory.folder_of("b").is_none());703
assert!(directory.folder_of("b").is_none());677
directory.apply_folder_change(&FolderChange::Create { name: "New".into() });704
}678
assert_eq!(directory.folders[2].name, "New");705
679
assert!(directory.folders[2].id.starts_with(PENDING_FOLDER_PREFIX));706
#[test]707
fn created_folder_lands_before_recent_and_keeps_its_place_when_reapplied() {708
let mut directory = Directory {709
folders: vec![710
folder("fav", FolderKind::Favorites, &[]),711
folder("recent", FolderKind::Recent, &[]),712
folder("muted", FolderKind::Muted, &[]),713
],714
..Default::default()715
};716
let create = FolderChange::Create { name: "New".into() };717
let pending_id = format!("{PENDING_FOLDER_PREFIX}1");718
directory.apply_folder_change(&create, &pending_id);719
directory.apply_folder_change(&create, &pending_id);720
let ids: Vec<&str> = directory721
.folders722
.iter()723
.map(|folder| folder.id.as_str())724
.collect();725
assert_eq!(ids, ["fav", pending_id.as_str(), "recent", "muted"]);726
let mut bare = Directory::default();727
bare.apply_folder_change(&create, "x");728
assert_eq!(bare.folders[0].id, "x");729
}730
731
#[test]732
fn pending_folders_are_no_move_targets() {733
let directory = Directory {734
folders: vec![735
folder("fav", FolderKind::Favorites, &[]),736
folder("work", FolderKind::UserCreated, &[]),737
folder(738
&format!("{PENDING_FOLDER_PREFIX}1"),739
FolderKind::UserCreated,740
&[],741
),742
],743
..Default::default()744
};745
assert_eq!(746
directory.move_targets(),747
[("work".to_owned(), "work".to_owned())]748
);680
}749
}681
750
682
#[test]751
#[test]@@ -1,7 +1,57 @@
1
use std::collections::VecDeque;
2
1
3
use gpui_kit::*;
2
4
use teams_core::FolderChange;
3
5
4
6
use crate::app_state::{AppEvent, AppState};
7
use crate::data::{Directory, PENDING_FOLDER_PREFIX};
8
9
pub const READ_ONLY_SECTIONS: &str = "Read-only mode: sections not changed";
10
11
#[derive(Debug, Clone, PartialEq, Eq)]
12
pub struct QueuedFolderChange {
13
pub change: FolderChange,
14
pub label: &'static str,
15
pub created_id: String,
16
}
17
18
#[derive(Debug, Default)]
19
pub struct SectionChanges {
20
queue: VecDeque<QueuedFolderChange>,
21
created: u64,
22
}
23
24
impl SectionChanges {
25
pub fn push(&mut self, change: FolderChange, label: &'static str) -> QueuedFolderChange {
26
self.created += 1;
27
let queued = QueuedFolderChange {
28
change,
29
label,
30
created_id: format!("{PENDING_FOLDER_PREFIX}{}", self.created),
31
};
32
self.queue.push_back(queued.clone());
33
queued
34
}
35
36
pub fn in_flight(&self) -> Option<&QueuedFolderChange> {
37
self.queue.front()
38
}
39
40
pub fn finish(&mut self) -> Option<&QueuedFolderChange> {
41
self.queue.pop_front();
42
self.queue.front()
43
}
44
45
pub fn clear(&mut self) {
46
self.queue.clear();
47
}
48
49
pub fn reapply(&self, directory: &mut Directory) {
50
for queued in &self.queue {
51
directory.apply_folder_change(&queued.change, &queued.created_id);
52
}
53
}
54
}
5
55
6
56
impl AppState {
7
57
pub fn create_section(&mut self, name: &str, cx: &mut Context<Self>) {
@@ -45,27 +95,116 @@ impl AppState {
45
95
label: &'static str,
46
96
cx: &mut Context<Self>,
47
97
) {
48
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
98
if self.mode.read_only {
99
self.raise_notice(READ_ONLY_SECTIONS.to_owned(), None, cx);
100
return;
101
}
102
if self.engine.is_none() {
103
if self.mode.demo {
104
let demo_id = uuid::Uuid::new_v4().to_string();
105
self.directory.apply_folder_change(&change, &demo_id);
106
self.notify_sections(cx);
107
}
108
return;
109
}
110
let starts_now = self.section_changes.in_flight().is_none();
111
let queued = self.section_changes.push(change, label);
112
self.directory
113
.apply_folder_change(&queued.change, &queued.created_id);
114
self.notify_sections(cx);
115
if starts_now {
116
self.run_next_section_change(cx);
117
}
118
}
119
120
fn run_next_section_change(&mut self, cx: &mut Context<Self>) {
121
let Some(queued) = self.section_changes.in_flight().cloned() else {
49
122
return;
50
123
};
51
self.directory.apply_folder_change(&change);
52
cx.emit(AppEvent::Sidebar);
53
cx.notify();
54
let Some(engine) = engine_or_demo else {
124
let Some(engine) = self.engine.clone() else {
125
self.section_changes.clear();
55
126
return;
56
127
};
57
128
self.run_chat_action(
58
label,
59
async move { engine.change_folders(change).await },
60
Self::reload_sections,
61
Self::reload_sections,
129
queued.label,
130
async move { engine.change_folders(queued.change).await },
131
Self::finish_section_change,
132
Self::finish_section_change,
62
133
cx,
63
134
);
64
135
}
65
136
66
fn reload_sections(&mut self, cx: &mut Context<Self>) {
137
fn finish_section_change(&mut self, cx: &mut Context<Self>) {
138
let has_next = self.section_changes.finish().is_some();
67
139
self.reload_directory();
140
self.notify_sections(cx);
141
if has_next {
142
self.run_next_section_change(cx);
143
}
144
}
145
146
pub(crate) fn reapply_section_changes(&mut self) {
147
self.section_changes.reapply(&mut self.directory);
148
}
149
150
fn notify_sections(&mut self, cx: &mut Context<Self>) {
68
151
cx.emit(AppEvent::Sidebar);
69
152
cx.notify();
70
153
}
71
154
}
155
156
#[cfg(test)]
157
mod tests {
158
use super::{Directory, FolderChange, SectionChanges};
159
use crate::data::{FolderInfo, FolderKind};
160
161
fn create(name: &str) -> FolderChange {
162
FolderChange::Create { name: name.into() }
163
}
164
165
#[test]
166
fn folder_changes_run_one_at_a_time_in_order() {
167
let mut changes = SectionChanges::default();
168
assert!(changes.in_flight().is_none());
169
changes.push(create("a"), "New section");
170
changes.push(create("b"), "New section");
171
assert_eq!(changes.in_flight().unwrap().change, create("a"));
172
assert_eq!(changes.finish().unwrap().change, create("b"));
173
assert!(changes.finish().is_none());
174
assert!(changes.in_flight().is_none());
175
}
176
177
#[test]
178
fn same_name_creates_get_distinct_pending_ids() {
179
let mut changes = SectionChanges::default();
180
changes.push(create("Todo"), "New section");
181
changes.push(create("Todo"), "New section");
182
let mut directory = Directory::default();
183
changes.reapply(&mut directory);
184
assert_eq!(directory.folders.len(), 2);
185
assert_ne!(directory.folders[0].id, directory.folders[1].id);
186
}
187
188
#[test]
189
fn pending_create_survives_a_directory_reload() {
190
let mut changes = SectionChanges::default();
191
changes.push(create("Todo"), "New section");
192
let reloaded = || Directory {
193
folders: vec![FolderInfo {
194
id: "recent".into(),
195
name: String::new(),
196
kind: FolderKind::Recent,
197
expanded: None,
198
conversation_ids: Vec::new(),
199
}],
200
..Default::default()
201
};
202
let mut directory = reloaded();
203
changes.reapply(&mut directory);
204
assert_eq!(directory.folders[0].name, "Todo");
205
changes.finish();
206
let mut directory = reloaded();
207
changes.reapply(&mut directory);
208
assert_eq!(directory.folders.len(), 1);
209
}
210
}
@@ -1,7 +1,57 @@1
use std::collections::VecDeque;2
1
use gpui_kit::*;3
use gpui_kit::*;2
use teams_core::FolderChange;4
use teams_core::FolderChange;3
5
4
use crate::app_state::{AppEvent, AppState};6
use crate::app_state::{AppEvent, AppState};7
use crate::data::{Directory, PENDING_FOLDER_PREFIX};8
9
pub const READ_ONLY_SECTIONS: &str = "Read-only mode: sections not changed";10
11
#[derive(Debug, Clone, PartialEq, Eq)]12
pub struct QueuedFolderChange {13
pub change: FolderChange,14
pub label: &'static str,15
pub created_id: String,16
}17
18
#[derive(Debug, Default)]19
pub struct SectionChanges {20
queue: VecDeque<QueuedFolderChange>,21
created: u64,22
}23
24
impl SectionChanges {25
pub fn push(&mut self, change: FolderChange, label: &'static str) -> QueuedFolderChange {26
self.created += 1;27
let queued = QueuedFolderChange {28
change,29
label,30
created_id: format!("{PENDING_FOLDER_PREFIX}{}", self.created),31
};32
self.queue.push_back(queued.clone());33
queued34
}35
36
pub fn in_flight(&self) -> Option<&QueuedFolderChange> {37
self.queue.front()38
}39
40
pub fn finish(&mut self) -> Option<&QueuedFolderChange> {41
self.queue.pop_front();42
self.queue.front()43
}44
45
pub fn clear(&mut self) {46
self.queue.clear();47
}48
49
pub fn reapply(&self, directory: &mut Directory) {50
for queued in &self.queue {51
directory.apply_folder_change(&queued.change, &queued.created_id);52
}53
}54
}5
55
6
impl AppState {56
impl AppState {7
pub fn create_section(&mut self, name: &str, cx: &mut Context<Self>) {57
pub fn create_section(&mut self, name: &str, cx: &mut Context<Self>) {@@ -45,27 +95,116 @@ impl AppState {45
label: &'static str,95
label: &'static str,46
cx: &mut Context<Self>,96
cx: &mut Context<Self>,47
) {97
) {48
let Some(engine_or_demo) = self.chat_action_engine(cx) else {98
if self.mode.read_only {99
self.raise_notice(READ_ONLY_SECTIONS.to_owned(), None, cx);100
return;101
}102
if self.engine.is_none() {103
if self.mode.demo {104
let demo_id = uuid::Uuid::new_v4().to_string();105
self.directory.apply_folder_change(&change, &demo_id);106
self.notify_sections(cx);107
}108
return;109
}110
let starts_now = self.section_changes.in_flight().is_none();111
let queued = self.section_changes.push(change, label);112
self.directory113
.apply_folder_change(&queued.change, &queued.created_id);114
self.notify_sections(cx);115
if starts_now {116
self.run_next_section_change(cx);117
}118
}119
120
fn run_next_section_change(&mut self, cx: &mut Context<Self>) {121
let Some(queued) = self.section_changes.in_flight().cloned() else {49
return;122
return;50
};123
};51
self.directory.apply_folder_change(&change);124
let Some(engine) = self.engine.clone() else {52
cx.emit(AppEvent::Sidebar);125
self.section_changes.clear();53
cx.notify();54
let Some(engine) = engine_or_demo else {55
return;126
return;56
};127
};57
self.run_chat_action(128
self.run_chat_action(58
label,129
queued.label,59
async move { engine.change_folders(change).await },130
async move { engine.change_folders(queued.change).await },60
Self::reload_sections,131
Self::finish_section_change,61
Self::reload_sections,132
Self::finish_section_change,62
cx,133
cx,63
);134
);64
}135
}65
136
66
fn reload_sections(&mut self, cx: &mut Context<Self>) {137
fn finish_section_change(&mut self, cx: &mut Context<Self>) {138
let has_next = self.section_changes.finish().is_some();67
self.reload_directory();139
self.reload_directory();140
self.notify_sections(cx);141
if has_next {142
self.run_next_section_change(cx);143
}144
}145
146
pub(crate) fn reapply_section_changes(&mut self) {147
self.section_changes.reapply(&mut self.directory);148
}149
150
fn notify_sections(&mut self, cx: &mut Context<Self>) {68
cx.emit(AppEvent::Sidebar);151
cx.emit(AppEvent::Sidebar);69
cx.notify();152
cx.notify();70
}153
}71
}154
}155
156
#[cfg(test)]157
mod tests {158
use super::{Directory, FolderChange, SectionChanges};159
use crate::data::{FolderInfo, FolderKind};160
161
fn create(name: &str) -> FolderChange {162
FolderChange::Create { name: name.into() }163
}164
165
#[test]166
fn folder_changes_run_one_at_a_time_in_order() {167
let mut changes = SectionChanges::default();168
assert!(changes.in_flight().is_none());169
changes.push(create("a"), "New section");170
changes.push(create("b"), "New section");171
assert_eq!(changes.in_flight().unwrap().change, create("a"));172
assert_eq!(changes.finish().unwrap().change, create("b"));173
assert!(changes.finish().is_none());174
assert!(changes.in_flight().is_none());175
}176
177
#[test]178
fn same_name_creates_get_distinct_pending_ids() {179
let mut changes = SectionChanges::default();180
changes.push(create("Todo"), "New section");181
changes.push(create("Todo"), "New section");182
let mut directory = Directory::default();183
changes.reapply(&mut directory);184
assert_eq!(directory.folders.len(), 2);185
assert_ne!(directory.folders[0].id, directory.folders[1].id);186
}187
188
#[test]189
fn pending_create_survives_a_directory_reload() {190
let mut changes = SectionChanges::default();191
changes.push(create("Todo"), "New section");192
let reloaded = || Directory {193
folders: vec![FolderInfo {194
id: "recent".into(),195
name: String::new(),196
kind: FolderKind::Recent,197
expanded: None,198
conversation_ids: Vec::new(),199
}],200
..Default::default()201
};202
let mut directory = reloaded();203
changes.reapply(&mut directory);204
assert_eq!(directory.folders[0].name, "Todo");205
changes.finish();206
let mut directory = reloaded();207
changes.reapply(&mut directory);208
assert_eq!(directory.folders.len(), 1);209
}210
}@@ -21,7 +21,7 @@ use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
21
21
use super::widgets::{count_badge, dot, icon, page_header, unread_marker};
22
22
use crate::app_state::{AppEvent, AppState, Selection};
23
23
use crate::chat_actions::TITLE_LIMIT;
24
use crate::data::{Directory, FolderKind, PENDING_FOLDER_PREFIX};
24
use crate::data::{Directory, is_pending_folder};
25
25
use crate::format;
26
26
use crate::local_previews::LocalPreview;
27
27
use crate::notice::truncated;
@@ -247,15 +247,20 @@ struct SectionMenuTarget {
247
247
previous_id: Option<String>,
248
248
next_id: Option<String>,
249
249
movable: bool,
250
read_only: bool,
250
251
}
251
252
252
fn section_menu_targets(sections: &[Section], directory: &Directory) -> Vec<SectionMenuTarget> {
253
fn section_menu_targets(
254
sections: &[Section],
255
directory: &Directory,
256
read_only: bool,
257
) -> Vec<SectionMenuTarget> {
253
258
let movable = |section: &Section| {
254
259
directory
255
260
.folders
256
261
.iter()
257
262
.any(|folder| folder.id == section.id)
258
&& !section.id.starts_with(PENDING_FOLDER_PREFIX)
263
&& !is_pending_folder(§ion.id)
259
264
};
260
265
sections
261
266
.iter()
@@ -274,14 +279,26 @@ fn section_menu_targets(sections: &[Section], directory: &Directory) -> Vec<Sect
274
279
.find(|other| movable(other))
275
280
.map(|other| other.id.clone()),
276
281
movable: movable(section),
282
read_only,
277
283
})
278
284
.collect()
279
285
}
280
286
281
fn new_section_item(state: &Entity<AppState>) -> PopupMenuItem {
287
fn drop_target(section: &Section) -> Option<Option<String>> {
288
if is_pending_folder(§ion.id) {
289
return None;
290
}
291
Some(
292
matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)
293
.then(|| section.id.clone()),
294
)
295
}
296
297
fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem {
282
298
let state = state.clone();
283
299
PopupMenuItem::new("New section")
284
300
.icon(menu_icon(IconName::Plus))
301
.disabled(read_only)
285
302
.on_click(move |_, window, cx| {
286
303
open_section_name_dialog(state.clone(), SectionNameTarget::New, window, cx);
287
304
})
@@ -293,13 +310,14 @@ fn move_section_item(
293
310
glyph: IconName,
294
311
folder_id: &str,
295
312
target_id: Option<&String>,
313
read_only: bool,
296
314
) -> PopupMenuItem {
297
315
let state = state.clone();
298
316
let folder_id = folder_id.to_owned();
299
317
let target_id = target_id.cloned();
300
318
PopupMenuItem::new(label)
301
319
.icon(menu_icon(glyph))
302
.disabled(target_id.is_none())
320
.disabled(read_only || target_id.is_none())
303
321
.on_click(move |_, _, cx| {
304
322
if let Some(target_id) = &target_id {
305
323
state.update(cx, |state, cx| {
@@ -324,6 +342,7 @@ fn section_menu(
324
342
popup = popup.item(
325
343
PopupMenuItem::new("Rename section")
326
344
.icon(menu_icon(IconName::Pencil))
345
.disabled(target.read_only)
327
346
.on_click(move |_, window, cx| {
328
347
open_section_name_dialog(
329
348
rename_state.clone(),
@@ -342,6 +361,7 @@ fn section_menu(
342
361
IconName::ArrowUp,
343
362
&target.id,
344
363
target.previous_id.as_ref(),
364
target.read_only,
345
365
))
346
366
.item(move_section_item(
347
367
state,
@@ -349,10 +369,11 @@ fn section_menu(
349
369
IconName::ArrowDown,
350
370
&target.id,
351
371
target.next_id.as_ref(),
372
target.read_only,
352
373
))
353
374
.separator();
354
375
}
355
popup = popup.item(new_section_item(state));
376
popup = popup.item(new_section_item(state, target.read_only));
356
377
if target.user_created {
357
378
let delete_state = state.clone();
358
379
let (folder_id, name) = (target.id.clone(), target.name.clone());
@@ -361,6 +382,7 @@ fn section_menu(
361
382
div().text_color(theme::red_soft()).child("Delete section")
362
383
})
363
384
.icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))
385
.disabled(target.read_only)
364
386
.on_click(move |_, window, cx| {
365
387
confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
366
388
}),
@@ -686,15 +708,16 @@ impl SidebarView {
686
708
}))
687
709
}
688
710
689
fn chat_list_menu_button(&self) -> impl IntoElement {
711
fn chat_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
690
712
let state = self.state.clone();
713
let read_only = self.state.read(cx).mode.read_only;
691
714
Button::new("chat-list-more")
692
715
.icon(IconName::Ellipsis)
693
716
.ghost()
694
717
.size(px(NEW_CHAT_BUTTON_SIZE))
695
718
.rounded(px(8.))
696
719
.tooltip("More options")
697
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state)))
720
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
698
721
}
699
722
700
723
fn draft_row(&self) -> impl IntoElement {
@@ -746,8 +769,7 @@ impl SidebarView {
746
769
menu: SectionMenuTarget,
747
770
cx: &mut Context<Self>,
748
771
) -> impl IntoElement {
749
let drop_target = matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)
750
.then(|| section.id.clone());
772
let drop_target = drop_target(section);
751
773
let toggle_id = section.id.clone();
752
774
let menu_state = self.state.clone();
753
775
h_flex()
@@ -761,19 +783,22 @@ impl SidebarView {
761
783
.rounded(px(6.))
762
784
.cursor_pointer()
763
785
.hover(|header| header.bg(theme::row_hover()))
764
.drag_over::<DraggedChat>(|style, _, _, _| {
765
style
766
.bg(theme::drop_background())
767
.border_1()
768
.border_dashed()
769
.border_color(theme::accent())
786
.when_some(drop_target, |header, drop_target| {
787
header
788
.drag_over::<DraggedChat>(|style, _, _, _| {
789
style
790
.bg(theme::drop_background())
791
.border_1()
792
.border_dashed()
793
.border_color(theme::accent())
794
})
795
.on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {
796
let target = drop_target.clone();
797
this.state.update(cx, |state, cx| {
798
state.move_chat(&dragged.id, target.as_deref(), cx)
799
});
800
}))
770
801
})
771
.on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {
772
let target = drop_target.clone();
773
this.state.update(cx, |state, cx| {
774
state.move_chat(&dragged.id, target.as_deref(), cx)
775
});
776
}))
777
802
.child(icon(
778
803
if section.collapsed {
779
804
IconName::ChevronRight
@@ -1018,16 +1043,11 @@ impl SidebarView {
1018
1043
let sections = build_sections(&input);
1019
1044
let menu = MenuContext {
1020
1045
state: self.state.clone(),
1021
folders: state
1022
.directory
1023
.folders
1024
.iter()
1025
.filter(|folder| folder.kind == FolderKind::UserCreated)
1026
.map(|folder| (folder.id.clone(), folder.name.clone()))
1027
.collect(),
1046
folders: state.directory.move_targets(),
1028
1047
favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),
1029
1048
};
1030
let section_menus = section_menu_targets(§ions, &state.directory);
1049
let section_menus =
1050
section_menu_targets(§ions, &state.directory, state.mode.read_only);
1031
1051
(sections, section_menus, menu, state.local_previews.clone())
1032
1052
};
1033
1053
@@ -1679,7 +1699,7 @@ impl Render for SidebarView {
1679
1699
let header = match self.tab {
1680
1700
SidebarTab::Chats => Some(
1681
1701
page_header(self.tab.title())
1682
.child(self.chat_list_menu_button())
1702
.child(self.chat_list_menu_button(cx))
1683
1703
.child(self.new_chat_button(cx)),
1684
1704
),
1685
1705
SidebarTab::Channels | SidebarTab::Calls => Some(page_header(self.tab.title())),
@@ -1702,8 +1722,40 @@ mod tests {
1702
1722
use std::collections::HashSet;
1703
1723
1704
1724
use super::{
1705
leave_description, parse_collapsed_teams, serialize_collapsed_teams, team_expanded,
1725
drop_target, leave_description, parse_collapsed_teams, serialize_collapsed_teams,
1726
team_expanded,
1706
1727
};
1728
use crate::data::PENDING_FOLDER_PREFIX;
1729
use crate::sidebar_model::{Section, SectionKind};
1730
1731
fn section(id: &str, kind: SectionKind) -> Section {
1732
Section {
1733
id: id.to_owned(),
1734
name: id.to_owned(),
1735
kind,
1736
collapsed: false,
1737
count: 0,
1738
unread_chats: 0,
1739
items: Vec::new(),
1740
hidden_count: 0,
1741
list_expanded: false,
1742
show_empty_hint: false,
1743
}
1744
}
1745
1746
#[test]
1747
fn pending_sections_take_no_dropped_chats() {
1748
let pending = format!("{PENDING_FOLDER_PREFIX}1");
1749
assert_eq!(drop_target(§ion(&pending, SectionKind::Folder)), None);
1750
assert_eq!(
1751
drop_target(§ion("work", SectionKind::Folder)),
1752
Some(Some("work".to_owned()))
1753
);
1754
assert_eq!(
1755
drop_target(§ion("recent", SectionKind::Others)),
1756
Some(None)
1757
);
1758
}
1707
1759
1708
1760
#[test]
1709
1761
fn teams_start_expanded() {
@@ -21,7 +21,7 @@ use super::section_dialog::{SectionNameTarget, open_section_name_dialog};21
use super::widgets::{count_badge, dot, icon, page_header, unread_marker};21
use super::widgets::{count_badge, dot, icon, page_header, unread_marker};22
use crate::app_state::{AppEvent, AppState, Selection};22
use crate::app_state::{AppEvent, AppState, Selection};23
use crate::chat_actions::TITLE_LIMIT;23
use crate::chat_actions::TITLE_LIMIT;24
use crate::data::{Directory, FolderKind, PENDING_FOLDER_PREFIX};24
use crate::data::{Directory, is_pending_folder};25
use crate::format;25
use crate::format;26
use crate::local_previews::LocalPreview;26
use crate::local_previews::LocalPreview;27
use crate::notice::truncated;27
use crate::notice::truncated;@@ -247,15 +247,20 @@ struct SectionMenuTarget {247
previous_id: Option<String>,247
previous_id: Option<String>,248
next_id: Option<String>,248
next_id: Option<String>,249
movable: bool,249
movable: bool,250
read_only: bool,250
}251
}251
252
252
fn section_menu_targets(sections: &[Section], directory: &Directory) -> Vec<SectionMenuTarget> {253
fn section_menu_targets(254
sections: &[Section],255
directory: &Directory,256
read_only: bool,257
) -> Vec<SectionMenuTarget> {253
let movable = |section: &Section| {258
let movable = |section: &Section| {254
directory259
directory255
.folders260
.folders256
.iter()261
.iter()257
.any(|folder| folder.id == section.id)262
.any(|folder| folder.id == section.id)258
&& !section.id.starts_with(PENDING_FOLDER_PREFIX)263
&& !is_pending_folder(§ion.id)259
};264
};260
sections265
sections261
.iter()266
.iter()@@ -274,14 +279,26 @@ fn section_menu_targets(sections: &[Section], directory: &Directory) -> Vec<Sect274
.find(|other| movable(other))279
.find(|other| movable(other))275
.map(|other| other.id.clone()),280
.map(|other| other.id.clone()),276
movable: movable(section),281
movable: movable(section),282
read_only,277
})283
})278
.collect()284
.collect()279
}285
}280
286
281
fn new_section_item(state: &Entity<AppState>) -> PopupMenuItem {287
fn drop_target(section: &Section) -> Option<Option<String>> {288
if is_pending_folder(§ion.id) {289
return None;290
}291
Some(292
matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)293
.then(|| section.id.clone()),294
)295
}296
297
fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem {282
let state = state.clone();298
let state = state.clone();283
PopupMenuItem::new("New section")299
PopupMenuItem::new("New section")284
.icon(menu_icon(IconName::Plus))300
.icon(menu_icon(IconName::Plus))301
.disabled(read_only)285
.on_click(move |_, window, cx| {302
.on_click(move |_, window, cx| {286
open_section_name_dialog(state.clone(), SectionNameTarget::New, window, cx);303
open_section_name_dialog(state.clone(), SectionNameTarget::New, window, cx);287
})304
})@@ -293,13 +310,14 @@ fn move_section_item(293
glyph: IconName,310
glyph: IconName,294
folder_id: &str,311
folder_id: &str,295
target_id: Option<&String>,312
target_id: Option<&String>,313
read_only: bool,296
) -> PopupMenuItem {314
) -> PopupMenuItem {297
let state = state.clone();315
let state = state.clone();298
let folder_id = folder_id.to_owned();316
let folder_id = folder_id.to_owned();299
let target_id = target_id.cloned();317
let target_id = target_id.cloned();300
PopupMenuItem::new(label)318
PopupMenuItem::new(label)301
.icon(menu_icon(glyph))319
.icon(menu_icon(glyph))302
.disabled(target_id.is_none())320
.disabled(read_only || target_id.is_none())303
.on_click(move |_, _, cx| {321
.on_click(move |_, _, cx| {304
if let Some(target_id) = &target_id {322
if let Some(target_id) = &target_id {305
state.update(cx, |state, cx| {323
state.update(cx, |state, cx| {@@ -324,6 +342,7 @@ fn section_menu(324
popup = popup.item(342
popup = popup.item(325
PopupMenuItem::new("Rename section")343
PopupMenuItem::new("Rename section")326
.icon(menu_icon(IconName::Pencil))344
.icon(menu_icon(IconName::Pencil))345
.disabled(target.read_only)327
.on_click(move |_, window, cx| {346
.on_click(move |_, window, cx| {328
open_section_name_dialog(347
open_section_name_dialog(329
rename_state.clone(),348
rename_state.clone(),@@ -342,6 +361,7 @@ fn section_menu(342
IconName::ArrowUp,361
IconName::ArrowUp,343
&target.id,362
&target.id,344
target.previous_id.as_ref(),363
target.previous_id.as_ref(),364
target.read_only,345
))365
))346
.item(move_section_item(366
.item(move_section_item(347
state,367
state,@@ -349,10 +369,11 @@ fn section_menu(349
IconName::ArrowDown,369
IconName::ArrowDown,350
&target.id,370
&target.id,351
target.next_id.as_ref(),371
target.next_id.as_ref(),372
target.read_only,352
))373
))353
.separator();374
.separator();354
}375
}355
popup = popup.item(new_section_item(state));376
popup = popup.item(new_section_item(state, target.read_only));356
if target.user_created {377
if target.user_created {357
let delete_state = state.clone();378
let delete_state = state.clone();358
let (folder_id, name) = (target.id.clone(), target.name.clone());379
let (folder_id, name) = (target.id.clone(), target.name.clone());@@ -361,6 +382,7 @@ fn section_menu(361
div().text_color(theme::red_soft()).child("Delete section")382
div().text_color(theme::red_soft()).child("Delete section")362
})383
})363
.icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))384
.icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))385
.disabled(target.read_only)364
.on_click(move |_, window, cx| {386
.on_click(move |_, window, cx| {365
confirm_delete_section(&delete_state, &folder_id, &name, window, cx);387
confirm_delete_section(&delete_state, &folder_id, &name, window, cx);366
}),388
}),@@ -686,15 +708,16 @@ impl SidebarView {686
}))708
}))687
}709
}688
710
689
fn chat_list_menu_button(&self) -> impl IntoElement {711
fn chat_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {690
let state = self.state.clone();712
let state = self.state.clone();713
let read_only = self.state.read(cx).mode.read_only;691
Button::new("chat-list-more")714
Button::new("chat-list-more")692
.icon(IconName::Ellipsis)715
.icon(IconName::Ellipsis)693
.ghost()716
.ghost()694
.size(px(NEW_CHAT_BUTTON_SIZE))717
.size(px(NEW_CHAT_BUTTON_SIZE))695
.rounded(px(8.))718
.rounded(px(8.))696
.tooltip("More options")719
.tooltip("More options")697
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state)))720
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))698
}721
}699
722
700
fn draft_row(&self) -> impl IntoElement {723
fn draft_row(&self) -> impl IntoElement {@@ -746,8 +769,7 @@ impl SidebarView {746
menu: SectionMenuTarget,769
menu: SectionMenuTarget,747
cx: &mut Context<Self>,770
cx: &mut Context<Self>,748
) -> impl IntoElement {771
) -> impl IntoElement {749
let drop_target = matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)772
let drop_target = drop_target(section);750
.then(|| section.id.clone());751
let toggle_id = section.id.clone();773
let toggle_id = section.id.clone();752
let menu_state = self.state.clone();774
let menu_state = self.state.clone();753
h_flex()775
h_flex()@@ -761,19 +783,22 @@ impl SidebarView {761
.rounded(px(6.))783
.rounded(px(6.))762
.cursor_pointer()784
.cursor_pointer()763
.hover(|header| header.bg(theme::row_hover()))785
.hover(|header| header.bg(theme::row_hover()))764
.drag_over::<DraggedChat>(|style, _, _, _| {786
.when_some(drop_target, |header, drop_target| {765
style787
header766
.bg(theme::drop_background())788
.drag_over::<DraggedChat>(|style, _, _, _| {767
.border_1()789
style768
.border_dashed()790
.bg(theme::drop_background())769
.border_color(theme::accent())791
.border_1()792
.border_dashed()793
.border_color(theme::accent())794
})795
.on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {796
let target = drop_target.clone();797
this.state.update(cx, |state, cx| {798
state.move_chat(&dragged.id, target.as_deref(), cx)799
});800
}))770
})801
})771
.on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {772
let target = drop_target.clone();773
this.state.update(cx, |state, cx| {774
state.move_chat(&dragged.id, target.as_deref(), cx)775
});776
}))777
.child(icon(802
.child(icon(778
if section.collapsed {803
if section.collapsed {779
IconName::ChevronRight804
IconName::ChevronRight@@ -1018,16 +1043,11 @@ impl SidebarView {1018
let sections = build_sections(&input);1043
let sections = build_sections(&input);1019
let menu = MenuContext {1044
let menu = MenuContext {1020
state: self.state.clone(),1045
state: self.state.clone(),1021
folders: state1046
folders: state.directory.move_targets(),1022
.directory1023
.folders1024
.iter()1025
.filter(|folder| folder.kind == FolderKind::UserCreated)1026
.map(|folder| (folder.id.clone(), folder.name.clone()))1027
.collect(),1028
favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),1047
favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),1029
};1048
};1030
let section_menus = section_menu_targets(§ions, &state.directory);1049
let section_menus =1050
section_menu_targets(§ions, &state.directory, state.mode.read_only);1031
(sections, section_menus, menu, state.local_previews.clone())1051
(sections, section_menus, menu, state.local_previews.clone())1032
};1052
};1033
1053
@@ -1679,7 +1699,7 @@ impl Render for SidebarView {1679
let header = match self.tab {1699
let header = match self.tab {1680
SidebarTab::Chats => Some(1700
SidebarTab::Chats => Some(1681
page_header(self.tab.title())1701
page_header(self.tab.title())1682
.child(self.chat_list_menu_button())1702
.child(self.chat_list_menu_button(cx))1683
.child(self.new_chat_button(cx)),1703
.child(self.new_chat_button(cx)),1684
),1704
),1685
SidebarTab::Channels | SidebarTab::Calls => Some(page_header(self.tab.title())),1705
SidebarTab::Channels | SidebarTab::Calls => Some(page_header(self.tab.title())),@@ -1702,8 +1722,40 @@ mod tests {1702
use std::collections::HashSet;1722
use std::collections::HashSet;1703
1723
1704
use super::{1724
use super::{1705
leave_description, parse_collapsed_teams, serialize_collapsed_teams, team_expanded,1725
drop_target, leave_description, parse_collapsed_teams, serialize_collapsed_teams,1726
team_expanded,1706
};1727
};1728
use crate::data::PENDING_FOLDER_PREFIX;1729
use crate::sidebar_model::{Section, SectionKind};1730
1731
fn section(id: &str, kind: SectionKind) -> Section {1732
Section {1733
id: id.to_owned(),1734
name: id.to_owned(),1735
kind,1736
collapsed: false,1737
count: 0,1738
unread_chats: 0,1739
items: Vec::new(),1740
hidden_count: 0,1741
list_expanded: false,1742
show_empty_hint: false,1743
}1744
}1745
1746
#[test]1747
fn pending_sections_take_no_dropped_chats() {1748
let pending = format!("{PENDING_FOLDER_PREFIX}1");1749
assert_eq!(drop_target(§ion(&pending, SectionKind::Folder)), None);1750
assert_eq!(1751
drop_target(§ion("work", SectionKind::Folder)),1752
Some(Some("work".to_owned()))1753
);1754
assert_eq!(1755
drop_target(§ion("recent", SectionKind::Others)),1756
Some(None)1757
);1758
}1707
1759
1708
#[test]1760
#[test]1709
fn teams_start_expanded() {1761
fn teams_start_expanded() {@@ -155,6 +155,7 @@ struct FolderWrite {
155
155
method: Method,
156
156
folder_id: Option<String>,
157
157
fields: Value,
158
answer_is_state: bool,
158
159
}
159
160
160
161
impl FolderWrite {
@@ -163,6 +164,16 @@ impl FolderWrite {
163
164
method: Method::Post,
164
165
folder_id: None,
165
166
fields: json!({"actions": actions}),
167
answer_is_state: true,
168
}
169
}
170
171
fn reread(method: Method, folder_id: Option<&str>, fields: Value) -> Self {
172
FolderWrite {
173
method,
174
folder_id: folder_id.map(str::to_owned),
175
fields,
176
answer_is_state: false,
166
177
}
167
178
}
168
179
@@ -258,11 +269,11 @@ impl<T: CsaTransport> Pins<T> {
258
269
259
270
pub async fn create_folder(&self, name: &str) -> Result<Folders> {
260
271
self.write(|_| {
261
Ok(Some(FolderWrite {
262
method: Method::Post,
263
folder_id: None,
264
fields: json!({"folderName": name, "actions": [{"action": "AddFolder"}]}),
265
}))
272
Ok(Some(FolderWrite::reread(
273
Method::Post,
274
None,
275
json!({"folderName": name, "actions": [{"action": "AddFolder"}]}),
276
)))
266
277
})
267
278
.await
268
279
}
@@ -272,11 +283,11 @@ impl<T: CsaTransport> Pins<T> {
272
283
if state.user_created(folder_id)?.name == name {
273
284
return Ok(None);
274
285
}
275
Ok(Some(FolderWrite {
276
method: Method::Put,
277
folder_id: Some(folder_id.to_owned()),
278
fields: json!({"folderName": name}),
279
}))
286
Ok(Some(FolderWrite::reread(
287
Method::Put,
288
Some(folder_id),
289
json!({"folderName": name}),
290
)))
280
291
})
281
292
.await
282
293
}
@@ -287,11 +298,11 @@ impl<T: CsaTransport> Pins<T> {
287
298
return Ok(None);
288
299
}
289
300
state.user_created(folder_id)?;
290
Ok(Some(FolderWrite {
291
method: Method::Delete,
292
folder_id: Some(folder_id.to_owned()),
293
fields: json!({}),
294
}))
301
Ok(Some(FolderWrite::reread(
302
Method::Delete,
303
Some(folder_id),
304
json!({}),
305
)))
295
306
})
296
307
.await
297
308
}
@@ -368,7 +379,9 @@ impl<T: CsaTransport> Pins<T> {
368
379
match answer.status {
369
380
200..=299 => {
370
381
return match parse_folders(&answer.body) {
371
Ok(current) if is_full_state(&answer.body) => Ok(current),
382
Ok(current) if write.answer_is_state && is_full_state(&answer.body) => {
383
Ok(current)
384
}
372
385
_ => self.folders().await,
373
386
};
374
387
}
@@ -465,11 +478,7 @@ mod tests {
465
478
466
479
#[test]
467
480
fn write_body_puts_the_lock_before_the_fields() {
468
let write = FolderWrite {
469
method: Method::Put,
470
folder_id: Some("a".into()),
471
fields: json!({"folderName": "B"}),
472
};
481
let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));
473
482
assert_eq!(
474
483
write.body(3),
475
484
json!({
@@ -155,6 +155,7 @@ struct FolderWrite {155
method: Method,155
method: Method,156
folder_id: Option<String>,156
folder_id: Option<String>,157
fields: Value,157
fields: Value,158
answer_is_state: bool,158
}159
}159
160
160
impl FolderWrite {161
impl FolderWrite {@@ -163,6 +164,16 @@ impl FolderWrite {163
method: Method::Post,164
method: Method::Post,164
folder_id: None,165
folder_id: None,165
fields: json!({"actions": actions}),166
fields: json!({"actions": actions}),167
answer_is_state: true,168
}169
}170
171
fn reread(method: Method, folder_id: Option<&str>, fields: Value) -> Self {172
FolderWrite {173
method,174
folder_id: folder_id.map(str::to_owned),175
fields,176
answer_is_state: false,166
}177
}167
}178
}168
179
@@ -258,11 +269,11 @@ impl<T: CsaTransport> Pins<T> {258
269
259
pub async fn create_folder(&self, name: &str) -> Result<Folders> {270
pub async fn create_folder(&self, name: &str) -> Result<Folders> {260
self.write(|_| {271
self.write(|_| {261
Ok(Some(FolderWrite {272
Ok(Some(FolderWrite::reread(262
method: Method::Post,273
Method::Post,263
folder_id: None,274
None,264
fields: json!({"folderName": name, "actions": [{"action": "AddFolder"}]}),275
json!({"folderName": name, "actions": [{"action": "AddFolder"}]}),265
}))276
)))266
})277
})267
.await278
.await268
}279
}@@ -272,11 +283,11 @@ impl<T: CsaTransport> Pins<T> {272
if state.user_created(folder_id)?.name == name {283
if state.user_created(folder_id)?.name == name {273
return Ok(None);284
return Ok(None);274
}285
}275
Ok(Some(FolderWrite {286
Ok(Some(FolderWrite::reread(276
method: Method::Put,287
Method::Put,277
folder_id: Some(folder_id.to_owned()),288
Some(folder_id),278
fields: json!({"folderName": name}),289
json!({"folderName": name}),279
}))290
)))280
})291
})281
.await292
.await282
}293
}@@ -287,11 +298,11 @@ impl<T: CsaTransport> Pins<T> {287
return Ok(None);298
return Ok(None);288
}299
}289
state.user_created(folder_id)?;300
state.user_created(folder_id)?;290
Ok(Some(FolderWrite {301
Ok(Some(FolderWrite::reread(291
method: Method::Delete,302
Method::Delete,292
folder_id: Some(folder_id.to_owned()),303
Some(folder_id),293
fields: json!({}),304
json!({}),294
}))305
)))295
})306
})296
.await307
.await297
}308
}@@ -368,7 +379,9 @@ impl<T: CsaTransport> Pins<T> {368
match answer.status {379
match answer.status {369
200..=299 => {380
200..=299 => {370
return match parse_folders(&answer.body) {381
return match parse_folders(&answer.body) {371
Ok(current) if is_full_state(&answer.body) => Ok(current),382
Ok(current) if write.answer_is_state && is_full_state(&answer.body) => {383
Ok(current)384
}372
_ => self.folders().await,385
_ => self.folders().await,373
};386
};374
}387
}@@ -465,11 +478,7 @@ mod tests {465
478
466
#[test]479
#[test]467
fn write_body_puts_the_lock_before_the_fields() {480
fn write_body_puts_the_lock_before_the_fields() {468
let write = FolderWrite {481
let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));469
method: Method::Put,470
folder_id: Some("a".into()),471
fields: json!({"folderName": "B"}),472
};473
assert_eq!(482
assert_eq!(474
write.body(3),483
write.body(3),475
json!({484
json!({@@ -533,9 +533,11 @@ async fn create_folder_posts_add_folder_with_the_name() {
533
533
let mock = Mock::new(vec![
534
534
(200, sections(10, &[], &[])),
535
535
(200, sections(11, &[("new", &[])], &[])),
536
(200, sections(11, &[("new", &[])], &[])),
536
537
]);
537
538
let state = pins(&mock).create_folder("zz").await.unwrap();
538
539
assert_eq!(state.folders.len(), 2);
540
assert_eq!(sent(&mock)[2].0, "GET");
539
541
let requests = sent(&mock);
540
542
assert_eq!(requests[1].0, "POST");
541
543
assert_eq!(requests[1].1, format!("{FOLDER_URL}{FOLDER_QUERY}"));
@@ -552,17 +554,44 @@ async fn create_folder_posts_add_folder_with_the_name() {
552
554
}
553
555
554
556
#[tokio::test]
555
async fn create_folder_rereads_after_a_partial_answer() {
556
let mut partial = sections(11, &[("new", &[])], &[]);
557
async fn folder_create_rename_delete_ignore_a_trimmed_answer_and_reread() {
558
let full = || sections(11, &[("t~u~A", &[]), ("t~u~B", &[])], &[]);
559
let trimmed = json!({"folderHierarchyVersion": 11, "conversationFolders": []});
560
for operation in ["create", "rename", "delete"] {
561
let mock = Mock::new(vec![
562
(200, sections(10, &[("t~u~A", &[]), ("t~u~B", &[])], &[])),
563
(200, trimmed.clone()),
564
(200, full()),
565
]);
566
let pins = pins(&mock);
567
let state = match operation {
568
"create" => pins.create_folder("zz").await,
569
"rename" => pins.rename_folder("t~u~A", "x").await,
570
_ => pins.delete_folder("t~u~A").await,
571
}
572
.unwrap();
573
assert_eq!(state.folders.len(), 3, "{operation}");
574
assert_eq!(sent(&mock).len(), 3, "{operation}");
575
}
576
}
577
578
#[tokio::test]
579
async fn folder_action_posts_still_take_a_full_answer_as_state() {
580
let mut partial = sections(11, &[("t~u~B", &["c"])], &[]);
557
581
partial["isPartialResponse"] = json!(true);
558
582
let mock = Mock::new(vec![
559
(200, sections(10, &[], &[])),
583
(200, sections(10, &[("t~u~B", &[])], &[])),
560
584
(200, partial),
561
(200, sections(11, &[("t~u~A", &[]), ("new", &[])], &[])),
585
(200, sections(11, &[("t~u~B", &["c"])], &[])),
562
586
]);
563
let state = pins(&mock).create_folder("zz").await.unwrap();
587
pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
564
588
assert_eq!(sent(&mock).len(), 3);
565
assert_eq!(state.folders.len(), 3);
589
let idle = Mock::new(vec![
590
(200, sections(10, &[("t~u~B", &[])], &[])),
591
(200, sections(11, &[("t~u~B", &["c"])], &[])),
592
]);
593
pins(&idle).move_to_folder("c", "t~u~B").await.unwrap();
594
assert_eq!(sent(&idle).len(), 2);
566
595
}
567
596
568
597
#[tokio::test]
@@ -570,6 +599,7 @@ async fn rename_folder_puts_the_name_on_the_folder_url() {
570
599
let mock = Mock::new(vec![
571
600
(200, sections(10, &[("t~u~A", &[])], &[])),
572
601
(200, sections(11, &[("t~u~A", &[])], &[])),
602
(200, sections(11, &[("t~u~A", &[])], &[])),
573
603
]);
574
604
pins(&mock).rename_folder("t~u~A", "Todo").await.unwrap();
575
605
let requests = sent(&mock);
@@ -599,6 +629,7 @@ async fn rename_or_delete_of_a_system_folder_sends_nothing() {
599
629
async fn delete_folder_sends_delete_with_only_the_lock() {
600
630
let mock = Mock::new(vec![
601
631
(200, sections(10, &[("t~u~A", &["c"])], &[])),
632
(200, json!({})),
602
633
(200, sections(11, &[], &[])),
603
634
]);
604
635
let state = pins(&mock).delete_folder("t~u~A").await.unwrap();
@@ -533,9 +533,11 @@ async fn create_folder_posts_add_folder_with_the_name() {533
let mock = Mock::new(vec![533
let mock = Mock::new(vec![534
(200, sections(10, &[], &[])),534
(200, sections(10, &[], &[])),535
(200, sections(11, &[("new", &[])], &[])),535
(200, sections(11, &[("new", &[])], &[])),536
(200, sections(11, &[("new", &[])], &[])),536
]);537
]);537
let state = pins(&mock).create_folder("zz").await.unwrap();538
let state = pins(&mock).create_folder("zz").await.unwrap();538
assert_eq!(state.folders.len(), 2);539
assert_eq!(state.folders.len(), 2);540
assert_eq!(sent(&mock)[2].0, "GET");539
let requests = sent(&mock);541
let requests = sent(&mock);540
assert_eq!(requests[1].0, "POST");542
assert_eq!(requests[1].0, "POST");541
assert_eq!(requests[1].1, format!("{FOLDER_URL}{FOLDER_QUERY}"));543
assert_eq!(requests[1].1, format!("{FOLDER_URL}{FOLDER_QUERY}"));@@ -552,17 +554,44 @@ async fn create_folder_posts_add_folder_with_the_name() {552
}554
}553
555
554
#[tokio::test]556
#[tokio::test]555
async fn create_folder_rereads_after_a_partial_answer() {557
async fn folder_create_rename_delete_ignore_a_trimmed_answer_and_reread() {556
let mut partial = sections(11, &[("new", &[])], &[]);558
let full = || sections(11, &[("t~u~A", &[]), ("t~u~B", &[])], &[]);559
let trimmed = json!({"folderHierarchyVersion": 11, "conversationFolders": []});560
for operation in ["create", "rename", "delete"] {561
let mock = Mock::new(vec![562
(200, sections(10, &[("t~u~A", &[]), ("t~u~B", &[])], &[])),563
(200, trimmed.clone()),564
(200, full()),565
]);566
let pins = pins(&mock);567
let state = match operation {568
"create" => pins.create_folder("zz").await,569
"rename" => pins.rename_folder("t~u~A", "x").await,570
_ => pins.delete_folder("t~u~A").await,571
}572
.unwrap();573
assert_eq!(state.folders.len(), 3, "{operation}");574
assert_eq!(sent(&mock).len(), 3, "{operation}");575
}576
}577
578
#[tokio::test]579
async fn folder_action_posts_still_take_a_full_answer_as_state() {580
let mut partial = sections(11, &[("t~u~B", &["c"])], &[]);557
partial["isPartialResponse"] = json!(true);581
partial["isPartialResponse"] = json!(true);558
let mock = Mock::new(vec![582
let mock = Mock::new(vec![559
(200, sections(10, &[], &[])),583
(200, sections(10, &[("t~u~B", &[])], &[])),560
(200, partial),584
(200, partial),561
(200, sections(11, &[("t~u~A", &[]), ("new", &[])], &[])),585
(200, sections(11, &[("t~u~B", &["c"])], &[])),562
]);586
]);563
let state = pins(&mock).create_folder("zz").await.unwrap();587
pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();564
assert_eq!(sent(&mock).len(), 3);588
assert_eq!(sent(&mock).len(), 3);565
assert_eq!(state.folders.len(), 3);589
let idle = Mock::new(vec![590
(200, sections(10, &[("t~u~B", &[])], &[])),591
(200, sections(11, &[("t~u~B", &["c"])], &[])),592
]);593
pins(&idle).move_to_folder("c", "t~u~B").await.unwrap();594
assert_eq!(sent(&idle).len(), 2);566
}595
}567
596
568
#[tokio::test]597
#[tokio::test]@@ -570,6 +599,7 @@ async fn rename_folder_puts_the_name_on_the_folder_url() {570
let mock = Mock::new(vec![599
let mock = Mock::new(vec![571
(200, sections(10, &[("t~u~A", &[])], &[])),600
(200, sections(10, &[("t~u~A", &[])], &[])),572
(200, sections(11, &[("t~u~A", &[])], &[])),601
(200, sections(11, &[("t~u~A", &[])], &[])),602
(200, sections(11, &[("t~u~A", &[])], &[])),573
]);603
]);574
pins(&mock).rename_folder("t~u~A", "Todo").await.unwrap();604
pins(&mock).rename_folder("t~u~A", "Todo").await.unwrap();575
let requests = sent(&mock);605
let requests = sent(&mock);@@ -599,6 +629,7 @@ async fn rename_or_delete_of_a_system_folder_sends_nothing() {599
async fn delete_folder_sends_delete_with_only_the_lock() {629
async fn delete_folder_sends_delete_with_only_the_lock() {600
let mock = Mock::new(vec![630
let mock = Mock::new(vec![601
(200, sections(10, &[("t~u~A", &["c"])], &[])),631
(200, sections(10, &[("t~u~A", &["c"])], &[])),632
(200, json!({})),602
(200, sections(11, &[], &[])),633
(200, sections(11, &[], &[])),603
]);634
]);604
let state = pins(&mock).delete_folder("t~u~A").await.unwrap();635
let state = pins(&mock).delete_folder("t~u~A").await.unwrap();